@mohsinonxrm/pptb-commandbar-studio 0.9.0-beta.2 → 0.10.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +242 -2
- package/README.md +16 -14
- package/SECURITY.md +4 -4
- package/dist/assets/BulkPublishModal-9_XxYmS2.js +2 -0
- package/dist/assets/CommandEditorPanel-BtBG8540.js +1 -0
- package/dist/assets/CommandPalette-C2YXN_gD.js +1 -0
- package/dist/assets/CompareView-Beq5V68_.js +11 -0
- package/dist/assets/CrmParameterEditor-DfZv5BuF.js +1 -0
- package/dist/assets/EditorDrawer-D0K8zHVK.js +2 -0
- package/dist/assets/HideInsteadOfDeleteModal-C4AKxh50.js +1 -0
- package/dist/assets/IconPickerModal-B9UeIP7Z.js +1 -0
- package/dist/assets/ImportXmlModal-Cf75oVpN.js +1 -0
- package/dist/assets/{MonacoEditor-DweI16yt.js → MonacoEditor-B3J81C8F.js} +2 -2
- package/dist/assets/NewButtonModal-DhGNLWEW.js +1 -0
- package/dist/assets/NewGroupModal-CMLOZ15C.js +1 -0
- package/dist/assets/NewTabModal-N7FF7DT1.js +1 -0
- package/dist/assets/RuleEditorPanel-C9CcMM1s.js +1 -0
- package/dist/assets/ScriptView-B0ILfTWe.js +1 -0
- package/dist/assets/TabDisplayRulesPanel-DVMEaWWv.js +1 -0
- package/dist/assets/TitleTranslationsView-C68zJcNK.js +1 -0
- package/dist/assets/TranslationsView-BZXsG_LU.js +1 -0
- package/dist/assets/WebResourceBrowser-DEXq2SCy.js +1 -0
- package/dist/assets/XmlView-DEUwTHCt.js +2 -0
- package/dist/assets/crmParameters-Dxz06tk4.js +1 -0
- package/dist/assets/{dnd-iy5K5XAJ.js → dnd-C19d6Mn0.js} +1 -1
- package/dist/assets/fluent-ui-BThr2m8u.js +59 -0
- package/dist/assets/index-Df9NSpg6.js +136 -0
- package/dist/assets/index-browser-Bmt9T2GD.js +2 -0
- package/dist/assets/languages-CGjPBPNA.js +1 -0
- package/dist/assets/{monaco-cQE5XS3B.js → monaco-DzBcrxae.js} +1 -1
- package/dist/assets/monacoSetup-BRltj-y7.js +1 -0
- package/dist/assets/publishService-CKoTOngS.js +36 -0
- package/dist/assets/ribbonXsdCheck-CJBpxpVm.js +1923 -0
- package/dist/assets/{server.browser-DTeSoizu.js → server.browser-BokSAg1N.js} +1 -1
- package/dist/assets/useReplaceWebResourceConfirm-BUfgdCRQ.js +1 -0
- package/dist/assets/{useStableKeys-49o4VnxU.js → useStableKeys-EsghhjoV.js} +1 -1
- package/dist/assets/xmlValidator-Dki8Hf7Y.js +3 -0
- package/dist/assets/xmllint-CcuGSrO9.wasm +0 -0
- package/dist/assets/xmllint-browser-C85XrDSU.js +4 -0
- package/dist/index.html +3 -3
- package/package.json +2 -1
- package/dist/assets/BulkPublishModal-DjdSDcWe.js +0 -36
- package/dist/assets/CommandEditorPanel-DYsxUTOk.js +0 -1
- package/dist/assets/CommandPalette-DihgRpHI.js +0 -1
- package/dist/assets/CompareView-CdQo0D6e.js +0 -7
- package/dist/assets/CrmParameterEditor-DO6Rt764.js +0 -1
- package/dist/assets/EditorDrawer-Cid60F3b.js +0 -2
- package/dist/assets/HideInsteadOfDeleteModal-Bk_foggy.js +0 -1
- package/dist/assets/IconPickerModal-CW_pvpVS.js +0 -1
- package/dist/assets/ImportXmlModal-BcszuTi-.js +0 -1
- package/dist/assets/NewButtonModal-C2fAUuZI.js +0 -1
- package/dist/assets/NewGroupModal-BDr4DPBs.js +0 -1
- package/dist/assets/NewTabModal-CYc1fc2A.js +0 -1
- package/dist/assets/RuleEditorPanel-BxGrJYo4.js +0 -1
- package/dist/assets/ScriptView-tkdIK4sg.js +0 -1
- package/dist/assets/TabDisplayRulesPanel-S_AxUWfB.js +0 -1
- package/dist/assets/TranslationsView-DZIGE2pC.js +0 -1
- package/dist/assets/WebResourceBrowser-Dc3kBMvH.js +0 -1
- package/dist/assets/XmlView-B0weY9hR.js +0 -2
- package/dist/assets/crmParameters-rgfZhhzN.js +0 -1
- package/dist/assets/fluent-ui-CQyNN9H3.js +0 -59
- package/dist/assets/index-DRTwBo4g.js +0 -136
- package/dist/assets/monacoSetup-BIq1zGyP.js +0 -1
- package/dist/assets/ruleKinds-BKTUiZ1-.js +0 -1
- package/dist/assets/useReplaceWebResourceConfirm-BhU1AM5L.js +0 -1
- package/dist/assets/xmlValidator-CnbyWxHe.js +0 -3
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./EditorDrawer-D0K8zHVK.js","./preload-helper-PPVm8Dsz.js","./fluent-ui-BThr2m8u.js","./dnd-C19d6Mn0.js","./BulkPublishModal-9_XxYmS2.js","./MonacoEditor-B3J81C8F.js","./publishService-CKoTOngS.js","./xmlValidator-Dki8Hf7Y.js","./crmParameters-Dxz06tk4.js","./NewButtonModal-DhGNLWEW.js","./NewGroupModal-CMLOZ15C.js","./NewTabModal-N7FF7DT1.js","./ImportXmlModal-Cf75oVpN.js","./CommandPalette-C2YXN_gD.js","./IconPickerModal-B9UeIP7Z.js","./useReplaceWebResourceConfirm-BUfgdCRQ.js","./WebResourceBrowser-DEXq2SCy.js","./HideInsteadOfDeleteModal-C4AKxh50.js","./server.browser-BokSAg1N.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{b as Vm,W as nt,m as pe,j as a,T as he,c as X,B as xe,t as f,r as B,C as ya,O as vr,d as Ti,e as Ce,L as fn,D as Xm,f as Km,g as Ym,h as Jm,i as Zm,k as Y,l as mn,n as Qm,o as Sr,p as ep,S as sc,u as ic,q as ac,P as xa,s as va,v as tp,w as np,F as op,x as Sa,y as qe,z as Ge,I as Et,A as sp,E as ip,G as ap,H as rp,J as lp,K as cp,M as wa,N as dp,Q as Ht,R as rn,U as Ca,V as Ra,X as up,Y as Je,Z as Ze,_ as dt,$ as Pn,a0 as Qe,a1 as et,a2 as Ia,a3 as rc,a4 as fe,a5 as mp,a6 as fo,a7 as jn,a8 as Mt,a9 as lc,aa as ja,ab as $a,ac as xs,ad as Ta,ae as pp,af as Dt,ag as Bt,ah as cc,ai as vs,aj as Mn,ak as fp,al as wr,am as dc,an as uc,ao as hp,ap as Ni,aq as ln,ar as mc,as as ki,at as Na,au as Fn,av as Lt,aw as ho,ax as Ro,ay as Cr,az as _n,aA as Wt,aB as ka,aC as ke,aD as Rr,aE as gp,aF as bp,aG as yp,aH as pc,aI as xp,aJ as vp,aK as Sp,aL as wp,aM as Cp,aN as Rp,aO as Ip,aP as jp,aQ as $p,aR as Ai,aS as Tp,aT as Np,aU as kp,aV as fc,aW as Ap,aX as Op,aY as Mp,aZ as Ep,a_ as Dp,a$ as Bp,b0 as Lp,b1 as hc,b2 as zp,b3 as Pp,b4 as Fp,b5 as _p,b6 as qp,b7 as Hp,b8 as Wp,b9 as gc,ba as Gp,bb as Up,bc as Vp,bd as Xp,be as Kp,bf as Yp,bg as Jp,bh as Zp,bi as Qp,bj as ef,bk as bc,bl as tf,bm as Aa,bn as nf,bo as of,bp as sf,bq as yc,br as af,bs as rf,bt as lf,bu as cf,bv as df,bw as uf,bx as mf,by as pf,bz as ff,bA as hf,bB as gf,bC as bf,bD as yf,bE as xf,bF as vf,bG as Sf,bH as wf,bI as Ho,bJ as Cf,bK as Rf,bL as If,bM as jf,bN as $f,bO as Tf,bP as Nf,bQ as kf,bR as xc,bS as Af,bT as vc,bU as Of,bV as Mf,bW as Ef,bX as Df,bY as Bf,bZ as Lf,b_ as zf,b$ as Pf,c0 as Ff,c1 as Sc,c2 as _f,c3 as qf,c4 as Hf,c5 as Ss,c6 as Wf,c7 as Gf,c8 as Uf,c9 as Vf,ca as Xf,cb as Kf,cc as Yf,cd as Oi,ce as Jf,cf as wc,cg as Zf,ch as Qf,ci as eh,cj as th,ck as nh,cl as Cc,cm as oh,cn as Rc,co as sh,cp as ih,cq as ah,cr as rh,cs as lh,ct as ch,cu as dh,cv as uh,cw as Ic,cx as mh,cy as ph,cz as fh,cA as Mi,cB as hh,cC as gh,cD as bh,cE as yh,cF as xh,cG as vh,cH as Sh,cI as jc,cJ as wh,cK as Ch,cL as Rh,cM as Ih,cN as jh,cO as $h,cP as Th,cQ as Nh,cR as kh,cS as Ah,cT as $c,cU as Oh,cV as Mh,cW as Eh,cX as Dh,cY as Bh,cZ as Lh,c_ as Ei,c$ as zh,d0 as Ph,d1 as Fh,d2 as _h,d3 as qh,d4 as Hh,d5 as Wh,d6 as Gh,d7 as Tc,d8 as Uh,d9 as Vh,da as Xh,db as Kh,dc as Yh,dd as Jh,de as Zh,df as Qh,dg as eg,dh as tg,di as ng,dj as og,dk as sg,dl as ig,dm as Ir,dn as ag,dp as jr,dq as rg,dr as lg,ds as cg,dt as $r,du as dg,dv as ug,dw as Tr,dx as mg,dy as pg,dz as fg,dA as Us,dB as hg,dC as Nr,dD as Ao,dE as gg,dF as Oo,dG as bg,dH as kr,dI as yg,dJ as Ar,dK as Nc,dL as kc,dM as Ac,dN as xg,dO as vg,dP as Sg,dQ as wg,dR as Or,dS as Vn,dT as Cg,dU as Xn,dV as go,dW as Oc,dX as He,dY as Oa,dZ as cn,d_ as Rg,d$ as Ig,e0 as jg,e1 as Mr,e2 as Mc,e3 as $g,e4 as Ec,e5 as Tg,e6 as Ma,e7 as Gt,e8 as Ng,e9 as kg,ea as Ag,eb as Og,ec as Er,ed as Dc,ee as Bc,ef as Lc,eg as zc,eh as Mg,ei as Eg,ej as Pc,ek as Ea,el as Da,em as Dg,en as Wo,eo as Vs,ep as Bg,eq as Lg,er as zg,es as Rn,et as Pg,eu as Fg,ev as _g,ew as qg,ex as Hg,ey as Fc,ez as Wg,eA as Gg,eB as Ug,eC as Vg,eD as Xg,eE as Kg,eF as Yg,eG as Jg,eH as Zg,eI as Qg,eJ as eb,eK as tb,eL as io,eM as Ut,eN as Vt,eO as nb,eP as ob,eQ as sb,eR as ib,eS as ab}from"./fluent-ui-BThr2m8u.js";import{_ as ht}from"./preload-helper-PPVm8Dsz.js";import{u as rb,a as _c,b as Qo,D as qc,c as Hc,d as Wc,K as Gc,P as Uc,e as Ba,p as Dr,s as lb,S as cb,v as db,f as ub,C as mb,g as pb}from"./dnd-C19d6Mn0.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&o(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var Mo={},Br;function fb(){if(Br)return Mo;Br=1;var e=Vm();return Mo.createRoot=e.createRoot,Mo.hydrateRoot=e.hydrateRoot,Mo}var hb=fb();const Lr=e=>{let t;const n=new Set,o=(d,u)=>{const m=typeof d=="function"?d(t):d;if(!Object.is(m,t)){const p=t;t=u??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(h=>h(t,p))}},s=()=>t,r={setState:o,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(o,s,r);return r},gb=(e=>e?Lr(e):Lr),bb=e=>e;function yb(e,t=bb){const n=nt.useSyncExternalStore(e.subscribe,nt.useCallback(()=>t(e.getState()),[e,t]),nt.useCallback(()=>t(e.getInitialState()),[e,t]));return nt.useDebugValue(n),n}const xb=e=>{const t=gb(e),n=o=>yb(t,o);return Object.assign(n,t),n},en=(e=>xb);function es(e){if(!e||!e.id&&!e.url)return"";const t=(e.url??"").trim().replace(/\/+$/,"").toLowerCase();return`${e.id??""}|${t}`}function Vc(){return window.toolboxAPI?.connections}async function La(){const e=Vc();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 Di 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 ao,Bi=0;function zr(e){const t=es(e);ao!==void 0&&t!==ao&&Bi++,ao=t}async function ws(e){const t=Vc();if(ao===void 0||!t?.getConnection&&!t?.getActiveConnection)return;let n;try{n=es(await La())}catch{throw new Di(e)}if(n!==ao)throw new Di(e)}function vb(e){const t=window.toolboxAPI?.events;if(typeof t?.on!="function")return()=>{};let n=0;const o=(s,i)=>{const l=i?.event;if(l!=="connection:updated"&&l!=="connection:created"&&l!=="connection:deleted")return;const r=++n;La().then(c=>{r===n&&e(c)}).catch(()=>{})};return t.on(o),()=>t.off?.(o)}function Xc(){const e=Bi;return async t=>{if(Bi!==e)throw new Di(t);await ws(t)}}const Li=new Set;function Sb(e){return Li.add(e),()=>Li.delete(e)}const ae=en()((e,t)=>({connectionId:"",connectionUrl:"",connectionName:"",environment:"Dev",publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:0,connectionNotice:null,setConnection:(n,o,s,i=t().connectionId)=>{zr({id:i,url:n}),e({connectionId:i,connectionUrl:n,connectionName:o,environment:s})},switchConnection:(n,o)=>{const s=t();zr(n),e({connectionId:n.id,connectionUrl:n.url,connectionName:n.name,environment:n.environment,publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:s.connectionVersion+1,connectionNotice:{...o,from:{name:s.connectionName,url:s.connectionUrl,environment:s.environment},to:{name:n.name,url:n.url,environment:n.environment}}})},dismissConnectionNotice:()=>e({connectionNotice:null}),setSolutions:n=>e({solutions:n}),setActiveSolution:n=>{ht(async()=>{const{useRuntimeLogStore:s}=await Promise.resolve().then(()=>Tb);return{useRuntimeLogStore:s}},void 0,import.meta.url).then(({useRuntimeLogStore:s})=>{s.getState().logInfo("dataverse",`Active solution: "${n.friendlyName||n.uniqueName}" — publisher="${n.publisherUniqueName||"(empty)"}", prefix="${n.publisherPrefix||"(empty)"}"`),(!n.publisherPrefix||n.publisherPrefix==="new"||/^defaultpublisher/i.test(n.publisherUniqueName??""))&&s.getState().logWarn("dataverse",`Solution "${n.friendlyName||n.uniqueName}" uses the org's default publisher (prefix="${n.publisherPrefix||"new"}"). All IDs and imports from CBS will land under that publisher. To use your own (e.g. "mxrm"), create a new solution in maker.powerapps.com bound to your custom publisher and pick that one here.`)});const o=t().activeSolution?.id!==n.id;if(e({activeSolution:n,publisherPrefix:n.publisherPrefix||"new",...o?{activeEntity:null,entities:[],solutionEntityIds:null,solutionRibbonComponentIds:null}:{}}),o)for(const s of Li)s()},setEntities:n=>e({entities:n}),setActiveEntity:n=>e({activeEntity:n}),setSolutionEntityIds:n=>e({solutionEntityIds:n}),setSolutionRibbonComponentIds:n=>e({solutionRibbonComponentIds:n}),setCurrentUser:(n,o)=>e({currentUserId:n,currentUserName:o}),setPublisherPrefix:n=>e({publisherPrefix:n})})),wb=e=>(t,n,o)=>{const s=o.subscribe;return o.subscribe=((l,r,c)=>{let d=l;if(r){const u=c?.equalityFn||Object.is;let m=l(o.getState());d=p=>{const h=l(p);if(!u(m,h)){const b=m;r(m=h,b)}},c?.fireImmediately&&r(m,m)}return s(d)}),e(t,n,o)},Cb=wb;function Kc(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),r=(i=n.getItem(s))!=null?i:null;return r instanceof Promise?r.then(l):l(r)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const zi=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(o){return zi(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return zi(o)(n)}}}},Rb=(e,t)=>(n,o,s)=>{let i={storage:Kc(()=>window.localStorage),partialize:x=>x,version:0,merge:(x,y)=>({...y,...x}),...t},l=!1,r=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return e((...x)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...x)},o,s);const m=()=>{const x=i.partialize({...o()});return u.setItem(i.name,{state:x,version:i.version})},p=s.setState;s.setState=(x,y)=>(p(x,y),m());const h=e((...x)=>(n(...x),m()),o,s);s.getInitialState=()=>h;let b;const g=()=>{var x,y;if(!u)return;const S=++r;l=!1,c.forEach(R=>{var M;return R((M=o())!=null?M:h)});const C=((y=i.onRehydrateStorage)==null?void 0:y.call(i,(x=o())!=null?x:h))||void 0;return zi(u.getItem.bind(u))(i.name).then(R=>{if(R)if(typeof R.version=="number"&&R.version!==i.version){if(i.migrate){const M=i.migrate(R.state,R.version);return M instanceof Promise?M.then(I=>[!0,I]):[!0,M]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,R.state];return[!1,void 0]}).then(R=>{var M;if(S!==r)return;const[I,$]=R;if(b=i.merge($,(M=o())!=null?M:h),n(b,!0),I)return m()}).then(()=>{S===r&&(C?.(o(),void 0),b=o(),l=!0,d.forEach(R=>R(b)))}).catch(R=>{S===r&&C?.(void 0,R)})};return s.persist={setOptions:x=>{i={...i,...x},x.storage&&(u=x.storage)},clearStorage:()=>{++r,u?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>l,onHydrate:x=>(c.add(x),()=>{c.delete(x)}),onFinishHydration:x=>(d.add(x),()=>{d.delete(x)})},i.skipHydration||g(),b||h},Ib=Rb;function jb(e,t=250){const n=new Map;let o;const s=()=>{o!==void 0&&clearTimeout(o),o=void 0;for(const[i,l]of n)try{e().setItem(i,l)}catch{}n.clear()};return typeof window<"u"&&(window.addEventListener("pagehide",s),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&s()})),{getItem:i=>{const l=n.get(i);if(l!==void 0)return l;try{return e().getItem(i)}catch{return null}},setItem:(i,l)=>{n.set(i,l),o??=setTimeout(s,t)},removeItem:i=>{n.delete(i);try{e().removeItem(i)}catch{}}}}function tt(e){const t=e.find(l=>l.kind==="command"),n=e[e.length-1],o=n?.kind==="rule"?n:null,s=e.find(l=>l.kind==="translations"),i=[...e].reverse().find(l=>l.kind==="diff");return{editorStack:e,commandEditorOpen:!!t,commandEditorId:t?.id??null,ruleEditorOpen:!!o,ruleEditorId:o?.id??null,ruleEditorKind:o?.ruleKind??null,tabDisplayRulesOpen:e.some(l=>l.kind==="tabRules"),xmlDrawerOpen:e.some(l=>l.kind==="xml"),diffViewerOpen:!!i,diffViewerMode:i?.id??"compare",localizationEditorOpen:!!s,localizationEditorButtonId:s?.id??null}}function zt(e,t){return e[e.length-1]?.kind===t.kind?[...e.slice(0,-1),t]:[...e,t]}const $b=e=>({leftPaneWidth:260,leftPaneTab:"structure",rightPaneWidth:340,bottomPanelHeight:220,bottomCollapsed:!0,rightPaneMode:"docked",themeMode:"light",ribbonViewStyle:"groups",activeBottomTab:"commands",editorStack:[],commandEditorOpen:!1,commandEditorId:null,ruleEditorOpen:!1,ruleEditorId:null,ruleEditorKind:null,commandEditorTab:"actions",xmlDrawerOpen:!1,bulkPublishOpen:!1,iconPickerOpen:!1,localizationEditorOpen:!1,localizationEditorButtonId:null,newGroupOpen:!1,newButtonGroupId:null,importXmlOpen:!1,importXmlSeed:"",importXmlNote:"",webResourceBrowserOpen:!1,diffViewerOpen:!1,diffViewerMode:"compare",tabDisplayRulesOpen:!1,commandPaletteOpen:!1,solutionPickerOpen:!1,scopeTipDismissed:[],tablePickerOpen:!1,propertiesRequested:!1,newTabOpen:!1,hideInsteadOfDelete:null,announcement:"",setLeftPaneWidth:t=>e({leftPaneWidth:t}),setRightPaneWidth:t=>e({rightPaneWidth:t}),setBottomPanelHeight:t=>e({bottomPanelHeight:t}),setBottomCollapsed:t=>e({bottomCollapsed:t}),setRightPaneMode:t=>e({rightPaneMode:t}),setThemeMode:t=>e({themeMode:t}),setRibbonViewStyle:t=>e({ribbonViewStyle:t}),setActiveBottomTab:t=>e({activeBottomTab:t}),openCommandEditor:t=>e(n=>({...tt(t?zt(n.editorStack,{kind:"command",id:t}):[]),commandEditorTab:t&&t===n.commandEditorId?n.commandEditorTab:"actions"})),closeCommandEditor:()=>e(tt([])),openRuleEditor:(t,n)=>e(o=>tt(t?zt(o.editorStack,{kind:"rule",id:t,ruleKind:n}):o.editorStack)),closeRuleEditor:()=>e(t=>tt(t.editorStack[t.editorStack.length-1]?.kind==="rule"?t.editorStack.slice(0,-1):t.editorStack)),setCommandEditorTab:t=>e({commandEditorTab:t}),openScriptView:(t,n)=>e(o=>tt(zt(o.editorStack,{kind:"script",id:t,editable:n}))),editorBack:()=>e(t=>tt(t.editorStack.slice(0,-1))),closeEditor:()=>e(tt([])),openXmlDrawer:t=>e(n=>tt(zt(n.editorStack,{kind:"xml",id:t}))),closeXmlDrawer:()=>e(t=>tt(t.editorStack.filter(n=>n.kind!=="xml"))),openBulkPublish:()=>e({bulkPublishOpen:!0}),closeBulkPublish:()=>e({bulkPublishOpen:!1}),openIconPicker:()=>e({iconPickerOpen:!0}),closeIconPicker:()=>e({iconPickerOpen:!1}),openLocalizationEditor:t=>e(n=>tt(zt(n.editorStack,{kind:"translations",id:t}))),openTitleTranslations:(t,n,o,s)=>e(i=>tt(zt(i.editorStack,{kind:"titleTranslations",id:s,location:t,tabId:o,container:n}))),closeLocalizationEditor:()=>e(t=>tt(t.editorStack.filter(n=>n.kind!=="translations"))),openNewGroup:()=>e({newGroupOpen:!0}),closeNewGroup:()=>e({newGroupOpen:!1}),openNewButton:t=>e({newButtonGroupId:t}),closeNewButton:()=>e({newButtonGroupId:null}),openImportXml:(t,n)=>e({importXmlOpen:!0,importXmlSeed:typeof t=="string"?t:"",importXmlNote:typeof n=="string"?n:""}),closeImportXml:()=>e({importXmlOpen:!1}),openWebResourceBrowser:()=>e({webResourceBrowserOpen:!0}),closeWebResourceBrowser:()=>e({webResourceBrowserOpen:!1}),openDiffViewer:(t,n)=>e(o=>tt(zt(o.editorStack,{kind:"diff",id:t,historyIndex:n}))),closeDiffViewer:()=>e(t=>tt(t.editorStack.filter(n=>n.kind!=="diff"))),openTabDisplayRules:(t,n)=>e(o=>tt(zt(o.editorStack,{kind:"tabRules",id:n,location:t}))),setCommandPaletteOpen:t=>e({commandPaletteOpen:t}),setSolutionPickerOpen:t=>e({solutionPickerOpen:t}),dismissScopeTip:t=>e(n=>n.scopeTipDismissed.includes(t)?{}:{scopeTipDismissed:[...n.scopeTipDismissed,t]}),setTablePickerOpen:t=>e({tablePickerOpen:t}),setLeftPaneTab:t=>e({leftPaneTab:t}),structureChoice:0,noteStructureChoice:()=>e(t=>({structureChoice:t.structureChoice+1})),setPropertiesRequested:t=>e({propertiesRequested:t}),openNewTab:()=>e({newTabOpen:!0}),closeNewTab:()=>e({newTabOpen:!1}),openHideInsteadOfDelete:t=>e({hideInsteadOfDelete:t}),closeHideInsteadOfDelete:()=>e({hideInsteadOfDelete:null}),announce:t=>e({announcement:t})}),J=en()(Ib($b,{name:"cbs:ui",storage:Kc(()=>jb(()=>localStorage)),partialize:e=>({leftPaneWidth:e.leftPaneWidth,leftPaneTab:e.leftPaneTab,rightPaneWidth:e.rightPaneWidth,bottomPanelHeight:e.bottomPanelHeight,bottomCollapsed:e.bottomCollapsed,rightPaneMode:e.rightPaneMode,themeMode:e.themeMode,ribbonViewStyle:e.ribbonViewStyle,scopeTipDismissed:e.scopeTipDismissed})})),re=en()((e,t)=>({entries:[],append:n=>{const s={id:`${Date.now()}-${t().entries.length+1}`,ts:new Date().toISOString(),...n};e({entries:[...t().entries,s].slice(-400)})},logInfo:(n,o)=>t().append({scope:n,level:"info",message:o}),logWarn:(n,o)=>t().append({scope:n,level:"warn",message:o}),logError:(n,o)=>t().append({scope:n,level:"error",message:o}),clear:()=>e({entries:[]})})),Tb=Object.freeze(Object.defineProperty({__proto__:null,useRuntimeLogStore:re},Symbol.toStringTag,{value:"Module"})),Nb=new Set(["Default","InvertResult","PropertyValue","ExpectedValue","TrackedInCrm","PassParams","AllowCustomRelationship","AllowSystemRelationship"]),Pr=["EnableRules","DisplayRules","Actions"];function kb(e,t){return Nb.has(t)||e.tagName==="BoolParameter"&&t==="Value"}function Ab(e){const t=e.trim();return t==="1"?"true":t==="0"?"false":t}function Ob(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/"/g,""")}function Go(e,t,n){const o=Array.from(e.attributes).map(l=>[l.name,kb(e,l.name)?Ab(l.value):l.value]).sort(([l],[r])=>l<r?-1:l>r?1:0).map(([l,r])=>` ${l}="${Ob(r)}"`).join(""),s=[];let i=[];for(const l of Array.from(e.childNodes))if(l.nodeType===1)i.push(l);else if(l.nodeType===3||l.nodeType===4){const r=(l.textContent??"").trim();r&&s.push(`${n} #text ${r}`)}if(t.normalizeCommands&&e.tagName==="CommandDefinition"){const l=new Map(i.map(d=>[d.tagName,d])),r=i.filter(d=>!Pr.includes(d.tagName)),c=Pr.map(d=>{const u=l.get(d);return u?Go(u,t,`${n} `):`${n} <${d}/>`});i=[],s.push(...c,...r.map(d=>Go(d,t,`${n} `)))}for(const l of i)s.push(Go(l,t,`${n} `));return s.length===0?`${n}<${e.tagName}${o}/>`:`${n}<${e.tagName}${o}>
|
|
3
|
+
${s.join(`
|
|
4
|
+
`)}
|
|
5
|
+
${n}</${e.tagName}>`}function Yc(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"?Yc(e):e;return Go(n,t,"")}function Mb(e,t,n={}){try{return En(e,n)===En(t,n)}catch{return!1}}const $n={button:"Button",flyout:"FlyoutAnchor",splitButton:"SplitButton",textBox:"TextBox",comboBox:"ComboBox",checkBox:"CheckBox",toggleButton:"ToggleButton",label:"Label",dropDown:"DropDown",mruSplitButton:"MRUSplitButton",spinner:"Spinner",galleryButton:"GalleryButton"},Jc=Object.fromEntries(Object.entries($n).map(([e,t])=>[t,e])),Eb=new Set(["toggleButton","label","dropDown","mruSplitButton","spinner","galleryButton"]);function ut(e){return!!e&&Eb.has(e)}const Zc=["Command","QueryCommand","MenuCommand","PopulateQueryCommand","CommandMenuOpen","CommandMenuClose","CommandPreview","CommandPreviewRevert","CommandRevert"],Qc=new RegExp(`\\s(?:${Zc.join("|")})="([^"]+)"`,"g");function ed(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),ut(e.kind))for(const o of e.source?.xml?.matchAll(Qc)??[])t.add(o[1]);return[...t]}function Db(e,t,n){const o=s=>s.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<");return e.replace(Qc,(s,i)=>i===t||i===o(t)?s.replace(`"${i}"`,`"${o(n)}"`):s)}const xt={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 td(e,t){const n=t.length>0?Math.min(...t):1/0,o=e.filter(s=>s<n);return{after:o.length>0?Math.max(...o):0,before:n}}function nd(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 od(e,t,n){const o=[],s=[],i=new Set([...t.maxSizes,...t.scales]),l=(p,h)=>{o.push({tabId:e,id:p.id,kind:p.kind,groupId:p.groupId,from:p.sequence,to:h}),i.add(h)},r=n.filter(p=>p.kind==="Scale"),c=[];for(const p of r)i.has(p.sequence)?c.push(p):i.add(p.sequence);for(const p of c)l(p,Math.max(0,...i)+1);const d=[...t.scales,...r.map(p=>o.find(h=>h.id===p.id&&h.kind==="Scale")?.to??p.sequence)],u=td(t.maxSizes,d),m=[];for(const p of n.filter(h=>h.kind==="MaxSize"))p.sequence<u.before&&!i.has(p.sequence)?i.add(p.sequence):m.push(p);for(const p of m){const h=nd(u,i);h===void 0?s.push(`The scaling of tab ${e} has no free position for MaxSize ${p.id} (Sequence ${p.sequence}): it must come before the first Scale (${u.before}) and use a Sequence no other step uses`):l(p,h)}return{changes:o,problems:s}}function Bb(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 qn(){return{customActions:new Map,templates:new Map,commandDefinitions:new Map,tabDisplayRules:new Map,displayRules:new Map,enableRules:new Map,locLabels:new Map}}const Dn=()=>new XMLSerializer;function sd(e){const t=new DOMParser().parseFromString(e,"application/xml"),n=t.querySelector("parsererror");if(n)throw new Error(`Invalid RibbonDiffXml: ${n.textContent??"parse error"}`);return t}function kt(e,t){return e?Array.from(e.children).filter(n=>n.tagName===t):[]}function ve(e,t){return kt(e,t)[0]}function id(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 AR(e){const t=qn(),o=sd(e).documentElement;if(o.tagName!=="RibbonDiffXml")throw new Error(`Expected <RibbonDiffXml> root, got <${o.tagName}>`);const s=Dn();for(const r of Array.from(ve(o,"CustomActions")?.children??[])){const c=id(r);c&&t.customActions.set(c,s.serializeToString(r))}const i=ve(ve(o,"Templates"),"RibbonTemplates");for(const r of Array.from(i?.children??[])){const c=r.getAttribute("Id");c&&t.templates.set(c,s.serializeToString(r))}for(const r of kt(ve(o,"CommandDefinitions"),"CommandDefinition")){const c=r.getAttribute("Id");c&&t.commandDefinitions.set(c,s.serializeToString(r))}const l=ve(o,"RuleDefinitions");for(const r of kt(ve(l,"TabDisplayRules"),"TabDisplayRule")){const c=r.getAttribute("TabCommand");c&&t.tabDisplayRules.set(c,s.serializeToString(r))}for(const r of kt(ve(l,"DisplayRules"),"DisplayRule")){const c=r.getAttribute("Id");c&&t.displayRules.set(c,s.serializeToString(r))}for(const r of kt(ve(l,"EnableRules"),"EnableRule")){const c=r.getAttribute("Id");c&&t.enableRules.set(c,s.serializeToString(r))}for(const r of kt(ve(o,"LocLabels"),"LocLabel")){const c=r.getAttribute("Id");c&&t.locLabels.set(c,s.serializeToString(r))}return t}function Se(e){return sd(e).documentElement}function Lb(e){const t=qn();for(const n of e.diffs){const o=n.rdx?.trim();if(!o)continue;const s=Se(o);switch(n.difftype){case 3:{const i=s.getAttribute("Id")??n.diffid;i&&t.locLabels.set(i,o);break}case 2:{const i=s.getAttribute("Id")??n.diffid;i&&t.templates.set(i,o);break}default:{const i=id(s);i&&t.customActions.set(i,o)}}}for(const n of e.commands){const o=n.commanddefinition?.trim(),s=n.command??(o?Se(o).getAttribute("Id"):null);o&&s&&t.commandDefinitions.set(s,o)}for(const n of e.rules){const o=n.ruledefinition?.trim();if(!o)continue;const s=Se(o);if(n.ruletype===3||s.tagName==="TabDisplayRule"){const i=s.getAttribute("TabCommand")??n.ruleid;i&&t.tabDisplayRules.set(i,o)}else if(n.ruletype===1||s.tagName==="EnableRule"){const i=s.getAttribute("Id")??n.ruleid;i&&t.enableRules.set(i,o)}else{const i=s.getAttribute("Id")??n.ruleid;i&&t.displayRules.set(i,o)}}return t}function za(e,t){const n=qn();for(const o of Object.keys(n)){for(const[s,i]of e[o])n[o].set(s,i);for(const[s,i]of t[o])n[o].set(s,i)}return n}function OR(e){const t=(n,o)=>Array.from(n.values()).map(s=>`${o}${s}`).join(`
|
|
6
|
+
`);return`<RibbonDiffXml>
|
|
7
|
+
<CustomActions>
|
|
8
|
+
${t(e.customActions," ")}
|
|
9
|
+
</CustomActions>
|
|
10
|
+
<Templates>
|
|
11
|
+
<RibbonTemplates Id="Mscrm.Templates">
|
|
12
|
+
${t(e.templates," ")}
|
|
13
|
+
</RibbonTemplates>
|
|
14
|
+
</Templates>
|
|
15
|
+
<CommandDefinitions>
|
|
16
|
+
${t(e.commandDefinitions," ")}
|
|
17
|
+
</CommandDefinitions>
|
|
18
|
+
<RuleDefinitions>
|
|
19
|
+
<TabDisplayRules>
|
|
20
|
+
${t(e.tabDisplayRules," ")}
|
|
21
|
+
</TabDisplayRules>
|
|
22
|
+
<DisplayRules>
|
|
23
|
+
${t(e.displayRules," ")}
|
|
24
|
+
</DisplayRules>
|
|
25
|
+
<EnableRules>
|
|
26
|
+
${t(e.enableRules," ")}
|
|
27
|
+
</EnableRules>
|
|
28
|
+
</RuleDefinitions>
|
|
29
|
+
<LocLabels>
|
|
30
|
+
${t(e.locLabels," ")}
|
|
31
|
+
</LocLabels>
|
|
32
|
+
</RibbonDiffXml>`}function zb(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 Fr(e,t){const n=Se(t);if(e==="commandDefinitions")for(const o of Array.from(n.getElementsByTagName("JavaScriptFunction")))zb(o)&&o.parentNode?.replaceChild(n.ownerDocument.createElement("PlatformJavaScriptFunction"),o);if(e==="locLabels")for(const o of Array.from(n.getElementsByTagName("Titles"))){const s=Array.from(o.children).sort((i,l)=>Number(i.getAttribute("languagecode"))-Number(l.getAttribute("languagecode")));for(const i of s)o.appendChild(i)}return En(n,{normalizeCommands:e==="commandDefinitions"})}const ad=(e,t,n)=>{try{return Fr(e,t)===Fr(e,n)}catch{return t===n}},_r=e=>Array.from(Se(e).getElementsByTagName("Title")).map(t=>`${t.getAttribute("languagecode")}=${t.getAttribute("description")??""}`);function Pb(e,t,n){if(e!=="locLabels")return ad(e,t,n);try{const o=new Set(_r(t)),s=_r(n);return s.length>0&&s.every(i=>o.has(i))}catch{return t===n}}function MR(e,t){const n=[];for(const o of Object.keys(t))for(const[s,i]of t[o]){const l=e[o].get(s);(l===void 0||!ad(o,l,i))&&n.push(`${o}:${s}`)}return n}function ER(e,t,n={}){const o=[],s=[],i=[],l=new Set(n.contentKeys??[]);for(const r of Object.keys(e)){for(const[c,d]of e[r]){const u=t[r].get(c);u===void 0?o.push(`${r}:${c}`):l.has(`${r}:${c}`)&&!Pb(r,d,u)&&i.push(`${r}:${c}`)}for(const c of t[r].keys())e[r].has(c)||s.push(`${r}:${c}`)}return{missing:o,unexpected:s,differing:i}}function DR(e){return Object.values(e).reduce((t,n)=>t+n.size,0)}function Xs(e){const t=Se(e);return t.tagName!=="CustomAction"?null:ve(t,"CommandUIDefinition")?.firstElementChild??null}function yt(e){return!!e&&e.endsWith("._children")}const Fb=new Set(["Menu","MenuSection","Controls"]);function Pi(e){return e.tagName==="Tab"||e.tagName==="Group"?[]:Array.from(e.getElementsByTagName("*")).filter(t=>!Fb.has(t.tagName)&&!!t.getAttribute("Id")&&t.parentElement?.tagName==="Controls")}const bo=e=>e?.tagName==="Tab"||e?.tagName==="Group",qr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function rd(e){return Array.from(e.getElementsByTagName("Controls")).flatMap(t=>Array.from(t.children))}function ld(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 ts(e){return bo(e)?rd(e):Pi(e)}function ns(e){const t=new Set;for(const n of e.customActions.values()){const o=Se(n);if(o.tagName!=="CustomAction"||!yt(o.getAttribute("Location")))continue;const s=ve(o,"CommandUIDefinition")?.firstElementChild,i=s?.getAttribute("Id");if(i&&t.add(i),s)for(const l of ts(s)){const r=l.getAttribute("Id");r&&t.add(r)}}return t}function cd(e,t){const n=new Map(e),o=Dn(),s=t?new Set(t):void 0;for(let i=!0;i;){i=!1;const l=new Map;for(const[r,c]of n){const d=Se(c);if(d.tagName!=="CustomAction"||!yt(d.getAttribute("Location")))continue;const u=ve(d,"CommandUIDefinition")?.firstElementChild;if(bo(u))for(const m of[u,...Array.from(u.getElementsByTagName("Group"))]){const p=m.getAttribute("Id");p&&!l.has(p)&&l.set(p,r)}}for(const[r,c]of n){const d=Se(c);if(d.tagName!=="CustomAction")continue;const u=/^(.+)\.(Controls|Groups|Scaling)\._children$/.exec(d.getAttribute("Location")??""),m=ve(d,"CommandUIDefinition")?.firstElementChild,p=u?l.get(u[1]):void 0;if(!u||!m||!p||p===r||s&&!s.has(r)&&!s.has(p))continue;const[,h,b]=u,g=Se(n.get(p)),x=ld(g,h);if(!x||x.tagName!==(b==="Controls"?"Group":"Tab"))continue;const y=g.ownerDocument;let S=ve(x,b);if(!S){S=y.createElement(b),S.setAttribute("Id",`${h}.${b}`);const I=b==="Scaling"?ve(x,"Groups"):void 0;x.insertBefore(S,I??null)}const C=y.importNode(m,!0),R=d.getAttribute("Sequence");!C.getAttribute("Sequence")&&R&&C.setAttribute("Sequence",R);const M=C.tagName==="MaxSize"?ve(S,"Scale"):void 0;S.insertBefore(C,M??null),n.set(p,o.serializeToString(g)),s?.add(p),n.delete(r),i=!0;break}}return n}function _b(e,t){const n=ve(e,"CommandUIDefinition")?.firstElementChild??null;return n?n.getAttribute("Id")===t?n:ts(n).find(o=>o.getAttribute("Id")===t)??null:null}function dd(e){const t=new Set;for(const n of e.customActions.values()){const o=Se(n);if(o.tagName!=="CustomAction"||!yt(o.getAttribute("Location")))continue;const s=ve(o,"CommandUIDefinition")?.firstElementChild;if(!s||s.tagName!=="Tab"&&s.tagName!=="Group")continue;const i=s.getAttribute("Id");i&&t.add(i);for(const l of Array.from(s.getElementsByTagName("Group"))){const r=l.getAttribute("Id");r&&t.add(r)}}return t}function Cs(e){const t=[];for(const n of e.customActions.values()){const o=Se(n);if(o.tagName!=="HideCustomAction")continue;const s=o.getAttribute("Location");s&&t.push({hideActionId:o.getAttribute("HideActionId")??"",location:s})}return t}function qb(e){const t=[],n=e.getAttribute("Id");n&&t.push(n);for(const o of Array.from(e.getElementsByTagName("*"))){const s=o.getAttribute("Id");s&&t.push(s)}return t}function ro(e){const t=[];for(const n of[e,...Array.from(e.getElementsByTagName("*"))])for(const o of Zc){const s=n.getAttribute(o);s&&t.push(s)}return t}function ud(e){const t=new Set;for(const n of e.customActions.values()){const o=Se(n);if(o.tagName==="CustomAction")for(const s of ro(o))t.add(s)}return t}function Hb(e){return/^(Mscrm|Microsoft)\./.test(e)}function Pa(e,t){if(Hb(e))return!0;for(const n of t)if(n===e)return!1;return!0}function Wb(e){const t=e?.match(/^(.+)\.(?:Controls|Groups)\._children$/);return t?t[1]:null}function Uo(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 Hr(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 Gb(e,t,n){const o=kt(e,"Menu")[0],s=kt(t,"Menu")[0];if(!o){for(const r of Pi(t))n(r.getAttribute("Id")??"")&&r.parentNode?.removeChild(r);return Uo(t,e)}const i=o.cloneNode(!0),l=(r,c)=>[i,...Array.from(i.getElementsByTagName("*"))].find(d=>d.getAttribute("Id")===c&&(r?d.tagName===r:d.parentElement?.tagName==="Controls"));if(s){for(const r of Array.from(s.getElementsByTagName("MenuSection"))){const c=l("MenuSection",r.getAttribute("Id")??"");if(c){Hr(r,c);continue}const d=l("Menu",r.parentElement?.getAttribute("Id")??"");if(!d)continue;const u=r.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 r of Pi(t)){const c=r.getAttribute("Id")??"";if(n(c))continue;const d=l(null,c);if(d){Hr(r,d);continue}const u=l("Controls",r.parentElement?.getAttribute("Id")??"");u&&u.appendChild(r.cloneNode(!0))}}for(const r of kt(t,"Menu"))t.removeChild(r);return t.appendChild(i),t}const Ks=/\$LocLabels:([^"'\s]+)/g;function Wr(e){const t=new Set;for(const n of e)for(const o of ro(Se(n)))t.add(o);return t}function Ub(e){const t=new Set;for(const n of e){const o=Se(n);for(const s of[o,...Array.from(o.getElementsByTagName("*"))])for(const i of Array.from(s.attributes))i.value.startsWith("$LocLabels:")&&t.add(i.value.slice(11))}return t}function Eo(e){const t={EnableRule:new Set,DisplayRule:new Set};for(const n of e){const o=Se(n);for(const s of["EnableRule","DisplayRule"])for(const i of Array.from(o.getElementsByTagName(s))){const l=i.getAttribute("Id");l&&t[s].add(l)}}return t}function BR(e,t,n={}){const o=new Set(n.editedCommandIds??[]),s=new Set(n.editedEnableRuleIds??[]),i=new Set(n.editedDisplayRuleIds??[]),l=new Set(n.deletedControlIds??[]),r=new Set(n.unhiddenControlIds??[]),c=new Set(n.retainedCommandIds??[]),d=Dn(),u=za(e,qn()),m=new Map,p=new Map,h=[];for(const[E,w]of e.customActions){const k=Xs(w),N=Se(w);if(N.tagName!=="CustomAction")continue;const j=N.getAttribute("Location");if(k?.getAttribute("Id")&&yt(j)){m.set(k.getAttribute("Id"),E);for(const _ of ts(k)){const W=_.getAttribute("Id");W&&h.push([W,E])}}else j&&p.set(j,E)}for(const[E,w]of h)m.has(E)||m.set(E,w);const b=(E,w)=>{const k=u.customActions.get(E);if(!k)return{ca:null,el:null,nested:!1};const N=Se(k),j=_b(N,w);return{ca:N,el:j,nested:!!j&&j.parentElement?.tagName!=="CommandUIDefinition"}},g=new Set;for(const[E,w]of t.customActions){const k=Se(w),N=Xs(w),j=N?.getAttribute("Id")??null,_=j?m.get(j):void 0,W=k.tagName==="CustomAction"&&yt(k.getAttribute("Location"));W&&j&&g.add(j);const ne=N?.tagName==="Tab"||N?.tagName==="Group";if(W&&ne)for(const G of rd(N)){const H=G.getAttribute("Id");if(!H)continue;g.add(H);const te=m.get(H),P=te?b(te,H):null;!te||!P?.ca||!P.el||(P.nested?(P.el.parentNode.removeChild(P.el),u.customActions.set(te,d.serializeToString(P.ca))):u.customActions.delete(te))}const le=k.tagName==="CustomAction"&&N&&j&&_&&!(W&&ne),ce=le?b(_,j):null;if(le&&ce?.ca&&ce.el&&ce.nested){const{ca:G,el:H}=ce;if(W)H.parentNode.removeChild(H),u.customActions.set(E,w);else{const te=Uo(G.ownerDocument.importNode(N,!0),H);H.parentNode.replaceChild(te,H)}u.customActions.set(_,d.serializeToString(G));continue}if(le&&ce?.ca&&ce.el){const{ca:G,el:H,nested:te}=ce;if(W&&te){H.parentNode.removeChild(H),u.customActions.set(_,d.serializeToString(G)),u.customActions.set(E,w);continue}let P=G.ownerDocument.importNode(N,!0);if(W?P=Gb(H,P,K=>{const ue=m.get(K);return!!ue&&ue!==_}):P=Uo(P,H),H.parentNode.replaceChild(P,H),!te){W&&G.setAttribute("Location",k.getAttribute("Location"));const K=N.getAttribute("Sequence")??(W?k.getAttribute("Sequence"):null);K&&G.setAttribute("Sequence",K)}u.customActions.set(_,d.serializeToString(G));continue}const F=k.getAttribute("Location"),L=k.tagName==="CustomAction"&&F?p.get(F):void 0;if(L&&N){const G=Xs(e.customActions.get(L)),H=Se(w),te=ve(H,"CommandUIDefinition");te?.firstElementChild&&Uo(te.firstElementChild,G),u.customActions.delete(L),u.customActions.set(E,d.serializeToString(H));continue}u.customActions.set(E,w)}for(const{id:E,sequence:w}of n.resequencedContainers??[])for(const[k,N]of u.customActions){const j=Se(N),_=ve(j,"CommandUIDefinition");if(j.tagName!=="CustomAction"||!_)continue;const W=_.firstElementChild,ne=W?.getAttribute("Id")===E?W:Array.from(_.getElementsByTagName("*")).find(le=>(le.tagName==="Group"||le.tagName==="Tab")&&le.getAttribute("Id")===E);ne&&(ne.setAttribute("Sequence",String(w)),ne===W&&j.setAttribute("Sequence",String(w)),u.customActions.set(k,Dn().serializeToString(j)))}for(const E of n.movedControls??[]){const w=m.get(E.id),k=w?b(w,E.id):null;if(!w||!k?.ca||!k.el){if(g.has(E.id))continue;throw new Error(`Can't move ${E.id}: it isn't in this entity's unmanaged customizations.`)}const{ca:N,el:j}=k,_=E.controlsId??`${E.groupId}.Controls`;if(j.setAttribute("Sequence",String(E.sequence)),!k.nested)N.setAttribute("Location",`${_}._children`),N.setAttribute("Sequence",String(E.sequence));else if(j.parentElement?.getAttribute("Id")!==_){const W=Array.from(N.getElementsByTagName("Controls")).find(ne=>ne.getAttribute("Id")===_);if(j.parentNode.removeChild(j),W)W.appendChild(j);else{let ne=`${E.id}.CustomAction`;for(;u.customActions.has(`ca:${ne}`);)ne+="_";u.customActions.set(`ca:${ne}`,`<CustomAction Id="${qr(ne)}" Location="${qr(`${_}._children`)}" Sequence="${E.sequence}"><CommandUIDefinition>${d.serializeToString(j)}</CommandUIDefinition></CustomAction>`)}}u.customActions.set(w,d.serializeToString(N))}const x=new Set,y=new Set;for(const[E,w]of Array.from(u.customActions)){const k=Se(w);if(k.tagName==="HideCustomAction"){r.has(k.getAttribute("Location")??"")&&u.customActions.delete(E);continue}const N=ve(k,"CommandUIDefinition")?.firstElementChild??null,j=N?.getAttribute("Id");if(!N||!yt(k.getAttribute("Location")))continue;if(j&&l.has(j)&&!g.has(j)){u.customActions.delete(E);for(const W of w.matchAll(Ks))y.add(W[1]);for(const W of ro(N))x.add(W);continue}const _=ts(N).filter(W=>{const ne=W.getAttribute("Id")??"";return l.has(ne)&&!g.has(ne)});if(_.length!==0){for(const W of _){const ne=d.serializeToString(W);for(const le of ne.matchAll(Ks))y.add(le[1]);for(const le of ro(W))x.add(le);W.parentNode?.removeChild(W)}u.customActions.set(E,d.serializeToString(k))}}const S=new Set,C=new Set(n.deletedContainerIds??[]),R=(E,w)=>{for(const k of qb(E))C.add(k);for(const k of ro(E))x.add(k);for(const k of[E,...Array.from(E.getElementsByTagName("Tab"))]){const N=k.tagName==="Tab"?k.getAttribute("Command"):null;N&&S.add(N)}for(const k of w.matchAll(Ks))y.add(k[1])};for(let E=C.size>0;E;){E=!1;for(const[w,k]of Array.from(u.customActions)){const N=Se(k),j=N.getAttribute("Location");if(N.tagName==="HideCustomAction"){j&&C.has(j)&&(u.customActions.delete(w),E=!0);continue}const _=ve(N,"CommandUIDefinition")?.firstElementChild??null,W=_?.getAttribute("Id")??null,ne=Wb(j);if(!!W&&C.has(W)&&yt(j)||!!ne&&C.has(ne)||!yt(j)&&!!j&&C.has(j)||!!_?.getAttribute("GroupId")&&C.has(_.getAttribute("GroupId"))){u.customActions.delete(w),_&&R(_,k),E=!0;continue}if(_?.tagName!=="Tab")continue;const ce=Array.from(_.getElementsByTagName("*")).filter(F=>F.tagName==="Group"?C.has(F.getAttribute("Id")??""):(F.tagName==="MaxSize"||F.tagName==="Scale")&&C.has(F.getAttribute("GroupId")??""));if(ce.length!==0){for(const F of ce)R(F,d.serializeToString(F)),F.parentNode?.removeChild(F);u.customActions.set(w,d.serializeToString(N)),E=!0}}}const M=new Set;for(const[E,w]of u.customActions)e.customActions.get(E)!==w&&M.add(E);u.customActions=cd(u.customActions,M);const I=(E,w)=>{for(const[k,N]of t[E])e[E].has(k)&&!w.has(k)||u[E].set(k,N)};I("commandDefinitions",o),I("enableRules",s),I("displayRules",i);const $=Wr(u.customActions.values());for(const E of x){if(c.has(E)||!u.commandDefinitions.has(E)||$.has(E))continue;const w=u.commandDefinitions.get(E);u.commandDefinitions.delete(E);const k=Eo([w]),N=Eo(u.commandDefinitions.values());for(const j of k.EnableRule)N.EnableRule.has(j)||u.enableRules.delete(j);for(const j of k.DisplayRule)N.DisplayRule.has(j)||u.displayRules.delete(j)}const T={EnableRule:new Set(n.retainedEnableRuleIds??[]),DisplayRule:new Set(n.retainedDisplayRuleIds??[])},v=ud(u);for(const E of n.uncustomisedCommandIds??[]){const w=u.commandDefinitions.get(E);if(w===void 0||t.commandDefinitions.has(E)||!Pa(E,v))continue;u.commandDefinitions.delete(E);const k=Eo(u.commandDefinitions.values()),N=Eo([w]);for(const j of["EnableRule","DisplayRule"])for(const _ of N[j]){const W=j==="EnableRule"?u.enableRules:u.displayRules;(j==="EnableRule"?t.enableRules:t.displayRules).has(_)||T[j].has(_)||k[j].has(_)||W.delete(_)}}for(const[E,w]of t.tabDisplayRules)u.tabDisplayRules.set(E,w);for(const[E,w]of t.templates)u.templates.set(E,w);const O=Ub(u.customActions.values());for(const E of y)!t.locLabels.has(E)&&!O.has(E)&&u.locLabels.delete(E);const A=Wr(u.customActions.values());for(const E of S)!t.tabDisplayRules.has(E)&&!A.has(E)&&u.tabDisplayRules.delete(E);for(const E of n.removedTabCommands??[])t.tabDisplayRules.has(E)||u.tabDisplayRules.delete(E);for(const[E,w]of t.locLabels){if(e.locLabels.get(E)){const N=Array.from(Se(w).querySelectorAll("Title")).map(j=>j.getAttribute("description"));if(N.length>0&&N.every(j=>j===E))continue}u.locLabels.set(E,w)}return u}function LR(e,t,n){const o=za(e,qn());for(const[s,i]of o.customActions){const l=Se(i);if(l.tagName!=="CustomAction"||!yt(l.getAttribute("Location")))continue;const r=ve(l,"CommandUIDefinition")?.firstElementChild;if(!bo(r))continue;const c=ld(r,t);if(!(!c||!bo(c))){c.setAttribute("Title",n),o.customActions.set(s,Dn().serializeToString(l));break}}return o}function Fa(e){const t=[],n=(o,s,i)=>({id:o.getAttribute("Id")??"",kind:o.tagName,groupId:o.getAttribute("GroupId")??"",sequence:Number(o.getAttribute("Sequence")??"0"),size:o.getAttribute("Size")??"",tabId:s,key:i});for(const[o,s]of e.customActions){const i=Se(s);if(i.tagName!=="CustomAction")continue;const l=ve(i,"CommandUIDefinition")?.firstElementChild;if(!l)continue;const r=/^(.+)\.Scaling\._children$/.exec(i.getAttribute("Location")??"");if(r&&(l.tagName==="MaxSize"||l.tagName==="Scale")&&t.push(n(l,r[1],o)),l.tagName==="Tab"&&yt(i.getAttribute("Location"))){const c=l.getAttribute("Id")??"";for(const d of Array.from(ve(l,"Scaling")?.children??[]))(d.tagName==="MaxSize"||d.tagName==="Scale")&&t.push(n(d,c,o))}}return t}function zR(e,t){const n=Fa(e),o=new Map;for(const c of n)o.set(c.tabId,[...o.get(c.tabId)??[],c]);const s=[],i=[];for(const[c,d]of o){const u=od(c,t[c]??{maxSizes:[],scales:[]},d);s.push(...u.changes),i.push(...u.problems)}if(s.length===0)return{parts:e,changes:s,problems:i};const l=za(e,qn()),r=Dn();for(const c of s){const d=n.find(h=>h.id===c.id&&h.kind===c.kind&&h.tabId===c.tabId),u=Se(l.customActions.get(d.key)),m=ve(u,"CommandUIDefinition").firstElementChild;(m.tagName==="Tab"?Array.from(ve(m,"Scaling")?.children??[]).find(h=>h.tagName===c.kind&&h.getAttribute("Id")===c.id):m)?.setAttribute("Sequence",String(c.to)),m.tagName!=="Tab"&&u.setAttribute("Sequence",String(c.to)),l.customActions.set(d.key,r.serializeToString(u))}return{parts:l,changes:s,problems:i}}function Vb(e,t){const n=new Map;for(const s of t.customActions.values()){const i=Se(s);if(i.tagName!=="CustomAction"||!yt(i.getAttribute("Location")))continue;const l=ve(i,"CommandUIDefinition")?.firstElementChild;if(bo(l))for(const r of[l,...Array.from(l.getElementsByTagName("Group"))]){const c=r.getAttribute("Id"),d=r.getAttribute("Title");c&&d?.startsWith("$LocLabels:")&&n.set(c,d)}}for(const s of e.tabs){const i=n.get(s.id);i&&(s.label=i);for(const l of s.groups){const r=n.get(l.id);r&&(l.label=r)}}const o=new Set(e.tabs.map(s=>s.id));for(const s of Fa(t)){if(!o.has(s.tabId))continue;e.scalingByTab=e.scalingByTab??{};const i=e.scalingByTab[s.tabId]=e.scalingByTab[s.tabId]??{tabId:s.tabId,maxSizes:[],scales:[]},l=s.kind==="MaxSize"?i.maxSizes:i.scales,r={id:s.id,groupId:s.groupId,size:s.size,sequence:s.sequence},c=l.findIndex(d=>d.id===s.id);c>=0?l[c]=r:l.push(r)}}function Ve(e,t,n=1033){if(!e)return"";const o=e.match(/^\$LocLabels:(.+)$/);if(o){const i=o[1],l=t.find(r=>r.id===i);if(l){const r=l.titles.find(u=>u.languageCode===n),c=l.titles.find(u=>u.languageCode===1033),d=l.titles[0];return r?.description??c?.description??d?.description??i}return i}const s=e.match(/^\$Resources(?:\([^)]*\))?:(.+)$/);return s?s[1]:e}function lo(e){return!!e&&/^\$Resources(\([^)]*\))?:/.test(e)}function md(e){return`$LocLabels:${e}`}function pd(e){const t=e.match(/^\$LocLabels:(.+)$/);return t?t[1]:null}const Gr=128;function Rs(e,t){const n=`${e}.${t}`;if(n.length<=Gr)return n;const o=Xb(e),s=Gr-t.length-o.length-2;return`${e.slice(0,s)}_${o}.${t}`}function Xb(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 Is(e){return Rs(e,"LabelText")}function js(e){return Rs(e,"ToolTipTitle")}function $s(e){return Rs(e,"ToolTipDescription")}function Kb(e){return Rs(e,"Title")}function Yb(e,t){const n=(o,s)=>(o?pd(o):null)??s;return{label:n(t?.labelToken,Is(e)),tooltipTitle:n(t?.tooltipTitleToken,js(e)),tooltipBody:n(t?.tooltipBodyToken,$s(e))}}function PR(e,t,n,o,s=1033){const i=e?pd(e):null;return i?o.some(l=>l.id===i)?i:(n??"")===Ve(e,[...o],s)?null:t:t}function Jb(e,t,n=1033){const o=new Set(Object.values(Yb(e.id,e.source))),s=new Set;for(const i of t)o.has(i.id)&&i.titles.forEach(l=>s.add(l.languageCode));return[...s].sort((i,l)=>i===n?-1:l===n?1:i-l)}const Jt={HomepageGrid:{label:"Main grid",title:"Main grid",body:"The command bar above the entity's full-page list of records. Unified Interface shows this ribbon as one flat bar: tabs, group layout and scaling are ignored, and commands that don't fit move under More commands (⋮).",ribbonId:"Mscrm.HomepageGrid.{table}"},Form:{label:"Main form",title:"Main form",body:"The command bar at the top of the entity's main form. Unified Interface shows it as one flat bar: tab layout and scaling are ignored, but button visibility and command actions work as configured, as in Ribbon Workbench. Microsoft doesn't support the tabbed ribbon on Unified Interface.",ribbonId:"Mscrm.Form.{table}"},SubGrid:{label:"Sub-grid",title:"Sub-grid",body:"The command bar on this entity's sub-grids on other entities' forms, and on the Related tab's associated view. Unified Interface shows the entity's whole sub-grid command bar there (Add New, Add Existing, Refresh, and with rows selected Edit, Delete, Assign, …), and in a narrow form column everything sits under More commands (⋮). Its built-in buttons can be overridden: in a live check, an override changed a sub-grid button's label, icon and command.",ribbonId:"Mscrm.SubGrid.{table}"},Application:{label:"Application",title:"Application ribbon",body:"Changes here apply to every entity. Your buttons in GlobalTab's New group appear in the global command bar at the top of every page, in Unified Interface only, so new buttons can go only there, and GlobalTab takes no new groups. Built-in GlobalTab buttons are read-only.",ribbonId:"Application ribbon"}};function Zb(e,t){return Jt[e].ribbonId.replace("{table}",t||"<entity>")}function Qb(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 Tn=e=>e==="flyout"||e==="splitButton",_a=["button","flyout"],fd=e=>["true","1"].includes(e?.trim().toLowerCase()??"");function pn(e){const t=[];for(const n of e.menu?.sections??[])for(const o of n.controls)t.push(o),t.push(...pn(o));return t}function hd(e){return e.flatMap(t=>[t,...pn(t)])}function je(e){return hd(e.buttons)}function ey(e,t){const n=[];for(const o of Object.keys(e))for(const s of e[o].tabs)for(const i of s.groups)for(const l of je(i))l.commandId===t&&n.push({location:o,tab:s,group:i,button:l});return n}function gd(e,t,n,o,s){const i=[];for(const{location:l,button:r}of ey(e,t))if(r.id!==n){const c=s&&l!==s?` (${Jt[l].label.toLowerCase()})`:"",d=(o(r)||r.id)+c;i.includes(d)||i.push(d)}return i}function Ts(e,t){for(const n of e)for(const o of n.menu?.sections??[]){const s=o.controls.findIndex(l=>l.id===t);if(s>=0)return{parent:n,section:o,index:s};const i=Ts(o.controls,t);if(i)return i}}function os(e,t){if(!e.buttons.some(n=>n.id===t))return Ts(e.buttons,t)}function Ns(e,t){if(!e||!t)return;const n=e.buttons.find(s=>s.id===t);if(n)return n;const o=Ts(e.buttons,t);return o?.section.controls[o.index]}function ty(e,t){if(!(!e||!t))return e.buttons.find(n=>n.id===t||pn(n).some(o=>o.id===t))}function bd(e,t){const n=Ts(e.buttons,t);return n?(n.section.controls.splice(n.index,1),!0):!1}function Ys(e){return{id:`${e}.Menu`,sections:[Fi(e,[])]}}function Fi(e,t,n){let o=t.length+1;const s=new Set(t.map(l=>l.id));for(;s.has(`${e}.MenuSection${o}`);)o++;const i=`${e}.MenuSection${o}`;return{id:i,title:n,sequence:o*10,displayMode:"Menu16",controlsId:`${i}.Controls`,controls:[]}}function ny(e,t,n,o){if(!e)return;const s=new Set,i=new Map,l=c=>{const d=i.get(c);if(d)return d;let u=c.startsWith(t)?`${n}${c.slice(t.length)}`:`${n}.${c.split(".").pop()||"Item"}`;for(let m=2;s.has(u);m++)u=`${u.replace(/_\d+$/,"")}_${m}`;return s.add(u),i.set(c,u),u},r=c=>c.replace(/(\sId=")([^"]*)(")/g,(d,u,m,p)=>`${u}${l(m)}${p}`);return{...e,id:l(e.id),sections:e.sections.map(c=>({...c,id:l(c.id),controlsId:l(c.controlsId),controls:c.controls.map(d=>ss(d,l(d.id),o)),...c.rawControls?{rawControls:c.rawControls.map(d=>({...d,xml:r(d.xml)}))}:{},...c.rawContent!==void 0?{rawContent:r(c.rawContent)}:{}}))}}function oy(e,t,n){return e.replace(/(\s(?:Id|InitialItem)=")([^"]*)(")/g,(o,s,i,l)=>`${s}${i.startsWith(t)?`${n}${i.slice(t.length)}`:`${n}.${i}`}${l}`)}const sy=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand"];function co(e,t){return!!t&&!!e?.startsWith("$LocLabels:")&&!t.has(e.slice(11))}function ss(e,t,n){const o=sy.filter(u=>e.source?.attributes[u]!==void 0),s=Qb(e.source),i={...s?.attributes??{},...Object.fromEntries(o.map(u=>[u,e.source.attributes[u]]))},l=u=>lo(u)||co(u,n)?u:void 0,r={labelToken:l(e.source?.labelToken),tooltipTitleToken:l(e.source?.tooltipTitleToken),tooltipBodyToken:l(e.source?.tooltipBodyToken)},c=Object.fromEntries(Object.entries(r).filter(([,u])=>u!==void 0)),d=e.source?.xml?oy(e.source.xml,e.id,t):void 0;return{...e,id:t,source:Object.keys(i).length+Object.keys(c).length>0||d?{...s?.modernImage?{modernImage:s.modernImage}:{},...c,attributes:i,...d?{xml:d}:{}}:void 0,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0,menu:ny(e.menu,e.id,t,n)}}const iy=["label","icon","image16","image32","tooltipTitle","tooltipBody","commandId","templateAlias"];function _i(e,t){for(const n of iy)if((e[n]??"")!==(t[n]??""))return!0;return!1}function It(e){const t=new Map,n=new Map,o=(s,i,l,r)=>{const c=n.get(s.id)??0;n.set(s.id,c+1);const d=`${s.id}#${c}`;t.set(d,r?{button:s,groupId:i,tabId:l,menu:r}:{button:s,groupId:i,tabId:l});for(const u of s.menu?.sections??[])for(const m of u.controls)o(m,i,l,{parentKey:d,parentId:s.id,sectionId:u.id,controlsId:u.controlsId})};for(const s of e.tabs)for(const i of s.groups)for(const l of i.buttons)o(l,i.id,s.id);return t}function qa(e,t){const n=It(t),o=It(e),s=l=>{for(let r=l.menu?.parentKey;r;r=o.get(r)?.menu?.parentKey)if(!n.has(r))return!0;return!1},i=[];for(const[l,r]of o){const c=n.get(l)?.button,d=r.button;if(s(r)){d.hidden&&i.push({entry:r,change:"hide"});continue}c?d.hidden&&!c.hidden?i.push({entry:r,change:"hide"}):_i(c,d)&&i.push({entry:r,change:"override"}):(d.hidden&&(d.oob||d.managed)||i.push({entry:r,change:"new"}),d.hidden&&i.push({entry:r,change:"hide"}))}return i}function yd(e){return e.commandId||`${e.id}.Command`}function ay(e,t){return e==="SubGrid"?`Mscrm.SubGrid.${t}.ContextualTabs._children`:"Mscrm.Tabs._children"}function xd(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 ry(e,t,n){const o=yd(e),s=(e.tabDisplayRules??[]).map(i=>({...i,tabCommand:i.tabCommand||o}));return{...e,commandId:o,tabDisplayRules:s.length>0?s:xd(t,n,o)}}function FR(e){const{current:t,baseline:n,commands:o,enableRules:s,displayRules:i,locLabels:l}=e,r=e.languageCode??1033,c=e.location==="Application",d=new Set,u=new Set;for(const L of n.tabs){d.add(L.id);for(const G of L.groups)u.add(G.id)}const m=It(n),p=new Map;for(const[L,G]of It(t))p.set(G.button,m.get(L)?.button);const h=t.tabs.filter(L=>!d.has(L.id)).map(L=>ry(L,e.location,e.entityLogicalName)),b=[],g=[],x=[],y=[],S=[],C=L=>S.push(L),R=[],M=L=>{const G=[];for(const H of L.buttons)H.hidden||p.get(H)||(G.push(ks(H,l,C,r,!0)),R.push(H,...pn(H)));return G},I=new Set,$=Sd(t,n).steps;for(const L of h){const G=new Map(L.groups.map(H=>[H.id,M(H)]));for(const H of L.groups)for(const te of H.buttons)!te.hidden&&!p.get(te)&&I.add(te);b.push(gy(L,t.scalingByTab?.[L.id],ay(e.location,e.entityLogicalName),G,$,C,r,l))}const T=[];for(const L of t.tabs)if(d.has(L.id)){for(const G of L.groups)if(!u.has(G.id)){for(const te of G.buttons)!te.hidden&&!p.get(te)&&I.add(te);g.push(hy(G,L.id,M(G),C,r,l));const H=$.get(G.id);H&&T.push(Hi(L.id,"MaxSize",H))}}g.push(...T);for(const{entry:L,change:G}of qa(t,n)){const{button:H,groupId:te,menu:P}=L;if(!I.has(H))if(G==="hide")y.push(fy(H));else if(G==="new"){const K=P?`${P.controlsId}._children`:`${te}.Controls._children`;x.push(my(H,K,l,C,r)),R.push(H,...pn(H))}else x.push(py(H,l,C,r)),R.push(H)}const v=new Set;for(const L of R)for(const G of ed(L))v.add(G);for(const L of t.tabs)for(const G of L.groups){const H=G.source?.attributes.Command;H&&!u.has(G.id)&&v.add(H)}const O=[];for(const L of h){const G=L.commandId;v.add(G),o.some(H=>H.id===G)||O.push({id:G,enableRules:[],displayRules:[],actions:[]})}const A=[...o.filter(L=>v.has(L.id)&&(!Qs(L.id)||L.actions.length>0)),...O],E=new Set,w=new Set;for(const L of A)L.enableRules.forEach(G=>E.add(G)),L.displayRules.forEach(G=>w.add(G));const k=s.filter(L=>E.has(L.id)&&!Qs(L.id)),N=i.filter(L=>w.has(L.id)&&!Qs(L.id)),j=Ry(S),_=A.map($y).join(`
|
|
33
|
+
`),W=k.map(Ty).join(`
|
|
34
|
+
`),ne=N.map(Ny).join(`
|
|
35
|
+
`),le=j.map(ky).join(`
|
|
36
|
+
`),ce=[...b,...g,...cy(t,n,d),...x,...y],F=h.filter(L=>L.tabDisplayRules.length>0).map(L=>Ay(L,c)).filter(Boolean).join(`
|
|
37
|
+
`);return`<RibbonDiffXml>
|
|
38
|
+
<CustomActions>
|
|
39
|
+
${ce.join(`
|
|
40
|
+
`)}
|
|
41
|
+
</CustomActions>
|
|
42
|
+
<Templates><RibbonTemplates Id="Mscrm.Templates"/></Templates>
|
|
43
|
+
<CommandDefinitions>
|
|
44
|
+
${_}
|
|
45
|
+
</CommandDefinitions>
|
|
46
|
+
<RuleDefinitions>
|
|
47
|
+
<TabDisplayRules>
|
|
48
|
+
${F}
|
|
49
|
+
</TabDisplayRules>
|
|
50
|
+
<DisplayRules>
|
|
51
|
+
${ne}
|
|
52
|
+
</DisplayRules>
|
|
53
|
+
<EnableRules>
|
|
54
|
+
${W}
|
|
55
|
+
</EnableRules>
|
|
56
|
+
</RuleDefinitions>
|
|
57
|
+
<LocLabels>
|
|
58
|
+
${le}
|
|
59
|
+
</LocLabels>
|
|
60
|
+
</RibbonDiffXml>`}function ly(e,t){const n=new Set,o=new Set;for(const b of t.tabs){n.add(b.id);for(const g of b.groups)o.add(g.id)}let s=0,i=0,l=0,r=0,c=0,d=0;for(const b of e.tabs){n.has(b.id)||r++,b.tabDisplayRules&&b.tabDisplayRules.length>0&&(d+=b.tabDisplayRules.length);for(const g of b.groups)!o.has(g.id)&&n.has(b.id)&&c++}for(const{change:b}of qa(e,t))b==="hide"?l++:b==="new"?s++:i++;const u=e.scalingByTab??{},m=t.scalingByTab??{};let p=0;for(const[b,g]of Object.entries(u))JSON.stringify(g)!==JSON.stringify(m[b])&&p++;const h=s+i+l+r+c+p>0;return{newButtons:s,overriddenButtons:i,hiddenButtons:l,newTabs:r,newGroups:c,scalingChanges:p,tabDisplayRules:d,hasAnyChange:h}}function cy(e,t,n){const o=[],s=[];for(const[i,l]of Object.entries(e.scalingByTab??{})){if(!n.has(i))continue;const r=t.scalingByTab?.[i],c=(d,u)=>u?.some(m=>JSON.stringify(m)===JSON.stringify(d))??!1;for(const d of l.maxSizes)c(d,r?.maxSizes)||o.push(Hi(i,"MaxSize",d));for(const d of l.scales)c(d,r?.scales)||s.push(Hi(i,"Scale",d))}return[...o,...s]}function qi(e,t){const n=e==="Scale"&&t.popupSize?` PopupSize="${ge(t.popupSize)}"`:"";return`<${e} Id="${ge(t.id)}" GroupId="${ge(t.groupId)}" Sequence="${t.sequence}" Size="${ge(t.size)}"${n}/>`}function Hi(e,t,n){return`<CustomAction Id="${ge(n.id)}.CustomAction"
|
|
61
|
+
Location="${ge(e)}.Scaling._children"
|
|
62
|
+
Sequence="${n.sequence}">
|
|
63
|
+
<CommandUIDefinition>
|
|
64
|
+
${qi(t,n)}
|
|
65
|
+
</CommandUIDefinition>
|
|
66
|
+
</CustomAction>`}const vd={"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"},dy=Object.keys(vd);function uy(e,t={}){const n=Ha(e.template);return vd[n]??(t[n]??t[e.template])?.find(o=>o!=="Popup")}function Sd(e,t){const n=new Map,o=[],s=[],i=new Set(t.tabs.map(r=>r.id)),l=new Set(t.tabs.flatMap(r=>r.groups.map(c=>c.id)));for(const r of e.tabs){const c=!i.has(r.id),d=e.scalingByTab?.[r.id],u=(d?.maxSizes??[]).map(b=>b.sequence),m=(d?.scales??[]).map(b=>b.sequence),p=new Set([...u,...m]);if(c&&p.size<u.length+m.length&&o.push(`The scaling of new tab ${r.id} uses a Sequence more than once — give every MaxSize and Scale its own`),c&&u.length>0)continue;const h=td(u,m);for(const b of r.groups){if(!c&&l.has(b.id)||d?.maxSizes.some(y=>y.groupId===b.id))continue;const g=uy(b,e.templateLayouts);if(!g){s.push(`New group "${b.label}" (${b.id}) uses template ${b.template}, whose layouts CBS doesn't know, so it gets no MaxSize: the classic ribbon may not show it. Pick one of Microsoft's templates to have one written.`);continue}const x=nd(h,p);if(x===void 0){o.push(`No free scaling position for the new group "${b.label}" (${b.id}) on tab ${r.id}: its MaxSize must come after the tab's last MaxSize (${h.after}) and before its first Scale (${h.before}), and no Sequence is free there`);continue}p.add(x),n.set(b.id,{id:`${b.id}.MaxSize`,groupId:b.id,size:g,sequence:x})}}return{steps:n,problems:o,warnings:s}}function my(e,t,n,o,s=1033){return`<CustomAction Id="${ge(e.id)}.CustomAction"
|
|
67
|
+
Location="${ge(t)}"
|
|
68
|
+
Sequence="${e.sequence}">
|
|
69
|
+
<CommandUIDefinition>
|
|
70
|
+
${ks(e,n,o,s,!0)}
|
|
71
|
+
</CommandUIDefinition>
|
|
72
|
+
</CustomAction>`}function py(e,t,n,o=1033){return`<CustomAction Id="${ge(e.id)}.Override.CustomAction"
|
|
73
|
+
Location="${ge(e.id)}"
|
|
74
|
+
Sequence="${e.sequence}">
|
|
75
|
+
<CommandUIDefinition>
|
|
76
|
+
${ks(e,t,n,o)}
|
|
77
|
+
</CommandUIDefinition>
|
|
78
|
+
</CustomAction>`}function fy(e,t){return`<HideCustomAction HideActionId="${ge(e.id)}.HideAction"
|
|
79
|
+
Location="${ge(e.id)}"/>`}function hy(e,t,n,o,s=1033,i=[]){return`<CustomAction Id="${ge(e.id)}.CustomAction"
|
|
80
|
+
Location="${ge(t)}.Groups._children"
|
|
81
|
+
Sequence="${e.sequence}">
|
|
82
|
+
<CommandUIDefinition>
|
|
83
|
+
${wd(e,o,n,s,i)}
|
|
84
|
+
</CommandUIDefinition>
|
|
85
|
+
</CustomAction>`}function gy(e,t,n,o,s,i,l=1033,r=[]){const c=Cd(e,i,l,r),d=e.commandId?` Command="${ge(e.commandId)}"`:"",u=e.groups.map(b=>wd(b,i,o.get(b.id)??[],l,r)).join(`
|
|
86
|
+
`),p=[...(t?.maxSizes.length?t.maxSizes:e.groups.map(b=>s.get(b.id)).filter(b=>!!b)).map(b=>qi("MaxSize",b)),...(t?.scales??[]).map(b=>qi("Scale",b))],h=p.length===0?`<Scaling Id="${ge(e.id)}.Scaling"/>`:`<Scaling Id="${ge(e.id)}.Scaling">
|
|
87
|
+
${p.join(`
|
|
88
|
+
`)}
|
|
89
|
+
</Scaling>`;return`<CustomAction Id="${ge(e.id)}.CustomAction"
|
|
90
|
+
Location="${ge(n)}"
|
|
91
|
+
Sequence="${e.sequence}">
|
|
92
|
+
<CommandUIDefinition>
|
|
93
|
+
<Tab Id="${ge(e.id)}"${d} Title="${ge(c)}"${Rd(e,r,i)} Sequence="${e.sequence}"${Id(e)}>
|
|
94
|
+
${h}
|
|
95
|
+
<Groups Id="${ge(e.id)}.Groups">
|
|
96
|
+
${u}
|
|
97
|
+
</Groups>
|
|
98
|
+
</Tab>
|
|
99
|
+
</CommandUIDefinition>
|
|
100
|
+
</CustomAction>`}function wd(e,t,n=[],o=1033,s=[]){const i=Cd(e,t,o,s),l=Ha(e.template),r=n.length===0?`<Controls Id="${ge(e.id)}.Controls"/>`:`<Controls Id="${ge(e.id)}.Controls">
|
|
101
|
+
${n.join(`
|
|
102
|
+
`)}
|
|
103
|
+
</Controls>`;return`<Group Id="${ge(e.id)}" Title="${ge(i)}"${Rd(e,s,t)} Sequence="${e.sequence}" Template="${ge(l)}"${Id(e)}>
|
|
104
|
+
${r}
|
|
105
|
+
</Group>`}function Cd(e,t,n,o){const s=`${e.id}.Title`;if(e.source&&e.label){const l=uo(e.label,e.source.titleToken,s,o,t,n);if(l)return l}const i=(o.find(l=>l.id===s)?.titles??[]).filter(l=>l.languageCode!==n);return t({id:s,titles:[{languageCode:n,description:e.label},...i]}),md(s)}function Rd(e,t,n){const o=e.description,s=o?.startsWith("$LocLabels:")?t.find(i=>i.id===o.slice(11)):void 0;return s&&n(s),ee("Description",o)}const by=new Set(["Id","Command","Title","Description","Sequence","Template"]);function Id(e){const t="buttons"in e;return Object.entries(e.source?.attributes??{}).filter(([n])=>t&&n==="Command"||!by.has(n)).filter(([n])=>!Wa.has(n)).map(([n,o])=>` ${n}="${ge(o)}"`).join("")}function Ha(e){const t=e?.trim();return t?t.includes(".")?t:`Mscrm.Templates.${t}`:"Mscrm.Templates.Flexible2"}function yy(e,t,n,o,s=1033){const i=e??"";if(i.startsWith("$LocLabels:")){const c=i.slice(11),d=n.find(u=>u.id===c);return d&&o(d),i}if(lo(i))return i;const l=[{languageCode:s,description:i}],r=n.find(c=>c.id===t);if(r)for(const c of r.titles)c.languageCode!==s&&l.push(c);return o({id:t,titles:l}),md(t)}const xy=["ToolTipTitle","ToolTipDescription","ToolTipHelpKeyWord","ToolTipShortcutKey","ToolTipImage32by32","ToolTipImage32by32Class","ToolTipImage32by32Left","ToolTipImage32by32Top"],Js=["Image16by16","Image16by16Class","Image16by16Left","Image16by16Top","Image32by32","Image32by32Class","Image32by32Left","Image32by32Top","ModernImage"],yn=["Id","Command","Sequence","TemplateAlias",...xy],Zs=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand","CacheMenuVersions"],vy={Button:new Set([...yn,...Js,"Alt","CommandType","CommandValueId","Description","LabelCss","LabelText","MenuItemId","ModernCommandType","Priority"]),FlyoutAnchor:new Set([...yn,...Js,...Zs,"Alt","CommandMenuClose","CommandType","LabelText","ModernCommandType","ToolTipSelectedItemTitle"]),SplitButton:new Set([...yn,...Js,...Zs,"Alt","CommandMenuClose","CommandMenuOpen","CommandType","LabelText","MenuAlt","MenuCommand","ToolTipSelectedItemTitle"]),CheckBox:new Set([...yn,"Alt","LabelText","MenuItemId","QueryCommand"]),TextBox:new Set([...yn,"ImeEnabled","MaxLength","QueryCommand","ShowAsLabel","Width"]),ComboBox:new Set([...yn,...Zs,"AllowFreeForm","Alt","AltArrow","AutoComplete","AutoCompleteDelay","CommandMenuClose","CommandMenuOpen","CommandPreview","CommandPreviewRevert","ImeEnabled","InitialItem","QueryCommand","ToolTipSelectedItemTitle","Width"])},Wa=new Set(["SolutionUniqueName"]);function Sy(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 uo(e,t,n,o,s,i=1033){if(t!==void 0&&(e??"")===Ve(t,o,i)){if(t.startsWith("$LocLabels:")){const c=o.find(d=>d.id===t.slice(11));c&&s(c)}return t}if(!e)return;const l=t?.startsWith("$LocLabels:")?t.slice(11):void 0,r=l&&o.some(c=>c.id===l)?l:n;return yy(e,r,o,s,i)}function Ga(e){const t=e.source,n=r=>!!r?.startsWith("$webresource:"),o=r=>r&&!r.startsWith("/")&&/[/.]/.test(r)?Ua(r):r,s=o(e.image32),i=o(e.image16),l=[[e.image32,s,"Image32by32"],[e.image16,i,"Image16by16"]].filter(([r,c,d])=>n(c)&&r!==t?.attributes[d]).map(([,r])=>r);return t&&Sy(t.modernImage)===e.icon&&l.length===0?t.modernImage:l[0]??[s,i,e.icon].find(n)}function ks(e,t,n,o=1033,s=!1){const i=Iy(e.kind),l=e.source;if(l?.xml&&ut(e.kind))return jy(e,l.xml,t,n);const r=new Map;for(const[b,g]of Object.entries(l?.attributes??{}))Wa.has(b)||r.set(b,g);const c=(b,g)=>g===void 0||g===""?r.delete(b):r.set(b,g);c("Id",e.id),c("Command",e.commandId||void 0),c("LabelText",uo(e.label,l?.labelToken,Is(e.id),t,n,o)??""),r.has("LabelText")||r.set("LabelText",""),c("ToolTipTitle",uo(e.tooltipTitle,l?.tooltipTitleToken,js(e.id),t,n,o)),c("ToolTipDescription",uo(e.tooltipBody,l?.tooltipBodyToken,$s(e.id),t,n,o)),c("TemplateAlias",e.templateAlias),c("Sequence",l&&!("Sequence"in l.attributes)&&e.sequence===0?void 0:String(e.sequence));const d=b=>!!b&&(b.startsWith("$webresource:")||b.includes("/")||b.includes(".")),u=b=>d(b)?Ua(b):void 0;c("ModernImage",Ga(e)),c("Image16by16",u(e.image16)),c("Image32by32",u(e.image32));const m=vy[i];if(m)for(const b of[...r.keys()])m.has(b)||r.delete(b);const p=Array.from(r.entries()).map(([b,g])=>`${b}="${ge(g)}"`).join(" "),h=s&&e.menu&&wy.has(i)?Cy(e.menu,t,n,o):"";return h?`<${i} ${p}>${h}</${i}>`:`<${i} ${p}/>`}const wy=new Set(["FlyoutAnchor","SplitButton","ComboBox"]);function Cy(e,t,n,o){const s=e.sections.map(r=>{const c=new Map(Object.entries(r.attributes??{})),d=(h,b)=>b===void 0||b===""?c.delete(h):c.set(h,b);d("Id",r.id),d("Title",uo(r.title,r.attributes?.Title,Kb(r.id),t,n,o));const u=!!r.attributes&&!("Sequence"in r.attributes)&&r.sequence===0;d("Sequence",u?void 0:String(r.sequence)),d("DisplayMode",r.displayMode);const m=Array.from(c.entries()).map(([h,b])=>` ${h}="${ge(b)}"`).join("");if(r.rawContent!==void 0)return`<MenuSection${m}>${r.rawContent}</MenuSection>`;const p=r.controls.map(h=>ks(h,t,n,o,!0));for(const h of[...r.rawControls??[]].sort((b,g)=>b.index-g.index))p.splice(Math.min(h.index,p.length),0,h.xml);return`<MenuSection${m}><Controls Id="${ge(r.controlsId)}">${p.join("")}</Controls></MenuSection>`}),i=new Map(Object.entries(e.attributes??{}));return i.set("Id",e.id),`<Menu${Array.from(i.entries()).map(([r,c])=>` ${r}="${ge(c)}"`).join("")}>${s.join("")}</Menu>`}function Qs(e){return/^(Mscrm|Microsoft)\./.test(e)}function Ry(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 Iy(e){return $n[e]??"Button"}function jy(e,t,n,o){const s=new DOMParser().parseFromString(t,"application/xml").documentElement;for(const l of[s,...Array.from(s.getElementsByTagName("*"))])for(const r of Wa)l.removeAttribute(r);s.setAttribute("Id",e.id),(s.hasAttribute("Sequence")||e.sequence!==0)&&s.setAttribute("Sequence",String(e.sequence));const i=new XMLSerializer().serializeToString(s);for(const l of i.matchAll(/\$LocLabels:([^"'\s<]+)/g)){const r=n.find(c=>c.id===l[1]);r&&o(r)}return i}function Ua(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 jd(e){const t=(e??"").trim();return t.startsWith("/")?t:Ua(t)}function ee(e,t){return t===void 0?"":` ${e}="${ge(String(t))}"`}function jt(e,t,n,o){return n.length===0?`<${e}${t}/>`:`<${e}${t}>
|
|
106
|
+
${n.map(s=>`${o} ${s}`).join(`
|
|
107
|
+
`)}
|
|
108
|
+
${o}</${e}>`}function $d(e,t=" "){switch(e.kind){case"javascript":return jt("JavaScriptFunction",`${ee("FunctionName",e.functionName)}${ee("Library",jd(e.library))}`,e.params.map(n=>Wi(n,!1)),t);case"url":return jt("Url",`${ee("Address",e.address)}${ee("PassParams",e.passParams)}${ee("WinMode",e.winMode)}${ee("WinParams",e.winParams)}`,e.params.map(n=>Wi(n,!0)),t);case"outlookCommand":return`<OutlookCommand${ee("ActionType",e.actionType)}${ee("Data",e.data)}/>`;case"raw":return e.xml;default:return""}}function $y(e){const t=" ",n=(l,r)=>{const c=[...r];for(const d of e.rawRuleRefs??[])d.container===l&&c.splice(Math.min(d.index,c.length),0,d.xml);return c},o=n("EnableRules",e.enableRules.map(l=>`<EnableRule Id="${ge(l)}"/>`)),s=n("DisplayRules",e.displayRules.map(l=>`<DisplayRule Id="${ge(l)}"/>`)),i=e.actions.map(l=>$d(l,`${t} `)).filter(Boolean);return`<CommandDefinition Id="${ge(e.id)}">
|
|
109
|
+
${t} ${jt("EnableRules","",o,`${t} `)}
|
|
110
|
+
${t} ${jt("DisplayRules","",s,`${t} `)}
|
|
111
|
+
${t} ${jt("Actions","",i,`${t} `)}
|
|
112
|
+
${t}</CommandDefinition>`}function Wi(e,t){const n=t?ee("Name",e.name??""):"";switch(e.kind){case"CrmParameter":return`<CrmParameter${n}${ee("Value",e.value)}/>`;case"BoolParameter":return`<BoolParameter${n}${ee("Value",e.value)}/>`;case"IntParameter":return`<IntParameter${n}${ee("Value",e.value)}/>`;case"DecimalParameter":return`<DecimalParameter${n}${ee("Value",e.value)}/>`;case"StringParameter":return`<StringParameter${n}${ee("Value",e.value)}/>`}}function Ty(e){return jt("EnableRule",ee("Id",e.id),e.steps.map(t=>As(t," "))," ")}function Ny(e){return jt("DisplayRule",ee("Id",e.id),e.steps.map(t=>As(t," "))," ")}function As(e,t=""){if(e.kind==="RawRule")return e.xml;if(e.kind==="OrRule"){const s=e.groups.map(i=>jt("Or","",i.map(l=>As(l,`${t} `)),`${t} `));return jt("OrRule","",s,t)}const n=`${ee("Default",e.default)}${ee("InvertResult",e.invertResult)}`,o=(s,i)=>`<${s}${i}${n}/>`;switch(e.kind){case"SelectionCountRule":return o("SelectionCountRule",`${ee("AppliesTo",e.appliesTo)}${ee("Minimum",e.minimum)}${ee("Maximum",e.maximum)}`);case"EntityRule":return o("EntityRule",`${ee("EntityName",e.entityName)}${ee("AppliesTo",e.appliesTo)}${ee("Context",e.context)}`);case"FormStateRule":return o("FormStateRule",ee("State",e.state));case"CommandClientTypeRule":return o("CommandClientTypeRule",ee("Type",e.type));case"CrmClientTypeRule":return o("CrmClientTypeRule",ee("Type",e.type));case"CustomRule":return jt("CustomRule",`${ee("FunctionName",e.functionName)}${ee("Library",e.library===void 0?void 0:jd(e.library))}${n}`,(e.params??[]).map(s=>Wi(s,!1)),t);case"FeatureControlRule":return o("FeatureControlRule",`${ee("FeatureControlBit",e.featureControlBit)}${ee("ExpectedValue",e.expectedValue)}`);case"MiscellaneousPrivilegeRule":return o("MiscellaneousPrivilegeRule",`${ee("PrivilegeName",e.privilegeName)}${ee("PrivilegeDepth",e.privilegeDepth)}`);case"FormTypeRule":return o("FormTypeRule",ee("Type",e.type));case"ValueRule":return o("ValueRule",`${ee("Field",e.field)}${ee("Value",e.value)}`);case"SkuRule":return o("SkuRule",ee("Sku",e.sku));case"HideForTabletExperienceRule":return o("HideForTabletExperienceRule","");case"OrganizationSettingRule":return o("OrganizationSettingRule",ee("Setting",e.setting));case"EntityPrivilegeRule":return o("EntityPrivilegeRule",`${ee("PrivilegeType",e.privilegeType)}${ee("PrivilegeDepth",e.privilegeDepth)}${ee("AppliesTo",e.appliesTo)}${ee("EntityName",e.entityName)}`);case"EntityPropertyRule":return o("EntityPropertyRule",`${ee("EntityName",e.entityName)}${ee("AppliesTo",e.appliesTo)}${ee("PropertyName",e.propertyName)}${ee("PropertyValue",e.propertyValue)}`);case"DeviceTypeRule":return o("DeviceTypeRule",ee("Type",e.type));case"RelationshipTypeRule":return o("RelationshipTypeRule",`${ee("AppliesTo",e.appliesTo)}${ee("RelationshipType",e.relationshipType)}${ee("AllowCustomRelationship",e.allowCustomRelationship)}${ee("AllowSystemRelationship",e.allowSystemRelationship)}`);case"RecordPrivilegeRule":return o("RecordPrivilegeRule",`${ee("PrivilegeType",e.privilegeType)}${ee("AppliesTo",e.appliesTo)}`);case"FormEntityContextRule":return o("FormEntityContextRule",ee("EntityName",e.entityName));case"PageRule":return o("PageRule",ee("Address",e.address));case"ReferencingAttributeRequiredRule":return o("ReferencingAttributeRequiredRule","");case"OutlookItemTrackingRule":return o("OutlookItemTrackingRule",`${ee("TrackedInCrm",e.trackedInCrm)}${ee("AppliesTo",e.appliesTo)}`);case"OutlookRenderTypeRule":return o("OutlookRenderTypeRule",ee("Type",e.type));case"OutlookVersionRule":return o("OutlookVersionRule",ee("Version",e.version));case"CrmOfflineAccessStateRule":return o("CrmOfflineAccessStateRule",ee("State",e.state));case"CrmOutlookClientTypeRule":return o("CrmOutlookClientTypeRule",ee("Type",e.type));case"CrmOutlookClientVersionRule":return o("CrmOutlookClientVersionRule",`${ee("Major",e.major)}${ee("Minor",e.minor)}${ee("Build",e.build)}${ee("Revision",e.revision)}`);case"OptionSetRule":return o("OptionSetRule",`${ee("OptionSet",e.optionSet)}${ee("StateCode",e.stateCode)}${ee("ObjectTypeCode",e.objectTypeCode)}`);default:{const s=e;throw new Error(`Unknown rule kind: ${s.kind}`)}}}function ky(e){const t=e.titles.map(n=>`<Title languagecode="${n.languageCode}" description="${ge(n.description)}"/>`).join(`
|
|
113
|
+
`);return`<LocLabel Id="${ge(e.id)}">
|
|
114
|
+
<Titles>
|
|
115
|
+
${t}
|
|
116
|
+
</Titles>
|
|
117
|
+
</LocLabel>`}function Ay(e,t){const n=new Map;for(const o of e.tabDisplayRules){const s=o.rules.map(i=>i.kind==="EntityRule"?`<EntityRule${ee("EntityName",i.entityName)}${ee("AppliesTo",i.appliesTo)}${ee("Context",i.context)}/>`:i.kind==="PageRule"&&t?`<PageRule${ee("Address",i.address)}/>`:"").filter(Boolean);n.set(o.tabCommand,[...n.get(o.tabCommand)??[],...s])}return[...n].filter(([,o])=>o.length>0).map(([o,s])=>`<TabDisplayRule TabCommand="${ge(o)}">
|
|
118
|
+
${s.join(`
|
|
119
|
+
`)}
|
|
120
|
+
</TabDisplayRule>`).join(`
|
|
121
|
+
`)}function ge(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function _R(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="${ge(o.localizedName)}" OriginalName="${ge(o.localizedName)}">${ge(o.schemaName)}</Name>
|
|
126
|
+
${o.ribbonDiffXml}
|
|
127
|
+
</Entity>`).join(`
|
|
128
|
+
`)}
|
|
129
|
+
</Entities>`}
|
|
130
|
+
${e.applicationRibbonDiffXml??""}
|
|
131
|
+
</ImportExportXml>`}function Gi(e){return/^(Mscrm|Microsoft)\./.test(e)}function is(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 Oy(e,t){return t?"unmanaged":Gi(e)?"oob":"unmanaged"}function Ur(e,t){for(const n of e.tabs)for(const o of n.groups)for(const s of je(o))t.has(s.id)?is(s,{origin:"unmanaged"}):s.origin==="unmanaged"&&is(s,{origin:"managed"})}function dn(e){return e.origin==="unmanaged"}function Va(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob&&!n.custom}function Os(e,t){return Nd(Td(t),[e])}function Td(e){const t=new Map;for(const n of e.tabs)for(const o of n.groups)for(const s of je(o))t.set(s.id,(t.get(s.id)??!0)&&dn(s));return t}function Nd(e,t){return hd(t).every(n=>e.get(n.id)??dn(n))}function as(e,t,n){return t?n?"has"in n?n.has(e):n.includes(e):!1:!0}function Xa(e,t,n){const o=t.tabs.some(s=>s.groups.some(i=>i.id===e.id));return as(e.id,o,n)&&Nd(Td(t),e.buttons)}const Vo="Only tabs and groups your unmanaged customizations add (with a translatable title), or new ones, can be renamed";function rs(e,t,n,o){const s=e==="tab"?n.tabs.find(l=>l.id===t):new Map(n.tabs.flatMap(l=>l.groups.map(r=>[r.id,r]))).get(t);if(!s)return!0;if(!as(t,!0,o?.containerIds))return!1;const i=/^\$LocLabels:(.+)$/.exec(s.label??"")?.[1];return!!i&&as(i,!0,o?.locLabelIds)}function kd(e,t,n){const o=t.tabs.some(s=>s.id===e.id);return as(e.id,o,n)&&e.groups.every(s=>Xa(s,t,n))}function qR(e,t){const n=t.tabs.flatMap(l=>l.groups.flatMap(r=>je(r))).filter(l=>l.id===e.id),o=n.find(l=>!dn(l)),s=o??n[0]??e,i=s.origin==="oob"?"the out-of-the-box ribbon":s.origin==="managed"?s.solutionName?`the managed solution "${s.solutionName}"`:"a managed solution":void 0;return o&&n.some(dn)?`The ribbon also places a button with this id from ${i??"another solution"}, and that one can't be deleted.`:i&&dn(e)?`It is your override of a button from ${i}: the original stays in the ribbon underneath it.`:i?`It comes from ${i}.`:dn(s)?"Its menu holds items from another solution.":"It comes from another solution."}function My(e,t,n=new Set){if(t.size!==0)for(const o of Object.keys(e))for(const s of e[o].tabs)for(const i of s.groups)for(const l of je(i)){const r=t.get(l.id);r&&!n.has(l.id)&&l.origin!=="oob"&&is(l,r)}}function Ms(e,t,n,o=[]){const i=new DOMParser().parseFromString(e,"application/xml"),l=i.querySelector("parsererror");if(l)throw new Error(`Ribbon XML parse error: ${l.textContent??"Unknown"}`);const r=Ey(i),c=Dy(i);zy(i,r);const d=new qy,u=Hy(i,d),m=Gy(i,d),p=Uy(i,d);d.flush();const h=[...Ky(i)];for(const S of o)h.some(C=>C.id===S.id)||h.push(S);const b=new Set,g=new Set;i.querySelectorAll("CustomAction").forEach(S=>{const C=S.querySelector("CommandUIDefinition");if(C?.firstElementChild){const R=C.firstElementChild.getAttribute("Id")??"";R&&b.add(R)}}),i.querySelectorAll("HideCustomAction").forEach(S=>{const C=S.getAttribute("Location")??"";C&&g.add(C)});for(const S of r)for(const C of S.groups)for(const R of je(C)){const M=b.has(R.id);is(R,{origin:Oy(R.id,M)}),R.hidden=g.has(R.id),R.source&&(R.source.labelToken=R.source.attributes.LabelText,R.source.tooltipTitleToken=R.source.attributes.ToolTipTitle,R.source.tooltipBodyToken=R.source.attributes.ToolTipDescription),R.label=Ve(R.label,h),R.tooltipTitle&&(R.tooltipTitle=Ve(R.tooltipTitle,h)),R.tooltipBody&&(R.tooltipBody=Ve(R.tooltipBody,h));for(const I of R.menu?.sections??[])I.title&&(I.title=Ve(I.title,h))}const x=By(i,r),y=Ly(i,r);return{ribbon:{location:t,entityLogicalName:n,tabs:r,...Object.keys(c).length>0?{scalingByTab:c}:{},...Object.keys(x).length?{templateLayouts:x}:{},...Object.keys(y).length?{templateAliases:y}:{}},commands:u,displayRules:p,enableRules:m,locLabels:h}}const Ad="Ribbon > Tabs > Tab, Ribbon > ContextualTabs > ContextualGroup > Tab";function Vr(e){const t=e.getAttribute("Description");return t===null?{}:{description:t}}function Ey(e){const t=[];return e.querySelectorAll(Ad).forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const s=n.getAttribute("Title")??o,i=[];n.querySelectorAll(":scope > Groups > Group").forEach(l=>{const r=l.getAttribute("Id")??"";if(!r)return;const c=l.getAttribute("Title")??l.getAttribute("Label")??r,d=parseInt(l.getAttribute("Sequence")??"0",10),u=l.getAttribute("Template")??"",m=[];l.querySelectorAll(":scope > Controls > *").forEach(p=>{Jc[p.tagName]&&Od(p,m)}),i.push({id:r,label:c,sequence:d,template:u,...Vr(l),buttons:m})}),t.push({id:o,label:s,sequence:parseInt(n.getAttribute("Sequence")??"0",10),commandId:n.getAttribute("Command")??void 0,...Vr(n),tabDisplayRules:[],groups:i})}),t.sort((n,o)=>n.sequence-o.sequence)}function Dy(e){const t={};return e.querySelectorAll(Ad).forEach(n=>{const o=n.getAttribute("Id"),s=Array.from(n.children).find(r=>r.tagName==="Scaling");if(!o||!s||t[o])return;const i=r=>({id:r.getAttribute("Id")??"",groupId:r.getAttribute("GroupId")??"",size:r.getAttribute("Size")??"",sequence:parseInt(r.getAttribute("Sequence")??"0",10),...r.getAttribute("PopupSize")?{popupSize:r.getAttribute("PopupSize")}:{}}),l=Array.from(s.children);t[o]={tabId:o,maxSizes:l.filter(r=>r.tagName==="MaxSize").map(i),scales:l.filter(r=>r.tagName==="Scale").map(i)}}),t}function By(e,t){const n=new Set(t.flatMap(s=>s.groups.map(i=>i.template)).filter(Boolean)),o={};return e.querySelectorAll("GroupTemplate").forEach(s=>{const i=s.getAttribute("Id");!i||!n.has(i)||(o[i]=Array.from(s.querySelectorAll(":scope > Layout")).map(l=>l.getAttribute("Title")??"").filter(Boolean))}),o}function Ly(e,t){const n=new Set(t.flatMap(s=>s.groups.map(i=>i.template)).filter(Boolean)),o={};return e.querySelectorAll("GroupTemplate").forEach(s=>{const i=s.getAttribute("Id");if(!i||!n.has(i))return;const l=new Set;s.querySelectorAll("[TemplateAlias]").forEach(r=>{const c=r.getAttribute("TemplateAlias");c&&l.add(c)}),o[i]=[...l]}),o}function zy(e,t){const n=new Map;for(const o of t)o.commandId&&n.set(o.commandId,o);e.querySelectorAll("RuleDefinitions > TabDisplayRules > TabDisplayRule").forEach(o=>{const s=o.getAttribute("TabCommand")??"",i=n.get(s);if(!i)return;const l=[];for(const c of Array.from(o.children))c.tagName==="EntityRule"?l.push({kind:"EntityRule",entityName:c.getAttribute("EntityName")??void 0,appliesTo:c.getAttribute("AppliesTo")??void 0,context:c.getAttribute("Context")??void 0}):c.tagName==="PageRule"&&l.push({kind:"PageRule",address:c.getAttribute("Address")??""});if(l.length===0)return;const r=i.tabDisplayRules.find(c=>c.tabCommand===s);r?r.rules.push(...l):i.tabDisplayRules.push({tabCommand:s,rules:l})})}function Od(e,t){const n=e.getAttribute("Id")??"";if(!n)return;const o=Jc[e.tagName]??"button",s=ut(o),i=e.getAttribute("LabelText")??n,l=_y(e.getAttribute("ModernImage")??void 0),r=parseInt(e.getAttribute("Sequence")??"0",10),c=e.getAttribute("TemplateAlias")??"",d=e.getAttribute("Command")??"";t.push({id:n,label:i,icon:l,sequence:r,templateAlias:c,commandId:d,kind:o,hidden:!1,oob:!0,custom:!1,managed:!1,tooltipTitle:e.getAttribute("ToolTipTitle")??void 0,tooltipBody:e.getAttribute("ToolTipDescription")??void 0,image16:e.getAttribute("Image16by16")??void 0,image32:e.getAttribute("Image32by32")??void 0,source:{modernImage:e.getAttribute("ModernImage")??void 0,attributes:Ui(e),...s?{xml:Bn().serializeToString(e)}:{}},menu:s?void 0:Fy(e)})}const Py=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]);function Ui(e){return Object.fromEntries(Array.from(e.attributes).map(t=>[t.name,t.value]))}function Fy(e){const t=it(e).find(s=>s.tagName==="Menu");if(!t)return;const n=Ui(t),o=[];for(const s of it(t)){if(s.tagName!=="MenuSection")continue;const i=s.getAttribute("Id")??"",l=it(s).find(u=>u.tagName==="Controls"),r=[],c=[];it(l).forEach((u,m)=>{Py.has(u.tagName)&&u.getAttribute("Id")?Od(u,r):c.push({index:m,xml:Bn().serializeToString(u)})});const d=Ui(s);o.push({id:i,title:s.getAttribute("Title")??void 0,sequence:parseInt(s.getAttribute("Sequence")??"0",10),displayMode:s.getAttribute("DisplayMode")??void 0,controlsId:l?.getAttribute("Id")??`${i}.Controls`,controls:r,attributes:d,...c.length?{rawControls:c}:{},...l?{}:{rawContent:it(s).map(u=>Bn().serializeToString(u)).join("")}})}return{id:t.getAttribute("Id")??`${e.getAttribute("Id")}.Menu`,sections:o,attributes:n}}function _y(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 Bn=()=>new XMLSerializer;function it(e){return e?Array.from(e.childNodes).filter(t=>t.nodeType===Node.ELEMENT_NODE):[]}class qy{pending=[];add(t){this.pending.push(t)}flush(){for(const t of[0,1]){const n=this.pending.filter(i=>i.phase===t);if(n.length===0)continue;const o=n.map(i=>i.generate());let s=null;try{const i=Yc(`<v>${o.map(l=>`<i>${l}</i>`).join("")}</v>`);s=it(i).map(l=>it(l)[0])}catch{s=null}n.forEach((i,l)=>{(s?s[l]&&En(s[l])===En(i.source):Mb(o[l],i.source))||i.fallback()})}this.pending=[]}}function Hy(e,t){const n=[];return e.querySelectorAll("CommandDefinition").forEach(o=>{const s=o.getAttribute("Id")??"";if(!s)return;const i=it(o),l=p=>i.find(h=>h.tagName===p),r=[],c=(p,h)=>{const b=[];return it(l(p)).forEach((g,x)=>{const y=g.getAttribute("Id");g.tagName===h&&y&&g.attributes.length===1&&it(g).length===0?b.push(y):r.push({container:p,index:x,xml:Bn().serializeToString(g)})}),b},d=c("EnableRules","EnableRule"),u=c("DisplayRules","DisplayRule"),m=[];it(l("Actions")).forEach((p,h)=>{const b=Wy(p);if(!b){m.push(Xr(p));return}m.push(b),t.add({source:p,generate:()=>$d(b),fallback:()=>m[h]=Xr(p),phase:0})}),n.push({id:s,enableRules:d,displayRules:u,actions:m,...r.length>0?{rawRuleRefs:r}:{}})}),n}function Xr(e){return{kind:"raw",tagName:e.tagName,xml:Bn().serializeToString(e)}}function Wy(e){switch(e.tagName){case"JavaScriptFunction":{const t=Vi(e);return t?{kind:"javascript",library:e.getAttribute("Library")??"",functionName:e.getAttribute("FunctionName")??"",params:t}:null}case"Url":{const t=Vi(e);if(!t)return null;const n=e.getAttribute("WinMode");return{kind:"url",address:e.getAttribute("Address")??"",passParams:At(e.getAttribute("PassParams")),winMode:n===null?void 0:Number(n),winParams:e.getAttribute("WinParams")??void 0,params:t}}case"OutlookCommand":return{kind:"outlookCommand",actionType:e.getAttribute("ActionType")??"",data:e.getAttribute("Data")??void 0};default:return null}}function At(e){if(e===null)return;const t=e.trim();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}function Vi(e){const t=[];for(const n of it(e)){const o=n.getAttribute("Name")??void 0,s=n.getAttribute("Value")??"";switch(n.tagName){case"CrmParameter":t.push({kind:"CrmParameter",name:o,value:s});break;case"BoolParameter":t.push({kind:"BoolParameter",name:o,value:At(s)??!1});break;case"IntParameter":t.push({kind:"IntParameter",name:o,value:parseInt(s,10)});break;case"DecimalParameter":t.push({kind:"DecimalParameter",name:o,value:parseFloat(s)});break;case"StringParameter":t.push({kind:"StringParameter",name:o,value:s});break;default:return null}}return t}function Gy(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > EnableRules > EnableRule").forEach(o=>{const s=o.getAttribute("Id")??"";s&&n.push({id:s,steps:Ka(o,t)})}),n}function Uy(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > DisplayRules > DisplayRule").forEach(o=>{const s=o.getAttribute("Id")??"";s&&n.push({id:s,steps:Ka(o,t)})}),n}function Ka(e,t){const n=[];return it(e).forEach((o,s)=>{const i=Xy(o,t);if(!i){n.push(Kr(o));return}n.push(i),t.add({source:o,generate:()=>As(n[s]),fallback:()=>n[s]=Kr(o),phase:i.kind==="OrRule"?1:0})}),n}function Kr(e){return{kind:"RawRule",tagName:e.tagName,xml:Bn().serializeToString(e)}}function Vy(e){const t={},n=At(e.getAttribute("Default")),o=At(e.getAttribute("InvertResult"));return n!==void 0&&(t.default=n),o!==void 0&&(t.invertResult=o),t}function Kn(e,t){const n=e.getAttribute(t);return n===null?void 0:parseInt(n,10)}function mt(e,t){return e.getAttribute(t)??void 0}function Re(e,t){return e.getAttribute(t)??""}function Xy(e,t){const n=Vy(e);switch(e.tagName){case"OrRule":{const o=it(e);return o.some(s=>s.tagName!=="Or")?null:{kind:"OrRule",groups:o.map(s=>Ka(s,t))}}case"SelectionCountRule":return{kind:"SelectionCountRule",minimum:Kn(e,"Minimum"),maximum:Kn(e,"Maximum"),appliesTo:mt(e,"AppliesTo"),...n};case"EntityRule":return{kind:"EntityRule",entityName:mt(e,"EntityName"),context:mt(e,"Context"),appliesTo:mt(e,"AppliesTo"),...n};case"FormStateRule":return{kind:"FormStateRule",state:Re(e,"State"),...n};case"CommandClientTypeRule":return{kind:"CommandClientTypeRule",type:Re(e,"Type"),...n};case"CustomRule":{const o=Vi(e);return o?{kind:"CustomRule",library:Re(e,"Library"),functionName:Re(e,"FunctionName"),...o.length>0?{params:o}:{},...n}:null}case"FeatureControlRule":{const o=At(e.getAttribute("ExpectedValue"));return o===void 0?null:{kind:"FeatureControlRule",featureControlBit:Re(e,"FeatureControlBit"),expectedValue:o,...n}}case"MiscellaneousPrivilegeRule":return{kind:"MiscellaneousPrivilegeRule",privilegeName:Re(e,"PrivilegeName"),privilegeDepth:mt(e,"PrivilegeDepth"),...n};case"CrmClientTypeRule":return{kind:"CrmClientTypeRule",type:Re(e,"Type"),...n};case"FormTypeRule":return{kind:"FormTypeRule",type:Re(e,"Type"),...n};case"ValueRule":return{kind:"ValueRule",field:Re(e,"Field"),value:Re(e,"Value"),...n};case"SkuRule":return{kind:"SkuRule",sku:Re(e,"Sku"),...n};case"HideForTabletExperienceRule":return{kind:"HideForTabletExperienceRule",...n};case"OrganizationSettingRule":return{kind:"OrganizationSettingRule",setting:Re(e,"Setting"),...n};case"EntityPrivilegeRule":return{kind:"EntityPrivilegeRule",entityName:mt(e,"EntityName"),appliesTo:mt(e,"AppliesTo"),privilegeType:Re(e,"PrivilegeType"),privilegeDepth:Re(e,"PrivilegeDepth"),...n};case"EntityPropertyRule":{const o=At(e.getAttribute("PropertyValue"));return o===void 0?null:{kind:"EntityPropertyRule",entityName:mt(e,"EntityName"),appliesTo:mt(e,"AppliesTo"),propertyName:Re(e,"PropertyName"),propertyValue:o,...n}}case"DeviceTypeRule":return{kind:"DeviceTypeRule",type:Re(e,"Type"),...n};case"OptionSetRule":return{kind:"OptionSetRule",optionSet:Re(e,"OptionSet"),stateCode:Re(e,"StateCode"),objectTypeCode:Re(e,"ObjectTypeCode"),...n};case"RecordPrivilegeRule":return{kind:"RecordPrivilegeRule",privilegeType:Re(e,"PrivilegeType"),appliesTo:mt(e,"AppliesTo"),...n};case"FormEntityContextRule":return{kind:"FormEntityContextRule",entityName:Re(e,"EntityName"),...n};case"PageRule":return{kind:"PageRule",address:Re(e,"Address"),...n};case"RelationshipTypeRule":return{kind:"RelationshipTypeRule",appliesTo:"SelectedEntity",relationshipType:mt(e,"RelationshipType"),allowCustomRelationship:At(e.getAttribute("AllowCustomRelationship")),allowSystemRelationship:At(e.getAttribute("AllowSystemRelationship")),...n};case"ReferencingAttributeRequiredRule":return{kind:"ReferencingAttributeRequiredRule",...n};case"OutlookItemTrackingRule":{const o=At(e.getAttribute("TrackedInCrm"));return o===void 0?null:{kind:"OutlookItemTrackingRule",trackedInCrm:o,appliesTo:mt(e,"AppliesTo"),...n}}case"OutlookRenderTypeRule":return{kind:"OutlookRenderTypeRule",type:Re(e,"Type"),...n};case"OutlookVersionRule":return{kind:"OutlookVersionRule",version:Re(e,"Version"),...n};case"CrmOfflineAccessStateRule":return{kind:"CrmOfflineAccessStateRule",state:Re(e,"State"),...n};case"CrmOutlookClientTypeRule":return{kind:"CrmOutlookClientTypeRule",type:Re(e,"Type"),...n};case"CrmOutlookClientVersionRule":return{kind:"CrmOutlookClientVersionRule",major:parseInt(Re(e,"Major"),10),minor:Kn(e,"Minor"),build:Kn(e,"Build"),revision:Kn(e,"Revision"),...n};default:return null}}function Ky(e){const t=[];return e.querySelectorAll("LocLabel").forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const s=[];n.querySelectorAll("Title").forEach(i=>{const l=parseInt(i.getAttribute("languagecode")??"1033",10),r=i.getAttribute("description")??"";s.push({languageCode:l,description:r})}),t.push({id:o,titles:s})}),t}function ls(e){return{controlIds:[...ns(e)],containerIds:[...dd(e)],locLabelIds:[...e.locLabels.keys()],hides:Cs(e),scalingStepIds:Fa(e).map(t=>t.id),commandIds:[...e.commandDefinitions.keys()],commandRefIds:[...ud(e)]}}async function HR(e){try{return ls(await Xi(e))}catch{return null}}function Yy(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=Ms(t,"HomepageGrid","");return{commands:n.commands,enableRules:n.enableRules,displayRules:n.displayRules}}function Jy(){return window.dataverseAPI}async function Nn(e){const t=[];let n=e;for(;n;){const o=await Jy().queryData(n);t.push(...o.value??[]);const s=o["@odata.nextLink"];n=s?s.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}async function Xi(e){const t=e===null?"entity eq null and ismanaged eq false":`entity eq '${e.replace(/'/g,"''")}' and ismanaged eq false`,[n,o,s]=await Promise.all([Nn(`ribbondiffs?$select=diffid,difftype,rdx,sequence&$filter=${t}&$orderby=sequence asc,diffid asc`),Nn(`ribboncommands?$select=command,commanddefinition&$filter=${t}&$orderby=command asc`),Nn(`ribbonrules?$select=ruleid,ruletype,ruledefinition&$filter=${t}&$orderby=ruleid asc`)]);return Lb({diffs:n,commands:o,rules:s})}function Ki(e){const t=[];for(const[n,o]of e.locLabels){const s=new DOMParser().parseFromString(o,"application/xml"),i=Array.from(s.querySelectorAll("Title")).map(l=>({languageCode:Number(l.getAttribute("languagecode")??1033),description:l.getAttribute("description")??""}));t.push({id:n,titles:i})}return t}function Yr(e,t,n,o){const i=`${Ja()}.${kn(e)}.${kn(t)}.${kn(n)}`;return Za(i,o)}function Ya(e,t,n){const s=`${Ja()}.${kn(e)}.${kn(t)}.Command`;return Za(s,n)}function yo(e,t,n){const s=`${Ja()}.${kn(e)}.${t}Rule`;return Za(s,n)}function Jr(e){return e.replace(/\.Command$/,"").split(".").pop()||"Rule"}function Ja(){try{return ae.getState().publisherPrefix||"new"}catch{return"new"}}function kn(e){return e.replace(/[^a-zA-Z0-9._]/g,"").replace(/^[^a-zA-Z]/,"x")}function Za(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n++;return`${e}${n}`}function Md(e,t,n,o,s){const i=o.replace(/[^a-zA-Z0-9_]/g,"")||"Button",l=`${e}.${t}.${n}.${i}`;let r=l;for(let c=2;s.has(`${r}.Button`)||s.has(`${r}.Command`);c++)r=`${l}${c}`;return{id:`${r}.Button`,commandId:`${r}.Command`}}function WR(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"}function Es(e,t){return Yi(Xt(e,""),Xt(t,""))}const on=Symbol("omitted");function Xt(e,t){switch(e!==null&&typeof e=="object"&&typeof e.toJSON=="function"&&(e=e.toJSON(String(t))),typeof e){case"number":return Number.isFinite(e)?e:null;case"undefined":case"function":case"symbol":return on;case"object":return e instanceof Number||e instanceof String||e instanceof Boolean?Xt(e.valueOf(),t):e;default:return e}}const Zr=(e,t)=>Object.prototype.propertyIsEnumerable.call(e,t);function Yi(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return!1;const n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){const i=e,l=t;if(i.length!==l.length)return!1;for(let r=0;r<i.length;r++){const c=Xt(i[r],r),d=Xt(l[r],r);if(!Yi(c===on?null:c,d===on?null:d))return!1}return!0}const o=e,s=t;for(const i of Object.keys(o)){const l=Xt(o[i],i),r=Zr(s,i)?Xt(s[i],i):on;if(l===on||r===on){if(l!==r)return!1}else if(!Yi(l,r))return!1}for(const i of Object.keys(s))if(!Zr(o,i)&&Xt(s[i],i)!==on)return!1;return!0}const Z=en()(e=>({location:"HomepageGrid",tabId:"MainTab",selectedButtonId:null,selectedGroupId:null,setLocation(t){e({location:t,tabId:"MainTab",selectedButtonId:null,selectedGroupId:null})},setTabId(t){e({tabId:t,selectedButtonId:null,selectedGroupId:null})},selectGroup(t){e({selectedGroupId:t,selectedButtonId:null})},selectButton(t,n){e({selectedGroupId:t,selectedButtonId:n})},selectButtonInContext(t,n,o,s){e({location:t,tabId:n,selectedGroupId:o,selectedButtonId:s})},clearSelection(){e({selectedButtonId:null,selectedGroupId:null})}})),Ji="Mscrm.GlobalTab",Ed="Mscrm.GlobalTab.New",Qr="the global command bar shows your buttons only in its New group (Mscrm.GlobalTab.New), in Unified Interface";function Dd(e,t){return e==="Application"&&t===Ji}function Zt(e,t){return Dd(e,t)?"The global command bar shows your buttons only in its New group: add them there.":void 0}function We(e,t,n){return Dd(e,t)&&n!==Ed?"The global command bar shows your buttons only in its New group: add them there.":void 0}function Io(e){return/\.AllEntities\./.test(e)||/\.VisualizationTab$/.test(e)}function xo(e){const t=e.filter(n=>!Io(n.id));return(t.find(n=>/\.MainTab$/.test(n.id))??t[0]??e[0])?.id}const Ye="Mscrm.OpenRecordItem",Bd=["HomepageGrid","SubGrid"],Zy=/\.(HomepageGrid|SubGrid)\.OpenRecordItem\d*\.Button$/;function Ld(e){return e.commandId===Ye&&Zy.test(e.id)}function Qa(e){const t=[];for(const n of e?.tabs??[])for(const o of n.groups)for(const s of je(o))s.commandId===Ye&&t.push({tabId:n.id,groupId:o.id,button:s});return t}function zd(e){return Qa(e).filter(t=>Ld(t.button))}function Pd(e){const t=e.button.origin;return t==="unmanaged"?"yours":t===void 0?"unknown":"theirs"}function Fd(e){const t=e?.tabs??[],n=xo(t.filter(i=>i.groups.length>0)),o=t.find(i=>i.id===n),s=o?.groups.find(i=>/\.Management$/.test(i.id))??o?.groups[0];return o&&s?{tabId:o.id,groupId:s.id}:null}function Qy(){return{id:Ye,enableRules:[],displayRules:[],actions:[{kind:"javascript",library:"$webresource:",functionName:"YourNamespace.openRecord",params:[{kind:"CrmParameter",value:"SelectedControlSelectedItemReferences"}]}]}}function ex(e){for(const t of e.actions){if(t.kind!=="javascript")continue;if(!t.library.trim().replace(/^\$webresource:/i,"").trim()||!t.functionName.trim())return`${Ye} has a JavaScript action without a web resource or function — set them in the Command Editor, or turn the override off`}return null}const tx=["Mscrm.HideOnModern","Mscrm.ShowOnlyOnModern"];function Yn(e,t){const n=new Set;for(const o of[t,e.baseline])for(const s of Object.values(o??{}))for(const i of s.tabs){n.add(i.id);for(const l of i.groups){n.add(l.id);for(const r of je(l))n.add(r.id)}}for(const o of Object.values(e.layers??{})){for(const s of o?.containerIds??[])n.add(s);for(const s of o?.controlIds??[])n.add(s)}return n}function An(e,t){return Ln(e,t)?.containerIds}function Ln(e,t){return e.layers[t==="Application"?"application":"entity"]}function xn(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 Ae(e,t,n,o,s="info"){return{ts:new Date().toISOString(),userId:"",userName:"You",op:e,target:t,detail:n,icon:o,color:s}}let lt=null;const nx=1e3;let cs=null,ox=0;function _d(e,t,n,o){const s=cs??o,i=e.past[e.past.length-1];return s&&i?.coalesceKey===s&&e.future.length===0&&(cs!==null||Date.parse(t.ts)-Date.parse(i.ts)<nx)?{past:[...e.past.slice(0,-1),{...i,...t}],future:[],mutationsSincePublish:e.mutationsSincePublish+1}:{past:[...e.past,{...t,coalesceKey:s,snapshot:n()}].slice(-80),future:[],mutationsSincePublish:e.mutationsSincePublish+1}}function _e(e,t,n,o){return lt?(lt.meta||(lt.meta=n),t):{...t,..._d(e,n,()=>Ct(e),o)}}function qd(e){const t={...e},n=new Set;return{draft:new Proxy(t,{get(s,i,l){if(!n.has(i)&&Object.prototype.hasOwnProperty.call(s,i)){n.add(i);const r=i;s[r]=JSON.parse(JSON.stringify(s[r]))}return Reflect.get(s,i,l)},set(s,i,l,r){return n.add(i),Reflect.set(s,i,l,r)}}),next:t}}function Ne(e,t,n,o){const{draft:s,next:i}=qd(e.ribbons);return t(s),_e(e,{ribbons:i},n,o)}function mo(e){const t=Es;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 Jn(e,t){const n=e.findIndex(o=>o.id===t.id);return n<0?[...e,t]:Es(e[n],t)?null:e.map((o,s)=>s===n?t:o)}const el={entity:null,application:null},ei={entity:[],application:[]},tl=["HomepageGrid","SubGrid","Form"];function Hd(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 nl(e,t){for(let n=1;n<e.length;n++)e[n].sequence>e[n-1].sequence||(t(e[n])?ds(e,n,t):t(e[n-1])&&ds(e,n-1,t));for(const n of e.filter(t)){const o=e.indexOf(n);if((e[o-1]?.sequence??-1/0)<n.sequence&&n.sequence<(e[o+1]?.sequence??1/0))continue;e.splice(o,1);const i=e.findIndex(l=>l.sequence>n.sequence);e.splice(i<0?e.length:i,0,n)}}function ft(e){return[...e].sort((t,n)=>t.sequence-n.sequence)}function Wd(e,t){const n=new Set(e.baseline[t]?.tabs.flatMap(s=>s.groups.map(i=>i.id))??[]),o=new Set(An(e,t)??[]);return s=>!n.has(s.id)||o.has(s.id)}function Gd(e,t,n,o,s){const i=ft(e.ribbons[t].tabs.find(d=>d.id===n)?.groups??[]),l=i.findIndex(d=>d.id===o),r=i[l+s];if(l<0||!r)return!1;const c=Wd(e,t);return c(i[l])||c(r)}function ds(e,t,n){let o=t;for(;o>0&&n(e[o-1]);)o--;let s=t;for(;s<e.length-1&&n(e[s+1]);)s++;const i=o>0?e[o-1].sequence:0,l=s<e.length-1?e[s+1].sequence:1/0;if(l-i-1>=s-o+1){let d=i;for(let u=o;u<=s;u++){const m=s-u,p=e[u];p.sequence>d&&p.sequence<=l-1-m||(p.sequence=l===1/0?d+10:d+Math.max(1,Math.min(10,Math.floor((l-d)/(m+2))))),d=p.sequence}return}const r=new Set(e.filter((d,u)=>u!==t).map(d=>d.sequence));let c=(t>0?e[t-1].sequence:0)+1;for(;r.has(c);)c++;e[t].sequence=c}function ol(e,t,n){const o=e[t],s=Hd(o.sequence,e[t-1]?.sequence,e[t+1]?.sequence);if(s!==void 0){o.sequence=s;return}if(ds(e,t,n),!((e[t-1]?.sequence??-1/0)<o.sequence&&o.sequence<(e[t+1]?.sequence??1/0))){e.splice(t,1);const l=e.findIndex(r=>r.sequence>o.sequence);e.splice(l<0?e.length:l,0,o)}}function ti(){const{activeSolution:e,publisherPrefix:t}=ae.getState();return e?.publisherPrefix?.trim()||t?.trim()||"new"}function ni(e,t){const n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(`${o}.`)||n.startsWith(`${o}_`)?e:`${t}.${e}`}const oi={HomepageGrid:{location:"HomepageGrid",entityLogicalName:"",tabs:[]},SubGrid:{location:"SubGrid",entityLogicalName:"",tabs:[]},Form:{location:"Form",entityLogicalName:"",tabs:[]},Application:{location:"Application",entityLogicalName:"",tabs:[]}};function gt(e,t,n,o,s){const i=e[t].tabs.find(r=>r.id===n)?.groups.find(r=>r.id===o),l=Ns(i,s);return i&&l?{group:i,button:l}:void 0}function Ud(e,t,n){return(e.baseline[t]?.tabs??[]).some(o=>o.groups.some(s=>je(s).some(i=>i.id===n)))}function Pt(e,t){return t?(re.getState().logWarn("ribbon",`Can't ${e}: ${t}`),!0):!1}function rt(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob===!0&&n.custom!==!0}function er(e,t,n){return n.origin!=="unmanaged"&&!n.hidden&&n.kind!=="flyout"&&n.kind!=="splitButton"&&!ut(n.kind)&&!rt(e,t,n)}function sx(e,t,n){for(const o of e.baseline[t].tabs)for(const s of o.groups){const i=s.buttons.find(l=>l.id===n);if(i)return i}}function ix(e,t,n){if(t.location!==n.location||t.tabId!==n.tabId||t.groupId!==n.groupId)return!1;const o=ft(e.buttons),s=o.findIndex(l=>l.id===t.buttonId),i=o[s+1]?.id;return n.beforeButtonId?n.beforeButtonId===t.buttonId||n.beforeButtonId===i:i===void 0}const us=/^\$LocLabels:/,po=e=>e.labelsUnknown?void 0:new Set(e.locLabels.map(t=>t.id));function ax(e,t){if(!e)return;const n=s=>s&&(!us.test(s)||co(s,t))?s:void 0,o={};for(const[s,i]of Object.entries(e.attributes))s!=="Id"&&!us.test(i)&&(o[s]=i);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 sl(e,t){const n=e.baselineCommands.find(s=>s.id===t),o=e.commands.find(s=>s.id===t);return!n||!o||Es(n,o)?e.commands:e.commands.map(s=>s.id===t?n:s)}const D=en()(Cb((e,t)=>({ribbons:xn(oi),baseline:xn(oi),baselineCommands:[],baselineEnableRules:[],baselineDisplayRules:[],baselineLocLabels:[],layers:{...el},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){const o=xn(n);e({ribbons:o,baseline:{...o},mutationsSincePublish:0,past:[],future:[]}),lt&&(lt={snapshot:Ct(t()),meta:null})},setConflicts(n){e({conflicts:n})},applyImport(n,o){e(s=>_e(s,{ribbons:{...s.ribbons,...xn(n.ribbons)},commands:[...n.commands],enableRules:[...n.enableRules],displayRules:[...n.displayRules],locLabels:[...n.locLabels]},Ae("imported","RibbonDiffXml",o,"arrow_upload","success")))},loadWorkspace(n){const o=xn(n.ribbons),s=JSON.parse(JSON.stringify(n.commands)),i=JSON.parse(JSON.stringify(n.displayRules)),l=JSON.parse(JSON.stringify(n.enableRules)),r=JSON.parse(JSON.stringify(n.locLabels));e({ribbons:o,baseline:{...o},commands:s,displayRules:i,enableRules:l,baselineCommands:[...s],baselineDisplayRules:[...i],baselineEnableRules:[...l],locLabels:r,baselineLocLabels:[...r],layers:{...el,...n.layers??{}},pendingUnhides:{...ei},orphans:{entity:[],application:[],...n.orphans??{}},pendingOrphanDeletes:{...ei},baseLanguageCode:n.baseLanguageCode??1033,baseLanguageUnknown:n.baseLanguageUnknown??!1,labelsUnknown:n.labelsUnknown??!1,customisedCommandIds:[],uncustomisedCommandIds:{entity:[],application:[]},reloadRequiredCommandIds:[],templates:[...n.templates??[]],conflicts:[...n.conflicts??[]],mutationsSincePublish:0,past:[],future:[]}),lt&&(lt={snapshot:Ct(t()),meta:null})},restoreWorkspace(n,o){const s=JSON.parse(JSON.stringify(n));e(i=>{const l=c=>{const d=i.layers[c];return d?s.pendingUnhides[c].filter(u=>d.hides.some(m=>m.location===u)):s.pendingUnhides[c]},r={...s,pendingUnhides:{entity:l("entity"),application:l("application")}};return Es(Ct({...i,...r}),Ct(i))?i:_e(i,r,Ae("restored","unsaved changes",o,"history"))})},resetWorkspace(){t().loadWorkspace({ribbons:oi,commands:[],displayRules:[],enableRules:[],locLabels:[]})},undo(){t().restore(t().past.length-1)},redo(){const n=t();if(n.future.length===0||lt)return;const[o,...s]=n.future;e({...o.snapshot,past:[...n.past,{...o,snapshot:Ct(n)}],future:s,mutationsSincePublish:mo({...n,...o.snapshot})?n.mutationsSincePublish+1:0})},restore(n){const o=t(),{past:s}=o;if(n<0||n>=s.length||lt)return;let i=Ct(o),l=o.future;for(let c=s.length-1;c>=n;c--)l=[{...s[c],coalesceKey:void 0,snapshot:i},...l],i=s[c].snapshot;const r=s.length-n;e({...i,past:s.slice(0,n),future:l,mutationsSincePublish:mo({...o,...i})?Math.max(1,o.mutationsSincePublish-r):0})},batch(n){if(lt){n();return}lt={snapshot:Ct(t()),meta:null};try{n()}finally{const{snapshot:o,meta:s}=lt;lt=null,s&&e(i=>_d(i,s,()=>o))}},beginEditSession(){cs=`session:${++ox}`},endEditSession(){cs=null},moveButton(n,o){const s=t(),l=s.ribbons[n.location].tabs.find(m=>m.id===n.tabId)?.groups.find(m=>m.id===n.groupId),r=l?.buttons.find(m=>m.id===n.buttonId),c=s.ribbons[o.location].tabs.find(m=>m.id===o.tabId)?.groups.find(m=>m.id===o.groupId);if(!r||!l||!c||(n.location!==o.location||n.tabId!==o.tabId||n.groupId!==o.groupId)&&Pt(`move ${r.id} to ${o.groupId}`,We(o.location,o.tabId,o.groupId)))return null;const d=sx(s,n.location,r.id)?.origin;if(d!==void 0&&d!=="unmanaged"&&!r.menu&&!Tn(r.kind)&&!rt(n.location,n.tabId,r)){if(ix(l,n,o))return null;const m=g=>(re.getState().logWarn("ribbon",`Can't move ${r.id}: ${g}`),null);if(r.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 entity's ribbon and the application ribbon.");const p=ti();let h=null,b=!1;return t().batch(()=>{const g=t().customiseButton(n.location,n.tabId,n.groupId,n.buttonId,p);g&&(b=!0,h=t().moveButton({...n,buttonId:g},o),re.getState().logInfo("ribbon",`${r.id} isn't yours, so it can't be moved: moved your copy ${g} instead and hid the original.`))}),b&&!h&&t().undo(),b?h: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 rt(n.location,n.tabId,r)?null:(e(m=>Ne(m,p=>{const h=p[n.location].tabs.find(I=>I.id===n.tabId);if(!h)return;const b=h.groups.find(I=>I.id===n.groupId);if(!b)return;const g=b.buttons.findIndex(I=>I.id===n.buttonId);if(g===-1||rt(n.location,n.tabId,b.buttons[g]))return;const y=(n.tabId===o.tabId&&n.location===o.location?h:p[o.location].tabs.find(I=>I.id===o.tabId))?.groups.find(I=>I.id===o.groupId);if(!y)return;const[S]=b.buttons.splice(g,1);y.buttons.sort((I,$)=>I.sequence-$.sequence);const C=o.beforeButtonId?y.buttons.findIndex(I=>I.id===o.beforeButtonId):y.buttons.length,R=C<0?y.buttons.length:C;y.buttons.splice(R,0,S);const M=Hd(S.sequence,y.buttons[R-1]?.sequence,y.buttons[R+1]?.sequence);if(M!==void 0)S.sequence=M;else{const I=new Set(m.layers[o.location==="Application"?"application":"entity"]?.controlIds??[]),$=new Set(m.baseline[o.location].tabs.flatMap(T=>T.groups.flatMap(v=>v.buttons.map(O=>O.id))));ds(y.buttons,R,T=>T===S||I.has(T.id)||!$.has(T.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"moved",target:n.buttonId,detail:`to ${o.groupId}`,icon:"arrow_move",color:"info"})),n.buttonId)},setButtonProp(n,o,s,i,l){const c=Object.values(l).every(d=>typeof d=="string")?`button:${n}:${i}:${Object.keys(l).sort().join(",")}`:void 0;e(d=>{const u=m=>{const p=gt(m,n,o,s,i);return!p||l.kind===void 0||l.kind===p.button.kind||!Ud(d,n,i)&&(p.group.buttons.includes(p.button)||_a.includes(l.kind))};return Object.keys(l).length===1&&!u(d.ribbons)?{}:Ne(d,m=>{const p=gt(m,n,o,s,i)?.button;if(!p||rt(n,o,p))return;const h=p.kind,b=u(m);Object.assign(p,l),b||(p.kind=h),Tn(p.kind)&&!p.menu&&(p.menu=Ys(p.id))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l.label??i,detail:Object.keys(l).join(", "),icon:"edit",color:"info"},c)})},deleteButton(n,o,s,i){const l=t(),r=gt(l.ribbons,n,o,s,i)?.button;if(r&&!Os(r,l.baseline[n])){re.getState().logWarn("ribbon",`"${r.label}" (${i}) was not deleted: only your own buttons can be deleted — hide it instead.`);return}e(c=>Ne(c,d=>{const u=gt(d,n,o,s,i);if(!u)return;const{group:m,button:p}=u;rt(n,o,p)||bd(m,i)||(m.buttons=m.buttons.filter(h=>h.id!==i))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:i,detail:s,icon:"delete",color:"danger"}))},addMenuItem({location:n,tabId:o,groupId:s,parentId:i,sectionId:l,item:r}){Pt(`add a menu item to ${i}`,We(n,o,s))||e(c=>Ne(c,d=>{const u=gt(d,n,o,s,i)?.button;if(!u||rt(n,o,u))return;u.menu=u.menu??Ys(u.id),u.menu.sections.length===0&&u.menu.sections.push(Fi(u.id,[]));const m=u.menu.sections.find(h=>h.id===l)??u.menu.sections[0],p=m.controls[m.controls.length-1]?.sequence??0;m.controls.push({...r,kind:r.kind??"button",sequence:r.sequence??p+10,templateAlias:r.templateAlias??"",hidden:!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:r.label,detail:`menu of ${i}`,icon:"add",color:"success"}))},addMenuSection(n,o,s,i,l){Pt(`add a menu section to ${i}`,We(n,o,s))||e(r=>Ne(r,c=>{const d=gt(c,n,o,s,i)?.button;!d||rt(n,o,d)||(d.menu=d.menu??{id:`${d.id}.Menu`,sections:[]},d.menu.sections.push(Fi(d.id,d.menu.sections,l)))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:l??"Menu section",detail:`menu of ${i}`,icon:"add",color:"success"}))},setMenuSectionProp(n,o,s,i,l,r){e(c=>Ne(c,d=>{const u=gt(d,n,o,s,i)?.button,m=u?.menu?.sections.find(p=>p.id===l);!u||!m||rt(n,o,u)||Object.assign(m,r)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l,detail:Object.keys(r).join(", "),icon:"edit",color:"info"}))},deleteMenuSection(n,o,s,i,l){e(r=>Ne(r,c=>{const d=gt(c,n,o,s,i)?.button;!d?.menu||rt(n,o,d)||(d.menu.sections=d.menu.sections.filter(u=>u.id!==l))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:l,detail:`menu of ${i}`,icon:"delete",color:"danger"}))},duplicateButton(n,o,s,i){Pt(`duplicate ${i} in ${s}`,We(n,o,s))||e(l=>Ne(l,r=>{const c=gt(r,n,o,s,i);if(c){const{group:d,button:u}=c;if(rt(n,o,u))return;const m=po(l),p=lo(u.source?.labelToken)||co(u.source?.labelToken,m),h={...ss(u,`${ni(u.id,ti())}_copy_${Date.now()}`,m),label:ut(u.kind)||p?u.label:`${u.label} (copy)`,sequence:u.sequence},b=os(d,i),g=b?b.section.controls:d.buttons,x=g.findIndex(C=>C.id===i);g.splice(x+1,0,h);const y=new Set(Ln(l,n)?.controlIds??[]),S=new Set((l.baseline[n]?.tabs??[]).flatMap(C=>C.groups.flatMap(je)).map(C=>C.id));ol(g,x+1,C=>C===h||y.has(C.id)||!S.has(C.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:i,detail:s,icon:"copy",color:"info"}))},createButton({tabId:n,groupId:o,location:s,button:i}){Pt(`add "${i.label??"New Button"}" to ${o}`,We(s,n,o))||e(l=>Ne(l,r=>{const d=r[s].tabs.find(u=>u.id===n)?.groups.find(u=>u.id===o);if(d){const u=new Set(d.buttons.map(b=>b.sequence)),m=Math.max(0,...d.buttons.map(b=>b.sequence))+10,p=i.sequence!==void 0&&!u.has(i.sequence)?i.sequence:m,h={...i,id:i.id??`new_${Date.now()}`,label:i.label??"New Button",kind:i.kind??"button",sequence:p,templateAlias:i.templateAlias??"o1",commandId:i.commandId??"",hidden:i.hidden??!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"};Tn(h.kind)&&!h.menu&&(h.menu=Ys(h.id)),d.buttons.push(h)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:i.label??"New Button",detail:o,icon:"add",color:"success"}))},createGroup({tabId:n,location:o,group:s}){Pt(`add the group "${s.label??"New Group"}" to ${n}`,Zt(o,n))||e(i=>Ne(i,l=>{const r=l[o].tabs.find(c=>c.id===n);if(r){const c=l[o],d=o==="Application"?"global":c.entityLogicalName,u={id:s.id??Yr(d,`${o}.${s.label??"New Group"}`,"Group",Yn(i,l)),label:s.label??"New Group",sequence:s.sequence!==void 0&&!r.groups.some(m=>m.sequence===s.sequence)?s.sequence:Math.max(0,...r.groups.map(m=>m.sequence))+10,template:s.template??"Flexible2",buttons:s.buttons??[]};r.groups.push(u)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:s.label??"New Group",detail:n,icon:"add",color:"success"}))},renameGroup(n,o,s,i){e(l=>Ne(l,r=>{const d=r[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===s);d&&(d.label=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:s,detail:i,icon:"edit",color:"info"}))},duplicateGroup(n,o,s){if(Pt(`duplicate ${s}`,Zt(n,o)))return;let i=null;if(e(l=>Ne(l,r=>{const c=r[n].tabs.find(R=>R.id===o);if(!c)return;const d=c.groups.find(R=>R.id===s);if(!d)return;const u=`_copy_${Date.now()}`,m=ti(),p=po(l),h=l.baseLanguageCode,b=d.source?.titleToken,g=b!==void 0&&Ve(b,l.locLabels,h)===d.label?b:d.label,x=lo(g)||co(g,p),y={...JSON.parse(JSON.stringify(d)),id:`${ni(d.id,m)}${u}`,label:x?Ve(g,l.locLabels,h):`${Ve(d.label,l.locLabels,h)} (copy)`,source:x?{titleToken:g,attributes:{}}:void 0,description:void 0,sequence:d.sequence,buttons:d.buttons.map(R=>ss(R,`${ni(R.id,m)}${u}`,p))},S=c.groups.findIndex(R=>R.id===s);c.groups.splice(S+1,0,y);const C=new Set((l.baseline[n]?.tabs??[]).flatMap(R=>R.groups.map(M=>M.id)));ol(c.groups,S+1,R=>R===y||!C.has(R.id)),x&&(i={copyId:y.id,title:g})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:s,detail:o,icon:"copy",color:"info"})),i){const{copyId:l,title:r}=i;re.getState().logInfo("ribbon",`Duplicate group ${s}: the copy ${l} keeps its title ${r}, which comes from ${lo(r)?"the platform":"another solution"} and can't take " (copy)". Rename the copy before you publish if it should read differently: once published, only titles of your own can be renamed.`)}},setGroupTemplate(n,o,s,i){e(l=>Ne(l,r=>{const d=r[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===s);d&&(d.template=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:s,detail:`template → ${i}`,icon:"edit",color:"info"}))},deleteGroup(n,o,s){const i=t(),l=i.ribbons[n].tabs.find(r=>r.id===o)?.groups.find(r=>r.id===s);if(l&&!Xa(l,i.baseline[n],An(i,n))){re.getState().logWarn("ribbon",`Group "${l.label}" (${s}) was not deleted: only your own groups, with only your own buttons in them, can be deleted — hide its buttons instead.`);return}e(r=>Ne(r,c=>{const d=c[n].tabs.find(u=>u.id===o);d&&(d.groups=d.groups.filter(u=>u.id!==s))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:s,detail:o,icon:"delete",color:"danger"}))},createTab(n,o){e(s=>o.id&&Yn(s,s.ribbons).has(o.id)?{}:Ne(s,i=>{const l=i[n],r=n==="Application"?"global":l.entityLogicalName,c=o.id??Yr(r,`${n}.${o.label??"New Tab"}`,"Tab",Yn(s,i)),d=yd({...o,id:c}),u={id:c,label:o.label??"New Tab",sequence:o.sequence!==void 0&&!l.tabs.some(m=>m.sequence===o.sequence)?o.sequence:Math.max(0,...l.tabs.map(m=>m.sequence))+10,commandId:d,tabDisplayRules:o.tabDisplayRules?.length?o.tabDisplayRules:xd(n,l.entityLogicalName,d),groups:[]};l.tabs.push(u)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:o.label??"New Tab",detail:n,icon:"add",color:"success"}))},renameTab(n,o,s){e(i=>Ne(i,l=>{const r=l[n].tabs.find(c=>c.id===o);r&&(r.label=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:o,detail:s,icon:"edit",color:"info"}))},deleteTab(n,o){const s=t(),i=s.ribbons[n].tabs.find(l=>l.id===o);if(i&&!kd(i,s.baseline[n],An(s,n))){re.getState().logWarn("ribbon",`Tab "${i.label}" (${o}) was not deleted: only your own tabs, with only your own groups and buttons in them, can be deleted.`);return}e(l=>Ne(l,r=>{r[n].tabs=r[n].tabs.filter(c=>c.id!==o)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:o,detail:n,icon:"delete",color:"danger"}))},reorderTabs(n,o){e(s=>Ne(s,i=>{const l=i[n].tabs,r=o.map(u=>l.find(m=>m.id===u)).filter(u=>u!==void 0);i[n].tabs=r;const c=new Set(s.baseline[n]?.tabs.map(u=>u.id)??[]),d=new Set(An(s,n)??[]);nl(r,u=>!c.has(u.id)||d.has(u.id))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:"Tabs",detail:n,icon:"arrow_sort",color:"info"}))},moveGroup(n,o,s,i){const l=t();if(!Gd(l,n,o,s,i))return;const r=l.ribbons[n].tabs.find(c=>c.id===o)?.groups.find(c=>c.id===s)?.label??s;e(c=>Ne(c,d=>{const u=d[n].tabs.find(b=>b.id===o);if(!u)return;u.groups.sort((b,g)=>b.sequence-g.sequence);const m=u.groups.findIndex(b=>b.id===s),[p]=u.groups.splice(m,1);u.groups.splice(m+i,0,p);const h=Wd(c,n);nl(u.groups,h)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:r,detail:i<0?"Moved left":"Moved right",icon:"arrow_sort",color:"info"}))},setTabDisplayRules(n,o,s){e(i=>Ne(i,l=>{const r=l[n].tabs.find(c=>c.id===o);r&&(r.tabDisplayRules=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} display rules`,detail:`${s.length} rule(s)`,icon:"eye",color:"info"}))},setScaling(n,o,s){e(i=>Ne(i,l=>{const r=l[n];r.scalingByTab=r.scalingByTab??{},r.scalingByTab[o]={tabId:o,maxSizes:[...s.maxSizes],scales:[...s.scales]}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} scaling`,detail:`${s.maxSizes.length} MaxSize, ${s.scales.length} Scale`,icon:"resize",color:"info"}))},hideOobButton(n,o,s,i){e(l=>Ne(l,r=>{const c=gt(r,n,o,s,i)?.button;c&&(rt(n,o,c)||(c.hidden=!0))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"hid",target:i,detail:s,icon:"eye_off",color:"warn"}))},customizeOobButton(n,o,s,i){e(l=>Ne(l,r=>{const c=gt(r,n,o,s,i)?.button;if(c){if(rt(n,o,c))return;c.oob=!1,c.custom=!0,c.managed=!1,c.origin="unmanaged"}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"customized",target:i,detail:"OOB override",icon:"edit",color:"info"}))},customiseButton(n,o,s,i,l){if(Pt(`customise ${i} in ${s}`,We(n,o,s)))return null;const r=t(),c=r.ribbons[n].tabs.find(y=>y.id===o)?.groups.find(y=>y.id===s)?.buttons.find(y=>y.id===i);if(!c||!er(n,o,c))return null;const d=Yn(r,r.ribbons),u=`${(l||"new").trim()}.${c.id}`;let m=u;for(let y=2;d.has(m);y++)m=`${u}.${y}`;const p=[],h=[],b=po(r),g=[[c.source?.labelToken,Is(m)],[c.source?.tooltipTitleToken,js(m)],[c.source?.tooltipBodyToken,$s(m)]];for(const[y,S]of g){if(!y||!us.test(y))continue;const C=r.locLabels.find(R=>R.id===y.replace(us,""));C?p.push({id:S,titles:C.titles.map(R=>({...R}))}):co(y,b)&&h.push(y)}h.length>0&&re.getState().logInfo("ribbon",`Customise button ${c.id}: ${h.join(", ")} ${h.length===1?"is":"are"} defined by another solution, so the copy ${m} uses ${h.length===1?"it":"them"} too. Edit the copy's text to give it a label of its own.`);const x=new Set(p.map(y=>y.id));return e(y=>{const{draft:S,next:C}=qd(y.ribbons),R=S[n].tabs.find(v=>v.id===o)?.groups.find(v=>v.id===s),M=R?.buttons.findIndex(v=>v.id===i)??-1;if(!R||M<0)return{};const I=R.buttons[M],$={...I,id:m,source:ax(I.source,b),hidden:!1,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0},T=R.buttons[M+1]?.sequence;return(T===void 0||I.sequence+1<T)&&($.sequence=I.sequence+1),I.hidden=!0,R.buttons.splice(M+1,0,$),_e(y,{ribbons:C,...p.length>0?{locLabels:[...y.locLabels.filter(v=>!x.has(v.id)),...p]}:{}},Ae("customised",i,`copied to ${m}, original hidden`+(h.length>0?" (keeps another solution's labels)":""),"copy"))}),m},customiseCommand(n){const o=t();return!o.commands.some(s=>s.id===n)||o.reloadRequiredCommandIds.includes(n)?!1:(e(s=>_e(s,{customisedCommandIds:[...s.customisedCommandIds.filter(i=>i!==n),n],uncustomisedCommandIds:si(s.uncustomisedCommandIds,n)},Ae("customised",n,"command copied to your layer on publish","code"))),!0)},uncustomiseCommand(n,o){e(s=>_e(s,{commands:sl(s,n),customisedCommandIds:s.customisedCommandIds.filter(i=>i!==n),uncustomisedCommandIds:{...si(s.uncustomisedCommandIds,n),[o]:[...s.uncustomisedCommandIds[o].filter(i=>i!==n),n]}},Ae("uncustomised",n,`command removed from the ${o==="entity"?"entity's":"application ribbon's"} layer on publish`,"arrow_undo")))},discardCommandChanges(n){const o=t(),s=sl(o,n);(s!==o.commands||o.customisedCommandIds.includes(n)||o.uncustomisedCommandIds.entity.includes(n)||o.uncustomisedCommandIds.application.includes(n))&&e(l=>_e(l,{commands:s,customisedCommandIds:l.customisedCommandIds.filter(r=>r!==n),uncustomisedCommandIds:si(l.uncustomisedCommandIds,n)},Ae("discarded",n,"command changes","arrow_undo")))},setOpenRecordOverride(n,o,s){if(!Bd.includes(n))return!1;const i=t(),l=i.ribbons[n],r=zd(l);if(o){if(r.length>0)return!0;const c=Fd(l);if(!c)return!1;const d=Yn(i,i.ribbons);for(const m of i.commands)d.add(m.id);const{id:u}=Md(s,l.entityLogicalName,n,"OpenRecordItem",d);return t().batch(()=>{t().createButton({location:n,tabId:c.tabId,groupId:c.groupId,button:{id:u,label:"Open record",tooltipTitle:"Open record",tooltipBody:`Runs the entity's ${Ye} action for the selected row, as opening a row does.`,kind:"button",templateAlias:"o1",commandId:Ye,hidden:!1,oob:!1,custom:!0,managed:!1}}),t().commands.some(m=>m.id===Ye)||t().upsertCommand(Qy())}),!0}return r.length===0?!0:r.some(c=>Pd(c)!=="yours")?!1:(t().batch(()=>{for(const u of r)t().deleteButton(n,u.tabId,u.groupId,u.button.id);const c=t();!Object.values(c.ribbons).some(u=>Qa(u).length>0)&&!c.baselineCommands.some(u=>u.id===Ye)&&e(u=>_e(u,{commands:u.commands.filter(m=>m.id!==Ye)},Ae("removed",Ye,"grid open override","delete","danger")))}),!0)},hideWithDisplayRules(n){const o=n?t().commands.find(i=>i.id===n):void 0;if(!o)return!1;const s=[...o.displayRules];for(const i of tx)s.includes(i)||s.push(i);return e(i=>{const l=Jn(i.commands,{...o,displayRules:s});return l?_e(i,{commands:l},Ae("hid",o.id,"with display rules","eye_off","warn")):i}),!0},upsertCommand(n){e(o=>{const s=Jn(o.commands,n);if(!s)return o;const i=s.length>o.commands.length;return _e(o,{commands:s},i?Ae("added",n.id,"command","add","success"):Ae("edited",n.id,"command","edit"),i?void 0:`command:${n.id}`)})},renameCommandId(n,o){const s=t();return!n||!o||n===o?!0:s.commands.some(i=>i.id===o)?!1:(e(i=>{const l=xn(i.ribbons);for(const c of Object.keys(l))for(const d of l[c].tabs)for(const u of d.groups)for(const m of je(u))m.commandId===n&&(m.commandId=o),m.source?.xml&&(m.source.xml=Db(m.source.xml,n,o));const r=i.commands.map(c=>c.id===n?{...c,id:o}:c);return _e(i,{ribbons:l,commands:r},Ae("renamed",n,`command -> ${o}`,"edit"))}),!0)},upsertDisplayRule(n){e(o=>{const s=Jn(o.displayRules,n);if(!s)return o;const i=s.length>o.displayRules.length;return _e(o,{displayRules:s},i?Ae("added",n.id,"display rule","add","success"):Ae("edited",n.id,"display rule","edit"),i?void 0:`displayRule:${n.id}`)})},renameDisplayRuleId(n,o){const s=t();return!n||!o||n===o?!0:s.displayRules.some(i=>i.id===o)?!1:(e(i=>{const l=i.displayRules.map(c=>c.id===n?{...c,id:o}:c),r=i.commands.map(c=>({...c,displayRules:c.displayRules.map(d=>d===n?o:d)}));return _e(i,{displayRules:l,commands:r},Ae("renamed",n,`display rule -> ${o}`,"edit"))}),!0)},upsertEnableRule(n){e(o=>{const s=Jn(o.enableRules,n);if(!s)return o;const i=s.length>o.enableRules.length;return _e(o,{enableRules:s},i?Ae("added",n.id,"enable rule","add","success"):Ae("edited",n.id,"enable rule","edit"),i?void 0:`enableRule:${n.id}`)})},renameEnableRuleId(n,o){const s=t();return!n||!o||n===o?!0:s.enableRules.some(i=>i.id===o)?!1:(e(i=>{const l=i.enableRules.map(c=>c.id===n?{...c,id:o}:c),r=i.commands.map(c=>({...c,enableRules:c.enableRules.map(d=>d===n?o:d)}));return _e(i,{enableRules:l,commands:r},Ae("renamed",n,`enable rule -> ${o}`,"edit"))}),!0)},upsertLocLabel(n){e(o=>{const s=Jn(o.locLabels,n);return s?_e(o,{locLabels:s},Ae("edited",n.id,"label","translate"),`locLabel:${n.id}`):o})},setLayerHideUnhidden(n,o,s){e(i=>{if(i.pendingUnhides[n].includes(o)===s)return i;const l=i.pendingUnhides[n].filter(r=>r!==o);return s&&l.push(o),_e(i,{pendingUnhides:{...i.pendingUnhides,[n]:l}},s?Ae("un-hid",o,"on publish","eye"):Ae("kept hidden",o,"by customizations","eye_off"))})},setOrphanDeleted(n,o,s){e(i=>{const l=i.orphans[n].find(c=>c.id===o);if(!l||s&&l.recentPublish?.published||i.pendingOrphanDeletes[n].includes(o)===s)return i;const r=i.pendingOrphanDeletes[n].filter(c=>c!==o);return s&&r.push(o),_e(i,{pendingOrphanDeletes:{...i.pendingOrphanDeletes,[n]:r}},s?Ae("deleted",o,"not on the canvas — removed on publish","delete","danger"):Ae("kept",o,"not on the canvas","arrow_undo"))})},setLayerSnapshot(n,o){e(s=>({layers:{...s.layers,[n]:o}}))},markPublished(n,o){e(s=>{const i=Object.keys(s.ribbons),l=n??i,r={...s.baseline},c={...s.ribbons};let d=s.locLabels,u=s.baselineLocLabels;const m=(w,k)=>[...w.filter(N=>!k.some(j=>j.id===N.id)),...k];for(const[w,k]of Object.entries(o??{})){const N=w==="entity"?tl:["Application"];for(const _ of N)l.includes(_)&&(c[_]===s.ribbons[_]&&(c[_]=JSON.parse(JSON.stringify(c[_]))),Vb(c[_],k));const j=Ki(k);d=m(d,j),u=m(u,j)}for(const w of l)r[w]=c[w];const p=i.every(w=>l.includes(w)),h={...s.layers},b={...s.pendingUnhides},g={entity:[],application:[]},x=[["entity",tl.every(w=>l.includes(w))],["application",l.includes("Application")]];for(const[w,k]of x){const N=o?.[w];if(!k||!N)continue;const j=h[w],_=(W,ne)=>[...new Set([...W,...ne])];h[w]=j?{...j,containerIds:_(j.containerIds,dd(N)),controlIds:_(j.controlIds,ns(N)),locLabelIds:_(j.locLabelIds,new Set(N.locLabels.keys()))}:ls(N)}for(const[w,k]of x){if(!k||b[w].length===0)continue;const N=h[w];N&&(h[w]={...N,hides:N.hides.filter(j=>!b[w].includes(j.location))}),g[w]=b[w],b[w]=[]}const y={...s.orphans},S={...s.pendingOrphanDeletes},C={entity:[],application:[]};for(const[w,k]of x)!k||S[w].length===0||(y[w]=y[w].filter(N=>!S[w].includes(N.id)),C[w]=S[w],S[w]=[]);const R={...s.uncustomisedCommandIds},M=[...s.reloadRequiredCommandIds],I={entity:[],application:[]};for(const[w,k]of x)if(k){for(const N of R[w])M.includes(N)||M.push(N);I[w]=R[w],R[w]=[]}const $=(w,k)=>({entity:w.entity.filter(N=>!k.entity.includes(N)),application:w.application.filter(N=>!k.application.includes(N))}),T=w=>({...w,snapshot:{...w.snapshot,pendingUnhides:$(w.snapshot.pendingUnhides,g),pendingOrphanDeletes:$(w.snapshot.pendingOrphanDeletes??ei,C),uncustomisedCommandIds:$(w.snapshot.uncustomisedCommandIds,I)}}),v=[g,I,C].reduce((w,k)=>w+k.entity.length+k.application.length,0)>0,O=s.past.map((w,k)=>{const N=v?T(w):w;return k===s.past.length-1&&N.coalesceKey?{...N,coalesceKey:void 0}:N}),A={ribbons:c,locLabels:d,baselineLocLabels:u,baseline:r,layers:h,pendingUnhides:b,uncustomisedCommandIds:R,orphans:y,pendingOrphanDeletes:S,...p?{baselineCommands:[...s.commands],baselineEnableRules:[...s.enableRules],baselineDisplayRules:[...s.displayRules],baselineLocLabels:[...d],customisedCommandIds:[]}:{}},E=mo({...s,...A});return{...A,past:O,future:v?s.future.map(T):s.future,reloadRequiredCommandIds:M,mutationsSincePublish:E?Math.max(1,s.mutationsSincePublish):0}})}})));Sb(()=>{D.getState().resetWorkspace(),Z.getState().clearSelection()});var Oe=Uint8Array,ct=Uint16Array,tr=Int32Array,Ds=new Oe([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]),Bs=new Oe([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]),Zi=new Oe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Vd=function(e,t){for(var n=new ct(31),o=0;o<31;++o)n[o]=t+=1<<e[o-1];for(var s=new tr(n[30]),o=1;o<30;++o)for(var i=n[o];i<n[o+1];++i)s[i]=i-n[o]<<5|o;return{b:n,r:s}},Xd=Vd(Ds,2),Kd=Xd.b,Qi=Xd.r;Kd[28]=258,Qi[258]=28;var Yd=Vd(Bs,0),rx=Yd.b,il=Yd.r,ea=new ct(32768);for(var $e=0;$e<32768;++$e){var Ft=($e&43690)>>1|($e&21845)<<1;Ft=(Ft&52428)>>2|(Ft&13107)<<2,Ft=(Ft&61680)>>4|(Ft&3855)<<4,ea[$e]=((Ft&65280)>>8|(Ft&255)<<8)>>1}var $t=(function(e,t,n){for(var o=e.length,s=0,i=new ct(t);s<o;++s)e[s]&&++i[e[s]-1];var l=new ct(t);for(s=1;s<t;++s)l[s]=l[s-1]+i[s-1]<<1;var r;if(n){r=new ct(1<<t);var c=15-t;for(s=0;s<o;++s)if(e[s])for(var d=s<<4|e[s],u=t-e[s],m=l[e[s]-1]++<<u,p=m|(1<<u)-1;m<=p;++m)r[ea[m]>>c]=d}else for(r=new ct(o),s=0;s<o;++s)e[s]&&(r[s]=ea[l[e[s]-1]++]>>15-e[s]);return r}),Qt=new Oe(288);for(var $e=0;$e<144;++$e)Qt[$e]=8;for(var $e=144;$e<256;++$e)Qt[$e]=9;for(var $e=256;$e<280;++$e)Qt[$e]=7;for(var $e=280;$e<288;++$e)Qt[$e]=8;var vo=new Oe(32);for(var $e=0;$e<32;++$e)vo[$e]=5;var lx=$t(Qt,9,0),cx=$t(Qt,9,1),dx=$t(vo,5,0),ux=$t(vo,5,1),ii=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},bt=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)},nr=function(e){return(e+7)/8|0},jo=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Oe(e.subarray(t,n))},mx=["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"],Ke=function(e,t,n){var o=new Error(t||mx[e]);if(o.code=e,Error.captureStackTrace&&Error.captureStackTrace(o,Ke),!n)throw o;return o},px=function(e,t,n,o){var s=e.length,i=o?o.length:0;if(!s||t.f&&!t.l)return n||new Oe(0);var l=!n,r=l||t.i!=2,c=t.i;l&&(n=new Oe(s*3));var d=function(Pe){var ot=n.length;if(Pe>ot){var Ee=new Oe(Math.max(ot*2,Pe));Ee.set(n),n=Ee}},u=t.f||0,m=t.p||0,p=t.b||0,h=t.l,b=t.d,g=t.m,x=t.n,y=s*8;do{if(!h){u=bt(e,m,1);var S=bt(e,m+1,3);if(m+=3,S)if(S==1)h=cx,b=ux,g=9,x=5;else if(S==2){var I=bt(e,m,31)+257,$=bt(e,m+10,15)+4,T=I+bt(e,m+5,31)+1;m+=14;for(var v=new Oe(T),O=new Oe(19),A=0;A<$;++A)O[Zi[A]]=bt(e,m+A*3,7);m+=$*3;for(var E=ii(O),w=(1<<E)-1,k=$t(O,E,1),A=0;A<T;){var N=k[bt(e,m,w)];m+=N&15;var C=N>>4;if(C<16)v[A++]=C;else{var j=0,_=0;for(C==16?(_=3+bt(e,m,3),m+=2,j=v[A-1]):C==17?(_=3+bt(e,m,7),m+=3):C==18&&(_=11+bt(e,m,127),m+=7);_--;)v[A++]=j}}var W=v.subarray(0,I),ne=v.subarray(I);g=ii(W),x=ii(ne),h=$t(W,g,1),b=$t(ne,x,1)}else Ke(1);else{var C=nr(m)+4,R=e[C-4]|e[C-3]<<8,M=C+R;if(M>s){c&&Ke(0);break}r&&d(p+R),n.set(e.subarray(C,M),p),t.b=p+=R,t.p=m=M*8,t.f=u;continue}if(m>y){c&&Ke(0);break}}r&&d(p+131072);for(var le=(1<<g)-1,ce=(1<<x)-1,F=m;;F=m){var j=h[ai(e,m)&le],L=j>>4;if(m+=j&15,m>y){c&&Ke(0);break}if(j||Ke(2),L<256)n[p++]=L;else if(L==256){F=m,h=null;break}else{var G=L-254;if(L>264){var A=L-257,H=Ds[A];G=bt(e,m,(1<<H)-1)+Kd[A],m+=H}var te=b[ai(e,m)&ce],P=te>>4;te||Ke(3),m+=te&15;var ne=rx[P];if(P>3){var H=Bs[P];ne+=ai(e,m)&(1<<H)-1,m+=H}if(m>y){c&&Ke(0);break}r&&d(p+131072);var K=p+G;if(p<ne){var ue=i-ne,Me=Math.min(ne,K);for(ue+p<0&&Ke(3);p<Me;++p)n[p]=o[ue+p]}for(;p<K;++p)n[p]=n[p-ne]}}t.l=h,t.p=F,t.b=p,t.f=u,h&&(u=1,t.m=g,t.d=b,t.n=x)}while(!u);return p!=n.length&&l?jo(n,0,p):n.subarray(0,p)},Tt=function(e,t,n){n<<=t&7;var o=t/8|0;e[o]|=n,e[o+1]|=n>>8},Zn=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},ri=function(e,t){for(var n=[],o=0;o<e.length;++o)e[o]&&n.push({s:o,f:e[o]});var s=n.length,i=n.slice();if(!s)return{t:Zd,l:0};if(s==1){var l=new Oe(n[0].s+1);return l[n[0].s]=1,{t:l,l:1}}n.sort(function(M,I){return M.f-I.f}),n.push({s:-1,f:25001});var r=n[0],c=n[1],d=0,u=1,m=2;for(n[0]={s:-1,f:r.f+c.f,l:r,r:c};u!=s-1;)r=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:r.f+c.f,l:r,r:c};for(var p=i[0].s,o=1;o<s;++o)i[o].s>p&&(p=i[o].s);var h=new ct(p+1),b=ta(n[u-1],h,0);if(b>t){var o=0,g=0,x=b-t,y=1<<x;for(i.sort(function(I,$){return h[$.s]-h[I.s]||I.f-$.f});o<s;++o){var S=i[o].s;if(h[S]>t)g+=y-(1<<b-h[S]),h[S]=t;else break}for(g>>=x;g>0;){var C=i[o].s;h[C]<t?g-=1<<t-h[C]++-1:++o}for(;o>=0&&g;--o){var R=i[o].s;h[R]==t&&(--h[R],++g)}b=t}return{t:new Oe(h),l:b}},ta=function(e,t,n){return e.s==-1?Math.max(ta(e.l,t,n+1),ta(e.r,t,n+1)):t[e.s]=n},al=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new ct(++t),o=0,s=e[0],i=1,l=function(c){n[o++]=c},r=1;r<=t;++r)if(e[r]==s&&r!=t)++i;else{if(!s&&i>2){for(;i>138;i-=138)l(32754);i>2&&(l(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(l(s),--i;i>6;i-=6)l(8304);i>2&&(l(i-3<<5|8208),i=0)}for(;i--;)l(s);i=1,s=e[r]}return{c:n.subarray(0,o),n:t}},Qn=function(e,t){for(var n=0,o=0;o<t.length;++o)n+=e[o]*t[o];return n},Jd=function(e,t,n){var o=n.length,s=nr(t+2);e[s]=o&255,e[s+1]=o>>8,e[s+2]=e[s]^255,e[s+3]=e[s+1]^255;for(var i=0;i<o;++i)e[s+i+4]=n[i];return(s+4+o)*8},rl=function(e,t,n,o,s,i,l,r,c,d,u){Tt(t,u++,n),++s[256];for(var m=ri(s,15),p=m.t,h=m.l,b=ri(i,15),g=b.t,x=b.l,y=al(p),S=y.c,C=y.n,R=al(g),M=R.c,I=R.n,$=new ct(19),T=0;T<S.length;++T)++$[S[T]&31];for(var T=0;T<M.length;++T)++$[M[T]&31];for(var v=ri($,7),O=v.t,A=v.l,E=19;E>4&&!O[Zi[E-1]];--E);var w=d+5<<3,k=Qn(s,Qt)+Qn(i,vo)+l,N=Qn(s,p)+Qn(i,g)+l+14+3*E+Qn($,O)+2*$[16]+3*$[17]+7*$[18];if(c>=0&&w<=k&&w<=N)return Jd(t,u,e.subarray(c,c+d));var j,_,W,ne;if(Tt(t,u,1+(N<k)),u+=2,N<k){j=$t(p,h,0),_=p,W=$t(g,x,0),ne=g;var le=$t(O,A,0);Tt(t,u,C-257),Tt(t,u+5,I-1),Tt(t,u+10,E-4),u+=14;for(var T=0;T<E;++T)Tt(t,u+3*T,O[Zi[T]]);u+=3*E;for(var ce=[S,M],F=0;F<2;++F)for(var L=ce[F],T=0;T<L.length;++T){var G=L[T]&31;Tt(t,u,le[G]),u+=O[G],G>15&&(Tt(t,u,L[T]>>5&127),u+=L[T]>>12)}}else j=lx,_=Qt,W=dx,ne=vo;for(var T=0;T<r;++T){var H=o[T];if(H>255){var G=H>>18&31;Zn(t,u,j[G+257]),u+=_[G+257],G>7&&(Tt(t,u,H>>23&31),u+=Ds[G]);var te=H&31;Zn(t,u,W[te]),u+=ne[te],te>3&&(Zn(t,u,H>>5&8191),u+=Bs[te])}else Zn(t,u,j[H]),u+=_[H]}return Zn(t,u,j[256]),u+_[256]},fx=new tr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Zd=new Oe(0),hx=function(e,t,n,o,s,i){var l=i.z||e.length,r=new Oe(o+l+5*(1+Math.ceil(l/7e3))+s),c=r.subarray(o,r.length-s),d=i.l,u=(i.r||0)&7;if(t){u&&(c[0]=i.r>>3);for(var m=fx[t-1],p=m>>13,h=m&8191,b=(1<<n)-1,g=i.p||new ct(32768),x=i.h||new ct(b+1),y=Math.ceil(n/3),S=2*y,C=function(Fe){return(e[Fe]^e[Fe+1]<<y^e[Fe+2]<<S)&b},R=new tr(25e3),M=new ct(288),I=new ct(32),$=0,T=0,v=i.i||0,O=0,A=i.w||0,E=0;v+2<l;++v){var w=C(v),k=v&32767,N=x[w];if(g[k]=N,x[w]=k,A<=v){var j=l-v;if(($>7e3||O>24576)&&(j>423||!d)){u=rl(e,c,0,R,M,I,T,O,E,v-E,u),O=$=T=0,E=v;for(var _=0;_<286;++_)M[_]=0;for(var _=0;_<30;++_)I[_]=0}var W=2,ne=0,le=h,ce=k-N&32767;if(j>2&&w==C(v-ce))for(var F=Math.min(p,j)-1,L=Math.min(32767,v),G=Math.min(258,j);ce<=L&&--le&&k!=N;){if(e[v+W]==e[v+W-ce]){for(var H=0;H<G&&e[v+H]==e[v+H-ce];++H);if(H>W){if(W=H,ne=ce,H>F)break;for(var te=Math.min(ce,H-2),P=0,_=0;_<te;++_){var K=v-ce+_&32767,ue=g[K],Me=K-ue&32767;Me>P&&(P=Me,N=K)}}}k=N,N=g[k],ce+=k-N&32767}if(ne){R[O++]=268435456|Qi[W]<<18|il[ne];var Pe=Qi[W]&31,ot=il[ne]&31;T+=Ds[Pe]+Bs[ot],++M[257+Pe],++I[ot],A=v+W,++$}else R[O++]=e[v],++M[e[v]]}}for(v=Math.max(v,A);v<l;++v)R[O++]=e[v],++M[e[v]];u=rl(e,c,d,R,M,I,T,O,E,v-E,u),d||(i.r=u&7|c[u/8|0]<<3,u-=7,i.h=x,i.p=g,i.i=v,i.w=A)}else{for(var v=i.w||0;v<l+d;v+=65535){var Ee=v+65535;Ee>=l&&(c[u/8|0]=d,Ee=l),u=Jd(c,u+1,e.subarray(v,Ee))}i.i=l}return jo(r,0,o+nr(u)+s)},gx=(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})(),bx=function(){var e=-1;return{p:function(t){for(var n=e,o=0;o<t.length;++o)n=gx[n&255^t[o]]^n>>>8;e=n},d:function(){return~e}}},yx=function(e,t,n,o,s){if(!s&&(s={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new Oe(i.length+e.length);l.set(i),l.set(e,i.length),e=l,s.w=i.length}return hx(e,t.level==null?6:t.level,t.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,o,s)},Qd=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},Rt=function(e,t){return e[t]|e[t+1]<<8},pt=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},li=function(e,t){return pt(e,t)+pt(e,t+4)*4294967296},Ue=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function eu(e,t){return yx(e,t||{},0,0)}function tu(e,t){return px(e,{i:2},t&&t.out,t&&t.dictionary)}var nu=function(e,t,n,o){for(var s in e){var i=e[s],l=t+s,r=o;Array.isArray(i)&&(r=Qd(o,i[1]),i=i[0]),ArrayBuffer.isView(i)?n[l]=[i,r]:(n[l+="/"]=[new Oe(0),r],nu(i,l,n,o))}},ll=typeof TextEncoder<"u"&&new TextEncoder,na=typeof TextDecoder<"u"&&new TextDecoder,xx=0;try{na.decode(Zd,{stream:!0}),xx=1}catch{}var vx=function(e){for(var t="",n=0;;){var o=e[n++],s=(o>127)+(o>223)+(o>239);if(n+s>e.length)return{s:t,r:jo(e,n-1)};s?s==3?(o=((o&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|o>>10,56320|o&1023)):s&1?t+=String.fromCharCode((o&31)<<6|e[n++]&63):t+=String.fromCharCode((o&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(o)}};function ms(e,t){if(t){for(var n=new Oe(e.length),o=0;o<e.length;++o)n[o]=e.charCodeAt(o);return n}if(ll)return ll.encode(e);for(var s=e.length,i=new Oe(e.length+(e.length>>1)),l=0,r=function(u){i[l++]=u},o=0;o<s;++o){if(l+5>i.length){var c=new Oe(l+8+(s-o<<1));c.set(i),i=c}var d=e.charCodeAt(o);d<128||t?r(d):d<2048?(r(192|d>>6),r(128|d&63)):d>55295&&d<57344?(d=65536+(d&1047552)|e.charCodeAt(++o)&1023,r(240|d>>18),r(128|d>>12&63),r(128|d>>6&63),r(128|d&63)):(r(224|d>>12),r(128|d>>6&63),r(128|d&63))}return jo(i,0,l)}function Ls(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(na)return na.decode(e);var s=vx(e),i=s.s,n=s.r;return n.length&&Ke(8),i}}var Sx=function(e,t){return t+30+Rt(e,t+26)+Rt(e,t+28)},wx=function(e,t,n){var o=Rt(e,t+28),s=Rt(e,t+30),i=Ls(e.subarray(t+46,t+46+o),!(Rt(e,t+8)&2048)),l=t+46+o,r=Cx(e,l,s,n,pt(e,t+20),pt(e,t+24),pt(e,t+42)),c=r[0],d=r[1],u=r[2];return[Rt(e,t+10),c,d,i,l+s+Rt(e,t+32),u]},Cx=function(e,t,n,o,s,i,l){var r=s==4294967295,c=i==4294967295,d=l==4294967295,u=t+n,m=r+c+d;if(o&&m){for(;t+4<u;t+=4+Rt(e,t+2))if(Rt(e,t)==1)return[r?li(e,t+4+8*c):s,c?li(e,t+4):i,d?li(e,t+4+8*(c+r)):l,1];o<2&&Ke(13)}return[s,i,l,0]},oa=function(e){var t=0;if(e)for(var n in e){var o=e[n].length;o>65535&&Ke(9),t+=o+4}return t},cl=function(e,t,n,o,s,i,l,r){var c=o.length,d=n.extra,u=r&&r.length,m=oa(d);Ue(e,t,l!=null?33639248:67324752),t+=4,l!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(i<0&&8),e[t++]=s&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var p=new Date(n.mtime==null?Date.now():n.mtime),h=p.getFullYear()-1980;if((h<0||h>119)&&Ke(10),Ue(e,t,h<<25|p.getMonth()+1<<21|p.getDate()<<16|p.getHours()<<11|p.getMinutes()<<5|p.getSeconds()>>1),t+=4,i!=-1&&(Ue(e,t,n.crc),Ue(e,t+4,i<0?-i-2:i),Ue(e,t+8,n.size)),Ue(e,t+12,c),Ue(e,t+14,m),t+=16,l!=null&&(Ue(e,t,u),Ue(e,t+6,n.attrs),Ue(e,t+10,l),t+=14),e.set(o,t),t+=c,m)for(var b in d){var g=d[b],x=g.length;Ue(e,t,+b),Ue(e,t+2,x),e.set(g,t+4),t+=4+x}return u&&(e.set(r,t),t+=u),t},Rx=function(e,t,n,o,s){Ue(e,t,101010256),Ue(e,t+8,n),Ue(e,t+10,n),Ue(e,t+12,o),Ue(e,t+16,s)};function GR(e,t){t||(t={});var n={},o=[];nu(e,"",n,t);var s=0,i=0;for(var l in n){var r=n[l],c=r[0],d=r[1],u=d.level==0?0:8,m=ms(l),p=m.length,h=d.comment,b=h&&ms(h),g=b&&b.length,x=oa(d.extra);p>65535&&Ke(11);var y=u?eu(c,d):c,S=y.length,C=bx();C.p(c),o.push(Qd(d,{size:c.length,crc:C.d(),c:y,f:m,m:b,u:p!=l.length||b&&h.length!=g,o:s,compression:u})),s+=30+p+x+S,i+=76+2*(p+x)+(g||0)+S}for(var R=new Oe(i+22),M=s,I=i-s,$=0;$<o.length;++$){var m=o[$];cl(R,m.o,m,m.f,m.u,m.c.length);var T=30+m.f.length+oa(m.extra);R.set(m.c,m.o+T),cl(R,s,m,m.f,m.u,m.c.length,m.o,m.m),s+=16+T+(m.m?m.m.length:0)}return Rx(R,s,o.length,I,M),R}function Ix(e,t){for(var n={},o=e.length-22;pt(e,o)!=101010256;--o)(!o||e.length-o>65558)&&Ke(13);var s=Rt(e,o+8);if(!s)return{};var i=pt(e,o+16),l=pt(e,o-20)==117853008;if(l){var r=pt(e,o-12);l=pt(e,r)==101075792,l&&(s=pt(e,r+32),i=pt(e,r+48))}for(var c=0;c<s;++c){var d=wx(e,i,l),u=d[0],m=d[1],p=d[2],h=d[3],b=d[4],g=d[5],x=Sx(e,g);i=b,u?u==8?n[h]=tu(e.subarray(x,x+m),{out:new Oe(p)}):Ke(14,"unknown compression type "+u):n[h]=jo(e,x,x+m)}return n}const zs=4,ou=30,su=`cbs:draft:v${zs}:`,jx=["cbs:ribbon:","cbs:draft:"],On={commands:"baselineCommands",enableRules:"baselineEnableRules",displayRules:"baselineDisplayRules",locLabels:"baselineLocLabels"},or=["HomepageGrid","SubGrid","Form","Application"];function iu(e){return{orgUrl:e.orgUrl.trim().replace(/\/+$/,"").toLowerCase(),solutionId:e.solutionId.trim().toLowerCase(),entityLogicalName:e.entityLogicalName.trim().toLowerCase()}}function zn(e){const t=iu(e);return`${su}${encodeURIComponent(t.orgUrl)}:${encodeURIComponent(t.solutionId)}:${encodeURIComponent(t.entityLogicalName)}`}function ps(e,t){return!e||!t?!1:zn(e)===zn(t)}function $x(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 Do=null;function au(e){const t=[e.baseline,e.baselineCommands,e.baselineEnableRules,e.baselineDisplayRules,e.baselineLocLabels,e.layers,e.baseLanguageCode];if(Do&&Do.of.every((o,s)=>o===t[s]))return Do.value;const n=$x(JSON.stringify(t));return Do={of:t,value:n},n}const dl=new WeakMap;function Bo(e){let t=dl.get(e);return t===void 0&&(t=JSON.stringify(e),dl.set(e,t)),t}const In=e=>JSON.parse(JSON.stringify(e)),$o={},ru={list:"groups",child:{list:"buttons",child:$o}};function lu(e){const t=new Map;for(const n of e)t.set(n.id,t.has(n.id)?null:n);return t}function ci(e,t,n){if(!n.list||!Array.isArray(e[n.list]))return e;const o=t?.[n.list]??[];return{...e,[n.list]:sa(e[n.list],o,n.child??$o)}}function Lo(e,t,n){if(!n.list||e[n.list]===void 0)return e;const o=t?.[n.list]??[];return{...e,[n.list]:ia(e[n.list],o,n.child??$o)}}function sa(e,t,n){const o=lu(t),s=new Set(e.map(i=>i.id));if(s.size===e.length&&o.size===t.length){const i=t.filter(r=>s.has(r.id)),l=e.slice(i.length);if(i.every((r,c)=>e[c].id===r.id)&&l.every(r=>!o.has(r.id)))return{set:e.slice(0,i.length).filter(r=>Bo(o.get(r.id))!==Bo(r)).map(r=>ci(r,o.get(r.id),n)),drop:t.filter(r=>!s.has(r.id)).map(r=>r.id),add:l.map(r=>ci(r,void 0,n))}}return e.map(i=>{const l=o.get(i.id)??void 0;return l&&Bo(l)===Bo(i)?i.id:ci(i,l,n)})}function ia(e,t,n){const o=lu(t);if(Array.isArray(e)){const c=[];for(const d of e)if(typeof d!="string")c.push(Lo(d,o.get(d.id)??void 0,n));else{const u=o.get(d);u&&c.push(In(u))}return c}const s=new Set(e.drop),i=new Map(e.set.map(c=>[c.id,c])),l=[];for(const c of e.add)o.has(c.id)?i.set(c.id,c):l.push(c);const r=new Set(t.map(c=>c.id));return[...t.filter(c=>!s.has(c.id)).map(c=>i.has(c.id)?Lo(i.get(c.id),c,n):In(c)),...[...i.values()].filter(c=>!r.has(c.id)).map(c=>Lo(c,void 0,n)),...l.map(c=>Lo(c,void 0,n))]}const Tx=e=>!Array.isArray(e)&&e.set.length+e.drop.length+e.add.length===0,fs=e=>e;function Nx(e){const t=Ct(e),n={};for(const i of or){const l=t.ribbons[i],r=e.baseline[i];if(!l)continue;const c=sa(l.tabs,r?.tabs??[],ru),d={};for(const[m,p]of Object.entries(l))m!=="tabs"&&JSON.stringify(p)!==JSON.stringify(r?.[m])&&(d[m]=p);const u=Object.keys(r??{}).filter(m=>m!=="tabs"&&!(m in l));(!Tx(c)||Object.keys(d).length+u.length>0)&&(n[i]={props:d,unset:u,tabs:c})}const o={};for(const i of Object.keys(On))o[i]=sa(fs(t[i]),fs(e[On[i]]),$o);const s={...t};delete s.ribbons;for(const i of Object.keys(On))delete s[i];return{ribbons:n,lists:o,other:s}}function kx(e,t){const{delta:n}=e,o={};for(const i of or){const l=n.ribbons[i],r=t.baseline[i];if(!l){o[i]=In(r);continue}const c={...In(r),...In(l.props)};for(const d of l.unset)delete c[d];c.tabs=ia(l.tabs,fs(r?.tabs??[]),ru),o[i]=c}const s={...Ct(t),...In(n.other),ribbons:o};for(const i of Object.keys(On))s[i]=ia(n.lists[i],fs(t[On[i]]),$o);return s}function Ax(e){return btoa(Ls(eu(ms(JSON.stringify(e)),{level:9}),!0))}function Ox(e){return JSON.parse(Ls(tu(ms(atob(e),!0))))}const Yt=e=>Array.isArray(e),di=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ul=e=>{if(Yt(e))return!0;const t=e;return!!t&&typeof t=="object"&&Yt(t.set)&&Yt(t.drop)&&Yt(t.add)},Mx=e=>!!e&&typeof e=="object"&&Yt(e.entity)&&Yt(e.application);function Ex(e){if(!e||typeof e!="object")return!1;const t=e,n=t.ribbons,o=t.other??{};return!!n&&typeof n=="object"&&Object.entries(n).every(([s,i])=>or.includes(s)&&ul(i?.tabs)&&di(i?.props)&&Yt(i?.unset))&&di(t.lists)&&Object.keys(On).every(s=>ul(t.lists[s]))&&di(t.other)&&["pendingUnhides","uncustomisedCommandIds"].every(s=>!(s in o)||Mx(o[s]))&&(!("customisedCommandIds"in o)||Yt(o.customisedCommandIds))}function Dx(e,t){try{const n={format:zs,key:iu(e),savedAt:new Date().toISOString(),baselineFingerprint:au(t),data:Ax(Nx(t))};return localStorage.setItem(zn(e),JSON.stringify(n)),n.savedAt}catch{return null}}function Bx(e){const t=zn(e);let n;try{n=localStorage.getItem(t)}catch{return null}if(!n)return null;try{const o=JSON.parse(n);if(o.format===zs&&ps(o.key,e)&&typeof o.data=="string"){const s=Ox(o.data);if(Ex(s)){const i=o;return{format:i.format,key:i.key,savedAt:i.savedAt,baselineFingerprint:i.baselineFingerprint,delta:s}}}}catch{}return hs(e),null}function Lx(e){try{const t=localStorage.getItem(zn(e));if(!t)return!1;const n=JSON.parse(t);return n.format===zs&&ps(n.key,e)&&typeof n.data=="string"}catch{return!1}}function hs(e){try{localStorage.removeItem(zn(e))}catch{}}function zx(e,t){try{const n=Date.parse(JSON.parse(e??"").savedAt??"");return!(t-n<=ou*864e5)}catch{return!0}}function Px(e=Date.now()){const t=[];try{for(let n=0;n<localStorage.length;n++){const o=localStorage.key(n);o&&(o.startsWith(su)?zx(localStorage.getItem(o),e):jx.some(s=>o.startsWith(s)))&&t.push(o)}for(const n of t)localStorage.removeItem(n)}catch{return 0}return t.length}function cu(e){return e.mutationsSincePublish>0||mo(e)}function Xo(){return Ie.getState().target!==null&&cu(D.getState())}let un=null;function sn(e){const{target:t,pending:n}=Ie.getState();if(!t||n)return!0;const o=e.ribbons.HomepageGrid.entityLogicalName;if(o&&o.toLowerCase()!==t.entityLogicalName.toLowerCase())return!0;let s=!0;if(!cu(e))un!==null&&e.future.some(r=>r.op==="restored"&&r.ts===un)||(hs(t),Ie.setState({lastSavedAt:null}));else{const l=Dx(t,e);s=l!==null,l&&Ie.setState({lastSavedAt:l})}const{saveFailed:i}=Ie.getState();return!s&&!i&&re.getState().logWarn("ribbon","Unsaved changes could not be saved as a draft (browser storage is full or unavailable): publish them, or they are lost when Command Bar Studio closes."),s===i&&Ie.setState({saveFailed:!s}),s}const Fx=["mutationsSincePublish","ribbons","commands","enableRules","displayRules","locLabels","pendingUnhides","customisedCommandIds","uncustomisedCommandIds","baseline","baselineCommands","baselineEnableRules","baselineDisplayRules","baselineLocLabels","layers"];function _x(){return D.subscribe((e,t)=>{e.baseline!==t.baseline&&(un=null),!Fx.every(n=>e[n]===t[n])&&sn(e)})}function du(e){const t=ae.getState();return{orgUrl:t.connectionUrl,solutionId:t.activeSolution?.id??"",entityLogicalName:e}}function qx(){const e=D.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 ui(e){Ie.setState({target:null,pending:null,pendingBaselineChanged:!1});const t=ae.getState();e.kind==="entity"?t.setActiveEntity(e.entity):t.setActiveSolution(e.solution)}const Ie=en()((e,t)=>({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null,beginLoad(){un=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,saveFailed:!1,lastSavedAt:null})},workspaceLoaded(n){const o=Bx(n);un=null,e({target:n,pending:o,restoreError:null,lastSavedAt:o?.savedAt??null,pendingBaselineChanged:!!o&&o.baselineFingerprint!==au(D.getState())})},restoreDraft(){const{target:n,pending:o}=t();if(!n||!o||!ps(n,o.key))return!1;const s=D.getState();try{s.restoreWorkspace(kx(o,s),`saved ${new Date(o.savedAt).toLocaleString()}`)}catch(r){const c=r instanceof Error?r.message:String(r);return re.getState().logError("ribbon",`The unsaved changes saved ${o.savedAt} couldn't be restored: ${c}`),e({restoreError:c}),!1}const i=D.getState(),l=i.past[i.past.length-1];return i.past.length>s.past.length&&l?.op==="restored"&&(un=l.ts),e({pending:null,pendingBaselineChanged:!1,restoreError:null}),sn(i),!0},discardDraft(){const{target:n,pending:o}=t();o&&(hs(o.key),e({pending:null,pendingBaselineChanged:!1,restoreError:null,lastSavedAt:null}),n&&ps(n,o.key)&&sn(D.getState()))},requestEntitySwitch(n){ae.getState().activeEntity?.logicalName!==n.logicalName&&(Xo()?(sn(D.getState()),e({pendingSwitch:{kind:"entity",entity:n}})):ui({kind:"entity",entity:n}))},requestSolutionSwitch(n){ae.getState().activeSolution?.id!==n.id&&(Xo()?(sn(D.getState()),e({pendingSwitch:{kind:"solution",solution:n}})):ui({kind:"solution",solution:n}))},resolveSwitch(n){const{pendingSwitch:o,target:s,pending:i}=t();if(o){if(n==="cancel"){e({pendingSwitch:null});return}n==="keep"&&!sn(D.getState())||(n==="discard"&&s&&!i&&hs(s),e({pendingSwitch:null,target:null,pending:null,pendingBaselineChanged:!1,saveFailed:!1}),qx(),ui(o))}},releaseForConnectionChange(){const n=Xo(),o=n?sn(D.getState()):!1;return un=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null}),{hadChanges:n,kept:o}}})),uu=e=>e?.trim().toLowerCase()==="production",UR=e=>uu(e),VR=(e,t)=>t.trim()!==""&&e.trim().toLowerCase()===t.trim().toLowerCase(),Hx=pe({root:{display:"inline-flex",alignItems:"center",gap:f.spacingHorizontalXS,minWidth:0,borderRadius:f.borderRadiusMedium,":focus-visible":{outline:`2px solid ${f.colorStrokeFocus2}`,outlineOffset:"2px"}},prefix:{color:f.colorNeutralForeground3},name:{maxWidth:"180px"},nameBelow1200:{display:"inline-flex",minWidth:0,"@media (max-width: 1200px)":{display:"none"}}});function Wx({prefix:e,compactBelow:t}){const n=Hx(),o=ae(r=>r.connectionName),s=ae(r=>r.connectionUrl),i=ae(r=>r.environment);if(!o&&!s)return null;const l=uu(i);return a.jsx(he,{content:s||o,relationship:"description",children:a.jsxs("span",{"data-testid":"environment-badge",className:n.root,tabIndex:0,children:[e&&a.jsx(X,{size:200,wrap:!1,className:n.prefix,children:e}),a.jsx("span",{className:t?n.nameBelow1200:void 0,children:a.jsx(X,{size:200,weight:"semibold",truncate:!0,wrap:!1,className:n.name,children:o||s})}),i&&a.jsx(xe,{size:"medium",appearance:l?"filled":"tint",color:l?"warning":"informative",children:i})]})})}const aa=en()(e=>({managed:{},setManaged:t=>e({managed:Object.fromEntries(t.map(n=>[n.id,n]))})})),mu=new Set(["label","labeltext","tabname","tabheading","title","tooltip","tooltiptitle","tooltipdescription","alt","button","tab","group","flyout","menu","name","text","caption"]),Gx=/^([A-Za-z_$][\w$]*(\.[\w$!{}-]+){2,}|[A-Z][\w$]*\.[\w$!{}-]+)$/,Ux=/^(Mscrm|Ribbon)(_[A-Za-z0-9]+){2,}$/,Vx=/^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)+$/,Xx=/^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*){2,}$/,Kx=/(?:ImageButtonText|ButtonText|ButtonLabel|ToolTipDescription|ToolTipTitle|ToolTip|Tooltip|LabelText|Label|Text|Title|Caption)$/;function ml(e){return e.replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").trim()}function pu(e,t=!1){if(t&&Xx.test(e)){const i=e.replace(Kx,"");return ml(i||e)}const n=Gx.test(e)?".":Ux.test(e)||t&&Vx.test(e)?"_":void 0;if(!n)return;const s=e.split(n).filter(i=>i&&!mu.has(i.toLowerCase())).at(-1);if(!(!s||/^(Mscrm|Ribbon|\{!EntityLogicalName\})$/i.test(s)))return ml(s)}function vt(e,t){const n=t?.trim();if(n&&n!==e)return n;const o=e.split(".").at(-1)??"";return mu.has(o.toLowerCase())?e:pu(e)??e}function Yx(e,t){return e.titles.find(n=>n.languageCode===t)?.description??e.titles.find(n=>n.languageCode===1033)?.description??e.titles[0]?.description}const pl=/^\$(Resources(\([^)]*\))?|LocLabels):/,Jx=[[/\{!EntityPluralDisplayName\}/g,"‹entity name, plural›"],[/\{!EntityDisplayName\}/g,"‹entity name›"]];function Zx(e){return Jx.reduce((t,[n,o])=>t.replace(n,o),e)}function Qx(e,t,n,o,s){const i=ev(e,t,n,o,s);return i&&Zx(i)}function ev(e,t,n,o,s){const i=Ve(e,t,n);if(!i)return i;const r=s!==void 0&&Ve(s,t,n)===(e??"")?s:e??"";if(!pl.test(r))return i;const c=o[i];if(c)return Yx(c,n)??i;const d=i===r.replace(pl,"");return pu(i,d)??i}function Be(){const e=aa(n=>n.managed),t=D(n=>n.baseLanguageCode);return B.useCallback((n,o,s,i)=>Qx(n,o,s??t??1033,e,i),[e,t])}const fu="Unified Interface has no visible tabs: this tab's buttons appear in the entity's command bar (or its overflow menu) wherever the tab's display rule applies.",eo=(e,t)=>JSON.stringify(e)===JSON.stringify(t),tv=e=>[e.icon,e.image16,e.image32].some(t=>!!t&&t.startsWith("$webresource:")),nv=e=>!!e.source&&Ga(e)===e.source.modernImage&&(e.source.modernImage!==void 0||!e.icon),ov=/^\$LocLabels:(.+)$/,qt=e=>e?ov.exec(e)?.[1]??null:null,sv=/^\s*<(EnableRule|DisplayRule)\b[^>]*?\sId="([^"]+)"/,to=e=>new Set(e??[]);function iv(e){const t=[];for(const n of Object.values(e.source?.attributes??{})){const o=qt(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 fl(e){return(e.menu?.sections??[]).map(t=>({id:t.id,title:t.title??"",sequence:t.sequence,displayMode:t.displayMode??"",controlsId:t.controlsId}))}function av(e){const t=[],n=[],o=[],s=[],i=[],l=[],r=[],c=[],d=[],u=[],m=new Map,p=(F,L)=>{const G=qt(F);G&&m.set(G,new Set([...m.get(G)??[],L]))};for(const{baseline:F}of e.locations)for(const L of F.tabs){p(L.label,L.id);for(const G of L.groups){p(G.label,G.id);for(const H of je(G))for(const te of Object.values(H.source?.attributes??{}))p(te,H.id)}}const h=new Set([...(e.locLabels??[]).map(F=>F.id),...to(e.layer?.locLabelIds)]);let b=!1;const g=new Set,x=to(e.layer?.containerIds),y=to(e.layer?.locLabelIds),S=new Set,C=new Set,R=new Map,M=new Map,I=[],$=new Set(e.locations.flatMap(({current:F})=>Array.from(It(F).values(),L=>L.button.id))),T=(F,L,G,H)=>{const te=qt(G);if(x.has(L)&&te&&y.has(te)&&!qt(H)&&H.trim())if([...m.get(te)??[]].some(P=>P!==L)){let P=`${L}.Title`;for(let K=2;P===te||h.has(P);K++)P=`${L}.Title${K}`;h.add(P),u.push({id:P,text:H,containerId:L,newLabel:!0})}else u.push({id:te,text:H,containerId:L});else t.push(`Renaming ${F} ${L} — only tabs and groups your unmanaged customizations add (with a translatable title) can be renamed`)};for(const{current:F,baseline:L}of e.locations){const G=ly(F,L);G.newButtons+G.overriddenButtons+G.hiddenButtons+G.newTabs+G.newGroups>0&&(b=!0),G.scalingChanges>0&&t.push(`Scaling changes on ${F.location} (not supported yet)`);const H=Sd(F,L);t.push(...H.problems),n.push(...H.warnings);const te=to(e.layer?.scalingStepIds);for(const[V,U]of Object.entries(L.scalingByTab??{})){const oe=F.tabs.find(me=>me.id===V),se=[...U.maxSizes.filter(me=>te.has(me.id)).map(me=>({...me,kind:"MaxSize"})),...U.scales.filter(me=>te.has(me.id)).map(me=>({...me,kind:"Scale"})),...(oe?.groups??[]).map(me=>H.steps.get(me.id)).filter(me=>!!me).map(me=>({...me,kind:"MaxSize"}))];if(se.length===0)continue;const Te=od(V,{maxSizes:U.maxSizes.filter(me=>!te.has(me.id)).map(me=>me.sequence),scales:U.scales.filter(me=>!te.has(me.id)).map(me=>me.sequence)},se);n.push(...Te.changes.map(Bb)),t.push(...Te.problems)}const P=It(F),K=It(L);for(const{button:V}of P.values())for(const U of ed(V))g.add(U);for(const[V,{button:U,menu:oe}]of P){const se=iv(U);se.forEach(ze=>S.add(ze));const Te=K.get(V)?.button,me=!Te||_i(Te,U);me&&oe&&!_a.includes(U.kind??"button")&&t.push(`Menu item "${U.label}" (${U.id}) is a ${$n[U.kind]??U.kind} — a menu can hold buttons and flyouts only; change its Kind`);for(const ze of[Is(U.id),js(U.id),$s(U.id)])me?C.add(ze):se.includes(ze)||R.set(ze,U);me&&se.forEach(ze=>C.add(ze))}for(const[V,U]of K){const oe=U.button.id,se=P.get(V);if(!se){if(U.menu&&$.has(oe)&&$.has(U.menu.parentId)&&U.button.origin!=="unmanaged"){t.push(`Moving the menu of ${U.menu.parentId} to another location — its item "${U.button.label}" (${oe}) comes from another solution and can't be moved with it; move the flyout back`);continue}if(ut(U.button.kind)&&$.has(oe)&&/<Menu[\s>/]/.test(U.button.source?.xml??"")){t.push(`Moving the <${$n[U.button.kind]}> "${U.button.label}" (${oe}) to another location — its menu may hold items of other solutions; move it within its location instead`);continue}dn(U.button)?o.push(oe):t.push(`Removing "${U.button.label}" (${oe}) — only your own unmanaged buttons can be deleted; hide it instead`);continue}U.button.hidden&&!se.button.hidden&&s.push(oe),(se.button.kind??"button")!==(U.button.kind??"button")&&t.push(`Changing the kind of "${se.button.label}" (${oe}) — not supported yet`);const Te=_i(U.button,se.button);Te&&ut(se.button.kind)&&t.push(`Editing the <${$n[se.button.kind]}> "${se.button.label}" (${oe}) — CBS shows it read-only; it can be hidden, or moved and deleted when it's your own`),Te&&(Tn(se.button.kind)||se.button.menu)&&U.button.origin!=="unmanaged"&&t.push(`Editing the flyout / split button "${se.button.label}" (${oe}) itself — only your own can be edited; its menu items can be edited, hidden or added to`),eo(fl(U.button),fl(se.button))||t.push(`Adding, removing or changing menu sections of "${se.button.label}" (${oe}) — not supported yet for an existing menu; add, edit or remove its items instead`),(se.button.icon??"")!==(U.button.icon??"")&&!tv(se.button)&&!nv(se.button)&&t.push(`Changing the icon of "${se.button.label}" (${oe}) to a built-in icon — not supported yet; choose an SVG web resource`),((se.menu||U.menu?se.menu?.controlsId!==U.menu?.controlsId:se.groupId!==U.groupId)||se.button.sequence!==U.button.sequence)&&(U.button.origin==="unmanaged"?l.push({id:oe,groupId:se.groupId,sequence:se.button.sequence,...se.menu?{controlsId:se.menu.controlsId}:{}}):t.push(`Moving or re-ordering "${se.button.label}" (${oe}) — only your own unmanaged buttons, and copies made with "Customise button", can be moved; undo the move, then hide it and add a new button instead`))}for(const[V,U]of P){if(K.has(V))continue;M.has(U.button.id)||M.set(U.button.id,{groupId:U.groupId,sequence:U.button.sequence,...U.menu?{controlsId:U.menu.controlsId}:{}});const oe=fd(U.button.source?.attributes.PopulateDynamically);Tn(U.button.kind)&&!oe&&!pn(U.button).some(se=>!se.hidden)&&I.push({id:U.button.id,label:U.button.label})}const ue=new Map(L.tabs.flatMap(V=>V.groups.map(U=>[U.id,U]))),Me=new Map(L.tabs.map(V=>[V.id,V])),Pe=L.tabs.map(V=>V.id).filter(V=>F.tabs.some(U=>U.id===V)),ot=F.tabs.map(V=>V.id).filter(V=>Me.has(V)),Ee=V=>!x.has(V),Fe=Pe.filter(Ee),Le=ot.filter(Ee).find((V,U)=>V!==Fe[U]);if(Le){const V=F.tabs.find(U=>U.id===Le);t.push(e.layer?`Reordering tab "${V.label}" (${V.id}) — only tabs your customizations add can be reordered; drag it back`:`Reordering tab "${V.label}" (${V.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 V of F.tabs){const U=Me.get(V.id);U&&x.has(V.id)&&U.sequence!==V.sequence&&c.push({id:V.id,sequence:V.sequence})}for(const V of F.tabs){const U=Me.get(V.id);if(U)for(const oe of V.groups){const se=U.groups.find(Te=>Te.id===oe.id);se&&x.has(oe.id)&&se.sequence!==oe.sequence&&d.push({id:oe.id,sequence:oe.sequence})}}const at=new Set(F.tabs.map(V=>V.id)),Gn=new Set(F.tabs.flatMap(V=>V.groups.map(U=>U.id)));for(const V of F.tabs){const U=qt(V.label);U&&S.add(U);const oe=Me.get(V.id);if(!oe){C.add(`${V.id}.Title`);const se=qt(V.source?.titleToken);se&&C.add(se),V.commandId&&g.add(V.commandId),F.location==="Application"&&(V.tabDisplayRules??[]).length===0&&t.push(`New tab ${V.id} has no tab display rule, so it would never be shown — add one in Tab rules`),n.push(`New tab "${V.label}" (${V.id}): ${fu}`)}oe&&oe.label!==V.label&&T("tab",V.id,oe.label,V.label),oe&&!eo(oe.tabDisplayRules??[],V.tabDisplayRules??[])&&(x.has(V.id)?V.commandId?r.push(V.id):t.push(`Changing the display rules of tab ${V.id} — the tab has no Command to attach them to`):t.push(`Changing the display rules of tab ${V.id} — only tabs your unmanaged customizations add can be changed`));for(const se of V.groups){const Te=qt(se.label);Te&&S.add(Te);const me=ue.get(se.id);if(!me){C.add(`${se.id}.Title`);const ze=se.source?.attributes.Command;ze&&g.add(ze);const gn=qt(se.source?.titleToken);gn&&C.add(gn)}me&&me.template!==se.template&&t.push(`Re-templating group ${se.id} — not supported yet`),me&&me.label!==se.label&&T("group",se.id,me.label,se.label)}}const z=(V,U)=>t.push(`Removing ${V} ${U} — only tabs and groups your unmanaged customizations add can be deleted; hide it instead`);for(const V of L.tabs){if(!at.has(V.id)){x.has(V.id)?i.push(V.id):z("tab",V.id);continue}for(const U of V.groups)Gn.has(U.id)||(x.has(U.id)?i.push(U.id):z("group",U.id))}}for(let F=o.length-1;F>=0;F--){const L=M.get(o[F]);L&&(l.push({id:o[F],...L}),o.splice(F,1))}for(const F of e.deletedOrphans??[]){for(const L of F.deleteControlIds)o.includes(L)||o.push(L);for(const L of F.deleteContainerIds)i.includes(L)||i.push(L)}for(const F of I)l.some(L=>L.id===F.id)||t.push(`New flyout / split button "${F.label}" has no menu items — add at least one item to its menu`);const v=e.layer?.commandIds?to(e.layer.commandIds):null,O=new Set(e.uncustomisedCommandIds??[]),A=[...O].filter(F=>v?v.has(F):g.has(F)&&!e.excludeCommandIds?.has(F));for(const F of A)e.layer?.commandRefIds&&!Pa(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(Ye)&&g.has(Ye)&&t.push(`Uncustomising ${Ye} — 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??[])g.delete(F);const E=new Set(e.customisedCommandIds??[]),w=new Map(e.baselineCommands.map(F=>[F.id,F])),k=e.commands.filter(F=>g.has(F.id)&&!O.has(F.id)&&(!w.has(F.id)||!eo(w.get(F.id),F)||E.has(F.id)&&!v?.has(F.id))).map(F=>F.id);for(const F of e.commands){if(!k.includes(F.id))continue;F.actions.some(G=>G.kind==="powerFx"||G.kind==="customApi")&&t.push(`Power Fx / Custom API action in command ${F.id} — classic ribbon commands can't run these; remove the action (#28)`);const L=F.id===Ye?ex(F):null;L&&t.push(L)}const N=new Set,j=new Set;for(const F of e.commands)if(!(!g.has(F.id)||O.has(F.id))){F.enableRules.forEach(L=>N.add(L)),F.displayRules.forEach(L=>j.add(L));for(const L of F.rawRuleRefs??[]){const G=sv.exec(L.xml);G&&(G[1]==="EnableRule"?N:j).add(G[2])}}const _=(F,L,G)=>{const H=new Map(L.map(te=>[te.id,te]));return F.filter(te=>G.has(te.id)&&(!H.has(te.id)||!eo(H.get(te.id),te))).map(te=>te.id)},W=_(e.enableRules,e.baselineEnableRules,N),ne=_(e.displayRules,e.baselineDisplayRules,j),le=[];if(e.locLabels&&e.baselineLocLabels){const F=new Map(e.baselineLocLabels.map(L=>[L.id,L]));for(const L of e.locLabels){const G=F.get(L.id);if(G&&eo(G,L)||C.has(L.id))continue;if(S.has(L.id)){y.has(L.id)?le.push(L.id):t.push(`Translations of label ${L.id} — it is defined by another solution; change the text in the properties pane instead`);continue}const H=R.get(L.id);H&&t.push(`Translations for "${H.label}" (${H.id}) — its text isn't a translatable label yet; change the text in the properties pane first, then add translations`)}}for(const{current:F,baseline:L}of e.locations){if(F.location!=="Application")continue;const G=F.tabs.find(K=>K.id===Ji);if(!G)continue;const H=L.tabs.find(K=>K.id===Ji),te=new Set(H?.groups.map(K=>K.id)??[]),P=new Map;for(const K of H?.groups??[])for(const ue of je(K))P.set(ue.id,K.id);for(const K of G.groups)if(K.id!==Ed){te.has(K.id)||n.push(`New group "${K.label}" (${K.id}) on GlobalTab: ${Qr}`);for(const ue of je(K))P.get(ue.id)!==K.id&&n.push(`"${ue.label}" (${ue.id}) in ${K.id}: ${Qr}`)}}const ce=(e.unhiddenLayerHideIds??[]).filter(F=>!s.includes(F));return{hasChanges:b||k.length>0||A.length>0||W.length>0||ne.length>0||o.length>0||s.length>0||ce.length>0||i.length>0||l.length>0||le.length>0||r.length>0||c.length>0||d.length>0||u.length>0,editedCommandIds:k,uncustomisedCommandIds:A,editedEnableRuleIds:W,editedDisplayRuleIds:ne,deletedButtonIds:o,unhiddenButtonIds:[...s,...ce],deletedContainerIds:i,movedButtons:l,editedLocLabelIds:le,editedTabIds:r,resequencedTabs:c,resequencedGroups:d,renamedLabels:u,unsupported:[...new Set(t)],warnings:[...new Set(n)]}}const hl=["HomepageGrid","Form","SubGrid","Application"];function rv(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function lv(e){if(e.includes("Application"))return"the application ribbon";const t=[...e].sort((n,o)=>hl.indexOf(n)-hl.indexOf(o));return`the ${rv(t.map(n=>Jt[n].label.toLowerCase()))}`}function cv(e){const{plan:t,buttonName:n,titleOf:o}=e,s=new Map,i=(x,y,S,C={})=>{const R=`${x}|${y}|${S}|${C.detail??""}`,M=s.get(R)??{change:{kind:x,action:y,name:S,...C.detail?{detail:C.detail}:{}},locations:[],preposition:C.preposition};C.location&&!M.locations.includes(C.location)&&M.locations.push(C.location),s.set(R,M)},l=new Map,r=new Map,c=new Map,d=new Map;for(const{current:x,baseline:y}of e.locations){for(const{button:S}of It(x).values())l.has(S.id)||l.set(S.id,{button:S,location:x.location});for(const{button:S}of It(y).values())r.has(S.id)||r.set(S.id,{button:S,location:y.location});for(const S of y.tabs){c.set(S.id,{kind:"tab",label:S.label,location:y.location});for(const C of S.groups)c.set(C.id,{kind:"group",label:C.label,location:y.location})}for(const S of x.tabs)d.set(S.id,{label:S.label,location:x.location})}const u=new Set(t.movedButtons.map(x=>x.id)),m=new Set,p=new Set;for(const{current:x,baseline:y}of e.locations){const S=x.location,C=new Map(y.tabs.map(I=>[I.id,I]));for(const I of x.tabs){const $=C.get(I.id);if(!$){i("new","Add tab",o(I.label),{location:S,preposition:"to"});continue}const T=new Set($.groups.map(v=>v.id));for(const v of I.groups)T.has(v.id)||i("new","Add group",o(v.label),{detail:`to tab “${o(I.label)}”`})}const R=qa(x,y),M=new Set(R.map(I=>I.entry.button.id));for(const{entry:I,change:$}of R){const{button:T}=I;if(u.has(T.id))continue;const v=n(T);$==="new"?(i("new","Add",v,{location:S,preposition:"to"}),T.commandId&&m.add(T.commandId)):$==="hide"?i("hide","Hide",v,{location:S,preposition:"on"}):i("change","Change",v,{location:S,preposition:"on"})}for(const{button:I}of It(x).values())I.commandId&&!M.has(I.id)&&p.add(I.commandId)}for(const x of t.unhiddenButtonIds){const y=l.get(x)??r.get(x);i("show","Show",y?n(y.button):x,{location:y?.location,preposition:"again on"})}for(const x of t.movedButtons){const y=l.get(x.id),S=r.get(x.id),C=y&&S&&y.location!==S.location;i("move","Move",y?n(y.button):x.id,{location:C?y.location:void 0,preposition:"to"})}for(const x of t.deletedButtonIds){const y=r.get(x);i("delete","Delete",y?n(y.button):x,{location:y?.location,preposition:"from"})}for(const x of t.deletedContainerIds){const y=c.get(x);i("delete",y?.kind==="group"?"Delete group":"Delete tab",y?o(y.label):x,{location:y?.location,preposition:"from"})}for(const x of t.renamedLabels){const y=c.get(x.containerId);i("change",y?.kind==="group"?"Rename group":"Rename tab",y?o(y.label):x.containerId,{detail:`to “${x.text}”`})}for(const x of t.resequencedTabs){const y=d.get(x.id);i("move","Move tab",y?o(y.label):x.id,{location:y?.location,preposition:"on"})}for(const x of t.resequencedGroups??[]){const y=c.get(x.id);i("move","Move group",y?o(y.label):x.id,{location:y?.location,preposition:"on"})}for(const x of t.editedTabIds){const y=d.get(x);i("change","Change the display rules of tab",y?o(y.label):x)}const h=new Set(e.baselineCommands.map(x=>x.id));for(const x of t.editedCommandIds)h.has(x)?i("change","Change command",x):(!m.has(x)||p.has(x))&&i("new","Add command",x);for(const x of t.uncustomisedCommandIds)i("change","Remove your copy of command",x,{detail:"(the original applies again)"});const b=new Set(e.baselineEnableRuleIds),g=new Set(e.baselineDisplayRuleIds);for(const x of t.editedEnableRuleIds)b.has(x)?i("change","Change enable rule",x):i("new","Add enable rule",x);for(const x of t.editedDisplayRuleIds)g.has(x)?i("change","Change display rule",x):i("new","Add display rule",x);for(const x of t.editedLocLabelIds)i("change","Change the translations of",x);return[...s.values()].map(({change:x,locations:y,preposition:S})=>y.length>0&&S?{...x,detail:`${S} ${lv(y)}`}:x)}const mi=["HomepageGrid","SubGrid","Form"];function dv(){const e=D(v=>v.ribbons),t=D(v=>v.baseline),n=D(v=>v.commands),o=D(v=>v.displayRules),s=D(v=>v.enableRules),i=D(v=>v.baselineCommands),l=D(v=>v.baselineEnableRules),r=D(v=>v.baselineDisplayRules),c=D(v=>v.locLabels),d=D(v=>v.baselineLocLabels),u=D(v=>v.layers),m=D(v=>v.pendingUnhides),p=D(v=>v.orphans),h=D(v=>v.pendingOrphanDeletes),b=D(v=>v.customisedCommandIds),g=D(v=>v.uncustomisedCommandIds),x=ae(v=>v.activeEntity),y=ae(v=>v.solutionRibbonComponentIds),S=Be(),C=Array.isArray(y)&&y.length>0,R=B.useCallback((v,O,A)=>av({locations:v.map(E=>({current:e[E],baseline:t[E]})),excludeCommandIds:A,locLabels:c,baselineLocLabels:d,layer:u[O]??void 0,unhiddenLayerHideIds:m[O],deletedOrphans:p[O].filter(E=>h[O].includes(E.id)),customisedCommandIds:b,uncustomisedCommandIds:g[O],commands:n,baselineCommands:i,enableRules:s,baselineEnableRules:l,displayRules:o,baselineDisplayRules:r}),[e,t,n,i,s,l,o,r,c,d,u,m,p,h,b,g]),M=B.useMemo(()=>x?R(mi,"entity"):null,[x,R]),I=B.useMemo(()=>{const v=new Set;if(x)for(const O of mi)for(const A of e[O].tabs)for(const E of A.groups)for(const w of je(E))w.commandId&&v.add(w.commandId);return R(["Application"],"application",v)},[R,x,e]),$=I.hasChanges&&C,T=B.useMemo(()=>{const v=(O,A)=>cv({locations:O.map(E=>({current:e[E],baseline:t[E]})),plan:A,baselineCommands:i,baselineEnableRuleIds:l.map(E=>E.id),baselineDisplayRuleIds:r.map(E=>E.id),buttonName:E=>S(E.label,c,void 0,E.source?.labelToken)||E.id,titleOf:E=>S(E,c)||E});return[...M?.hasChanges?v(mi,M):[],...$?v(["Application"],I):[]]},[M,I,$,e,t,i,l,r,c,S]);return{entityPlan:M,appPlan:I,solutionSupportsAppRibbon:C,includeApplicationRibbon:$,scopes:[...x&&M?.hasChanges?[x.logicalName]:[],...$?["Application ribbon"]:[]],unsupported:[...M?.unsupported??[],...I.unsupported],warnings:[...M?.warnings??[],...I.warnings],changes:T}}function hu(){const e=Ie(i=>i.target!==null),{changes:t,unsupported:n}=dv(),o=D(i=>i.mutationsSincePublish>0),s=D(i=>i.mutationsSincePublish===0&&mo(i));return{count:t.length,canPublish:e&&(t.length>0||n.length>0||o||s)}}const uv=pe({combobox:{minWidth:"140px",width:"220px",flexShrink:1,"@media (max-width: 1200px)":{width:"180px"}},input:{minWidth:0,width:"100%"},listbox:{maxHeight:"min(480px, 70vh)"},option:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS,minWidth:0,width:"100%"},names:{display:"flex",flexDirection:"column",minWidth:0,flex:1},ellipsis:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},logical:{fontFamily:f.fontFamilyMonospace,color:f.colorNeutralForeground3},muted:{color:f.colorNeutralForeground3,flexShrink:0},empty:{whiteSpace:"normal"}}),mv="__none";function pv(e,t){const n=t.trim().toLowerCase();return!n||e.displayName.toLowerCase().includes(n)||e.logicalName.toLowerCase().includes(n)}function fv(){const e=uv(),t=ae($=>$.entities),n=ae($=>$.activeEntity),o=ae($=>$.activeSolution),s=ae($=>$.solutionEntityIds),i=Ie($=>$.requestEntitySwitch),l=J($=>$.tablePickerOpen),r=J($=>$.setTablePickerOpen),{count:c}=hu(),[d,u]=B.useState(null),m=B.useRef(null),p=!!o&&s===null,h=!o||p,b=l&&!h;B.useEffect(()=>{b&&document.activeElement!==m.current&&m.current?.focus()},[b]);const g=B.useMemo(()=>{const $=new Set;if(!l)return $;for(const T of t)Lx(du(T.logicalName))&&$.add(T.logicalName);return $},[l,t]),x=t.filter($=>pv($,d??"")),y=x.filter($=>$.isCustomEntity),S=x.filter($=>!$.isCustomEntity),C=$=>{const T=$.logicalName===n?.logicalName,v=T?c:0;return a.jsx(Ti,{value:$.logicalName,text:$.displayName,children:a.jsxs("div",{className:e.option,children:[a.jsxs("div",{className:e.names,children:[a.jsx(X,{size:200,weight:T?"semibold":"regular",className:e.ellipsis,children:$.displayName}),a.jsx(X,{size:200,className:Ce(e.logical,e.ellipsis),children:$.logicalName})]}),v>0?a.jsxs(xe,{appearance:"tint",color:"brand",size:"medium",children:[v," change",v===1?"":"s"]}):!T&&g.has($.logicalName)&&a.jsx(xe,{appearance:"tint",color:"brand",size:"medium",children:"Draft"}),$.isManaged&&a.jsx(fn,{fontSize:12,className:e.muted,"aria-label":"Managed entity"})]})},$.logicalName)},R=t.length===0&&o?`No entities in ${o.friendlyName}. Add one in the maker portal (Solutions › ${o.friendlyName} › Add existing › Table) and reload.`:"No entities match.",M=($,T)=>{if(T.optionValue===void 0||$.type==="keydown"&&$.key==="Tab")return;u(null);const v=t.find(O=>O.logicalName===T.optionValue);v&&v.logicalName!==n?.logicalName&&i(v)},I=o?p?"Loading entities…":"Choose entity":"Choose a solution first";return a.jsxs(ya,{ref:m,"aria-label":"Entity",className:e.combobox,input:{className:e.input},listbox:{className:e.listbox},placeholder:I,disabled:h,freeform:!0,value:d??n?.displayName??"",selectedOptions:n?[n.logicalName]:[],open:b,onOpenChange:($,T)=>{r(T.open),T.open||u(null)},onChange:$=>{u($.target.value),l||r(!0)},onOptionSelect:M,onFocus:$=>$.currentTarget.select(),children:[y.length>0&&a.jsx(vr,{label:`Custom (${y.length})`,children:y.map(C)}),S.length>0&&a.jsx(vr,{label:`Standard (${S.length})`,children:S.map(C)}),x.length===0&&a.jsx(Ti,{value:mv,text:"",disabled:!0,children:a.jsx("span",{className:e.empty,children:R})})]})}const pi={small:440,medium:600,large:960},gu=pe({surface:{width:"calc(100vw - 32px)",maxHeight:"calc(100vh - 48px)",display:"flex",flexDirection:"column"},small:{maxWidth:`${pi.small}px`},medium:{maxWidth:`${pi.medium}px`},large:{maxWidth:`${pi.large}px`},body:{maxHeight:"calc(100vh - 96px)",minHeight:0},content:{minHeight:0,overflowY:"auto"},wholeRow:{gridColumnStart:1},danger:{backgroundColor:f.colorStatusDangerBackground3,color:f.colorNeutralForegroundOnBrand,":hover":{backgroundColor:f.colorStatusDangerBackground3Hover,color:f.colorNeutralForegroundOnBrand},":hover:active":{backgroundColor:f.colorStatusDangerBackground3Pressed,color:f.colorNeutralForegroundOnBrand}}}),hn=({open:e,onOpenChange:t,title:n,size:o="medium",modalType:s="modal",actions:i,startActions:l,children:r,contentClassName:c})=>{const d=gu(),u=s!=="alert",m=B.useRef(null);return B.useEffect(()=>{if(!e)return;const p=m.current?.querySelector("[data-autofocus]");p?.focus(),(p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement)&&p.select()},[e]),a.jsx(Xm,{modalType:s,open:e,onOpenChange:(p,h)=>t(h.open),children:a.jsx(Km,{ref:m,className:Ce(d.surface,d[o]),children:a.jsxs(Ym,{className:d.body,children:[a.jsx(Jm,{action:u?a.jsx(Zm,{action:"close",children:a.jsx(Y,{appearance:"subtle","aria-label":"Close",icon:a.jsx(mn,{})})}):void 0,children:n}),a.jsx(Qm,{className:Ce(d.content,c),children:r}),(i||l)&&a.jsxs(a.Fragment,{children:[l&&a.jsx(Sr,{position:"start",children:l}),a.jsx(Sr,{position:"end",className:l?void 0:d.wholeRow,children:i})]})]})})})},sr=({className:e,children:t,...n})=>{const o=gu();return a.jsx(Y,{...n,appearance:"primary",className:Ce(o.danger,e),children:t})},gs=e=>e instanceof Error?e.message:String(e),hv=3e3;function gv(e,t){let n;const o=new Promise((s,i)=>{n=setTimeout(()=>i(new Error(`no answer in ${t/1e3} s`)),t)});return Promise.race([e,o]).finally(()=>clearTimeout(n))}async function Ps(e){const t=[],n=window.toolboxAPI?.utils?.copyToClipboard;if(n)try{return await gv(n(e),hv),{ok:!0}}catch(o){t.push(`host: ${gs(o)}`)}if(navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0}}catch(o){t.push(`browser: ${gs(o)}`)}return{ok:!1,error:t.join("; ")||"no clipboard is available here"}}async function XR(e,t,n){const o=window.toolboxAPI?.fileSystem?.saveFile;if(o)try{const s=await o(e,t,n);return s?{ok:!0,path:s}:{ok:!1,canceled:!0}}catch(s){return{ok:!1,error:gs(s)}}try{const s=URL.createObjectURL(new Blob([t],{type:"application/xml"})),i=document.createElement("a");return i.href=s,i.download=e,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4),{ok:!0}}catch(s){return{ok:!1,error:gs(s)}}}const ra=48,Fs=pe({root:{height:`${ra}px`,display:"flex",alignItems:"center",gap:f.spacingHorizontalS,padding:`0 ${f.spacingHorizontalM}`,backgroundColor:f.colorNeutralBackground3,borderBottom:`1px solid ${f.colorNeutralStroke2}`,flexShrink:0,minWidth:0},brand:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS,flexShrink:0},brandMark:{width:"24px",height:"24px",borderRadius:f.borderRadiusMedium,backgroundColor:f.colorBrandBackground,color:f.colorNeutralForegroundOnBrand,display:"flex",alignItems:"center",justifyContent:"center"},brandTitle:{whiteSpace:"nowrap","@media (max-width: 1100px)":{display:"none"}},divider:{width:"1px",alignSelf:"stretch",margin:`${f.spacingVerticalM} 0`,backgroundColor:f.colorNeutralStroke2,flexShrink:0},solutionTrigger:{minWidth:0,maxWidth:"420px",flexShrink:1,justifyContent:"flex-start",columnGap:f.spacingHorizontalSNudge,"@media (max-width: 1200px)":{maxWidth:"300px"}},chipBadge:{flexShrink:0},wideOnly:{"@media (max-width: 1200px)":{display:"none"}},pickerFooter:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:f.spacingHorizontalS,marginTop:f.spacingVerticalXS},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:f.colorNeutralForeground3,flexShrink:0},solutionPickerSurface:{padding:f.spacingHorizontalM,width:"380px",maxWidth:"calc(100vw - 32px)",display:"flex",flexDirection:"column",gap:f.spacingVerticalS},optionText:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},search:{flexShrink:0,color:f.colorNeutralForeground3,fontWeight:f.fontWeightRegular},searchText:{"@media (max-width: 1180px)":{display:"none"}},kbd:{marginLeft:f.spacingHorizontalS,padding:"0 4px",border:`1px solid ${f.colorNeutralStroke2}`,borderRadius:f.borderRadiusSmall,fontSize:f.fontSizeBase200,"@media (max-width: 1180px)":{display:"none"}},toolsOverflow:{flex:"1 1 0",minWidth:"40px",overflow:"hidden",display:"flex",justifyContent:"flex-end"},toolbar:{flexWrap:"nowrap",minWidth:0},overflowSlot:{display:"inline-flex"},publish:{flexShrink:0},helpBody:{display:"flex",flexDirection:"column",gap:f.spacingVerticalS,maxWidth:"320px"},shortcuts:{display:"grid",gridTemplateColumns:"auto 1fr",columnGap:f.spacingHorizontalM,rowGap:f.spacingVerticalXXS,margin:0,fontSize:f.fontSizeBase200,lineHeight:f.lineHeightBase200,"& dt":{fontWeight:f.fontWeightSemibold,whiteSpace:"nowrap"},"& dd":{margin:0}}}),bv=[["Ctrl+K","Search"],["Ctrl+S","Publish"],["Ctrl+Z / Ctrl+Y","Undo / redo"],["Ctrl+D","Duplicate"],["Ctrl+X / Ctrl+V","Move a button"]];function yv(){const e=Fs(),t=J(d=>d.openBulkPublish),n=J(d=>d.setCommandPaletteOpen),{count:o,canPublish:s}=hu(),[i,l]=B.useState(!1),r=o>0?`Publish ${o} change${o===1?"":"s"}`:"Publish",c=a.jsx(Y,{appearance:"primary",icon:a.jsx(ep,{}),className:e.publish,disabledFocusable:!s,onClick:s?t:void 0,children:s&&o===0?"Publish changes":r});return a.jsxs("header",{className:e.root,children:[a.jsxs("div",{className:e.brand,children:[a.jsx("div",{className:e.brandMark,"aria-hidden":"true",children:a.jsx(X,{size:100,weight:"bold",children:"CBS"})}),a.jsx(X,{weight:"semibold",size:300,className:e.brandTitle,children:"Command Bar Studio"})]}),a.jsx("div",{className:e.divider}),a.jsx(Wx,{compactBelow:1200}),a.jsx("div",{className:e.divider}),a.jsx(Sv,{}),a.jsx(fv,{}),a.jsx(Rv,{onHelp:()=>l(!0)}),a.jsx(he,{content:"Search buttons, commands, rules (Ctrl+K)",relationship:"label",children:a.jsxs(Y,{appearance:"outline",icon:a.jsx(sc,{}),className:e.search,onClick:()=>n(!0),children:[a.jsx("span",{className:e.searchText,children:"Search"}),a.jsx("span",{className:e.kbd,"aria-hidden":"true",children:"Ctrl K"})]})}),s?c:a.jsx(he,{content:"No unpublished changes on this entity. Make a change and it shows here as Publish 1 change.",relationship:"description",children:c}),a.jsx(hn,{open:i,onOpenChange:l,title:"Command Bar Studio",size:"small",children:a.jsx(xu,{})})]})}function xv(e){return(e.publisherPrefix||"new")==="new"||/^defaultpublisher/i.test(e.publisherUniqueName??"")}function vv(e){const t=e.friendlyName||e.uniqueName,n=(e.version??"").split(".").slice(0,3).join(".");return n?`${t} v${n}`:t}function Sv(){const e=Fs(),t=ae(v=>v.solutions),n=ae(v=>v.activeSolution),o=ae(v=>v.connectionUrl),s=Ie(v=>v.requestSolutionSwitch),i=J(v=>v.solutionPickerOpen),l=J(v=>v.setSolutionPickerOpen),r=J(v=>v.scopeTipDismissed.includes(o)),c=J(v=>v.dismissScopeTip),[d,u]=B.useState(""),m=B.useRef(null),[p,h]=B.useState(null),b=ic(m,h),g=()=>requestAnimationFrame(()=>{const v=document.activeElement;(!v||v===document.body)&&m.current?.focus()}),x=()=>{c(o),g()},y=B.useMemo(()=>t.filter(v=>!v.isManaged).map(v=>({value:v.id,children:v.friendlyName||v.uniqueName,searchText:`${v.friendlyName??""} ${v.uniqueName??""} ${v.version??""}`.toLowerCase(),solution:v})),[t]),S=ac(d,y,{optionToText:v=>v.searchText,filter:(v,O)=>v.includes(O.toLowerCase()),optionToReactKey:v=>v.value,renderOption:v=>a.jsx(Ti,{value:v.value,text:v.solution.friendlyName??v.solution.uniqueName,children:a.jsxs("div",{className:e.optionText,children:[a.jsx(X,{size:200,weight:"semibold",children:v.solution.friendlyName||v.solution.uniqueName}),a.jsxs(X,{size:200,className:e.muted,children:[v.solution.uniqueName," · v",v.solution.version,v.solution.publisherName?` · ${v.solution.publisherName}`:""]})]})},v.value),noOptionsMessage:t.length===0?"Loading solutions…":y.length===0?"No solutions found":`No solutions match "${d}"`}),C=(v,O)=>{const A=t.find(E=>E.id===O.optionValue);A&&(s(A),l(!1),u(""),requestAnimationFrame(()=>{const E=document.activeElement;(!E||E===document.body)&&m.current?.focus()}))},R=n?vv(n):"",M=n?xv(n):!1,I=n?.publisherPrefix||"new",$=n?`${n.friendlyName||n.uniqueName} (${n.uniqueName}) v${n.version}${n.publisherName?` · ${n.publisherName}`:""}${M?". Imports will land under the org's default publisher.":""}`:"Choose the solution your changes are saved to",T=!n&&!!o&&!r&&!i&&!!p;return a.jsxs(a.Fragment,{children:[a.jsxs(xa,{open:i,onOpenChange:(v,O)=>l(O.open),positioning:"below-start",trapFocus:!0,withArrow:!0,children:[a.jsx(va,{disableButtonEnhancement:!0,children:a.jsx(he,{content:$,relationship:"description",children:a.jsxs(Y,{ref:b,appearance:"outline",icon:a.jsx(op,{}),"aria-label":n?`Solution: ${R}`:"Choose scope",className:e.solutionTrigger,children:[n?a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:e.ellipsis,children:["Solution: ",R]}),a.jsx(xe,{appearance:"outline",size:"small",className:Ce(e.chipBadge,e.wideOnly),children:"Unmanaged"}),a.jsxs(xe,{appearance:"tint",size:"small",color:M?"warning":"informative",className:e.chipBadge,icon:M?a.jsx(tp,{}):void 0,children:[I,"_"]})]}):"Choose scope",a.jsx(np,{className:e.muted})]})})}),a.jsxs(Sa,{className:e.solutionPickerSurface,children:[a.jsx(X,{weight:"semibold",size:400,children:"Solution"}),a.jsx(qe,{label:"Unmanaged solution",children:a.jsx(ya,{placeholder:t.length===0?"Loading solutions…":"Search name, unique name or version…",value:d,onChange:v=>u(v.target.value),onOptionSelect:C,freeform:!0,clearable:!0,children:S})}),a.jsx(Ge,{className:e.muted,children:"Command Bar Studio edits one unmanaged solution at a time. Its entities appear in the entity picker."}),n&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsx(Et,{size:"small",info:M?`New ids are prefixed "${I}_", the org's default publisher: imports will land under it. To use your own prefix, create a solution in make.powerapps.com bound to your publisher.`:`New ids are prefixed "${I}_" (publisher ${n.publisherName||n.publisherUniqueName||I}).`,children:"Publisher prefix"}),a.jsxs(xe,{appearance:"tint",color:M?"warning":"informative",size:"medium",children:[I,"_"]})]}),a.jsxs("div",{className:e.pickerFooter,children:[a.jsx(Ge,{className:e.muted,children:"Changes apply right away."}),a.jsx(Y,{appearance:"primary",size:"small",onClick:()=>{l(!1),g()},children:"Done"})]})]})]}),T&&a.jsx(sp,{open:!0,onOpenChange:(v,O)=>{O.open||x()},positioning:{target:p,position:"below",align:"start"},children:a.jsxs(ip,{style:{maxWidth:320},children:[a.jsx(ap,{children:"Tip"}),a.jsxs(rp,{children:[a.jsx(lp,{children:"Choose where entities come from"}),"Pick the unmanaged solution whose command bars you want to edit. Its entities appear in the entity picker."]}),a.jsx(cp,{primary:{children:"Choose scope",onClick:()=>{c(o),l(!0)}},secondary:{children:"Got it",onClick:x}})]})})]})}async function wv(e,t){const n=`${e.replace(/\/$/,"")}/main.aspx?pagetype=entitylist&etn=${encodeURIComponent(t)}`;await window.toolboxAPI?.utils.openInConnectionBrowser(n,"primary")}function Cv(){const e=D(h=>h.past),t=D(h=>h.future),n=D(h=>h.undo),o=D(h=>h.redo),s=J(h=>h.openXmlDrawer),i=J(h=>h.openImportXml),l=J(h=>h.openDiffViewer),r=J(h=>h.rightPaneMode),c=J(h=>h.setRightPaneMode),d=J(h=>h.bottomCollapsed),u=J(h=>h.setBottomCollapsed),m=ae(h=>h.connectionUrl),p=ae(h=>h.activeEntity?.logicalName);return{canUndo:e.length>0,canRedo:t.length>0,undo:n,redo:o,viewXml:()=>s(Z.getState().location),importXml:()=>i(),compare:()=>l("compare"),canOpenInApp:!!(m&&p),openInApp:()=>m&&p?void wv(m,p):void 0,rightPaneMode:r,setRightPaneMode:c,bottomCollapsed:d,setBottomCollapsed:u}}const bu=e=>a.jsxs(a.Fragment,{children:[a.jsx(fe,{onClick:e.viewXml,children:"View XML"}),a.jsx(fe,{onClick:e.importXml,children:"Import XML…"}),a.jsx(fe,{onClick:e.compare,children:"Compare with published"})]});function la(e){return{checkedValues:{properties:[e.rightPaneMode],bottom:e.bottomCollapsed?[]:["show"]},onCheckedValueChange:(t,n)=>{n.name==="properties"&&e.setRightPaneMode(n.checkedItems[0]),n.name==="bottom"&&e.setBottomCollapsed(!n.checkedItems.includes("show"))}}}const yu=a.jsxs(a.Fragment,{children:[a.jsxs(mp,{children:[a.jsx(fo,{children:"Properties pane"}),a.jsx(jn,{name:"properties",value:"docked",children:"Docked"}),a.jsx(jn,{name:"properties",value:"floating",children:"Floating"}),a.jsx(jn,{name:"properties",value:"hidden",children:"Hidden"})]}),a.jsx(Mt,{}),a.jsx(lc,{name:"bottom",value:"show",children:"Show the bottom panel"})]});function Rv({onHelp:e}){const t=Fs(),n=Cv();return a.jsx(wa,{padding:40,children:a.jsx("div",{className:t.toolsOverflow,children:a.jsxs(dp,{"aria-label":"Tools",size:"small",className:t.toolbar,children:[a.jsx(Ht,{id:"undo",groupId:"history",children:a.jsx(he,{content:"Undo (Ctrl+Z)",relationship:"label",children:a.jsx(rn,{icon:a.jsx(Ca,{}),disabledFocusable:!n.canUndo,onClick:n.undo})})}),a.jsx(Ht,{id:"redo",groupId:"history",children:a.jsx(he,{content:"Redo (Ctrl+Y)",relationship:"label",children:a.jsx(rn,{icon:a.jsx(Ra,{}),disabledFocusable:!n.canRedo,onClick:n.redo})})}),a.jsx(up,{}),a.jsx(Ht,{id:"xml",children:a.jsx("span",{className:t.overflowSlot,children:a.jsxs(Je,{children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsxs(rn,{icon:a.jsx(Pn,{}),children:["XML ",a.jsx(dt,{fontSize:12})]})}),a.jsx(Qe,{children:a.jsx(et,{children:bu(n)})})]})})}),a.jsx(Ht,{id:"open",children:a.jsx(he,{content:"Open this entity in Dynamics 365",relationship:"label",children:a.jsx(rn,{icon:a.jsx(Ia,{}),disabledFocusable:!n.canOpenInApp,onClick:n.openInApp})})}),a.jsx(Ht,{id:"view",children:a.jsx("span",{className:t.overflowSlot,children:a.jsxs(Je,{...la(n),children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(he,{content:"View",relationship:"label",children:a.jsx(rn,{icon:a.jsx(rc,{})})})}),a.jsx(Qe,{children:a.jsx(et,{children:yu})})]})})}),a.jsx(Ht,{id:"help",children:a.jsx("span",{className:t.overflowSlot,children:a.jsx(jv,{})})}),a.jsx(Iv,{tools:n,onHelp:e})]})})})}function Iv({tools:e,onHelp:t}){const{ref:n,isOverflowing:o,overflowCount:s}=$a();return o?a.jsxs(Je,{...la(e),children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(he,{content:`More tools (${s})`,relationship:"label",children:a.jsx(rn,{ref:n,icon:a.jsx(xs,{})})})}),a.jsx(Qe,{children:a.jsxs(et,{children:[a.jsx(vn,{id:"undo",children:a.jsx(fe,{icon:a.jsx(Ca,{}),disabled:!e.canUndo,onClick:e.undo,secondaryContent:"Ctrl+Z",children:"Undo"})}),a.jsx(vn,{id:"redo",children:a.jsx(fe,{icon:a.jsx(Ra,{}),disabled:!e.canRedo,onClick:e.redo,secondaryContent:"Ctrl+Y",children:"Redo"})}),a.jsx(vn,{id:"xml",children:a.jsxs(Je,{children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(Pn,{}),children:"XML"})}),a.jsx(Qe,{children:a.jsx(et,{children:bu(e)})})]})}),a.jsx(vn,{id:"open",children:a.jsx(fe,{icon:a.jsx(Ia,{}),disabled:!e.canOpenInApp,onClick:e.openInApp,children:"Open in Dynamics 365"})}),a.jsx(vn,{id:"view",children:a.jsxs(Je,{...la(e),children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(rc,{}),children:"View"})}),a.jsx(Qe,{children:a.jsx(et,{children:yu})})]})}),a.jsx(vn,{id:"help",children:a.jsx(fe,{icon:a.jsx(ja,{}),onClick:t,children:"Help"})})]})})]}):null}function vn({id:e,children:t}){return Ta(e)?null:t}const gl="https://github.com/mohsinonxrm/pptb-mxrm-commandbar-studio#readme";function xu(){const e=Fs(),[t,n]=B.useState("");return a.jsxs("div",{className:e.helpBody,children:[a.jsx(X,{size:200,children:"Your changes are kept as a draft for each entity automatically, until you publish or discard them."}),a.jsx("dl",{className:e.shortcuts,children:bv.map(([o,s])=>a.jsxs(B.Fragment,{children:[a.jsx("dt",{children:o}),a.jsx("dd",{children:s})]},o))}),a.jsx(Y,{size:"small",onClick:async()=>n((await Ps(gl)).ok?"yes":"no"),children:"Copy documentation link"}),t==="yes"&&a.jsx(X,{size:200,children:"Copied: paste it into your browser."}),t==="no"&&a.jsxs(X,{size:200,children:["Couldn't copy. The link is ",gl]})]})}function jv(){return a.jsxs(xa,{withArrow:!0,children:[a.jsx(va,{disableButtonEnhancement:!0,children:a.jsx(he,{content:"Help",relationship:"label",children:a.jsx(rn,{icon:a.jsx(ja,{})})})}),a.jsxs(Sa,{"aria-label":"Help",children:[a.jsx(X,{weight:"semibold",children:"Command Bar Studio"}),a.jsx(xu,{})]})]})}const vu="cbs.ui.";function Su(e,t){try{const n=window.localStorage.getItem(vu+e);return n===null?t:JSON.parse(n)}catch{return t}}function wu(e,t){try{window.localStorage.setItem(vu+e,JSON.stringify(t))}catch{}}const $v=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXS,flexShrink:0},more:{alignSelf:"flex-start",fontSize:f.fontSizeBase200}}),bl={error:0,warning:1,info:2,success:3};function yl(e){const t=Su(e,{});return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(n=>typeof n[1]=="string"))}const ir=({scope:e,messages:t,className:n})=>{const o=$v(),s=`dismissed.${e}`,[i,l]=B.useState(()=>yl(s)),[r,c]=B.useState(!1),[d,u]=B.useState(e);d!==e&&(u(e),l(yl(s)),c(!1));const m=t.filter(b=>i[b.id]!==(b.signature??"")).sort((b,g)=>bl[b.intent]-bl[g.intent]);if(m.length===0)return null;const p=r?m:m.slice(0,1),h=b=>{if(b.onDismiss){b.onDismiss();return}const g={...i,[b.id]:b.signature??""};l(g),wu(s,g)};return a.jsxs("div",{className:n?`${o.root} ${n}`:o.root,children:[a.jsx(pp,{animate:"both",children:p.map(b=>a.jsxs(Dt,{intent:b.intent,layout:"multiline",children:[a.jsxs(Bt,{children:[a.jsx(cc,{children:b.title}),b.body]}),(b.actions||b.dismissible!==!1)&&a.jsx(vs,{containerAction:b.dismissible===!1?void 0:a.jsx(Y,{appearance:"transparent","aria-label":`Dismiss: ${b.title}`,icon:a.jsx(mn,{}),onClick:()=>h(b)}),children:b.actions})]},b.id))}),m.length>1&&a.jsx(Mn,{as:"button",className:o.more,"aria-expanded":r,onClick:()=>c(b=>!b),children:r?"Show fewer":`+${m.length-1} more`})]})};function Tv(){const e=Ie(n=>n.saveFailed),t=Ie(n=>n.lastSavedAt);return e?{id:"draft-save-failed",intent:"error",title:"Your latest changes can't be saved as a draft",body:t?a.jsxs(a.Fragment,{children:["The browser storage is full. The last saved draft is from"," ",new Date(t).toLocaleString(),"; publish your changes, or the ones made since are lost when Command Bar Studio closes."]}):a.jsx(a.Fragment,{children:"The browser storage is full. Publish your changes, or they are lost when Command Bar Studio closes."}),dismissible:!1}:null}function Nv(){const e=ae(s=>s.connectionNotice),t=ae(s=>s.dismissConnectionNotice);if(!e)return null;const n=`${e.from.name||e.from.url} (${e.from.environment})`,o=`${e.to.name||e.to.url} (${e.to.environment})`;return{id:"connection-changed",intent:e.draftLost?"error":e.to.environment==="Production"?"warning":"info",title:`Connection changed to ${o}`,body:a.jsxs(a.Fragment,{children:["The solution and entity loaded from ",n," were closed; pick a solution to continue in ",o,"."," ",e.draftKept&&a.jsxs(a.Fragment,{children:["Your unpublished changes were kept as a draft: switch the tool back to"," ",n," and open the entity to restore them."]}),e.draftLost&&a.jsx(a.Fragment,{children:"Your unpublished changes couldn't be saved as a draft (the browser storage is full) and are lost."})]}),onDismiss:t}}function kv(){const e=Tv();return[Nv(),e].filter(n=>n!==null)}const Av=pe({slot:{padding:`${f.spacingVerticalS} ${f.spacingHorizontalM} 0`}});function Ov(){const e=Av(),t=kv();return t.length===0?null:a.jsx(ir,{scope:"shell",messages:t,className:e.slot})}const Cu=B.createContext({}),we=en()((e,t)=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],appFilter:"all",selectedCommandId:null,loadToken:0,beginLoad(n){const o=t().loadToken+1;return e({tableLogicalName:n,status:"loading",error:null,commands:[],apps:[],selectedCommandId:null,loadToken:o}),o},finishLoad(n,o){if(n!==t().loadToken)return;const{appFilter:s}=t(),i=s==="all"||o.apps.some(l=>l.id===s);e({status:o.error?"unavailable":"loaded",error:o.error??null,commands:o.commands,apps:o.apps,appFilter:i?s:"all"})},reset(){e(n=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],selectedCommandId:null,appFilter:"all",loadToken:n.loadToken+1}))},setAppFilter(n){e({appFilter:n?n.toLowerCase():"all"})},selectCommand(n){n&&Z.getState().clearSelection(),e({selectedCommandId:n})}}));Z.subscribe((e,t)=>{if(!we.getState().selectedCommandId)return;(e.selectedButtonId&&e.selectedButtonId!==t.selectedButtonId||e.location!==t.location||e.tabId!==t.tabId)&&we.setState({selectedCommandId:null})});function Mv(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 Ev='[role="dialog"], [role="alertdialog"], [role="menu"], [role="menubar"], [role="listbox"], .fui-PopoverSurface, .fui-MenuPopover',Ru=".fui-OverlayDrawer, .fui-InlineDrawer",xl=e=>!!e.closest(Ru)&&!e.matches('[role="alertdialog"]');function Dv(e){const t=e instanceof Element?e.closest(Ev):null;return t&&!xl(t)?!0:Array.from(document.querySelectorAll('[aria-modal="true"], [role="alertdialog"]')).some(n=>!xl(n))}function Bv(e){return e instanceof Element&&!!e.closest(Ru)}function Lv(){const e=J(R=>R.setCommandPaletteOpen),t=J(R=>R.openBulkPublish),n=J(R=>R.announce),o=J(R=>R.openHideInsteadOfDelete),s=D(R=>R.undo),i=D(R=>R.redo),l=D(R=>R.past),r=D(R=>R.future),c=Z(R=>R.selectedButtonId),d=Z(R=>R.selectedGroupId),u=Z(R=>R.tabId),m=Z(R=>R.location),p=D(R=>R.duplicateButton),h=D(R=>R.deleteButton),b=D(R=>R.moveButton),g=D(R=>R.ribbons),x=D(R=>R.baseline),y=Z(R=>R.selectButtonInContext),S=Z(R=>R.selectGroup),C=B.useRef(null);B.useEffect(()=>{const R=M=>{const $=navigator.platform.toUpperCase().includes("MAC")?M.metaKey:M.ctrlKey,T=M.target,v=M.key??"",O=M.altKey||M.getModifierState?.("AltGraph"),A=!O&&/^Key[A-Z]$/.test(M.code??"")&&!/^[a-z]$/i.test(v)?M.code.slice(3).toLowerCase():v.length===1?v.toLowerCase():v,E=$&&!M.shiftKey&&!O;if(M.key==="Escape"){e(!1);return}if(Dv(T)){E&&A==="s"&&M.preventDefault();return}if(E&&A==="k"){M.preventDefault(),e(!0),n("Command palette opened");return}if(E&&A==="s"){M.preventDefault(),t(),n("Bulk publish dialog opened");return}const w=Mv(T);if(E&&A==="z"&&l.length>0&&!w){M.preventDefault(),s(),n("Undo");return}if($&&!O&&(A==="y"||M.shiftKey&&A==="z")&&!w){M.preventDefault(),r.length>0&&(i(),n("Redo"));return}if(!Bv(T)){if(E&&A==="d"){if(!w&&c&&d&&u&&m){M.preventDefault();const k=We(m,u,d);if(k){n(k);return}p(m,u,d,c),n("Button duplicated")}return}if($&&!O&&A==="x"){if(!w&&c&&d&&u&&m){M.preventDefault();const k=g[m].tabs.find(N=>N.id===u)?.groups.find(N=>N.id===d);if(k&&os(k,c)){n("Menu items can't be cut. Delete the item and add a new one to the other menu.");return}C.current={location:m,tabId:u,groupId:d,buttonId:c},n("Button cut. Focus a destination group, then press paste.")}return}if($&&!O&&A==="v"){const k=C.current;if(!w&&k&&d&&u&&m){M.preventDefault();const N=b({groupId:k.groupId,buttonId:k.buttonId,tabId:k.tabId,location:k.location},{groupId:d,tabId:u,location:m});if(C.current=null,!N){n("The button couldn't be moved there.");return}requestAnimationFrame(()=>{y(m,u,d,N),document.querySelector(`[data-ribbon-btn-id="${N}"]`)?.focus()}),n(N===k.buttonId?"Button pasted to destination group.":"Pasted your copy of the button to the destination group; the original is hidden.")}return}if((M.key==="Delete"||M.key==="Backspace")&&c&&d&&u&&m&&!w){const k=g[m].tabs.find(F=>F.id===u),N=k?.groups.find(F=>F.id===d),j=Ns(N,c);if(!j)return;if(M.preventDefault(),!Os(j,x[m])){m==="Application"&&u==="Mscrm.GlobalTab"&&j.oob&&!j.custom?n(`"${j.label}" is read-only and can't be deleted.`):j.hidden?n(`"${j.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 _=N?os(N,c):void 0,W=_?_.section.controls.map(F=>({groupId:d,buttonId:F.id})):k?.groups.flatMap(F=>F.buttons.map(L=>({groupId:F.id,buttonId:L.id})))??[],ne=W.findIndex(F=>F.buttonId===c),le=W[ne+1]??W[ne-1]??(_?{groupId:d,buttonId:_.parent.id}:null),ce=d;h(m,u,d,c),requestAnimationFrame(()=>{if(le){y(m,u,le.groupId,le.buttonId),document.querySelector(`[data-ribbon-btn-id="${le.buttonId}"]`)?.focus();return}ce&&(S(ce),document.querySelector(`[data-add-btn-group-id="${ce}"]`)?.focus())}),n("Button deleted")}}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[e,t,n,o,s,i,l.length,r.length,c,d,u,m,p,h,b,g,x,y,S])}const zv=pe({handleV:{width:"4px",cursor:"col-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:f.colorNeutralStroke2},":active":{backgroundColor:f.colorBrandStroke1},":focus-visible":{backgroundColor:f.colorBrandStroke1,outline:"none"},userSelect:"none"},handleH:{height:"4px",cursor:"row-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:f.colorNeutralStroke2},":active":{backgroundColor:f.colorBrandStroke1},":focus-visible":{backgroundColor:f.colorBrandStroke1,outline:"none"},userSelect:"none"}}),Pv=16,Fv=64;function fi({direction:e,onResize:t,value:n,min:o,max:s,target:i,"aria-label":l=`Resize ${e} pane`}){const r=zv(),c=B.useRef(0),d=B.useCallback(p=>{p.currentTarget.setPointerCapture(p.pointerId),c.current=e==="vertical"?p.clientX:p.clientY},[e]),u=B.useCallback(p=>{if(!p.currentTarget.hasPointerCapture(p.pointerId))return;const h=e==="vertical"?p.clientX:p.clientY,b=h-c.current;c.current=h,t(b)},[e,t]),m=B.useCallback(p=>{const h=e==="vertical"?["ArrowLeft","ArrowRight"]:["ArrowUp","ArrowDown"],b=p.key===h[0]?-1:p.key===h[1]?1:0;b!==0&&(p.preventDefault(),t(b*(p.shiftKey?Fv:Pv)))},[e,t]);return a.jsx("div",{className:e==="vertical"?r.handleV:r.handleH,role:"separator","aria-orientation":e==="vertical"?"vertical":"horizontal","aria-label":l,"aria-valuenow":Math.round(n),"aria-valuemin":o,"aria-valuemax":s,"aria-valuetext":`${i}, ${Math.round(n)} pixels ${e==="vertical"?"wide":"high"}`,tabIndex:0,onKeyDown:m,onPointerDown:d,onPointerMove:u})}class _t extends nt.Component{state={hasError:!1,error:null};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[CBS ErrorBoundary]",this.props.label??"panel",t,n)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:a.jsxs(Dt,{intent:"error",style:{margin:8},children:[a.jsxs(Bt,{children:[a.jsx("strong",{children:this.props.label??"Panel"})," encountered an error:"," ",this.state.error?.message??"Unknown error"]}),a.jsx(vs,{children:a.jsx(Y,{size:"small",onClick:this.handleRetry,children:"Retry"})})]}):this.props.children}}const _v=.4,ar=160,rr=200,Iu=500,ju=600;function Ko(e,t,n){const o=t+n-e*(1-_v);if(o<=0||t+n===0)return{left:t,right:n};const s=(i,l)=>Math.max(Math.min(i,l),Math.round(i-o*i/(t+n)));return{left:s(t,ar),right:n===0?0:s(n,rr)}}function qv(e,t,n,o,s){const i=Ko(e,t,n),l=(c,d,u)=>Math.max(d,Math.min(u,c));if(o==="left"){const c=l(i.left+s,ar,Iu);return n>0&&i.right!==n?{left:c,right:i.right}:{left:c}}const r=l(i.right-s,rr,ju);return i.left!==t?{left:i.left,right:r}:{right:r}}const Hv=B.lazy(()=>ht(()=>import("./EditorDrawer-D0K8zHVK.js"),__vite__mapDeps([0,1,2,3]),import.meta.url)),Wv=B.lazy(()=>ht(()=>import("./BulkPublishModal-9_XxYmS2.js"),__vite__mapDeps([4,1,2,5,6,7,8,3]),import.meta.url)),Gv=B.lazy(()=>ht(()=>import("./NewButtonModal-DhGNLWEW.js"),__vite__mapDeps([9,2,1,3]),import.meta.url)),Uv=B.lazy(()=>ht(()=>import("./NewGroupModal-CMLOZ15C.js"),__vite__mapDeps([10,2,1,3]),import.meta.url)),Vv=B.lazy(()=>ht(()=>import("./NewTabModal-N7FF7DT1.js"),__vite__mapDeps([11,2,1,3]),import.meta.url)),Xv=B.lazy(()=>ht(()=>import("./ImportXmlModal-Cf75oVpN.js"),__vite__mapDeps([12,2,7,8,5,1,3]),import.meta.url)),Kv=B.lazy(()=>ht(()=>import("./CommandPalette-C2YXN_gD.js"),__vite__mapDeps([13,2,1,3]),import.meta.url)),Yv=B.lazy(()=>ht(()=>import("./IconPickerModal-B9UeIP7Z.js"),__vite__mapDeps([14,2,15,1,3]),import.meta.url)),Jv=B.lazy(()=>ht(()=>import("./WebResourceBrowser-DEXq2SCy.js"),__vite__mapDeps([16,2,15,1,3]),import.meta.url)),Zv=B.lazy(()=>ht(()=>import("./HideInsteadOfDeleteModal-C4AKxh50.js"),__vite__mapDeps([17,2,1,3]),import.meta.url)),Qv=pe({root:{display:"flex",flexDirection:"column",height:"100vh",overflow:"hidden",backgroundColor:f.colorNeutralBackground1,color:f.colorNeutralForeground1,fontFamily:f.fontFamilyBase},body:{display:"flex",flex:1,overflow:"hidden",position:"relative"},leftPane:{flexShrink:0,overflow:"hidden",borderRight:`1px solid ${f.colorNeutralStroke2}`},rightPane:{flexShrink:0,overflow:"hidden",borderLeft:`1px solid ${f.colorNeutralStroke2}`},bottomPanel:{flexShrink:0},rail:{width:"48px",flexShrink:0,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:f.spacingVerticalS,borderRight:`1px solid ${f.colorNeutralStroke2}`,backgroundColor:f.colorNeutralBackground2},drawerBody:{position:"relative",width:"100%",height:"100%",overflow:"hidden"},belowTopBar:{top:`${ra+1}px`,height:`calc(100vh - ${ra+1}px)`}}),eS=[{value:"structure",label:"Structure",icon:a.jsx(dc,{})},{value:"solution",label:"Solution",icon:a.jsx(uc,{})}],tS=1200,vl=120,Sl=520;function nS(){const[e,t]=B.useState(()=>window.innerWidth);return B.useEffect(()=>{const n=()=>t(window.innerWidth);return window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),e}function oS({children:e,leftPane:t,rightPane:n,bottomPanel:o}){const s=Qv(),i=J(Q=>Q.leftPaneWidth),l=J(Q=>Q.rightPaneWidth),r=J(Q=>Q.rightPaneMode),c=J(Q=>Q.setLeftPaneWidth),d=J(Q=>Q.setRightPaneWidth),u=J(Q=>Q.bottomPanelHeight),m=J(Q=>Q.bottomCollapsed),p=J(Q=>Q.setBottomPanelHeight),h=J(Q=>Q.announcement),b=nS(),g=b<tS,x=Z(Q=>Q.selectedButtonId),y=Z(Q=>Q.selectedGroupId),S=ae(Q=>Q.activeEntity?.logicalName??null),[C,R]=B.useState(!1),M=J(Q=>Q.leftPaneTab),I=J(Q=>Q.setLeftPaneTab),$=we(Q=>Q.selectedCommandId),[T,v]=B.useState(!1),O=J(Q=>Q.propertiesRequested),A=J(Q=>Q.setPropertiesRequested),E=T||g&&O,w=()=>{v(!1),A(!1)},k=!!(x||y||$),N=`${y??""}|${x??""}|${$??""}`,[j,_]=B.useState(N);j!==N&&(_(N),g&&!C&&k&&v(!0));const[W,ne]=B.useState(g);W!==g&&(ne(g),R(!1),v(!1));const le=J(Q=>Q.structureChoice),[ce,F]=B.useState(le);ce!==le&&(F(le),R(!1),g&&k&&v(!0));const[L,G]=B.useState(S);L!==S&&(G(S),R(!1));const H=Ko(b,i,r==="docked"?l:0),te={left:Math.max(H.left,Ko(b,Iu,H.right).left),right:Math.max(H.right,Ko(b,H.left,ju).right)},P=J(Q=>Q.editorStack.length>0||Q.bulkPublishOpen||Q.newButtonGroupId!==null||Q.newGroupOpen||Q.newTabOpen||Q.importXmlOpen||Q.commandPaletteOpen||Q.iconPickerOpen||Q.webResourceBrowserOpen||Q.hideInsteadOfDelete!==null),K=B.useRef(null),ue=B.useRef(!1);Lv(),B.useEffect(()=>{O&&!g&&A(!1)},[O,g,A]),B.useEffect(()=>{if(P&&!ue.current){const Q=document.activeElement;K.current=Q instanceof HTMLElement?Q:null}if(!P&&ue.current){const Q=K.current;requestAnimationFrame(()=>{!Q||!Q.isConnected||Q.focus()})}ue.current=P},[P]);const Me=r==="docked"?l:0,Pe=B.useCallback((Q,Le)=>{const at=qv(b,i,Me,Q,Le);at.left!==void 0&&c(at.left),at.right!==void 0&&d(at.right)},[b,i,Me,c,d]),ot=B.useCallback(Q=>Pe("left",Q),[Pe]),Ee=B.useCallback(Q=>Pe("right",Q),[Pe]),Fe=B.useCallback(Q=>{const Le=u-Q;p(Math.max(vl,Math.min(Sl,Le)))},[u,p]);return a.jsxs("div",{className:s.root,children:[a.jsx(yv,{}),a.jsx(Ov,{}),a.jsxs("div",{className:s.body,children:[g?a.jsxs("nav",{className:s.rail,"aria-label":"Side panes",children:[eS.map(({value:Q,label:Le,icon:at})=>a.jsx(he,{content:Le,relationship:"label",children:a.jsx(Y,{appearance:"subtle",icon:at,"aria-pressed":C&&M===Q,onClick:()=>{I(Q),R(!0)}})},Q)),r!=="hidden"&&a.jsx(he,{content:"Properties",relationship:"label",children:a.jsx(Y,{appearance:"subtle",icon:a.jsx(fp,{}),"aria-pressed":E,onClick:()=>E?w():v(!0)})})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:s.leftPane,style:{width:H.left},children:a.jsx(_t,{label:"Left pane",children:t})}),a.jsx(fi,{direction:"vertical",onResize:ot,value:H.left,min:Math.min(ar,H.left),max:te.left,target:"Left pane","aria-label":"Resize left pane"})]}),a.jsx(_t,{label:"Ribbon canvas",children:e}),g&&a.jsxs(a.Fragment,{children:[a.jsx(wr,{position:"start",size:"small",open:C,onOpenChange:(Q,Le)=>R(Le.open),"aria-label":M==="structure"?"Structure":"Solution",children:a.jsx("div",{className:s.drawerBody,children:a.jsx(_t,{label:"Left pane",children:t})})}),r!=="hidden"&&a.jsx(wr,{position:"end",size:"small",modalType:"non-modal",className:s.belowTopBar,open:E,onOpenChange:(Q,Le)=>Le.open?v(!0):w(),"aria-label":"Properties",children:a.jsx("div",{className:s.drawerBody,children:a.jsx(Cu.Provider,{value:{onClose:w},children:a.jsx(_t,{label:"Properties pane",children:n})})})})]}),!g&&r==="docked"&&a.jsxs(a.Fragment,{children:[a.jsx(fi,{direction:"vertical",onResize:Ee,value:H.right,min:Math.min(rr,H.right),max:te.right,target:"Properties pane","aria-label":"Resize right pane"}),a.jsx("div",{className:s.rightPane,style:{width:H.right},children:a.jsx(_t,{label:"Properties pane",children:n})})]}),!g&&r==="floating"&&a.jsx("div",{style:{position:"absolute",right:8,top:8,bottom:8,width:l,maxWidth:"90vw",border:`1px solid ${f.colorNeutralStroke2}`,backgroundColor:f.colorNeutralBackground1,boxShadow:f.shadow16,borderRadius:f.borderRadiusMedium,overflow:"hidden",zIndex:10},children:a.jsx(_t,{label:"Properties pane",children:n})})]}),!m&&a.jsx(fi,{direction:"horizontal",onResize:Fe,value:u,min:vl,max:Sl,target:"Bottom panel","aria-label":"Resize bottom panel"}),a.jsx("div",{className:s.bottomPanel,children:a.jsx(_t,{label:"Bottom panel",children:o})}),a.jsx(_t,{label:"Panels",children:a.jsxs(B.Suspense,{fallback:null,children:[a.jsx(Hv,{}),a.jsx(Wv,{}),a.jsx(Gv,{}),a.jsx(Uv,{}),a.jsx(Vv,{}),a.jsx(Xv,{}),a.jsx(Kv,{}),a.jsx(Yv,{}),a.jsx(Jv,{}),a.jsx(Zv,{})]})}),a.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",left:-9999,top:"auto"},children:h})]})}const sS=["HomepageGrid","SubGrid","Form"];function iS(e,t){const n=new Map;for(const b of Object.values(t.baseline))for(const g of b.tabs)for(const x of g.groups)for(const y of x.buttons)n.set(y.id,y.origin);let o=!1,s=!1,i=Gi(e);for(const[b,g]of Object.entries(t.ribbons))for(const x of g.tabs)for(const y of x.groups)for(const S of y.buttons)S.commandId===e&&(sS.includes(b)?o=!0:s=!0,n.has(S.id)&&n.get(S.id)!=="unmanaged"&&(i=!0));const l=o||!s?"entity":"application",r=o&&s,c=t.layers[l],d=c?.commandIds?c.commandIds.includes(e):void 0,u=t.baselineCommands.find(b=>b.id===e),m=(b,g=l)=>({provenance:b,scope:g,sharedWithApplication:r});if(t.reloadRequiredCommandIds.includes(e))return m("reloadRequired");for(const b of["entity","application"])if(t.uncustomisedCommandIds[b].includes(e))return m("uncustomising",b);if(!u||!i&&d!==!1)return m("custom");if(d){const b=c?.commandRefIds?Pa(e,c.commandRefIds):Gi(e);return m(b?"customised":"custom")}const p=t.commands.find(b=>b.id===e),h=!!p&&JSON.stringify(p)!==JSON.stringify(u);return t.customisedCommandIds.includes(e)||h?m("customising"):m("oob")}const aS={oob:"Out of the box",customising:"Customised (unpublished)",customised:"Customised in your layer",uncustomising:"Uncustomised (unpublished)",custom:"Custom",reloadRequired:"Uncustomised — reload the entity"};function _s(e){const t=D(d=>d.commands),n=D(d=>d.baselineCommands),o=D(d=>d.ribbons),s=D(d=>d.baseline),i=D(d=>d.layers),l=D(d=>d.customisedCommandIds),r=D(d=>d.uncustomisedCommandIds),c=D(d=>d.reloadRequiredCommandIds);return nt.useMemo(()=>e&&t.some(d=>d.id===e)?iS(e,{commands:t,baselineCommands:n,ribbons:o,baseline:s,layers:i,customisedCommandIds:l,uncustomisedCommandIds:r,reloadRequiredCommandIds:c}):null,[e,t,n,o,s,i,l,r,c])}function rS(e){return e?.provenance==="oob"||e?.provenance==="uncustomising"||e?.provenance==="reloadRequired"}function lS({location:e,tabId:t,groupId:n,button:o,onDone:s}){const i=D(p=>p.customiseButton),l=D(p=>p.customiseCommand),r=ae(p=>p.activeSolution),c=ae(p=>p.publisherPrefix),d=Z(p=>p.selectButtonInContext),u=J(p=>p.openCommandEditor),m=_s(o.commandId||void 0);return a.jsxs(a.Fragment,{children:[o.origin!=="unmanaged"&&a.jsx(fe,{icon:a.jsx(hp,{}),disabled:!er(e,t,o),onClick:()=>{const p=r?.publisherPrefix?.trim()||c?.trim()||"new",h=i(e,t,n,o.id,p);h&&d(e,t,n,h),s()},children:"Customise button (copy, hide original)"}),m?.provenance==="oob"&&a.jsx(fe,{icon:a.jsx(Pn,{}),onClick:()=>{l(o.commandId)&&u(o.commandId),s()},children:"Customise command"})]})}const Hn=({open:e,title:t,children:n,confirmLabel:o,cancelLabel:s="Cancel",destructive:i=!1,onConfirm:l,onCancel:r})=>a.jsx(hn,{open:e,onOpenChange:c=>!c&&r(),title:t,size:"small",modalType:"alert",actions:a.jsxs(a.Fragment,{children:[a.jsx(Y,{appearance:"secondary",onClick:r,children:s}),i?a.jsx(sr,{onClick:l,children:o}):a.jsx(Y,{appearance:"primary",onClick:l,children:o})]}),children:n}),cS=pe({body:{display:"flex",flexDirection:"column",gap:f.spacingVerticalM},options:{display:"flex",flexDirection:"column",gap:f.spacingVerticalS},description:{display:"block",color:f.colorNeutralForeground2,paddingLeft:"32px",marginTop:`-${f.spacingVerticalXS}`}}),$u=({open:e,buttonLabel:t,buttonId:n,commandId:o,deleteBlockedReason:s,onConfirmHide:i,onConfirmDisplayRule:l,onCancel:r})=>{const c=cS(),d=Be(),u=D(y=>y.locLabels),m=D(y=>y.ribbons),p=Z(y=>y.location),h=o?gd(m,o,n??"",y=>d(y.label,u,void 0,y.source?.labelToken),p):[],[b,g]=B.useState(o&&h.length===0?"rules":"button"),x=h.length===0?"No other button uses its command.":`Also hides ${h.length===1?"1 other button":`${h.length} other buttons`} that use${h.length===1?"s":""} its command: ${h.slice(0,4).join(", ")}${h.length>4?", …":""}.`;return a.jsx(hn,{open:e,onOpenChange:y=>!y&&r(),size:"medium",title:s?`Can't delete "${t}"`:`Hide "${t}"?`,actions:a.jsxs(a.Fragment,{children:[a.jsx(Y,{appearance:"secondary",onClick:r,children:"Cancel"}),a.jsx(Y,{appearance:"primary",onClick:b==="rules"?l:i,children:"Hide button"})]}),children:a.jsxs("div",{className:c.body,children:[s&&a.jsxs(X,{children:[s," Only buttons your solution adds can be deleted; you can hide this one instead."]}),a.jsxs(Ni,{className:c.options,value:b,onChange:(y,S)=>g(S.value),"aria-label":"How to hide it",children:[a.jsxs("div",{children:[a.jsx(ln,{value:"button",label:"Hide this button only"}),a.jsx(X,{size:200,className:c.description,children:"Removes it from this entity's ribbon. Show it again under “Hidden by customizations” in Properties. Once a managed solution ships the hide, only a new version of that solution can bring it back."})]}),a.jsxs("div",{children:[a.jsx(ln,{value:"rules",disabled:!o,label:"Hide it with display rules on its command"}),a.jsx(X,{size:200,className:c.description,children:o?`Adds two display rules to the command so it never shows. Easy to undo: remove the rules. ${x}`:"Not available: this button has no command."})]})]}),a.jsx(Et,{size:"small",info:a.jsx(a.Fragment,{children:"“Hide this button only” adds a HideCustomAction to your customizations. The display rules are Mscrm.HideOnModern and Mscrm.ShowOnlyOnModern, which are never both true."}),children:"What each one writes"})]})})};function dS(e,t,n,o,s,i=Ve){const l=e.groups.filter(c=>c.id!==t&&!(n&&c.buttons.some(d=>d.id===n))).map(c=>({groupId:c.id,text:vt(c.id,i(c.label,o,s,c.source?.titleToken).trim())})),r=new Map;for(const c of l)r.set(c.text,(r.get(c.text)??0)+1);return l.map(c=>(r.get(c.text)??0)>1&&c.text!==c.groupId?{...c,text:`${c.text} (${c.groupId})`}:c)}const uS=pe({danger:{color:f.colorPaletteRedForeground1},note:{maxWidth:"280px",whiteSpace:"normal"}});function To({location:e,tab:t,target:n,onClose:o}){const s=uS(),i=Be(),l=D(T=>T.locLabels),r=D(T=>T.baseLanguageCode),c=D(T=>T.baseline),d=D(T=>T.setButtonProp),u=D(T=>T.customizeOobButton),m=D(T=>T.duplicateButton),p=D(T=>T.moveButton),h=D(T=>T.deleteButton),b=D(T=>T.hideOobButton),g=Z(T=>T.selectButtonInContext),x=J(T=>T.openIconPicker),y=J(T=>T.openLocalizationEditor),[S,C]=B.useState(null),[R,M]=B.useState(null),I=T=>i(T.label,l,void 0,T.source?.labelToken),$=n&&(()=>{const{button:T,groupId:v}=n,O=Va(e,t.id,T),A=ut(T.kind),E=dS(t,v,T.id,l,r,i).filter(k=>!We(e,t.id,k.groupId)),w=k=>()=>{k(),o()};return a.jsxs(Je,{open:!0,onOpenChange:(k,N)=>!N.open&&o(),positioning:{target:n.anchor,position:"below",align:"start"},children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Qe,{children:a.jsxs(et,{"aria-label":`Actions for ${I(T)}`,children:[O&&a.jsx(fo,{className:s.note,children:"Microsoft's global command bar buttons can't be changed."}),!O&&A&&a.jsxs(fo,{className:s.note,children:[xt[T.kind],": shown read-only. You can hide, move or delete it."]}),a.jsx(fe,{icon:a.jsx(mc,{}),onClick:w(()=>g(e,t.id,v,T.id)),children:"Edit properties"}),a.jsx(fe,{icon:a.jsx(ki,{}),disabled:O||A,onClick:w(()=>{g(e,t.id,v,T.id),x()}),children:"Change icon…"}),a.jsx(fe,{icon:a.jsx(Na,{}),disabled:O||A,onClick:w(()=>y(T.id)),children:"Edit labels…"}),a.jsx(Mt,{}),T.hidden?a.jsx(fe,{icon:a.jsx(Fn,{}),disabled:O,onClick:w(()=>d(e,t.id,v,T.id,{hidden:!1})),children:"Show button"}):a.jsx(fe,{icon:a.jsx(Lt,{}),disabled:O,onClick:w(()=>T.oob?C(n):d(e,t.id,v,T.id,{hidden:!0})),children:T.oob?"Hide button…":"Hide button"}),(T.origin==="oob"||T.origin==="managed")&&a.jsx(fe,{icon:a.jsx(ho,{}),disabled:O||A,onClick:w(()=>u(e,t.id,v,T.id)),children:"Create override…"}),a.jsx(lS,{location:e,tabId:t.id,groupId:v,button:T,onDone:o}),a.jsx(Mt,{}),a.jsx(fe,{icon:a.jsx(Ro,{}),disabled:O||!!We(e,t.id,v),subText:O?void 0:We(e,t.id,v),onClick:w(()=>m(e,t.id,v,T.id)),children:"Duplicate"}),E.length===0||O?a.jsx(fe,{icon:a.jsx(Cr,{}),disabled:!0,secondaryContent:O?void 0:"No other groups",children:"Move to"}):a.jsxs(Je,{children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(Cr,{}),children:"Move to"})}),a.jsx(Qe,{children:a.jsx(et,{"aria-label":"Move to group",children:E.map(k=>a.jsx(fe,{onClick:w(()=>{const N=p({groupId:v,buttonId:T.id,tabId:t.id,location:e},{groupId:k.groupId,tabId:t.id,location:e});N&&g(e,t.id,k.groupId,N)}),children:k.text},k.groupId))})})]}),Os(T,c[e])&&a.jsxs(a.Fragment,{children:[a.jsx(Mt,{}),a.jsx(fe,{icon:a.jsx(_n,{className:s.danger}),className:s.danger,disabled:O,onClick:w(()=>M(n)),children:"Delete…"})]})]})})]})})();return a.jsxs(a.Fragment,{children:[$,R&&a.jsxs(Hn,{open:!0,title:"Delete button",confirmLabel:"Delete button",destructive:!0,onConfirm:()=>{h(e,t.id,R.groupId,R.button.id),M(null)},onCancel:()=>M(null),children:["Delete “",I(R.button),"”? You can undo this until you publish."]}),S&&a.jsx($u,{open:!0,buttonLabel:I(S.button),buttonId:S.button.id,commandId:S.button.commandId,onConfirmHide:()=>{b(e,t.id,S.groupId,S.button.id),C(null)},onConfirmDisplayRule:()=>{D.getState().hideWithDisplayRules(S.button.commandId),C(null)},onCancel:()=>C(null)})]})}const Tu=({open:e,initialLabel:t,onRename:n,onCancel:o,noun:s="group"})=>{const[i,l]=B.useState(t),r=i.trim(),c=()=>{r&&(r===t.trim()?o():n(r))};return a.jsx(hn,{open:e,onOpenChange:d=>!d&&o(),size:"small",title:`Rename ${s}`,actions:a.jsxs(a.Fragment,{children:[a.jsx(Y,{appearance:"secondary",onClick:o,children:"Cancel"}),a.jsx(Y,{appearance:"primary",onClick:c,disabled:!r,children:"Rename"})]}),children:a.jsx(qe,{label:s==="tab"?"Tab title":"Group title",required:!0,validationState:r?"none":"error",validationMessage:r?void 0:`Enter a title for the ${s}.`,children:a.jsx(Wt,{value:i,onChange:(d,u)=>l(u.value),onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),c())},"data-autofocus":!0})})})},mS=e=>e.replace(/^Mscrm\.Templates\./,""),pS=({open:e,currentTemplate:t,customTemplateIds:n=[],loadedGroup:o=!1,onChange:s,onCancel:i})=>{const l=Ha(t),[r,c]=B.useState(l),d=[...new Set([...dy,...n,l])],u=()=>{r===l?i():s(r)};return a.jsxs(hn,{open:e,onOpenChange:m=>!m&&i(),size:"small",title:"Change group template",actions:a.jsxs(a.Fragment,{children:[a.jsx(Y,{appearance:"secondary",onClick:i,children:"Cancel"}),a.jsx(Y,{appearance:"primary",onClick:u,disabled:r===l,children:"Change template"})]}),children:[a.jsx(qe,{label:"Group template",hint:"How the group's buttons shrink when the classic ribbon is narrow. Unified Interface ignores it.",children:a.jsx(ka,{value:r,onChange:(m,p)=>c(p.value),children:d.map(m=>a.jsxs("option",{value:m,children:[mS(m),m===l?" (current)":""]},m))})}),o&&a.jsx(Dt,{intent:"warning",style:{marginTop:"12px"},children:a.jsx(Bt,{children:"This group was loaded from the environment. Publishing can't change an existing group's template yet (it's reported as not supported); groups you add publish theirs."})})]})};function fS(e){if(e instanceof HTMLElement)return e;const{x:t,y:n}=e;return{getBoundingClientRect:()=>({x:t,y:n,top:n,left:t,right:t,bottom:n,width:0,height:0,toJSON:()=>({})})}}function lr({location:e,tab:t,target:n,onClose:o,moveLabels:s=["Move left","Move right"]}){const i=Be(),l=D(A=>A.locLabels),r=D(A=>A.baseLanguageCode),c=D(A=>A.baseline),d=D(A=>A.layers),u=D(A=>A.templates),m=D(A=>A.duplicateGroup),p=D(A=>A.setGroupTemplate),h=D(A=>A.renameGroup),b=D(A=>A.deleteGroup),g=D(A=>A.moveGroup),x=D(A=>A.ribbons),y=J(A=>A.openNewButton),S=J(A=>A.openTitleTranslations),[C,R]=B.useState(null),[M,I]=B.useState(null),[$,T]=B.useState(null);B.useEffect(()=>{n?.action==="rename"&&(R(n.group),o())},[n,o]);const v=A=>vt(A.id,i(A.label,l,r,A.source?.titleToken)),O=n&&!n.action&&(()=>{const{group:A}=n,E=w=>()=>{w(),o()};return a.jsxs(Je,{open:!0,onOpenChange:(w,k)=>!k.open&&o(),positioning:{position:"below",align:"start",target:fS(n.anchor)},children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Qe,{children:a.jsxs(et,{"aria-label":`Actions for ${v(A)}`,children:[a.jsx(fe,{icon:a.jsx(ke,{}),disabled:!!We(e,t.id,A.id),subText:We(e,t.id,A.id),onClick:E(()=>y(A.id)),children:"Add button…"}),rs("group",A.id,c[e],Ln({layers:d},e))?a.jsx(fe,{icon:a.jsx(Rr,{}),onClick:E(()=>R(A)),children:"Rename…"}):a.jsx(fe,{icon:a.jsx(Rr,{}),disabled:!0,title:Vo,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),a.jsx(fe,{icon:a.jsx(Na,{}),disabled:!rs("group",A.id,c[e],Ln({layers:d},e)),onClick:E(()=>S(e,"group",t.id,A.id)),children:"Translate title…"}),a.jsx(fe,{icon:a.jsx(Ro,{}),disabled:!!Zt(e,t.id),subText:Zt(e,t.id),onClick:E(()=>m(e,t.id,A.id)),children:"Duplicate group"}),a.jsx(fe,{icon:a.jsx(ho,{}),onClick:E(()=>I(A)),children:"Change template…"}),a.jsx(Mt,{}),[-1,1].map((w,k)=>{const N=Gd({ribbons:x,baseline:c,layers:d},e,t.id,A.id,w),j=t.groups,_=j.findIndex(ne=>ne.id===A.id),W=!j[_+w];return a.jsx(fe,{icon:w<0?a.jsx(gp,{}):a.jsx(bp,{}),disabled:!N,subText:N||W?void 0:"Only groups your customizations add can change places",onClick:E(()=>g(e,t.id,A.id,w)),children:s[k]},w)}),Xa(A,c[e],An({layers:d},e))&&a.jsxs(a.Fragment,{children:[a.jsx(Mt,{}),a.jsx(fe,{icon:a.jsx(_n,{}),onClick:E(()=>T(A)),children:"Delete group"})]})]})})]})})();return a.jsxs(a.Fragment,{children:[O,C&&a.jsx(Tu,{open:!0,initialLabel:Ve(C.label,l,r),onRename:A=>{h(e,t.id,C.id,A),R(null)},onCancel:()=>R(null)}),M&&a.jsx(pS,{open:!0,currentTemplate:M.template,customTemplateIds:u.map(A=>A.id),loadedGroup:c[e].tabs.some(A=>A.id===t.id&&A.groups.some(E=>E.id===M.id)),onChange:A=>{p(e,t.id,M.id,A),I(null)},onCancel:()=>I(null)}),$&&a.jsxs(Hn,{open:!0,title:"Delete group",confirmLabel:"Delete group",destructive:!0,onConfirm:()=>{b(e,t.id,$.id),T(null)},onCancel:()=>T(null),children:["Delete the group “",v($),"” and its"," ",$.buttons.length," button",$.buttons.length===1?"":"s","?"]})]})}function Nu(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 hS={new:ke,plus:ke,addexisting:ke,exporttoexcel:Nc,tablegroup:bc,flows:Ar,process:Ar,emaillink:yg,sendbyemail:hc,failedmail:Ei,letter:Ei,remove:mn,close:mn,abandon:mn,cancel:kr,cleardefault:kr,assign:bg,activate:Oo,saveascomplete:Oo,finishstage:Oo,setdefault:Oo,deactivate:gg,reactivate:gc,connection:Ao,connect:Ao,connectiontoother:Ao,connectiontome:Ao,addtoqueue:Nr,bulletlistadd:Nr,queueitemdetail:hg,ratingempty:Ho,ratingfull:Ho,ratingfullgrey:Ho,report:Ai,openinpowerbi:Ai,wordtemplates:Us,documenttemplates:Us,applytemplate:Us,dynamics365:fg,formdesign:pg,msteamsicon:mg,convert:Tr,switchprocess:Tr,viewhierarchy:ug,linkarticle:xc,saveandclose:dg,saveandedit:Tc,runroutingrule:$r,saveandrunroutingrule:$r,createquickcampaign:cg,pdficonfile:lg,mergerecords:rg,yammericon:jr,post:jr,opportunity:Oi,opportunitieslist:Oi,case:wc,deletebulk:_n,foldertrack:Sc,sadsmiley:ag,kbrecords:Ir,insertkbarticle:Ir,salesliterature:ig,follow:Fn,history:sg,contactcard:og,flash:ng,pin:tg,multiselect:eg,browsecards:yc,addmembers:Qh,distributionlist:Cc,health:Zh,tools:Jh,relationshipassistant:fc,task:Yh,appointment:Kh},ku={add:{regular:ke,filled:Xh},delete:{regular:_n,filled:Vh},edit:{regular:mc,filled:Uh},save:{regular:Tc,filled:Gh},copy:{regular:Ro,filled:Wh},cut:{regular:Hh,filled:qh},clipboardpaste:{regular:_h,filled:Fh},share:{regular:Ph,filled:zh},mail:{regular:Ei,filled:Lh},chat:{regular:Bh,filled:Dh},phone:{regular:Eh,filled:Mh},search:{regular:sc,filled:Oh},filter:{regular:$c,filled:Ah},arrowleft:{regular:kh,filled:Nh},arrowright:{regular:Th,filled:$h},arrowup:{regular:jh,filled:Ih},arrowdown:{regular:Rh,filled:Ch},chevrondown:{regular:dt,filled:wh},chevronup:{regular:jc,filled:Sh},navigation:{regular:vh,filled:xh},home:{regular:yh,filled:bh},settings:{regular:gh,filled:hh},info:{regular:Mi,filled:fh},warning:{regular:ph,filled:mh},checkmark:{regular:Ic,filled:uh},dismiss:{regular:mn,filled:dh},questioncircle:{regular:ja,filled:ch},lockclosed:{regular:fn,filled:lh},lockopen:{regular:rh,filled:ah},shield:{regular:ih,filled:sh},person:{regular:Rc,filled:oh},people:{regular:Cc,filled:nh},personadd:{regular:th,filled:eh},building:{regular:Qf,filled:Zf},briefcase:{regular:wc,filled:Jf},money:{regular:Oi,filled:Yf},creditcard:{regular:Kf,filled:Xf},cart:{regular:Vf,filled:Uf},tag:{regular:Gf,filled:Wf},document:{regular:Ss,filled:Hf},documentbulletlist:{regular:qf,filled:_f},folder:{regular:Sc,filled:Ff},folderopen:{regular:Pf,filled:zf},attach:{regular:Lf,filled:Bf},arrowdownload:{regular:Df,filled:Ef},arrowupload:{regular:Mf,filled:Of},globe:{regular:vc,filled:Af},link:{regular:xc,filled:kf},open:{regular:Ia,filled:Nf},calendar:{regular:Tf,filled:$f},clock:{regular:jf,filled:If},timer:{regular:Rf,filled:Cf},star:{regular:Ho,filled:wf},heart:{regular:Sf,filled:vf},thumblike:{regular:xf,filled:yf},thumbdislike:{regular:bf,filled:gf},eye:{regular:Fn,filled:hf},eyeoff:{regular:Lt,filled:ff},zoomin:{regular:pf,filled:mf},zoomout:{regular:uf,filled:df},maximize:{regular:cf,filled:lf},minimize:{regular:rf,filled:af},grid:{regular:yc,filled:sf},list:{regular:of,filled:nf},table:{regular:Aa,filled:tf},tablesimple:{regular:bc,filled:ef},code:{regular:Pn,filled:Qp},bug:{regular:Zp,filled:Jp},play:{regular:Yp,filled:Kp},pause:{regular:Xp,filled:Vp},stop:{regular:Up,filled:Gp},refresh:{regular:gc,filled:Wp},arrowsync:{regular:Hp,filled:qp},arrowundo:{regular:Ca,filled:_p},arrowredo:{regular:Ra,filled:Fp},printer:{regular:Pp,filled:zp},send:{regular:hc,filled:Lp},rocket:{regular:Bp,filled:Dp},sparkle:{regular:Ep,filled:Mp},trophy:{regular:Op,filled:Ap},lightbulb:{regular:fc,filled:kp},bot:{regular:Np,filled:Tp},databar:{regular:Ai,filled:$p},chartmultiple:{regular:jp,filled:Ip},poll:{regular:Rp,filled:Cp},layoutcolumntwo:{regular:wp,filled:Sp},codeblock:{regular:vp,filled:xp},clockarrowcounterclockwise:{regular:pc,filled:yp}},cr=({name:e,size:t=20,variant:n="regular",style:o,className:s,"aria-hidden":i=!0})=>{const l=Nu(e).replace(/_/g,""),r=ku[l],c=(n==="filled"?r?.filled??r?.regular:r?.regular)??hS[l]??ho;return a.jsx(c,{fontSize:t,"aria-hidden":i,className:s,style:{display:"inline-block",verticalAlign:"middle",flexShrink:0,color:f.colorNeutralForeground1,...o}})};async function KR(e,t=32,n="regular"){const o=Nu(e).replace(/_/g,""),s=ku[o],i=n==="filled"?s?.filled??s?.regular:s?.regular;if(!i)return null;const{renderToStaticMarkup:l}=await ht(async()=>{const{renderToStaticMarkup:c}=await import("./server.browser-BokSAg1N.js").then(d=>d.s);return{renderToStaticMarkup:c}},__vite__mapDeps([18,2]),import.meta.url);let r=l(nt.createElement(i,{fontSize:t}));return r.includes("<svg")?(r.includes("xmlns")||(r=r.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),r=r.replace(/width="1em"/,`width="${t}"`).replace(/height="1em"/,`height="${t}"`),r=r.replace(/\s(?:class|aria-hidden|focusable|data-fui-icon|font-size)="[^"]*"/g,""),r):null}function Au(){return window.dataverseAPI}async function gS(){let e="the organization record has no languagecode";for(let t=0;t<2;t++)try{const o=(await Au().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 bS=[/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 yS(e){const t=e instanceof Error?`${e.message} ${String(e.code??"")}`:typeof e=="string"?e:JSON.stringify(e??"");return bS.some(n=>n.test(t))}const xS={0:"Import",1:"Uninstall",2:"Export",3:"Publish",4:"PublishAll",5:"LanguageProvision",6:"ImportTranslation",7:"RibbonMetadataGeneration",8:"WorkflowSetState",10:"ExportLite",11:"UpdatingMissingPackages"},Ou=30;async function vS(e=Ou,t=Date.now()){const n=t-e*6e4;try{return((await Au().queryData("msdyn_solutionhistories?$select=msdyn_name,msdyn_operation,msdyn_status,msdyn_starttime&$orderby=msdyn_starttime desc&$top=25")).value??[]).filter(s=>typeof s.msdyn_operation=="number"&&(s.msdyn_status===0||s.msdyn_status===2)&&s.msdyn_operation!==2&&s.msdyn_operation!==10&&(!s.msdyn_starttime||Date.parse(s.msdyn_starttime)>=n)).map(s=>({operation:xS[s.msdyn_operation??-1]??`operation ${s.msdyn_operation}`,name:s.msdyn_name??"",startedOn:s.msdyn_starttime??""}))}catch{return[]}}const Mu=e=>new Promise(t=>setTimeout(t,e)),wl=e=>e.map(t=>t.name&&t.name!==t.operation?`${t.operation} (${t.name})`:t.operation).join(", ");async function YR(e={}){const t=e.sleep??Mu,n=e.now??Date.now,o=n()+(e.timeoutMs??10*6e4);for(;;){const s=await vS(Ou,n());if(s.length===0)return;if(n()>=o)throw new Error(`The environment is still busy (${wl(s)} running). Try again when it has finished — Solutions › History shows its progress.`);e.onProgress?.(`Waiting for another operation to finish: ${wl(s)}…`),await t(15e3)}}async function Eu(e,t,n={}){const o=n.sleep??Mu,s=n.now??Date.now,i=s()+(n.timeoutMs??10*6e4);for(let l=0;;l++)try{return await t()}catch(r){if(!yS(r))throw r;const c=Math.min(6e4,15e3*2**l);if(s()+c>i)throw new Error(`${e} kept failing because another solution operation is running in the environment (${r instanceof Error?r.message:String(r)}). Try again when it has finished.`);n.onProgress?.(`${e}: another solution operation is running in the environment — retrying in ${Math.round(c/1e3)} s…`),await o(c)}}function tn(){const e=window.dataverseAPI;if(!e)throw new Error("dataverseAPI is not available in the current runtime");return e}const Du={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 Bu(e){return Du[e]??"xml"}async function SS(e,t){let n="webresourceset?$select=webresourceid,name,displayname,description,webresourcetype,modifiedon,ismanaged&$orderby=name asc";if(t!==void 0){const s=Object.entries(Du).find(([,i])=>i===t)?.[0];s&&(n+=`&$filter=webresourcetype eq ${s}`)}return(await e.queryData(n)).value.map(s=>{const i=s;return{id:String(i.webresourceid??""),name:String(i.name??""),displayName:i.displayname?String(i.displayname):void 0,description:i.description?String(i.description):void 0,webResourceType:Bu(Number(i.webresourcetype??3)),modifiedOn:i.modifiedon?String(i.modifiedon):void 0,isCustom:i.ismanaged===!1}})}async function wS(e,t){const n=await e.retrieve("webresource",t,["content"]);return n.content?String(n.content):""}const Lu=61;async function zu(e,t,n,o=ws){await o("Adding the web resource to the solution"),await e.execute({operationName:"AddSolutionComponent",operationType:"action",parameters:{ComponentId:t,ComponentType:Lu,SolutionUniqueName:n,AddRequiredComponents:!1}})}class CS extends Error{constructor(t){super(`Web resource ${t} already exists; it was left as it is.`),this.name="WebResourceSaveCancelled"}}async function RS(e,t,n,o,s={}){const i=s.guard??Xc(),{displayName:l,solutionUniqueName:r,onExisting:c}=s;let d=s.keepExisting??!1;const u=await e.queryData(`webresourceset?$select=webresourceid,ismanaged&$filter=name eq '${t.replace(/'/g,"''")}'&$top=1`),m={name:t,content:n,webresourcetype:o,...l?{displayname:l}:{}};let p;if(u.value.length>0){const h=u.value[0],b=String(h.webresourceid??"");if(!d&&c){const g=h.ismanaged===!0,x=await c({id:b,name:t,managed:g});if(x==="cancel")throw new CS(t);if(x==="replace"&&g)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=x==="keep"}d||(await i("Saving the web resource"),await e.update("webresource",b,m)),p={id:b,created:!1,updated:!d}}else{await i("Saving the web resource");const h=await e.create("webresource",m);p={id:String(h.id??""),created:!0,updated:!1}}if(r&&p.id){try{await zu(e,p.id,r,i)}catch(h){throw new Error(`Web resource ${t} was saved but could not be added to solution ${r}: ${h instanceof Error?h.message:String(h)}`)}p.solutionUniqueName=r}return p}const Cl=40,Rl=(e,t)=>Array.from({length:Math.ceil(e.length/t)},(n,o)=>e.slice(o*t,(o+1)*t)),IS=e=>`'${e.replace(/'/g,"''").replace(/[^A-Za-z0-9/._\-'~]/gu,t=>encodeURIComponent(t))}'`,Il=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function jS(e,t,n){const o=t.map(c=>c.split(/[?#]/)[0].trim()).filter(Boolean),s=o.filter((c,d)=>o.findIndex(u=>u.toLowerCase()===c.toLowerCase())===d),i={};for(const c of s)i[c.toLowerCase()]={exists:!1,inSolution:!1};if(s.length===0)return i;const l=new Map;for(const c of Rl(s,Cl)){const d=c.map(m=>`name eq ${IS(m)}`).join(" or "),u=await e.queryData(`webresourceset?$select=webresourceid,name,ismanaged&$filter=${d}`);for(const m of u.value??[]){const p=m,h=String(p.name??"").toLowerCase();if(!(h in i))continue;i[h]={exists:!0,inSolution:!1,managed:p.ismanaged===!0};const b=String(p.webresourceid??"").toLowerCase();Il.test(b)&&l.set(b,h)}}const r=n?.replace(/[{}]/g,"");if(r&&Il.test(r)&&l.size>0)for(const c of Rl([...l.keys()],Cl)){const d=c.map(m=>`objectid eq ${m}`).join(" or "),u=await e.queryData(`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${r} and componenttype eq ${Lu} and (${d})`);for(const m of u.value??[]){const p=l.get(String(m.objectid??"").toLowerCase());p&&(i[p].inSolution=!0)}}return i}async function JR(e,t){return jS(tn(),e,t)}async function ZR(e){return SS(tn(),e)}async function QR(e){return wS(tn(),e)}async function $S(e){const t=tn(),n=e.replace(/'/g,"''"),o=await t.queryData(`webresourceset?$select=webresourceid,name,displayname,webresourcetype,ismanaged&$filter=name eq '${n}'&$top=1`);if(!o.value?.length)return null;const s=o.value[0];return{id:String(s.webresourceid??""),name:String(s.name??""),displayName:s.displayname?String(s.displayname):void 0,webResourceType:Bu(Number(s.webresourcetype??3)),isCustom:s.ismanaged===!1}}async function TS(e,t,n,o={}){const s=ae.getState().activeSolution,i=o.solutionUniqueName??(s&&!s.isManaged?s.uniqueName:void 0),l=o.guard??Xc(),r=await RS(tn(),e,t,n,{...o,solutionUniqueName:i,guard:l});if((r.created||r.updated)&&o.publish!==!1)try{await Eu(`Publishing web resource ${e}`,()=>Pu(r.id,l),{timeoutMs:2*6e4,onProgress:c=>re.getState().logInfo("webresource",c)}),r.published=!0}catch(c){r.publishWarning=`Web resource ${e} was saved but not published (${c instanceof Error?c.message:String(c)}). Users get the previous version until it's published: save it again, or run Publish All.`,re.getState().logWarn("webresource",r.publishWarning)}if(!i){const c=s?`the active solution ${s.uniqueName} is managed`:"no solution is selected";r.solutionWarning=`Web resource ${e} was saved but not added to any solution because ${c}. It is only in the Default solution — select an unmanaged solution and save it again so it travels with your customizations.`,re.getState().logWarn("webresource",r.solutionWarning)}return r}async function eI(e,t,n=ws){const o=t??await $S(e);if(!o?.id)throw new Error(`No web resource named ${e} exists in this environment.`);const s=o.id;if(o.isCustom===!1){const l=`Web resource ${e} is managed, so it isn't added to your solution. The solution that provides it must be installed wherever you import your customizations.`;return re.getState().logWarn("webresource",l),{solutionWarning:l}}const i=ae.getState().activeSolution;if(!i||i.isManaged){const l=i?`the active solution ${i.uniqueName} is managed`:"no solution is selected",r=`Web resource ${e} was not added to any solution because ${l}. Select an unmanaged solution and pick the icon again so it travels with your customizations.`;return re.getState().logWarn("webresource",r),{solutionWarning:r}}return await zu(tn(),s,i.uniqueName,n),{solutionUniqueName:i.uniqueName}}async function Pu(e,t=ws){const n=tn(),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 NS={5:"image/png",6:"image/jpeg",7:"image/gif",10:"image/x-icon",11:"image/svg+xml"};async function kS(e){const o=(await tn().queryData(`webresourceset?$select=content,webresourcetype&$filter=name eq '${e.replace(/'/g,"''")}'&$top=1`)).value?.[0],s=NS[Number(o?.webresourcetype)],i=o?.content;return s&&typeof i=="string"&&i?`data:${s};base64,${i}`:null}const AS=.35,Sn=24,jl=new Map;function OS(e){return new Promise(t=>{const n=new Image;n.onload=()=>{try{const o=document.createElement("canvas");o.width=Sn,o.height=Sn;const s=o.getContext("2d");if(!s)return t("light");s.drawImage(n,0,0,Sn,Sn);const{data:i}=s.getImageData(0,0,Sn,Sn);let l=0,r=0;for(let c=0;c<i.length;c+=4){const d=i[c+3]/255;d<.5||(l+=d*(.2126*i[c]+.7152*i[c+1]+.0722*i[c+2]),r+=d*255)}t(r>0&&l/r<AS?"dark":"light")}catch{t("light")}},n.onerror=()=>t("light"),n.src=e})}function MS(e){let t=jl.get(e);return t||(t=OS(e),jl.set(e,t)),t}const $l="$webresource:",ES="invert(1) hue-rotate(180deg)",hi=new Map,DS=6;let gi=0;const Tl=[];async function BS(e){gi>=DS&&await new Promise(t=>Tl.push(t)),gi++;try{return await e()}finally{gi--,Tl.shift()?.()}}function LS(e,t){let n=hi.get(e);return n||(n=BS(()=>kS(t)).catch(()=>(hi.delete(e),null)),hi.set(e,n)),n}function zS(e){return[e.image32,e.image16,e.source?.modernImage].find(n=>n?.startsWith($l))?.slice($l.length).trim()||void 0}function St({button:e,size:t,style:n}){const o=ae(p=>p.connectionUrl),s=J(p=>p.themeMode==="dark"),i=zS(e),l=i?`${o}|${i}`:"",[r,c]=B.useState({key:"",src:null}),[d,u]=B.useState(null);B.useEffect(()=>{if(!l||!i)return;let p=!0;return LS(l,i).then(h=>{p&&c({key:l,src:h})}),()=>{p=!1}},[l,i]);const m=l&&r.key===l?r.src:null;if(B.useEffect(()=>{if(!s||!m)return;let p=!0;return MS(m).then(h=>{p&&u({src:m,tone:h})}),()=>{p=!1}},[s,m]),m){const h=[s&&d?.src===m&&d.tone==="dark"&&ES,n?.filter!=="none"&&n?.filter].filter(Boolean).join(" ")||void 0;return a.jsx("img",{src:m,width:t,height:t,alt:"","aria-hidden":!0,style:{objectFit:"contain",...n,filter:h}})}return a.jsx(cr,{name:e.icon||"apps_add_in",size:t,style:n})}const Fu="__end__";function PS(e,t){return`slot::${e}::${t??Fu}`}function FS(e){return`group::${e}`}function Nl(e){if(e.startsWith("slot::")){const[,t,n]=e.split("::");return{kind:"slot",groupId:t,beforeButtonId:n===Fu?null:n}}return e.startsWith("group::")?{kind:"group",groupId:e.slice(7)}:null}const wn={root:{display:"flex",gap:f.spacingHorizontalM,flexWrap:"wrap",alignItems:"flex-start",minHeight:"120px",padding:`${f.spacingVerticalS} ${f.spacingHorizontalM}`},groupButtons:{display:"flex",gap:f.spacingHorizontalXS,flexWrap:"wrap",minHeight:"72px",alignItems:"flex-start",padding:f.spacingHorizontalXS},groupLabel:{textAlign:"center",fontSize:f.fontSizeBase100,color:f.colorNeutralForeground3,borderTop:`1px solid ${f.colorNeutralStroke2}`,paddingTop:f.spacingVerticalXS,paddingBottom:f.spacingVerticalXS,marginTop:"auto"},emptyTab:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:f.spacingVerticalM,minHeight:"160px",color:f.colorNeutralForeground3,flex:1,padding:"48px",textAlign:"center"},addGroupBtn:{minHeight:"96px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",border:`1px dashed ${f.colorNeutralStroke2}`,borderRadius:f.borderRadiusMedium,cursor:"pointer",color:f.colorNeutralForeground3,backgroundColor:"transparent"},addButtonGhost:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",width:"60px",minHeight:"72px",borderRadius:f.borderRadiusMedium,border:`1px dashed ${f.colorNeutralStroke2}`,backgroundColor:"transparent",cursor:"pointer",color:f.colorNeutralForeground3}};function _S({button:e}){const t=D(s=>s.locLabels),o=Be()(e.label,t,void 0,e.source?.labelToken);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:f.borderRadiusMedium,border:`1px solid ${f.colorBrandStroke1}`,backgroundColor:f.colorNeutralBackground1,boxShadow:f.shadow16,opacity:.9,cursor:"grabbing",pointerEvents:"none",color:e.custom?f.colorBrandForeground1:f.colorNeutralForeground1},children:[a.jsx(St,{button:e,size:24}),a.jsx("span",{style:{fontSize:f.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.colorNeutralForeground1},children:o})]})}function qS({group:e,isDropTarget:t,children:n,...o}){const{setNodeRef:s,isOver:i}=Ba({id:FS(e.id),data:{type:"group",groupId:e.id}});return a.jsx("div",{ref:s,style:{display:"flex",flexDirection:"column",minWidth:"80px",border:`1px solid ${i||t?f.colorBrandStroke1:f.colorNeutralStroke2}`,borderRadius:f.borderRadiusMedium,backgroundColor:i||t?f.colorBrandBackground2:f.colorNeutralBackground2,padding:`${f.spacingVerticalXS} ${f.spacingHorizontalXS}`,transition:"border-color 0.1s, background-color 0.1s"},...o,children:n})}function kl({groupId:e,beforeButtonId:t}){const n=PS(e,t),{setNodeRef:o,isOver:s}=Ba({id:n,data:{type:"slot",groupId:e,beforeButtonId:t}});return a.jsx("div",{ref:o,style:{width:s?"2px":"0px",minHeight:"72px",backgroundColor:f.colorBrandStroke1,borderRadius:"2px",flexShrink:0,transition:"width 0.1s"},"aria-hidden":!0})}function HS({tab:e,location:t}){const n=D(O=>O.locLabels),o=Be(),s=D(O=>O.baseLanguageCode),i=O=>vt(O.id,o(O.label,n,s,O.source?.titleToken)),l=D(O=>O.moveButton),r=D(O=>O.createGroup),c=J(O=>O.openNewButton),d=J(O=>O.openNewGroup),u=Z(O=>O.selectButtonInContext),m=Z(O=>O.selectGroup),[p,h]=B.useState(null),[b,g]=B.useState(null),[x,y]=B.useState(null),[S,C]=B.useState(null),R=B.useMemo(()=>{if(!x)return null;for(const O of e.groups){const A=O.buttons.find(E=>E.id===x);if(A)return{button:A,groupId:O.id}}return null},[x,e.groups]),M=_c(Qo(Uc,{activationConstraint:{distance:5}}),Qo(Gc));function I(O){y(String(O.active.id))}function $(O){const A=O.over;if(!A){C(null);return}const E=Nl(String(A.id));C(E?E.groupId:null)}function T(){y(null),C(null)}function v(O){const{active:A,over:E}=O;if(y(null),C(null),!E||!A)return;let w=null;for(const j of e.groups)if(j.buttons.some(_=>_.id===A.id)){w=j.id;break}if(!w)return;const k=Nl(String(E.id));if(!k)return;let N=null;k.kind==="slot"?N=l({groupId:w,buttonId:String(A.id),tabId:e.id,location:t},{groupId:k.groupId,beforeButtonId:k.beforeButtonId??void 0,tabId:e.id,location:t}):k.kind==="group"&&k.groupId!==w&&(N=l({groupId:w,buttonId:String(A.id),tabId:e.id,location:t},{groupId:k.groupId,tabId:e.id,location:t})),N&&N!==String(A.id)&&u(t,e.id,k.groupId,N)}return e.groups.length===0?a.jsxs("div",{style:wn.emptyTab,children:[a.jsx(Ss,{fontSize:36,"aria-hidden":!0}),a.jsx(X,{children:"This tab has no groups yet"}),a.jsxs("button",{type:"button",style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 16px",background:f.colorBrandBackground,color:f.colorNeutralForegroundInverted,border:"none",borderRadius:f.borderRadiusMedium,cursor:"pointer",fontSize:f.fontSizeBase300},onClick:()=>d(),children:[a.jsx(ke,{fontSize:12})," Add first group"]})]}):a.jsxs(a.Fragment,{children:[a.jsxs(qc,{sensors:M,collisionDetection:Hc,onDragStart:I,onDragOver:$,onDragEnd:v,onDragCancel:T,children:[a.jsxs("div",{style:wn.root,role:"group","aria-label":"Groups","data-ribbon-canvas-root":"1",children:[e.groups.map(O=>a.jsxs(qS,{group:O,isDropTarget:S===O.id,role:"group","aria-label":i(O),tabIndex:0,"data-ribbon-group-id":O.id,onContextMenu:A=>{A.target.closest("[data-btn]")||(A.preventDefault(),g({group:O,anchor:{x:A.clientX,y:A.clientY}}))},onFocus:A=>{A.target===A.currentTarget&&m(O.id)},onKeyDown:A=>{if(A.target===A.currentTarget&&(A.key==="Enter"||A.key===" ")&&O.buttons.length>0){A.preventDefault();const E=O.buttons[0];if(!E)return;u(t,e.id,O.id,E.id),document.querySelector(`[data-ribbon-btn-id="${E.id}"]`)?.focus()}},children:[a.jsxs("div",{style:wn.groupButtons,children:[O.buttons.map(A=>a.jsxs(nt.Fragment,{children:[x&&a.jsx(kl,{groupId:O.id,beforeButtonId:A.id}),a.jsx(WS,{button:A,groupId:O.id,tabId:e.id,location:t,activeId:x,onContextMenu:E=>h({groupId:O.id,button:A,anchor:E.currentTarget})})]},A.id)),x&&a.jsx(kl,{groupId:O.id,beforeButtonId:null}),a.jsxs("button",{type:"button",style:wn.addButtonGhost,"data-add-btn-group-id":O.id,disabled:!!We(t,e.id,O.id),onClick:()=>c(O.id),title:We(t,e.id,O.id)??`Add button to ${i(O)}`,"aria-label":`Add button to ${i(O)}`,children:[a.jsx(ke,{fontSize:16}),a.jsx(X,{size:100,style:{color:"inherit"},children:"Add"})]})]}),a.jsx(he,{content:`Template: ${O.template||"Flexible2"}`,relationship:"description",children:a.jsx("div",{style:wn.groupLabel,children:i(O)})})]},O.id)),a.jsx("button",{type:"button",style:wn.addGroupBtn,disabled:!!Zt(t,e.id),onClick:()=>r({tabId:e.id,location:t,group:{label:"New Group",sequence:(e.groups.length+1)*10,template:"Flexible2",buttons:[]}}),title:Zt(t,e.id)??"Add group","aria-label":"Add group",children:a.jsx(ke,{fontSize:16})})]}),a.jsx(Wc,{dropAnimation:null,children:R?a.jsx(_S,{button:R.button}):null})]}),a.jsx(To,{location:t,tab:e,target:p,onClose:()=>h(null)}),a.jsx(lr,{location:t,tab:e,target:b,onClose:()=>g(null)})]})}const WS=nt.memo(function({button:t,groupId:n,tabId:o,location:s,activeId:i,onContextMenu:l}){const r=Z(v=>v.selectedButtonId),c=Z(v=>v.selectButtonInContext),d=D(v=>v.locLabels),u=Be(),m=r===t.id,p=s==="Application"&&o==="Mscrm.GlobalTab"&&t.oob&&!t.custom,h=u(t.label,d,void 0,t.source?.labelToken),b=ut(t.kind)?xt[t.kind]:void 0,g=b?` (${b}, read-only)`:"",{attributes:x,listeners:y,setNodeRef:S,isDragging:C}=rb({id:t.id,data:{type:"button",button:t,groupId:n},disabled:t.managed||p}),R=C||i===t.id,{onKeyDown:M,...I}=y??{},$={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:f.borderRadiusMedium,cursor:"grab",border:m?`1px solid ${f.colorBrandStroke1}`:t.custom?`1px solid ${f.colorBrandStroke2}`:"1px solid transparent",backgroundColor:m?f.colorBrandBackground2:t.managed?f.colorNeutralBackground3:"transparent",opacity:R?.3:t.hidden?.4:1,position:"relative",userSelect:"none",color:t.custom?f.colorBrandForeground1:f.colorNeutralForeground1,transition:"opacity 0.15s, border-color 0.1s, background-color 0.1s"},T=v=>{if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(v.key))return;v.preventDefault();const O=v.currentTarget.closest("[data-ribbon-canvas-root='1']");if(!O)return;const A=Array.from(O.querySelectorAll(`[data-ribbon-tab-id="${o}"][data-btn="1"]`)),E=A.findIndex(W=>W.dataset.ribbonBtnId===t.id);if(E<0||A.length===0)return;const w=v.key==="ArrowLeft"||v.key==="ArrowUp"?-1:1,k=Math.max(0,Math.min(A.length-1,E+w)),N=A[k],j=N?.dataset.ribbonGroupId,_=N?.dataset.ribbonBtnId;!N||!j||!_||(c(s,o,j,_),N.focus())};return a.jsx(he,{content:p?"OOB global command bar buttons cannot be customized.":`${h}${g}${t.hidden?" — hidden":""}`,relationship:"label",children:a.jsxs("button",{ref:S,type:"button","data-btn":"1","data-ribbon-tab-id":o,"data-ribbon-group-id":n,"data-ribbon-btn-id":t.id,style:$,"aria-current":m?"true":void 0,"aria-label":`${h}${g}${t.hidden?" — hidden":""}${t.custom?" (custom)":""}${t.managed?" (read-only)":""}`,onClick:()=>c(s,o,n,t.id),onFocus:()=>c(s,o,n,t.id),onKeyDown:v=>{if(!i){if(v.key==="Enter"||v.key===" "){c(s,o,n,t.id),M?M(v):v.preventDefault();return}T(v)}},onContextMenu:v=>{v.preventDefault(),v.stopPropagation(),c(s,o,n,t.id),l(v)},...x,...I,children:[a.jsx(St,{button:t,size:24,style:{filter:t.custom?"none":"grayscale(40%) opacity(0.85)"}}),a.jsx("span",{style:{fontSize:f.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.colorNeutralForeground1},children:h}),b&&a.jsx("span",{style:{fontSize:f.fontSizeBase100,lineHeight:"1",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:f.colorNeutralForeground3},children:b}),t.menu&&a.jsx(dt,{fontSize:10,"aria-label":"Has a menu"}),t.hidden&&a.jsx("span",{style:{position:"absolute",top:2,right:2},"aria-hidden":!0,children:a.jsx(Lt,{fontSize:10,style:{color:f.colorNeutralForeground3}})}),t.custom&&!t.managed&&a.jsx(he,{content:"Yours: added by your customizations",relationship:"label",children:a.jsx(xe,{size:"extra-small",color:"brand",style:{position:"absolute",bottom:4,right:4}})}),(t.managed||p)&&a.jsx("span",{style:{position:"absolute",top:2,left:2},title:p?"OOB global command bar buttons cannot be customized.":"Read-only (managed)",children:a.jsx(fn,{fontSize:10,style:{color:f.colorNeutralForeground3}})})]})})});function GS(e,t,n){if(!t.buttonId||n.groupId===t.groupId&&n.buttonId===t.buttonId)return null;const o=e.find(r=>r.id===n.groupId);if(!o)return null;const s=ft(o.buttons);if(!n.buttonId)return o.id===t.groupId&&s.at(-1)?.id===t.buttonId?null:{groupId:o.id};const i=s.findIndex(r=>r.id===n.buttonId);if(i<0)return null;const l=o.id===t.groupId?s.findIndex(r=>r.id===t.buttonId):-1;if(l>=0&&l<i){const r=s[i+1]?.id;return r?{groupId:o.id,before:r}:{groupId:o.id}}return{groupId:o.id,before:n.buttonId}}const dr=pe({root:{display:"flex",flexWrap:"wrap",alignItems:"flex-start",gap:f.spacingHorizontalM},card:{flex:"1 1 240px",minWidth:"220px",maxWidth:"320px",display:"flex",flexDirection:"column",backgroundColor:f.colorNeutralBackground1,border:`1px solid ${f.colorNeutralStroke2}`,borderRadius:f.borderRadiusLarge,boxShadow:f.shadow2,minHeight:0},cardSelected:{border:`1px solid ${f.colorBrandStroke1}`},cardOver:{backgroundColor:f.colorBrandBackground2},header:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalXS} ${f.spacingVerticalXS} ${f.spacingHorizontalM}`,borderBottom:`1px solid ${f.colorNeutralStroke3}`},titleButton:{flex:1,minWidth:0,display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",padding:0,fontWeight:"inherit",textAlign:"left"},ellipsis:{display:"block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:f.colorNeutralForeground3},rows:{display:"flex",flexDirection:"column",padding:f.spacingVerticalXS,gap:"2px",minHeight:"8px"},row:{display:"flex",alignItems:"center",justifyContent:"flex-start",gap:f.spacingHorizontalS,width:"100%",maxWidth:"100%",minWidth:0,minHeight:"32px",padding:`0 ${f.spacingHorizontalS}`,fontWeight:f.fontWeightRegular,textAlign:"left"},rowSelected:{backgroundColor:f.colorSubtleBackgroundSelected,border:`1px solid ${f.colorBrandStroke1}`},rowHidden:{color:f.colorNeutralForeground3},handle:{color:f.colorNeutralForeground3,flexShrink:0},handleOff:{visibility:"hidden"},label:{flex:1,minWidth:0},footer:{padding:`0 ${f.spacingHorizontalXS} ${f.spacingVerticalXS}`},overlay:{boxShadow:f.shadow16,backgroundColor:f.colorNeutralBackground1,borderRadius:f.borderRadiusMedium}}),US=e=>{const t=e.droppableContainers.filter(i=>String(i.id).startsWith("row:")),n=e.droppableContainers.filter(i=>String(i.id).startsWith("card:"));if(e.pointerCoordinates){const i=Dr({...e,droppableContainers:t});if(i.length)return i;const l=Dr({...e,droppableContainers:n});if(l.length)return l}const o=new Set(t.map(i=>i.data.current?.groupId)),s=n.filter(i=>!o.has(i.data.current?.groupId));return Hc({...e,droppableContainers:[...t,...s]})},ur=(e,t)=>`row:${e}:${t}`,_u=e=>`card:${e}`;function VS({tab:e,location:t}){const n=dr(),o=Be(),s=D(w=>w.locLabels),i=D(w=>w.baseLanguageCode),l=D(w=>w.moveButton),r=Z(w=>w.selectedGroupId),c=Z(w=>w.selectedButtonId),d=Z(w=>w.selectGroup),u=Z(w=>w.selectButtonInContext),m=J(w=>w.openNewButton),[p,h]=B.useState(null),[b,g]=B.useState(null),[x,y]=B.useState(null),[S,C]=B.useState(null),R=B.useRef(null),M=w=>vt(w.id,o(w.label,s,i,w.source?.titleToken)),I=w=>o(w.label,s,void 0,w.source?.labelToken)||w.id,$=_c(Qo(Uc,{activationConstraint:{distance:5}}),Qo(Gc,{coordinateGetter:lb,keyboardCodes:{start:["Space"],cancel:["Escape"],end:["Space","Enter"]}})),T=w=>setTimeout(()=>{if(document.activeElement?.closest('[role="dialog"], [role="alertdialog"]'))return;const k=Z.getState().selectedButtonId;(w instanceof HTMLElement&&w.isConnected?w:[...R.current?.querySelectorAll("[data-card-button]")??[]].find(j=>j.dataset.cardButton===k))?.focus()}),v=w=>{const k=String(w??"");for(const N of e.groups){if(k===_u(N.id))return`the end of ${M(N)}`;const j=N.buttons.find(_=>k===ur(N.id,_.id));if(j)return`${I(j)} in ${M(N)}`}return""},O=w=>w&&typeof w=="object"&&"groupId"in w?w:null,A=w=>{const k=O(w.active.data.current),N=e.groups.find(_=>_.id===k?.groupId),j=N?.buttons.find(_=>_.id===k?.buttonId);N&&j&&y({button:j,groupId:N.id})},E=w=>{y(null),C(null);const k=O(w.active.data.current),N=O(w.over?.data.current);if(!k?.buttonId||!N)return;const j=GS(e.groups,k,N);if(!j)return;const _=l({location:t,tabId:e.id,groupId:k.groupId,buttonId:k.buttonId},{location:t,tabId:e.id,groupId:j.groupId,beforeButtonId:j.before});_&&(u(t,e.id,j.groupId,_),setTimeout(()=>[...R.current?.querySelectorAll("[data-card-button]")??[]].find(W=>W.dataset.cardButton===_)?.focus()))};return a.jsxs(a.Fragment,{children:[a.jsxs(qc,{sensors:$,collisionDetection:US,onDragStart:A,onDragOver:w=>C(O(w.over?.data.current)?.groupId??null),onDragEnd:E,onDragCancel:()=>{y(null),C(null)},accessibility:{screenReaderInstructions:{draggable:"To move a button, press Space. Use the arrow keys to move it, Space or Enter to drop it, Escape to cancel."},announcements:{onDragStart:({active:w})=>`Picked up ${v(w.id)}.`,onDragOver:({active:w,over:k})=>k?`${v(w.id)} is over ${v(k.id)}.`:void 0,onDragEnd:({active:w,over:k})=>k?`${v(w.id)} was dropped on ${v(k.id)}.`:`${v(w.id)} was dropped.`,onDragCancel:({active:w})=>`Moving ${v(w.id)} was cancelled.`}},children:[a.jsx("div",{ref:R,className:n.root,"aria-label":`Groups of ${e.id}`,role:"list",children:ft(e.groups).map(w=>a.jsx(XS,{group:w,tab:e,location:t,title:M(w),buttonText:I,selected:r===w.id&&!c,selectedButtonId:r===w.id?c:null,dropping:S===w.id&&!!x,onSelectGroup:()=>d(w.id),onSelectButton:k=>u(t,e.id,w.id,k.id),onGroupMenu:k=>h({group:w,anchor:k}),onButtonMenu:(k,N)=>g({button:k,groupId:w.id,anchor:N}),onAddButton:()=>m(w.id),addBlockedReason:We(t,e.id,w.id)},w.id))}),a.jsx(Wc,{dropAnimation:null,children:x&&a.jsxs("div",{className:Ce(n.row,n.overlay),children:[a.jsx(kc,{className:n.handle}),a.jsx(St,{button:x.button,size:16}),a.jsx("span",{className:Ce(n.label,n.ellipsis),children:I(x.button)})]})})]}),a.jsx(lr,{location:t,tab:e,target:p,onClose:()=>{T(p?.anchor),h(null)}}),a.jsx(To,{location:t,tab:e,target:b,onClose:()=>{T(b?.anchor),g(null)}})]})}function XS({group:e,tab:t,location:n,title:o,buttonText:s,selected:i,selectedButtonId:l,dropping:r,onSelectGroup:c,onSelectButton:d,onGroupMenu:u,onButtonMenu:m,onAddButton:p,addBlockedReason:h}){const b=dr(),{setNodeRef:g}=Ba({id:_u(e.id),data:{groupId:e.id}}),x=ft(e.buttons);return a.jsxs("section",{ref:g,role:"listitem","aria-label":o,"data-group-card":e.id,className:Ce(b.card,i&&b.cardSelected,r&&b.cardOver),children:[a.jsxs("div",{className:b.header,children:[a.jsx(he,{content:`${o} (${e.id})`,relationship:"description",children:a.jsxs(Y,{appearance:"transparent",className:b.titleButton,"aria-pressed":i,onClick:c,onContextMenu:y=>{y.preventDefault(),u(y.currentTarget)},onKeyDown:y=>{(y.key==="ContextMenu"||y.shiftKey&&y.key==="F10")&&(y.preventDefault(),u(y.currentTarget))},children:[a.jsx(X,{weight:"semibold",size:300,className:b.ellipsis,children:o}),a.jsx(X,{size:200,className:Ce(b.ellipsis,b.muted),children:e.template||"Flexible2"})]})}),a.jsx(he,{content:"Group options",relationship:"label",children:a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(Ac,{}),"aria-label":`Group options: ${o}`,onClick:y=>u(y.currentTarget)})})]}),a.jsx(cb,{items:x.map(y=>ur(e.id,y.id)),strategy:db,children:a.jsx("div",{className:b.rows,role:"list","aria-label":`Buttons in ${o}`,children:x.map(y=>a.jsx(KS,{button:y,groupId:e.id,text:s(y),locked:y.managed||Va(n,t.id,y),selected:l===y.id,onSelect:()=>d(y),onMenu:S=>m(y,S)},y.id))})}),a.jsx("div",{className:b.footer,children:a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),disabledFocusable:!!h,title:h,onClick:p,"aria-label":`Add button to ${o}`,children:"Add button"})})]})}function KS({button:e,groupId:t,text:n,locked:o,selected:s,onSelect:i,onMenu:l}){const r=dr(),{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:h}=ub({id:ur(t,e.id),data:{groupId:t,buttonId:e.id},disabled:{draggable:o,droppable:!1}}),b=e.custom&&!e.managed,g=ut(e.kind)?xt[e.kind]:void 0,x=`${n}${g?` (${g}, read-only)`:""}${e.hidden?", hidden":""}${b?", yours":""}, Sequence ${e.sequence}`;return a.jsx("div",{role:"listitem",style:{opacity:h?.4:1},children:a.jsx(he,{content:`${n} (${e.id})`,relationship:"description",children:a.jsxs(Y,{ref:u,appearance:"subtle",...c,...d,"aria-roledescription":o?void 0:"draggable button","aria-label":x,"aria-pressed":s,"data-card-button":e.id,className:Ce(r.row,s&&r.rowSelected,e.hidden&&r.rowHidden),style:{transform:mb.Transform.toString(m),transition:p},onClick:i,onContextMenu:y=>{y.preventDefault(),l(y.currentTarget)},onKeyDown:y=>{if(y.key==="ContextMenu"||y.shiftKey&&y.key==="F10"){y.preventDefault(),l(y.currentTarget);return}d?.onKeyDown?.(y)},children:[a.jsx(kc,{"aria-hidden":!0,className:Ce(r.handle,o&&r.handleOff)}),a.jsx(St,{button:e,size:16}),a.jsx("span",{className:Ce(r.label,r.ellipsis),children:n}),e.hidden?a.jsx(xe,{size:"medium",appearance:"outline",color:"subtle",children:"Hidden"}):b?a.jsx(xe,{size:"medium",appearance:"tint",color:"brand",children:"Yours"}):null,a.jsx(X,{size:200,className:r.muted,children:e.sequence})]})})})}const no={Form:0,MainGrid:1,SubGrid:2,AssociatedGrid:3,GlobalHeader:5},YS={0:"Form",1:"Main grid",2:"Subgrid",3:"Associated grid",4:"Quick form",5:"Global header",6:"Dashboard"},qu="appaction_appactionrule_classicrules",JS=["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"],bi="@OData.Community.Display.V1.FormattedValue",De=e=>typeof e=="string"&&e.trim()!==""?e:typeof e=="number"?String(e):void 0,Ot=e=>{if(e==null||e==="")return;const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0},zo=e=>e===!0||e===1||e==="true"||e==="1",an=e=>{const t=De(e);return t?t.toLowerCase():null};function ZS(e){switch(Ot(e)){case 1:return"dropdown";case 2:return"split";case 3:return"group";default:return"button"}}function QS(e){const t=Ot(e);return t===1?"formula":t===2?"javascript":"none"}function ew(e){const t=Ot(e);return t===1?"formula":t===2?"classicRules":"none"}function tw(e){const t=Ot(e);return t===1?"migrated":t===2?"enhancedMigrated":"default"}function Al(e,t){const n={componentLibrary:De(e[`${t}componentlibrary`]),componentName:De(e[`${t}componentname`]),functionName:De(e[`${t}functionname`])};return n.componentLibrary||n.componentName||n.functionName?n:void 0}function nw(e){return Array.isArray(e)?e.map(t=>{const n=an(t.appactionruleid);return n?{id:n,name:De(t.name)??De(t.uniquename)??n,uniqueName:De(t.uniquename),kind:Ot(t.type)===0?"enable":"display"}:null}).filter(t=>t!==null):[]}function ow(e){const t=an(e.appactionid);if(!t)return null;const n=Ot(e.location);if(n===void 0)return null;const o=De(e.name)??"",s=De(e.uniquename)??o;return{id:t,name:o,uniqueName:s,label:De(e.buttonlabeltext)??(o||s||t),tooltipTitle:De(e.buttontooltiptitle),tooltipDescription:De(e.buttontooltipdescription),accessibilityText:De(e.buttonaccessibilitytext),appModuleId:an(e._appmoduleid_value),appName:De(e[`_appmoduleid_value${bi}`]),scope:Ot(e.context)===0?"all":"entity",contextValue:De(e.contextvalue),contextEntityId:an(e._contextentity_value)??void 0,location:n,type:ZS(e.type),sequence:Ot(e.sequence)??Ot(e.buttonsequencepriority)??0,hidden:zo(e.hidden),disabled:zo(e.isdisabled),origin:tw(e.origin),managed:zo(e.ismanaged),fontIcon:De(e.fonticon),iconWebResourceId:an(e._iconwebresourceid_value)??void 0,iconWebResourceName:De(e[`_iconwebresourceid_value${bi}`]),parentId:an(e._parentappactionid_value),groupTitle:De(e.grouptitle),groupTitleHidden:zo(e.isgrouptitlehidden),action:QS(e.onclickeventtype),jsFunctionName:De(e.onclickeventjavascriptfunctionname),jsParameters:De(e.onclickeventjavascriptparameters),jsWebResourceId:an(e._onclickeventjavascriptwebresourceid_value)??void 0,jsWebResourceName:De(e[`_onclickeventjavascriptwebresourceid_value${bi}`]),onSelectFormula:Al(e,"onclickeventformula"),visibility:ew(e.visibilitytype),visibilityFormula:Al(e,"visibilityformula"),classicRules:nw(e[qu])}}function sw(e){const t=new Map;for(const n of e){const o=ow(n);o&&!t.has(o.id)&&t.set(o.id,o)}return[...t.values()]}function iw(e){switch(e){case"HomepageGrid":return[no.MainGrid];case"SubGrid":return[no.SubGrid,no.AssociatedGrid];case"Form":return[no.Form];case"Application":return[no.GlobalHeader]}}function aw(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 rw(e,t){return t==="all"||e.appModuleId===null||e.appModuleId===t.toLowerCase()}function lw(e,t){const n=new Set(iw(t.location));return e.filter(o=>n.has(o.location)&&rw(o,t.appFilter)&&aw(o,t.table))}const ca=(e,t)=>e.sequence-t.sequence||e.label.localeCompare(t.label)||e.id.localeCompare(t.id);function Hu(e){const t=new Set(e.map(l=>l.id)),n=new Map,o=[];for(const l of e)if(l.parentId&&l.parentId!==l.id&&t.has(l.parentId)){const r=n.get(l.parentId)??[];r.push(l),n.set(l.parentId,r)}else o.push(l);const s=new Set,i=l=>{s.add(l.id);const r=(n.get(l.id)??[]).filter(c=>!s.has(c.id)).sort(ca);return{command:l,children:r.map(i)}};return o.sort(ca).map(i)}function Wu(e){return e.flatMap(t=>[t.command,...Wu(t.children)])}const Gu=/\{!EntityLogicalName\}/gi,cw=/(?:![A-Za-z0-9_]+)*!\d+$/;function dw(e,t){if(e.origin==="default")return[];const n=[],o=s=>{s.includes(".")&&!n.includes(s)&&n.push(s)};for(const s of[e.uniqueName,e.name]){if(!s)continue;const i=s.trim().replace(Gu,t).replace(cw,""),l=i.indexOf("_"),r=i.indexOf(".");l>0&&(r===-1||l<r)&&o(i.slice(l+1)),o(i)}return n}function da(e,t){return e.replace(Gu,t).toLowerCase()}function Ol(e,t){const n=da(e,t).split(".");return n.length<4||n[0]!=="mscrm"?null:[n[0],n[1],"*",...n.slice(3)].join(".")}function Ml(e,t,n,o={}){const s=new Map,i=new Map;for(const r of t){const c=da(r,n);s.has(c)||s.set(c,r);const d=Ol(r,n);d&&!i.has(d)&&i.set(d,r)}const l=new Map;for(const r of e){if(r.disabled&&!o.includeDisabled)continue;const c=dw(r,n),d=c.map(m=>s.get(da(m,n))).find(Boolean)??c.map(m=>Ol(m,n)).map(m=>m?i.get(m):void 0).find(Boolean);if(!d)continue;const u=l.get(d)??[];u.push({buttonId:d,command:r,effect:r.hidden?"hidden":"replaced"}),l.set(d,u)}return l}function uw(e,t,n){const o=l=>l.toLowerCase(),s=`mscrm.${o(t)}.${o(n)}.maintab`,i=e.find(l=>l.id==="Mscrm.GlobalTab")?.id;return t==="Application"&&i?i:e.find(l=>o(l.id)===s)?.id??e.find(l=>/maintab$/i.test(l.id)&&!/\.allentities\./i.test(l.id))?.id??i??e[0]?.id}function Uu(e){return(e.menu?.sections??[]).flatMap(t=>t.controls.flatMap(n=>[n,...Uu(n)]))}function mw(e){const{commands:t,tabs:n,location:o,entityLogicalName:s}=e,i=n.flatMap(y=>y.groups.flatMap(S=>S.buttons)),l=[...i,...i.flatMap(Uu)].map(y=>y.id),r=new Map(t.map(y=>[y.id,y])),c=new Set([...Ml(t,l,s,{includeDisabled:!0}).values()].flat().map(y=>y.command.id)),d=new Map,u=(y,S=new Set)=>{const C=d.get(y.id);if(C!==void 0)return C;let R=y.parentId?r.get(y.parentId):void 0;for(const I=new Set;R?.type==="group"&&!c.has(R.id)&&!I.has(R.id);)I.add(R.id),R=R.parentId?r.get(R.parentId):void 0;const M=c.has(y.id)&&(!R||!S.has(R.id)&&u(R,S.add(y.id)));return d.set(y.id,M),M},p=(y=>{for(const[S,C]of y){const R=C.filter(M=>u(M.command));R.length>0?y.set(S,R):y.delete(S)}return y})(Ml(t,l,s)),h=new Set([...p.values()].flat().map(y=>y.command.id)),b=y=>{const S=new Set;for(let C=y.parentId;C&&!S.has(C);C=r.get(C)?.parentId??null){S.add(C);const R=r.get(C);if(R&&u(R))return C}},g=new Map,x=[];for(const y of t){const S=b(y);if(!S){u(y)||x.push(y);continue}if(h.has(y.id))continue;const C=g.get(S)??[];C.push(y),g.set(S,C)}for(const y of p.values())for(const S of y){const C=g.get(S.command.id);C&&(S.items=[...C].sort(ca))}return{commandBarTabId:uw(n,o,s),nodes:Hu(x),overrides:p,unmatchedMigrated:x.filter(y=>y.origin!=="default")}}function Vu(e,t){const n=new Map,o=[];for(const s of t){const i=e.find(r=>r.sequence>s.command.sequence);if(!i){o.push(s);continue}const l=n.get(i.id)??[];l.push(s),n.set(i.id,l)}return{before:n,trailing:o}}function El(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 pw(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 fw(e,t,n){const o=new Map(t.map(i=>[i.id.toLowerCase(),i])),s=new Map;for(const i of n??[]){const l=o.get(i.toLowerCase());l&&s.set(l.id.toLowerCase(),l)}if(n)return[...s.values()].sort((i,l)=>i.name.localeCompare(l.name)||i.id.localeCompare(l.id));for(const i of e)!i.appModuleId||s.has(i.appModuleId)||s.set(i.appModuleId,o.get(i.appModuleId)??{id:i.appModuleId,name:i.appName??i.appModuleId});return[...s.values()].sort((i,l)=>i.name.localeCompare(l.name)||i.id.localeCompare(l.id))}function So(e,t){return e.appModuleId===null?"All apps":t?.get(e.appModuleId)??e.appName??e.appModuleId}function mr(e,t){const n=So(e.command,t),o=e.command.appModuleId===null?"in all apps":`in ${n}`,s=e.effect==="hidden"?`Hidden by modern command ${e.command.label} ${o}`:`Rendered as modern command ${e.command.label} ${o} (migrated)`;return e.items?.length?`${s}; its menu also has ${e.items.map(i=>i.label).join(", ")}`:s}function Xu(e,t){if(!e?.length)return"";const n=e.find(o=>o.effect==="hidden");return n?` — ${mr(n,t).replace(/^Hidden/,"hidden")}`:" — modern (migrated)"}const hw={button:"Command",dropdown:"Dropdown",split:"Split button",group:"Group"},gw={default:"Command designer",migrated:"Migrated from classic",enhancedMigrated:"Enhanced migrated from classic"};function Ku(e,t){const n=[{label:"App",value:So(e,t)},{label:"Location",value:`${YS[e.location]??`Location ${e.location}`}${e.scope==="all"?" (all entities)":""}`},{label:"Type",value:hw[e.type]},{label:"Order",value:String(e.sequence)},{label:"Origin",value:gw[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:El(e.visibilityFormula)??"Power Fx formula"});else if(e.visibility==="classicRules"){const o=e.classicRules.filter(s=>s.kind==="display").map(s=>s.name);n.push({label:"Visibility",value:o.length?`Classic rules: ${o.join(", ")}`:"Classic rules"})}if(e.action==="formula")n.push({label:"OnSelect (Power Fx)",value:El(e.onSelectFormula)??"Power Fx formula"});else if(e.action==="javascript"){const o=e.jsWebResourceName??e.jsWebResourceId,s=e.jsFunctionName??"(no function)";n.push({label:"Action (JavaScript)",value:o?`${s} in ${o}`:s}),e.jsParameters&&n.push({label:"Parameters",value:e.jsParameters})}return n}function bw(){return window.dataverseAPI}const wo=e=>e instanceof Error?e.message:String(e);async function bs(e){const t=[],n=new Set;let o=e;for(;o&&!n.has(o);){n.add(o);const s=await bw().queryData(o);t.push(...s.value??[]);const i=s["@odata.nextLink"];o=i?i.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}function Yu(e){return/\b40[13]\b|0x80040220|prvRead|privilege|unauthori[sz]ed|forbidden|not have permission/i.test(wo(e))}const Ju=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Dl(e,t){const n=[`contextvalue eq '${e.logicalName.replace(/'/g,"''")}'`];e.metadataId&&Ju.test(e.metadataId)&&n.push(`_contextentity_value eq ${e.metadataId}`);const o=`statecode eq 0 and (context eq 0 or ${n.join(" or ")}) and (location eq 0 or location eq 1 or location eq 2 or location eq 3 or location eq 5)`,s=t?`&$expand=${qu}($select=appactionruleid,name,uniquename,type)`:"";return`appactions?$select=${JS.join(",")}&$filter=${o}${s}`}async function yw(e){const t=re.getState();let n;try{n=await bs(Dl(e,!0))}catch(o){if(Yu(o))throw o;t.logInfo("dataverse",`Modern commands: classic rules couldn't be expanded (${wo(o)}); retrying without them.`),n=await bs(Dl(e,!1))}return sw(n)}async function xw(e){const t=re.getState(),n="appmodules?$select=appmoduleid,appmoduleidunique,name,uniquename",o=e.metadataId&&Ju.test(e.metadataId)?`appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 1 and objectid eq ${e.metadataId}`:null,[s,i]=await Promise.all([bs(n),o?bs(o).catch(d=>(t.logInfo("dataverse",`Modern commands: couldn't resolve which apps contain ${e.logicalName} (${wo(d)}).`),null)):Promise.resolve(null)]),l=s,r=l.filter(d=>!!d.appmoduleid).map(d=>({id:String(d.appmoduleid).toLowerCase(),name:d.name?.trim()||d.uniquename||String(d.appmoduleid),uniqueName:d.uniquename}));let c=null;if(i){const d=new Set(i.map(u=>u._appmoduleidunique_value).filter(u=>typeof u=="string").map(u=>u.toLowerCase()));c=new Set(l.filter(u=>u.appmoduleid&&u.appmoduleidunique&&d.has(u.appmoduleidunique.toLowerCase())).map(u=>String(u.appmoduleid).toLowerCase()))}return{apps:r,containingAppIds:c}}async function vw(e){const t=re.getState(),[n,o]=await Promise.allSettled([yw(e),xw(e)]);if(n.status==="rejected"){const r=wo(n.reason);return t.logWarn("dataverse",Yu(n.reason)?`No permission to read modern commands (appaction) for ${e.logicalName}; the canvas shows classic commands only. (${r})`:`Modern commands unavailable for ${e.logicalName}: ${r}`),{commands:[],apps:[],error:r}}o.status==="rejected"&&t.logInfo("dataverse",`Modern commands: app list unavailable (${wo(o.reason)}); showing app ids from the commands.`);const{apps:s,containingAppIds:i}=o.status==="fulfilled"?o.value:{apps:[],containingAppIds:null},l=pw(n.value,i);return t.logInfo("dataverse",`Loaded ${l.length} modern command${l.length===1?"":"s"} for ${e.logicalName}.`),{commands:l,apps:fw(l,s,i)}}function Sw(){const e=ae(n=>n.activeEntity?.logicalName),t=ae(n=>n.activeEntity?.metadataId);B.useEffect(()=>{const n=we.getState();if(!e||typeof window.dataverseAPI>"u"){n.reset();return}const o=n.beginLoad(e);vw({logicalName:e,metadataId:t}).then(s=>we.getState().finishLoad(o,s))},[e,t])}function Wn(){const e=we(n=>n.apps),t=we(n=>n.commands);return B.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 Zu(e){const t=we(i=>i.commands),n=we(i=>i.appFilter),o=ae(i=>i.activeEntity?.logicalName),s=ae(i=>i.activeEntity?.metadataId);return B.useMemo(()=>o?lw(t,{location:e,appFilter:n,table:{logicalName:o,metadataId:s}}):[],[t,n,e,o,s])}const ua=new Set;function ww(){ua.clear()}function pr(e){const t=Zu(e),n=ae(u=>u.activeEntity?.logicalName)??"",o=D(u=>u.ribbons[e]?.tabs),s=D(u=>u.ribbons[e]?.entityLogicalName??""),i=we(u=>u.status==="loaded"?u.tableLogicalName:null),l=(o?.length??0)>0&&(e==="Application"||s.toLowerCase()===n.toLowerCase()),r=B.useMemo(()=>mw({commands:t,tabs:l?o??[]:[],location:e,entityLogicalName:n}),[t,o,l,e,n]),d=!!n&&i===n&&l?r.unmatchedMigrated.map(u=>u.uniqueName).join(", "):"";return B.useEffect(()=>{const u=`${n}|${e}|${d}`;!d||ua.has(u)||(ua.add(u),re.getState().logInfo("ribbon",`Migrated modern commands without a classic control in ${n} ${e}: ${d}`))},[d,n,e]),r}function qs(e,t){const n=pr(e);return B.useMemo(()=>{const o=t.groups.flatMap(i=>i.buttons.map(l=>({id:l.id,sequence:l.sequence}))),s=t.id===n.commandBarTabId?n.nodes:[];return{nodes:s,placement:Vu(o,s),overrides:n.overrides}},[n,t])}function Cw(e,t){const{overrides:n}=pr(e);return t&&n.get(t)||Rw}const Rw=[];function Iw(){const e=we(s=>s.selectedCommandId),t=Z(s=>s.selectedButtonId),n=Z(s=>s.location),o=Zu(n);return B.useMemo(()=>{if(!e||t)return null;const s=o.find(l=>l.id===e);if(!s)return null;let i;for(const l of Hu(o))if(i=Qu(l,e),i)break;return{command:s,children:i?Wu(i.children):[]}},[e,t,o])}function Qu(e,t){if(e.command.id===t)return e;for(const n of e.children){const o=Qu(n,t);if(o)return o}}function jw(e,t,n){const o=ft(e.groups).flatMap(r=>ft(r.buttons).map(c=>{const d=n.get(c.id)??[],u=c.hidden||d.length>0&&d.every(h=>h.effect==="hidden"),m=d.find(h=>h.effect==="replaced")?.command;return{item:{kind:"classic",id:c.id,button:c,groupId:r.id,replacedBy:m},hidden:u}})),s=t.filter(r=>!r.command.hidden&&!r.command.disabled),i=Vu(o.map(r=>({id:r.item.id,sequence:r.item.button.sequence})),s),l=r=>({kind:"modern",id:`modern:${r.command.id}`,command:r.command});return[...o.flatMap(({item:r,hidden:c})=>[...(i.before.get(r.id)??[]).map(l),...c?[]:[r]]),...i.trailing.map(l)]}const em=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXS,marginBottom:f.spacingVerticalM},header:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:f.spacingHorizontalS,minWidth:0},muted:{color:f.colorNeutralForeground3},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},bar:{display:"flex",alignItems:"center",gap:"2px",minWidth:0,height:"40px",padding:`0 ${f.spacingHorizontalXS}`,overflow:"hidden",backgroundColor:f.colorNeutralBackground1,border:`1px solid ${f.colorNeutralStroke2}`,borderRadius:f.borderRadiusMedium,boxShadow:f.shadow2},command:{flexShrink:0,fontWeight:f.fontWeightRegular,maxWidth:"220px"},selected:{backgroundColor:f.colorSubtleBackgroundSelected,outline:`1px solid ${f.colorBrandStroke1}`},empty:{padding:`0 ${f.spacingHorizontalS}`}});function $w({tab:e,location:t}){const n=em(),o=Be(),s=D(S=>S.locLabels),i=D(S=>S.baseLanguageCode),l=Z(S=>S.selectedButtonId),r=Z(S=>S.selectButtonInContext),c=we(S=>S.selectedCommandId),d=we(S=>S.selectCommand),u=qs(t,e),m=xg({axis:"horizontal",memorizeCurrent:!0}),p=jw(e,u.nodes,u.overrides),h=vt(e.id,o(e.label,s,i,e.source?.titleToken)),b=S=>S.kind==="modern"?S.command.label||S.command.uniqueName:S.replacedBy?S.replacedBy.label||S.replacedBy.uniqueName:o(S.button.label,s,void 0,S.button.source?.labelToken)||S.button.id,g=S=>S.kind==="classic"?S.id===l||!l&&!!S.replacedBy&&S.replacedBy.id===c:!l&&S.command.id===c,x=S=>S.kind==="classic"?r(t,e.id,S.groupId,S.button.id):d(S.command.id),y=Io(e.id);return a.jsxs("section",{className:n.root,"aria-label":"How users see it",children:[a.jsxs("div",{className:n.header,children:[a.jsx(X,{weight:"semibold",size:300,children:"How users see it"}),a.jsxs(X,{size:200,className:Ce(n.muted,n.ellipsis),children:[h," · ",p.length," command",p.length===1?"":"s"]}),a.jsx(xe,{appearance:"outline",color:"informative",size:"medium",children:"Preview: rules not applied"}),a.jsx(Et,{size:"small",info:"The tab's commands in the order Unified Interface lists them, without the ones hidden by your customizations or replaced by a modern command. Display and enable rules aren't evaluated, so some of these may not show, or be disabled, for users. What doesn't fit goes into the ⋮ menu.",infoButton:{"aria-label":"About this preview"}})]}),y?a.jsx(X,{size:200,className:Ce(n.bar,n.empty,n.muted),children:"Unified Interface doesn't show this tab's commands."}):p.length===0?a.jsx(X,{size:200,className:Ce(n.bar,n.empty,n.muted),children:"No commands on this tab are shown."}):a.jsx(wa,{padding:40,children:a.jsxs("div",{className:n.bar,role:"toolbar",...m,"aria-label":`Command bar preview: ${h}`,children:[p.map(S=>a.jsx(Ht,{id:S.id,priority:g(S)?2:1,children:a.jsx(Tw,{item:S,text:b(S),selected:g(S),onChoose:()=>x(S)})},S.id)),a.jsx(Nw,{items:p,textOf:b,isSelected:g,onChoose:x})]})})]})}const Tw=B.forwardRef(function({item:t,text:n,selected:o,onChoose:s},i){const l=em(),r=t.kind==="classic"&&!!t.button.menu;return a.jsxs(Y,{ref:i,appearance:"subtle",size:"small",className:Ce(l.command,o&&l.selected),"aria-current":o||void 0,"data-users-bar":t.id,"aria-description":t.kind==="modern"?"Modern command":t.replacedBy?"Modern command, migrated from this button":t.id,icon:t.kind==="classic"?a.jsx(St,{button:t.button,size:16}):void 0,onClick:s,children:[a.jsx("span",{className:l.ellipsis,children:n}),r&&a.jsx(dt,{fontSize:12,"aria-label":"Has a menu"})]})});function Nw({items:e,textOf:t,isSelected:n,onChoose:o}){const{ref:s,isOverflowing:i,overflowCount:l}=$a();return i?a.jsxs(Je,{children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(Y,{ref:s,appearance:"subtle",size:"small",icon:a.jsx(Ac,{}),"aria-label":`${l} more commands`,children:l})}),a.jsx(Qe,{children:a.jsx(et,{children:e.map(r=>a.jsx(kw,{item:r,text:t(r),selected:n(r),onChoose:()=>o(r)},r.id))})})]}):null}function kw({item:e,text:t,selected:n,onChoose:o}){return Ta(e.id)?null:a.jsx(fe,{icon:e.kind==="classic"?a.jsx(St,{button:e.button,size:16}):void 0,secondaryContent:n?"Selected":e.kind==="modern"?"Modern":void 0,onClick:o,children:t})}function tm(e,t,n=`_copy_${Date.now()}`){return{...ss(e,`${e.id}${n}`,t),label:e.label??"New Button",kind:e.kind??"button",sequence:void 0,templateAlias:e.templateAlias??"o1",commandId:e.commandId??"",hidden:!1,oob:!1,custom:!0,managed:!1}}const nm=pe({chip:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,height:"32px",padding:`0 ${f.spacingHorizontalS}`,borderRadius:f.borderRadiusMedium,border:`1px dashed ${f.colorPaletteBerryBorderActive}`,backgroundColor:f.colorPaletteBerryBackground1,color:f.colorNeutralForeground1,cursor:"default",whiteSpace:"nowrap",flexShrink:0,userSelect:"none",":hover":{backgroundColor:f.colorPaletteBerryBackground2},":focus-visible":{outline:`2px solid ${f.colorBrandStroke1}`,outlineOffset:"2px"}},selected:{border:`1px solid ${f.colorPaletteBerryForeground2}`,backgroundColor:f.colorPaletteBerryBackground2},muted:{opacity:.5},hidden:{textDecoration:"line-through"},tooltip:{display:"flex",flexDirection:"column",gap:"2px",maxWidth:"360px"},tooltipRow:{fontSize:f.fontSizeBase200,overflowWrap:"anywhere"}});function om({node:e,appNames:t}){const n=nm(),o=e.command;return a.jsxs("div",{className:n.tooltip,children:[a.jsx(X,{weight:"semibold",children:o.label}),a.jsx(X,{className:n.tooltipRow,children:"Modern command — read-only in CBS; edit it in the command designer."}),Ku(o,t).map(s=>a.jsxs(X,{className:n.tooltipRow,children:[a.jsxs("b",{children:[s.label,":"]})," ",s.value]},s.label)),e.children.length>0&&a.jsxs(X,{className:n.tooltipRow,children:[a.jsx("b",{children:"Items:"})," ",e.children.map(s=>s.command.label).join(", ")]})]})}function Aw({node:e,appNames:t,showApp:n,onDragRejected:o}){const s=nm(),i=e.command,l=we(b=>b.selectedCommandId),r=we(b=>b.selectCommand),c=Z(b=>b.selectedButtonId),d=l===i.id&&!c,u=i.type==="dropdown"||i.type==="split"||e.children.length>0,m=i.fontIcon&&!i.fontIcon.startsWith("$")?i.fontIcon:"apps_add_in",p=`${i.hidden?" — hidden":""}${i.disabled?" — disabled":""}`,h=b=>{b.preventDefault(),b.stopPropagation(),b.dataTransfer.dropEffect="none",o?.()};return a.jsx(he,{content:a.jsx(om,{node:e,appNames:t}),relationship:"description",children:a.jsxs("button",{type:"button",draggable:!1,className:Ce(s.chip,d&&s.selected,(i.hidden||i.disabled)&&s.muted,i.hidden&&s.hidden),"aria-pressed":d,"aria-label":`${i.label} — modern command (read-only), ${So(i,t)}${p}`,onClick:()=>r(i.id),onDragStart:b=>b.preventDefault(),onDragOver:h,onDrop:h,onContextMenu:b=>{b.preventDefault(),r(i.id)},children:[a.jsx(cr,{name:m,size:16}),a.jsx(X,{size:200,children:i.label}),u&&a.jsx(dt,{fontSize:12,"aria-hidden":!0}),i.hidden&&a.jsx(Lt,{fontSize:12,"aria-hidden":!0}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",icon:a.jsx(fn,{}),children:"Modern"}),n&&a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",color:"informative",children:So(i,t)})]})})}function fr({overrides:e,appNames:t}){if(!e?.length)return null;const n=e.some(s=>s.effect==="hidden"),o=e.map(s=>mr(s,t)).join(`
|
|
132
|
+
`);return a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:n?"warning":"important",title:o,"aria-label":o,children:n?"Hidden by modern":"Modern (migrated)"})}const Po="application/x-rw-btn",Bl="application/x-rw-se",Ow=pe({root:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,padding:`${f.spacingHorizontalS} 0`,minHeight:"48px"},scrollRow:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,flex:1,minWidth:0,overflowX:"auto",overflowY:"hidden",paddingBottom:f.spacingHorizontalXS},button:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,height:"32px",padding:`0 ${f.spacingHorizontalS}`,borderRadius:f.borderRadiusMedium,border:"1px solid transparent",cursor:"pointer",backgroundColor:"transparent",color:f.colorNeutralForeground1,whiteSpace:"nowrap",flexShrink:0,position:"relative",userSelect:"none",":hover":{backgroundColor:f.colorNeutralBackground3,border:`1px solid ${f.colorNeutralStroke1}`},":focus-visible":{outline:`2px solid ${f.colorBrandStroke1}`,outlineOffset:"2px"}},buttonSelected:{backgroundColor:f.colorBrandBackground2,border:`1px solid ${f.colorBrandStroke1}`},buttonHidden:{opacity:.4,textDecoration:"line-through"},buttonCustom:{border:`1px solid ${f.colorBrandStroke2}`},lockIcon:{position:"absolute",top:"4px",left:"4px",color:f.colorNeutralForeground3,pointerEvents:"none"},dropLine:{width:"2px",height:"24px",backgroundColor:f.colorBrandStroke1,borderRadius:"2px",flexShrink:0},overflowBtn:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,height:"32px",padding:`0 ${f.spacingHorizontalS}`,borderRadius:f.borderRadiusMedium,border:`1px solid ${f.colorNeutralStroke2}`,backgroundColor:f.colorNeutralBackground2,cursor:"pointer",color:f.colorNeutralForeground3,flexShrink:0},trailingControls:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,flexShrink:0,paddingLeft:f.spacingHorizontalS,borderLeft:`1px solid ${f.colorNeutralStroke2}`,marginLeft:f.spacingHorizontalXS}});function Mw({tab:e,location:t}){const n=Ow(),o=Z(j=>j.selectedButtonId),s=Z(j=>j.selectButtonInContext),i=D(j=>j.moveButton),l=D(j=>j.locLabels),r=Be(),c=D(j=>j.baseLanguageCode),d=(j,_,W)=>r(j,l,c,W)||_,u=J(j=>j.openNewButton),m=J(j=>j.announce),[p,h]=B.useState(null),[b,g]=B.useState(null),[x,y]=B.useState(null),S=qs(t,e),C=Wn(),R=we(j=>j.appFilter==="all"),M=j=>a.jsx(Aw,{node:j,appNames:C,showApp:R,onDragRejected:()=>h(null)},j.command.id),I=j=>Xu(S.overrides.get(j.id),C),$=j=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&j.oob&&!j.custom,T=j=>ut(j.kind),v=j=>T(j)?` (${xt[j.kind]}, read-only)`:"",O=e.groups.flatMap(j=>j.buttons.map(_=>({button:_,groupId:j.id})));function A(j,_,W){j.dataTransfer.setData(Po,JSON.stringify({groupId:_,buttonId:W})),j.dataTransfer.effectAllowed="move",g(W)}function E(){g(null),h(null)}function w(j,_){const W=Array.from(j.dataTransfer.types??[]);!W.includes(Po)&&!W.includes(Bl)||(j.preventDefault(),j.dataTransfer.dropEffect=W.includes(Po)?"move":"copy",h({beforeButtonId:_}))}const k=D(j=>j.createButton);function N(j,_,W){j.preventDefault(),j.stopPropagation();const ne=j.dataTransfer.getData(Po);if(ne){try{const ce=JSON.parse(ne);if(ce?.buttonId){const F=i({groupId:ce.groupId,buttonId:ce.buttonId,tabId:e.id,location:t},{groupId:_,beforeButtonId:W??void 0,tabId:e.id,location:t});F&&F!==ce.buttonId&&s(t,e.id,_,F)}}catch{}h(null),g(null);return}const le=j.dataTransfer.getData(Bl);if(le){try{const F=JSON.parse(le)?.button,L=We(t,e.id,_);F&&L?m(L):F&&k({location:t,tabId:e.id,groupId:_,button:tm(F,po(D.getState()))})}catch{}h(null),g(null);return}h(null),g(null)}return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:n.root,children:[a.jsxs("div",{className:n.scrollRow,onDragOver:j=>{j.preventDefault()},onDrop:j=>N(j,e.groups[0]?.id??"",null),children:[O.map(({button:j,groupId:_})=>a.jsxs(nt.Fragment,{children:[S.placement.before.get(j.id)?.map(M),p?.beforeButtonId===j.id&&a.jsx("div",{className:n.dropLine,"aria-hidden":!0}),a.jsx(he,{content:$(j)?"OOB global command bar buttons cannot be customized.":`${r(j.label,l,void 0,j.source?.labelToken)}${v(j)}${j.hidden?" — hidden":""}${I(j)}`,relationship:"label",children:a.jsxs("button",{type:"button",className:[n.button,o===j.id?n.buttonSelected:"",j.hidden?n.buttonHidden:"",j.custom?n.buttonCustom:""].filter(Boolean).join(" "),"aria-current":o===j.id?"true":void 0,"aria-label":`${r(j.label,l,void 0,j.source?.labelToken)}${v(j)}${j.hidden?" — hidden":""}${I(j)}`,onClick:()=>s(t,e.id,_,j.id),onContextMenu:W=>{W.preventDefault(),s(t,e.id,_,j.id),y({button:j,groupId:_,anchor:W.currentTarget})},draggable:!j.managed&&!$(j),onDragStart:W=>A(W,_,j.id),onDragEnd:E,onDragOver:W=>w(W,j.id),onDrop:W=>N(W,_,j.id),style:{opacity:b===j.id?.3:void 0},children:[a.jsx(St,{button:j,size:16}),a.jsx(X,{size:200,children:r(j.label,l,void 0,j.source?.labelToken)}),T(j)&&a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",color:"informative",children:xt[j.kind]}),j.menu&&a.jsx(dt,{fontSize:12,"aria-label":"Has a menu"}),j.hidden&&a.jsx(Lt,{fontSize:12,"aria-hidden":!0}),j.custom&&a.jsx(xe,{style:{flexShrink:0},size:"medium",color:"brand",appearance:"tint","aria-label":"Custom",children:"NEW"}),a.jsx(fr,{overrides:S.overrides.get(j.id),appNames:C}),$(j)&&a.jsx("span",{className:n.lockIcon,title:"OOB global command bar buttons cannot be customized.",children:a.jsx(fn,{fontSize:12})})]})})]},j.id)),S.placement.trailing.map(M)]}),a.jsx("div",{className:n.trailingControls,children:(()=>{const j=e.groups[0];return j?a.jsx(he,{content:`Add a new button to "${d(j.label,j.id,j.source?.titleToken)}"`,relationship:"label",children:a.jsxs("button",{type:"button",className:n.overflowBtn,onClick:()=>u(j.id),"aria-label":"Add a new button",children:[a.jsx(ke,{fontSize:14})," Add"]})}):a.jsx(he,{content:'No groups in this tab yet. Switch to "Classic ribbon" view to add a group first.',relationship:"label",children:a.jsxs("button",{type:"button",className:n.overflowBtn,disabled:!0,children:[a.jsx(ke,{fontSize:14})," Add"]})})})()})]}),a.jsx(To,{location:t,tab:e,target:x,onClose:()=>y(null)})]})}const Ew=pe({root:{marginTop:f.spacingVerticalM,display:"flex",flexDirection:"column",gap:f.spacingVerticalXS},header:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS},row:{cursor:"pointer",backgroundColor:f.colorPaletteBerryBackground1,":hover":{backgroundColor:f.colorPaletteBerryBackground2}},rowSelected:{backgroundColor:f.colorPaletteBerryBackground2,outline:`1px solid ${f.colorPaletteBerryBorderActive}`},hidden:{opacity:.55,textDecoration:"line-through"},mono:{fontFamily:f.fontFamilyMonospace,color:f.colorNeutralForeground3},table:{tableLayout:"fixed",width:"100%"},note:{color:f.colorNeutralForeground3,minWidth:0}}),Dw={button:"command",dropdown:"dropdown",split:"split",group:"group"};function Bw({tab:e,location:t}){const n=Ew(),{nodes:o}=qs(t,e),s=Wn(),i=we(p=>p.selectedCommandId),l=we(p=>p.selectCommand),r=Z(p=>p.selectedButtonId),[c,d]=B.useState(!0);if(o.length===0)return null;const u=[],m=(p,h)=>{for(const b of p)u.push({node:b,depth:h}),m(b.children,h+1)};return m(o,0),a.jsxs("section",{className:n.root,"aria-label":"Modern commands",children:[a.jsxs("div",{className:n.header,children:[a.jsx(Y,{appearance:"subtle",size:"small",icon:c?a.jsx(dt,{}):a.jsx(vg,{}),"aria-expanded":c,onClick:()=>d(!c),children:a.jsxs(X,{weight:"semibold",size:200,children:["Modern commands (",u.length,")"]})}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",children:"read-only"}),a.jsx(X,{size:200,truncate:!0,wrap:!1,className:n.note,children:"Built with the command designer (appaction). Edit them there."})]}),c&&a.jsxs(Sg,{size:"small",className:n.table,"aria-label":"Modern commands (read-only)",children:[a.jsx(wg,{children:a.jsxs(Or,{children:[a.jsx(Vn,{style:{width:52},children:"#"}),a.jsx(Vn,{style:{width:"36%"},children:"Label"}),a.jsx(Vn,{style:{width:"20%"},children:"App"}),a.jsx(Vn,{style:{width:96},children:"Type"}),a.jsx(Vn,{children:"Unique name"})]})}),a.jsx(Cg,{children:u.map(({node:p,depth:h})=>{const b=p.command,g=i===b.id&&!r;return a.jsxs(Or,{className:Ce(n.row,g&&n.rowSelected),"aria-selected":g,tabIndex:0,onClick:()=>l(b.id),onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l(b.id))},children:[a.jsx(Xn,{children:b.sequence}),a.jsx(Xn,{children:a.jsx(he,{content:a.jsx(om,{node:p,appNames:s}),relationship:"description",children:a.jsxs("span",{className:b.hidden||b.disabled?n.hidden:void 0,style:{paddingLeft:h*16,display:"flex",gap:4,alignItems:"center",minWidth:0,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:[a.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:b.label}),b.hidden&&a.jsx(Lt,{fontSize:12,"aria-label":"hidden"}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",children:"Modern"})]})})}),a.jsx(Xn,{children:a.jsx(go,{truncate:!0,children:So(b,s)})}),a.jsx(Xn,{children:a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",children:Dw[b.type]})}),a.jsx(Xn,{children:a.jsx(go,{truncate:!0,className:n.mono,children:a.jsx("span",{title:b.uniqueName,children:b.uniqueName})})})]},b.id)})})]})]})}const Lw=pe({root:{width:"100%",minWidth:0},toolbar:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS,padding:`${f.spacingVerticalXS} 0`},search:{flex:1,minWidth:0,maxWidth:"480px"},muted:{color:f.colorNeutralForeground3},grid:{width:"100%",minWidth:0},header:{position:"sticky",top:`calc(-1 * ${f.spacingHorizontalM})`,zIndex:1,backgroundColor:f.colorNeutralBackground1},row:{cursor:"pointer"},rowSelected:{backgroundColor:f.colorSubtleBackgroundSelected,":hover":{backgroundColor:f.colorSubtleBackgroundSelected}},hidden:{color:f.colorNeutralForeground3},mono:{fontFamily:f.fontFamilyMonospace,color:f.colorNeutralForeground3},badge:{marginLeft:f.spacingHorizontalXS,flexShrink:0},labelMain:{display:"flex",alignItems:"center",minWidth:0,overflow:"hidden"},shrink:{minWidth:0},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}),Ll={id:"ID",command:"Command"},zl=e=>!!e.target.closest('button, input, [role="switch"], [role="menuitem"]');function zw({tab:e,location:t}){const n=Lw(),o=Z(w=>w.selectedButtonId),s=Z(w=>w.selectButtonInContext),i=D(w=>w.setButtonProp),l=D(w=>w.locLabels),r=D(w=>w.baseLanguageCode),c=Be(),{overrides:d}=qs(t,e),u=Wn(),[m,p]=B.useState(""),[h,b]=B.useState([]),[g,x]=B.useState(null),[y,S]=B.useState(void 0),C=Oc({tabBehavior:"unlimited",ignoreDefaultKeydown:{Enter:!0}}),R=B.useMemo(()=>{let w=0;return ft(e.groups).flatMap(k=>ft(k.buttons).map(N=>({button:N,label:c(N.label,l,void 0,N.source?.labelToken)||N.id,groupId:k.id,groupLabel:vt(k.id,c(k.label,l,r,k.source?.titleToken)),order:w++})))},[e,c,l,r]),M=m.toLowerCase().trim(),I=M?R.filter(({button:w,label:k,groupLabel:N,groupId:j})=>w.id.toLowerCase().includes(M)||k.toLowerCase().includes(M)||w.label.toLowerCase().includes(M)||(w.commandId??"").toLowerCase().includes(M)||N.toLowerCase().includes(M)||j.toLowerCase().includes(M)):R,$=w=>s(t,e.id,w.groupId,w.button.id),T=(w,k)=>x({button:w.button,groupId:w.groupId,anchor:k}),v={seq:{defaultWidth:52,minWidth:44,idealWidth:52},label:{defaultWidth:220,minWidth:140,idealWidth:220},kind:{defaultWidth:110,minWidth:80,idealWidth:110},group:{defaultWidth:150,minWidth:90,idealWidth:150},visible:{defaultWidth:72,minWidth:64,idealWidth:72},id:{defaultWidth:240,minWidth:140,idealWidth:240},command:{defaultWidth:220,minWidth:140,idealWidth:220},actions:{defaultWidth:44,minWidth:44,idealWidth:44}},O=w=>a.jsx(X,{size:200,weight:"semibold",children:w}),A=(w,k)=>a.jsx(go,{truncate:!0,className:k,title:w,children:w}),E=[He({columnId:"seq",compare:(w,k)=>w.button.sequence-k.button.sequence||w.order-k.order,renderHeaderCell:()=>O("#"),renderCell:({button:w})=>a.jsx(X,{size:200,children:w.sequence})}),He({columnId:"label",compare:(w,k)=>w.label.localeCompare(k.label)||w.order-k.order,renderHeaderCell:()=>O("Label"),renderCell:({button:w,label:k})=>a.jsx(he,{content:`${k} (${w.id})`,relationship:"description",children:a.jsxs(go,{media:a.jsx(St,{button:w,size:16}),className:Ce(n.shrink,w.hidden&&n.hidden),content:{className:n.shrink},main:{className:n.labelMain},children:[a.jsx("span",{className:n.ellipsis,children:k}),a.jsx("span",{className:n.badge,children:a.jsx(fr,{overrides:d.get(w.id),appNames:u})})]})})}),He({columnId:"kind",compare:(w,k)=>xt[w.button.kind].localeCompare(xt[k.button.kind])||w.order-k.order,renderHeaderCell:()=>O("Kind"),renderCell:({button:w})=>A(xt[w.kind]??w.kind)}),He({columnId:"group",compare:(w,k)=>w.groupLabel.localeCompare(k.groupLabel)||w.order-k.order,renderHeaderCell:()=>O("Group"),renderCell:({groupLabel:w})=>A(w)}),...h.includes("id")?[He({columnId:"id",compare:(w,k)=>w.button.id.localeCompare(k.button.id),renderHeaderCell:()=>O("ID"),renderCell:({button:w})=>A(w.id,n.mono)})]:[],...h.includes("command")?[He({columnId:"command",compare:(w,k)=>(w.button.commandId??"").localeCompare(k.button.commandId??"")||w.order-k.order,renderHeaderCell:()=>O("Command"),renderCell:({button:w})=>A(w.commandId||"—",n.mono)})]:[],He({columnId:"visible",compare:(w,k)=>Number(w.button.hidden)-Number(k.button.hidden)||w.order-k.order,renderHeaderCell:()=>O("Visible"),renderCell:({button:w,label:k,groupId:N})=>{const j=Va(t,e.id,w);return a.jsx(he,{content:j?"Microsoft's global command bar buttons can't be changed.":w.hidden?"Hidden":"Shown",relationship:"description",children:a.jsx(Oa,{checked:!w.hidden,disabled:j,"aria-label":`Toggle visibility of ${k}`,onChange:(_,W)=>i(t,e.id,N,w.id,{hidden:!W.checked})})})}}),He({columnId:"actions",renderHeaderCell:()=>a.jsx("span",{className:n.muted}),renderCell:w=>a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(xs,{}),"aria-label":`Actions for ${w.label}`,onClick:k=>T(w,k.currentTarget)})})];return a.jsxs("div",{className:n.root,children:[a.jsxs("div",{className:n.toolbar,children:[a.jsx(cn,{size:"small",className:n.search,placeholder:`Filter ${R.length} button${R.length!==1?"s":""}`,"aria-label":"Filter the buttons",value:m,onChange:(w,k)=>p(k.value)}),M&&a.jsxs(X,{size:200,className:n.muted,children:[I.length," match",I.length!==1?"es":""]}),a.jsxs(Je,{checkedValues:{columns:h},onCheckedValueChange:(w,k)=>b(k.checkedItems),children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(Rg,{}),children:"Columns"})}),a.jsx(Qe,{children:a.jsx(et,{children:Object.keys(Ll).map(w=>a.jsx(lc,{name:"columns",value:w,children:Ll[w]},w))})})]})]}),a.jsx("div",{...C,children:a.jsxs(Ig,{className:n.grid,items:I,columns:E,columnSizingOptions:v,resizableColumns:!0,sortable:!0,sortState:y,onSortChange:(w,k)=>S(k),getRowId:w=>w.button.id,focusMode:"composite",size:"small","aria-label":`Buttons of ${e.id}`,children:[a.jsx(jg,{className:n.header,children:a.jsx(Mr,{children:({renderHeaderCell:w})=>a.jsx(Mc,{children:w()})})}),a.jsx($g,{children:({item:w,rowId:k})=>{const N=o===w.button.id;return a.jsx(Mr,{"aria-selected":N,"data-list-button":w.button.id,className:Ce(n.row,N&&n.rowSelected),onClick:j=>{zl(j)||$(w)},onKeyDown:j=>{zl(j)||(j.key==="Enter"||j.key===" "?(j.preventDefault(),$(w)):(j.key==="ContextMenu"||j.shiftKey&&j.key==="F10")&&(j.preventDefault(),T(w,j.currentTarget)))},onContextMenu:j=>{j.preventDefault(),T(w,j.currentTarget)},children:({renderCell:j})=>a.jsx(Ec,{children:j(w)})},k)}})]},h.join("|"))}),I.length===0&&a.jsx(X,{size:200,className:n.muted,as:"p",children:M?"No buttons match.":"This tab has no buttons."}),a.jsx(To,{location:t,tab:e,target:g,onClose:()=>{const w=g?.anchor;setTimeout(()=>{document.activeElement?.closest('[role="dialog"], [role="alertdialog"]')||w?.isConnected&&w.focus()}),x(null)}}),a.jsx(Bw,{tab:e,location:t})]})}const sm=pe({root:{marginTop:f.spacingVerticalM,border:`1px solid ${f.colorNeutralStroke2}`,borderRadius:f.borderRadiusMedium,backgroundColor:f.colorNeutralBackground1,maxWidth:"520px"},header:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalM}`,borderBottom:`1px solid ${f.colorNeutralStroke2}`},spacer:{flex:1},body:{display:"flex",flexDirection:"column",gap:f.spacingVerticalS,padding:f.spacingHorizontalS},section:{display:"flex",flexDirection:"column",gap:"2px"},sectionHeader:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,padding:`2px ${f.spacingHorizontalXS}`,color:f.colorNeutralForeground3},item:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS,width:"100%",minHeight:"28px",padding:`0 ${f.spacingHorizontalS}`,border:"1px solid transparent",borderRadius:f.borderRadiusMedium,backgroundColor:"transparent",color:f.colorNeutralForeground1,cursor:"pointer",textAlign:"left",":hover":{backgroundColor:f.colorNeutralBackground3},":focus-visible":{outline:`2px solid ${f.colorBrandStroke1}`}},itemSelected:{backgroundColor:f.colorBrandBackground2,border:`1px solid ${f.colorBrandStroke1}`},itemHidden:{opacity:.45,textDecoration:"line-through"},itemRow:{display:"flex",alignItems:"center",gap:"2px"},nested:{marginLeft:f.spacingHorizontalL,paddingLeft:f.spacingHorizontalS,borderLeft:`1px dashed ${f.colorNeutralStroke2}`},empty:{padding:`2px ${f.spacingHorizontalS}`,color:f.colorNeutralForeground3}});function Pw({tab:e,location:t}){const n=sm(),o=Z(I=>I.selectedButtonId),s=Z(I=>I.selectedGroupId),i=Z(I=>I.selectButtonInContext),l=D(I=>I.baseline),r=D(I=>I.locLabels),c=Be(),d=D(I=>I.addMenuSection),u=D(I=>I.setMenuSectionProp),m=D(I=>I.deleteMenuSection),{overrides:p}=pr(t),h=Wn(),b=e.groups.find(I=>I.id===s),g=ty(b,o),x=B.useMemo(()=>{const I=new Set;for(const $ of l[t]?.tabs??[])for(const T of $.groups)for(const v of je(T))I.add(v.id);return I},[l,t]);if(!b||!g||!g.menu&&!Tn(g.kind))return null;const y=b.id,S=I=>c(I.label,r,void 0,I.source?.labelToken),C=I=>fd(I.source?.attributes.PopulateDynamically)?I.source?.attributes.PopulateQueryCommand??"a command":null,R=I=>{const $=[...I.menu?.sections??[]].sort((O,A)=>O.sequence-A.sequence),T=!x.has(I.id),v=C(I);return a.jsxs(a.Fragment,{children:[v&&a.jsxs(Ge,{className:n.empty,children:["Populated when the menu opens, by ",v,". Static items below are kept as they are."]}),$.map(O=>a.jsx(Fw,{section:O,parent:I,editable:T,onTitle:A=>u(t,e.id,y,I.id,O.id,{title:A}),onDisplayMode:A=>u(t,e.id,y,I.id,O.id,{displayMode:A}),onDelete:()=>m(t,e.id,y,I.id,O.id),renderItem:M},O.id)),$.length===0&&!v&&a.jsx(Ge,{className:n.empty,children:"No menu sections yet."}),T&&a.jsx("div",{children:a.jsx(Y,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),onClick:()=>d(t,e.id,y,I.id,""),children:"Add section"})})]})},M=I=>{const $=I.id===o,T=p.get(I.id);return a.jsxs("div",{children:[a.jsxs("div",{className:n.itemRow,children:[a.jsxs("button",{type:"button",className:[n.item,$?n.itemSelected:"",I.hidden?n.itemHidden:""].filter(Boolean).join(" "),"aria-pressed":$,"aria-label":`Menu item ${S(I)}${I.hidden?" — hidden":""}${Xu(T,h)}`,onClick:()=>i(t,e.id,y,I.id),children:[a.jsx(St,{button:I,size:16}),a.jsx(X,{size:200,children:S(I)}),I.menu&&a.jsx(dt,{fontSize:12,"aria-hidden":!0}),a.jsx(fr,{overrides:T,appNames:h}),I.custom&&!x.has(I.id)&&a.jsx(xe,{style:{flexShrink:0},size:"medium",color:"brand",appearance:"tint",children:"NEW"})]}),$&&a.jsx(qw,{item:I,location:t,tabId:e.id,groupId:y,onDeleted:()=>i(t,e.id,y,g.id)})]}),I.menu&&a.jsx("div",{className:n.nested,children:R(I)})]},I.id)};return a.jsxs("section",{className:n.root,"aria-label":`Menu of ${S(g)}`,children:[a.jsxs("div",{className:n.header,children:[a.jsx(dt,{"aria-hidden":!0}),a.jsx(X,{weight:"semibold",size:300,children:S(g)}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",children:g.kind==="splitButton"?"Split button menu":"Flyout menu"}),a.jsx("span",{className:n.spacer}),a.jsxs(Ge,{children:[pn(g).length," item(s)"]})]}),a.jsx("div",{className:n.body,children:R(g)})]})}function Fw({section:e,parent:t,editable:n,onTitle:o,onDisplayMode:s,onDelete:i,renderItem:l}){const r=sm(),c=D(m=>m.locLabels),d=Be(),u=[...e.controls].sort((m,p)=>m.sequence-p.sequence);return a.jsxs("div",{className:r.section,children:[a.jsx("div",{className:r.sectionHeader,children:n?a.jsxs(a.Fragment,{children:[a.jsx(Wt,{size:"small",placeholder:"Section title (optional)",value:e.title??"","aria-label":"Menu section title",onChange:(m,p)=>o(p.value)}),a.jsxs(ka,{size:"small","aria-label":"Menu section display mode",value:e.displayMode??"Menu16",onChange:(m,p)=>s(p.value),children:[a.jsx("option",{value:"Menu16",children:"16 px icons"}),a.jsx("option",{value:"Menu32",children:"32 px icons"}),a.jsx("option",{value:"Menu",children:"Text only"})]}),a.jsx(he,{content:"Delete section and its items",relationship:"label",children:a.jsx(Y,{size:"small",appearance:"subtle",icon:a.jsx(_n,{}),onClick:i})})]}):a.jsx(Ge,{children:d(e.title,c,void 0,e.attributes?.Title)||e.id})}),u.map(m=>l(m)),e.rawContent!==void 0&&a.jsx(Ge,{className:r.empty,children:"Gallery / dynamic content (kept as is)"}),(e.rawControls?.length??0)>0&&a.jsxs(Ge,{className:r.empty,children:[e.rawControls.length," other control(s) CBS doesn't edit (kept as they are)"]}),e.rawContent===void 0&&a.jsx(_w,{parent:t,section:e})]})}function _w({parent:e,section:t}){const n=Z(h=>h.location),o=Z(h=>h.tabId),s=Z(h=>h.selectedGroupId),i=Z(h=>h.selectButtonInContext),l=D(h=>h.addMenuItem),r=D(h=>h.upsertCommand),c=ae(h=>h.activeSolution),d=ae(h=>h.publisherPrefix),u=ae(h=>h.activeEntity),m=o&&s?We(n,o,s):void 0,p=()=>{if(!s)return;const{ribbons:h,commands:b}=D.getState(),g=new Set(b.map(C=>C.id));for(const C of Object.values(h))for(const R of C.tabs)for(const M of R.groups)for(const I of je(M))g.add(I.id);const x=c?.publisherPrefix?.trim()||d?.trim()||"new",{id:y,commandId:S}=Md(x,u?.logicalName??"global",n,"MenuItem",g);l({location:n,tabId:o,groupId:s,parentId:e.id,sectionId:t.id,item:{id:y,label:"Menu item",commandId:S}}),r({id:S,enableRules:[],displayRules:[],actions:[]}),i(n,o,s,y)};return a.jsx("div",{children:a.jsx(Y,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),disabledFocusable:!!m,title:m,onClick:p,children:"Add item"})})}function qw({item:e,location:t,tabId:n,groupId:o,onDeleted:s}){const i=D(c=>c.setButtonProp),l=D(c=>c.deleteButton),r=D(c=>c.baseline[t]);return a.jsxs(a.Fragment,{children:[a.jsx(he,{content:e.hidden?"Show item":"Hide item",relationship:"label",children:a.jsx(Y,{size:"small",appearance:"subtle",icon:e.hidden?a.jsx(Fn,{}):a.jsx(Lt,{}),onClick:()=>i(t,n,o,e.id,{hidden:!e.hidden})})}),Os(e,r)&&a.jsx(he,{content:"Delete item",relationship:"label",children:a.jsx(Y,{size:"small",appearance:"subtle",icon:a.jsx(_n,{}),onClick:()=>{l(t,n,o,e.id),s()}})})]})}const Hw=pe({surface:{maxWidth:"380px",display:"flex",flexDirection:"column",gap:f.spacingVerticalS},ribbonId:{fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,color:f.colorNeutralForeground3,overflowWrap:"anywhere"}}),Ww=({location:e,table:t,compact:n})=>{const o=Hw(),s=Jt[e],i=n?a.jsx(he,{content:"About this location",relationship:"label",children:a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(Mi,{})})}):a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(Mi,{}),children:"About this location"});return a.jsxs(xa,{withArrow:!0,positioning:"below-start",children:[a.jsx(va,{disableButtonEnhancement:!0,children:i}),a.jsxs(Sa,{className:o.surface,"aria-label":`About ${s.title}`,children:[a.jsx(X,{weight:"semibold",children:s.title}),a.jsx(X,{children:s.body}),a.jsx("span",{className:o.ribbonId,children:Zb(e,t)})]})]})},Gw=pe({popover:{overflowY:"auto"},trigger:{maxWidth:"200px",minWidth:0},label:{color:f.colorNeutralForeground3,flexShrink:0},value:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function Uw(){const e=Gw(),t=we(c=>c.status),n=we(c=>c.apps),o=we(c=>c.appFilter),s=we(c=>c.setAppFilter),i=we(c=>c.commands.length),l=we(c=>c.error);if(t==="idle")return null;if(t==="loading")return a.jsx(Tg,{size:"extra-tiny","aria-label":"Loading modern commands"});if(t==="unavailable")return a.jsx(Et,{size:"small",info:`Modern commands couldn't be read: ${l??"unknown error"}`,children:"Modern commands unavailable"});const r=o==="all"?"All apps":n.find(c=>c.id===o)?.name??"All apps";return a.jsxs(Je,{positioning:{autoSize:"height"},checkedValues:{app:[o]},onCheckedValueChange:(c,d)=>s(d.checkedItems[0]??"all"),children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(he,{content:`${i} modern command${i===1?"":"s"} for this entity (read-only). Pick an app to see its command bar.`,relationship:"description",children:a.jsxs(Y,{appearance:"subtle",size:"small",className:e.trigger,"aria-label":`App for modern commands: ${r}`,icon:a.jsx(dt,{}),iconPosition:"after",children:[a.jsx("span",{className:e.label,children:"App: "}),a.jsx("span",{className:e.value,children:r})]})})}),a.jsx(Qe,{className:e.popover,children:a.jsxs(et,{children:[a.jsx(jn,{name:"app",value:"all",children:"All apps"}),n.map(c=>a.jsx(jn,{name:"app",value:c.id,children:c.name},c.id))]})})]})}const Vw=pe({row:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,padding:`0 ${f.spacingHorizontalS}`,minHeight:"40px",borderBottom:`1px solid ${f.colorNeutralStroke2}`,flexShrink:0,minWidth:0},locationRow:{backgroundColor:f.colorNeutralBackground2},locationTabs:{flex:"1 1 0",minWidth:0,overflow:"hidden",display:"flex",alignItems:"center"},spacer:{flex:"1 1 0",minWidth:0},viewValue:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:f.colorNeutralForeground3,flexShrink:0},tableName:{flex:"0 1 auto",maxWidth:"200px",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",paddingRight:f.spacingHorizontalS,borderRight:`1px solid ${f.colorNeutralStroke2}`,fontWeight:f.fontWeightSemibold},pinned:{flexShrink:0}}),im=["HomepageGrid","Form","SubGrid","Application"],am={HomepageGrid:a.jsx(Aa,{}),Form:a.jsx(Ss,{}),SubGrid:a.jsx(Ng,{}),Application:a.jsx(vc,{})},Fo={groups:"Group cards",classic:"Classic ribbon",modern:"Modern command bar",list:"List"};function Xw(){const e=Vw(),t=Z(p=>p.location),n=Z(p=>p.setLocation),o=Z(p=>p.setTabId),s=Z(p=>p.tabId),i=D(p=>p.ribbons),l=!/^(Mscrm|Microsoft)\./.test(s)&&i[t].tabs.some(p=>p.id===s),r=ae(p=>p.activeEntity?.logicalName),c=ae(p=>p.activeEntity?.displayName),d=J(p=>p.ribbonViewStyle),u=J(p=>p.setRibbonViewStyle),m=p=>{n(p);const h=xo(i[p].tabs);h&&o(h)};return a.jsxs("div",{className:`${e.row} ${e.locationRow}`,children:[r&&a.jsx(he,{content:`Entity: ${c||r} (${r})`,relationship:"description",children:a.jsx("span",{className:e.tableName,tabIndex:0,children:c||r})}),a.jsx(wa,{minimumVisible:1,padding:48,children:a.jsxs("div",{className:e.locationTabs,children:[a.jsxs(Ma,{size:"small","aria-label":"Where the command bar appears",selectedValue:t,onTabSelect:(p,h)=>m(h.value),children:[im.map(p=>a.jsx(Ht,{id:p,priority:p===t?2:1,children:a.jsx(Gt,{value:p,icon:am[p],children:Jt[p].label})},p)),a.jsx(Kw,{onSelect:m})]}),a.jsx(Ww,{location:t,table:r,compact:!0}),l&&a.jsx(Et,{size:"small",info:fu,infoButton:{"aria-label":"How Unified Interface shows this tab"}})]})}),a.jsx(Uw,{}),a.jsxs(Je,{checkedValues:{view:[d]},onCheckedValueChange:(p,h)=>u(h.checkedItems[0]),children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsxs(Y,{appearance:"subtle",size:"small",icon:a.jsx(dt,{}),iconPosition:"after","aria-label":`View as: ${Fo[d]}`,className:e.pinned,children:[a.jsx("span",{className:e.muted,children:"View: "}),a.jsx("span",{className:e.viewValue,children:Fo[d]})]})}),a.jsx(Qe,{children:a.jsx(et,{children:Object.keys(Fo).map(p=>a.jsx(jn,{name:"view",value:p,children:Fo[p]},p))})})]})]})}function Kw({onSelect:e}){const{ref:t,isOverflowing:n,overflowCount:o}=$a();return n?a.jsxs(Je,{children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(Y,{ref:t,appearance:"transparent",size:"small",icon:a.jsx(dt,{}),iconPosition:"after","aria-label":`${o} more locations`,children:"More"})}),a.jsx(Qe,{children:a.jsx(et,{children:im.map(s=>a.jsx(Yw,{location:s,onSelect:e},s))})})]}):null}function Yw({location:e,onSelect:t}){return Ta(e)?null:a.jsx(fe,{icon:am[e],onClick:()=>t(e),children:Jt[e].label})}const hr=pe({empty:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:f.spacingVerticalM,padding:f.spacingHorizontalXXL,textAlign:"center",color:f.colorNeutralForeground3},icon:{fontSize:"40px",color:f.colorNeutralForeground4},body:{maxWidth:"420px"},loading:{display:"flex",flexDirection:"column",gap:f.spacingVerticalM,padding:f.spacingHorizontalM},skeletonRow:{display:"flex",gap:f.spacingHorizontalS},skeletonCards:{display:"flex",gap:f.spacingHorizontalM,flexWrap:"wrap"},card:{flex:"1 1 200px",height:"140px"},status:{color:f.colorNeutralForeground2},error:{display:"flex",flexDirection:"column",gap:f.spacingVerticalS,padding:f.spacingHorizontalM,maxWidth:"720px"},details:{margin:0,fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:f.colorNeutralForeground2}});function Jw({kind:e}){const t=hr(),n=J(s=>s.setSolutionPickerOpen),o=J(s=>s.setTablePickerOpen);return e==="noSolution"?a.jsxs("div",{className:t.empty,children:[a.jsx(kg,{className:t.icon,"aria-hidden":"true"}),a.jsx(X,{size:500,weight:"semibold",children:"Choose a solution to start"}),a.jsx(X,{className:t.body,children:"Your changes are saved to the solution you pick. Only unmanaged solutions are listed."}),a.jsx(Y,{appearance:"primary",onClick:()=>n(!0),children:"Choose solution"})]}):a.jsxs("div",{className:t.empty,children:[a.jsx(Aa,{className:t.icon,"aria-hidden":"true"}),a.jsx(X,{size:500,weight:"semibold",children:"Pick an entity"}),a.jsx(X,{className:t.body,children:"Choose an entity from this solution to see and change its command bars."}),a.jsx(Y,{appearance:"primary",onClick:()=>o(!0),children:"Choose entity"})]})}function Zw({table:e,step:t}){const n=hr();return a.jsxs("div",{className:n.loading,children:[a.jsx(Ag,{thickness:"medium","aria-label":"Loading"}),a.jsxs(X,{role:"status","aria-live":"polite",className:n.status,children:[e?`Loading ${e}`:"Loading the ribbon",t?` · ${t}`:""]}),a.jsxs(Og,{"aria-hidden":"true",className:n.loading,children:[a.jsx("div",{className:n.skeletonRow,children:[70,80,90,60,75].map(o=>a.jsx(Er,{style:{width:o,height:32}},o))}),a.jsx("div",{className:n.skeletonCards,children:[0,1,2].map(o=>a.jsx(Er,{className:n.card},o))})]})]})}function Qw(e){return/\b401\b|unauthori[sz]ed/i.test(e)?"Your connection may have expired.":/\b403\b|forbidden|privilege/i.test(e)?"Your account may not have permission to read this entity's ribbon.":/\b(429|503|504)\b|timeout|timed out/i.test(e)?"Dataverse was busy or didn't answer in time. Try again in a moment.":/\b5\d\d\b/.test(e)?"Dataverse returned an error.":/failed to fetch|network/i.test(e)?"The connection to Dataverse failed.":"Something went wrong while reading it."}function eC({table:e,error:t,onRetry:n}){const o=hr(),[s,i]=B.useState("");return a.jsxs("div",{className:o.error,children:[a.jsxs(Dt,{intent:"error",layout:"multiline",children:[a.jsxs(Bt,{children:[a.jsxs(cc,{children:["Couldn't load ",e?`${e}'s`:"the"," ribbon"]}),Qw(t)]}),n&&a.jsx(vs,{children:a.jsx(Y,{size:"small",appearance:"primary",onClick:n,children:"Retry"})})]}),a.jsx(Dc,{collapsible:!0,children:a.jsxs(Bc,{value:"details",children:[a.jsx(Lc,{size:"small",children:"Details"}),a.jsxs(zc,{children:[a.jsx("pre",{className:o.details,children:t}),a.jsx(Y,{size:"small",onClick:async()=>i((await Ps(t)).ok?"yes":"no"),children:s==="yes"?"Copied":s==="no"?"Couldn't copy":"Copy details"})]})]})})]})}const tC=pe({root:{display:"flex",flexDirection:"column",flex:1,minWidth:0,overflow:"hidden",backgroundColor:f.colorNeutralBackground1},messages:{padding:`${f.spacingVerticalS} ${f.spacingHorizontalM} 0`},canvas:{flex:1,overflow:"auto",padding:f.spacingHorizontalM}}),nC=pe({root:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"80px",gap:f.spacingHorizontalM,color:f.colorNeutralForeground3}});function oC({isLoadingRibbon:e=!1,loadingTable:t,loadingStep:n=null,ribbonLoadError:o=null,layerReadError:s=null,onRetryRibbonLoad:i,emptyState:l}){const r=tC(),c=Z(T=>T.location),d=Z(T=>T.tabId),u=Z(T=>T.setTabId),m=D(T=>T.ribbons),p=D(T=>T.orphans.entity.filter(v=>!T.pendingOrphanDeletes.entity.includes(v.id)&&!v.recentPublish?.published).map(v=>v.id).sort().join("|")),h=p?p.split("|").length:0,b=ae(T=>T.connectionUrl),g=Z(T=>T.clearSelection),x=J(T=>T.ribbonViewStyle),y=J(T=>T.openNewGroup),S=J(T=>T.setPropertiesRequested),[C,R]=B.useState(!1),M=m[c],I=M.tabs.find(T=>T.id===d)??M.tabs.find(T=>T.id===xo(M.tabs));B.useEffect(()=>{if(!M.tabs.length)return;if(!M.tabs.some(v=>v.id===d)){const v=xo(M.tabs);v&&u(v)}},[M.tabs,d,u]);const $=[];return s&&!e&&!o&&$.push({id:"layer-read",intent:"warning",title:"Couldn't read your unmanaged ribbon customizations",body:`Labels may show as ids, and what you can edit or delete is unknown. Reload before editing. Details: ${s}`,dismissible:!1,actions:i&&a.jsx(Y,{size:"small",onClick:()=>Xo()?R(!0):i(),children:"Retry"})}),I&&Io(I.id)&&$.push({id:`hidden-tab:${I.id}`,intent:"warning",title:"Unified Interface doesn't show this tab's buttons",body:"They don't come back when the entity is reloaded either. Add buttons to the entity's main tab instead."}),c!=="Application"&&h>0&&$.push({id:"orphans",intent:"warning",signature:p,title:`${h} of your customizations ${h!==1?"aren't":"isn't"} on the canvas`,body:a.jsxs(a.Fragment,{children:["The ribbon doesn't return ",h!==1?"them":"it",". See"," ",a.jsx("strong",{children:"Orphaned customizations"})," in the Properties pane to delete"," ",h!==1?"them":"it","."]}),actions:a.jsx(Y,{size:"small",onClick:()=>{g(),S(!0)},children:"Show"})}),l?a.jsx("main",{className:r.root,"aria-label":"Ribbon canvas",children:a.jsx(Jw,{kind:l})}):a.jsxs("main",{className:r.root,"aria-label":"Ribbon canvas",children:[a.jsx(Xw,{}),a.jsx(ir,{messages:$,scope:`canvas:${b}:${M.entityLogicalName}:${c}`,className:r.messages}),a.jsx("div",{className:r.canvas,children:e?a.jsx(Zw,{table:t,step:n}):o?a.jsx(eC,{table:t,error:o,onRetry:i}):I?a.jsxs(a.Fragment,{children:[x==="groups"?a.jsxs(a.Fragment,{children:[a.jsx($w,{tab:I,location:c}),a.jsx(VS,{tab:I,location:c})]}):x==="classic"?a.jsx(HS,{tab:I,location:c}):x==="modern"?a.jsx(Mw,{tab:I,location:c}):a.jsx(zw,{tab:I,location:c}),a.jsx(Pw,{tab:I,location:c})]}):a.jsx(sC,{onAddGroup:y})}),C&&i&&a.jsx(Hn,{open:!0,title:"Reload the ribbon",confirmLabel:"Reload",onConfirm:()=>{R(!1),i()},onCancel:()=>R(!1),children:"You have unpublished changes. Reloading replaces the canvas; your changes are kept in a draft that is offered after the reload. They were made while your labels weren't loaded, so check their texts before you publish: a text can read a label's id."})]})}function sC({onAddGroup:e}){const t=nC();return a.jsxs("div",{className:t.root,children:[a.jsx(Ss,{fontSize:32,style:{opacity:.4}}),a.jsx(X,{size:300,children:"This tab has no groups yet"}),a.jsx(Y,{appearance:"primary",size:"small",icon:a.jsx(ke,{}),onClick:e,children:"Add first group"})]})}let oo=null;const ma={set(e){oo=e},invoke(e){const t=oo;oo=null,t?.(e)},clear(){oo=null},hasPending(){return oo!==null}},iC=pe({field:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXXS,minWidth:0},row:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,minWidth:0},input:{flex:1,minWidth:0,backgroundColor:f.colorNeutralBackground3},srOnly:{position:"absolute",width:"1px",height:"1px",overflow:"hidden",clipPath:"inset(50%)",whiteSpace:"nowrap"},value:{fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,textOverflow:"ellipsis"}}),rm=({label:e,value:t,action:n,hideLabel:o})=>{const s=iC(),i=B.useId(),[l,r]=B.useState("idle"),c=B.useRef(void 0);B.useEffect(()=>()=>clearTimeout(c.current),[]);const d=async()=>{const p=await Ps(t);r(p.ok?"copied":"failed"),clearTimeout(c.current),c.current=setTimeout(()=>r("idle"),2e3)},u=l==="copied"?`${e} copied`:l==="failed"?`Couldn't copy the ${e.toLowerCase()}`:`Copy ${e.toLowerCase()}`,m=a.jsxs("div",{className:s.row,children:[a.jsx(he,{content:t,relationship:"description",withArrow:!0,children:a.jsx(Wt,{id:i,className:s.input,input:{className:s.value},value:t,readOnly:!0,appearance:"filled-darker","aria-label":o?e:void 0})}),a.jsx(he,{content:u,relationship:"label",children:a.jsx(Y,{appearance:"subtle",icon:l==="copied"?a.jsx(Ic,{}):a.jsx(Ro,{}),onClick:()=>{d()}})}),n,a.jsx("span",{"aria-live":"polite",className:s.srOnly,children:l==="idle"?"":u})]});return o?m:a.jsxs("div",{className:s.field,children:[a.jsx(Mg,{htmlFor:i,size:"small",weight:"semibold",children:e}),m]})},aC=["button","flyout","splitButton","textBox","comboBox","checkBox"],rC=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalM,minWidth:0},row:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS},localeChips:{display:"flex",flexWrap:"wrap",gap:f.spacingHorizontalXS,alignItems:"center"},iconPreview:{width:"32px",height:"32px",borderRadius:"6px",backgroundColor:f.colorNeutralBackground4,color:f.colorNeutralForeground1,display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${f.colorNeutralStroke2}`,flexShrink:0},keyHint:{overflowWrap:"anywhere"},lockedNote:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,color:f.colorNeutralForeground2},webResLink:{fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,cursor:"pointer",color:f.colorBrandForeground1,textDecoration:"underline",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1,border:"none",background:"transparent",textAlign:"left"}});function yi({button:e,location:t,tabId:n,groupId:o,part:s}){const i=rC(),l=D(I=>I.setButtonProp),r=D(I=>I.locLabels),c=D(I=>I.baseLanguageCode),d=J(I=>I.openIconPicker),u=J(I=>I.openLocalizationEditor),m=J(I=>I.openWebResourceBrowser),p=D(I=>!I.ribbons[t].tabs.find($=>$.id===n)?.groups.find($=>$.id===o)?.buttons.some($=>$.id===e.id)),h=D(I=>Ud(I,t,e.id)),b=D(I=>I.ribbons[t].tabs.find($=>$.id===n)?.groups.find($=>$.id===o)),g=Be(),x=[...new Set([...p?_a:aC,e.kind])];function y(I){l(t,n,o,e.id,I)}const S=e.origin!=="unmanaged",C={label:g(e.label,r,void 0,e.source?.labelToken),tooltipTitle:g(e.tooltipTitle,r,void 0,e.source?.tooltipTitleToken),tooltipBody:g(e.tooltipBody,r,void 0,e.source?.tooltipBodyToken)},R=(I,$)=>I&&I!==$?{children:`From ${I}`,className:i.keyHint}:void 0,M=Jb(e,r,c);return s==="position"?a.jsxs("div",{className:i.root,children:[a.jsx(qe,{label:"Group",hint:"Use Move to in the button's menu to move it.",children:a.jsx(Wt,{readOnly:!0,appearance:"filled-darker",value:b?vt(b.id,g(b.label,r,c,b.source?.titleToken)):o})}),a.jsx(qe,{label:"Order",hint:"Lower numbers show first within the group. Unified Interface merges the groups into one bar.",children:a.jsx(Eg,{value:e.sequence,disabled:S,step:10,min:0,onChange:(I,$)=>y({sequence:Number($.value??e.sequence)})})})]}):s==="advanced"?a.jsxs("div",{className:i.root,children:[a.jsx(qe,{label:"Kind",hint:h?"A loaded control's kind can't be changed: add a new control instead.":p?"A menu holds buttons and flyouts.":void 0,children:a.jsx(ka,{value:e.kind,disabled:h,onChange:(I,$)=>y({kind:$.value}),children:x.map(I=>a.jsx("option",{value:I,children:xt[I]},I))})}),a.jsx(qe,{label:"Template alias",hint:"Which slot of the group's layout the button uses on the classic ribbon, for example o1.",children:a.jsx(Wt,{value:e.templateAlias,readOnly:S,onChange:(I,$)=>y({templateAlias:$.value})})})]}):a.jsxs("div",{className:i.root,children:[S&&a.jsxs(X,{size:200,className:i.lockedNote,children:[a.jsx(fn,{"aria-hidden":!0})," Customise this button, or create an override, to edit these fields."]}),a.jsx(qe,{label:"Label",hint:S?R(e.label,C.label):void 0,children:a.jsx(Wt,{value:S?C.label:e.label,readOnly:S,appearance:S?"filled-darker":void 0,onChange:(I,$)=>y({label:$.value})})}),a.jsx(qe,{label:"Translations",children:a.jsxs("div",{className:i.localeChips,children:[a.jsx(Pc,{"aria-label":"Languages of this button's text",size:"small",children:(M.length?M:[1033]).map(I=>a.jsx(Ea,{value:String(I),appearance:"brand",children:a.jsxs(Da,{disabled:S,onClick:()=>u(e.id),children:[I===1033?"en-US":String(I),M.length===0?" (default)":""]})},I))}),a.jsx(Y,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),disabled:S,onClick:()=>u(e.id),children:"Add language…"})]})}),a.jsx(qe,{label:"Tooltip title",hint:S?R(e.tooltipTitle,C.tooltipTitle):void 0,children:a.jsx(Wt,{value:S?C.tooltipTitle:e.tooltipTitle??"",readOnly:S,appearance:S?"filled-darker":void 0,onChange:(I,$)=>y({tooltipTitle:$.value})})}),a.jsx(qe,{label:"Tooltip body",hint:S?R(e.tooltipBody,C.tooltipBody):void 0,children:a.jsx(Dg,{value:S?C.tooltipBody:e.tooltipBody??"",readOnly:S,appearance:S?"filled-darker":void 0,onChange:(I,$)=>y({tooltipBody:$.value}),resize:"vertical"})}),a.jsx(Wo,{}),a.jsx(qe,{label:"Icon",children:a.jsxs("div",{className:i.row,children:[a.jsx("div",{className:i.iconPreview,children:e.icon?a.jsx(cr,{name:e.icon,size:20}):a.jsx(ki,{style:{color:f.colorNeutralForeground3}})}),a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(ki,{}),disabled:S,onClick:d,children:"Change…"})]})}),e.icon&&a.jsx(qe,{label:"Modern image",hint:"What Unified Interface shows. Set from the icon you pick.",children:a.jsx(Wt,{value:Ga(e)??"(none)",readOnly:!0})}),e.image16&&a.jsx(qe,{label:"Image16",children:a.jsx("div",{className:i.row,children:a.jsx(he,{content:e.image16,relationship:"description",children:a.jsx(Mn,{as:"button",className:i.webResLink,disabled:S,onClick:()=>{ma.set(I=>{y({image16:`$webresource:${I.name}`,icon:I.name.split("/").pop()?.replace(/\..*$/,"")})}),m()},children:e.image16})})})}),e.image32&&a.jsx(qe,{label:"Image32",children:a.jsx("div",{className:i.row,children:a.jsx(he,{content:e.image32,relationship:"description",children:a.jsx(Mn,{as:"button",className:i.webResLink,disabled:S,onClick:()=>{ma.set(I=>{y({image32:`$webresource:${I.name}`})}),m()},children:e.image32})})})}),a.jsx(Oa,{label:"Visible",checked:!e.hidden,onChange:(I,$)=>y({hidden:!$.checked})}),a.jsx(rm,{label:"Button ID",value:e.id})]})}const lC=pe({row:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:f.spacingHorizontalS}}),cC={oob:"informative",customising:"warning",customised:"brand",uncustomising:"danger",custom:"success",reloadRequired:"danger"};function _o(e){return e.scope==="application"?"the application ribbon's layer (every entity)":e.sharedWithApplication?"this entity's layer only (the application ribbon keeps the original)":"this entity's layer"}function dC({commandId:e,compact:t=!1,hideBadge:n=!1}){const o=lC(),s=_s(e),i=D(y=>y.customiseCommand),l=D(y=>y.uncustomiseCommand),r=D(y=>y.discardCommandChanges),c=D(y=>{const S=y.commands.find(R=>R.id===e),C=y.baselineCommands.find(R=>R.id===e);return!!S&&!!C&&JSON.stringify(S)!==JSON.stringify(C)}),[d,u]=B.useState(null);if(!s)return null;const m=(y,S,C)=>{c?u({what:y,confirmLabel:S,run:C}):C()},p=d&&a.jsxs(Hn,{open:!0,title:"Discard unpublished changes?",confirmLabel:d.confirmLabel,destructive:!0,onConfirm:()=>{d.run(),u(null)},onCancel:()=>u(null),children:[d.what," discards your unpublished changes to ",a.jsx("code",{children:e}),"."]}),{provenance:h}=s,b=h==="oob"?a.jsx(Y,{size:"small",appearance:"outline",onClick:()=>i(e),children:"Customise command"}):h==="customising"?a.jsx(Y,{size:"small",appearance:"subtle",onClick:()=>m("Discarding the customisation","Discard customisation",()=>r(e)),children:"Discard customisation"}):h==="customised"?a.jsx(Y,{size:"small",appearance:"subtle",onClick:()=>m("Uncustomising","Uncustomise",()=>l(e,s.scope)),children:"Uncustomise"}):h==="uncustomising"?a.jsx(Y,{size:"small",appearance:"subtle",onClick:()=>r(e),children:"Undo uncustomise"}):null,g=a.jsx(xe,{appearance:h==="oob"?"outline":"filled",color:cC[h],size:"medium",children:aS[h]});if(t)return a.jsxs("div",{className:o.row,children:[g,b,p]});const x={oob:`Out of the box or from another solution, so it's read-only. Customise it to copy it — actions, parameters and rules — into ${_o(s)} and change it there; its buttons keep using it.`,customising:`On publish, this command is copied into ${_o(s)} and replaces the original there. Rules keep their ids; a rule you edit is written to the layer as well.`,customised:`${_o(s).replace(/^./,y=>y.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 ${_o(s)} is removed (with rules only it used) and the original applies again. Reload the entity 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 entity to load the original before changing or customising it again."};return h==="custom"?n?null:a.jsx("div",{className:o.row,children:g}):a.jsxs(a.Fragment,{children:[a.jsxs(Dt,{layout:"multiline",intent:h==="uncustomising"||h==="reloadRequired"?"warning":"info",children:[a.jsx(Bt,{children:a.jsxs("div",{className:o.row,children:[!n&&g,a.jsx(X,{size:200,children:x[h]})]})}),b&&a.jsx(vs,{children:b})]}),p]})}const uC=pe({field:{minWidth:0},combobox:{minWidth:0,width:"100%"},listbox:{maxHeight:"280px",maxWidth:"min(480px, 90vw)",overflowWrap:"anywhere"}});function lm({label:e,options:t,selected:n,onSelect:o,placeholder:s="Type to filter",noOptionsMessage:i="Nothing matches.",hint:l}){const r=uC(),[c,d]=B.useState(n),[u,m]=B.useState(n);u!==n&&(m(n),d(n));const p=ac(c,t.map(b=>({value:b,children:b})),{noOptionsMessage:i,optionToReactKey:b=>b.value,optionToText:b=>b.value}),h=(b,g)=>{d(g.optionText??""),o(g.optionValue??"")};return a.jsx(qe,{label:e,hint:l,className:r.field,children:a.jsx(ya,{size:"small",freeform:!0,clearable:!0,className:r.combobox,listbox:{className:r.listbox},placeholder:s,value:c,selectedOptions:n?[n]:[],onChange:b=>{d(b.target.value),n&&o("")},onOptionSelect:h,children:p})})}const mC=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalM,minWidth:0},commandRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:f.spacingHorizontalS,padding:`${f.spacingHorizontalXS} ${f.spacingHorizontalS}`,borderRadius:f.borderRadiusMedium,border:`1px solid ${f.colorNeutralStroke2}`,backgroundColor:f.colorNeutralBackground3},commandId:{fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,color:f.colorNeutralForeground1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function pC({button:e,groupId:t,tabId:n,location:o}){const s=mC(),i=D(g=>g.commands),l=D(g=>g.upsertCommand),r=D(g=>g.setButtonProp),c=D(g=>g.batch),d=J(g=>g.openCommandEditor),[u,m]=nt.useState(""),p=i.find(g=>g.id===e.commandId),h=()=>{const g=new Set(i.map(y=>y.id)),x=Ya("New","Command",g);c(()=>{l({id:x,enableRules:[],displayRules:[],actions:[]}),r(o,n,t,e.id,{commandId:x})}),d(x)},b=()=>{u&&(r(o,n,t,e.id,{commandId:u}),m(""))};return a.jsx("div",{className:s.root,children:p?a.jsxs(a.Fragment,{children:[a.jsx(rm,{label:"Command ID",value:p.id,action:a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(Pn,{}),onClick:()=>d(p.id),children:"Edit command"})}),a.jsx(dC,{commandId:p.id,compact:!0}),p.actions.length>0&&a.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:p.actions.map((g,x)=>a.jsx(Vs,{size:"extra-small",appearance:"outline",children:g.kind==="javascript"?`JS: ${g.functionName}`:g.kind==="url"?`URL: ${g.address}`:g.kind==="powerFx"?`Fx: ${g.expression}`:g.kind==="customApi"?`API: ${g.actionName}`:g.kind==="outlookCommand"?`Outlook: ${g.actionType}`:`XML: ${g.tagName}`},x))}),p.enableRules.length>0&&a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[a.jsx(X,{size:200,style:{color:f.colorNeutralForeground3},children:"Enable rules:"}),p.enableRules.map(g=>a.jsx(Vs,{size:"extra-small",appearance:"outline",color:"success",children:g},g))]}),p.displayRules.length>0&&a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[a.jsx(X,{size:200,style:{color:f.colorNeutralForeground3},children:"Display rules:"}),p.displayRules.map(g=>a.jsx(Vs,{size:"extra-small",appearance:"outline",color:"informative",children:g},g))]})]}):e.commandId?a.jsx("div",{className:s.commandRow,children:a.jsxs(X,{className:s.commandId,style:{color:f.colorStatusWarningForeground3},children:[e.commandId," (not found)"]})}):a.jsxs(a.Fragment,{children:[a.jsx(lm,{label:"Use an existing command",options:i.map(g=>g.id),selected:u,onSelect:m,noOptionsMessage:"No command matches."}),a.jsxs("div",{style:{display:"flex",gap:f.spacingHorizontalXS},children:[a.jsx(Y,{appearance:"outline",size:"small",disabled:!u,onClick:b,children:"Bind"}),a.jsx(Y,{appearance:"outline",size:"small",icon:a.jsx(ke,{}),onClick:h,children:"Create and bind"})]})]})})}const tI={CommandClientTypeRule:"Client (Unified Interface / legacy)",CrmClientTypeRule:"Client (web / Outlook)",CrmOfflineAccessStateRule:"Offline access",CrmOutlookClientTypeRule:"Outlook client",CrmOutlookClientVersionRule:"Outlook client version",CustomRule:"Your JavaScript",DeviceTypeRule:"Device",EntityPrivilegeRule:"Entity privilege",EntityPropertyRule:"Entity property",EntityRule:"Entity",FeatureControlRule:"Feature control bit",FormEntityContextRule:"Form's entity",FormStateRule:"Form state",FormTypeRule:"Form type",HideForTabletExperienceRule:"Hide on tablets",MiscellaneousPrivilegeRule:"Other privilege",OptionSetRule:"Choice value",OrganizationSettingRule:"Organization setting",OrRule:"Any of (Or)",OutlookItemTrackingRule:"Outlook item tracking",OutlookRenderTypeRule:"Outlook or web",OutlookVersionRule:"Outlook version",PageRule:"Page address",RawRule:"Other rule (kept as XML)",RecordPrivilegeRule:"Record privilege",ReferencingAttributeRequiredRule:"Referencing column required",RelationshipTypeRule:"Relationship type",SelectionCountRule:"Selected records",SkuRule:"Deployment (online / on-premises)",ValueRule:"Column value"},nI=[{label:"Client and device",kinds:["CommandClientTypeRule","CrmClientTypeRule","DeviceTypeRule","CrmOutlookClientVersionRule"]},{label:"Form",kinds:["FormStateRule","FormTypeRule","FormEntityContextRule"]},{label:"Entity",kinds:["EntityRule","EntityPrivilegeRule","EntityPropertyRule","OptionSetRule"]},{label:"Selection and record",kinds:["SelectionCountRule","ValueRule","RecordPrivilegeRule"]},{label:"Other",kinds:["MiscellaneousPrivilegeRule","OrganizationSettingRule","FeatureControlRule","PageRule","SkuRule","HideForTabletExperienceRule","RelationshipTypeRule","ReferencingAttributeRequiredRule"]},{label:"Outlook",kinds:["CrmOfflineAccessStateRule","CrmOutlookClientTypeRule","OutlookItemTrackingRule","OutlookRenderTypeRule","OutlookVersionRule"]},{label:"Combine steps",kinds:["OrRule"]},{label:"Your code",kinds:["CustomRule"]}],fC=new Set(["CustomRule","OutlookItemTrackingRule","RecordPrivilegeRule","SelectionCountRule"]),cm=new Set(["CrmOutlookClientVersionRule","DeviceTypeRule","EntityPrivilegeRule","EntityPropertyRule","FeatureControlRule","FormEntityContextRule","FormTypeRule","HideForTabletExperienceRule","MiscellaneousPrivilegeRule","OptionSetRule","OrganizationSettingRule","OutlookRenderTypeRule","ReferencingAttributeRequiredRule","RelationshipTypeRule"]),oI=new Set([...Array.from(cm),"HideIfNetBreezeNotAvailableRule","HideIfServiceMetadataAvailableRule","HideIfSharepointS2SConfigurationEnabledRule","HideIfExportToExcelNotEnabledRule","IsExportToExcelOnlineEnabledRule","HideIfDisabledForMobileRule","HideIfHybridSSSNotEnabledRule","HideIfEmailSignatureNotEnabledRule","HideIfReverseHybridSSSNotEnabledRule","HideIfDelveNotAvailableRule","HideIfTestExchangeServerNotEnabledRule","HideIfSSSTroubleshootingNotEnabledRule","HideIfCurrentUserIsNotSystemAdministratorRule","HideIfPowerBITileNotAvailableRule","HideIfProcessActiveRule","HideIfProcessInactiveRule","HideIfProcessUnificationIsDisabledRule","HideIfO365UserDoesNotHaveExchangeSubscriptionsRule","HideIfEmailIsApprovedByAdminRule","HideIfUserIsNotTenantAdminRule","HideIfEmailIsApprovedByAdminBasedOnESPRule","HideIfProductRecommendationsNotEnabledRule"]),dm=[{id:"Mscrm.ShowOnGridAndQuickAction",label:"Show on the grid and as a quick action"},{id:"Mscrm.ShowOnGrid",label:"Show only on the grid"},{id:"Mscrm.ShowOnQuickAction",label:"Show only as a quick action"}],hC=dm.map(e=>e.id);function gC(e,t){return e.some(n=>n.kind==="OrRule"?n.groups.some(o=>gC(o,t)):n.kind==="RawRule"?n.tagName===t||new RegExp(`<${t}\\b`).test(n.xml):n.kind===t)}function sI(e,t,n=!1){return e==="RawRule"||n&&e==="OrRule"?!1:t==="enable"?!cm.has(e):!fC.has(e)}const bC=new Set(["enablerule","displayrule","rule","enable","display","tabdisplayrule","mscrm"]);function yC(e){const t=e.split(".").filter(Boolean);for(let n=t.length-1;n>=0;n--)if(!bC.has(t[n].toLowerCase()))return t[n];return e}function um(e,t,n){if(n)return e;const o=t==="enable"?dm.find(s=>s.id===e):void 0;return o?`${e}: Microsoft's rule, "${o.label}". It's in the application ribbon, so there's nothing to open here.`:`${e} isn't in the loaded ribbon, so there's nothing to open here.`}const xC=({ruleId:e,kind:t,onOpen:n,onRemove:o})=>{const s=yC(e),i=t==="enable"?"enable rule":"display rule",l=um(e,t,!!n);return a.jsxs(Ea,{value:e,size:"small",appearance:"outline",children:[a.jsx(he,{content:l,relationship:"description",children:a.jsx(Da,{hasSecondaryAction:!!o,onClick:n,children:s})}),o&&a.jsx(Bg,{"aria-label":`Unbind ${i} ${s}`,onClick:o})]})},vC=pe({section:{display:"flex",flexDirection:"column",gap:f.spacingHorizontalXS},header:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS},pillList:{display:"flex",flexWrap:"wrap",gap:f.spacingHorizontalXS,maxWidth:"100%",minWidth:0},addBtn:{alignSelf:"flex-start"},note:{fontSize:f.fontSizeBase200,color:f.colorNeutralForeground3,fontStyle:"italic"}}),mm=({kind:e})=>{const t=vC(),n=Z(N=>N.location),o=Z(N=>N.tabId),s=Z(N=>N.selectedGroupId),i=Z(N=>N.selectedButtonId),l=D(N=>N.commands),r=D(N=>N.displayRules),c=D(N=>N.enableRules),d=D(N=>N.upsertCommand),u=D(N=>N.upsertDisplayRule),m=D(N=>N.upsertEnableRule),p=D(N=>N.batch),h=J(N=>N.openRuleEditor),y=D(N=>N.ribbons)[n].tabs.find(N=>N.id===o)?.groups.find(N=>N.id===s),S=Ns(y,i),C=l.find(N=>N.id===S?.commandId),R=_s(C?.id),M=rS(R),I=R?.provenance==="uncustomising"?"Undo the uncustomise to change its rules.":R?.provenance==="reloadRequired"?"Reload the entity to change its rules.":"Customise the command to change its rules.",$=e==="display"?C?.displayRules??[]:C?.enableRules??[],T=e==="display"?r:c,[v,O]=nt.useState(""),A=T.filter(N=>!$.includes(N.id)),E=N=>{if(!C)return;const j=$.filter(_=>_!==N);d(e==="display"?{...C,displayRules:j}:{...C,enableRules:j})},w=()=>{if(!C)return;if(e==="display"){const _=new Set(r.map(ne=>ne.id)),W=yo(Jr(C.id),"Display",_);p(()=>{u({id:W,steps:[]}),d({...C,displayRules:[...C.displayRules,W]})}),h(W,"display");return}const N=new Set(c.map(_=>_.id)),j=yo(Jr(C.id),"Enable",N);p(()=>{m({id:j,steps:[]}),d({...C,enableRules:[...C.enableRules,j]})}),h(j,"enable")},k=()=>{!C||!v||(d(e==="display"?{...C,displayRules:[...C.displayRules,v]}:{...C,enableRules:[...C.enableRules,v]}),O(""))};return a.jsxs("div",{className:t.section,children:[!C&&a.jsx(X,{className:t.note,children:"Bind a command first to manage rules."}),$.length>0&&a.jsx(Pc,{className:t.pillList,"aria-label":e==="display"?"Bound display rules":"Bound enable rules",children:$.map(N=>a.jsx(xC,{ruleId:N,kind:e,onOpen:T.some(j=>j.id===N)?()=>h(N,e):void 0,onRemove:M?void 0:()=>E(N)},N))}),C&&M&&a.jsx(X,{className:t.note,children:I}),C&&!M&&a.jsxs(a.Fragment,{children:[a.jsx(lm,{label:`Bind an existing ${e} rule`,options:[...A.map(N=>N.id),...e==="enable"&&n==="HomepageGrid"?hC.filter(N=>!$.includes(N)&&!A.some(j=>j.id===N)):[]],selected:v,onSelect:O,noOptionsMessage:"No rule matches."}),a.jsxs("div",{style:{display:"flex",gap:f.spacingHorizontalXS},children:[a.jsx(Y,{className:t.addBtn,appearance:"subtle",size:"small",onClick:k,disabled:!v,children:"Bind"}),a.jsxs(Y,{className:t.addBtn,appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:w,children:["Create new ",e," rule"]})]})]}),e==="enable"&&a.jsx(Et,{size:"small",info:"Disabled buttons are hidden in the modern command bar (Unified Interface). In the classic ribbon, they stay visible but do nothing when clicked.",children:"What a failing enable rule does"})]})},SC=()=>a.jsx(mm,{kind:"display"}),wC=()=>a.jsx(mm,{kind:"enable"}),CC=pe({section:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXS},note:{color:f.colorNeutralForeground2}}),RC=()=>{const e=CC(),t=Z(m=>m.location),n=Z(m=>m.tabId),o=D(m=>m.ribbons[t]),s=D(m=>m.locLabels),i=D(m=>m.baseLanguageCode),l=Be(),r=o.tabs.find(m=>m.id===n),c=o.scalingByTab?.[n],d=(c?.maxSizes.length??0)+(c?.scales.length??0),u=r?.groups.length??0;return a.jsxs("div",{className:e.section,children:[r?a.jsxs(X,{size:200,className:e.note,children:["“",vt(r.id,l(r.label,s,i,r.source?.titleToken)),"” has ",u," group",u===1?"":"s"," and ",d," scaling step",d===1?"":"s","."]}):a.jsx(X,{size:200,className:e.note,children:"Select a tab to see its scaling."}),a.jsx(X,{size:200,className:e.note,children:"Scaling decides how groups shrink as the classic ribbon narrows; Unified Interface ignores it. Command Bar Studio can't change it yet."})]})},IC=pe({section:{display:"flex",flexDirection:"column",gap:f.spacingHorizontalXS},row:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS},note:{fontSize:f.fontSizeBase200,color:f.colorNeutralForeground3}}),jC=()=>{const e=IC(),t=Z(C=>C.location),n=Z(C=>C.selectedButtonId),o=D(C=>C.ribbons),s=J(C=>C.openCommandEditor),i=D(C=>C.setOpenRecordOverride),l=Z(C=>C.clearSelection),r=ae(C=>C.activeSolution),c=ae(C=>C.publisherPrefix),d=o[t],u=Bd.includes(t),m=zd(d),p=m.length>0,h=m.map(C=>Pd(C)),b=h.includes("theirs"),g=!b&&h.includes("unknown"),x=!p&&!Fd(d),y=Qa(d).filter(C=>!Ld(C.button)),S=C=>{const R=r?.publisherPrefix?.trim()||c?.trim()||"new";!C&&m.some(M=>M.button.id===n)&&l(),!(!i(t,C,R)||!C)&&s(Ye)};return a.jsxs("div",{className:e.section,children:[u&&a.jsxs("div",{children:[a.jsx(Oa,{label:a.jsx(Et,{info:a.jsxs(a.Fragment,{children:["When on, double-clicking a row of this entity's"," ",t==="SubGrid"?"sub-grids (on any form)":"home grid",", selecting its primary column link or pressing Enter runs your command instead of opening the record. Unified Interface only. As Microsoft's recipe requires, an “Open record” button using the command is added here: don't hide it. The Command Editor opens so you can set the script; Publish waits until you do. Turning it off removes that button."]}),children:`Override opening a record from the ${t==="SubGrid"?"sub-grid":"home grid"}`}),checked:p,disabled:b||g||x,onChange:(C,R)=>S(R.checked)}),b&&a.jsx(X,{size:200,className:e.note,children:`The "Open record" button here comes from another solution, so the override can't be turned off from your customizations.`}),g&&a.jsx(X,{size:200,className:e.note,children:`CBS doesn't know yet which solution the "Open record" button here comes from (its solution layers haven't loaded), so it isn't removed — reload the entity if this doesn't clear.`}),y.length>0&&a.jsxs(X,{size:200,className:e.note,children:["Also using Mscrm.OpenRecordItem here:"," ",y.map(C=>C.button.id).join(", "),". Turning the override off keeps ",y.length===1?"it":"them"," ","and the command."]}),x&&a.jsx(X,{size:200,className:e.note,children:"This location has no group to put the button in."})]}),t==="Form"&&a.jsxs(X,{size:200,className:e.note,children:["Changes apply to every main form of this entity."," ",a.jsx(Et,{size:"small",info:"Unified Interface doesn't support a ribbon for one form only, so Command Bar Studio changes the entity's form ribbon, which all its main forms use.",infoButton:{"aria-label":"Why every form"}})]})]})},$C=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS,minWidth:0},id:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200},pending:{textDecoration:"line-through",color:f.colorNeutralForeground3}});function TC(){const e=$C(),t=D(i=>i.layers),n=D(i=>i.pendingUnhides),o=D(i=>i.setLayerHideUnhidden),s=["entity","application"].flatMap(i=>(t[i]?.hides??[]).map(l=>({scope:i,...l})));return s.length===0?null:a.jsxs("section",{className:e.root,"aria-label":"Hidden by customizations",children:[a.jsx(X,{as:"h3",size:300,weight:"semibold",children:"Hidden by customizations"}),a.jsx(Ge,{children:"Hidden by a HideCustomAction in your unmanaged customizations, so they aren't on the canvas. Un-hiding takes effect when you publish; reload afterwards to see them."}),s.map(i=>{const l=n[i.scope].includes(i.location);return a.jsxs("div",{className:e.row,children:[a.jsx(Lt,{}),a.jsx(he,{content:`${i.location} (${i.scope==="entity"?"this entity":"application ribbon"})`,relationship:"description",children:a.jsx(X,{className:`${e.id} ${l?e.pending:""}`,children:i.location})}),a.jsx(Y,{size:"small",appearance:l?"subtle":"secondary",onClick:()=>o(i.scope,i.location,!l),children:l?"Keep hidden":"Unhide"})]},`${i.scope}:${i.location}`)})]})}const NC=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"flex-start",gap:f.spacingHorizontalS,minWidth:0},icon:{flexShrink:0,marginTop:"2px",color:f.colorPaletteMarigoldForeground1},text:{display:"flex",flexDirection:"column",flex:1,minWidth:0},mono:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200},why:{color:f.colorNeutralForeground3},pending:{textDecoration:"line-through",color:f.colorNeutralForeground3}});function kC(){const e=NC(),t=D(r=>r.orphans),n=D(r=>r.pendingOrphanDeletes),o=D(r=>r.setOrphanDeleted),[s,i]=B.useState(null),l=["entity","application"].flatMap(r=>t[r].map(c=>({scope:r,...c})));return l.length===0?null:a.jsxs("section",{className:e.root,"aria-label":"Orphaned customizations",children:[a.jsx(X,{as:"h3",size:300,weight:"semibold",children:"Orphaned customizations"}),a.jsx(Ge,{children:"In your unmanaged customizations, but the ribbon doesn't return them, so they aren't on the canvas (and, except for tabs, Unified Interface doesn't show them either). Publishing keeps them unless you delete them. For a while after a publish the ribbon can still be the one from before it (10 minutes or more), so what you just published can show up here: don't delete it, reload later."}),l.map(r=>{const c=n[r.scope].includes(r.id),d=r.label&&r.label!==r.id?`“${r.label}” `:"",u=`${r.scope}:${r.id}`,m=!!r.recentPublish?.published,p=c?a.jsx(Y,{size:"small",appearance:"subtle","aria-label":`Keep ${r.id}`,onClick:()=>o(r.scope,r.id,!1),children:"Keep"}):m?a.jsx(he,{content:"Published from here moments ago: reload later — it most likely isn't loaded yet",relationship:"description",children:a.jsx(Y,{size:"small",disabledFocusable:!0,"aria-label":`Delete ${r.id}`,children:"Delete"})}):r.recentPublish?a.jsx(Y,{size:"small",appearance:"secondary","aria-label":`Delete ${r.id}`,onClick:()=>i({scope:r.scope,id:r.id,minutesAgo:r.recentPublish?.minutesAgo}),children:"Delete…"}):a.jsx(Y,{size:"small",appearance:"secondary","aria-label":`Delete ${r.id}`,onClick:()=>o(r.scope,r.id,!0),children:"Delete"});return a.jsxs("div",{className:e.row,children:[a.jsx(Lg,{className:e.icon}),a.jsxs("div",{className:e.text,children:[a.jsx(he,{content:`${r.element} ${r.id} — CustomAction ${r.customActionId} at ${r.location}`,relationship:"description",children:a.jsxs(X,{className:Ce(e.mono,c&&e.pending),children:[d,r.id]})}),a.jsx(Ge,{className:Ce(e.mono,e.why),children:r.location}),a.jsx(Ge,{className:e.why,children:r.why})]}),p]},u)}),s&&a.jsxs(Hn,{open:!0,title:"Delete a recent customization?",confirmLabel:"Delete anyway",destructive:!0,onConfirm:()=>{o(s.scope,s.id,!0),i(null)},onCancel:()=>i(null),children:[s.id," was published",s.minutesAgo!==void 0?` about ${s.minutesAgo} minute${s.minutesAgo===1?"":"s"} ago`:" recently",". The ribbon may not show it yet, so it may not be orphaned at all. Reload the entity later to check before deleting it."]})]})}const AC=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS},field:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},mono:{fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,overflowWrap:"anywhere"},xml:{margin:0,maxHeight:"240px",overflow:"auto",padding:f.spacingHorizontalS,borderRadius:f.borderRadiusMedium,backgroundColor:f.colorNeutralBackground3,fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,whiteSpace:"pre-wrap",overflowWrap:"anywhere"}});function OC({button:e,location:t,tabId:n,groupId:o}){const s=AC(),i=D(g=>g.locLabels),l=Be(),r=D(g=>g.setButtonProp),c=D(g=>g.hideOobButton),d=D(g=>g.hideWithDisplayRules),[u,m]=B.useState(!1),p=t==="Application"&&n==="Mscrm.GlobalTab"&&e.oob&&!e.custom,h=xt[e.kind],b=(g,x)=>x?a.jsxs("div",{className:s.field,children:[a.jsx(Ge,{children:g}),a.jsx(X,{className:s.mono,children:x})]}):null;return a.jsxs("section",{className:s.root,"aria-label":`${h} (read-only)`,children:[a.jsxs("div",{className:s.title,children:[a.jsx(fn,{"aria-hidden":!0}),a.jsx(X,{as:"h3",size:300,weight:"semibold",children:"Shown read-only"})]}),a.jsxs(Ge,{children:["Command Bar Studio shows this <",$n[e.kind],"> but doesn't edit it. You can hide it, and move or delete it when your customizations add it; its XML is published as it was loaded."]}),b("Label",l(e.label,i,void 0,e.source?.labelToken)),b("Id",e.id),b("Command",e.commandId||void 0),a.jsx("div",{children:a.jsx(Y,{size:"small",disabled:p,icon:e.hidden?a.jsx(Fn,{}):a.jsx(Lt,{}),onClick:()=>!e.hidden&&e.oob?m(!0):r(t,n,o,e.id,{hidden:!e.hidden}),children:e.hidden?"Unhide":"Hide"})}),u&&a.jsx($u,{open:!0,buttonLabel:l(e.label,i,void 0,e.source?.labelToken),buttonId:e.id,commandId:e.commandId,onConfirmHide:()=>{c(t,n,o,e.id),m(!1)},onConfirmDisplayRule:()=>{d(e.commandId),m(!1)},onCancel:()=>m(!1)}),e.source?.xml&&a.jsxs("div",{className:s.field,children:[a.jsx(Ge,{children:"XML"}),a.jsx("pre",{className:s.xml,children:e.source.xml})]})]})}const pm=pe({root:{display:"flex",flexDirection:"column",gap:f.spacingVerticalS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:f.spacingHorizontalS,flexWrap:"wrap"},grid:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:f.spacingHorizontalM,rowGap:f.spacingVerticalXS,alignItems:"baseline"},key:{color:f.colorNeutralForeground3,fontSize:f.fontSizeBase200},value:{fontSize:f.fontSizeBase200,overflowWrap:"anywhere",minWidth:0},mono:{fontFamily:f.fontFamilyMonospace},list:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXXS}});function Nt({label:e,value:t,mono:n}){const o=pm();return t?a.jsxs(a.Fragment,{children:[a.jsx(X,{className:o.key,children:e}),a.jsx(X,{className:`${o.value} ${n?o.mono:""}`,children:t})]}):null}function MC({command:e,items:t}){const n=pm(),o=Wn(),s=we(r=>r.selectCommand),i=we(r=>e.parentId?r.commands.find(c=>c.id===e.parentId):void 0),l=e.visibility==="formula"||e.action==="formula";return a.jsxs("section",{className:n.root,"aria-label":"Modern command properties",children:[a.jsxs("div",{className:n.title,children:[a.jsx(zg,{children:e.label}),a.jsx(xe,{appearance:"tint",color:"important",children:"Modern"}),e.managed&&a.jsx(xe,{appearance:"outline",color:"informative",children:"Managed"})]}),a.jsx(Dt,{intent:"info",children:a.jsx(Bt,{children:"Modern commands are read-only in Command Bar Studio and are never published from here. Edit them in the command designer."})}),a.jsxs("div",{className:n.grid,children:[Ku(e,o).map(r=>a.jsx(Nt,{label:r.label,value:r.value},r.label)),a.jsx(Nt,{label:"Tooltip title",value:e.tooltipTitle}),a.jsx(Nt,{label:"Tooltip text",value:e.tooltipDescription}),a.jsx(Nt,{label:"Accessibility text",value:e.accessibilityText}),a.jsx(Nt,{label:"Icon",value:e.fontIcon??e.iconWebResourceName??e.iconWebResourceId}),a.jsx(Nt,{label:"Group title",value:e.groupTitle}),a.jsx(Nt,{label:"Name",value:e.name}),a.jsx(Nt,{label:"Unique name",value:e.uniqueName,mono:!0}),a.jsx(Nt,{label:"Id",value:e.id,mono:!0})]}),l&&a.jsx(Ge,{children:"Power Fx formulas are stored in the app's command component library, not on the command, so only the function reference is shown here."}),i&&a.jsxs(a.Fragment,{children:[a.jsx(Wo,{}),a.jsx(X,{className:n.key,children:"Inside"}),a.jsx(Mn,{onClick:()=>s(i.id),children:i.label})]}),t.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Wo,{}),a.jsxs(X,{className:n.key,children:["Items (",t.length,")"]}),a.jsx("div",{className:n.list,children:t.map(r=>a.jsxs(Mn,{onClick:()=>s(r.id),children:[r.label,r.hidden?" (hidden)":""]},r.id))})]}),e.classicRules.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Wo,{}),a.jsxs(X,{className:n.key,children:["Classic rules (",e.classicRules.length,")"]}),a.jsx("div",{className:n.list,children:e.classicRules.map(r=>a.jsxs(X,{className:`${n.value} ${n.mono}`,children:[r.kind==="enable"?"Enable":"Display",":"," ",r.uniqueName??r.name]},r.id))})]})]})}const EC=pe({slot:{padding:`${f.spacingVerticalS} ${f.spacingHorizontalM} 0`},list:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXXS}});function DC({button:e,location:t,tabId:n,groupId:o,overrides:s}){const i=EC(),l=D(y=>y.customizeOobButton),r=D(y=>y.customiseButton),c=D(y=>y.conflicts),d=ae(y=>y.activeSolution),u=ae(y=>y.publisherPrefix),m=Z(y=>y.selectButtonInContext),p=Wn(),h=we(y=>y.selectCommand),b=er(t,n,e),g=[],x=ut(e.kind);if(e.origin==="managed"||e.origin==="oob"&&!x){const y=c.find($=>$.elementId===e.id),S=e.solutionName??y?.solutions[0]?.solutionName,C=e.publisherName??y?.solutions[0]?.publisher,R=e.origin==="oob"?"Out-of-the-box button":`From the managed solution${S?` ${S}`:""}${C?` by ${C}`:""}`,M=x?void 0:"You can't edit it directly: customise a copy, or create an override, to change it.",I=a.jsxs(a.Fragment,{children:[!x&&b&&a.jsx(Y,{size:"small",onClick:()=>{const $=d?.publisherPrefix?.trim()||u?.trim()||"new",T=r(t,n,o,e.id,$);T&&m(t,n,o,T)},children:"Customise button"}),!x&&a.jsx(Y,{size:"small",onClick:()=>l(t,n,o,e.id),children:"Create override"})]});g.push({id:"provenance",intent:"info",title:R,body:M,dismissible:!1,actions:I})}if(s.length>0){const y=s.some(S=>S.effect==="hidden");g.push({id:"modern-override",intent:y?"warning":"info",title:y?"Hidden by a modern command":"Shown as a modern command",dismissible:!1,body:a.jsxs("div",{className:i.list,children:[s.map(S=>a.jsxs("span",{children:[mr(S,p),"."," ",a.jsx(Mn,{inline:!0,onClick:()=>h(S.command.id),children:"View"})]},S.command.id)),a.jsx(Ge,{children:"Matched by the migrated command's unique name. Unified Interface may show the modern command instead of this button."})]})})}return g.length===0?null:a.jsx(ir,{scope:"properties",messages:g,className:i.slot})}const BC=pe({header:{position:"sticky",top:0,zIndex:1,display:"flex",alignItems:"center",gap:f.spacingHorizontalS,minHeight:"52px",padding:`${f.spacingVerticalS} ${f.spacingHorizontalS} ${f.spacingVerticalS} ${f.spacingHorizontalM}`,backgroundColor:f.colorNeutralBackground2,borderBottom:`1px solid ${f.colorNeutralStroke2}`,flexShrink:0},tile:{width:"36px",height:"36px",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:f.borderRadiusMedium,backgroundColor:f.colorNeutralBackground1,border:`1px solid ${f.colorNeutralStroke2}`},text:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:f.spacingVerticalXXS},label:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},badges:{display:"flex",flexWrap:"wrap",gap:f.spacingHorizontalXS},badge:{flexShrink:0,maxWidth:"100%"},badgeText:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function LC(e){return e.origin==="unmanaged"?{text:"Yours",color:"brand"}:e.origin==="managed"?{text:e.solutionName?`Managed · ${e.solutionName}`:"Managed",color:"informative"}:{text:"Out of the box",color:"informative"}}function zC({button:e}){const t=BC(),{onClose:n}=B.useContext(Cu),o=Z(u=>u.clearSelection),s=D(u=>u.locLabels),i=Be(),l=n?{label:"Close properties",run:n}:e?{label:"Clear selection",run:o}:void 0,r=l&&a.jsx(he,{content:l.label,relationship:"label",children:a.jsx(Y,{appearance:"subtle",icon:a.jsx(mn,{}),onClick:l.run})});if(!e)return a.jsxs("div",{className:t.header,children:[a.jsx(X,{size:400,weight:"semibold",className:t.text,children:"Properties"}),r]});const c=i(e.label,s,void 0,e.source?.labelToken)||e.id,d=LC(e);return a.jsxs("div",{className:t.header,children:[a.jsx("div",{className:t.tile,"aria-hidden":!0,children:a.jsx(St,{button:e,size:20})}),a.jsxs("div",{className:t.text,children:[a.jsx(he,{content:c,relationship:"description",children:a.jsx(X,{as:"h2",size:400,weight:"semibold",className:t.label,tabIndex:0,children:c})}),a.jsxs("div",{className:t.badges,children:[a.jsx(xe,{size:"medium",appearance:"tint",color:d.color,className:t.badge,children:a.jsx("span",{className:t.badgeText,children:d.text})}),a.jsx(xe,{size:"medium",appearance:"outline",color:"informative",className:t.badge,children:xt[e.kind]})]})]}),r]})}const PC="Mscrm.HideOnModern",FC="Mscrm.ShowOnlyOnModern";function fm(e,t){if(e===PC)return"classic";if(e===FC)return"uci";const n=t?.steps.length===1?t.steps[0]:void 0;if(!(n?.kind!=="CommandClientTypeRule"||n.default!==void 0))return n.type==="Modern"?n.invertResult?"classic":"uci":n.type==="Refresh"&&!n.invertResult?"classic":"other"}function _C(e,t){const n=e.displayRules.map(o=>fm(o,t.find(s=>s.id===o))).filter(o=>o!==void 0);return n.length===0?"all":n.length===1&&n[0]!=="other"?n[0]:"custom"}const qC=pe({group:{display:"flex",flexDirection:"column",gap:f.spacingVerticalXXS}});function HC({button:e}){const t=qC(),n=Be(),o=D(S=>S.commands),s=D(S=>S.displayRules),i=D(S=>S.ribbons),l=Z(S=>S.location),r=D(S=>S.locLabels),c=D(S=>S.upsertCommand),d=D(S=>S.upsertDisplayRule),u=D(S=>S.batch),m=_s(e.commandId||void 0),p=o.find(S=>S.id===e.commandId);if(!p)return a.jsx(qe,{label:"Show on",hint:"Bind a command first: where a button shows is set on its command.",children:a.jsx(Ni,{disabled:!0,value:"all",children:a.jsx(ln,{value:"all",label:"All clients"})})});const h=_C(p,s),b=m?.provenance==="custom"||m?.provenance==="customising"||m?.provenance==="customised",g=gd(i,p.id,e.id,S=>n(S.label,r,void 0,S.source?.labelToken),l),x=S=>{const C=p.displayRules.filter(T=>fm(T,s.find(v=>v.id===T))===void 0);if(S==="all"){c({...p,displayRules:C});return}const R=S==="uci"?"Modern":"Refresh",M=s.find(T=>T.steps.length===1&&T.steps[0].kind==="CommandClientTypeRule"&&T.steps[0].type===R&&!T.steps[0].invertResult&&T.steps[0].default===void 0);let I=M?.id??`${p.id}.${R}.DisplayRule`;for(let T=1;!M&&s.some(v=>v.id===I);T++)I=`${p.id}.${R}.DisplayRule.${T}`;const $={kind:"CommandClientTypeRule",type:R};u(()=>{M||d({id:I,steps:[$]}),c({...p,displayRules:[...C,I]})})},y=b?g.length>0?`Also changes ${g.length===1?"1 other button":`${g.length} other buttons`} that use${g.length===1?"s":""} this command: ${g.slice(0,3).join(", ")}${g.length>3?", …":""}.`:"Set by display rules on the button's command.":"Customise the command to change where it shows.";return a.jsx(qe,{label:"Show on",hint:y,children:a.jsxs(Ni,{className:t.group,value:h,disabled:!b,onChange:(S,C)=>C.value!=="custom"&&x(C.value),children:[a.jsx(ln,{value:"all",label:"All clients"}),a.jsx(ln,{value:"uci",label:"Unified Interface only"}),a.jsx(ln,{value:"classic",label:"Classic web client only (not shown in Unified Interface)"}),h==="custom"&&a.jsx(ln,{value:"custom",label:"Custom: see Display rules",disabled:!0})]})})}const WC=pe({item:{borderBottom:`1px solid ${f.colorNeutralStroke3}`},headerRow:{display:"flex",alignItems:"center",paddingRight:f.spacingHorizontalS},header:{flex:1,minWidth:0,fontWeight:f.fontWeightSemibold},count:{marginLeft:f.spacingHorizontalXS},panel:{display:"flex",flexDirection:"column",gap:f.spacingVerticalM,margin:0,padding:`0 ${f.spacingHorizontalL} ${f.spacingVerticalM}`,minWidth:0}}),GC=({storageKey:e,defaultOpen:t,children:n})=>{const[o,s]=B.useState(()=>Su(`sections.${e}`,t)),i=(l,r)=>{const c=r.openItems.map(String);s(c),wu(`sections.${e}`,c)};return a.jsx(Dc,{multiple:!0,collapsible:!0,openItems:o,onToggle:i,children:n})},nn=({value:e,title:t,info:n,count:o,children:s})=>{const i=WC();return a.jsxs(Bc,{value:e,className:i.item,children:[a.jsxs("div",{className:i.headerRow,children:[a.jsxs(Lc,{size:"small",className:i.header,children:[t,!!o&&a.jsx(Rn,{count:o,size:"medium",appearance:"ghost",color:"informative",className:i.count})]}),n&&a.jsx(Et,{info:n,infoButton:{"aria-label":`About ${t}`}})]}),a.jsx(zc,{className:i.panel,children:s})]})},UC=pe({root:{display:"flex",flexDirection:"column",height:"100%",overflowY:"auto",overflowX:"hidden",backgroundColor:f.colorNeutralBackground2},empty:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:f.spacingHorizontalM,color:f.colorNeutralForeground3,padding:f.spacingHorizontalXL,textAlign:"center"},place:{padding:`${f.spacingVerticalS} ${f.spacingHorizontalM} 0`,color:f.colorNeutralForeground2}});function VC(){const e=UC(),t=Z(x=>x.selectedButtonId),n=Z(x=>x.selectedGroupId),o=Z(x=>x.location),s=Z(x=>x.tabId),c=D(x=>x.ribbons)[o].tabs.find(x=>x.id===s)?.groups.find(x=>x.id===n),d=Ns(c,t),u=c&&d?os(c,d.id):void 0,m=D(x=>x.locLabels),p=Be(),h=Iw(),b=Cw(o,d?.id),g=D(x=>d?.commandId?x.commands.find(y=>y.id===d.commandId):void 0);return a.jsxs("aside",{className:e.root,"aria-label":"Properties",children:[a.jsx(zC,{button:d}),!d&&h?a.jsx(MC,{command:h.command,items:h.children}):d?a.jsxs(a.Fragment,{children:[a.jsx(DC,{button:d,location:o,tabId:s,groupId:n,overrides:b}),u&&a.jsxs(Ge,{className:e.place,children:["Menu item of “",p(u.parent.label,m,void 0,u.parent.source?.labelToken),"”",u.section.title?` — section “${u.section.title}”`:""]}),ut(d.kind)?a.jsx(OC,{button:d,location:o,tabId:s,groupId:n}):a.jsxs(GC,{storageKey:"properties.button",defaultOpen:["appearance","position","command","display","enable"],children:[a.jsxs(nn,{value:"appearance",title:"Appearance",children:[a.jsx(yi,{part:"appearance",button:d,location:o,tabId:s,groupId:n}),a.jsx(HC,{button:d})]}),a.jsx(nn,{value:"position",title:"Position",children:a.jsx(yi,{part:"position",button:d,location:o,tabId:s,groupId:n})}),a.jsx(nn,{value:"command",title:"Command",children:a.jsx(pC,{button:d,groupId:n,tabId:s,location:o})}),a.jsx(nn,{value:"display",title:"Display rules",count:g?.displayRules.length,info:"All of them must pass for the button to show.",children:a.jsx(SC,{})}),a.jsx(nn,{value:"enable",title:"Enable rules",count:g?.enableRules.length,info:"All of them must pass for the button to be enabled. Unified Interface hides a button that isn't enabled.",children:a.jsx(wC,{})}),a.jsx(nn,{value:"scaling",title:"Scaling",info:"Scaling only applies to the classic ribbon. Unified Interface ignores it.",children:a.jsx(RC,{})}),a.jsxs(nn,{value:"advanced",title:"Advanced",children:[a.jsx(yi,{part:"advanced",button:d,location:o,tabId:s,groupId:n}),a.jsx(jC,{})]})]},`${n}|${d.id}`)]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.empty,children:[a.jsx(Pg,{fontSize:32,style:{opacity:.4}}),a.jsx(X,{size:300,children:"Select a button to view its properties"})]}),a.jsx(TC,{}),a.jsx(kC,{})]})]})}function hm(e,t){const n=new Map,o=l=>{l&&n.set(l,(n.get(l)??0)+1)};for(const l of Object.keys(e))for(const r of e[l].tabs){o(r.commandId);for(const c of r.groups){o(c.source?.attributes.Command);for(const d of je(c))o(d.commandId),o(d.source?.attributes.PopulateQueryCommand)}}const s=new Map,i=new Map;for(const l of t){for(const r of new Set(l.enableRules))s.set(r,(s.get(r)??0)+1);for(const r of new Set(l.displayRules))i.set(r,(i.get(r)??0)+1)}return{byCommand:n,byEnable:s,byDisplay:i}}const XC=e=>(Fg({...e,renderRow:()=>null}),e),gm=B.createContext(void 0),KC=void 0,YC=()=>{var e;return(e=B.useContext(gm))!=null?e:KC},JC=gm.Provider,bm=B.createContext({current:null}),ZC={current:null},ym=()=>{var e;return(e=B.useContext(bm))!=null?e:ZC},QC=bm.Provider,xm=B.createContext({current:null}),e0={current:null},vm=()=>{var e;return(e=B.useContext(xm))!=null?e:e0},t0=xm.Provider,n0=(e,t)=>{const{height:n,itemSize:o,width:s="100%",ariaRowIndexStart:i=2,children:l,listProps:r}=e,c=ym(),d=vm(),m=_g({...e,children:l},t),p=B.useCallback(({data:g,index:x,style:y,isScrolling:S})=>{const C=g[x];return B.createElement(JC,{value:i+x},B.createElement(qg,{value:C.rowId},l(C,y,x,S)))},[i,l]),h=B.useCallback(()=>{c.current&&d.current&&d.current.scroll({left:c.current.scrollLeft,behavior:"instant"})},[]),b=B.useCallback(g=>{var x;(x=c.current)==null||x.removeEventListener("scroll",h),c.current=g,g&&g.addEventListener("scroll",h)},[]);return{...m,itemSize:o,height:n,virtualizedRow:p,width:s,ariaRowIndexStart:i,listProps:r,outerRef:b}};function pa(){return pa=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},pa.apply(null,arguments)}function Pl(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function fa(e,t){return fa=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,o){return n.__proto__=o,n},fa(e,t)}function o0(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,fa(e,t)}var Fl=Number.isNaN||function(t){return typeof t=="number"&&t!==t};function s0(e,t){return!!(e===t||Fl(e)&&Fl(t))}function i0(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!s0(e[n],t[n]))return!1;return!0}function xi(e,t){t===void 0&&(t=i0);var n,o=[],s,i=!1;function l(){for(var r=[],c=0;c<arguments.length;c++)r[c]=arguments[c];return i&&n===this&&t(r,o)||(s=e.apply(this,r),i=!0,n=this,o=r),s}return l}var a0=typeof performance=="object"&&typeof performance.now=="function",_l=a0?function(){return performance.now()}:function(){return Date.now()};function ql(e){cancelAnimationFrame(e.id)}function r0(e,t){var n=_l();function o(){_l()-n>=t?e.call(null):s.id=requestAnimationFrame(o)}var s={id:requestAnimationFrame(o)};return s}var vi=-1;function Hl(e){if(e===void 0&&(e=!1),vi===-1||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",document.body.appendChild(t),vi=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return vi}var Cn=null;function Wl(e){if(e===void 0&&(e=!1),Cn===null||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",n.direction="rtl";var o=document.createElement("div"),s=o.style;return s.width="100px",s.height="100px",t.appendChild(o),document.body.appendChild(t),t.scrollLeft>0?Cn="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?Cn="negative":Cn="positive-ascending"),document.body.removeChild(t),Cn}return Cn}var l0=150,c0=function(t,n){return t};function d0(e){var t,n=e.getItemOffset,o=e.getEstimatedTotalSize,s=e.getItemSize,i=e.getOffsetForIndexAndAlignment,l=e.getStartIndexForOffset,r=e.getStopIndexForStartIndex,c=e.initInstanceProps,d=e.shouldResetStyleCacheOnItemSizeChange,u=e.validateProps;return t=(function(m){o0(p,m);function p(b){var g;return g=m.call(this,b)||this,g._instanceProps=c(g.props,Pl(g)),g._outerRef=void 0,g._resetIsScrollingTimeoutId=null,g.state={instance:Pl(g),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof g.props.initialScrollOffset=="number"?g.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},g._callOnItemsRendered=void 0,g._callOnItemsRendered=xi(function(x,y,S,C){return g.props.onItemsRendered({overscanStartIndex:x,overscanStopIndex:y,visibleStartIndex:S,visibleStopIndex:C})}),g._callOnScroll=void 0,g._callOnScroll=xi(function(x,y,S){return g.props.onScroll({scrollDirection:x,scrollOffset:y,scrollUpdateWasRequested:S})}),g._getItemStyle=void 0,g._getItemStyle=function(x){var y=g.props,S=y.direction,C=y.itemSize,R=y.layout,M=g._getItemStyleCache(d&&C,d&&R,d&&S),I;if(M.hasOwnProperty(x))I=M[x];else{var $=n(g.props,x,g._instanceProps),T=s(g.props,x,g._instanceProps),v=S==="horizontal"||R==="horizontal",O=S==="rtl",A=v?$:0;M[x]=I={position:"absolute",left:O?void 0:A,right:O?A:void 0,top:v?0:$,height:v?"100%":T,width:v?T:"100%"}}return I},g._getItemStyleCache=void 0,g._getItemStyleCache=xi(function(x,y,S){return{}}),g._onScrollHorizontal=function(x){var y=x.currentTarget,S=y.clientWidth,C=y.scrollLeft,R=y.scrollWidth;g.setState(function(M){if(M.scrollOffset===C)return null;var I=g.props.direction,$=C;if(I==="rtl")switch(Wl()){case"negative":$=-C;break;case"positive-descending":$=R-S-C;break}return $=Math.max(0,Math.min($,R-S)),{isScrolling:!0,scrollDirection:M.scrollOffset<$?"forward":"backward",scrollOffset:$,scrollUpdateWasRequested:!1}},g._resetIsScrollingDebounced)},g._onScrollVertical=function(x){var y=x.currentTarget,S=y.clientHeight,C=y.scrollHeight,R=y.scrollTop;g.setState(function(M){if(M.scrollOffset===R)return null;var I=Math.max(0,Math.min(R,C-S));return{isScrolling:!0,scrollDirection:M.scrollOffset<I?"forward":"backward",scrollOffset:I,scrollUpdateWasRequested:!1}},g._resetIsScrollingDebounced)},g._outerRefSetter=function(x){var y=g.props.outerRef;g._outerRef=x,typeof y=="function"?y(x):y!=null&&typeof y=="object"&&y.hasOwnProperty("current")&&(y.current=x)},g._resetIsScrollingDebounced=function(){g._resetIsScrollingTimeoutId!==null&&ql(g._resetIsScrollingTimeoutId),g._resetIsScrollingTimeoutId=r0(g._resetIsScrolling,l0)},g._resetIsScrolling=function(){g._resetIsScrollingTimeoutId=null,g.setState({isScrolling:!1},function(){g._getItemStyleCache(-1,null)})},g}p.getDerivedStateFromProps=function(g,x){return u0(g,x),u(g),null};var h=p.prototype;return h.scrollTo=function(g){g=Math.max(0,g),this.setState(function(x){return x.scrollOffset===g?null:{scrollDirection:x.scrollOffset<g?"forward":"backward",scrollOffset:g,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},h.scrollToItem=function(g,x){x===void 0&&(x="auto");var y=this.props,S=y.itemCount,C=y.layout,R=this.state.scrollOffset;g=Math.max(0,Math.min(g,S-1));var M=0;if(this._outerRef){var I=this._outerRef;C==="vertical"?M=I.scrollWidth>I.clientWidth?Hl():0:M=I.scrollHeight>I.clientHeight?Hl():0}this.scrollTo(i(this.props,g,x,R,this._instanceProps,M))},h.componentDidMount=function(){var g=this.props,x=g.direction,y=g.initialScrollOffset,S=g.layout;if(typeof y=="number"&&this._outerRef!=null){var C=this._outerRef;x==="horizontal"||S==="horizontal"?C.scrollLeft=y:C.scrollTop=y}this._callPropsCallbacks()},h.componentDidUpdate=function(){var g=this.props,x=g.direction,y=g.layout,S=this.state,C=S.scrollOffset,R=S.scrollUpdateWasRequested;if(R&&this._outerRef!=null){var M=this._outerRef;if(x==="horizontal"||y==="horizontal")if(x==="rtl")switch(Wl()){case"negative":M.scrollLeft=-C;break;case"positive-ascending":M.scrollLeft=C;break;default:var I=M.clientWidth,$=M.scrollWidth;M.scrollLeft=$-I-C;break}else M.scrollLeft=C;else M.scrollTop=C}this._callPropsCallbacks()},h.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&ql(this._resetIsScrollingTimeoutId)},h.render=function(){var g=this.props,x=g.children,y=g.className,S=g.direction,C=g.height,R=g.innerRef,M=g.innerElementType,I=g.innerTagName,$=g.itemCount,T=g.itemData,v=g.itemKey,O=v===void 0?c0:v,A=g.layout,E=g.outerElementType,w=g.outerTagName,k=g.style,N=g.useIsScrolling,j=g.width,_=this.state.isScrolling,W=S==="horizontal"||A==="horizontal",ne=W?this._onScrollHorizontal:this._onScrollVertical,le=this._getRangeToRender(),ce=le[0],F=le[1],L=[];if($>0)for(var G=ce;G<=F;G++)L.push(B.createElement(x,{data:T,key:O(G,T),index:G,isScrolling:N?_:void 0,style:this._getItemStyle(G)}));var H=o(this.props,this._instanceProps);return B.createElement(E||w||"div",{className:y,onScroll:ne,ref:this._outerRefSetter,style:pa({position:"relative",height:C,width:j,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:S},k)},B.createElement(M||I||"div",{children:L,ref:R,style:{height:W?"100%":H,pointerEvents:_?"none":void 0,width:W?H:"100%"}}))},h._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var g=this.props.itemCount;if(g>0){var x=this._getRangeToRender(),y=x[0],S=x[1],C=x[2],R=x[3];this._callOnItemsRendered(y,S,C,R)}}if(typeof this.props.onScroll=="function"){var M=this.state,I=M.scrollDirection,$=M.scrollOffset,T=M.scrollUpdateWasRequested;this._callOnScroll(I,$,T)}},h._getRangeToRender=function(){var g=this.props,x=g.itemCount,y=g.overscanCount,S=this.state,C=S.isScrolling,R=S.scrollDirection,M=S.scrollOffset;if(x===0)return[0,0,0,0];var I=l(this.props,M,this._instanceProps),$=r(this.props,I,M,this._instanceProps),T=!C||R==="backward"?Math.max(1,y):1,v=!C||R==="forward"?Math.max(1,y):1;return[Math.max(0,I-T),Math.max(0,Math.min(x-1,$+v)),I,$]},p})(B.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var u0=function(t,n){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,n.instance},m0=d0({getItemOffset:function(t,n){var o=t.itemSize;return n*o},getItemSize:function(t,n){var o=t.itemSize;return o},getEstimatedTotalSize:function(t){var n=t.itemCount,o=t.itemSize;return o*n},getOffsetForIndexAndAlignment:function(t,n,o,s,i,l){var r=t.direction,c=t.height,d=t.itemCount,u=t.itemSize,m=t.layout,p=t.width,h=r==="horizontal"||m==="horizontal",b=h?p:c,g=Math.max(0,d*u-b),x=Math.min(g,n*u),y=Math.max(0,n*u-b+u+l);switch(o==="smart"&&(s>=y-b&&s<=x+b?o="auto":o="center"),o){case"start":return x;case"end":return y;case"center":{var S=Math.round(y+(x-y)/2);return S<Math.ceil(b/2)?0:S>g+Math.floor(b/2)?g:S}default:return s>=y&&s<=x?s:s<y?y:x}},getStartIndexForOffset:function(t,n){var o=t.itemCount,s=t.itemSize;return Math.max(0,Math.min(o-1,Math.floor(n/s)))},getStopIndexForStartIndex:function(t,n,o){var s=t.direction,i=t.height,l=t.itemCount,r=t.itemSize,c=t.layout,d=t.width,u=s==="horizontal"||c==="horizontal",m=n*r,p=u?d:i,h=Math.ceil((p+o-m)/r);return Math.max(0,Math.min(l-1,n+h-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.itemSize}});const p0=e=>{const{slots:t,slotProps:n}=Hg(e),{dir:o}=Fc();return B.createElement(t.root,n.root,B.createElement(m0,{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))},Sm=B.forwardRef((e,t)=>{const n=n0(e,t);return XC(n),p0(n)});Sm.displayName="DataGridBody";const f0=(e,t)=>{var n;const{targetDocument:o}=Fc(),s=Wg({targetDocument:o}),i=B.useRef(null),l=B.useRef(null);let r=e.containerWidthOffset;r===void 0&&(r=e.selectionMode?-44:0,r-=s||0);const c=Gg({...e,"aria-rowcount":e.items.length,containerWidthOffset:r},t);return e.resizableColumns&&((n=e.resizableColumnsOptions)==null?void 0:n.autoFitColumns)===!1&&c.root.style&&(c.root.style.minWidth="auto"),{...c,headerRef:i,bodyRef:l}},h0=(e,t)=>B.createElement(t0,{value:e.headerRef},B.createElement(QC,{value:e.bodyRef},Ug(e,t))),wm=B.forwardRef((e,t)=>{const n=f0(e,t);return Vg(n),h0(n,Xg(n))});wm.displayName="DataGrid";const g0=(e,t)=>{const n=YC();return Kg({...e,"aria-rowindex":n},t)},b0=pe({root:{minWidth:"fit-content"}}),y0=e=>{const t=b0();return e.root.className=Ce(t.root,e.root.className),Yg(e),e},gr=B.forwardRef((e,t)=>{const n=g0(e,t);return y0(n),Jg(n)});gr.displayName="DataGridRow";const x0=(e,t)=>{const n=ym(),o=vm(),s=B.useCallback(()=>{n.current&&o.current&&n.current.scroll({left:o.current.scrollLeft,behavior:"instant"})},[]),i=B.useCallback(r=>{var c;(c=o.current)==null||c.removeEventListener("scroll",s),o.current=r,r&&r.addEventListener("scroll",s)},[]),l=Zg(e,t);return l.root.ref=ic(l.root.ref,i),l},v0=pe({root:{overflowX:"auto",scrollbarWidth:"none","::-webkit-scrollbar":{width:0,height:0}}}),S0=e=>{const t=v0();return e.root.className=Ce(t.root,e.root.className),Qg(e),e},Cm=B.forwardRef((e,t)=>{const n=x0(e,t);return S0(n),eb(n)});Cm.displayName="DataGridHeader";const w0=new Set(["mscrm","command","commands","enablerule","enablerules","displayrule","displayrules","rule","button","customaction","template","templates"]);function Yo(e){const t=e.split(".").filter(Boolean);for(let n=t.length-1;n>=0;n--)if(!w0.has(t[n].toLowerCase()))return t[n];return e}const Si=36,No=pe({row:{cursor:"pointer"},selected:{backgroundColor:f.colorSubtleBackgroundSelected,":hover":{backgroundColor:f.colorSubtleBackgroundSelected}},mono:{fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200},tags:{display:"flex",gap:f.spacingHorizontalXXS,minWidth:0,overflow:"hidden",whiteSpace:"nowrap"},chip:{display:"inline-flex",padding:"0 6px",borderRadius:f.borderRadiusMedium,fontSize:f.fontSizeBase200,border:`1px solid ${f.colorNeutralStroke2}`,backgroundColor:f.colorNeutralBackground3,flexShrink:0},muted:{color:f.colorNeutralForeground3},empty:{padding:f.spacingVerticalS,color:f.colorNeutralForeground3},box:{flex:1,minHeight:0,minWidth:0,overflowX:"auto",overflowY:"auto"}}),C0={javascript:"JS",url:"URL",powerFx:"Fx",customApi:"API",outlookCommand:"Outlook",raw:"XML"},Kt=e=>a.jsx(X,{size:200,weight:"semibold",children:e}),Rm=(e,t)=>a.jsxs(xe,{size:"medium",appearance:"tint",color:e?"brand":"informative",children:[e??0," ",t,e===1?"":"s"]});function Im({id:e}){const t=No();return a.jsx(he,{content:e,relationship:"description",children:a.jsx(go,{truncate:!0,className:t.mono,children:e})})}const jm=nt.createContext(null),wi=e=>!!e.target.closest("button");function R0({item:e,rowId:t,style:n}){const o=No(),s=nt.useContext(jm),i=s.idOf(e),l=s.selected===i;return a.jsx(gr,{style:n,"aria-current":l||void 0,"data-element-row":i,className:Ce(o.row,l&&o.selected),onClick:r=>{wi(r)||s.select(i)},onDoubleClick:r=>{wi(r)||s.open(e)},onKeyDown:r=>{wi(r)||(r.key===" "?(r.preventDefault(),s.select(i)):r.key==="Enter"&&(r.preventDefault(),s.open(e)))},children:({renderCell:r})=>a.jsx(Ec,{children:r(e)})},t)}const I0=({item:e,rowId:t},n)=>a.jsx(R0,{item:e,rowId:t,style:n}),Gl=34;function $m({items:e,columns:t,sizing:n,idOf:o,label:s,height:i,onOpen:l,emptyText:r}){const c=No(),[d,u]=B.useState(null),m=B.useRef(null),[p,h]=B.useState(0);B.useLayoutEffect(()=>{const y=Math.floor(m.current?.getBoundingClientRect().height??0);y!==p&&h(y)},[i,p]),B.useEffect(()=>{const y=m.current;if(!y||typeof ResizeObserver>"u")return;const S=new ResizeObserver(([C])=>h(Math.floor(C.contentRect.height)));return S.observe(y),()=>S.disconnect()},[]);const b=Oc({tabBehavior:"unlimited",ignoreDefaultKeydown:{Enter:!0}}),g=B.useMemo(()=>({selected:d,select:u,open:l,idOf:o}),[d,l,o]),x=Math.max(Si,(p||i+Gl)-Gl);return a.jsx("div",{ref:m,className:c.box,...b,children:e.length===0?a.jsx(X,{as:"p",size:200,className:c.empty,children:r}):a.jsx(jm.Provider,{value:g,children:a.jsxs(wm,{items:e,columns:t,columnSizingOptions:n,resizableColumns:!0,getRowId:o,focusMode:"composite",size:"small","aria-label":s,children:[a.jsx(Cm,{children:a.jsx(gr,{children:({renderHeaderCell:y})=>a.jsx(Mc,{children:y()})})}),a.jsx(Sm,{itemSize:Si,height:Math.min(x,e.length*Si),listProps:{width:"100%",style:{overflowX:"hidden"}},children:I0})]})})})}function Ul({id:e,kind:t,onOpen:n}){return a.jsx(he,{content:um(e,t,!!n),relationship:"description",children:a.jsx(Ea,{size:"extra-small",appearance:"outline",shape:"rounded",children:a.jsx(Da,{onClick:n,children:Yo(e)})})})}function j0({commands:e,usage:t,height:n,onOpen:o,onOpenRule:s,isRuleLoaded:i=()=>!0,emptyText:l}){const r=No(),c=[He({columnId:"id",renderHeaderCell:()=>Kt("Command"),renderCell:d=>a.jsx(Im,{id:d.id})}),He({columnId:"actions",renderHeaderCell:()=>Kt("Actions"),renderCell:d=>a.jsx("span",{className:r.tags,children:d.actions.length===0?a.jsx("span",{className:r.muted,children:"—"}):d.actions.map((u,m)=>a.jsx("span",{className:r.chip,children:C0[u.kind]??"XML"},m))})}),He({columnId:"enable",renderHeaderCell:()=>Kt("Enable rules"),renderCell:d=>a.jsx("span",{className:r.tags,children:d.enableRules.map(u=>a.jsx(Ul,{id:u,kind:"enable",onOpen:i(u,"enable")?()=>s(u,"enable"):void 0},u))})}),He({columnId:"display",renderHeaderCell:()=>Kt("Display rules"),renderCell:d=>a.jsx("span",{className:r.tags,children:d.displayRules.map(u=>a.jsx(Ul,{id:u,kind:"display",onOpen:i(u,"display")?()=>s(u,"display"):void 0},u))})}),He({columnId:"used",renderHeaderCell:()=>Kt("Used by"),renderCell:d=>Rm(t.get(d.id),"control")}),He({columnId:"edit",renderHeaderCell:()=>null,renderCell:d=>a.jsx(Y,{appearance:"subtle",size:"small","aria-label":`Edit ${d.id}`,onClick:()=>o(d.id),children:"Edit"})})];return a.jsx($m,{items:e,columns:c,sizing:{id:{defaultWidth:260,minWidth:120},actions:{defaultWidth:84,minWidth:48},enable:{defaultWidth:180,minWidth:80},display:{defaultWidth:180,minWidth:80},used:{defaultWidth:100,minWidth:72},edit:{defaultWidth:60,minWidth:52}},idOf:d=>d.id,label:"Commands",height:n,onOpen:d=>o(d.id),emptyText:l})}function Vl({rules:e,kind:t,usage:n,height:o,onOpen:s,emptyText:i}){const l=No(),r=[He({columnId:"id",renderHeaderCell:()=>Kt("Rule"),renderCell:c=>a.jsx(Im,{id:c.id})}),He({columnId:"steps",renderHeaderCell:()=>Kt("Steps"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.steps.length===0?a.jsx("span",{className:l.muted,children:"—"}):a.jsxs(a.Fragment,{children:[c.steps.slice(0,3).map((d,u)=>a.jsx("span",{className:l.chip,children:d.kind.replace(/Rule$/,"")},u)),c.steps.length>3&&a.jsxs("span",{className:Ce(l.chip,l.muted),children:["+",c.steps.length-3]})]})})}),He({columnId:"used",renderHeaderCell:()=>Kt("Used by"),renderCell:c=>Rm(n.get(c.id),"command")}),He({columnId:"edit",renderHeaderCell:()=>null,renderCell:c=>a.jsx(Y,{appearance:"subtle",size:"small","aria-label":`Edit ${c.id}`,onClick:()=>s(c.id),children:"Edit"})})];return a.jsx($m,{items:e,columns:r,sizing:{id:{defaultWidth:360,minWidth:140},steps:{defaultWidth:260,minWidth:100},used:{defaultWidth:110,minWidth:80},edit:{defaultWidth:60,minWidth:52}},idOf:c=>c.id,label:t==="enable"?"Enable rules":"Display rules",height:o,onOpen:c=>s(c.id),emptyText:i})}const Tm=pe({root:{display:"flex",flexDirection:"column",borderTop:`1px solid ${f.colorNeutralStroke2}`,backgroundColor:f.colorNeutralBackground2,flexShrink:0},tabRow:{display:"flex",alignItems:"center",borderBottom:`1px solid ${f.colorNeutralStroke2}`,gap:0,paddingRight:f.spacingHorizontalS,flexShrink:0},content:{flex:1,minHeight:0,overflowY:"auto",padding:`${f.spacingHorizontalXS} ${f.spacingHorizontalM}`},gridContent:{overflow:"hidden",display:"flex",flexDirection:"column"},tabCount:{marginLeft:f.spacingHorizontalXS},toolbar:{flexShrink:0,display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,paddingBottom:f.spacingHorizontalXS,borderBottom:`1px solid ${f.colorNeutralStroke3}`,marginBottom:f.spacingHorizontalXS},historyRow:{display:"flex",alignItems:"flex-start",gap:f.spacingHorizontalS,padding:`${f.spacingHorizontalXS} 0`,borderBottom:`1px solid ${f.colorNeutralStroke3}`},historyAvatar:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:f.colorBrandBackground2,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:"2px"},historyContent:{flex:1,minWidth:0},consoleRow:{padding:"2px 0",fontFamily:f.fontFamilyMonospace,fontSize:f.fontSizeBase200,display:"flex",gap:f.spacingHorizontalS},consoleTs:{color:f.colorNeutralForeground4,flexShrink:0,fontSize:f.fontSizeBase200}}),Ci="Shown once the entity's ribbon is loaded.";function $0(){const e=Tm(),t=Ie(P=>P.target!==null),n=J(P=>P.activeBottomTab),o=J(P=>P.setActiveBottomTab),s=J(P=>P.bottomPanelHeight),i=J(P=>P.bottomCollapsed),l=J(P=>P.setBottomCollapsed),r=D(P=>P.commands),c=D(P=>P.displayRules),d=D(P=>P.enableRules),u=D(P=>P.past),m=D(P=>P.ribbons),p=D(P=>P.restore),h=ae(P=>P.currentUserName),b=re(P=>P.entries),g=re(P=>P.clear),x=re(P=>P.logWarn),y=J(P=>P.openCommandEditor),S=J(P=>P.openRuleEditor),C=J(P=>P.openDiffViewer),R=D(P=>P.upsertCommand),M=D(P=>P.upsertEnableRule),I=D(P=>P.upsertDisplayRule),[$,T]=B.useState(""),[v,O]=B.useState(""),[A,E]=B.useState(""),[w,k]=B.useState(""),N=B.useMemo(()=>{const P=$.toLowerCase().trim();return P?r.filter(K=>K.id.toLowerCase().includes(P)||K.enableRules.some(ue=>ue.toLowerCase().includes(P))||K.displayRules.some(ue=>ue.toLowerCase().includes(P))):r},[r,$]),j=B.useMemo(()=>{const P=v.toLowerCase().trim();return P?c.filter(K=>K.id.toLowerCase().includes(P)||K.steps.some(ue=>ue.kind.toLowerCase().includes(P))):c},[c,v]),_=B.useMemo(()=>{const P=A.toLowerCase().trim();return P?d.filter(K=>K.id.toLowerCase().includes(P)||K.steps.some(ue=>ue.kind.toLowerCase().includes(P))):d},[d,A]),W=B.useMemo(()=>{const P=w.toLowerCase().trim();return P?u.filter(K=>K.op.toLowerCase().includes(P)||K.target.toLowerCase().includes(P)||K.detail.toLowerCase().includes(P)||K.userName.toLowerCase().includes(P)):u},[u,w]),ne=()=>{const P=new Set(r.map(ue=>ue.id)),K=Ya("New","Command",P);R({id:K,enableRules:[],displayRules:[],actions:[]}),y(K)},le=()=>{const P=new Set(d.map(ue=>ue.id)),K=yo("New","Enable",P);M({id:K,steps:[]}),S(K,"enable")},ce=()=>{const P=new Set(c.map(ue=>ue.id)),K=yo("New","Display",P);I({id:K,steps:[]}),S(K,"display")},F=B.useMemo(()=>hm(m,r),[m,r]),L=i?32:s,G=Math.max(36,s-116),H=n==="commands"||n==="displayRules"||n==="enableRules";function te(P){return P.userName&&P.userName!=="You"?P.userName:h||"You"}return a.jsxs("div",{className:e.root,style:{height:L},children:[a.jsxs("div",{className:e.tabRow,children:[a.jsxs(Ma,{selectedValue:n,onTabSelect:(P,K)=>{o(K.value),i&&l(!1)},size:"small",style:{flex:1},children:[a.jsxs(Gt,{value:"commands",children:["Commands",a.jsx(Rn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:r.length,showZero:!0,overflowCount:9999})]}),a.jsxs(Gt,{value:"displayRules",children:["Display rules",a.jsx(Rn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:c.length,showZero:!0,overflowCount:9999})]}),a.jsxs(Gt,{value:"enableRules",children:["Enable rules",a.jsx(Rn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:d.length,showZero:!0,overflowCount:9999})]}),a.jsxs(Gt,{value:"history",children:["History",a.jsx(Rn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:u.length,showZero:!0,overflowCount:9999})]}),a.jsx(Gt,{value:"console",children:"Console"})]}),a.jsx(Y,{appearance:"subtle",size:"small",icon:i?a.jsx(jc,{}):a.jsx(dt,{}),onClick:()=>l(!i),"aria-label":i?"Expand panel":"Collapse panel"})]}),!i&&a.jsxs("div",{className:Ce(e.content,H&&e.gridContent),children:[n==="commands"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:ne,children:"New command"}),a.jsx(cn,{size:"small",placeholder:`Filter ${r.length} command${r.length!==1?"s":""}…`,value:$,"aria-label":"Filter the commands",onChange:(P,K)=>T(K.value),style:{minWidth:0,flex:1,maxWidth:360}}),$&&a.jsxs(X,{size:200,style:{color:f.colorNeutralForeground3},children:[N.length," match",N.length!==1?"es":""]})]}),a.jsx(j0,{commands:N,usage:F.byCommand,height:G,onOpen:y,onOpenRule:S,isRuleLoaded:(P,K)=>(K==="enable"?d:c).some(ue=>ue.id===P),emptyText:t?$?"No commands match.":"No commands.":Ci})]}),n==="displayRules"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:ce,children:"New display rule"}),a.jsx(cn,{size:"small",placeholder:`Filter ${c.length} display rule${c.length!==1?"s":""}…`,value:v,"aria-label":"Filter the display rules",onChange:(P,K)=>O(K.value),style:{minWidth:0,flex:1,maxWidth:360}}),v&&a.jsxs(X,{size:200,style:{color:f.colorNeutralForeground3},children:[j.length," match",j.length!==1?"es":""]})]}),a.jsx(Vl,{rules:j,kind:"display",usage:F.byDisplay,height:G,onOpen:P=>S(P,"display"),emptyText:t?v?"No display rules match.":"No display rules.":Ci})]}),n==="enableRules"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:le,children:"New enable rule"}),a.jsx(cn,{size:"small",placeholder:`Filter ${d.length} enable rule${d.length!==1?"s":""}…`,value:A,"aria-label":"Filter the enable rules",onChange:(P,K)=>E(K.value),style:{minWidth:0,flex:1,maxWidth:360}}),A&&a.jsxs(X,{size:200,style:{color:f.colorNeutralForeground3},children:[_.length," match",_.length!==1?"es":""]})]}),a.jsx(Vl,{rules:_,kind:"enable",usage:F.byEnable,height:G,onOpen:P=>S(P,"enable"),emptyText:t?A?"No enable rules match.":"No enable rules.":Ci})]}),n==="history"&&a.jsxs(a.Fragment,{children:[u.length>0&&a.jsxs("div",{className:e.toolbar,children:[a.jsx(cn,{size:"small",placeholder:`Filter ${u.length} entr${u.length!==1?"ies":"y"}…`,value:w,"aria-label":"Filter the history",onChange:(P,K)=>k(K.value),style:{minWidth:0,flex:1,maxWidth:360}}),w&&a.jsxs(X,{size:200,style:{color:f.colorNeutralForeground3},children:[W.length," match",W.length!==1?"es":""]})]}),u.length===0?a.jsx(X,{size:200,style:{color:f.colorNeutralForeground3},children:"No history yet — make a change to see it here."}):W.slice().reverse().map((P,K)=>{const ue=u.indexOf(P);return a.jsxs("div",{className:e.historyRow,children:[a.jsx("div",{className:e.historyAvatar,"aria-hidden":!0,children:a.jsx(Rc,{fontSize:12,style:{color:f.colorBrandForeground1}})}),a.jsxs("div",{className:e.historyContent,children:[a.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[a.jsx(X,{size:200,weight:"semibold",children:P.op}),a.jsxs(X,{size:200,children:["— ",a.jsx("strong",{children:P.target})]}),P.detail&&a.jsx(X,{size:200,style:{color:f.colorNeutralForeground3},children:P.detail})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2},children:[a.jsxs(X,{size:200,style:{color:f.colorNeutralForeground3},children:[te(P)," ·"," ",new Date(P.ts).toLocaleTimeString()]}),a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(tb,{}),onClick:()=>C("history",ue),children:"View diff"}),a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(pc,{}),title:"Undo this change and every later one (redo brings them back)",onClick:()=>p(ue),children:"Undo from here"})]})]})]},K)})]}),n==="console"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(Ro,{}),disabled:b.length===0,onClick:()=>{const P=b.slice().reverse().map(K=>{const ue=new Date(K.ts).toLocaleTimeString();return`${K.scope} ${ue}
|
|
133
|
+
[${K.level.toUpperCase()}]
|
|
134
|
+
${K.message}`}).join(`
|
|
135
|
+
|
|
136
|
+
`);Ps(P).then(K=>{K.ok||x("ui",`Couldn't copy the log: ${K.error}.`)})},title:"Copy all log entries to clipboard",children:"Copy log"}),a.jsx(Y,{appearance:"subtle",size:"small",onClick:g,children:"Clear log"})]}),a.jsx("div",{children:b.length===0?a.jsx(X,{size:200,style:{color:f.colorNeutralForeground3},children:"No runtime diagnostics yet."}):b.slice().reverse().map(P=>a.jsx(T0,{ts:`${P.scope} ${new Date(P.ts).toLocaleTimeString()}`,level:P.level,message:P.message},P.id))})]})]})]})}function T0({ts:e,level:t,message:n}){const o=Tm(),s=t==="error"?f.colorStatusDangerForeground1:t==="warn"?f.colorStatusWarningForeground1:f.colorNeutralForeground3;return a.jsxs("div",{className:o.consoleRow,children:[a.jsx("span",{className:o.consoleTs,children:e}),a.jsxs("span",{style:{color:s},children:["[",t.toUpperCase(),"]"]}),a.jsx("span",{style:{color:f.colorNeutralForeground1},children:n})]})}const N0=pe({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},header:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalS}`,flexShrink:0},search:{flex:1,minWidth:0},body:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"},selected:{backgroundColor:f.colorSubtleBackgroundSelected,":hover":{backgroundColor:f.colorSubtleBackgroundSelected}},label:{display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},hidden:{color:f.colorNeutralForeground3},muted:{color:f.colorNeutralForeground3},yours:{flexShrink:0,marginLeft:f.spacingHorizontalXS},empty:{padding:`${f.spacingVerticalM} ${f.spacingHorizontalM}`,color:f.colorNeutralForeground3}}),so=e=>`tab:${e}`,Jo=(e,t)=>`group:${e}:${t}`,ha=(e,t,n)=>`btn:${e}:${t}:${n}`,Xl=(e,t,n)=>n?t&&ha(e,t,n):t?Jo(e,t):so(e),k0=e=>e.target===e.currentTarget,A0=e=>e.key==="ContextMenu"||e.shiftKey&&e.key==="F10";function O0(){const e=N0(),t=Be(),n=Z(q=>q.location),o=Z(q=>q.tabId),s=Z(q=>q.selectedGroupId),i=Z(q=>q.selectedButtonId),l=Z(q=>q.setTabId),r=Z(q=>q.selectGroup),c=Z(q=>q.selectButtonInContext),d=D(q=>q.ribbons[n].tabs),u=D(q=>q.locLabels),m=D(q=>q.baseLanguageCode),p=D(q=>q.baseline),h=D(q=>q.layers),b=D(q=>q.renameTab),g=D(q=>q.deleteTab),x=D(q=>q.reorderTabs),y=ae(q=>!!q.activeEntity),S=Ie(q=>q.target!==null),C=J(q=>q.openNewTab),R=J(q=>q.openNewGroup),M=J(q=>q.openTabDisplayRules),I=J(q=>q.openTitleTranslations),$=J(q=>q.announce),T=J(q=>q.noteStructureChoice),[v,O]=B.useState(""),[A,E]=B.useState(()=>new Set),[w,k]=B.useState(null),[N,j]=B.useState(null),[_,W]=B.useState(null),[ne,le]=B.useState(null),[ce,F]=B.useState(null),[L,G]=B.useState(null),[H,te]=B.useState(null),P=B.useRef(null),K=B.useRef(null),ue=q=>vt(q.id,t(q.label,u,m,q.source?.titleToken)),Me=q=>vt(q.id,t(q.label,u,m,q.source?.titleToken)),Pe=q=>t(q.label,u,void 0,q.source?.labelToken)||q.id,ot=d.find(q=>q.id===o);B.useEffect(()=>{const q=[so(o)];s&&q.push(Jo(o,s)),E(ie=>q.every(de=>ie.has(de))?ie:new Set([...ie,...q]))},[n,o,s]);const Ee=Xl(o,s,i);B.useEffect(()=>{if(!Ee)return;[...K.current?.querySelectorAll("[data-structure-key]")??[]].find(ie=>ie.dataset.structureKey===Ee)?.scrollIntoView?.({block:"nearest"})},[Ee]);const Fe=v.trim().toLowerCase(),Q=B.useMemo(()=>{const q=(ye,be)=>ye.toLowerCase().includes(Fe)||be.toLowerCase().includes(Fe),ie=new Set,de=new Set;if(!Fe)return{shown:null,opened:de};for(const ye of d){const be=so(ye.id),Xe=q(ue(ye),ye.id);for(const st of ye.groups){const wt=Jo(ye.id,st.id),bn=q(Me(st),st.id);for(const Un of st.buttons){const xr=q(Pe(Un),Un.id);(xr||bn||Xe)&&ie.add(ha(ye.id,st.id,Un.id)),xr&&(de.add(be),de.add(wt),ie.add(wt),ie.add(be))}(bn||Xe)&&ie.add(wt),bn&&(de.add(be),ie.add(be))}Xe&&ie.add(be)}return{shown:ie,opened:de}},[Fe,d,u,m,t]),Le=q=>!Q.shown||Q.shown.has(q),at=Fe?w??Q.opened:A,Gn=(q,ie)=>{const de=String(ie.value),ye=P.current===de&&ie.type==="Click"?!0:ie.open;P.current=null;const be=new Set(at);ye?be.add(de):be.delete(de),Fe?k(be):E(be)},z=q=>{(q.id!==o||s||i)&&l(q.id)},V=(q,ie)=>{q.id!==o&&l(q.id),r(ie.id)},U=(q,ie,de)=>c(n,q.id,ie.id,de.id),oe=q=>rs("tab",q.id,p[n],Ln({layers:h},n)),se=q=>rs("group",q.id,p[n],Ln({layers:h},n)),Te=q=>kd(q,p[n],An({layers:h},n)),me=(q,ie,de)=>{$(`${de} can't be renamed: ${Vo}.`),re.getState().logInfo("structure",`${q} ${ie} can't be renamed: ${Vo}.`)},ze=(q,ie)=>{const de=d.map(Xe=>Xe.id),ye=de.indexOf(q.id),be=ye+ie;ye<0||be<0||be>=de.length||x(n,pb(de,ye,be))},gn=q=>setTimeout(()=>{const ie=document.activeElement?.closest('[role="dialog"], [role="alertdialog"]');if(ie&&!ie.contains(K.current))return;const de=Z.getState(),ye=Xl(de.tabId,de.selectedGroupId,de.selectedButtonId),be=[...K.current?.querySelectorAll("[data-structure-key]")??[]].find(Xe=>Xe.dataset.structureKey===ye)??q?.closest('[role="treeitem"]');be?.isConnected&&be.focus()}),ko=d.find(q=>q.id===ce)??ot,Hs=(q,ie,de,ye)=>({"data-structure-key":q,onClick:()=>{Ee!==q&&(P.current=q),ie(),q.startsWith("tab:")||T()},onKeyDown:be=>{k0(be)&&(A0(be)?(be.preventDefault(),ie(),de(be.currentTarget)):be.key==="F2"&&ye&&(be.preventDefault(),ye()))},onContextMenu:be=>{be.target.closest('[role="treeitem"]')===be.currentTarget&&(be.preventDefault(),ie(),de(be.currentTarget))}}),Ws=(q,ie,de)=>a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(xs,{}),"aria-label":`Actions for ${q}`,onClick:ye=>{ie(),de(ye.currentTarget)}}),Hm=(q,ie,de)=>{const ye=ha(q.id,ie.id,de.id);if(!Le(ye))return null;const be=Pe(de),Xe=Ee===ye,st=de.custom&&!de.managed,wt=()=>U(q,ie,de),bn=Un=>{F(q.id),le({button:de,groupId:ie.id,anchor:Un})};return a.jsx(Ut,{itemType:"leaf",value:ye,"aria-selected":Xe,"aria-description":de.id,...Hs(ye,wt,bn),children:a.jsx(Vt,{className:Xe?e.selected:void 0,iconBefore:a.jsx(St,{button:de,size:16}),aside:de.hidden?a.jsx(xe,{size:"medium",appearance:"outline",color:"subtle",children:"Hidden"}):a.jsx(X,{size:200,className:e.muted,"aria-label":`Sequence ${de.sequence}`,children:de.sequence}),actions:Ws(be,wt,bn),children:a.jsxs("span",{style:{display:"flex",alignItems:"center",minWidth:0},children:[a.jsx("span",{className:Ce(e.label,de.hidden&&e.hidden),children:be}),st&&a.jsx(he,{content:"Yours: added by your customizations",relationship:"label",children:a.jsx(xe,{size:"extra-small",color:"brand",className:e.yours})})]})})},ye)},Wm=(q,ie)=>{const de=Jo(q.id,ie.id);if(!Le(de))return null;const ye=Me(ie),be=Ee===de,Xe=()=>V(q,ie),st=wt=>{F(q.id),W({group:ie,anchor:wt})};return a.jsxs(Ut,{itemType:"branch",value:de,"aria-selected":be,"aria-description":ie.id,...Hs(de,Xe,st,()=>{if(!se(ie))return me("Group",ie.id,ye);Xe(),F(q.id),W({group:ie,anchor:document.body,action:"rename"})}),children:[a.jsx(Vt,{className:be?e.selected:void 0,iconBefore:a.jsx(ob,{}),aside:a.jsx(X,{size:200,className:e.muted,"aria-label":`${ie.buttons.length} controls`,children:ie.buttons.length}),actions:Ws(ye,Xe,st),children:a.jsx("span",{className:e.label,children:ye})}),a.jsx(io,{children:ft(ie.buttons).map(wt=>Hm(q,ie,wt))})]},de)},Gm=q=>{const ie=so(q.id);if(!Le(ie))return null;const de=ue(q),ye=Ee===ie,be=st=>j({tab:q,anchor:st}),Xe=()=>{oe(q)?G(q):me("Tab",q.id,de)};return a.jsxs(Ut,{itemType:"branch",value:ie,"aria-selected":ye,"aria-description":q.id,...Hs(ie,()=>z(q),be,Xe),children:[a.jsx(Vt,{className:ye?e.selected:void 0,iconBefore:a.jsx(nb,{}),aside:a.jsx(X,{size:200,className:e.muted,"aria-label":`${q.groups.length} groups`,children:q.groups.length}),actions:Ws(de,()=>z(q),be),children:a.jsx("span",{className:e.label,children:de})}),a.jsx(io,{children:ft(q.groups).map(st=>Wm(q,st))})]},ie)},Gs=N?d.findIndex(q=>q.id===N.tab.id):-1,yr=N?N.tab.tabDisplayRules.reduce((q,ie)=>q+ie.rules.length,0):0,Um=d.filter(q=>Le(so(q.id)));return a.jsxs("div",{className:e.root,children:[a.jsxs("div",{className:e.header,children:[a.jsx(cn,{size:"small",className:e.search,placeholder:"Filter tabs, groups, buttons","aria-label":"Filter the structure",value:v,disabled:!y||!S,onChange:(q,ie)=>{O(ie.value),k(null)}}),a.jsx(he,{content:"Add tab",relationship:"label",children:a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),disabled:!y||!S,onClick:C})})]}),a.jsx("div",{className:e.body,children:y?S?d.length===0?a.jsx(X,{as:"p",block:!0,size:200,className:e.empty,children:"This location has no tabs."}):Um.length===0?a.jsxs(X,{as:"p",block:!0,size:200,className:e.empty,children:["Nothing matches “",v.trim(),"”."]}):a.jsx(io,{ref:K,size:"small","aria-label":"Ribbon structure",openItems:at,onOpenChange:Gn,children:d.map(Gm)}):a.jsx(X,{as:"p",block:!0,size:200,className:e.empty,children:"Shown once the entity's ribbon is loaded."}):a.jsx(X,{as:"p",block:!0,size:200,className:e.empty,children:"Choose an entity to see its tabs, groups and buttons."})}),N&&a.jsxs(Je,{open:!0,onOpenChange:(q,ie)=>{ie.open||(j(null),gn(N.anchor))},positioning:{target:N.anchor,position:"below",align:"start"},children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Qe,{children:a.jsxs(et,{"aria-label":`Actions for ${ue(N.tab)}`,children:[oe(N.tab)?a.jsx(fe,{secondaryContent:"F2",onClick:()=>G(N.tab),children:"Rename…"}):a.jsx(fe,{disabled:!0,title:Vo,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),a.jsx(fe,{icon:a.jsx(Na,{}),disabled:!oe(N.tab),onClick:()=>I(n,"tab",N.tab.id,N.tab.id),children:"Translate title…"}),a.jsx(fe,{icon:a.jsx(Fn,{}),secondaryContent:yr>0?String(yr):void 0,onClick:()=>M(n,N.tab.id),children:"Tab display rules…"}),a.jsx(fe,{icon:a.jsx(ke,{}),disabled:!!Zt(n,N.tab.id),subText:Zt(n,N.tab.id),onClick:()=>{z(N.tab),R()},children:"Add group…"}),a.jsx(Mt,{}),a.jsx(fe,{disabled:Gs<=0,onClick:()=>ze(N.tab,-1),children:"Move up"}),a.jsx(fe,{disabled:Gs<0||Gs>=d.length-1,onClick:()=>ze(N.tab,1),children:"Move down"}),a.jsx(Mt,{}),a.jsx(fe,{disabled:!Te(N.tab),onClick:()=>te(N.tab),children:"Delete tab…"})]})})]}),ko&&a.jsx(lr,{location:n,tab:ko,moveLabels:["Move up","Move down"],target:_,onClose:()=>{gn(_?.anchor instanceof HTMLElement?_.anchor:void 0),W(null)}}),ko&&a.jsx(To,{location:n,tab:ko,target:ne,onClose:()=>{gn(ne?.anchor),le(null)}}),L&&a.jsx(Tu,{open:!0,noun:"tab",initialLabel:Ve(L.label,u,m),onRename:q=>{b(n,L.id,q),G(null)},onCancel:()=>G(null)}),H&&a.jsxs(Hn,{open:!0,title:"Delete tab",confirmLabel:"Delete tab",destructive:!0,onConfirm:()=>{g(n,H.id),te(null)},onCancel:()=>te(null),children:["Delete the tab “",ue(H),"” and its groups and buttons?"]})]})}const M0="application/x-rw-se",E0=pe({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},header:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS,padding:`${f.spacingVerticalS} ${f.spacingHorizontalS}`,flexShrink:0},search:{flex:1,minWidth:0},body:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"},name:{display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:f.colorNeutralForeground3,whiteSpace:"nowrap"},meta:{display:"flex",alignItems:"center",gap:f.spacingHorizontalXS},empty:{padding:`${f.spacingVerticalS} ${f.spacingHorizontalM}`,color:f.colorNeutralForeground3}}),Ri=100,D0=e=>e.key==="ContextMenu"||e.shiftKey&&e.key==="F10";function B0(){const e=E0(),t=Be(),n=D(z=>z.commands),o=D(z=>z.displayRules),s=D(z=>z.enableRules),i=D(z=>z.templates),l=D(z=>z.ribbons),r=D(z=>z.baseline),c=D(z=>z.locLabels),d=D(z=>z.baseLanguageCode),u=D(z=>z.upsertCommand),m=D(z=>z.upsertEnableRule),p=D(z=>z.upsertDisplayRule),h=D(z=>z.createButton),b=Z(z=>z.location),g=Z(z=>z.tabId),x=Z(z=>z.selectButtonInContext),y=J(z=>z.openCommandEditor),S=J(z=>z.openRuleEditor),C=J(z=>z.announce),R=J(z=>z.noteStructureChoice),[M,I]=B.useState(""),[$,T]=B.useState(()=>new Set(["buttons"])),[v,O]=B.useState(null),[A,E]=B.useState({}),w=B.useMemo(()=>{const z=[];for(const V of Object.keys(l)){const U=new Set(r[V].tabs.flatMap(oe=>oe.groups.flatMap(se=>je(se))).map(oe=>oe.id));for(const oe of l[V].tabs)for(const se of oe.groups)for(const Te of je(se))Te.custom&&z.push({button:Te,location:V,tabId:oe.id,groupId:se.id,isNew:!U.has(Te.id)})}return z},[l,r]),k=B.useMemo(()=>hm(l,n),[l,n]),N=z=>t(z.label,c,void 0,z.source?.labelToken)||z.id,j=M.trim().toLowerCase(),_=(...z)=>!j||z.some(V=>V.toLowerCase().includes(j)),W=w.filter(z=>_(N(z.button),z.button.id)),ne=n.filter(z=>_(z.id)),ce=[...s.map(z=>({id:z.id,kind:"enable"})),...o.map(z=>({id:z.id,kind:"display"}))].filter(z=>_(z.id)),F=i.filter(z=>_(z.id)),L=j?new Set([["buttons",W],["commands",ne],["rules",ce],["templates",F]].filter(([,z])=>z.length>0).map(([z])=>z)):null,[G,H]=B.useState(null),te=L?G?.q===j?G.open:L:$,P=()=>{const z=Ya("New","Command",new Set(n.map(V=>V.id)));u({id:z,enableRules:[],displayRules:[],actions:[]}),y(z)},K=z=>{const V=yo("New",z==="enable"?"Enable":"Display",new Set([...s.map(U=>U.id),...o.map(U=>U.id)]));z==="enable"?m({id:V,steps:[]}):p({id:V,steps:[]}),S(V,z)},ue=z=>{x(z.location,z.tabId,z.groupId,z.button.id),R()},Me=l[b].tabs.find(z=>z.id===g),Pe=Me?ft(Me.groups).filter(z=>!We(b,Me.id,z.id)):[],ot=!!v&&v.row.location==="Application"!=(b==="Application"),Ee=(z,V,U)=>{Me&&(h({location:b,tabId:Me.id,groupId:V,button:tm(z.button,po(D.getState()))}),C(`A copy of ${N(z.button)} was added to ${U}.`))},Fe=(z,V,U,oe,se,Te={},me)=>a.jsx(Ut,{itemType:"leaf",value:z,"aria-description":oe,onClick:se,...Te,children:a.jsx(Vt,{aside:U,actions:me,children:a.jsx("span",{className:e.name,title:oe,children:V})})},z),Q=(z,V,U,oe,se)=>{const Te=te.has(z),me=A[z]??Ri;return a.jsxs(Ut,{itemType:"branch",value:z,children:[a.jsx(Vt,{aside:a.jsx(Rn,{size:"medium",appearance:"ghost",color:"informative",count:U.length,showZero:!0}),children:V}),a.jsx(io,{children:Te&&(U.length===0?at(se):[...U.slice(0,me).map(ze=>nt.cloneElement(oe(ze),{"data-branch-row":z})),...U.length>me?[a.jsx(Ut,{itemType:"leaf",value:`more:${z}`,onClick:()=>{setTimeout(()=>{document.querySelectorAll(`[data-branch-row="${z}"]`)[me]?.focus()}),E(ze=>({...ze,[z]:me+Ri}))},children:a.jsx(Vt,{children:a.jsxs("span",{className:e.muted,children:["Show"," ",Math.min(Ri,U.length-me)," ","more of ",U.length-me]})})},`more:${z}`)]:[]])})]},z)},Le=z=>z?`used ${z}×`:"not used",at=z=>a.jsx(Ut,{itemType:"leaf",value:`none:${z}`,"aria-disabled":!0,children:a.jsx(Vt,{children:a.jsx("span",{className:e.muted,children:z})})}),Gn=z=>{const V=`button:${z.location}:${z.button.id}`,U=oe=>O({row:z,anchor:oe});return Fe(V,N(z.button),a.jsxs("span",{className:e.meta,children:[a.jsx(xe,{size:"medium",appearance:"outline",children:Jt[z.location].label}),z.isNew&&a.jsx(xe,{size:"medium",color:"brand",appearance:"tint",children:"New"})]}),`${z.button.id} · ${Jt[z.location].label}`,()=>ue(z),{draggable:!0,onDragStart:oe=>{oe.dataTransfer.setData(M0,JSON.stringify({button:z.button})),oe.dataTransfer.effectAllowed="copy"},onContextMenu:oe=>{oe.preventDefault(),U(oe.currentTarget)},onKeyDown:oe=>{oe.target===oe.currentTarget&&D0(oe)&&(oe.preventDefault(),U(oe.currentTarget))}},a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(xs,{}),"aria-label":`Actions for ${N(z.button)}`,onClick:oe=>U(oe.currentTarget)}))};return a.jsxs("div",{className:e.root,children:[a.jsxs("div",{className:e.header,children:[a.jsx(cn,{size:"small",className:e.search,placeholder:"Search buttons, commands, rules","aria-label":"Search the solution's elements",contentBefore:a.jsx($c,{}),value:M,onChange:(z,V)=>I(V.value)}),a.jsxs(Je,{children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx(he,{content:"New command or rule",relationship:"label",children:a.jsx(Y,{appearance:"subtle",size:"small",icon:a.jsx(ke,{})})})}),a.jsx(Qe,{children:a.jsxs(et,{children:[a.jsx(fe,{icon:a.jsx(Pn,{}),onClick:P,children:"New command"}),a.jsx(fe,{icon:a.jsx(ho,{}),onClick:()=>K("enable"),children:"New enable rule"}),a.jsx(fe,{icon:a.jsx(ho,{}),onClick:()=>K("display"),children:"New display rule"})]})})]})]}),a.jsx("div",{className:e.body,children:a.jsxs(io,{size:"small","aria-label":"Solution elements",openItems:te,onOpenChange:(z,V)=>{const U=new Set(te);V.open?U.add(String(V.value)):U.delete(String(V.value)),j?H({q:j,open:U}):T(U)},children:[Q("buttons","Buttons",W,Gn,j?"No buttons match.":"None of your buttons yet."),Q("commands","Commands",ne,z=>Fe(`command:${z.id}`,Yo(z.id),a.jsx(X,{size:200,className:e.muted,children:Le(k.byCommand.get(z.id))}),z.id,()=>y(z.id)),j?"No commands match.":"No commands."),Q("rules","Rules",ce,z=>Fe(`rule:${z.kind}:${z.id}`,Yo(z.id),a.jsxs("span",{className:e.meta,children:[a.jsx(X,{size:200,className:e.muted,children:Le((z.kind==="enable"?k.byEnable:k.byDisplay).get(z.id))}),a.jsx(xe,{size:"medium",appearance:"tint",color:z.kind==="enable"?"success":"informative",children:z.kind==="enable"?"Enable":"Display"})]}),z.id,()=>S(z.id,z.kind)),j?"No rules match.":"No rules."),Q("templates","Templates",F,z=>a.jsx(Ut,{itemType:"leaf",value:`template:${z.id}`,"aria-description":z.id,children:a.jsx(Vt,{iconBefore:a.jsx(Nc,{}),children:a.jsx("span",{className:e.name,title:z.id,children:Yo(z.id)})})},`template:${z.id}`),j?"No templates match.":"No templates.")]})}),v&&a.jsxs(Je,{open:!0,onOpenChange:(z,V)=>!V.open&&O(null),positioning:{target:v.anchor,position:"below",align:"start"},children:[a.jsx(Ze,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Qe,{children:a.jsxs(et,{"aria-label":`Actions for ${N(v.row.button)}`,children:[a.jsx(fe,{onClick:()=>ue(v.row),children:"Go to button"}),a.jsx(Mt,{}),a.jsx(fo,{children:"Add a copy to a group of this tab"}),ot&&a.jsx(fo,{children:b==="Application"?"An entity's button can't go on the application ribbon.":"An application ribbon button can't go on an entity's ribbon."}),Pe.length===0?a.jsx(fe,{disabled:!0,children:"No groups on this tab"}):Pe.map(z=>{const V=vt(z.id,t(z.label,c,d,z.source?.titleToken));return a.jsxs(fe,{disabled:ot,onClick:()=>Ee(v.row,z.id,V),children:["Add to ",V]},z.id)})]})})]},`${v.row.location}:${v.row.button.id}`)]})}const L0=pe({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},tabs:{flexShrink:0,padding:`0 ${f.spacingHorizontalXS}`,borderBottom:`1px solid ${f.colorNeutralStroke2}`},body:{flex:1,minHeight:0,overflow:"hidden"}});function z0(){const e=L0(),t=J(o=>o.leftPaneTab),n=J(o=>o.setLeftPaneTab);return a.jsxs("div",{className:e.root,children:[a.jsxs(Ma,{size:"small",className:e.tabs,"aria-label":"Left pane",selectedValue:t,onTabSelect:(o,s)=>n(s.value),children:[a.jsx(Gt,{value:"structure",icon:a.jsx(dc,{}),children:"Structure"}),a.jsx(Gt,{value:"solution",icon:a.jsx(uc,{}),children:"Solution"})]}),a.jsx("div",{className:e.body,role:"tabpanel","aria-label":t==="structure"?"Structure":"Solution",children:t==="structure"?a.jsx(O0,{}):a.jsx(B0,{})})]})}function br(){return window.dataverseAPI}async function P0(){const e=br();re.getState().logInfo("dataverse","Loading solutions...");const s=((await e.queryData("solutions?$select=solutionid,uniquename,friendlyname,version,ismanaged,versionnumber,isvisible&$expand=publisherid($select=publisherid,uniquename,friendlyname,customizationprefix,customizationoptionvalueprefix)&$filter=isvisible eq true and uniquename ne 'Active' and uniquename ne 'Default'&$orderby=friendlyname asc")).value??[]).map(l=>{const r=l.publisherid??{};return{id:String(l.solutionid??""),uniqueName:String(l.uniquename??""),friendlyName:String(l.friendlyname??""),version:String(l.version??""),isManaged:!!l.ismanaged,publisherId:r.publisherid??"",publisherUniqueName:r.uniquename??"",publisherName:r.friendlyname??"",publisherPrefix:r.customizationprefix??"",publisherOptionValuePrefix:typeof r.customizationoptionvalueprefix=="number"?r.customizationoptionvalueprefix:void 0,versionNumber:l.versionnumber}});re.getState().logInfo("dataverse",`Loaded ${s.length} solution(s).`);const i=s.filter(l=>!l.isManaged).slice(0,5);for(const l of i)re.getState().logInfo("dataverse",` • "${l.friendlyName||l.uniqueName}" → prefix="${l.publisherPrefix||"(empty)"}" (publisher: ${l.publisherName||l.publisherUniqueName||"(empty)"})`);return s}async function F0(e){if(!e)return[];const t=br();re.getState().logInfo("dataverse",`Loading solution entity components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 1`,i=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return re.getState().logInfo("dataverse",`Solution contains ${i.length} entity component(s).`),i}async function _0(e){if(!e)return[];const t=br();re.getState().logInfo("dataverse",`Loading solution ribbon components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 50`,i=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return re.getState().logInfo("dataverse",`Solution contains ${i.length} ribbon-customization component(s).`),i}function q0(){return window.dataverseAPI}async function H0(e){if(e.length===0)return[];const t=q0(),n=re.getState();n.logInfo("dataverse",`Loading metadata for ${e.length} solution entit${e.length===1?"y":"ies"}...`);const o="MetadataId,LogicalName,SchemaName,DisplayName,IsCustomEntity,IsIntersect",s=d=>({metadataId:String(d.MetadataId??""),logicalName:String(d.LogicalName??""),schemaName:d.SchemaName?String(d.SchemaName):void 0,displayName:d.DisplayName?.UserLocalizedLabel?.Label??String(d.LogicalName??""),isCustomEntity:!!d.IsCustomEntity,isManaged:!1,isIntersect:!!d.IsIntersect}),i=async d=>{try{return s(await t.queryData(`EntityDefinitions(${d})?$select=${o}`))}catch(u){return n.logWarn("dataverse",`Could not resolve entity for component ${d}: ${u instanceof Error?u.message:String(u)}`),null}},l=[];for(let d=0;d<e.length;d+=40)l.push(e.slice(d,d+40));const c=(await Promise.all(l.map(async d=>{try{const m=((await t.queryData(`EntityDefinitions?$select=${o}&$filter=${d.map(h=>`MetadataId eq ${h}`).join(" or ")}`)).value??[]).map(s),p=new Set(m.map(h=>h.metadataId.toLowerCase()));for(const h of d)p.has(h.toLowerCase())||n.logWarn("dataverse",`Could not resolve entity for component ${h}: not found.`);return m}catch(u){n.logWarn("dataverse",`Couldn't read ${d.length} entities in one request (${u instanceof Error?u.message:String(u)}); reading them one at a time.`);const m=[];for(const p of d)m.push(await i(p));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} entities.`),c}async function Nm(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const o=Ix(n),s=Object.entries(o).find(([i])=>i.toLowerCase().endsWith("ribbonxml.xml"));if(!s){const i=Object.keys(o);throw new Error(`Dataverse returned a ribbon package without RibbonXml.xml (it has ${i.length>0?i.join(", "):"no files"}).`)}return Ls(s[1])}const km=30,W0=km*6e4,Am=(e,t)=>`cbs:lastPublish:${e.replace(/\/+$/,"")}:${t}`;function Om(e,t){try{const n=sessionStorage.getItem(e);if(!n)return null;const o=JSON.parse(n);if(typeof o.at!="number"||!o.publishedAt||typeof o.publishedAt!="object")return null;const s=Object.fromEntries(Object.entries(o.publishedAt).filter(i=>typeof i[1]=="number"&&t-i[1]<W0));return{at:o.at,publishedAt:s}}catch{return null}}function iI(e,t,n,o=Date.now()){const s=Am(e,t),i={...Om(s,o)?.publishedAt??{}};for(const l of n){const r=/^customActions:ca:(.+)$/.exec(l)?.[1];r&&(i[r]=o)}try{sessionStorage.setItem(s,JSON.stringify({at:o,publishedAt:i}))}catch{}}function G0(e,t,n=Date.now()){return Om(Am(e,t),n)}const Kl=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]),Ii=new Set(["Tab","Group"]),Yl=/^(.+)\._children$/;function Jl(e){return e?Array.from(e.children):[]}function Co(e,t){return t?e.split("{!EntityLogicalName}").join(t):e}function U0(e,t){const n=new Map,o=(s,i)=>n.set(Co(s,t),i);for(const s of e)for(const i of s.tabs){o(`${i.id}.Groups`,i.id);for(const l of i.groups){o(`${l.id}.Controls`,i.id);for(const r of je(l))for(const c of r.menu?.sections??[])o(c.controlsId,i.id)}}return n}function V0(e,t){const n=new Set,o=s=>n.add(Co(s,t));for(const s of e)for(const i of s.tabs){o(i.id);for(const l of i.groups){o(l.id);for(const r of je(l))o(r.id)}}return n}function Zl(e){return[e,...Array.from(e.getElementsByTagName("*"))].flatMap(t=>t.getAttribute("Id")??[])}function X0(e,t,n,o={}){const{locLabels:s=[],languageCode:i=1033}=o,l=[...t],r=$=>Co($,n),c=V0(l,n),d=U0(l,n),u=[...Cs(e).map($=>$.location),...o.otherHides??[]].map(r),m=new Set(u),p=new Set,h=[...e.customActions.values()].map($=>new DOMParser().parseFromString($,"application/xml").documentElement);for(const $ of h)if($.tagName==="CustomAction")for(const T of Array.from($.getElementsByTagName("*")))m.has(r(T.getAttribute("Id")??""))&&Zl(T).forEach(v=>p.add(r(v)));const b=$=>p.has($)||u.some(T=>$===T||$.startsWith(`${T}.`)),g=new Set(["Mscrm.Tabs",`Mscrm.SubGrid.${n}.ContextualTabs`]),x=($,T)=>{const v=d.get(T);return v&&Io(v)?{reason:"hidden-tab",why:`It is on the tab ${v}, which Unified Interface doesn't show; the ribbon doesn't return what is added there.`}:v||g.has(T)?{reason:"not-returned",why:$==="Tab"?`The ribbon doesn't return this tab at ${T}, so Command Bar Studio can't place it (it may still show in Unified Interface).`:`${T} is on the canvas, but the ribbon doesn't return this ${$.toLowerCase()} there (for example a control added to a new group in a separate CustomAction).`}:{reason:"missing-location",why:/^(Mscrm|Microsoft)\./.test(T)?`${T} isn't in this entity's ribbon as loaded: it is not shown — possibly hidden by another solution — or it was removed.`:`${T} isn't in this entity's ribbon as loaded: the group, tab or menu was removed or renamed, the Location is misspelled, or it is hidden by another solution.`}},y=$=>{const T=$.getAttribute("LabelText")??$.getAttribute("Title")??$.getAttribute("Alt")??"";return Ve(T,s,i)||($.getAttribute("Id")??"")},S=[],C=($,T,v)=>{const O=$.getAttribute("Id")??"",A=Yl.exec(T)?.[1]??T;if(!O||c.has(r(O))||b(r(O))||b(r(A)))return;const E=Ii.has($.tagName);S.push({orphan:{id:O,element:$.tagName,label:y($),location:T,customActionId:v,...x($.tagName,r(A)),deleteControlIds:E?[]:[O],deleteContainerIds:E?[O]:[]},parent:A,inside:new Set(Zl($))})};for(const $ of h){if($.tagName!=="CustomAction")continue;const T=$.getAttribute("Location")??"";if(!Yl.test(T)||/\.Scaling\._children$/.test(T))continue;const v=Jl(Jl($).find(E=>E.tagName==="CommandUIDefinition"))[0],O=v?.getAttribute("Id");if(!v||!O||!(Ii.has(v.tagName)||Kl.has(v.tagName)))continue;const A=$.getAttribute("Id")??"";if(!c.has(r(O))){C(v,T,A);continue}for(const E of Array.from(v.getElementsByTagName("*"))){const w=E.parentElement;w?.tagName!=="Controls"&&w?.tagName!=="Groups"||!Ii.has(E.tagName)&&!Kl.has(E.tagName)||C(E,`${w.getAttribute("Id")??""}._children`,A)}}const R=$=>S.find(T=>T!==$&&T.inside.has($.parent)&&!$.inside.has(T.parent)),M=$=>{const T=new Set([$]);let v=$;for(let O=R(v);O&&!T.has(O);O=R(v))T.add(O),v=O;return v},I=S.filter($=>!R($));for(const $ of S){const T=M($);if(T===$||!I.includes(T))continue;const v=(O,A)=>A.forEach(E=>O.includes(E)||O.push(E));v(T.orphan.deleteControlIds,$.orphan.deleteControlIds),v(T.orphan.deleteContainerIds,$.orphan.deleteContainerIds)}return I.map($=>$.orphan)}function K0(e,t,n=Date.now()){if(!t)return e;const o=km*6e4,s=i=>Math.max(0,Math.floor((n-i)/6e4));return e.map(i=>{const l=t.publishedAt[i.customActionId];if(l!==void 0&&n-l<o){const c=s(l);return{...i,recentPublish:{minutesAgo:c,published:!0},why:`Published from here ${c} min before this entity was loaded: the ribbon may not have caught up yet (it can lag 10 minutes or more). Reload the entity later before deleting it. ${i.why}`}}if(n-t.at>=o)return i;const r=s(t.at);return{...i,recentPublish:{minutesAgo:r,published:!1},why:`The entity was published from here ${r} min before this entity was loaded, and the ribbon may not have caught up yet. ${i.why}`}})}const Mm=window.dataverseAPI;function qo(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 Em(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 Dm(e){return Em(e)[0]}function Y0(e,t,n={}){const o={HomepageGrid:[],SubGrid:[],Form:[]};for(const i of e)i.id.startsWith("Mscrm.Form.")?o.Form.push(i):i.id.startsWith("Mscrm.SubGrid.")?o.SubGrid.push(i):i.id.startsWith("Mscrm.HomepageGrid.")?o.HomepageGrid.push(i):o[Dm(i)??"HomepageGrid"].push(i);const s=i=>{const l=Object.fromEntries(o[i].filter(r=>n[r.id]).map(r=>[r.id,n[r.id]]));return{location:i,entityLogicalName:t,tabs:o[i],...Object.keys(l).length>0?{scalingByTab:l}:{}}};return{HomepageGrid:s("HomepageGrid"),SubGrid:s("SubGrid"),Form:s("Form")}}const J0="Microsoft.Dynamics.CRM.RibbonLocationFilters'All'";function Z0(e){return`RetrieveEntityRibbon(EntityName=@e,RibbonLocationFilter=@f)?@e='${encodeURIComponent(e.replace(/'/g,"''"))}'&@f=${J0}`}async function Q0(e,t=[]){re.getState().logInfo("dataverse",`RetrieveEntityRibbon(${e}, All)`);const n=await Mm.queryData(Z0(e));if(typeof n?.CompressedEntityXml!="string"||!n.CompressedEntityXml)throw new Error(`Dataverse returned no ribbon for ${e} (RetrieveEntityRibbon had no CompressedEntityXml).`);const o=await Nm(n.CompressedEntityXml),s=Ms(o,"HomepageGrid",e,t),i=Y0(s.ribbon.tabs,e,s.ribbon.scalingByTab);if(s.ribbon.templateLayouts)for(const l of Object.values(i))l.templateLayouts=s.ribbon.templateLayouts;if(s.ribbon.templateAliases)for(const l of Object.values(i))l.templateAliases=s.ribbon.templateAliases;return re.getState().logInfo("dataverse",`RetrieveEntityRibbon succeeded for ${e} (Form=${i.Form.tabs.length}, HomepageGrid=${i.HomepageGrid.tabs.length}, SubGrid=${i.SubGrid.tabs.length})`),{ribbons:i,commands:s.commands,displayRules:s.displayRules,enableRules:s.enableRules,locLabels:s.locLabels}}const Bm=5*6e4;let ga=null,ba=0,Lm=0;function eR(e={}){ga=null,ba++,e.afterPublish&&(Lm=Date.now()+Bm)}async function tR(e=[]){const t=re.getState(),n=ae.getState().connectionUrl,o=ga;let s;if(o&&o.environment===n&&Date.now()-o.at<Bm)s=o.xml,t.logInfo("dataverse","RetrieveApplicationRibbon (reused from this session)");else{const i=ba;t.logInfo("dataverse","RetrieveApplicationRibbon()");const r=(await Mm.execute({operationName:"RetrieveApplicationRibbon",operationType:"function"}))?.CompressedApplicationRibbonXml;if(typeof r!="string"||!r)throw new Error("Dataverse returned no application ribbon (RetrieveApplicationRibbon had no CompressedApplicationRibbonXml).");s=await Nm(r),i===ba&&Date.now()>=Lm&&(ga={environment:n,at:Date.now(),xml:s}),t.logInfo("dataverse","RetrieveApplicationRibbon succeeded")}return Ms(s,"Application","{!EntityLogicalName}",e)}function ji(e,t,n,o=[]){const s={added:[],replaced:[]};if(n.commandDefinitions.size+n.enableRules.size+n.displayRules.size===0)return s;const i=Yy(n),l=(h,b)=>JSON.stringify(h,Ql)===JSON.stringify(b,Ql),r=(h,b)=>{const g=new Map(b.map(x=>[x.id,x]));for(let x=0;x<h.length;x++){const y=g.get(h[x].id);y&&!l(y,h[x])&&(h[x]=y,s.replaced.push(y.id))}};r(t.commands,i.commands),r(t.enableRules,i.enableRules),r(t.displayRules,i.displayRules);const c=new Set(t.commands.map(h=>h.id)),d=new Set(o.filter(h=>!c.has(h)&&n.commandDefinitions.has(h)));for(const h of e)for(const b of h.tabs)for(const g of b.groups)for(const x of je(g))x.commandId&&!c.has(x.commandId)&&n.commandDefinitions.has(x.commandId)&&d.add(x.commandId);const u=i.commands.filter(h=>d.has(h.id));t.commands.push(...u),s.added.push(...u.map(h=>h.id));const m=new Set(t.enableRules.map(h=>h.id)),p=new Set(t.displayRules.map(h=>h.id));for(const h of t.commands){for(const b of h.enableRules){const g=i.enableRules.find(x=>x.id===b);g&&!m.has(b)&&(t.enableRules.push(g),m.add(b),s.added.push(b))}for(const b of h.displayRules){const g=i.displayRules.find(x=>x.id===b);g&&!p.has(b)&&(t.displayRules.push(g),p.add(b),s.added.push(b))}}return s}function Ql(e,t){if(typeof t!="string"||!t.trimStart().startsWith("<"))return t;try{return En(t)}catch{return t}}function nR(e,t){const n=(o,s)=>new Map([...o].filter(([i])=>!s?.has(i)));return{...e,commandDefinitions:n(e.commandDefinitions,t?.commandDefinitions),enableRules:n(e.enableRules,t?.enableRules),displayRules:n(e.displayRules,t?.displayRules)}}function oR(e,t,n){if(n!==1033)for(const o of e)for(const s of o.tabs)for(const i of s.groups)for(const l of je(i)){for(const d of l.menu?.sections??[]){const u=d.attributes?.Title;u?.startsWith("$LocLabels:")&&(d.title=Ve(u,t,n))}const r=l.source;if(!r)continue;const c=[[r.labelToken,"label"],[r.tooltipTitleToken,"tooltipTitle"],[r.tooltipBodyToken,"tooltipBody"]];for(const[d,u]of c)d?.startsWith("$LocLabels:")&&(l[u]=Ve(d,t,n))}}function ec(e,t,n,o){const s=new Set(Object.values(e).flatMap(p=>p?.tabs.map(h=>h.id)??[])),i=new Set(Cs(t).map(p=>p.location)),l=n?`Mscrm.SubGrid.${n}.ContextualTabs._children`:null,r=[];for(const p of cd(t.customActions).values()){const h=new DOMParser().parseFromString(p,"application/xml").documentElement;if(h.tagName!=="CustomAction")continue;const b=Co(h.getAttribute("Location")??"",n??void 0);if(b!=="Mscrm.Tabs._children"&&b!==l)continue;const g=Array.from(h.getElementsByTagName("CommandUIDefinition")[0]?.children??[])[0],x=g?.tagName==="Tab"?g.getAttribute("Id"):null;!x||s.has(Co(x,n??void 0))||r.push({xml:new XMLSerializer().serializeToString(g),subGrid:b===l})}if(r.length===0)return[];const c=`<RibbonDefinitions><RibbonDefinition><UI><Ribbon><Tabs>${r.map(p=>p.xml).join("")}</Tabs></Ribbon></UI><RuleDefinitions><TabDisplayRules>${[...t.tabDisplayRules.values()].join("")}</TabDisplayRules></RuleDefinitions></RibbonDefinition></RibbonDefinitions>`,d=Ms(c,n?"HomepageGrid":"Application",n??"{!EntityLogicalName}",o);d.ribbon.tabs=d.ribbon.tabs.filter(p=>!i.has(p.id));for(const p of d.ribbon.tabs){p.groups=p.groups.filter(h=>!i.has(h.id));for(const h of p.groups){h.buttons=h.buttons.filter(b=>!i.has(b.id));for(const b of je(h))i.has(b.id)&&bd(h,b.id)}}const u=new Set(r.filter(p=>p.subGrid).map(p=>new DOMParser().parseFromString(p.xml,"application/xml").documentElement.getAttribute("Id"))),m=p=>n?u.has(p.id)?"SubGrid":Dm(p)??"HomepageGrid":"Application";for(const p of d.ribbon.tabs){const h=n&&!u.has(p.id)?Em(p).slice(1):[];h.length>0&&re.getState().logWarn("ribbon",`Tab ${p.id} shows on the ${m(p)} and on the ${h.join(" and ")} (its display rules); Command Bar Studio lists it under ${m(p)} only.`);const b=e[m(p)];if(!b)continue;b.tabs.push(p),b.tabs.sort((x,y)=>x.sequence-y.sequence);const g=d.ribbon.scalingByTab?.[p.id];g&&(b.scalingByTab={...b.scalingByTab??{},[p.id]:g})}return d.ribbon.tabs.map(p=>p.id)}function $i(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);re.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 sR(e,t){const n=re.getState();t?.("Reading your customizations…");const o=[],s=g=>x=>(o.push(`${g}: ${x instanceof Error?x.message:String(x)}`),null),[i,l,r]=await Promise.all([Xi(e).catch(s(`the ${e} entity's customizations`)),Xi(null).catch(s("the application ribbon's customizations")),gS().catch(g=>{n.logWarn("dataverse",`${g instanceof Error?g.message:String(g)} Labels are shown in English; publishing reads it again and stops if it still can't.`)})]),c=i?Ki(i):[],d=l?Ki(l):[];t?.("Reading the entity's ribbon and the application ribbon…");const[u,m]=await Promise.all([Q0(e,[...c,...d]),tR(d)]);if(i){const g=ec(u.ribbons,i,e,[...c,...d]);g.length>0&&n.logInfo("ribbon",`Loaded tab(s) ${g.join(", ")} from the entity's unmanaged layer.`);const x=ns(i);for(const y of Object.values(u.ribbons))Ur(y,x);$i("RetrieveEntityRibbon",ji(Object.values(u.ribbons),u,i,[Ye]))}l&&(ec({Application:m.ribbon},l,null,d),Ur(m.ribbon,ns(l)),$i("RetrieveApplicationRibbon",ji([m.ribbon],m,l)),$i("RetrieveEntityRibbon",ji(Object.values(u.ribbons),u,nR(l,i))));const p=qo([...u.locLabels,...m.locLabels]),h=r??1033;t?.("Matching labels and ownership…"),oR([...Object.values(u.ribbons),m.ribbon],p,h);const b=i?X0(i,Object.values(u.ribbons),e,{locLabels:p,languageCode:h,otherHides:l?Cs(l).map(g=>g.location):[]}):[];return b.length>0&&n.logWarn("ribbon",`${b.length} element(s) of the entity's unmanaged customizations aren't on the canvas — the ribbon doesn't return them (see "Orphaned customizations"): ${b.map(g=>`${g.id} at ${g.location}`).join(", ")}.`),{ribbons:{HomepageGrid:u.ribbons.HomepageGrid,SubGrid:u.ribbons.SubGrid,Form:u.ribbons.Form,Application:m.ribbon},commands:qo([...u.commands,...m.commands]),displayRules:qo([...u.displayRules,...m.displayRules]),enableRules:qo([...u.enableRules,...m.enableRules]),locLabels:p,layers:{entity:i?ls(i):null,application:l?ls(l):null},baseLanguageCode:r,orphans:b,...o.length>0?{layerReadError:o.join("; ")}:{}}}const iR="System",ys="{!EntityLogicalName}",Zo=new Map;function aR(e){if(!e||!e.includes("<"))return[];try{const t=new DOMParser().parseFromString(e,"application/xml");if(t.querySelector("parsererror"))return[];const n=t.getElementsByTagName("CommandUIDefinition")[0];if(!n)return[];const o=[];for(const s of Array.from(n.getElementsByTagName("*"))){const i=s.getAttribute("Id");i&&o.push(i)}return o}catch{return[]}}async function rR(e){const t=e.filter(n=>!Zo.has(n));for(let n=0;n<t.length;n+=40){const o=t.slice(n,n+40),s=await Nn(`solutions?$select=solutionid,uniquename&$expand=publisherid($select=friendlyname)&$filter=${o.map(i=>`solutionid eq ${i}`).join(" or ")}`);for(const i of o)Zo.set(i,null);for(const i of s){const l=i.publisherid;Zo.set(String(i.solutionid),{uniqueName:String(i.uniquename??""),publisherName:l?.friendlyname})}}}async function lR(e){const t=re.getState(),n=new Map;if(!e||e===ys)return n;try{const o=e.replace(/'/g,"''"),s=await Nn(`ribbondiffs?$select=rdx,solutionid&$filter=(entity eq '${o}' or entity eq null) and ismanaged eq true and difftype le 1&$orderby=solutionid`),i=new Map;for(const l of s){const r=String(l.solutionid??"");if(r)for(const c of aR(String(l.rdx??""))){const d=c.split(ys).join(e);for(const u of d===c?[c]:[c,d])i.has(u)||i.set(u,new Set),i.get(u).add(r)}}await rR([...new Set([...i.values()].flatMap(l=>[...l]))]);for(const[l,r]of i){const c=[...r].map(d=>Zo.get(d)).find(d=>d&&d.uniqueName!==iR);c&&n.set(l,{origin:"managed",solutionName:c.uniqueName,publisherName:c.publisherName})}t.logInfo("provenance",`${s.length} managed CustomAction(s) for ${e}: ${n.size} control(s) from managed solutions.`)}catch(o){t.logWarn("provenance",`Couldn't read which managed solutions add ${e}'s controls (${o instanceof Error?o.message:String(o)}); their owners aren't shown. This is non-fatal.`)}return n}async function cR(e){if(!e||e===ys)return[];try{const t=e.replace(/'/g,"''"),n=await Nn(`ribbondiffs?$select=rdx&$filter=(entity eq '${t}' or entity eq null) and ismanaged eq true and difftype eq 3&$orderby=solutionid`),o=[],s=new DOMParser;for(const i of n){const l=s.parseFromString(String(i.rdx??""),"application/xml");if(!l.querySelector("parsererror"))for(const r of Array.from(l.getElementsByTagName("LocLabel"))){const c=r.getAttribute("Id");if(!c)continue;const d=Array.from(r.getElementsByTagName("Title")).map(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(ys).join(e);u!==c&&o.push({id:u,titles:d})}}return re.getState().logInfo("provenance",`${o.length} label text(s) from managed solutions for ${e}.`),o}catch(t){return re.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 dR(){return window.dataverseAPI}async function uR(){const e=dR();re.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 re.getState().logWarn("dataverse","WhoAmI returned no user id."),{id:"",name:""};const s=(await e.retrieve("systemuser",n,["fullname"])).fullname?.trim(),i={id:n,name:s&&s.length>0?s:"Current User"};return re.getState().logInfo("dataverse",`Current user resolved: ${i.name}.`),i}function mR(){B.useEffect(()=>{const e=Px();return e>0&&re.getState().logInfo("ribbon",`Discarded ${e} unsaved-changes draft(s) older than ${ou} days, or saved by an earlier version of Command Bar Studio (they can't be restored correctly).`),_x()},[])}function pR(){const e=Ie(i=>i.pending),t=Ie(i=>i.pendingBaselineChanged),n=Ie(i=>i.restoreError),o=Ie(i=>i.restoreDraft),s=Ie(i=>i.discardDraft);return e?a.jsxs(hn,{open:!0,onOpenChange:()=>{},modalType:"alert",size:"small",title:"Unpublished changes",actions:a.jsxs(a.Fragment,{children:[a.jsx(sr,{onClick:s,children:"Discard changes"}),a.jsx(Y,{appearance:"primary",disabled:!!n,onClick:()=>o(),"data-autofocus":!0,children:"Restore changes"})]}),children:[a.jsxs(X,{block:!0,children:["You have unpublished changes to this entity from a previous session (saved"," ",new Date(e.savedAt).toLocaleString(),"). Restore them on top of the ribbon as it is now, or discard them?"]}),t&&a.jsx(Dt,{intent:"warning",layout:"multiline",style:{marginTop:"12px"},children:a.jsx(Bt,{children:"The entity's ribbon has changed since then (published from another session, or by someone else): review the publish plan before publishing."})}),n&&a.jsx(Dt,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:a.jsxs(Bt,{children:["These changes couldn't be restored (",n,"). Discard them to continue; the details are in the runtime log."]})})]}):null}function fR(){const e=Ie(d=>d.pendingSwitch),t=Ie(d=>d.pending!==null),n=Ie(d=>d.saveFailed),o=Ie(d=>d.resolveSwitch),s=ae(d=>d.activeEntity),i=ae(d=>d.activeSolution);if(!e)return null;const l=s?.displayName||s?.logicalName||"this entity",r=e.kind==="entity"?`entity ${e.entity.displayName||e.entity.logicalName}`:`solution ${e.solution.friendlyName||e.solution.uniqueName}`,c=i?.friendlyName||i?.uniqueName||"this solution";return a.jsxs(hn,{open:!0,onOpenChange:d=>!d&&o("cancel"),modalType:"alert",size:"small",title:"Unpublished changes",actions:a.jsxs(a.Fragment,{children:[a.jsx(Y,{appearance:"secondary",onClick:()=>o("cancel"),children:"Cancel"}),a.jsxs(sr,{onClick:()=>o("discard"),children:["Discard",t?" and switch":" changes"]}),!t&&a.jsx(Y,{appearance:"primary",disabled:n,onClick:()=>o("keep"),children:"Keep as draft"})]}),children:[a.jsxs(X,{block:!0,children:[l," has changes that aren't published. Switch to ",r,"?"]}),a.jsx(X,{block:!0,style:{marginTop:"8px"},children:t?a.jsxs(a.Fragment,{children:["Changes made since opening ",l," aren't saved: the unsaved changes of your previous session are kept until you restore or discard them."]}):a.jsxs(a.Fragment,{children:[a.jsx("strong",{children:"Keep as draft"})," saves them on this computer: they are offered again when you open ",l," in ",c,". ",a.jsx("strong",{children:"Discard changes"})," ","deletes them."]})}),n&&!t&&a.jsx(Dt,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:a.jsx(Bt,{children:"The changes can't be saved as a draft: the browser storage is full. Publish them first, or discard them to switch."})})]})}function hR(){const e=ae(v=>v.setSolutions),t=ae(v=>v.setEntities),n=ae(v=>v.setCurrentUser),o=ae(v=>v.setSolutionEntityIds),s=ae(v=>v.setSolutionRibbonComponentIds),i=ae(v=>v.activeSolution),l=ae(v=>v.activeEntity),r=ae(v=>v.connectionVersion),c=D(v=>v.loadWorkspace),d=Z(v=>v.setTabId),u=J(v=>v.themeMode),m=re(v=>v.logInfo),p=re(v=>v.logWarn),h=re(v=>v.logError);mR(),Sw();const[b,g]=B.useState("idle"),[x,y]=B.useState(null),[S,C]=B.useState(null),[R,M]=B.useState(null),[I,$]=B.useState(0);B.useEffect(()=>{m("runtime","Loading solutions and current user...");let v=!1;return P0().then(O=>{v||(e(O),m("runtime",`Loaded ${O.length} solution(s). Pick one to load its entities.`))}).catch(O=>{v||h("runtime",`Failed to load solutions: ${O instanceof Error?O.message:String(O)}`)}),uR().then(O=>{v||!O.id||(n(O.id,O.name),m("runtime",`Current user: ${O.name}.`))}).catch(O=>{p("runtime",`Failed to resolve current user: ${O instanceof Error?O.message:String(O)}`)}),()=>{v=!0}},[e,n,m,p,h,r]),B.useEffect(()=>{if(!i){o(null),s(null),t([]);return}let v=!1;return(async()=>{try{const[O,A]=await Promise.all([F0(i.id),_0(i.id)]);if(v)return;if(o(O),s(A),O.length===0){t([]);return}const E=await H0(O);if(v)return;t(E)}catch(O){if(v)return;h("runtime",`Failed to load solution entities: ${O instanceof Error?O.message:String(O)}`),o([]),s([]),t([])}})(),()=>{v=!0}},[i,t,o,s,h]),B.useEffect(()=>{if(Ie.getState().beginLoad(),!l?.logicalName){g("idle"),y(null),M(null);return}let v=!1;const O=du(l.logicalName);return g("loading"),y(null),M(null),C(null),m("ribbon",`Loading ribbon workspace for ${l.logicalName}...`),aa.getState().setManaged([]),cR(l.logicalName).then(A=>{v||aa.getState().setManaged(A)}),Promise.all([sR(l.logicalName,A=>{v||C(A)}),lR(l.logicalName).catch(()=>new Map)]).then(([A,E])=>{if(v)return;const w=new Set([...A.layers?.entity?.controlIds??[],...A.layers?.application?.controlIds??[]]);My(A.ribbons,E,w);const k=[],N=new Set;for(const le of Object.values(A.ribbons))for(const ce of le.tabs)for(const F of ce.groups)for(const L of je(F))L.origin==="managed"&&!N.has(L.id)&&(N.add(L.id),k.push({elementId:L.id,elementKind:"button",solutions:[{solutionId:"",solutionName:L.solutionName??"Managed Solution",publisher:L.publisherName??"",managed:!0,wins:!0,importedOn:void 0}]}));D.getState().setConflicts(k),c({ribbons:A.ribbons,commands:A.commands,displayRules:A.displayRules,enableRules:A.enableRules,locLabels:A.locLabels,layers:A.layers,baseLanguageCode:A.baseLanguageCode,baseLanguageUnknown:A.baseLanguageCode===void 0,labelsUnknown:A.layerReadError!==void 0,orphans:{entity:K0(A.orphans??[],G0(ae.getState().connectionUrl,l.logicalName))}});const{location:j,tabId:_}=Z.getState(),W=A.ribbons[j]?.tabs??[];if(!(W.some(le=>le.id===_)&&!Io(_))){const le=xo(W);le&&d(le)}Ie.getState().workspaceLoaded(O),M(A.layerReadError??null),A.layerReadError&&p("ribbon",`Unmanaged layer not read: ${A.layerReadError}`),g("idle"),m("ribbon",`Ribbon workspace loaded for ${l.logicalName}.`)}).catch(A=>{if(v)return;const E=A instanceof Error?A.message:"Failed to load ribbon";g("error"),y(E),h("ribbon",`Ribbon load failed for ${l.logicalName}: ${E}`)}),()=>{v=!0}},[l?.logicalName,c,I,d,m,p,h]);function T(){eR(),$(v=>v+1)}return a.jsxs(sb,{theme:u==="dark"?ib:ab,children:[a.jsx(oS,{leftPane:a.jsx(z0,{}),rightPane:a.jsx(VC,{}),bottomPanel:a.jsx($0,{}),children:a.jsx(oC,{isLoadingRibbon:b==="loading",loadingTable:l?.displayName??l?.logicalName,loadingStep:S,ribbonLoadError:x,layerReadError:R,onRetryRibbonLoad:T,emptyState:i?l?void 0:"noTable":"noSolution"})}),a.jsx(pR,{}),a.jsx(fR,{})]})}const gR=5e3,tc=3e4,zm="1.2.7";function nc(e,t,n){let o;return Promise.race([e,new Promise((s,i)=>{o=setTimeout(()=>i(new Error(n)),t)})]).finally(()=>clearTimeout(o))}async function bR(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 ${zm} or later.`);const s=[];let i="light";try{const r=t.utils?.getCurrentTheme;if(typeof r!="function")throw new Error("the host has no theme API");i=await nc(r(),gR,"the host didn't answer")==="dark"?"dark":"light"}catch(r){s.push(`Couldn't read the host theme (${Fm(r)}); using the light theme.`)}const l=await nc(o(),tc,`Power Platform ToolBox didn't return the active connection within ${tc/1e3} seconds. Make sure a connection is active and signed in, then open Command Bar Studio again.`);if(!l)throw new Error("No active connection: connect to an environment in Power Platform ToolBox, then open Command Bar Studio again.");return{connection:l,theme:i,warnings:s}}function Pm(e,t,n="Command Bar Studio couldn't start"){const o=e.ownerDocument,s=(c,d)=>{const u=o.createElement(c);return d&&(u.textContent=d),u},i=s("div");i.setAttribute("role","alert"),i.style.cssText="font-family: 'Segoe UI', system-ui, sans-serif; padding: 24px; max-width: 720px; line-height: 1.5;",i.append(s("h1",n));const l=s("p",Fm(t));l.style.fontWeight="600",i.append(l);const r=s("ul");for(const c of["Close the Command Bar Studio tab and open the tool again.",`Use Power Platform ToolBox ${zm} or later (desktop app or VS Code extension).`,"Make sure a connection is active and signed in.","If it keeps happening, report it at https://github.com/mohsinonxrm/pptb-mxrm-commandbar-studio/issues with this message."])r.append(s("li",c));i.append(r),e.replaceChildren(i)}function Fm(e){return e instanceof Error?e.message:String(e)}class yR extends B.Component{state={error:void 0};box=B.createRef();static getDerivedStateFromError(t){return{error:t??new Error("Unknown error")}}componentDidCatch(t,n){console.error("[CBS RootErrorBoundary]",t,n),re.getState().logError("app",t instanceof Error?t.message:String(t))}componentDidMount(){this.componentDidUpdate()}componentDidUpdate(){this.state.error!==void 0&&this.box.current&&Pm(this.box.current,this.state.error,"Command Bar Studio stopped working")}render(){return this.state.error===void 0?this.props.children:a.jsx("div",{ref:this.box})}}function xR(e){return e.replace(/([A-Z])/g,(t,n,o)=>(o>0?"_":"")+t.toLowerCase())}function vR(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 _m(e,t="regular"){return`${xR(e)}${t==="filled"?".filled":""}.svg`}function SR(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/${_m(t,n)}`}const wR=11,CR=2*6e4,oc={save:TS,publish:Pu},qm=new Set;function RR(){qm.clear()}async function aI(e,t,n,o,s={}){const i=s.save??oc.save,l=s.publish??oc.publish,r=s.published??qm,c=SR(n,e,t),d=await o(e,20,t);if(!d)throw new Error(`Could not convert the Fluent icon "${e}" to SVG`);const u=await i(c,vR(d),wR,{displayName:`${_m(e,t)} (CBS icon)`,keepExisting:!0,guard:s.guard,publish:!1}),m={name:c,id:u.id,created:u.created};if(!r.has(u.id))try{await Eu(`Publishing icon web resource ${c}`,()=>l(u.id,s.guard),{timeoutMs:CR,...s.busy}),r.add(u.id)}catch(p){m.publishError=p instanceof Error?p.message:String(p)}return m}const IR=["commandEditorOpen","ruleEditorOpen","iconPickerOpen","newGroupOpen","importXmlOpen","webResourceBrowserOpen","newTabOpen"];function jR(e){if(!e)return"none";const t=ae.getState(),n=re.getState();if(es(e)===es({id:t.connectionId,url:t.connectionUrl}))return e.name===t.connectionName&&e.environment===t.environment?"none":(t.setConnection(e.url,e.name,e.environment,e.id),n.logInfo("startup",`Connection details updated: ${e.name} (${e.environment}).`),"details");const s=`${t.connectionName||t.connectionUrl} (${t.environment})`,i=`${e.name} (${e.environment})`,{hadChanges:l,kept:r}=Ie.getState().releaseForConnectionChange();D.getState().resetWorkspace(),Z.getState().clearSelection(),we.getState().reset(),RR(),ww(),ma.clear(),t.switchConnection(e,{draftKept:l&&r,draftLost:l&&!r});try{J.setState({...Object.fromEntries(IR.map(c=>[c,!1])),editorStack:[]})}catch(c){n.logWarn("startup",`Couldn't close the open panels after the connection change: ${c instanceof Error?c.message:String(c)}`)}return n.logWarn("startup",`The tool's connection changed from ${s} to ${i}. The loaded solution and entity were closed.`),l&&r&&n.logInfo("startup",`The unpublished changes were kept as a draft for ${s}.`),l&&!r&&n.logError("startup",`The unpublished changes on ${s} couldn't be saved as a draft (browser storage full) and are lost.`),"switched"}async function $R(){const e=re.getState().logInfo,t=window,n=t.toolboxAPI,{connection:o,theme:s,warnings:i}=await bR({toolboxAPI:n,dataverseAPI:t.dataverseAPI});e("startup","Connected to PPTB host runtime.");for(const p of i)re.getState().logWarn("startup",p);e("startup",`Host theme loaded: ${s}.`);const{setConnection:l}=ae.getState(),{setThemeMode:r}=J.getState(),c=await La().catch(()=>null)??o;l(c.url,c.name,c.environment,c.id),r(s),e("startup",`Connected to ${c.name} (${c.environment}).`),vb(p=>jR(p));const d=()=>{n.utils.getCurrentTheme().then(p=>{J.getState().setThemeMode(p==="dark"?"dark":"light")}).catch(p=>{re.getState().logWarn("startup",`Theme refresh failed: ${p instanceof Error?p.message:String(p)}`)})};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&d()}),n.events?.on((p,h)=>{h?.event==="settings:updated"&&d()});const u=document.getElementById("root");if(!u)throw new Error("No #root element found");hb.createRoot(u).render(a.jsx(B.StrictMode,{children:a.jsx(yR,{children:a.jsx(hR,{})})}))}$R().catch(e=>{re.getState().logError("startup",e instanceof Error?e.message:String(e)),console.error(e);const t=document.getElementById("root")??document.body;Pm(t,e)});export{wm as $,hn as A,ed as B,ut as C,_i as D,mi as E,is as F,Ve as G,Be as H,rm as I,Ie as J,Jc as K,Ns as L,Jt as M,vt as N,ZR as O,dy as P,cr as Q,xR as R,SR as S,Ua as T,fu as U,Wx as V,aI as W,KR as X,eI as Y,TS as Z,CS as _,D as a,fC as a$,Cm as a0,gr as a1,Sm as a2,ma as a3,$u as a4,qR as a5,rS as a6,dC as a7,dm as a8,xC as a9,Pa as aA,BR as aB,LR as aC,Fa as aD,zR as aE,MR as aF,DR as aG,U0 as aH,eR as aI,gS as aJ,YR as aK,_R as aL,GR as aM,ms as aN,Bb as aO,Eu as aP,ge as aQ,yS as aR,Di as aS,ER as aT,Ye as aU,Ld as aV,fd as aW,Gr as aX,hC as aY,Io as aZ,oI as a_,yo as aa,nI as ab,sI as ac,tI as ad,gC as ae,$S as af,QR as ag,An as ah,FR as ai,XR as aj,OR as ak,Ct as al,mo as am,AR as an,ky as ao,qn as ap,za as aq,Ay as ar,$y as as,Ny as at,Ty as au,yd as av,Xi as aw,ns as ax,dd as ay,ud as az,J as b,PR as b0,$s as b1,js as b2,Is as b3,pd as b4,rs as b5,Ln as b6,ey as c,ae as d,uu as e,VR as f,La as g,dv as h,Gi as i,Ps as j,re as k,JR as l,iI as m,HR as n,Z as o,We as p,je as q,UR as r,Md as s,Zt as t,_s as u,Yn as v,Xc as w,Yr as x,WR as y,Ms as z};
|