@mohsinonxrm/pptb-commandbar-studio 0.7.0-beta.1 → 0.7.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +7 -0
  3. package/dist/assets/BulkPublishModal-dGiT6nNQ.js +36 -0
  4. package/dist/assets/{CommandEditorPanel-1tDOtoTt.js → CommandEditorPanel-BfcpfNps.js} +1 -1
  5. package/dist/assets/CommandPalette-C4NOIuA3.js +1 -0
  6. package/dist/assets/{ConflictDrawer-CjObt6DP.js → ConflictDrawer-CW1NLdAD.js} +1 -1
  7. package/dist/assets/{DiffViewer-Dfu_9b4v.js → DiffViewer-R0g0dxLc.js} +1 -1
  8. package/dist/assets/{HideInsteadOfDeleteModal-C64qc-fw.js → HideInsteadOfDeleteModal-DbfHSKmm.js} +1 -1
  9. package/dist/assets/{IconPickerModal-D6hQ_Aqx.js → IconPickerModal-B1AgGWq0.js} +1 -1
  10. package/dist/assets/ImportXmlModal-DImDI43_.js +1 -0
  11. package/dist/assets/LocalizationEditor-CeAgqq85.js +1 -0
  12. package/dist/assets/{MonacoEditor-CBUJNFgC.js → MonacoEditor-BRCY30rO.js} +1 -1
  13. package/dist/assets/{NewButtonModal-B_ugATAS.js → NewButtonModal-DqdSshXe.js} +1 -1
  14. package/dist/assets/{NewGroupModal-Dvg8CSJr.js → NewGroupModal-VysrEsbU.js} +1 -1
  15. package/dist/assets/{NewTabModal-CjMNMXb5.js → NewTabModal-ChEmOjmh.js} +1 -1
  16. package/dist/assets/{RuleEditorPanel-B5or3M9d.js → RuleEditorPanel-C26e1gMH.js} +1 -1
  17. package/dist/assets/{ScalingEditorPanel-CzQtkicj.js → ScalingEditorPanel-f2Rmk9AG.js} +1 -1
  18. package/dist/assets/{TabDisplayRulesPanel-BqzSpzqp.js → TabDisplayRulesPanel-DR-c2-Km.js} +1 -1
  19. package/dist/assets/{UrlComposerModal-BDP57HQn.js → UrlComposerModal-DFwPOYL1.js} +1 -1
  20. package/dist/assets/{WebResourceBrowser-BK_G_Q_c.js → WebResourceBrowser-D2RMaFeZ.js} +1 -1
  21. package/dist/assets/XmlDrawer-DXyRtGs1.js +2 -0
  22. package/dist/assets/index-CKs2IGe0.js +136 -0
  23. package/dist/assets/{useReplaceWebResourceConfirm-Dx7RdpEN.js → useReplaceWebResourceConfirm-C4vg9hxg.js} +1 -1
  24. package/dist/assets/xmlValidator-TOuV4jko.js +3 -0
  25. package/dist/index.html +1 -1
  26. package/package.json +1 -1
  27. package/dist/assets/BulkPublishModal-CF7sSmBT.js +0 -29
  28. package/dist/assets/CommandPalette-BBM1PJH0.js +0 -1
  29. package/dist/assets/ImportXmlModal-DXwUce5n.js +0 -1
  30. package/dist/assets/LocalizationEditor-DXqbD2ZN.js +0 -1
  31. package/dist/assets/XmlDrawer-C4lJ7_MF.js +0 -2
  32. package/dist/assets/index-CL8TmfXp.js +0 -139
  33. package/dist/assets/xmlValidator-DvDaU5OO.js +0 -3
@@ -0,0 +1,136 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./XmlDrawer-DXyRtGs1.js","./fluent-icons-DUgjkNjy.js","./monaco-BIO15LCS.js","./monaco-DdLsZAcA.css","./MonacoEditor-BRCY30rO.js","./fluent-ui-Dde22_ZN.js","./dnd-BmqIZ1-i.js","./CommandEditorPanel-BfcpfNps.js","./CrmParameterEditor-CQD0gNNH.js","./crmParameters-rgfZhhzN.js","./RuleEditorPanel-C26e1gMH.js","./ruleKinds-B9hACGaq.js","./BulkPublishModal-dGiT6nNQ.js","./xmlValidator-TOuV4jko.js","./NewButtonModal-DqdSshXe.js","./NewGroupModal-VysrEsbU.js","./NewTabModal-ChEmOjmh.js","./ImportXmlModal-DImDI43_.js","./CommandPalette-C4NOIuA3.js","./LocalizationEditor-CeAgqq85.js","./IconPickerModal-B1AgGWq0.js","./useReplaceWebResourceConfirm-C4vg9hxg.js","./TabDisplayRulesPanel-DR-c2-Km.js","./ScalingEditorPanel-f2Rmk9AG.js","./ConflictDrawer-CW1NLdAD.js","./WebResourceBrowser-D2RMaFeZ.js","./UrlComposerModal-DFwPOYL1.js","./DiffViewer-R0g0dxLc.js","./HideInsteadOfDeleteModal-DbfHSKmm.js","./server.browser-xEJRzS2D.js"])))=>i.map(i=>d[i]);
2
+ import{y as r,z as me,i as gt,B as Vl,E as ft,F as vr,G as Sr,H as wr,J as Cr,Q as Ir,K as Rr,L as Kl,M as It,N as Ut,O as jr,P as Jl,U as $r,V as Yl,X as Nr,Y as Zl,Z as Ql,$ as ec,a0 as tc,a1 as nc,a2 as oc,a3 as ic,a4 as sc,a5 as rc,a6 as ac,a7 as lc,a8 as cc,a9 as dc,aa as uc,ab as mc,ac as pc,ad as fc,ae as hc,af as gc,ag as bc,ah as yc,ai as xc,aj as vc,ak as Sc,al as wc,am as Cc,an as Ic,ao as Rc,ap as jc,aq as $c,ar as Nc,as as Tc,at as kc,au as Ac,av as Dc,aw as Ec,ax as Oc,ay as zc,az as Bc,aA as Mc,aB as Lc,aC as Pc,aD as Tr,aE as Fc,aF as _c,aG as qc,aH as Hc,aI as Wc,aJ as Gc,aK as Uc,aL as Xc,aM as Vc,aN as Kc,aO as Jc,aP as Yc,aQ as Zc,aR as Ye,aS as Qc,aT as ed,aU as td,aV as nd,aW as od,aX as id,aY as sd,aZ as rd,a_ as ad,a$ as ld,b0 as cd,b1 as dd,b2 as ud,b3 as md,b4 as pd,b5 as fd,b6 as hd,b7 as gd,b8 as bd,b9 as yd,ba as kr,bb as xd,bc as vd,bd as Sd,be as wd,bf as Cd,bg as Id,bh as Rd,bi as jd,bj as $d,bk as Nd,bl as Td,bm as kd,bn as Ad,bo as mo,bp as Dd,bq as Ed,br as Od,bs as zd,bt as Bd,bu as Md,bv as Ld,bw as Pd,bx as Fd,by as _d,bz as qd,bA as Hd,bB as Wd,bC as Gd,bD as Ud,bE as Xd,bF as Vd,bG as Ar,bH as Kd,bI as Jd,bJ as Yd,bK as Zd,bL as Qd,bM as Rt,bN as eu,bO as tu,h as po,g as nu,bP as ou,w as iu,x as su,bQ as ru,bR as au,bS as lu,bT as cu,bU as du,bV as uu,bW as mu,bX as Dr,bY as pu,bZ as fu,A as hu,b_ as gu,s as bu,b$ as yu,c0 as xu,c1 as vu,c2 as Su,c3 as wu,c4 as Cu,c5 as Iu,c6 as Ru,c7 as ju,c8 as $u,c9 as Nu,ca as Tu,cb as ku,cc as Au,cd as Du,ce as Eu,cf as Ou,cg as zu,ch as Bu,ci as Mu,cj as gn,ck as Lu,cl as Pu,cm as fo,cn as Fu,co as _t,cp as _u,cq as Ae,cr as qt,cs as Gn,ct as Er,cu as Or,cv as ps,m as Ht,cw as qu,cx as Hu,cy as Wu,cz as Gu}from"./fluent-icons-DUgjkNjy.js";import{l as Uu,m as Xu,R as Ue,_ as Ne,a as L}from"./monaco-BIO15LCS.js";import{a as Vu,T as Te,t as m,b as F,B as de,u as Ku,P as Ju,c as Yu,d as J,e as Zu,F as Oe,C as Qu,S as dt,O as em,M as we,f as Ce,g as Mt,h as fe,D as Xt,i as Vt,j as Kt,k as Jt,l as Yt,m as Zt,I as qe,n as Zo,o as Qo,p as ei,q as ti,s as pt,v as tm,w as nm,x as om,y as im,z as zr,A as sm,E as rm,G as am,H as lm,J as cm,K as dm,L as um,N as mm,Q as pm,R as fm,U as hm,V as gm,W as bm,X as ym,Y as fs,Z as At,_ as xm,$ as Dt,a0 as rt,a1 as Ei,a2 as Br,a3 as Mr,a4 as Me,a5 as Oi,a6 as vm,a7 as Ve,a8 as Sm,a9 as No,aa as jt,ab as ni,ac as zi,ad as Ke,ae as wm,af as Cm,ag as Im,ah as Rm}from"./fluent-ui-Dde22_ZN.js";import{u as jm,a as Lr,b as Un,K as Pr,P as Fr,D as _r,c as $m,d as Nm,e as qr,f as Tm,S as km,h as Am,g as Dm,C as Em}from"./dnd-BmqIZ1-i.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))o(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const l of s.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&o(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function o(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();function Om(e){return new Worker(""+new URL("editor.worker-D1TDBLlL.js",import.meta.url).href,{name:e?.name})}function zm(e){return new Worker(""+new URL("json.worker-BggoxaER.js",import.meta.url).href,{name:e?.name})}function Bm(e){return new Worker(""+new URL("ts.worker-BrLZGe_E.js",import.meta.url).href,{name:e?.name})}function Mm(e){return new Worker(""+new URL("css.worker-C_6RgliQ.js",import.meta.url).href,{name:e?.name})}function Lm(e){return new Worker(""+new URL("html.worker-CLyYFd_g.js",import.meta.url).href,{name:e?.name})}Uu.config({monaco:Xu});self.MonacoEnvironment={getWorker(e,t){return t==="json"?new zm:t==="typescript"||t==="javascript"?new Bm:t==="css"||t==="scss"||t==="less"?new Mm:t==="html"||t==="handlebars"||t==="razor"?new Lm:new Om}};var An={},hs;function Pm(){if(hs)return An;hs=1;var e=Vu();return An.createRoot=e.createRoot,An.hydrateRoot=e.hydrateRoot,An}var Fm=Pm();const gs=e=>{let t;const n=new Set,o=(d,u)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const f=t;t=u??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(h=>h(t,f))}},i=()=>t,a={setState:o,getState:i,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(o,i,a);return a},_m=(e=>e?gs(e):gs),qm=e=>e;function Hm(e,t=qm){const n=Ue.useSyncExternalStore(e.subscribe,Ue.useCallback(()=>t(e.getState()),[e,t]),Ue.useCallback(()=>t(e.getInitialState()),[e,t]));return Ue.useDebugValue(n),n}const Wm=e=>{const t=_m(e),n=o=>Hm(t,o);return Object.assign(n,t),n},$t=(e=>Wm);function Xn(e){if(!e||!e.id&&!e.url)return"";const t=(e.url??"").trim().replace(/\/+$/,"").toLowerCase();return`${e.id??""}|${t}`}function Hr(){return window.toolboxAPI?.connections}async function Bi(){const e=Hr();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 oi 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 mn,ii=0;function bs(e){const t=Xn(e);mn!==void 0&&t!==mn&&ii++,mn=t}async function ho(e){const t=Hr();if(mn===void 0||!t?.getConnection&&!t?.getActiveConnection)return;let n;try{n=Xn(await Bi())}catch{throw new oi(e)}if(n!==mn)throw new oi(e)}function Gm(e){const t=window.toolboxAPI?.events;if(typeof t?.on!="function")return()=>{};let n=0;const o=(i,s)=>{const l=s?.event;if(l!=="connection:updated"&&l!=="connection:created"&&l!=="connection:deleted")return;const a=++n;Bi().then(c=>{a===n&&e(c)}).catch(()=>{})};return t.on(o),()=>t.off?.(o)}function Um(){const e=ii;return async t=>{if(ii!==e)throw new oi(t);await ho(t)}}const si=new Set;function Xm(e){return si.add(e),()=>si.delete(e)}const ie=$t()((e,t)=>({connectionId:"",connectionUrl:"",connectionName:"",environment:"Dev",publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:0,connectionNotice:null,setConnection:(n,o,i,s=t().connectionId)=>{bs({id:s,url:n}),e({connectionId:s,connectionUrl:n,connectionName:o,environment:i})},switchConnection:(n,o)=>{const i=t();bs(n),e({connectionId:n.id,connectionUrl:n.url,connectionName:n.name,environment:n.environment,publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:i.connectionVersion+1,connectionNotice:{...o,from:{name:i.connectionName,url:i.connectionUrl,environment:i.environment},to:{name:n.name,url:n.url,environment:n.environment}}})},dismissConnectionNotice:()=>e({connectionNotice:null}),setSolutions:n=>e({solutions:n}),setActiveSolution:n=>{Ne(async()=>{const{useRuntimeLogStore:i}=await Promise.resolve().then(()=>ep);return{useRuntimeLogStore:i}},void 0,import.meta.url).then(({useRuntimeLogStore:i})=>{i.getState().logInfo("dataverse",`Active solution: "${n.friendlyName||n.uniqueName}" — publisher="${n.publisherUniqueName||"(empty)"}", prefix="${n.publisherPrefix||"(empty)"}"`),(!n.publisherPrefix||n.publisherPrefix==="new"||/^defaultpublisher/i.test(n.publisherUniqueName??""))&&i.getState().logWarn("dataverse",`Solution "${n.friendlyName||n.uniqueName}" uses the org's default publisher (prefix="${n.publisherPrefix||"new"}"). All IDs and imports from CBS will land under that publisher. To use your own (e.g. "mxrm"), create a new solution in maker.powerapps.com bound to your custom publisher and pick that one here.`)});const o=t().activeSolution?.id!==n.id;if(e({activeSolution:n,publisherPrefix:n.publisherPrefix||"new",...o?{activeEntity:null,entities:[],solutionEntityIds:null,solutionRibbonComponentIds:null}:{}}),o)for(const i of si)i()},setEntities:n=>e({entities:n}),setActiveEntity:n=>e({activeEntity:n}),setSolutionEntityIds:n=>e({solutionEntityIds:n}),setSolutionRibbonComponentIds:n=>e({solutionRibbonComponentIds:n}),setCurrentUser:(n,o)=>e({currentUserId:n,currentUserName:o}),setPublisherPrefix:n=>e({publisherPrefix:n})})),Vm=e=>(t,n,o)=>{const i=o.subscribe;return o.subscribe=((l,a,c)=>{let d=l;if(a){const u=c?.equalityFn||Object.is;let p=l(o.getState());d=f=>{const h=l(f);if(!u(p,h)){const y=p;a(p=h,y)}},c?.fireImmediately&&a(p,p)}return i(d)}),e(t,n,o)},Km=Vm;function Jm(e,t){let n;try{n=e()}catch{return}return{getItem:i=>{var s;const l=c=>c===null?null:JSON.parse(c,void 0),a=(s=n.getItem(i))!=null?s:null;return a instanceof Promise?a.then(l):l(a)},setItem:(i,s)=>n.setItem(i,JSON.stringify(s,void 0)),removeItem:i=>n.removeItem(i)}}const ri=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(o){return ri(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return ri(o)(n)}}}},Ym=(e,t)=>(n,o,i)=>{let s={storage:Jm(()=>window.localStorage),partialize:b=>b,version:0,merge:(b,g)=>({...g,...b}),...t},l=!1,a=0;const c=new Set,d=new Set;let u=s.storage;if(!u)return e((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...b)},o,i);const p=()=>{const b=s.partialize({...o()});return u.setItem(s.name,{state:b,version:s.version})},f=i.setState;i.setState=(b,g)=>(f(b,g),p());const h=e((...b)=>(n(...b),p()),o,i);i.getInitialState=()=>h;let y;const x=()=>{var b,g;if(!u)return;const S=++a;l=!1,c.forEach(v=>{var I;return v((I=o())!=null?I:h)});const w=((g=s.onRehydrateStorage)==null?void 0:g.call(s,(b=o())!=null?b:h))||void 0;return ri(u.getItem.bind(u))(s.name).then(v=>{if(v)if(typeof v.version=="number"&&v.version!==s.version){if(s.migrate){const I=s.migrate(v.state,v.version);return I instanceof Promise?I.then(A=>[!0,A]):[!0,I]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,v.state];return[!1,void 0]}).then(v=>{var I;if(S!==a)return;const[A,R]=v;if(y=s.merge(R,(I=o())!=null?I:h),n(y,!0),A)return p()}).then(()=>{S===a&&(w?.(o(),void 0),y=o(),l=!0,d.forEach(v=>v(y)))}).catch(v=>{S===a&&w?.(void 0,v)})};return i.persist={setOptions:b=>{s={...s,...b},b.storage&&(u=b.storage)},clearStorage:()=>{++a,u?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>x(),hasHydrated:()=>l,onHydrate:b=>(c.add(b),()=>{c.delete(b)}),onFinishHydration:b=>(d.add(b),()=>{d.delete(b)})},s.skipHydration||x(),y||h},Zm=Ym,Qm=e=>({leftPaneWidth:260,rightPaneWidth:340,bottomPanelHeight:220,bottomCollapsed:!1,rightPaneMode:"docked",themeMode:"light",ribbonViewStyle:"modern",activeBottomTab:"commands",commandEditorOpen:!1,commandEditorId:null,ruleEditorOpen:!1,ruleEditorId:null,ruleEditorKind:null,xmlDrawerOpen:!1,bulkPublishOpen:!1,iconPickerOpen:!1,localizationEditorOpen:!1,localizationEditorButtonId:null,newGroupOpen:!1,newButtonGroupId:null,importXmlOpen:!1,importXmlSeed:"",importXmlNote:"",conflictDrawerOpen:!1,conflictElementId:null,webResourceBrowserOpen:!1,urlComposerOpen:!1,diffViewerOpen:!1,diffViewerMode:"compare",tabDisplayRulesOpen:!1,scalingEditorOpen:!1,commandPaletteOpen:!1,newTabOpen:!1,hideInsteadOfDelete:null,announcement:"",setLeftPaneWidth:t=>e({leftPaneWidth:t}),setRightPaneWidth:t=>e({rightPaneWidth:t}),setBottomPanelHeight:t=>e({bottomPanelHeight:t}),setBottomCollapsed:t=>e({bottomCollapsed:t}),setRightPaneMode:t=>e({rightPaneMode:t}),setThemeMode:t=>e({themeMode:t}),setRibbonViewStyle:t=>e({ribbonViewStyle:t}),setActiveBottomTab:t=>e({activeBottomTab:t}),openCommandEditor:t=>e({commandEditorOpen:!0,commandEditorId:t}),closeCommandEditor:()=>e({commandEditorOpen:!1,commandEditorId:null}),openRuleEditor:(t,n)=>e({ruleEditorOpen:!0,ruleEditorId:t,ruleEditorKind:n}),closeRuleEditor:()=>e({ruleEditorOpen:!1,ruleEditorId:null,ruleEditorKind:null}),openXmlDrawer:()=>e({xmlDrawerOpen:!0}),closeXmlDrawer:()=>e({xmlDrawerOpen:!1}),openBulkPublish:()=>e({bulkPublishOpen:!0}),closeBulkPublish:()=>e({bulkPublishOpen:!1}),openIconPicker:()=>e({iconPickerOpen:!0}),closeIconPicker:()=>e({iconPickerOpen:!1}),openLocalizationEditor:t=>e({localizationEditorOpen:!0,localizationEditorButtonId:t}),closeLocalizationEditor:()=>e({localizationEditorOpen:!1,localizationEditorButtonId:null}),openNewGroup:()=>e({newGroupOpen:!0}),closeNewGroup:()=>e({newGroupOpen:!1}),openNewButton:t=>e({newButtonGroupId:t}),closeNewButton:()=>e({newButtonGroupId:null}),openImportXml:(t,n)=>e({importXmlOpen:!0,importXmlSeed:typeof t=="string"?t:"",importXmlNote:typeof n=="string"?n:""}),closeImportXml:()=>e({importXmlOpen:!1}),openConflictDrawer:t=>e({conflictDrawerOpen:!0,conflictElementId:t}),closeConflictDrawer:()=>e({conflictDrawerOpen:!1,conflictElementId:null}),openWebResourceBrowser:()=>e({webResourceBrowserOpen:!0}),closeWebResourceBrowser:()=>e({webResourceBrowserOpen:!1}),openUrlComposer:()=>e({urlComposerOpen:!0}),closeUrlComposer:()=>e({urlComposerOpen:!1}),openDiffViewer:t=>e({diffViewerOpen:!0,diffViewerMode:t}),closeDiffViewer:()=>e({diffViewerOpen:!1}),openTabDisplayRules:()=>e({tabDisplayRulesOpen:!0}),closeTabDisplayRules:()=>e({tabDisplayRulesOpen:!1}),openScalingEditor:()=>e({scalingEditorOpen:!0}),closeScalingEditor:()=>e({scalingEditorOpen:!1}),setCommandPaletteOpen:t=>e({commandPaletteOpen:t}),openNewTab:()=>e({newTabOpen:!0}),closeNewTab:()=>e({newTabOpen:!1}),openHideInsteadOfDelete:t=>e({hideInsteadOfDelete:t}),closeHideInsteadOfDelete:()=>e({hideInsteadOfDelete:null}),announce:t=>e({announcement:t})}),ee=$t()(Zm(Qm,{name:"cbs:ui",partialize:e=>({leftPaneWidth:e.leftPaneWidth,rightPaneWidth:e.rightPaneWidth,bottomPanelHeight:e.bottomPanelHeight,bottomCollapsed:e.bottomCollapsed,rightPaneMode:e.rightPaneMode,themeMode:e.themeMode,ribbonViewStyle:e.ribbonViewStyle})})),se=$t()((e,t)=>({entries:[],append:n=>{const i={id:`${Date.now()}-${t().entries.length+1}`,ts:new Date().toISOString(),...n};e({entries:[...t().entries,i].slice(-400)})},logInfo:(n,o)=>t().append({scope:n,level:"info",message:o}),logWarn:(n,o)=>t().append({scope:n,level:"warn",message:o}),logError:(n,o)=>t().append({scope:n,level:"error",message:o}),clear:()=>e({entries:[]})})),ep=Object.freeze(Object.defineProperty({__proto__:null,useRuntimeLogStore:se},Symbol.toStringTag,{value:"Module"})),tp=new Set(["Default","InvertResult","PropertyValue","ExpectedValue","TrackedInCrm","PassParams","AllowCustomRelationship","AllowSystemRelationship"]),ys=["EnableRules","DisplayRules","Actions"];function np(e,t){return tp.has(t)||e.tagName==="BoolParameter"&&t==="Value"}function op(e){const t=e.trim();return t==="1"?"true":t==="0"?"false":t}function ip(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;")}function Fn(e,t,n){const o=Array.from(e.attributes).map(l=>[l.name,np(e,l.name)?op(l.value):l.value]).sort(([l],[a])=>l<a?-1:l>a?1:0).map(([l,a])=>` ${l}="${ip(a)}"`).join(""),i=[];let s=[];for(const l of Array.from(e.childNodes))if(l.nodeType===1)s.push(l);else if(l.nodeType===3||l.nodeType===4){const a=(l.textContent??"").trim();a&&i.push(`${n} #text ${a}`)}if(t.normalizeCommands&&e.tagName==="CommandDefinition"){const l=new Map(s.map(d=>[d.tagName,d])),a=s.filter(d=>!ys.includes(d.tagName)),c=ys.map(d=>{const u=l.get(d);return u?Fn(u,t,`${n} `):`${n} <${d}/>`});s=[],i.push(...c,...a.map(d=>Fn(d,t,`${n} `)))}for(const l of s)i.push(Fn(l,t,`${n} `));return i.length===0?`${n}<${e.tagName}${o}/>`:`${n}<${e.tagName}${o}>
3
+ ${i.join(`
4
+ `)}
5
+ ${n}</${e.tagName}>`}function Wr(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 Wt(e,t={}){const n=typeof e=="string"?Wr(e):e;return Fn(n,t,"")}function sp(e,t,n={}){try{return Wt(e,n)===Wt(t,n)}catch{return!1}}const bn={button:"Button",flyout:"FlyoutAnchor",splitButton:"SplitButton",textBox:"TextBox",comboBox:"ComboBox",checkBox:"CheckBox",toggleButton:"ToggleButton",label:"Label",dropDown:"DropDown",mruSplitButton:"MRUSplitButton",spinner:"Spinner",galleryButton:"GalleryButton"},Gr=Object.fromEntries(Object.entries(bn).map(([e,t])=>[t,e])),rp=new Set(["toggleButton","label","dropDown","mruSplitButton","spinner","galleryButton"]);function Ze(e){return!!e&&rp.has(e)}const Ur=["Command","QueryCommand","MenuCommand","PopulateQueryCommand","CommandMenuOpen","CommandMenuClose","CommandPreview","CommandPreviewRevert","CommandRevert"],Xr=new RegExp(`\\s(?:${Ur.join("|")})="([^"]+)"`,"g");function Vr(e){const t=new Set(e.commandId?[e.commandId]:[]);if(Ze(e.kind))for(const n of e.source?.xml?.matchAll(Xr)??[])t.add(n[1]);return[...t]}function ap(e,t,n){const o=i=>i.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;");return e.replace(Xr,(i,s)=>s===t||s===o(t)?i.replace(`"${s}"`,`"${o(n)}"`):i)}const Vn={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 Kr(e,t){const n=t.length>0?Math.min(...t):1/0,o=e.filter(i=>i<n);return{after:o.length>0?Math.max(...o):0,before:n}}function Jr(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 Yr(e,t,n){const o=[],i=[],s=new Set([...t.maxSizes,...t.scales]),l=(f,h)=>{o.push({tabId:e,id:f.id,kind:f.kind,groupId:f.groupId,from:f.sequence,to:h}),s.add(h)},a=n.filter(f=>f.kind==="Scale"),c=[];for(const f of a)s.has(f.sequence)?c.push(f):s.add(f.sequence);for(const f of c)l(f,Math.max(0,...s)+1);const d=[...t.scales,...a.map(f=>o.find(h=>h.id===f.id&&h.kind==="Scale")?.to??f.sequence)],u=Kr(t.maxSizes,d),p=[];for(const f of n.filter(h=>h.kind==="MaxSize"))f.sequence<u.before&&!s.has(f.sequence)?s.add(f.sequence):p.push(f);for(const f of p){const h=Jr(u,s);h===void 0?i.push(`The scaling of tab ${e} has no free position for MaxSize ${f.id} (Sequence ${f.sequence}): it must come before the first Scale (${u.before}) and use a Sequence no other step uses`):l(f,h)}return{changes:o,problems:i}}function lp(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 Qt(){return{customActions:new Map,templates:new Map,commandDefinitions:new Map,tabDisplayRules:new Map,displayRules:new Map,enableRules:new Map,locLabels:new Map}}const $n=()=>new XMLSerializer;function Zr(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 at(e,t){return e?Array.from(e.children).filter(n=>n.tagName===t):[]}function he(e,t){return at(e,t)[0]}function Qr(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 Ix(e){const t=Qt(),o=Zr(e).documentElement;if(o.tagName!=="RibbonDiffXml")throw new Error(`Expected <RibbonDiffXml> root, got <${o.tagName}>`);const i=$n();for(const a of Array.from(he(o,"CustomActions")?.children??[])){const c=Qr(a);c&&t.customActions.set(c,i.serializeToString(a))}const s=he(he(o,"Templates"),"RibbonTemplates");for(const a of Array.from(s?.children??[])){const c=a.getAttribute("Id");c&&t.templates.set(c,i.serializeToString(a))}for(const a of at(he(o,"CommandDefinitions"),"CommandDefinition")){const c=a.getAttribute("Id");c&&t.commandDefinitions.set(c,i.serializeToString(a))}const l=he(o,"RuleDefinitions");for(const a of at(he(l,"TabDisplayRules"),"TabDisplayRule")){const c=a.getAttribute("TabCommand");c&&t.tabDisplayRules.set(c,i.serializeToString(a))}for(const a of at(he(l,"DisplayRules"),"DisplayRule")){const c=a.getAttribute("Id");c&&t.displayRules.set(c,i.serializeToString(a))}for(const a of at(he(l,"EnableRules"),"EnableRule")){const c=a.getAttribute("Id");c&&t.enableRules.set(c,i.serializeToString(a))}for(const a of at(he(o,"LocLabels"),"LocLabel")){const c=a.getAttribute("Id");c&&t.locLabels.set(c,i.serializeToString(a))}return t}function ge(e){return Zr(e).documentElement}function cp(e){const t=Qt();for(const n of e.diffs){const o=n.rdx?.trim();if(!o)continue;const i=ge(o);switch(n.difftype){case 3:{const s=i.getAttribute("Id")??n.diffid;s&&t.locLabels.set(s,o);break}case 2:{const s=i.getAttribute("Id")??n.diffid;s&&t.templates.set(s,o);break}default:{const s=Qr(i);s&&t.customActions.set(s,o)}}}for(const n of e.commands){const o=n.commanddefinition?.trim(),i=n.command??(o?ge(o).getAttribute("Id"):null);o&&i&&t.commandDefinitions.set(i,o)}for(const n of e.rules){const o=n.ruledefinition?.trim();if(!o)continue;const i=ge(o);if(n.ruletype===3||i.tagName==="TabDisplayRule"){const s=i.getAttribute("TabCommand")??n.ruleid;s&&t.tabDisplayRules.set(s,o)}else if(n.ruletype===1||i.tagName==="EnableRule"){const s=i.getAttribute("Id")??n.ruleid;s&&t.enableRules.set(s,o)}else{const s=i.getAttribute("Id")??n.ruleid;s&&t.displayRules.set(s,o)}}return t}function Mi(e,t){const n=Qt();for(const o of Object.keys(n)){for(const[i,s]of e[o])n[o].set(i,s);for(const[i,s]of t[o])n[o].set(i,s)}return n}function Rx(e){const t=(n,o)=>Array.from(n.values()).map(i=>`${o}${i}`).join(`
6
+ `);return`<RibbonDiffXml>
7
+ <CustomActions>
8
+ ${t(e.customActions," ")}
9
+ </CustomActions>
10
+ <Templates>
11
+ <RibbonTemplates Id="Mscrm.Templates">
12
+ ${t(e.templates," ")}
13
+ </RibbonTemplates>
14
+ </Templates>
15
+ <CommandDefinitions>
16
+ ${t(e.commandDefinitions," ")}
17
+ </CommandDefinitions>
18
+ <RuleDefinitions>
19
+ <TabDisplayRules>
20
+ ${t(e.tabDisplayRules," ")}
21
+ </TabDisplayRules>
22
+ <DisplayRules>
23
+ ${t(e.displayRules," ")}
24
+ </DisplayRules>
25
+ <EnableRules>
26
+ ${t(e.enableRules," ")}
27
+ </EnableRules>
28
+ </RuleDefinitions>
29
+ <LocLabels>
30
+ ${t(e.locLabels," ")}
31
+ </LocLabels>
32
+ </RibbonDiffXml>`}function dp(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 xs(e,t){const n=ge(t);if(e==="commandDefinitions")for(const o of Array.from(n.getElementsByTagName("JavaScriptFunction")))dp(o)&&o.parentNode?.replaceChild(n.ownerDocument.createElement("PlatformJavaScriptFunction"),o);if(e==="locLabels")for(const o of Array.from(n.getElementsByTagName("Titles"))){const i=Array.from(o.children).sort((s,l)=>Number(s.getAttribute("languagecode"))-Number(l.getAttribute("languagecode")));for(const s of i)o.appendChild(s)}return Wt(n,{normalizeCommands:e==="commandDefinitions"})}const ea=(e,t,n)=>{try{return xs(e,t)===xs(e,n)}catch{return t===n}},vs=e=>Array.from(ge(e).getElementsByTagName("Title")).map(t=>`${t.getAttribute("languagecode")}=${t.getAttribute("description")??""}`);function up(e,t,n){if(e!=="locLabels")return ea(e,t,n);try{const o=new Set(vs(t)),i=vs(n);return i.length>0&&i.every(s=>o.has(s))}catch{return t===n}}function jx(e,t){const n=[];for(const o of Object.keys(t))for(const[i,s]of t[o]){const l=e[o].get(i);(l===void 0||!ea(o,l,s))&&n.push(`${o}:${i}`)}return n}function $x(e,t,n={}){const o=[],i=[],s=[],l=new Set(n.contentKeys??[]);for(const a of Object.keys(e)){for(const[c,d]of e[a]){const u=t[a].get(c);u===void 0?o.push(`${a}:${c}`):l.has(`${a}:${c}`)&&!up(a,d,u)&&s.push(`${a}:${c}`)}for(const c of t[a].keys())e[a].has(c)||i.push(`${a}:${c}`)}return{missing:o,unexpected:i,differing:s}}function Nx(e){return Object.values(e).reduce((t,n)=>t+n.size,0)}function To(e){const t=ge(e);return t.tagName!=="CustomAction"?null:he(t,"CommandUIDefinition")?.firstElementChild??null}function Je(e){return!!e&&e.endsWith("._children")}const mp=new Set(["Menu","MenuSection","Controls"]);function ai(e){return e.tagName==="Tab"||e.tagName==="Group"?[]:Array.from(e.getElementsByTagName("*")).filter(t=>!mp.has(t.tagName)&&!!t.getAttribute("Id")&&t.parentElement?.tagName==="Controls")}const yn=e=>e?.tagName==="Tab"||e?.tagName==="Group",Ss=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function ta(e){return Array.from(e.getElementsByTagName("Controls")).flatMap(t=>Array.from(t.children))}function na(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 Kn(e){return yn(e)?ta(e):ai(e)}function Jn(e){const t=new Set;for(const n of e.customActions.values()){const o=ge(n);if(o.tagName!=="CustomAction"||!Je(o.getAttribute("Location")))continue;const i=he(o,"CommandUIDefinition")?.firstElementChild,s=i?.getAttribute("Id");if(s&&t.add(s),i)for(const l of Kn(i)){const a=l.getAttribute("Id");a&&t.add(a)}}return t}function oa(e,t){const n=new Map(e),o=$n(),i=t?new Set(t):void 0;for(let s=!0;s;){s=!1;const l=new Map;for(const[a,c]of n){const d=ge(c);if(d.tagName!=="CustomAction"||!Je(d.getAttribute("Location")))continue;const u=he(d,"CommandUIDefinition")?.firstElementChild;if(yn(u))for(const p of[u,...Array.from(u.getElementsByTagName("Group"))]){const f=p.getAttribute("Id");f&&!l.has(f)&&l.set(f,a)}}for(const[a,c]of n){const d=ge(c);if(d.tagName!=="CustomAction")continue;const u=/^(.+)\.(Controls|Groups|Scaling)\._children$/.exec(d.getAttribute("Location")??""),p=he(d,"CommandUIDefinition")?.firstElementChild,f=u?l.get(u[1]):void 0;if(!u||!p||!f||f===a||i&&!i.has(a)&&!i.has(f))continue;const[,h,y]=u,x=ge(n.get(f)),b=na(x,h);if(!b||b.tagName!==(y==="Controls"?"Group":"Tab"))continue;const g=x.ownerDocument;let S=he(b,y);if(!S){S=g.createElement(y),S.setAttribute("Id",`${h}.${y}`);const A=y==="Scaling"?he(b,"Groups"):void 0;b.insertBefore(S,A??null)}const w=g.importNode(p,!0),v=d.getAttribute("Sequence");!w.getAttribute("Sequence")&&v&&w.setAttribute("Sequence",v);const I=w.tagName==="MaxSize"?he(S,"Scale"):void 0;S.insertBefore(w,I??null),n.set(f,o.serializeToString(x)),i?.add(f),n.delete(a),s=!0;break}}return n}function pp(e,t){const n=he(e,"CommandUIDefinition")?.firstElementChild??null;return n?n.getAttribute("Id")===t?n:Kn(n).find(o=>o.getAttribute("Id")===t)??null:null}function ia(e){const t=new Set;for(const n of e.customActions.values()){const o=ge(n);if(o.tagName!=="CustomAction"||!Je(o.getAttribute("Location")))continue;const i=he(o,"CommandUIDefinition")?.firstElementChild;if(!i||i.tagName!=="Tab"&&i.tagName!=="Group")continue;const s=i.getAttribute("Id");s&&t.add(s);for(const l of Array.from(i.getElementsByTagName("Group"))){const a=l.getAttribute("Id");a&&t.add(a)}}return t}function go(e){const t=[];for(const n of e.customActions.values()){const o=ge(n);if(o.tagName!=="HideCustomAction")continue;const i=o.getAttribute("Location");i&&t.push({hideActionId:o.getAttribute("HideActionId")??"",location:i})}return t}function fp(e){const t=[],n=e.getAttribute("Id");n&&t.push(n);for(const o of Array.from(e.getElementsByTagName("*"))){const i=o.getAttribute("Id");i&&t.push(i)}return t}function pn(e){const t=[];for(const n of[e,...Array.from(e.getElementsByTagName("*"))])for(const o of Ur){const i=n.getAttribute(o);i&&t.push(i)}return t}function sa(e){const t=new Set;for(const n of e.customActions.values()){const o=ge(n);if(o.tagName==="CustomAction")for(const i of pn(o))t.add(i)}return t}function hp(e){return/^(Mscrm|Microsoft)\./.test(e)}function Li(e,t){if(hp(e))return!0;for(const n of t)if(n===e)return!1;return!0}function gp(e){const t=e?.match(/^(.+)\.(?:Controls|Groups)\._children$/);return t?t[1]:null}function _n(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 ws(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 bp(e,t,n){const o=at(e,"Menu")[0],i=at(t,"Menu")[0];if(!o){for(const a of ai(t))n(a.getAttribute("Id")??"")&&a.parentNode?.removeChild(a);return _n(t,e)}const s=o.cloneNode(!0),l=(a,c)=>[s,...Array.from(s.getElementsByTagName("*"))].find(d=>d.getAttribute("Id")===c&&(a?d.tagName===a:d.parentElement?.tagName==="Controls"));if(i){for(const a of Array.from(i.getElementsByTagName("MenuSection"))){const c=l("MenuSection",a.getAttribute("Id")??"");if(c){ws(a,c);continue}const d=l("Menu",a.parentElement?.getAttribute("Id")??"");if(!d)continue;const u=a.cloneNode(!0);for(const p of Array.from(u.getElementsByTagName("*")))p.parentElement?.tagName==="Controls"&&n(p.getAttribute("Id")??"")&&p.parentNode?.removeChild(p);d.appendChild(u)}for(const a of ai(t)){const c=a.getAttribute("Id")??"";if(n(c))continue;const d=l(null,c);if(d){ws(a,d);continue}const u=l("Controls",a.parentElement?.getAttribute("Id")??"");u&&u.appendChild(a.cloneNode(!0))}}for(const a of at(t,"Menu"))t.removeChild(a);return t.appendChild(s),t}const ko=/\$LocLabels:([^"'\s]+)/g;function Cs(e){const t=new Set;for(const n of e)for(const o of pn(ge(n)))t.add(o);return t}function yp(e){const t=new Set;for(const n of e){const o=ge(n);for(const i of[o,...Array.from(o.getElementsByTagName("*"))])for(const s of Array.from(i.attributes))s.value.startsWith("$LocLabels:")&&t.add(s.value.slice(11))}return t}function Dn(e){const t={EnableRule:new Set,DisplayRule:new Set};for(const n of e){const o=ge(n);for(const i of["EnableRule","DisplayRule"])for(const s of Array.from(o.getElementsByTagName(i))){const l=s.getAttribute("Id");l&&t[i].add(l)}}return t}function Tx(e,t,n={}){const o=new Set(n.editedCommandIds??[]),i=new Set(n.editedEnableRuleIds??[]),s=new Set(n.editedDisplayRuleIds??[]),l=new Set(n.deletedControlIds??[]),a=new Set(n.unhiddenControlIds??[]),c=new Set(n.retainedCommandIds??[]),d=$n(),u=Mi(e,Qt()),p=new Map,f=new Map,h=[];for(const[O,T]of e.customActions){const z=To(T),$=ge(T);if($.tagName!=="CustomAction")continue;const M=$.getAttribute("Location");if(z?.getAttribute("Id")&&Je(M)){p.set(z.getAttribute("Id"),O);for(const G of Kn(z)){const K=G.getAttribute("Id");K&&h.push([K,O])}}else M&&f.set(M,O)}for(const[O,T]of h)p.has(O)||p.set(O,T);const y=(O,T)=>{const z=u.customActions.get(O);if(!z)return{ca:null,el:null,nested:!1};const $=ge(z),M=pp($,T);return{ca:$,el:M,nested:!!M&&M.parentElement?.tagName!=="CommandUIDefinition"}},x=new Set;for(const[O,T]of t.customActions){const z=ge(T),$=To(T),M=$?.getAttribute("Id")??null,G=M?p.get(M):void 0,K=z.tagName==="CustomAction"&&Je(z.getAttribute("Location"));K&&M&&x.add(M);const Q=$?.tagName==="Tab"||$?.tagName==="Group";if(K&&Q)for(const j of ta($)){const C=j.getAttribute("Id");if(!C)continue;x.add(C);const B=p.get(C),Y=B?y(B,C):null;!B||!Y?.ca||!Y.el||(Y.nested?(Y.el.parentNode.removeChild(Y.el),u.customActions.set(B,d.serializeToString(Y.ca))):u.customActions.delete(B))}const P=z.tagName==="CustomAction"&&$&&M&&G&&!(K&&Q),q=P?y(G,M):null;if(P&&q?.ca&&q.el&&q.nested){const{ca:j,el:C}=q;if(K)C.parentNode.removeChild(C),u.customActions.set(O,T);else{const B=_n(j.ownerDocument.importNode($,!0),C);C.parentNode.replaceChild(B,C)}u.customActions.set(G,d.serializeToString(j));continue}if(P&&q?.ca&&q.el){const{ca:j,el:C,nested:B}=q;if(K&&B){C.parentNode.removeChild(C),u.customActions.set(G,d.serializeToString(j)),u.customActions.set(O,T);continue}let Y=j.ownerDocument.importNode($,!0);if(K?Y=bp(C,Y,le=>{const _=p.get(le);return!!_&&_!==G}):Y=_n(Y,C),C.parentNode.replaceChild(Y,C),!B){K&&j.setAttribute("Location",z.getAttribute("Location"));const le=$.getAttribute("Sequence")??(K?z.getAttribute("Sequence"):null);le&&j.setAttribute("Sequence",le)}u.customActions.set(G,d.serializeToString(j));continue}const V=z.getAttribute("Location"),U=z.tagName==="CustomAction"&&V?f.get(V):void 0;if(U&&$){const j=To(e.customActions.get(U)),C=ge(T),B=he(C,"CommandUIDefinition");B?.firstElementChild&&_n(B.firstElementChild,j),u.customActions.delete(U),u.customActions.set(O,d.serializeToString(C));continue}u.customActions.set(O,T)}for(const O of n.movedControls??[]){const T=p.get(O.id),z=T?y(T,O.id):null;if(!T||!z?.ca||!z.el){if(x.has(O.id))continue;throw new Error(`Can't move ${O.id}: it isn't in this table's unmanaged customizations.`)}const{ca:$,el:M}=z,G=O.controlsId??`${O.groupId}.Controls`;if(M.setAttribute("Sequence",String(O.sequence)),!z.nested)$.setAttribute("Location",`${G}._children`),$.setAttribute("Sequence",String(O.sequence));else if(M.parentElement?.getAttribute("Id")!==G){const K=Array.from($.getElementsByTagName("Controls")).find(Q=>Q.getAttribute("Id")===G);if(M.parentNode.removeChild(M),K)K.appendChild(M);else{let Q=`${O.id}.CustomAction`;for(;u.customActions.has(`ca:${Q}`);)Q+="_";u.customActions.set(`ca:${Q}`,`<CustomAction Id="${Ss(Q)}" Location="${Ss(`${G}._children`)}" Sequence="${O.sequence}"><CommandUIDefinition>${d.serializeToString(M)}</CommandUIDefinition></CustomAction>`)}}u.customActions.set(T,d.serializeToString($))}const b=new Set,g=new Set;for(const[O,T]of Array.from(u.customActions)){const z=ge(T);if(z.tagName==="HideCustomAction"){a.has(z.getAttribute("Location")??"")&&u.customActions.delete(O);continue}const $=he(z,"CommandUIDefinition")?.firstElementChild??null,M=$?.getAttribute("Id");if(!$||!Je(z.getAttribute("Location")))continue;if(M&&l.has(M)&&!x.has(M)){u.customActions.delete(O);for(const K of T.matchAll(ko))g.add(K[1]);for(const K of pn($))b.add(K);continue}const G=Kn($).filter(K=>{const Q=K.getAttribute("Id")??"";return l.has(Q)&&!x.has(Q)});if(G.length!==0){for(const K of G){const Q=d.serializeToString(K);for(const P of Q.matchAll(ko))g.add(P[1]);for(const P of pn(K))b.add(P);K.parentNode?.removeChild(K)}u.customActions.set(O,d.serializeToString(z))}}const S=new Set,w=new Set(n.deletedContainerIds??[]),v=(O,T)=>{for(const z of fp(O))w.add(z);for(const z of pn(O))b.add(z);for(const z of[O,...Array.from(O.getElementsByTagName("Tab"))]){const $=z.tagName==="Tab"?z.getAttribute("Command"):null;$&&S.add($)}for(const z of T.matchAll(ko))g.add(z[1])};for(let O=w.size>0;O;){O=!1;for(const[T,z]of Array.from(u.customActions)){const $=ge(z),M=$.getAttribute("Location");if($.tagName==="HideCustomAction"){M&&w.has(M)&&(u.customActions.delete(T),O=!0);continue}const G=he($,"CommandUIDefinition")?.firstElementChild??null,K=G?.getAttribute("Id")??null,Q=gp(M);if(!!K&&w.has(K)&&Je(M)||!!Q&&w.has(Q)||!Je(M)&&!!M&&w.has(M)||!!G?.getAttribute("GroupId")&&w.has(G.getAttribute("GroupId"))){u.customActions.delete(T),G&&v(G,z),O=!0;continue}if(G?.tagName!=="Tab")continue;const q=Array.from(G.getElementsByTagName("*")).filter(V=>V.tagName==="Group"?w.has(V.getAttribute("Id")??""):(V.tagName==="MaxSize"||V.tagName==="Scale")&&w.has(V.getAttribute("GroupId")??""));if(q.length!==0){for(const V of q)v(V,d.serializeToString(V)),V.parentNode?.removeChild(V);u.customActions.set(T,d.serializeToString($)),O=!0}}}const I=new Set;for(const[O,T]of u.customActions)e.customActions.get(O)!==T&&I.add(O);u.customActions=oa(u.customActions,I);const A=(O,T)=>{for(const[z,$]of t[O])e[O].has(z)&&!T.has(z)||u[O].set(z,$)};A("commandDefinitions",o),A("enableRules",i),A("displayRules",s);const R=Cs(u.customActions.values());for(const O of b){if(c.has(O)||!u.commandDefinitions.has(O)||R.has(O))continue;const T=u.commandDefinitions.get(O);u.commandDefinitions.delete(O);const z=Dn([T]),$=Dn(u.commandDefinitions.values());for(const M of z.EnableRule)$.EnableRule.has(M)||u.enableRules.delete(M);for(const M of z.DisplayRule)$.DisplayRule.has(M)||u.displayRules.delete(M)}const k={EnableRule:new Set(n.retainedEnableRuleIds??[]),DisplayRule:new Set(n.retainedDisplayRuleIds??[])},N=sa(u);for(const O of n.uncustomisedCommandIds??[]){const T=u.commandDefinitions.get(O);if(T===void 0||t.commandDefinitions.has(O)||!Li(O,N))continue;u.commandDefinitions.delete(O);const z=Dn(u.commandDefinitions.values()),$=Dn([T]);for(const M of["EnableRule","DisplayRule"])for(const G of $[M]){const K=M==="EnableRule"?u.enableRules:u.displayRules;(M==="EnableRule"?t.enableRules:t.displayRules).has(G)||k[M].has(G)||z[M].has(G)||K.delete(G)}}for(const[O,T]of t.tabDisplayRules)u.tabDisplayRules.set(O,T);for(const[O,T]of t.templates)u.templates.set(O,T);const W=yp(u.customActions.values());for(const O of g)!t.locLabels.has(O)&&!W.has(O)&&u.locLabels.delete(O);const X=Cs(u.customActions.values());for(const O of S)!t.tabDisplayRules.has(O)&&!X.has(O)&&u.tabDisplayRules.delete(O);for(const O of n.removedTabCommands??[])t.tabDisplayRules.has(O)||u.tabDisplayRules.delete(O);for(const[O,T]of t.locLabels){if(e.locLabels.get(O)){const $=Array.from(ge(T).querySelectorAll("Title")).map(M=>M.getAttribute("description"));if($.length>0&&$.every(M=>M===O))continue}u.locLabels.set(O,T)}return u}function kx(e,t,n){const o=Mi(e,Qt());for(const[i,s]of o.customActions){const l=ge(s);if(l.tagName!=="CustomAction"||!Je(l.getAttribute("Location")))continue;const a=he(l,"CommandUIDefinition")?.firstElementChild;if(!yn(a))continue;const c=na(a,t);if(!(!c||!yn(c))){c.setAttribute("Title",n),o.customActions.set(i,$n().serializeToString(l));break}}return o}function Pi(e){const t=[],n=(o,i,s)=>({id:o.getAttribute("Id")??"",kind:o.tagName,groupId:o.getAttribute("GroupId")??"",sequence:Number(o.getAttribute("Sequence")??"0"),size:o.getAttribute("Size")??"",tabId:i,key:s});for(const[o,i]of e.customActions){const s=ge(i);if(s.tagName!=="CustomAction")continue;const l=he(s,"CommandUIDefinition")?.firstElementChild;if(!l)continue;const a=/^(.+)\.Scaling\._children$/.exec(s.getAttribute("Location")??"");if(a&&(l.tagName==="MaxSize"||l.tagName==="Scale")&&t.push(n(l,a[1],o)),l.tagName==="Tab"&&Je(s.getAttribute("Location"))){const c=l.getAttribute("Id")??"";for(const d of Array.from(he(l,"Scaling")?.children??[]))(d.tagName==="MaxSize"||d.tagName==="Scale")&&t.push(n(d,c,o))}}return t}function Ax(e,t){const n=Pi(e),o=new Map;for(const c of n)o.set(c.tabId,[...o.get(c.tabId)??[],c]);const i=[],s=[];for(const[c,d]of o){const u=Yr(c,t[c]??{maxSizes:[],scales:[]},d);i.push(...u.changes),s.push(...u.problems)}if(i.length===0)return{parts:e,changes:i,problems:s};const l=Mi(e,Qt()),a=$n();for(const c of i){const d=n.find(h=>h.id===c.id&&h.kind===c.kind&&h.tabId===c.tabId),u=ge(l.customActions.get(d.key)),p=he(u,"CommandUIDefinition").firstElementChild;(p.tagName==="Tab"?Array.from(he(p,"Scaling")?.children??[]).find(h=>h.tagName===c.kind&&h.getAttribute("Id")===c.id):p)?.setAttribute("Sequence",String(c.to)),p.tagName!=="Tab"&&u.setAttribute("Sequence",String(c.to)),l.customActions.set(d.key,a.serializeToString(u))}return{parts:l,changes:i,problems:s}}function xp(e,t){const n=new Map;for(const i of t.customActions.values()){const s=ge(i);if(s.tagName!=="CustomAction"||!Je(s.getAttribute("Location")))continue;const l=he(s,"CommandUIDefinition")?.firstElementChild;if(yn(l))for(const a of[l,...Array.from(l.getElementsByTagName("Group"))]){const c=a.getAttribute("Id"),d=a.getAttribute("Title");c&&d?.startsWith("$LocLabels:")&&n.set(c,d)}}for(const i of e.tabs){const s=n.get(i.id);s&&(i.label=s);for(const l of i.groups){const a=n.get(l.id);a&&(l.label=a)}}const o=new Set(e.tabs.map(i=>i.id));for(const i of Pi(t)){if(!o.has(i.tabId))continue;e.scalingByTab=e.scalingByTab??{};const s=e.scalingByTab[i.tabId]=e.scalingByTab[i.tabId]??{tabId:i.tabId,maxSizes:[],scales:[]},l=i.kind==="MaxSize"?s.maxSizes:s.scales,a={id:i.id,groupId:i.groupId,size:i.size,sequence:i.sequence},c=l.findIndex(d=>d.id===i.id);c>=0?l[c]=a:l.push(a)}}function ue(e,t,n=1033){if(!e)return"";const o=e.match(/^\$LocLabels:(.+)$/);if(o){const s=o[1],l=t.find(a=>a.id===s);if(l){const a=l.titles.find(u=>u.languageCode===n),c=l.titles.find(u=>u.languageCode===1033),d=l.titles[0];return a?.description??c?.description??d?.description??s}return s}const i=e.match(/^\$Resources(?:\([^)]*\))?:(.+)$/);return i?i[1]:e}function Fi(e){return!!e&&/^\$Resources(\([^)]*\))?:/.test(e)}function ra(e){return`$LocLabels:${e}`}function aa(e){const t=e.match(/^\$LocLabels:(.+)$/);return t?t[1]:null}const Is=128;function bo(e,t){const n=`${e}.${t}`;if(n.length<=Is)return n;const o=vp(e),i=Is-t.length-o.length-2;return`${e.slice(0,i)}_${o}.${t}`}function vp(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 yo(e){return bo(e,"LabelText")}function xo(e){return bo(e,"ToolTipTitle")}function vo(e){return bo(e,"ToolTipDescription")}function Sp(e){return bo(e,"Title")}function wp(e,t){const n=(o,i)=>(o?aa(o):null)??i;return{label:n(t?.labelToken,yo(e)),tooltipTitle:n(t?.tooltipTitleToken,xo(e)),tooltipBody:n(t?.tooltipBodyToken,vo(e))}}function Dx(e,t,n,o,i=1033){const s=e?aa(e):null;return s?o.some(l=>l.id===s)?s:(n??"")===ue(e,[...o],i)?null:t:t}function Cp(e,t,n=1033){const o=new Set(Object.values(wp(e.id,e.source))),i=new Set;for(const s of t)o.has(s.id)&&s.titles.forEach(l=>i.add(l.languageCode));return[...i].sort((s,l)=>s===n?-1:l===n?1:s-l)}function Ip(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 Lt=e=>e==="flyout"||e==="splitButton",la=e=>["true","1"].includes(e?.trim().toLowerCase()??"");function Ct(e){const t=[];for(const n of e.menu?.sections??[])for(const o of n.controls)t.push(o),t.push(...Ct(o));return t}function ca(e){return e.flatMap(t=>[t,...Ct(t)])}function $e(e){return ca(e.buttons)}function So(e,t){for(const n of e)for(const o of n.menu?.sections??[]){const i=o.controls.findIndex(l=>l.id===t);if(i>=0)return{parent:n,section:o,index:i};const s=So(o.controls,t);if(s)return s}}function Yn(e,t){if(!e.buttons.some(n=>n.id===t))return So(e.buttons,t)}function en(e,t){if(!e||!t)return;const n=e.buttons.find(i=>i.id===t);if(n)return n;const o=So(e.buttons,t);return o?.section.controls[o.index]}function Rp(e,t){if(!(!e||!t))return e.buttons.find(n=>n.id===t||Ct(n).some(o=>o.id===t))}function da(e,t){const n=So(e.buttons,t);return n?(n.section.controls.splice(n.index,1),!0):!1}function Ao(e){return{id:`${e}.Menu`,sections:[li(e,[])]}}function li(e,t,n){let o=t.length+1;const i=new Set(t.map(l=>l.id));for(;i.has(`${e}.MenuSection${o}`);)o++;const s=`${e}.MenuSection${o}`;return{id:s,title:n,sequence:o*10,displayMode:"Menu16",controlsId:`${s}.Controls`,controls:[]}}function jp(e,t,n,o){if(!e)return;const i=new Set,s=new Map,l=c=>{const d=s.get(c);if(d)return d;let u=c.startsWith(t)?`${n}${c.slice(t.length)}`:`${n}.${c.split(".").pop()||"Item"}`;for(let p=2;i.has(u);p++)u=`${u.replace(/_\d+$/,"")}_${p}`;return i.add(u),s.set(c,u),u},a=c=>c.replace(/(\sId=")([^"]*)(")/g,(d,u,p,f)=>`${u}${l(p)}${f}`);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=>Qn(d,l(d.id),o)),...c.rawControls?{rawControls:c.rawControls.map(d=>({...d,xml:a(d.xml)}))}:{},...c.rawContent!==void 0?{rawContent:a(c.rawContent)}:{}}))}}function $p(e,t,n){return e.replace(/(\s(?:Id|InitialItem)=")([^"]*)(")/g,(o,i,s,l)=>`${i}${s.startsWith(t)?`${n}${s.slice(t.length)}`:`${n}.${s}`}${l}`)}const Np=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand"];function Zn(e,t){return!!t&&!!e?.startsWith("$LocLabels:")&&!t.has(e.slice(11))}function Qn(e,t,n){const o=Np.filter(u=>e.source?.attributes[u]!==void 0),i=Ip(e.source),s={...i?.attributes??{},...Object.fromEntries(o.map(u=>[u,e.source.attributes[u]]))},l=u=>Fi(u)||Zn(u,n)?u:void 0,a={labelToken:l(e.source?.labelToken),tooltipTitleToken:l(e.source?.tooltipTitleToken),tooltipBodyToken:l(e.source?.tooltipBodyToken)},c=Object.fromEntries(Object.entries(a).filter(([,u])=>u!==void 0)),d=e.source?.xml?$p(e.source.xml,e.id,t):void 0;return{...e,id:t,source:Object.keys(s).length+Object.keys(c).length>0||d?{...i?.modernImage?{modernImage:i.modernImage}:{},...c,attributes:s,...d?{xml:d}:{}}:void 0,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0,menu:jp(e.menu,e.id,t,n)}}const Tp=["label","icon","image16","image32","tooltipTitle","tooltipBody","commandId","templateAlias"];function ci(e,t){for(const n of Tp)if((e[n]??"")!==(t[n]??""))return!0;return!1}function wt(e){const t=new Map,n=new Map,o=(i,s,l,a)=>{const c=n.get(i.id)??0;n.set(i.id,c+1);const d=`${i.id}#${c}`;t.set(d,a?{button:i,groupId:s,tabId:l,menu:a}:{button:i,groupId:s,tabId:l});for(const u of i.menu?.sections??[])for(const p of u.controls)o(p,s,l,{parentKey:d,parentId:i.id,sectionId:u.id,controlsId:u.controlsId})};for(const i of e.tabs)for(const s of i.groups)for(const l of s.buttons)o(l,s.id,i.id);return t}function ua(e,t){const n=wt(t),o=wt(e),i=l=>{for(let a=l.menu?.parentKey;a;a=o.get(a)?.menu?.parentKey)if(!n.has(a))return!0;return!1},s=[];for(const[l,a]of o){const c=n.get(l)?.button,d=a.button;if(i(a)){d.hidden&&s.push({entry:a,change:"hide"});continue}c?d.hidden&&!c.hidden?s.push({entry:a,change:"hide"}):ci(c,d)&&s.push({entry:a,change:"override"}):(d.hidden&&(d.oob||d.managed)||s.push({entry:a,change:"new"}),d.hidden&&s.push({entry:a,change:"hide"}))}return s}function ma(e){return e.commandId||`${e.id}.Command`}function kp(e,t){return e==="SubGrid"?`Mscrm.SubGrid.${t}.ContextualTabs._children`:"Mscrm.Tabs._children"}function pa(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 Ap(e,t,n){const o=ma(e),i=(e.tabDisplayRules??[]).map(s=>({...s,tabCommand:s.tabCommand||o}));return{...e,commandId:o,tabDisplayRules:i.length>0?i:pa(t,n,o)}}function Ex(e){const{current:t,baseline:n,commands:o,enableRules:i,displayRules:s,locLabels:l}=e,a=e.languageCode??1033,c=e.location==="Application",d=new Set,u=new Set;for(const U of n.tabs){d.add(U.id);for(const j of U.groups)u.add(j.id)}const p=wt(n),f=new Map;for(const[U,j]of wt(t))f.set(j.button,p.get(U)?.button);const h=t.tabs.filter(U=>!d.has(U.id)).map(U=>Ap(U,e.location,e.entityLogicalName)),y=[],x=[],b=[],g=[],S=[],w=U=>S.push(U),v=[],I=U=>{const j=[];for(const C of U.buttons)C.hidden||f.get(C)||(j.push(wo(C,l,w,a,!0)),v.push(C,...Ct(C)));return j},A=new Set,R=ha(t,n).steps;for(const U of h){const j=new Map(U.groups.map(C=>[C.id,I(C)]));for(const C of U.groups)for(const B of C.buttons)!B.hidden&&!f.get(B)&&A.add(B);y.push(Fp(U,t.scalingByTab?.[U.id],kp(e.location,e.entityLogicalName),j,R,w,a,l))}const k=[];for(const U of t.tabs)if(d.has(U.id)){for(const j of U.groups)if(!u.has(j.id)){for(const B of j.buttons)!B.hidden&&!f.get(B)&&A.add(B);x.push(Pp(j,U.id,I(j),w,a,l));const C=R.get(j.id);C&&k.push(ui(U.id,"MaxSize",C))}}x.push(...k);for(const{entry:U,change:j}of ua(t,n)){const{button:C,groupId:B,menu:Y}=U;if(!A.has(C))if(j==="hide")g.push(Lp(C));else if(j==="new"){const le=Y?`${Y.controlsId}._children`:`${B}.Controls._children`;b.push(Bp(C,le,l,w,a)),v.push(C,...Ct(C))}else b.push(Mp(C,l,w,a)),v.push(C)}const N=new Set;for(const U of v)for(const j of Vr(U))N.add(j);const W=[];for(const U of h){const j=U.commandId;N.add(j),o.some(C=>C.id===j)||W.push({id:j,enableRules:[],displayRules:[],actions:[]})}const X=[...o.filter(U=>N.has(U.id)&&(!Eo(U.id)||U.actions.length>0)),...W],O=new Set,T=new Set;for(const U of X)U.enableRules.forEach(j=>O.add(j)),U.displayRules.forEach(j=>T.add(j));const z=i.filter(U=>O.has(U.id)&&!Eo(U.id)),$=s.filter(U=>T.has(U.id)&&!Eo(U.id)),M=Xp(S),G=X.map(Yp).join(`
33
+ `),K=z.map(Zp).join(`
34
+ `),Q=$.map(Qp).join(`
35
+ `),P=M.map(ef).join(`
36
+ `),q=[...y,...x,...Ep(t,n,d),...b,...g],V=h.filter(U=>U.tabDisplayRules.length>0).map(U=>tf(U,c)).filter(Boolean).join(`
37
+ `);return`<RibbonDiffXml>
38
+ <CustomActions>
39
+ ${q.join(`
40
+ `)}
41
+ </CustomActions>
42
+ <Templates><RibbonTemplates Id="Mscrm.Templates"/></Templates>
43
+ <CommandDefinitions>
44
+ ${G}
45
+ </CommandDefinitions>
46
+ <RuleDefinitions>
47
+ <TabDisplayRules>
48
+ ${V}
49
+ </TabDisplayRules>
50
+ <DisplayRules>
51
+ ${Q}
52
+ </DisplayRules>
53
+ <EnableRules>
54
+ ${K}
55
+ </EnableRules>
56
+ </RuleDefinitions>
57
+ <LocLabels>
58
+ ${P}
59
+ </LocLabels>
60
+ </RibbonDiffXml>`}function Dp(e,t){const n=new Set,o=new Set;for(const y of t.tabs){n.add(y.id);for(const x of y.groups)o.add(x.id)}let i=0,s=0,l=0,a=0,c=0,d=0;for(const y of e.tabs){n.has(y.id)||a++,y.tabDisplayRules&&y.tabDisplayRules.length>0&&(d+=y.tabDisplayRules.length);for(const x of y.groups)!o.has(x.id)&&n.has(y.id)&&c++}for(const{change:y}of ua(e,t))y==="hide"?l++:y==="new"?i++:s++;const u=e.scalingByTab??{},p=t.scalingByTab??{};let f=0;for(const[y,x]of Object.entries(u))JSON.stringify(x)!==JSON.stringify(p[y])&&f++;const h=i+s+l+a+c+f>0;return{newButtons:i,overriddenButtons:s,hiddenButtons:l,newTabs:a,newGroups:c,scalingChanges:f,tabDisplayRules:d,hasAnyChange:h}}function Ep(e,t,n){const o=[],i=[];for(const[s,l]of Object.entries(e.scalingByTab??{})){if(!n.has(s))continue;const a=t.scalingByTab?.[s],c=(d,u)=>u?.some(p=>JSON.stringify(p)===JSON.stringify(d))??!1;for(const d of l.maxSizes)c(d,a?.maxSizes)||o.push(ui(s,"MaxSize",d));for(const d of l.scales)c(d,a?.scales)||i.push(ui(s,"Scale",d))}return[...o,...i]}function di(e,t){return`<${e} Id="${ae(t.id)}" GroupId="${ae(t.groupId)}" Sequence="${t.sequence}" Size="${ae(t.size)}"/>`}function ui(e,t,n){return`<CustomAction Id="${ae(n.id)}.CustomAction"
61
+ Location="${ae(e)}.Scaling._children"
62
+ Sequence="${n.sequence}">
63
+ <CommandUIDefinition>
64
+ ${di(t,n)}
65
+ </CommandUIDefinition>
66
+ </CustomAction>`}const fa={"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"},Op=Object.keys(fa);function zp(e){return fa[_i(e.template)]}function ha(e,t){const n=new Map,o=[],i=new Set(t.tabs.map(l=>l.id)),s=new Set(t.tabs.flatMap(l=>l.groups.map(a=>a.id)));for(const l of e.tabs){const a=!i.has(l.id),c=e.scalingByTab?.[l.id],d=(c?.maxSizes??[]).map(h=>h.sequence),u=(c?.scales??[]).map(h=>h.sequence),p=new Set([...d,...u]);if(a&&p.size<d.length+u.length&&o.push(`The scaling of new tab ${l.id} uses a Sequence more than once — give every MaxSize and Scale its own`),a&&d.length>0)continue;const f=Kr(d,u);for(const h of l.groups){if(!a&&s.has(h.id)||c?.maxSizes.some(b=>b.groupId===h.id))continue;const y=zp(h);if(!y)continue;const x=Jr(f,p);if(x===void 0){o.push(`No free scaling position for the new group "${h.label}" (${h.id}) on tab ${l.id}: its MaxSize must come after the tab's last MaxSize (${f.after}) and before its first Scale (${f.before}), and no Sequence is free there`);continue}p.add(x),n.set(h.id,{id:`${h.id}.MaxSize`,groupId:h.id,size:y,sequence:x})}}return{steps:n,problems:o}}function Bp(e,t,n,o,i=1033){return`<CustomAction Id="${ae(e.id)}.CustomAction"
67
+ Location="${ae(t)}"
68
+ Sequence="${e.sequence}">
69
+ <CommandUIDefinition>
70
+ ${wo(e,n,o,i,!0)}
71
+ </CommandUIDefinition>
72
+ </CustomAction>`}function Mp(e,t,n,o=1033){return`<CustomAction Id="${ae(e.id)}.Override.CustomAction"
73
+ Location="${ae(e.id)}"
74
+ Sequence="${e.sequence}">
75
+ <CommandUIDefinition>
76
+ ${wo(e,t,n,o)}
77
+ </CommandUIDefinition>
78
+ </CustomAction>`}function Lp(e,t){return`<HideCustomAction HideActionId="${ae(e.id)}.HideAction"
79
+ Location="${ae(e.id)}"/>`}function Pp(e,t,n,o,i=1033,s=[]){return`<CustomAction Id="${ae(e.id)}.CustomAction"
80
+ Location="${ae(t)}.Groups._children"
81
+ Sequence="${e.sequence}">
82
+ <CommandUIDefinition>
83
+ ${ga(e,o,n,i,s)}
84
+ </CommandUIDefinition>
85
+ </CustomAction>`}function Fp(e,t,n,o,i,s,l=1033,a=[]){const c=ba(e,s,l,a),d=e.commandId?` Command="${ae(e.commandId)}"`:"",u=e.groups.map(y=>ga(y,s,o.get(y.id)??[],l,a)).join(`
86
+ `),f=[...(t?.maxSizes.length?t.maxSizes:e.groups.map(y=>i.get(y.id)).filter(y=>!!y)).map(y=>di("MaxSize",y)),...(t?.scales??[]).map(y=>di("Scale",y))],h=f.length===0?`<Scaling Id="${ae(e.id)}.Scaling"/>`:`<Scaling Id="${ae(e.id)}.Scaling">
87
+ ${f.join(`
88
+ `)}
89
+ </Scaling>`;return`<CustomAction Id="${ae(e.id)}.CustomAction"
90
+ Location="${ae(n)}"
91
+ Sequence="${e.sequence}">
92
+ <CommandUIDefinition>
93
+ <Tab Id="${ae(e.id)}"${d} Title="${ae(c)}"${ya(e,a,s)} Sequence="${e.sequence}"${xa(e)}>
94
+ ${h}
95
+ <Groups Id="${ae(e.id)}.Groups">
96
+ ${u}
97
+ </Groups>
98
+ </Tab>
99
+ </CommandUIDefinition>
100
+ </CustomAction>`}function ga(e,t,n=[],o=1033,i=[]){const s=ba(e,t,o,i),l=_i(e.template),a=n.length===0?`<Controls Id="${ae(e.id)}.Controls"/>`:`<Controls Id="${ae(e.id)}.Controls">
101
+ ${n.join(`
102
+ `)}
103
+ </Controls>`;return`<Group Id="${ae(e.id)}" Title="${ae(s)}"${ya(e,i,t)} Sequence="${e.sequence}" Template="${ae(l)}"${xa(e)}>
104
+ ${a}
105
+ </Group>`}function ba(e,t,n,o){const i=`${e.id}.Title`;if(e.source&&e.label){const s=fn(e.label,e.source.titleToken,i,o,t,n);if(s)return s}return t({id:i,titles:[{languageCode:n,description:e.label}]}),ra(i)}function ya(e,t,n){const o=e.description,i=o?.startsWith("$LocLabels:")?t.find(s=>s.id===o.slice(11)):void 0;return i&&n(i),Z("Description",o)}const _p=new Set(["Id","Command","Title","Description","Sequence","Template"]);function xa(e){return Object.entries(e.source?.attributes??{}).filter(([t])=>!_p.has(t)&&!qi.has(t)).map(([t,n])=>` ${t}="${ae(n)}"`).join("")}function _i(e){const t=e?.trim();return t?t.includes(".")?t:`Mscrm.Templates.${t}`:"Mscrm.Templates.Flexible2"}function qp(e,t,n,o,i=1033){const s=e??"";if(s.startsWith("$LocLabels:")){const c=s.slice(11),d=n.find(u=>u.id===c);return o(d??{id:c,titles:[{languageCode:i,description:c}]}),s}if(Fi(s))return s;const l=[{languageCode:i,description:s}],a=n.find(c=>c.id===t);if(a)for(const c of a.titles)c.languageCode!==i&&l.push(c);return o({id:t,titles:l}),ra(t)}const Do=["ModernImage","Image16by16","Image32by32"],Hp={textBox:["LabelText",...Do],comboBox:["LabelText",...Do],checkBox:Do},qi=new Set(["SolutionUniqueName"]);function Wp(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 fn(e,t,n,o,i,s=1033){if(t!==void 0&&(e??"")===ue(t,o,s)){if(t.startsWith("$LocLabels:")){const c=o.find(d=>d.id===t.slice(11));c&&i(c)}return t}if(!e)return;const l=t?.startsWith("$LocLabels:")?t.slice(11):void 0,a=l&&o.some(c=>c.id===l)?l:n;return qp(e,a,o,i,s)}function Hi(e){const t=e.source,n=i=>!!i?.startsWith("$webresource:"),o=[[e.image32,"Image32by32"],[e.image16,"Image16by16"]].filter(([i,s])=>n(i)&&i!==t?.attributes[s]).map(([i])=>i);return t&&Wp(t.modernImage)===e.icon&&o.length===0?t.modernImage:o[0]??[e.image32,e.image16,e.icon].find(n)}function wo(e,t,n,o=1033,i=!1){const s=Vp(e.kind),l=e.source;if(l?.xml&&Ze(e.kind))return Kp(e,l.xml,t,n);const a=new Map;for(const[f,h]of Object.entries(l?.attributes??{}))qi.has(f)||a.set(f,h);const c=(f,h)=>h===void 0||h===""?a.delete(f):a.set(f,h);c("Id",e.id),c("Command",e.commandId||void 0),c("LabelText",fn(e.label,l?.labelToken,yo(e.id),t,n,o)??""),a.has("LabelText")||a.set("LabelText",""),c("ToolTipTitle",fn(e.tooltipTitle,l?.tooltipTitleToken,xo(e.id),t,n,o)),c("ToolTipDescription",fn(e.tooltipBody,l?.tooltipBodyToken,vo(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=f=>!!f&&(f.startsWith("$webresource:")||f.includes("/")||f.includes("."));c("ModernImage",Hi(e)),c("Image16by16",d(e.image16)?e.image16:void 0),c("Image32by32",d(e.image32)?e.image32:void 0);for(const f of Hp[e.kind]??[])a.delete(f);const u=Array.from(a.entries()).map(([f,h])=>`${f}="${ae(h)}"`).join(" "),p=i&&e.menu&&Gp.has(s)?Up(e.menu,t,n,o):"";return p?`<${s} ${u}>${p}</${s}>`:`<${s} ${u}/>`}const Gp=new Set(["FlyoutAnchor","SplitButton","ComboBox"]);function Up(e,t,n,o){const i=e.sections.map(a=>{const c=new Map(Object.entries(a.attributes??{})),d=(h,y)=>y===void 0||y===""?c.delete(h):c.set(h,y);d("Id",a.id),d("Title",fn(a.title,a.attributes?.Title,Sp(a.id),t,n,o));const u=!!a.attributes&&!("Sequence"in a.attributes)&&a.sequence===0;d("Sequence",u?void 0:String(a.sequence)),d("DisplayMode",a.displayMode);const p=Array.from(c.entries()).map(([h,y])=>` ${h}="${ae(y)}"`).join("");if(a.rawContent!==void 0)return`<MenuSection${p}>${a.rawContent}</MenuSection>`;const f=a.controls.map(h=>wo(h,t,n,o,!0));for(const h of[...a.rawControls??[]].sort((y,x)=>y.index-x.index))f.splice(Math.min(h.index,f.length),0,h.xml);return`<MenuSection${p}><Controls Id="${ae(a.controlsId)}">${f.join("")}</Controls></MenuSection>`}),s=new Map(Object.entries(e.attributes??{}));return s.set("Id",e.id),`<Menu${Array.from(s.entries()).map(([a,c])=>` ${a}="${ae(c)}"`).join("")}>${i.join("")}</Menu>`}function Eo(e){return/^(Mscrm|Microsoft)\./.test(e)}function Xp(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 Vp(e){return bn[e]??"Button"}function Kp(e,t,n,o){const i=new DOMParser().parseFromString(t,"application/xml").documentElement;for(const l of[i,...Array.from(i.getElementsByTagName("*"))])for(const a of qi)l.removeAttribute(a);i.setAttribute("Id",e.id),(i.hasAttribute("Sequence")||e.sequence!==0)&&i.setAttribute("Sequence",String(e.sequence));const s=new XMLSerializer().serializeToString(i);for(const l of s.matchAll(/\$LocLabels:([^"'\s<]+)/g)){const a=n.find(c=>c.id===l[1]);a&&o(a)}return s}function Jp(e){const t=(e??"").trim();return!t||/^\$webresource:/i.test(t)||/^https?:\/\//i.test(t)||t.startsWith("/")?t:`$webresource:${t}`}function Z(e,t){return t===void 0?"":` ${e}="${ae(String(t))}"`}function nt(e,t,n,o){return n.length===0?`<${e}${t}/>`:`<${e}${t}>
106
+ ${n.map(i=>`${o} ${i}`).join(`
107
+ `)}
108
+ ${o}</${e}>`}function va(e,t=" "){switch(e.kind){case"javascript":return nt("JavaScriptFunction",`${Z("FunctionName",e.functionName)}${Z("Library",Jp(e.library))}`,e.params.map(n=>mi(n,!1)),t);case"url":return nt("Url",`${Z("Address",e.address)}${Z("PassParams",e.passParams)}${Z("WinMode",e.winMode)}${Z("WinParams",e.winParams)}`,e.params.map(n=>mi(n,!0)),t);case"outlookCommand":return`<OutlookCommand${Z("ActionType",e.actionType)}${Z("Data",e.data)}/>`;case"raw":return e.xml;default:return""}}function Yp(e){const t=" ",n=(l,a)=>{const c=[...a];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="${ae(l)}"/>`)),i=n("DisplayRules",e.displayRules.map(l=>`<DisplayRule Id="${ae(l)}"/>`)),s=e.actions.map(l=>va(l,`${t} `)).filter(Boolean);return`<CommandDefinition Id="${ae(e.id)}">
109
+ ${t} ${nt("EnableRules","",o,`${t} `)}
110
+ ${t} ${nt("DisplayRules","",i,`${t} `)}
111
+ ${t} ${nt("Actions","",s,`${t} `)}
112
+ ${t}</CommandDefinition>`}function mi(e,t){const n=t?Z("Name",e.name??""):"";switch(e.kind){case"CrmParameter":return`<CrmParameter${n}${Z("Value",e.value)}/>`;case"BoolParameter":return`<BoolParameter${n}${Z("Value",e.value)}/>`;case"IntParameter":return`<IntParameter${n}${Z("Value",e.value)}/>`;case"DecimalParameter":return`<DecimalParameter${n}${Z("Value",e.value)}/>`;case"StringParameter":return`<StringParameter${n}${Z("Value",e.value)}/>`}}function Zp(e){return nt("EnableRule",Z("Id",e.id),e.steps.map(t=>Co(t," "))," ")}function Qp(e){return nt("DisplayRule",Z("Id",e.id),e.steps.map(t=>Co(t," "))," ")}function Co(e,t=""){if(e.kind==="RawRule")return e.xml;if(e.kind==="OrRule"){const i=e.groups.map(s=>nt("Or","",s.map(l=>Co(l,`${t} `)),`${t} `));return nt("OrRule","",i,t)}const n=`${Z("Default",e.default)}${Z("InvertResult",e.invertResult)}`,o=(i,s)=>`<${i}${s}${n}/>`;switch(e.kind){case"SelectionCountRule":return o("SelectionCountRule",`${Z("AppliesTo",e.appliesTo)}${Z("Minimum",e.minimum)}${Z("Maximum",e.maximum)}`);case"EntityRule":return o("EntityRule",`${Z("EntityName",e.entityName)}${Z("AppliesTo",e.appliesTo)}${Z("Context",e.context)}`);case"FormStateRule":return o("FormStateRule",Z("State",e.state));case"CommandClientTypeRule":return o("CommandClientTypeRule",Z("Type",e.type));case"CrmClientTypeRule":return o("CrmClientTypeRule",Z("Type",e.type));case"CustomRule":return nt("CustomRule",`${Z("FunctionName",e.functionName)}${Z("Library",e.library)}${n}`,(e.params??[]).map(i=>mi(i,!1)),t);case"FeatureControlRule":return o("FeatureControlRule",`${Z("FeatureControlBit",e.featureControlBit)}${Z("ExpectedValue",e.expectedValue)}`);case"MiscellaneousPrivilegeRule":return o("MiscellaneousPrivilegeRule",`${Z("PrivilegeName",e.privilegeName)}${Z("PrivilegeDepth",e.privilegeDepth)}`);case"FormTypeRule":return o("FormTypeRule",Z("Type",e.type));case"ValueRule":return o("ValueRule",`${Z("Field",e.field)}${Z("Value",e.value)}`);case"SkuRule":return o("SkuRule",Z("Sku",e.sku));case"HideForTabletExperienceRule":return o("HideForTabletExperienceRule","");case"OrganizationSettingRule":return o("OrganizationSettingRule",Z("Setting",e.setting));case"EntityPrivilegeRule":return o("EntityPrivilegeRule",`${Z("PrivilegeType",e.privilegeType)}${Z("PrivilegeDepth",e.privilegeDepth)}${Z("AppliesTo",e.appliesTo)}${Z("EntityName",e.entityName)}`);case"EntityPropertyRule":return o("EntityPropertyRule",`${Z("EntityName",e.entityName)}${Z("AppliesTo",e.appliesTo)}${Z("PropertyName",e.propertyName)}${Z("PropertyValue",e.propertyValue)}`);case"DeviceTypeRule":return o("DeviceTypeRule",Z("Type",e.type));case"RelationshipTypeRule":return o("RelationshipTypeRule",`${Z("AppliesTo",e.appliesTo)}${Z("RelationshipType",e.relationshipType)}${Z("AllowCustomRelationship",e.allowCustomRelationship)}${Z("AllowSystemRelationship",e.allowSystemRelationship)}`);case"RecordPrivilegeRule":return o("RecordPrivilegeRule",`${Z("PrivilegeType",e.privilegeType)}${Z("AppliesTo",e.appliesTo)}`);case"FormEntityContextRule":return o("FormEntityContextRule",Z("EntityName",e.entityName));case"PageRule":return o("PageRule",Z("Address",e.address));case"ReferencingAttributeRequiredRule":return o("ReferencingAttributeRequiredRule","");case"OutlookItemTrackingRule":return o("OutlookItemTrackingRule",`${Z("TrackedInCrm",e.trackedInCrm)}${Z("AppliesTo",e.appliesTo)}`);case"OutlookRenderTypeRule":return o("OutlookRenderTypeRule",Z("Type",e.type));case"OutlookVersionRule":return o("OutlookVersionRule",Z("Version",e.version));case"CrmOfflineAccessStateRule":return o("CrmOfflineAccessStateRule",Z("State",e.state));case"CrmOutlookClientTypeRule":return o("CrmOutlookClientTypeRule",Z("Type",e.type));case"CrmOutlookClientVersionRule":return o("CrmOutlookClientVersionRule",`${Z("Major",e.major)}${Z("Minor",e.minor)}${Z("Build",e.build)}${Z("Revision",e.revision)}`);case"OptionSetRule":return o("OptionSetRule",`${Z("OptionSet",e.optionSet)}${Z("StateCode",e.stateCode)}${Z("ObjectTypeCode",e.objectTypeCode)}`);default:{const i=e;throw new Error(`Unknown rule kind: ${i.kind}`)}}}function ef(e){const t=e.titles.map(n=>`<Title languagecode="${n.languageCode}" description="${ae(n.description)}"/>`).join(`
113
+ `);return`<LocLabel Id="${ae(e.id)}">
114
+ <Titles>
115
+ ${t}
116
+ </Titles>
117
+ </LocLabel>`}function tf(e,t){return e.tabDisplayRules.map(n=>{const o=n.rules.map(i=>i.kind==="EntityRule"?`<EntityRule${Z("EntityName",i.entityName)}${Z("AppliesTo",i.appliesTo)}${Z("Context",i.context)}/>`:i.kind==="PageRule"&&t?`<PageRule${Z("Address",i.address)}/>`:"").filter(Boolean);return o.length===0?"":`<TabDisplayRule TabCommand="${ae(n.tabCommand)}">
118
+ ${o.join(`
119
+ `)}
120
+ </TabDisplayRule>`}).filter(Boolean).join(`
121
+ `)}function ae(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ox(e){const t=e.entities??[];return`<?xml version="1.0" encoding="utf-8"?>
122
+ <ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">${t.length===0?"":`
123
+ <Entities>
124
+ ${t.map(o=>` <Entity>
125
+ <Name LocalizedName="${ae(o.localizedName)}" OriginalName="${ae(o.localizedName)}">${ae(o.schemaName)}</Name>
126
+ ${o.ribbonDiffXml}
127
+ </Entity>`).join(`
128
+ `)}
129
+ </Entities>`}
130
+ ${e.applicationRibbonDiffXml??""}
131
+ </ImportExportXml>`}function pi(e){return/^(Mscrm|Microsoft)\./.test(e)}function eo(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 nf(e,t){return t?"unmanaged":pi(e)?"oob":"unmanaged"}function Rs(e,t){for(const n of e.tabs)for(const o of n.groups)for(const i of $e(o))t.has(i.id)?eo(i,{origin:"unmanaged"}):i.origin==="unmanaged"&&eo(i,{origin:"managed"})}function vt(e){return e.origin==="unmanaged"}function Nn(e,t){return wa(Sa(t),[e])}function Sa(e){const t=new Map;for(const n of e.tabs)for(const o of n.groups)for(const i of $e(o))t.set(i.id,(t.get(i.id)??!0)&&vt(i));return t}function wa(e,t){return ca(t).every(n=>e.get(n.id)??vt(n))}function to(e,t,n){return t?n?"has"in n?n.has(e):n.includes(e):!1:!0}function Wi(e,t,n){const o=t.tabs.some(i=>i.groups.some(s=>s.id===e.id));return to(e.id,o,n)&&wa(Sa(t),e.buttons)}const Gi="Only tabs and groups your unmanaged customizations add (with a translatable title), or new ones, can be renamed";function Ca(e,t,n,o){const i=e==="tab"?n.tabs.find(l=>l.id===t):new Map(n.tabs.flatMap(l=>l.groups.map(a=>[a.id,a]))).get(t);if(!i)return!0;if(!to(t,!0,o?.containerIds))return!1;const s=/^\$LocLabels:(.+)$/.exec(i.label??"")?.[1];return!!s&&to(s,!0,o?.locLabelIds)}function Ia(e,t,n){const o=t.tabs.some(i=>i.id===e.id);return to(e.id,o,n)&&e.groups.every(i=>Wi(i,t,n))}function zx(e,t){const n=t.tabs.flatMap(l=>l.groups.flatMap(a=>$e(a))).filter(l=>l.id===e.id),o=n.find(l=>!vt(l)),i=o??n[0]??e,s=i.origin==="oob"?"the out-of-the-box ribbon":i.origin==="managed"?i.solutionName?`the managed solution "${i.solutionName}"`:"a managed solution":void 0;return o&&n.some(vt)?`The ribbon also places a button with this id from ${s??"another solution"}, and that one can't be deleted.`:s&&vt(e)?`It is your override of a button from ${s}: the original stays in the ribbon underneath it.`:s?`It comes from ${s}.`:vt(i)?"Its menu holds items from another solution.":"It comes from another solution."}function of(e,t){if(t.size!==0)for(const n of Object.keys(e))for(const o of e[n].tabs)for(const i of o.groups)for(const s of $e(i)){const l=t.get(s.id);l&&eo(s,l)}}function Io(e,t,n,o=[]){const s=new DOMParser().parseFromString(e,"application/xml"),l=s.querySelector("parsererror");if(l)throw new Error(`Ribbon XML parse error: ${l.textContent??"Unknown"}`);const a=sf(s),c=rf(s);lf(s,a);const d=new mf,u=pf(s,d),p=hf(s,d),f=gf(s,d);d.flush();const h=[...xf(s)];for(const g of o)h.some(S=>S.id===g.id)||h.push(g);const y=new Set,x=new Set;s.querySelectorAll("CustomAction").forEach(g=>{const S=g.querySelector("CommandUIDefinition");if(S?.firstElementChild){const w=S.firstElementChild.getAttribute("Id")??"";w&&y.add(w)}}),s.querySelectorAll("HideCustomAction").forEach(g=>{const S=g.getAttribute("Location")??"";S&&x.add(S)});for(const g of a)for(const S of g.groups)for(const w of $e(S)){const v=y.has(w.id);eo(w,{origin:nf(w.id,v)}),w.hidden=x.has(w.id),w.source&&(w.source.labelToken=w.source.attributes.LabelText,w.source.tooltipTitleToken=w.source.attributes.ToolTipTitle,w.source.tooltipBodyToken=w.source.attributes.ToolTipDescription),w.label=ue(w.label,h),w.tooltipTitle&&(w.tooltipTitle=ue(w.tooltipTitle,h)),w.tooltipBody&&(w.tooltipBody=ue(w.tooltipBody,h));for(const I of w.menu?.sections??[])I.title&&(I.title=ue(I.title,h))}const b=af(s,a);return{ribbon:{location:t,entityLogicalName:n,tabs:a,...Object.keys(c).length>0?{scalingByTab:c}:{},...Object.keys(b).length?{templateLayouts:b}:{}},commands:u,displayRules:f,enableRules:p,locLabels:h}}const Ra="Ribbon > Tabs > Tab, Ribbon > ContextualTabs > ContextualGroup > Tab";function js(e){const t=e.getAttribute("Description");return t===null?{}:{description:t}}function sf(e){const t=[];return e.querySelectorAll(Ra).forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const i=n.getAttribute("Title")??o,s=[];n.querySelectorAll(":scope > Groups > Group").forEach(l=>{const a=l.getAttribute("Id")??"";if(!a)return;const c=l.getAttribute("Title")??l.getAttribute("Label")??a,d=parseInt(l.getAttribute("Sequence")??"0",10),u=l.getAttribute("Template")??"",p=[];l.querySelectorAll(":scope > Controls > *").forEach(f=>{Gr[f.tagName]&&ja(f,p)}),s.push({id:a,label:c,sequence:d,template:u,...js(l),buttons:p})}),t.push({id:o,label:i,sequence:parseInt(n.getAttribute("Sequence")??"0",10),commandId:n.getAttribute("Command")??void 0,...js(n),tabDisplayRules:[],groups:s})}),t.sort((n,o)=>n.sequence-o.sequence)}function rf(e){const t={};return e.querySelectorAll(Ra).forEach(n=>{const o=n.getAttribute("Id"),i=Array.from(n.children).find(a=>a.tagName==="Scaling");if(!o||!i||t[o])return;const s=a=>({id:a.getAttribute("Id")??"",groupId:a.getAttribute("GroupId")??"",size:a.getAttribute("Size")??"",sequence:parseInt(a.getAttribute("Sequence")??"0",10)}),l=Array.from(i.children);t[o]={tabId:o,maxSizes:l.filter(a=>a.tagName==="MaxSize").map(s),scales:l.filter(a=>a.tagName==="Scale").map(s)}}),t}function af(e,t){const n=new Set(t.flatMap(i=>i.groups.map(s=>s.template)).filter(Boolean)),o={};return e.querySelectorAll("GroupTemplate").forEach(i=>{const s=i.getAttribute("Id");!s||!n.has(s)||(o[s]=Array.from(i.querySelectorAll(":scope > Layout")).map(l=>l.getAttribute("Title")??"").filter(Boolean))}),o}function lf(e,t){const n=new Map;for(const o of t)o.commandId&&n.set(o.commandId,o);e.querySelectorAll("RuleDefinitions > TabDisplayRules > TabDisplayRule").forEach(o=>{const i=o.getAttribute("TabCommand")??"",s=n.get(i);if(!s)return;const l=[];o.querySelectorAll("EntityRule").forEach(a=>{l.push({kind:"EntityRule",entityName:a.getAttribute("EntityName")??void 0,appliesTo:a.getAttribute("AppliesTo")??void 0,context:a.getAttribute("Context")??void 0})}),o.querySelectorAll("PageRule").forEach(a=>{l.push({kind:"PageRule",address:a.getAttribute("Address")??""})}),l.length>0&&s.tabDisplayRules.push({tabCommand:i,rules:l})})}function ja(e,t){const n=e.getAttribute("Id")??"";if(!n)return;const o=Gr[e.tagName]??"button",i=Ze(o),s=e.getAttribute("LabelText")??n,l=uf(e.getAttribute("ModernImage")??void 0),a=parseInt(e.getAttribute("Sequence")??"0",10),c=e.getAttribute("TemplateAlias")??"",d=e.getAttribute("Command")??"";t.push({id:n,label:s,icon:l,sequence:a,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:fi(e),...i?{xml:Gt().serializeToString(e)}:{}},menu:i?void 0:df(e)})}const cf=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]);function fi(e){return Object.fromEntries(Array.from(e.attributes).map(t=>[t.name,t.value]))}function df(e){const t=Le(e).find(i=>i.tagName==="Menu");if(!t)return;const n=fi(t),o=[];for(const i of Le(t)){if(i.tagName!=="MenuSection")continue;const s=i.getAttribute("Id")??"",l=Le(i).find(u=>u.tagName==="Controls"),a=[],c=[];Le(l).forEach((u,p)=>{cf.has(u.tagName)&&u.getAttribute("Id")?ja(u,a):c.push({index:p,xml:Gt().serializeToString(u)})});const d=fi(i);o.push({id:s,title:i.getAttribute("Title")??void 0,sequence:parseInt(i.getAttribute("Sequence")??"0",10),displayMode:i.getAttribute("DisplayMode")??void 0,controlsId:l?.getAttribute("Id")??`${s}.Controls`,controls:a,attributes:d,...c.length?{rawControls:c}:{},...l?{}:{rawContent:Le(i).map(u=>Gt().serializeToString(u)).join("")}})}return{id:t.getAttribute("Id")??`${e.getAttribute("Id")}.Menu`,sections:o,attributes:n}}function uf(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 Gt=()=>new XMLSerializer;function Le(e){return e?Array.from(e.childNodes).filter(t=>t.nodeType===Node.ELEMENT_NODE):[]}class mf{pending=[];add(t){this.pending.push(t)}flush(){for(const t of[0,1]){const n=this.pending.filter(s=>s.phase===t);if(n.length===0)continue;const o=n.map(s=>s.generate());let i=null;try{const s=Wr(`<v>${o.map(l=>`<i>${l}</i>`).join("")}</v>`);i=Le(s).map(l=>Le(l)[0])}catch{i=null}n.forEach((s,l)=>{(i?i[l]&&Wt(i[l])===Wt(s.source):sp(o[l],s.source))||s.fallback()})}this.pending=[]}}function pf(e,t){const n=[];return e.querySelectorAll("CommandDefinition").forEach(o=>{const i=o.getAttribute("Id")??"";if(!i)return;const s=Le(o),l=f=>s.find(h=>h.tagName===f),a=[],c=(f,h)=>{const y=[];return Le(l(f)).forEach((x,b)=>{const g=x.getAttribute("Id");x.tagName===h&&g&&x.attributes.length===1&&Le(x).length===0?y.push(g):a.push({container:f,index:b,xml:Gt().serializeToString(x)})}),y},d=c("EnableRules","EnableRule"),u=c("DisplayRules","DisplayRule"),p=[];Le(l("Actions")).forEach((f,h)=>{const y=ff(f);if(!y){p.push($s(f));return}p.push(y),t.add({source:f,generate:()=>va(y),fallback:()=>p[h]=$s(f),phase:0})}),n.push({id:i,enableRules:d,displayRules:u,actions:p,...a.length>0?{rawRuleRefs:a}:{}})}),n}function $s(e){return{kind:"raw",tagName:e.tagName,xml:Gt().serializeToString(e)}}function ff(e){switch(e.tagName){case"JavaScriptFunction":{const t=hi(e);return t?{kind:"javascript",library:e.getAttribute("Library")??"",functionName:e.getAttribute("FunctionName")??"",params:t}:null}case"Url":{const t=hi(e);if(!t)return null;const n=e.getAttribute("WinMode");return{kind:"url",address:e.getAttribute("Address")??"",passParams:lt(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 lt(e){if(e===null)return;const t=e.trim();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}function hi(e){const t=[];for(const n of Le(e)){const o=n.getAttribute("Name")??void 0,i=n.getAttribute("Value")??"";switch(n.tagName){case"CrmParameter":t.push({kind:"CrmParameter",name:o,value:i});break;case"BoolParameter":t.push({kind:"BoolParameter",name:o,value:lt(i)??!1});break;case"IntParameter":t.push({kind:"IntParameter",name:o,value:parseInt(i,10)});break;case"DecimalParameter":t.push({kind:"DecimalParameter",name:o,value:parseFloat(i)});break;case"StringParameter":t.push({kind:"StringParameter",name:o,value:i});break;default:return null}}return t}function hf(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > EnableRules > EnableRule").forEach(o=>{const i=o.getAttribute("Id")??"";i&&n.push({id:i,steps:Ui(o,t)})}),n}function gf(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > DisplayRules > DisplayRule").forEach(o=>{const i=o.getAttribute("Id")??"";i&&n.push({id:i,steps:Ui(o,t)})}),n}function Ui(e,t){const n=[];return Le(e).forEach((o,i)=>{const s=yf(o,t);if(!s){n.push(Ns(o));return}n.push(s),t.add({source:o,generate:()=>Co(n[i]),fallback:()=>n[i]=Ns(o),phase:s.kind==="OrRule"?1:0})}),n}function Ns(e){return{kind:"RawRule",tagName:e.tagName,xml:Gt().serializeToString(e)}}function bf(e){const t={},n=lt(e.getAttribute("Default")),o=lt(e.getAttribute("InvertResult"));return n!==void 0&&(t.default=n),o!==void 0&&(t.invertResult=o),t}function nn(e,t){const n=e.getAttribute(t);return n===null?void 0:parseInt(n,10)}function We(e,t){return e.getAttribute(t)??void 0}function pe(e,t){return e.getAttribute(t)??""}function yf(e,t){const n=bf(e);switch(e.tagName){case"OrRule":{const o=Le(e);return o.some(i=>i.tagName!=="Or")?null:{kind:"OrRule",groups:o.map(i=>Ui(i,t))}}case"SelectionCountRule":return{kind:"SelectionCountRule",minimum:nn(e,"Minimum"),maximum:nn(e,"Maximum"),appliesTo:We(e,"AppliesTo"),...n};case"EntityRule":return{kind:"EntityRule",entityName:We(e,"EntityName"),context:We(e,"Context"),appliesTo:We(e,"AppliesTo"),...n};case"FormStateRule":return{kind:"FormStateRule",state:pe(e,"State"),...n};case"CommandClientTypeRule":return{kind:"CommandClientTypeRule",type:pe(e,"Type"),...n};case"CustomRule":{const o=hi(e);return o?{kind:"CustomRule",library:pe(e,"Library"),functionName:pe(e,"FunctionName"),...o.length>0?{params:o}:{},...n}:null}case"FeatureControlRule":{const o=lt(e.getAttribute("ExpectedValue"));return o===void 0?null:{kind:"FeatureControlRule",featureControlBit:pe(e,"FeatureControlBit"),expectedValue:o,...n}}case"MiscellaneousPrivilegeRule":return{kind:"MiscellaneousPrivilegeRule",privilegeName:pe(e,"PrivilegeName"),privilegeDepth:We(e,"PrivilegeDepth"),...n};case"CrmClientTypeRule":return{kind:"CrmClientTypeRule",type:pe(e,"Type"),...n};case"FormTypeRule":return{kind:"FormTypeRule",type:pe(e,"Type"),...n};case"ValueRule":return{kind:"ValueRule",field:pe(e,"Field"),value:pe(e,"Value"),...n};case"SkuRule":return{kind:"SkuRule",sku:pe(e,"Sku"),...n};case"HideForTabletExperienceRule":return{kind:"HideForTabletExperienceRule",...n};case"OrganizationSettingRule":return{kind:"OrganizationSettingRule",setting:pe(e,"Setting"),...n};case"EntityPrivilegeRule":return{kind:"EntityPrivilegeRule",entityName:We(e,"EntityName"),appliesTo:We(e,"AppliesTo"),privilegeType:pe(e,"PrivilegeType"),privilegeDepth:pe(e,"PrivilegeDepth"),...n};case"EntityPropertyRule":{const o=lt(e.getAttribute("PropertyValue"));return o===void 0?null:{kind:"EntityPropertyRule",entityName:We(e,"EntityName"),appliesTo:We(e,"AppliesTo"),propertyName:pe(e,"PropertyName"),propertyValue:o,...n}}case"DeviceTypeRule":return{kind:"DeviceTypeRule",type:pe(e,"Type"),...n};case"OptionSetRule":return{kind:"OptionSetRule",optionSet:pe(e,"OptionSet"),stateCode:pe(e,"StateCode"),objectTypeCode:pe(e,"ObjectTypeCode"),...n};case"RecordPrivilegeRule":return{kind:"RecordPrivilegeRule",privilegeType:pe(e,"PrivilegeType"),appliesTo:We(e,"AppliesTo"),...n};case"FormEntityContextRule":return{kind:"FormEntityContextRule",entityName:pe(e,"EntityName"),...n};case"PageRule":return{kind:"PageRule",address:pe(e,"Address"),...n};case"RelationshipTypeRule":return{kind:"RelationshipTypeRule",appliesTo:"SelectedEntity",relationshipType:We(e,"RelationshipType"),allowCustomRelationship:lt(e.getAttribute("AllowCustomRelationship")),allowSystemRelationship:lt(e.getAttribute("AllowSystemRelationship")),...n};case"ReferencingAttributeRequiredRule":return{kind:"ReferencingAttributeRequiredRule",...n};case"OutlookItemTrackingRule":{const o=lt(e.getAttribute("TrackedInCrm"));return o===void 0?null:{kind:"OutlookItemTrackingRule",trackedInCrm:o,appliesTo:We(e,"AppliesTo"),...n}}case"OutlookRenderTypeRule":return{kind:"OutlookRenderTypeRule",type:pe(e,"Type"),...n};case"OutlookVersionRule":return{kind:"OutlookVersionRule",version:pe(e,"Version"),...n};case"CrmOfflineAccessStateRule":return{kind:"CrmOfflineAccessStateRule",state:pe(e,"State"),...n};case"CrmOutlookClientTypeRule":return{kind:"CrmOutlookClientTypeRule",type:pe(e,"Type"),...n};case"CrmOutlookClientVersionRule":return{kind:"CrmOutlookClientVersionRule",major:parseInt(pe(e,"Major"),10),minor:nn(e,"Minor"),build:nn(e,"Build"),revision:nn(e,"Revision"),...n};default:return null}}function xf(e){const t=[];return e.querySelectorAll("LocLabel").forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const i=[];n.querySelectorAll("Title").forEach(s=>{const l=parseInt(s.getAttribute("languagecode")??"1033",10),a=s.getAttribute("description")??"";i.push({languageCode:l,description:a})}),t.push({id:o,titles:i})}),t}function no(e){return{controlIds:[...Jn(e)],containerIds:[...ia(e)],locLabelIds:[...e.locLabels.keys()],hides:go(e),scalingStepIds:Pi(e).map(t=>t.id),commandIds:[...e.commandDefinitions.keys()],commandRefIds:[...sa(e)]}}async function Bx(e){try{return no(await gi(e))}catch{return null}}function vf(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=Io(t,"HomepageGrid","");return{commands:n.commands,enableRules:n.enableRules,displayRules:n.displayRules}}function Sf(){return window.dataverseAPI}async function Oo(e){const t=[];let n=e;for(;n;){const o=await Sf().queryData(n);t.push(...o.value??[]);const i=o["@odata.nextLink"];n=i?i.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}async function gi(e){const t=e===null?"entity eq null and ismanaged eq false":`entity eq '${e.replace(/'/g,"''")}' and ismanaged eq false`,[n,o,i]=await Promise.all([Oo(`ribbondiffs?$select=diffid,difftype,rdx,sequence&$filter=${t}&$orderby=sequence asc,diffid asc`),Oo(`ribboncommands?$select=command,commanddefinition&$filter=${t}&$orderby=command asc`),Oo(`ribbonrules?$select=ruleid,ruletype,ruledefinition&$filter=${t}&$orderby=ruleid asc`)]);return cp({diffs:n,commands:o,rules:i})}function bi(e){const t=[];for(const[n,o]of e.locLabels){const i=new DOMParser().parseFromString(o,"application/xml"),s=Array.from(i.querySelectorAll("Title")).map(l=>({languageCode:Number(l.getAttribute("languagecode")??1033),description:l.getAttribute("description")??""}));t.push({id:n,titles:s})}return t}function Ts(e,t,n,o){const s=`${Vi()}.${Pt(e)}.${Pt(t)}.${Pt(n)}`;return Ki(s,o)}function Xi(e,t,n){const i=`${Vi()}.${Pt(e)}.${Pt(t)}.Command`;return Ki(i,n)}function xn(e,t,n){const i=`${Vi()}.${Pt(e)}.${t}Rule`;return Ki(i,n)}function ks(e){return e.replace(/\.Command$/,"").split(".").pop()||"Rule"}function Vi(){try{return ie.getState().publisherPrefix||"new"}catch{return"new"}}function Pt(e){return e.replace(/[^a-zA-Z0-9._]/g,"").replace(/^[^a-zA-Z]/,"x")}function Ki(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n++;return`${e}${n}`}function $a(e,t,n,o,i){const s=o.replace(/[^a-zA-Z0-9_]/g,"")||"Button",l=`${e}.${t}.${n}.${s}`;let a=l;for(let c=2;i.has(`${a}.Button`)||i.has(`${a}.Command`);c++)a=`${l}${c}`;return{id:`${a}.Button`,commandId:`${a}.Command`}}function Mx(e){return/\s/.test(e)?"ID must not contain whitespace":e?/^[a-zA-Z]/.test(e)?null:"ID must start with a letter":"ID must not be empty"}const te=$t()(e=>({location:"HomepageGrid",tabId:"MainTab",selectedButtonId:null,selectedGroupId:null,setLocation(t){e({location:t,tabId:"MainTab",selectedButtonId:null,selectedGroupId:null})},setTabId(t){e({tabId:t,selectedButtonId:null,selectedGroupId:null})},selectGroup(t){e({selectedGroupId:t,selectedButtonId:null})},selectButton(t,n){e({selectedGroupId:t,selectedButtonId:n})},selectButtonInContext(t,n,o,i){e({location:t,tabId:n,selectedGroupId:o,selectedButtonId:i})},clearSelection(){e({selectedButtonId:null,selectedGroupId:null})}}));function Ro(e){return/\.AllEntities\./.test(e)||/\.VisualizationTab$/.test(e)}function hn(e){const t=e.filter(n=>!Ro(n.id));return(t.find(n=>/\.MainTab$/.test(n.id))??t[0]??e[0])?.id}const Be="Mscrm.OpenRecordItem",Na=["HomepageGrid","SubGrid"],wf=/\.(HomepageGrid|SubGrid)\.OpenRecordItem\d*\.Button$/;function Ta(e){return e.commandId===Be&&wf.test(e.id)}function Ji(e){const t=[];for(const n of e?.tabs??[])for(const o of n.groups)for(const i of $e(o))i.commandId===Be&&t.push({tabId:n.id,groupId:o.id,button:i});return t}function ka(e){return Ji(e).filter(t=>Ta(t.button))}function Aa(e){const t=e.button.origin;return t==="unmanaged"?"yours":t===void 0?"unknown":"theirs"}function Da(e){const t=e?.tabs??[],n=hn(t.filter(s=>s.groups.length>0)),o=t.find(s=>s.id===n),i=o?.groups.find(s=>/\.Management$/.test(s.id))??o?.groups[0];return o&&i?{tabId:o.id,groupId:i.id}:null}function Cf(){return{id:Be,enableRules:[],displayRules:[],actions:[{kind:"javascript",library:"$webresource:",functionName:"YourNamespace.openRecord",params:[{kind:"CrmParameter",value:"SelectedControlSelectedItemReferences"}]}]}}function If(e){for(const t of e.actions){if(t.kind!=="javascript")continue;if(!t.library.trim().replace(/^\$webresource:/i,"").trim()||!t.functionName.trim())return`${Be} has a JavaScript action without a web resource or function — set them in the Command Editor, or turn the override off`}return null}const Rf=["Mscrm.HideOnModern","Mscrm.ShowOnlyOnModern"];function on(e,t){const n=new Set;for(const o of[t,e.baseline])for(const i of Object.values(o??{}))for(const s of i.tabs){n.add(s.id);for(const l of s.groups){n.add(l.id);for(const a of $e(l))n.add(a.id)}}for(const o of Object.values(e.layers??{})){for(const i of o?.containerIds??[])n.add(i);for(const i of o?.controlIds??[])n.add(i)}return n}function oo(e,t){return Yi(e,t)?.containerIds}function Yi(e,t){return e.layers[t==="Application"?"application":"entity"]}function Pe(e){return JSON.parse(JSON.stringify(e))}function et(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 ve(e,t,n,o,i="info"){return{ts:new Date().toISOString(),userId:"",userName:"You",op:e,target:t,detail:n,icon:o,color:i}}let _e=null;const jf=1e3;function ke(e,t,n,o){if(_e)return _e.meta||(_e.meta=n),t;const i=e.past[e.past.length-1];if(o&&i?.coalesceKey===o&&e.future.length===0&&Date.parse(n.ts)-Date.parse(i.ts)<jf)return{...t,past:[...e.past.slice(0,-1),{...i,...n}],mutationsSincePublish:e.mutationsSincePublish+1};const s={...n,coalesceKey:o,snapshot:et(e)};return{...t,past:[...e.past,s].slice(-80),future:[],mutationsSincePublish:e.mutationsSincePublish+1}}function Se(e,t,n,o){const i=Pe(e.ribbons);return t(i),ke(e,{ribbons:i},n,o)}function qn(e){const t=(n,o)=>JSON.stringify(n)===JSON.stringify(o);return e.pendingUnhides.entity.length+e.pendingUnhides.application.length>0||e.pendingOrphanDeletes.entity.length+e.pendingOrphanDeletes.application.length>0||e.customisedCommandIds.length>0||e.uncustomisedCommandIds.entity.length+e.uncustomisedCommandIds.application.length>0||!t(e.ribbons,e.baseline)||!t(e.commands,e.baselineCommands)||!t(e.enableRules,e.baselineEnableRules)||!t(e.displayRules,e.baselineDisplayRules)||!t(e.locLabels,e.baselineLocLabels)}function sn(e,t){const n=e.findIndex(o=>o.id===t.id);return n<0?[...e,t]:JSON.stringify(e[n])===JSON.stringify(t)?null:e.map((o,i)=>i===n?t:o)}const As={entity:null,application:null},zo={entity:[],application:[]},Ds=["HomepageGrid","SubGrid","Form"];function $f(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 Nf(e,t,n){let o=t;for(;o>0&&n(e[o-1]);)o--;let i=t;for(;i<e.length-1&&n(e[i+1]);)i++;const s=o>0?e[o-1].sequence:0,l=i<e.length-1?e[i+1].sequence:1/0;if(l-s-1>=i-o+1){let d=s;for(let u=o;u<=i;u++){const p=i-u,f=e[u];f.sequence>d&&f.sequence<=l-1-p||(f.sequence=l===1/0?d+10:d+Math.max(1,Math.min(10,Math.floor((l-d)/(p+2))))),d=f.sequence}return}const a=new Set(e.filter((d,u)=>u!==t).map(d=>d.sequence));let c=(t>0?e[t-1].sequence:0)+1;for(;a.has(c);)c++;e[t].sequence=c}const Bo={HomepageGrid:{location:"HomepageGrid",entityLogicalName:"",tabs:[]},SubGrid:{location:"SubGrid",entityLogicalName:"",tabs:[]},Form:{location:"Form",entityLogicalName:"",tabs:[]},Application:{location:"Application",entityLogicalName:"",tabs:[]}};function Qe(e,t,n,o,i){const s=e[t].tabs.find(a=>a.id===n)?.groups.find(a=>a.id===o),l=en(s,i);return s&&l?{group:s,button:l}:void 0}function Fe(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob===!0&&n.custom!==!0}function Zi(e,t,n){return n.origin!=="unmanaged"&&!n.hidden&&n.kind!=="flyout"&&n.kind!=="splitButton"&&!Ze(n.kind)&&!Fe(e,t,n)}function Tf(e,t,n){for(const o of e.baseline[t].tabs)for(const i of o.groups){const s=i.buttons.find(l=>l.id===n);if(s)return s}}function kf(e,t,n){if(t.location!==n.location||t.tabId!==n.tabId||t.groupId!==n.groupId)return!1;const o=e.buttons.findIndex(s=>s.id===t.buttonId),i=e.buttons[o+1]?.id;return n.beforeButtonId?n.beforeButtonId===t.buttonId||n.beforeButtonId===i:i===void 0}const io=/^\$LocLabels:/,Hn=e=>e.labelsUnknown?void 0:new Set(e.locLabels.map(t=>t.id));function Af(e,t){if(!e)return;const n=i=>i&&(!io.test(i)||Zn(i,t))?i:void 0,o={};for(const[i,s]of Object.entries(e.attributes))i!=="Id"&&!io.test(s)&&(o[i]=s);return{...e,labelToken:n(e.labelToken),tooltipTitleToken:n(e.tooltipTitleToken),tooltipBodyToken:n(e.tooltipBodyToken),attributes:o}}const Mo=(e,t)=>({entity:e.entity.filter(n=>n!==t),application:e.application.filter(n=>n!==t)});function Es(e,t){const n=e.baselineCommands.find(i=>i.id===t),o=e.commands.find(i=>i.id===t);return!n||!o||JSON.stringify(n)===JSON.stringify(o)?e.commands:e.commands.map(i=>i.id===t?JSON.parse(JSON.stringify(n)):i)}const D=$t()(Km((e,t)=>({ribbons:Pe(Bo),baseline:Pe(Bo),baselineCommands:[],baselineEnableRules:[],baselineDisplayRules:[],baselineLocLabels:[],layers:{...As},pendingUnhides:{entity:[],application:[]},orphans:{entity:[],application:[]},pendingOrphanDeletes:{entity:[],application:[]},baseLanguageCode:1033,baseLanguageUnknown:!1,labelsUnknown:!1,customisedCommandIds:[],uncustomisedCommandIds:{entity:[],application:[]},reloadRequiredCommandIds:[],commands:[],displayRules:[],enableRules:[],locLabels:[],templates:[],conflicts:[],mutationsSincePublish:0,past:[],future:[],loadRibbons(n){e({ribbons:Pe(n),baseline:Pe(n),mutationsSincePublish:0,past:[],future:[]}),_e&&(_e={snapshot:et(t()),meta:null})},setConflicts(n){e({conflicts:n})},applyImport(n,o){e(i=>ke(i,{ribbons:{...i.ribbons,...Pe(n.ribbons)},commands:[...n.commands],enableRules:[...n.enableRules],displayRules:[...n.displayRules],locLabels:[...n.locLabels]},ve("imported","RibbonDiffXml",o,"arrow_upload","success")))},loadWorkspace(n){const o=Pe(n.ribbons);e({ribbons:o,baseline:Pe(o),commands:[...n.commands],displayRules:[...n.displayRules],enableRules:[...n.enableRules],baselineCommands:JSON.parse(JSON.stringify(n.commands)),baselineDisplayRules:JSON.parse(JSON.stringify(n.displayRules)),baselineEnableRules:JSON.parse(JSON.stringify(n.enableRules)),locLabels:[...n.locLabels],baselineLocLabels:JSON.parse(JSON.stringify(n.locLabels)),layers:{...As,...n.layers??{}},pendingUnhides:{...zo},orphans:{entity:[],application:[],...n.orphans??{}},pendingOrphanDeletes:{...zo},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:[]}),_e&&(_e={snapshot:et(t()),meta:null})},restoreWorkspace(n,o){const i=JSON.parse(JSON.stringify(n));e(s=>{const l=c=>{const d=s.layers[c];return d?i.pendingUnhides[c].filter(u=>d.hides.some(p=>p.location===u)):i.pendingUnhides[c]},a={...i,pendingUnhides:{entity:l("entity"),application:l("application")}};return JSON.stringify(et({...s,...a}))===JSON.stringify(et(s))?s:ke(s,a,ve("restored","unsaved changes",o,"history"))})},resetWorkspace(){t().loadWorkspace({ribbons:Bo,commands:[],displayRules:[],enableRules:[],locLabels:[]})},undo(){t().restore(t().past.length-1)},redo(){const n=t();if(n.future.length===0||_e)return;const[o,...i]=n.future;e({...o.snapshot,past:[...n.past,{...o,snapshot:et(n)}],future:i,mutationsSincePublish:qn({...n,...o.snapshot})?n.mutationsSincePublish+1:0})},restore(n){const o=t(),{past:i}=o;if(n<0||n>=i.length||_e)return;let s=et(o),l=o.future;for(let c=i.length-1;c>=n;c--)l=[{...i[c],coalesceKey:void 0,snapshot:s},...l],s=i[c].snapshot;const a=i.length-n;e({...s,past:i.slice(0,n),future:l,mutationsSincePublish:qn({...o,...s})?Math.max(1,o.mutationsSincePublish-a):0})},batch(n){if(_e){n();return}_e={snapshot:et(t()),meta:null};try{n()}finally{const{snapshot:o,meta:i}=_e;_e=null,i&&e(s=>({past:[...s.past,{...i,snapshot:o}].slice(-80),future:[],mutationsSincePublish:s.mutationsSincePublish+1}))}},moveButton(n,o){const i=t(),l=i.ribbons[n.location].tabs.find(p=>p.id===n.tabId)?.groups.find(p=>p.id===n.groupId),a=l?.buttons.find(p=>p.id===n.buttonId),c=i.ribbons[o.location].tabs.find(p=>p.id===o.tabId)?.groups.find(p=>p.id===o.groupId);if(!a||!l||!c)return null;const d=Tf(i,n.location,a.id)?.origin;if(d!==void 0&&d!=="unmanaged"&&!a.menu&&!Lt(a.kind)&&!Fe(n.location,n.tabId,a)){if(kf(l,n,o))return null;const p=g=>(se.getState().logWarn("ribbon",`Can't move ${a.id}: ${g}`),null);if(a.hidden)return p("it's hidden — move your copy of it instead.");if(n.location==="Application"!=(o.location==="Application"))return p("it isn't yours, and a copy can't move between the table's ribbon and the application ribbon.");const{activeSolution:f,publisherPrefix:h}=ie.getState(),y=f?.publisherPrefix?.trim()||h?.trim()||"new";let x=null,b=!1;return t().batch(()=>{const g=t().customiseButton(n.location,n.tabId,n.groupId,n.buttonId,y);g&&(b=!0,x=t().moveButton({...n,buttonId:g},o),se.getState().logInfo("ribbon",`${a.id} isn't yours, so it can't be moved: moved your copy ${g} instead and hid the original.`))}),b&&!x&&t().undo(),b?x:p("it isn't yours and can't be copied (e.g. it has an override of its command); undo the override, then move it.")}return Fe(n.location,n.tabId,a)?null:(e(p=>Se(p,f=>{const h=f[n.location].tabs.find(A=>A.id===n.tabId);if(!h)return;const y=h.groups.find(A=>A.id===n.groupId);if(!y)return;const x=y.buttons.findIndex(A=>A.id===n.buttonId);if(x===-1||Fe(n.location,n.tabId,y.buttons[x]))return;const g=(n.tabId===o.tabId&&n.location===o.location?h:f[o.location].tabs.find(A=>A.id===o.tabId))?.groups.find(A=>A.id===o.groupId);if(!g)return;const[S]=y.buttons.splice(x,1),w=o.beforeButtonId?g.buttons.findIndex(A=>A.id===o.beforeButtonId):g.buttons.length,v=w<0?g.buttons.length:w;g.buttons.splice(v,0,S);const I=$f(S.sequence,g.buttons[v-1]?.sequence,g.buttons[v+1]?.sequence);if(I!==void 0)S.sequence=I;else{const A=new Set(p.layers[o.location==="Application"?"application":"entity"]?.controlIds??[]),R=new Set(p.baseline[o.location].tabs.flatMap(k=>k.groups.flatMap(N=>N.buttons.map(W=>W.id))));Nf(g.buttons,v,k=>k===S||A.has(k.id)||!R.has(k.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"moved",target:n.buttonId,detail:`to ${o.groupId}`,icon:"arrow_move",color:"info"})),n.buttonId)},setButtonProp(n,o,i,s,l){const c=Object.values(l).every(d=>typeof d=="string")?`button:${n}:${s}:${Object.keys(l).sort().join(",")}`:void 0;e(d=>Se(d,u=>{const p=Qe(u,n,o,i,s)?.button;p&&(Fe(n,o,p)||(Object.assign(p,l),Lt(p.kind)&&!p.menu&&(p.menu=Ao(p.id))))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l.label??s,detail:Object.keys(l).join(", "),icon:"edit",color:"info"},c))},deleteButton(n,o,i,s){const l=t(),a=Qe(l.ribbons,n,o,i,s)?.button;if(a&&!Nn(a,l.baseline[n])){se.getState().logWarn("ribbon",`"${a.label}" (${s}) was not deleted: only your own buttons can be deleted — hide it instead.`);return}e(c=>Se(c,d=>{const u=Qe(d,n,o,i,s);if(!u)return;const{group:p,button:f}=u;Fe(n,o,f)||da(p,s)||(p.buttons=p.buttons.filter(h=>h.id!==s))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:s,detail:i,icon:"delete",color:"danger"}))},addMenuItem({location:n,tabId:o,groupId:i,parentId:s,sectionId:l,item:a}){e(c=>Se(c,d=>{const u=Qe(d,n,o,i,s)?.button;if(!u||Fe(n,o,u))return;u.menu=u.menu??Ao(u.id),u.menu.sections.length===0&&u.menu.sections.push(li(u.id,[]));const p=u.menu.sections.find(h=>h.id===l)??u.menu.sections[0],f=p.controls[p.controls.length-1]?.sequence??0;p.controls.push({...a,kind:a.kind??"button",sequence:a.sequence??f+10,templateAlias:a.templateAlias??"",hidden:!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:a.label,detail:`menu of ${s}`,icon:"add",color:"success"}))},addMenuSection(n,o,i,s,l){e(a=>Se(a,c=>{const d=Qe(c,n,o,i,s)?.button;!d||Fe(n,o,d)||(d.menu=d.menu??{id:`${d.id}.Menu`,sections:[]},d.menu.sections.push(li(d.id,d.menu.sections,l)))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:l??"Menu section",detail:`menu of ${s}`,icon:"add",color:"success"}))},setMenuSectionProp(n,o,i,s,l,a){e(c=>Se(c,d=>{const u=Qe(d,n,o,i,s)?.button,p=u?.menu?.sections.find(f=>f.id===l);!u||!p||Fe(n,o,u)||Object.assign(p,a)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l,detail:Object.keys(a).join(", "),icon:"edit",color:"info"}))},deleteMenuSection(n,o,i,s,l){e(a=>Se(a,c=>{const d=Qe(c,n,o,i,s)?.button;!d?.menu||Fe(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 ${s}`,icon:"delete",color:"danger"}))},duplicateButton(n,o,i,s){e(l=>Se(l,a=>{const c=Qe(a,n,o,i,s);if(c){const{group:d,button:u}=c;if(Fe(n,o,u))return;const p=Hn(l),f=Fi(u.source?.labelToken)||Zn(u.source?.labelToken,p),h={...Qn(u,`${u.id}_copy_${Date.now()}`,p),label:Ze(u.kind)||f?u.label:`${u.label} (copy)`,sequence:u.sequence+5},y=Yn(d,s),x=y?y.section.controls:d.buttons,b=x.findIndex(g=>g.id===s);x.splice(b+1,0,h)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:s,detail:i,icon:"copy",color:"info"}))},createButton({tabId:n,groupId:o,location:i,button:s}){e(l=>Se(l,a=>{const d=a[i].tabs.find(u=>u.id===n)?.groups.find(u=>u.id===o);if(d){const u=new Set(d.buttons.map(y=>y.sequence)),p=Math.max(0,...d.buttons.map(y=>y.sequence))+10,f=s.sequence!==void 0&&!u.has(s.sequence)?s.sequence:p,h={...s,id:s.id??`new_${Date.now()}`,label:s.label??"New Button",kind:s.kind??"button",sequence:f,templateAlias:s.templateAlias??"o1",commandId:s.commandId??"",hidden:s.hidden??!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"};Lt(h.kind)&&!h.menu&&(h.menu=Ao(h.id)),d.buttons.push(h)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:s.label??"New Button",detail:o,icon:"add",color:"success"}))},createGroup({tabId:n,location:o,group:i}){e(s=>Se(s,l=>{const a=l[o].tabs.find(c=>c.id===n);if(a){const c=l[o],d=o==="Application"?"global":c.entityLogicalName,u={id:i.id??Ts(d,`${o}.${i.label??"New Group"}`,"Group",on(s,l)),label:i.label??"New Group",sequence:i.sequence!==void 0&&!a.groups.some(p=>p.sequence===i.sequence)?i.sequence:Math.max(0,...a.groups.map(p=>p.sequence))+10,template:i.template??"Flexible2",buttons:i.buttons??[]};a.groups.push(u)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:i.label??"New Group",detail:n,icon:"add",color:"success"}))},renameGroup(n,o,i,s){e(l=>Se(l,a=>{const d=a[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===i);d&&(d.label=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:i,detail:s,icon:"edit",color:"info"}))},duplicateGroup(n,o,i){e(s=>Se(s,l=>{const a=l[n].tabs.find(h=>h.id===o);if(!a)return;const c=a.groups.find(h=>h.id===i);if(!c)return;const d=`_copy_${Date.now()}`,u=Hn(s),p={...JSON.parse(JSON.stringify(c)),id:`${c.id}${d}`,label:`${ue(c.label,s.locLabels,s.baseLanguageCode)} (copy)`,source:void 0,description:void 0,sequence:c.sequence+5,buttons:c.buttons.map(h=>Qn(h,`${h.id}${d}`,u))},f=a.groups.findIndex(h=>h.id===i);a.groups.splice(f+1,0,p)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:i,detail:o,icon:"copy",color:"info"}))},setGroupTemplate(n,o,i,s){e(l=>Se(l,a=>{const d=a[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===i);d&&(d.template=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:i,detail:`template → ${s}`,icon:"edit",color:"info"}))},deleteGroup(n,o,i){const s=t(),l=s.ribbons[n].tabs.find(a=>a.id===o)?.groups.find(a=>a.id===i);if(l&&!Wi(l,s.baseline[n],oo(s,n))){se.getState().logWarn("ribbon",`Group "${l.label}" (${i}) was not deleted: only your own groups, with only your own buttons in them, can be deleted — hide its buttons instead.`);return}e(a=>Se(a,c=>{const d=c[n].tabs.find(u=>u.id===o);d&&(d.groups=d.groups.filter(u=>u.id!==i))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:i,detail:o,icon:"delete",color:"danger"}))},createTab(n,o){e(i=>o.id&&on(i,i.ribbons).has(o.id)?{}:Se(i,s=>{const l=s[n],a=n==="Application"?"global":l.entityLogicalName,c=o.id??Ts(a,`${n}.${o.label??"New Tab"}`,"Tab",on(i,s)),d=ma({...o,id:c}),u={id:c,label:o.label??"New Tab",sequence:o.sequence!==void 0&&!l.tabs.some(p=>p.sequence===o.sequence)?o.sequence:Math.max(0,...l.tabs.map(p=>p.sequence))+10,commandId:d,tabDisplayRules:o.tabDisplayRules?.length?o.tabDisplayRules:pa(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,i){e(s=>Se(s,l=>{const a=l[n].tabs.find(c=>c.id===o);a&&(a.label=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:o,detail:i,icon:"edit",color:"info"}))},deleteTab(n,o){const i=t(),s=i.ribbons[n].tabs.find(l=>l.id===o);if(s&&!Ia(s,i.baseline[n],oo(i,n))){se.getState().logWarn("ribbon",`Tab "${s.label}" (${o}) was not deleted: only your own tabs, with only your own groups and buttons in them, can be deleted.`);return}e(l=>Se(l,a=>{a[n].tabs=a[n].tabs.filter(c=>c.id!==o)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:o,detail:n,icon:"delete",color:"danger"}))},reorderTabs(n,o){e(i=>Se(i,s=>{const l=s[n].tabs;s[n].tabs=o.map(a=>l.find(c=>c.id===a)).filter(a=>a!==void 0)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:"Tabs",detail:n,icon:"arrow_sort",color:"info"}))},setTabDisplayRules(n,o,i){e(s=>Se(s,l=>{const a=l[n].tabs.find(c=>c.id===o);a&&(a.tabDisplayRules=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} display rules`,detail:`${i.length} rule(s)`,icon:"eye",color:"info"}))},setScaling(n,o,i){e(s=>Se(s,l=>{const a=l[n];a.scalingByTab=a.scalingByTab??{},a.scalingByTab[o]={tabId:o,maxSizes:[...i.maxSizes],scales:[...i.scales]}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} scaling`,detail:`${i.maxSizes.length} MaxSize, ${i.scales.length} Scale`,icon:"resize",color:"info"}))},hideOobButton(n,o,i,s){e(l=>Se(l,a=>{const c=Qe(a,n,o,i,s)?.button;c&&(Fe(n,o,c)||(c.hidden=!0))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"hid",target:s,detail:i,icon:"eye_off",color:"warn"}))},customizeOobButton(n,o,i,s){e(l=>Se(l,a=>{const c=Qe(a,n,o,i,s)?.button;if(c){if(Fe(n,o,c))return;c.oob=!1,c.custom=!0,c.managed=!1,c.origin="unmanaged"}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"customized",target:s,detail:"OOB override",icon:"edit",color:"info"}))},customiseButton(n,o,i,s,l){const a=t(),c=a.ribbons[n].tabs.find(g=>g.id===o)?.groups.find(g=>g.id===i)?.buttons.find(g=>g.id===s);if(!c||!Zi(n,o,c))return null;const d=on(a,a.ribbons),u=`${(l||"new").trim()}.${c.id}`;let p=u;for(let g=2;d.has(p);g++)p=`${u}.${g}`;const f=[],h=[],y=Hn(a),x=[[c.source?.labelToken,yo(p)],[c.source?.tooltipTitleToken,xo(p)],[c.source?.tooltipBodyToken,vo(p)]];for(const[g,S]of x){if(!g||!io.test(g))continue;const w=a.locLabels.find(v=>v.id===g.replace(io,""));w?f.push({id:S,titles:w.titles.map(v=>({...v}))}):Zn(g,y)&&h.push(g)}h.length>0&&se.getState().logInfo("ribbon",`Customise button ${c.id}: ${h.join(", ")} ${h.length===1?"is":"are"} defined by another solution, so the copy ${p} uses ${h.length===1?"it":"them"} too. Edit the copy's text to give it a label of its own.`);const b=new Set(f.map(g=>g.id));return e(g=>{const S=Pe(g.ribbons),w=S[n].tabs.find(k=>k.id===o)?.groups.find(k=>k.id===i),v=w?.buttons.findIndex(k=>k.id===s)??-1;if(!w||v<0)return{};const I=w.buttons[v],A={...I,id:p,source:Af(I.source,y),hidden:!1,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0},R=w.buttons[v+1]?.sequence;return(R===void 0||I.sequence+1<R)&&(A.sequence=I.sequence+1),I.hidden=!0,w.buttons.splice(v+1,0,A),ke(g,{ribbons:S,...f.length>0?{locLabels:[...g.locLabels.filter(k=>!b.has(k.id)),...f]}:{}},ve("customised",s,`copied to ${p}, original hidden`+(h.length>0?" (keeps another solution's labels)":""),"copy"))}),p},customiseCommand(n){const o=t();return!o.commands.some(i=>i.id===n)||o.reloadRequiredCommandIds.includes(n)?!1:(e(i=>ke(i,{customisedCommandIds:[...i.customisedCommandIds.filter(s=>s!==n),n],uncustomisedCommandIds:Mo(i.uncustomisedCommandIds,n)},ve("customised",n,"command copied to your layer on publish","code"))),!0)},uncustomiseCommand(n,o){e(i=>ke(i,{commands:Es(i,n),customisedCommandIds:i.customisedCommandIds.filter(s=>s!==n),uncustomisedCommandIds:{...Mo(i.uncustomisedCommandIds,n),[o]:[...i.uncustomisedCommandIds[o].filter(s=>s!==n),n]}},ve("uncustomised",n,`command removed from the ${o==="entity"?"table's":"application ribbon's"} layer on publish`,"arrow_undo")))},discardCommandChanges(n){const o=t(),i=Es(o,n);(i!==o.commands||o.customisedCommandIds.includes(n)||o.uncustomisedCommandIds.entity.includes(n)||o.uncustomisedCommandIds.application.includes(n))&&e(l=>ke(l,{commands:i,customisedCommandIds:l.customisedCommandIds.filter(a=>a!==n),uncustomisedCommandIds:Mo(l.uncustomisedCommandIds,n)},ve("discarded",n,"command changes","arrow_undo")))},setOpenRecordOverride(n,o,i){if(!Na.includes(n))return!1;const s=t(),l=s.ribbons[n],a=ka(l);if(o){if(a.length>0)return!0;const c=Da(l);if(!c)return!1;const d=on(s,s.ribbons);for(const p of s.commands)d.add(p.id);const{id:u}=$a(i,l.entityLogicalName,n,"OpenRecordItem",d);return t().batch(()=>{t().createButton({location:n,tabId:c.tabId,groupId:c.groupId,button:{id:u,label:"Open record",tooltipTitle:"Open record",tooltipBody:`Runs the table's ${Be} action for the selected row, as opening a row does.`,kind:"button",templateAlias:"o1",commandId:Be,hidden:!1,oob:!1,custom:!0,managed:!1}}),t().commands.some(p=>p.id===Be)||t().upsertCommand(Cf())}),!0}return a.length===0?!0:a.some(c=>Aa(c)!=="yours")?!1:(t().batch(()=>{for(const u of a)t().deleteButton(n,u.tabId,u.groupId,u.button.id);const c=t();!Object.values(c.ribbons).some(u=>Ji(u).length>0)&&!c.baselineCommands.some(u=>u.id===Be)&&e(u=>ke(u,{commands:u.commands.filter(p=>p.id!==Be)},ve("removed",Be,"grid open override","delete","danger")))}),!0)},hideWithDisplayRules(n){const o=n?t().commands.find(s=>s.id===n):void 0;if(!o)return!1;const i=[...o.displayRules];for(const s of Rf)i.includes(s)||i.push(s);return e(s=>{const l=sn(s.commands,{...o,displayRules:i});return l?ke(s,{commands:l},ve("hid",o.id,"with display rules","eye_off","warn")):s}),!0},upsertCommand(n){e(o=>{const i=sn(o.commands,n);if(!i)return o;const s=i.length>o.commands.length;return ke(o,{commands:i},s?ve("added",n.id,"command","add","success"):ve("edited",n.id,"command","edit"),s?void 0:`command:${n.id}`)})},renameCommandId(n,o){const i=t();return!n||!o||n===o?!0:i.commands.some(s=>s.id===o)?!1:(e(s=>{const l=Pe(s.ribbons);for(const c of Object.keys(l))for(const d of l[c].tabs)for(const u of d.groups)for(const p of $e(u))p.commandId===n&&(p.commandId=o),p.source?.xml&&(p.source.xml=ap(p.source.xml,n,o));const a=s.commands.map(c=>c.id===n?{...c,id:o}:c);return ke(s,{ribbons:l,commands:a},ve("renamed",n,`command -> ${o}`,"edit"))}),!0)},upsertDisplayRule(n){e(o=>{const i=sn(o.displayRules,n);if(!i)return o;const s=i.length>o.displayRules.length;return ke(o,{displayRules:i},s?ve("added",n.id,"display rule","add","success"):ve("edited",n.id,"display rule","edit"),s?void 0:`displayRule:${n.id}`)})},renameDisplayRuleId(n,o){const i=t();return!n||!o||n===o?!0:i.displayRules.some(s=>s.id===o)?!1:(e(s=>{const l=s.displayRules.map(c=>c.id===n?{...c,id:o}:c),a=s.commands.map(c=>({...c,displayRules:c.displayRules.map(d=>d===n?o:d)}));return ke(s,{displayRules:l,commands:a},ve("renamed",n,`display rule -> ${o}`,"edit"))}),!0)},upsertEnableRule(n){e(o=>{const i=sn(o.enableRules,n);if(!i)return o;const s=i.length>o.enableRules.length;return ke(o,{enableRules:i},s?ve("added",n.id,"enable rule","add","success"):ve("edited",n.id,"enable rule","edit"),s?void 0:`enableRule:${n.id}`)})},renameEnableRuleId(n,o){const i=t();return!n||!o||n===o?!0:i.enableRules.some(s=>s.id===o)?!1:(e(s=>{const l=s.enableRules.map(c=>c.id===n?{...c,id:o}:c),a=s.commands.map(c=>({...c,enableRules:c.enableRules.map(d=>d===n?o:d)}));return ke(s,{enableRules:l,commands:a},ve("renamed",n,`enable rule -> ${o}`,"edit"))}),!0)},upsertLocLabel(n){e(o=>{const i=sn(o.locLabels,n);return i?ke(o,{locLabels:i},ve("edited",n.id,"label","translate"),`locLabel:${n.id}`):o})},setLayerHideUnhidden(n,o,i){e(s=>{if(s.pendingUnhides[n].includes(o)===i)return s;const l=s.pendingUnhides[n].filter(a=>a!==o);return i&&l.push(o),ke(s,{pendingUnhides:{...s.pendingUnhides,[n]:l}},i?ve("un-hid",o,"on publish","eye"):ve("kept hidden",o,"by customizations","eye_off"))})},setOrphanDeleted(n,o,i){e(s=>{const l=s.orphans[n].find(c=>c.id===o);if(!l||i&&l.recentPublish?.published||s.pendingOrphanDeletes[n].includes(o)===i)return s;const a=s.pendingOrphanDeletes[n].filter(c=>c!==o);return i&&a.push(o),ke(s,{pendingOrphanDeletes:{...s.pendingOrphanDeletes,[n]:a}},i?ve("deleted",o,"not on the canvas — removed on publish","delete","danger"):ve("kept",o,"not on the canvas","arrow_undo"))})},setLayerSnapshot(n,o){e(i=>({layers:{...i.layers,[n]:o}}))},markPublished(n,o){e(i=>{const s=Object.keys(i.ribbons),l=n??s,a=Pe(i.baseline),c=Pe(i.ribbons);let d=i.locLabels,u=i.baselineLocLabels;const p=(T,z)=>[...T.filter($=>!z.some(M=>M.id===$.id)),...z];for(const[T,z]of Object.entries(o??{})){const $=T==="entity"?Ds:["Application"];for(const G of $)l.includes(G)&&xp(c[G],z);const M=bi(z);d=p(d,M),u=p(u,JSON.parse(JSON.stringify(M)))}for(const T of l)a[T]=Pe(c)[T];const f=s.every(T=>l.includes(T)),h={...i.layers},y={...i.pendingUnhides},x={entity:[],application:[]},b=[["entity",Ds.every(T=>l.includes(T))],["application",l.includes("Application")]];for(const[T,z]of b){const $=o?.[T];if(!z||!$)continue;const M=h[T],G=(K,Q)=>[...new Set([...K,...Q])];h[T]=M?{...M,containerIds:G(M.containerIds,ia($)),controlIds:G(M.controlIds,Jn($)),locLabelIds:G(M.locLabelIds,new Set($.locLabels.keys()))}:no($)}for(const[T,z]of b){if(!z||y[T].length===0)continue;const $=h[T];$&&(h[T]={...$,hides:$.hides.filter(M=>!y[T].includes(M.location))}),x[T]=y[T],y[T]=[]}const g={...i.orphans},S={...i.pendingOrphanDeletes},w={entity:[],application:[]};for(const[T,z]of b)!z||S[T].length===0||(g[T]=g[T].filter($=>!S[T].includes($.id)),w[T]=S[T],S[T]=[]);const v={...i.uncustomisedCommandIds},I=[...i.reloadRequiredCommandIds],A={entity:[],application:[]};for(const[T,z]of b)if(z){for(const $ of v[T])I.includes($)||I.push($);A[T]=v[T],v[T]=[]}const R=(T,z)=>({entity:T.entity.filter($=>!z.entity.includes($)),application:T.application.filter($=>!z.application.includes($))}),k=T=>({...T,snapshot:{...T.snapshot,pendingUnhides:R(T.snapshot.pendingUnhides,x),pendingOrphanDeletes:R(T.snapshot.pendingOrphanDeletes??zo,w),uncustomisedCommandIds:R(T.snapshot.uncustomisedCommandIds,A)}}),N=[x,A,w].reduce((T,z)=>T+z.entity.length+z.application.length,0)>0,W=i.past.map((T,z)=>{const $=N?k(T):T;return z===i.past.length-1&&$.coalesceKey?{...$,coalesceKey:void 0}:$}),X={ribbons:c,locLabels:d,baselineLocLabels:u,baseline:a,layers:h,pendingUnhides:y,uncustomisedCommandIds:v,orphans:g,pendingOrphanDeletes:S,...f?{baselineCommands:JSON.parse(JSON.stringify(i.commands)),baselineEnableRules:JSON.parse(JSON.stringify(i.enableRules)),baselineDisplayRules:JSON.parse(JSON.stringify(i.displayRules)),baselineLocLabels:JSON.parse(JSON.stringify(d)),customisedCommandIds:[]}:{}},O=qn({...i,...X});return{...X,past:W,future:N?i.future.map(k):i.future,reloadRequiredCommandIds:I,mutationsSincePublish:O?Math.max(1,i.mutationsSincePublish):0}})}})));Xm(()=>{D.getState().resetWorkspace(),te.getState().clearSelection()});var Ie=Uint8Array,He=Uint16Array,Qi=Int32Array,jo=new Ie([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]),$o=new Ie([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]),yi=new Ie([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ea=function(e,t){for(var n=new He(31),o=0;o<31;++o)n[o]=t+=1<<e[o-1];for(var i=new Qi(n[30]),o=1;o<30;++o)for(var s=n[o];s<n[o+1];++s)i[s]=s-n[o]<<5|o;return{b:n,r:i}},Oa=Ea(jo,2),za=Oa.b,xi=Oa.r;za[28]=258,xi[258]=28;var Ba=Ea($o,0),Df=Ba.b,Os=Ba.r,vi=new He(32768);for(var ye=0;ye<32768;++ye){var ut=(ye&43690)>>1|(ye&21845)<<1;ut=(ut&52428)>>2|(ut&13107)<<2,ut=(ut&61680)>>4|(ut&3855)<<4,vi[ye]=((ut&65280)>>8|(ut&255)<<8)>>1}var ot=(function(e,t,n){for(var o=e.length,i=0,s=new He(t);i<o;++i)e[i]&&++s[e[i]-1];var l=new He(t);for(i=1;i<t;++i)l[i]=l[i-1]+s[i-1]<<1;var a;if(n){a=new He(1<<t);var c=15-t;for(i=0;i<o;++i)if(e[i])for(var d=i<<4|e[i],u=t-e[i],p=l[e[i]-1]++<<u,f=p|(1<<u)-1;p<=f;++p)a[vi[p]>>c]=d}else for(a=new He(o),i=0;i<o;++i)e[i]&&(a[i]=vi[l[e[i]-1]++]>>15-e[i]);return a}),bt=new Ie(288);for(var ye=0;ye<144;++ye)bt[ye]=8;for(var ye=144;ye<256;++ye)bt[ye]=9;for(var ye=256;ye<280;++ye)bt[ye]=7;for(var ye=280;ye<288;++ye)bt[ye]=8;var vn=new Ie(32);for(var ye=0;ye<32;++ye)vn[ye]=5;var Ef=ot(bt,9,0),Of=ot(bt,9,1),zf=ot(vn,5,0),Bf=ot(vn,5,1),Lo=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Xe=function(e,t,n){var o=t/8|0;return(e[o]|e[o+1]<<8)>>(t&7)&n},Po=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},es=function(e){return(e+7)/8|0},Tn=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Ie(e.subarray(t,n))},Mf=["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"],ze=function(e,t,n){var o=new Error(t||Mf[e]);if(o.code=e,Error.captureStackTrace&&Error.captureStackTrace(o,ze),!n)throw o;return o},Lf=function(e,t,n,o){var i=e.length,s=o?o.length:0;if(!i||t.f&&!t.l)return n||new Ie(0);var l=!n,a=l||t.i!=2,c=t.i;l&&(n=new Ie(i*3));var d=function(Ee){var E=n.length;if(Ee>E){var H=new Ie(Math.max(E*2,Ee));H.set(n),n=H}},u=t.f||0,p=t.p||0,f=t.b||0,h=t.l,y=t.d,x=t.m,b=t.n,g=i*8;do{if(!h){u=Xe(e,p,1);var S=Xe(e,p+1,3);if(p+=3,S)if(S==1)h=Of,y=Bf,x=9,b=5;else if(S==2){var A=Xe(e,p,31)+257,R=Xe(e,p+10,15)+4,k=A+Xe(e,p+5,31)+1;p+=14;for(var N=new Ie(k),W=new Ie(19),X=0;X<R;++X)W[yi[X]]=Xe(e,p+X*3,7);p+=R*3;for(var O=Lo(W),T=(1<<O)-1,z=ot(W,O,1),X=0;X<k;){var $=z[Xe(e,p,T)];p+=$&15;var w=$>>4;if(w<16)N[X++]=w;else{var M=0,G=0;for(w==16?(G=3+Xe(e,p,3),p+=2,M=N[X-1]):w==17?(G=3+Xe(e,p,7),p+=3):w==18&&(G=11+Xe(e,p,127),p+=7);G--;)N[X++]=M}}var K=N.subarray(0,A),Q=N.subarray(A);x=Lo(K),b=Lo(Q),h=ot(K,x,1),y=ot(Q,b,1)}else ze(1);else{var w=es(p)+4,v=e[w-4]|e[w-3]<<8,I=w+v;if(I>i){c&&ze(0);break}a&&d(f+v),n.set(e.subarray(w,I),f),t.b=f+=v,t.p=p=I*8,t.f=u;continue}if(p>g){c&&ze(0);break}}a&&d(f+131072);for(var P=(1<<x)-1,q=(1<<b)-1,V=p;;V=p){var M=h[Po(e,p)&P],U=M>>4;if(p+=M&15,p>g){c&&ze(0);break}if(M||ze(2),U<256)n[f++]=U;else if(U==256){V=p,h=null;break}else{var j=U-254;if(U>264){var X=U-257,C=jo[X];j=Xe(e,p,(1<<C)-1)+za[X],p+=C}var B=y[Po(e,p)&q],Y=B>>4;B||ze(3),p+=B&15;var Q=Df[Y];if(Y>3){var C=$o[Y];Q+=Po(e,p)&(1<<C)-1,p+=C}if(p>g){c&&ze(0);break}a&&d(f+131072);var le=f+j;if(f<Q){var _=s-Q,ce=Math.min(Q,le);for(_+f<0&&ze(3);f<ce;++f)n[f]=o[_+f]}for(;f<le;++f)n[f]=n[f-Q]}}t.l=h,t.p=V,t.b=f,t.f=u,h&&(u=1,t.m=x,t.d=y,t.n=b)}while(!u);return f!=n.length&&l?Tn(n,0,f):n.subarray(0,f)},it=function(e,t,n){n<<=t&7;var o=t/8|0;e[o]|=n,e[o+1]|=n>>8},rn=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},Fo=function(e,t){for(var n=[],o=0;o<e.length;++o)e[o]&&n.push({s:o,f:e[o]});var i=n.length,s=n.slice();if(!i)return{t:La,l:0};if(i==1){var l=new Ie(n[0].s+1);return l[n[0].s]=1,{t:l,l:1}}n.sort(function(I,A){return I.f-A.f}),n.push({s:-1,f:25001});var a=n[0],c=n[1],d=0,u=1,p=2;for(n[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=i-1;)a=n[n[d].f<n[p].f?d++:p++],c=n[d!=u&&n[d].f<n[p].f?d++:p++],n[u++]={s:-1,f:a.f+c.f,l:a,r:c};for(var f=s[0].s,o=1;o<i;++o)s[o].s>f&&(f=s[o].s);var h=new He(f+1),y=Si(n[u-1],h,0);if(y>t){var o=0,x=0,b=y-t,g=1<<b;for(s.sort(function(A,R){return h[R.s]-h[A.s]||A.f-R.f});o<i;++o){var S=s[o].s;if(h[S]>t)x+=g-(1<<y-h[S]),h[S]=t;else break}for(x>>=b;x>0;){var w=s[o].s;h[w]<t?x-=1<<t-h[w]++-1:++o}for(;o>=0&&x;--o){var v=s[o].s;h[v]==t&&(--h[v],++x)}y=t}return{t:new Ie(h),l:y}},Si=function(e,t,n){return e.s==-1?Math.max(Si(e.l,t,n+1),Si(e.r,t,n+1)):t[e.s]=n},zs=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new He(++t),o=0,i=e[0],s=1,l=function(c){n[o++]=c},a=1;a<=t;++a)if(e[a]==i&&a!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)l(32754);s>2&&(l(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(l(i),--s;s>6;s-=6)l(8304);s>2&&(l(s-3<<5|8208),s=0)}for(;s--;)l(i);s=1,i=e[a]}return{c:n.subarray(0,o),n:t}},an=function(e,t){for(var n=0,o=0;o<t.length;++o)n+=e[o]*t[o];return n},Ma=function(e,t,n){var o=n.length,i=es(t+2);e[i]=o&255,e[i+1]=o>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var s=0;s<o;++s)e[i+s+4]=n[s];return(i+4+o)*8},Bs=function(e,t,n,o,i,s,l,a,c,d,u){it(t,u++,n),++i[256];for(var p=Fo(i,15),f=p.t,h=p.l,y=Fo(s,15),x=y.t,b=y.l,g=zs(f),S=g.c,w=g.n,v=zs(x),I=v.c,A=v.n,R=new He(19),k=0;k<S.length;++k)++R[S[k]&31];for(var k=0;k<I.length;++k)++R[I[k]&31];for(var N=Fo(R,7),W=N.t,X=N.l,O=19;O>4&&!W[yi[O-1]];--O);var T=d+5<<3,z=an(i,bt)+an(s,vn)+l,$=an(i,f)+an(s,x)+l+14+3*O+an(R,W)+2*R[16]+3*R[17]+7*R[18];if(c>=0&&T<=z&&T<=$)return Ma(t,u,e.subarray(c,c+d));var M,G,K,Q;if(it(t,u,1+($<z)),u+=2,$<z){M=ot(f,h,0),G=f,K=ot(x,b,0),Q=x;var P=ot(W,X,0);it(t,u,w-257),it(t,u+5,A-1),it(t,u+10,O-4),u+=14;for(var k=0;k<O;++k)it(t,u+3*k,W[yi[k]]);u+=3*O;for(var q=[S,I],V=0;V<2;++V)for(var U=q[V],k=0;k<U.length;++k){var j=U[k]&31;it(t,u,P[j]),u+=W[j],j>15&&(it(t,u,U[k]>>5&127),u+=U[k]>>12)}}else M=Ef,G=bt,K=zf,Q=vn;for(var k=0;k<a;++k){var C=o[k];if(C>255){var j=C>>18&31;rn(t,u,M[j+257]),u+=G[j+257],j>7&&(it(t,u,C>>23&31),u+=jo[j]);var B=C&31;rn(t,u,K[B]),u+=Q[B],B>3&&(rn(t,u,C>>5&8191),u+=$o[B])}else rn(t,u,M[C]),u+=G[C]}return rn(t,u,M[256]),u+G[256]},Pf=new Qi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),La=new Ie(0),Ff=function(e,t,n,o,i,s){var l=s.z||e.length,a=new Ie(o+l+5*(1+Math.ceil(l/7e3))+i),c=a.subarray(o,a.length-i),d=s.l,u=(s.r||0)&7;if(t){u&&(c[0]=s.r>>3);for(var p=Pf[t-1],f=p>>13,h=p&8191,y=(1<<n)-1,x=s.p||new He(32768),b=s.h||new He(y+1),g=Math.ceil(n/3),S=2*g,w=function(oe){return(e[oe]^e[oe+1]<<g^e[oe+2]<<S)&y},v=new Qi(25e3),I=new He(288),A=new He(32),R=0,k=0,N=s.i||0,W=0,X=s.w||0,O=0;N+2<l;++N){var T=w(N),z=N&32767,$=b[T];if(x[z]=$,b[T]=z,X<=N){var M=l-N;if((R>7e3||W>24576)&&(M>423||!d)){u=Bs(e,c,0,v,I,A,k,W,O,N-O,u),W=R=k=0,O=N;for(var G=0;G<286;++G)I[G]=0;for(var G=0;G<30;++G)A[G]=0}var K=2,Q=0,P=h,q=z-$&32767;if(M>2&&T==w(N-q))for(var V=Math.min(f,M)-1,U=Math.min(32767,N),j=Math.min(258,M);q<=U&&--P&&z!=$;){if(e[N+K]==e[N+K-q]){for(var C=0;C<j&&e[N+C]==e[N+C-q];++C);if(C>K){if(K=C,Q=q,C>V)break;for(var B=Math.min(q,C-2),Y=0,G=0;G<B;++G){var le=N-q+G&32767,_=x[le],ce=le-_&32767;ce>Y&&(Y=ce,$=le)}}}z=$,$=x[z],q+=z-$&32767}if(Q){v[W++]=268435456|xi[K]<<18|Os[Q];var Ee=xi[K]&31,E=Os[Q]&31;k+=jo[Ee]+$o[E],++I[257+Ee],++A[E],X=N+K,++R}else v[W++]=e[N],++I[e[N]]}}for(N=Math.max(N,X);N<l;++N)v[W++]=e[N],++I[e[N]];u=Bs(e,c,d,v,I,A,k,W,O,N-O,u),d||(s.r=u&7|c[u/8|0]<<3,u-=7,s.h=b,s.p=x,s.i=N,s.w=X)}else{for(var N=s.w||0;N<l+d;N+=65535){var H=N+65535;H>=l&&(c[u/8|0]=d,H=l),u=Ma(c,u+1,e.subarray(N,H))}s.i=l}return Tn(a,0,o+es(u)+i)},_f=(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})(),qf=function(){var e=-1;return{p:function(t){for(var n=e,o=0;o<t.length;++o)n=_f[n&255^t[o]]^n>>>8;e=n},d:function(){return~e}}},Hf=function(e,t,n,o,i){if(!i&&(i={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),l=new Ie(s.length+e.length);l.set(s),l.set(e,s.length),e=l,i.w=s.length}return Ff(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,o,i)},Pa=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},tt=function(e,t){return e[t]|e[t+1]<<8},Ge=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},_o=function(e,t){return Ge(e,t)+Ge(e,t+4)*4294967296},De=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Fa(e,t){return Hf(e,t||{},0,0)}function _a(e,t){return Lf(e,{i:2},t&&t.out,t&&t.dictionary)}var qa=function(e,t,n,o){for(var i in e){var s=e[i],l=t+i,a=o;Array.isArray(s)&&(a=Pa(o,s[1]),s=s[0]),ArrayBuffer.isView(s)?n[l]=[s,a]:(n[l+="/"]=[new Ie(0),a],qa(s,l,n,o))}},Ms=typeof TextEncoder<"u"&&new TextEncoder,wi=typeof TextDecoder<"u"&&new TextDecoder,Wf=0;try{wi.decode(La,{stream:!0}),Wf=1}catch{}var Gf=function(e){for(var t="",n=0;;){var o=e[n++],i=(o>127)+(o>223)+(o>239);if(n+i>e.length)return{s:t,r:Tn(e,n-1)};i?i==3?(o=((o&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|o>>10,56320|o&1023)):i&1?t+=String.fromCharCode((o&31)<<6|e[n++]&63):t+=String.fromCharCode((o&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(o)}};function so(e,t){if(t){for(var n=new Ie(e.length),o=0;o<e.length;++o)n[o]=e.charCodeAt(o);return n}if(Ms)return Ms.encode(e);for(var i=e.length,s=new Ie(e.length+(e.length>>1)),l=0,a=function(u){s[l++]=u},o=0;o<i;++o){if(l+5>s.length){var c=new Ie(l+8+(i-o<<1));c.set(s),s=c}var d=e.charCodeAt(o);d<128||t?a(d):d<2048?(a(192|d>>6),a(128|d&63)):d>55295&&d<57344?(d=65536+(d&1047552)|e.charCodeAt(++o)&1023,a(240|d>>18),a(128|d>>12&63),a(128|d>>6&63),a(128|d&63)):(a(224|d>>12),a(128|d>>6&63),a(128|d&63))}return Tn(s,0,l)}function Sn(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(wi)return wi.decode(e);var i=Gf(e),s=i.s,n=i.r;return n.length&&ze(8),s}}var Uf=function(e,t){return t+30+tt(e,t+26)+tt(e,t+28)},Xf=function(e,t,n){var o=tt(e,t+28),i=tt(e,t+30),s=Sn(e.subarray(t+46,t+46+o),!(tt(e,t+8)&2048)),l=t+46+o,a=Vf(e,l,i,n,Ge(e,t+20),Ge(e,t+24),Ge(e,t+42)),c=a[0],d=a[1],u=a[2];return[tt(e,t+10),c,d,s,l+i+tt(e,t+32),u]},Vf=function(e,t,n,o,i,s,l){var a=i==4294967295,c=s==4294967295,d=l==4294967295,u=t+n,p=a+c+d;if(o&&p){for(;t+4<u;t+=4+tt(e,t+2))if(tt(e,t)==1)return[a?_o(e,t+4+8*c):i,c?_o(e,t+4):s,d?_o(e,t+4+8*(c+a)):l,1];o<2&&ze(13)}return[i,s,l,0]},Ci=function(e){var t=0;if(e)for(var n in e){var o=e[n].length;o>65535&&ze(9),t+=o+4}return t},Ls=function(e,t,n,o,i,s,l,a){var c=o.length,d=n.extra,u=a&&a.length,p=Ci(d);De(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|(s<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),h=f.getFullYear()-1980;if((h<0||h>119)&&ze(10),De(e,t,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,s!=-1&&(De(e,t,n.crc),De(e,t+4,s<0?-s-2:s),De(e,t+8,n.size)),De(e,t+12,c),De(e,t+14,p),t+=16,l!=null&&(De(e,t,u),De(e,t+6,n.attrs),De(e,t+10,l),t+=14),e.set(o,t),t+=c,p)for(var y in d){var x=d[y],b=x.length;De(e,t,+y),De(e,t+2,b),e.set(x,t+4),t+=4+b}return u&&(e.set(a,t),t+=u),t},Kf=function(e,t,n,o,i){De(e,t,101010256),De(e,t+8,n),De(e,t+10,n),De(e,t+12,o),De(e,t+16,i)};function Lx(e,t){t||(t={});var n={},o=[];qa(e,"",n,t);var i=0,s=0;for(var l in n){var a=n[l],c=a[0],d=a[1],u=d.level==0?0:8,p=so(l),f=p.length,h=d.comment,y=h&&so(h),x=y&&y.length,b=Ci(d.extra);f>65535&&ze(11);var g=u?Fa(c,d):c,S=g.length,w=qf();w.p(c),o.push(Pa(d,{size:c.length,crc:w.d(),c:g,f:p,m:y,u:f!=l.length||y&&h.length!=x,o:i,compression:u})),i+=30+f+b+S,s+=76+2*(f+b)+(x||0)+S}for(var v=new Ie(s+22),I=i,A=s-i,R=0;R<o.length;++R){var p=o[R];Ls(v,p.o,p,p.f,p.u,p.c.length);var k=30+p.f.length+Ci(p.extra);v.set(p.c,p.o+k),Ls(v,i,p,p.f,p.u,p.c.length,p.o,p.m),i+=16+k+(p.m?p.m.length:0)}return Kf(v,i,o.length,A,I),v}function Jf(e,t){for(var n={},o=e.length-22;Ge(e,o)!=101010256;--o)(!o||e.length-o>65558)&&ze(13);var i=tt(e,o+8);if(!i)return{};var s=Ge(e,o+16),l=Ge(e,o-20)==117853008;if(l){var a=Ge(e,o-12);l=Ge(e,a)==101075792,l&&(i=Ge(e,a+32),s=Ge(e,a+48))}for(var c=0;c<i;++c){var d=Xf(e,s,l),u=d[0],p=d[1],f=d[2],h=d[3],y=d[4],x=d[5],b=Uf(e,x);s=y,u?u==8?n[h]=_a(e.subarray(b,b+p),{out:new Ie(f)}):ze(14,"unknown compression type "+u):n[h]=Tn(e,b,b+p)}return n}const ts=4,Ha=30,Wa=`cbs:draft:v${ts}:`,Yf=["cbs:ribbon:","cbs:draft:"],Ft={commands:"baselineCommands",enableRules:"baselineEnableRules",displayRules:"baselineDisplayRules",locLabels:"baselineLocLabels"},ns=["HomepageGrid","SubGrid","Form","Application"];function Ga(e){return{orgUrl:e.orgUrl.trim().replace(/\/+$/,"").toLowerCase(),solutionId:e.solutionId.trim().toLowerCase(),entityLogicalName:e.entityLogicalName.trim().toLowerCase()}}function wn(e){const t=Ga(e);return`${Wa}${encodeURIComponent(t.orgUrl)}:${encodeURIComponent(t.solutionId)}:${encodeURIComponent(t.entityLogicalName)}`}function Ii(e,t){return!e||!t?!1:wn(e)===wn(t)}function Zf(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 En=null;function Ua(e){const t=[e.baseline,e.baselineCommands,e.baselineEnableRules,e.baselineDisplayRules,e.baselineLocLabels,e.layers,e.baseLanguageCode];if(En&&En.of.every((o,i)=>o===t[i]))return En.value;const n=Zf(JSON.stringify(t));return En={of:t,value:n},n}const Ps=new WeakMap;function On(e){let t=Ps.get(e);return t===void 0&&(t=JSON.stringify(e),Ps.set(e,t)),t}const Bt=e=>JSON.parse(JSON.stringify(e)),kn={},Xa={list:"groups",child:{list:"buttons",child:kn}};function Va(e){const t=new Map;for(const n of e)t.set(n.id,t.has(n.id)?null:n);return t}function qo(e,t,n){if(!n.list||!Array.isArray(e[n.list]))return e;const o=t?.[n.list]??[];return{...e,[n.list]:Ri(e[n.list],o,n.child??kn)}}function zn(e,t,n){if(!n.list||e[n.list]===void 0)return e;const o=t?.[n.list]??[];return{...e,[n.list]:ji(e[n.list],o,n.child??kn)}}function Ri(e,t,n){const o=Va(t),i=new Set(e.map(s=>s.id));if(i.size===e.length&&o.size===t.length){const s=t.filter(a=>i.has(a.id)),l=e.slice(s.length);if(s.every((a,c)=>e[c].id===a.id)&&l.every(a=>!o.has(a.id)))return{set:e.slice(0,s.length).filter(a=>On(o.get(a.id))!==On(a)).map(a=>qo(a,o.get(a.id),n)),drop:t.filter(a=>!i.has(a.id)).map(a=>a.id),add:l.map(a=>qo(a,void 0,n))}}return e.map(s=>{const l=o.get(s.id)??void 0;return l&&On(l)===On(s)?s.id:qo(s,l,n)})}function ji(e,t,n){const o=Va(t);if(Array.isArray(e)){const c=[];for(const d of e)if(typeof d!="string")c.push(zn(d,o.get(d.id)??void 0,n));else{const u=o.get(d);u&&c.push(Bt(u))}return c}const i=new Set(e.drop),s=new Map(e.set.map(c=>[c.id,c])),l=[];for(const c of e.add)o.has(c.id)?s.set(c.id,c):l.push(c);const a=new Set(t.map(c=>c.id));return[...t.filter(c=>!i.has(c.id)).map(c=>s.has(c.id)?zn(s.get(c.id),c,n):Bt(c)),...[...s.values()].filter(c=>!a.has(c.id)).map(c=>zn(c,void 0,n)),...l.map(c=>zn(c,void 0,n))]}const Qf=e=>!Array.isArray(e)&&e.set.length+e.drop.length+e.add.length===0,ro=e=>e;function eh(e){const t=et(e),n={};for(const s of ns){const l=t.ribbons[s],a=e.baseline[s];if(!l)continue;const c=Ri(l.tabs,a?.tabs??[],Xa),d={};for(const[p,f]of Object.entries(l))p!=="tabs"&&JSON.stringify(f)!==JSON.stringify(a?.[p])&&(d[p]=f);const u=Object.keys(a??{}).filter(p=>p!=="tabs"&&!(p in l));(!Qf(c)||Object.keys(d).length+u.length>0)&&(n[s]={props:d,unset:u,tabs:c})}const o={};for(const s of Object.keys(Ft))o[s]=Ri(ro(t[s]),ro(e[Ft[s]]),kn);const i={...t};delete i.ribbons;for(const s of Object.keys(Ft))delete i[s];return{ribbons:n,lists:o,other:i}}function th(e,t){const{delta:n}=e,o={};for(const s of ns){const l=n.ribbons[s],a=t.baseline[s];if(!l){o[s]=Bt(a);continue}const c={...Bt(a),...Bt(l.props)};for(const d of l.unset)delete c[d];c.tabs=ji(l.tabs,ro(a?.tabs??[]),Xa),o[s]=c}const i={...et(t),...Bt(n.other),ribbons:o};for(const s of Object.keys(Ft))i[s]=ji(n.lists[s],ro(t[Ft[s]]),kn);return i}function nh(e){return btoa(Sn(Fa(so(JSON.stringify(e)),{level:9}),!0))}function oh(e){return JSON.parse(Sn(_a(so(atob(e),!0))))}const ht=e=>Array.isArray(e),Ho=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Fs=e=>{if(ht(e))return!0;const t=e;return!!t&&typeof t=="object"&&ht(t.set)&&ht(t.drop)&&ht(t.add)},ih=e=>!!e&&typeof e=="object"&&ht(e.entity)&&ht(e.application);function sh(e){if(!e||typeof e!="object")return!1;const t=e,n=t.ribbons,o=t.other??{};return!!n&&typeof n=="object"&&Object.entries(n).every(([i,s])=>ns.includes(i)&&Fs(s?.tabs)&&Ho(s?.props)&&ht(s?.unset))&&Ho(t.lists)&&Object.keys(Ft).every(i=>Fs(t.lists[i]))&&Ho(t.other)&&["pendingUnhides","uncustomisedCommandIds"].every(i=>!(i in o)||ih(o[i]))&&(!("customisedCommandIds"in o)||ht(o.customisedCommandIds))}function rh(e,t){try{const n={format:ts,key:Ga(e),savedAt:new Date().toISOString(),baselineFingerprint:Ua(t),data:nh(eh(t))};return localStorage.setItem(wn(e),JSON.stringify(n)),n.savedAt}catch{return null}}function ah(e){const t=wn(e);let n;try{n=localStorage.getItem(t)}catch{return null}if(!n)return null;try{const o=JSON.parse(n);if(o.format===ts&&Ii(o.key,e)&&typeof o.data=="string"){const i=oh(o.data);if(sh(i)){const s=o;return{format:s.format,key:s.key,savedAt:s.savedAt,baselineFingerprint:s.baselineFingerprint,delta:i}}}}catch{}return ao(e),null}function ao(e){try{localStorage.removeItem(wn(e))}catch{}}function lh(e,t){try{const n=Date.parse(JSON.parse(e??"").savedAt??"");return!(t-n<=Ha*864e5)}catch{return!0}}function ch(e=Date.now()){const t=[];try{for(let n=0;n<localStorage.length;n++){const o=localStorage.key(n);o&&(o.startsWith(Wa)?lh(localStorage.getItem(o),e):Yf.some(i=>o.startsWith(i)))&&t.push(o)}for(const n of t)localStorage.removeItem(n)}catch{return 0}return t.length}function Ka(e){return e.mutationsSincePublish>0||qn(e)}function Wn(){return xe.getState().target!==null&&Ka(D.getState())}let St=null;function yt(e){const{target:t,pending:n}=xe.getState();if(!t||n)return!0;const o=e.ribbons.HomepageGrid.entityLogicalName;if(o&&o.toLowerCase()!==t.entityLogicalName.toLowerCase())return!0;let i=!0;if(!Ka(e))St!==null&&e.future.some(a=>a.op==="restored"&&a.ts===St)||(ao(t),xe.setState({lastSavedAt:null}));else{const l=rh(t,e);i=l!==null,l&&xe.setState({lastSavedAt:l})}const{saveFailed:s}=xe.getState();return!i&&!s&&se.getState().logWarn("ribbon","Unsaved changes could not be saved as a draft (browser storage is full or unavailable): publish them, or they are lost when Command Bar Studio closes."),i===s&&xe.setState({saveFailed:!i}),i}const dh=["mutationsSincePublish","ribbons","commands","enableRules","displayRules","locLabels","pendingUnhides","customisedCommandIds","uncustomisedCommandIds","baseline","baselineCommands","baselineEnableRules","baselineDisplayRules","baselineLocLabels","layers"];function uh(){return D.subscribe((e,t)=>{e.baseline!==t.baseline&&(St=null),!dh.every(n=>e[n]===t[n])&&yt(e)})}function mh(e){const t=ie.getState();return{orgUrl:t.connectionUrl,solutionId:t.activeSolution?.id??"",entityLogicalName:e}}function ph(){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 Wo(e){xe.setState({target:null,pending:null,pendingBaselineChanged:!1});const t=ie.getState();e.kind==="entity"?t.setActiveEntity(e.entity):t.setActiveSolution(e.solution)}const xe=$t()((e,t)=>({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null,beginLoad(){St=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,saveFailed:!1,lastSavedAt:null})},workspaceLoaded(n){const o=ah(n);St=null,e({target:n,pending:o,restoreError:null,lastSavedAt:o?.savedAt??null,pendingBaselineChanged:!!o&&o.baselineFingerprint!==Ua(D.getState())})},restoreDraft(){const{target:n,pending:o}=t();if(!n||!o||!Ii(n,o.key))return!1;const i=D.getState();try{i.restoreWorkspace(th(o,i),`saved ${new Date(o.savedAt).toLocaleString()}`)}catch(a){const c=a instanceof Error?a.message:String(a);return se.getState().logError("ribbon",`The unsaved changes saved ${o.savedAt} couldn't be restored: ${c}`),e({restoreError:c}),!1}const s=D.getState(),l=s.past[s.past.length-1];return s.past.length>i.past.length&&l?.op==="restored"&&(St=l.ts),e({pending:null,pendingBaselineChanged:!1,restoreError:null}),yt(s),!0},discardDraft(){const{target:n,pending:o}=t();o&&(ao(o.key),e({pending:null,pendingBaselineChanged:!1,restoreError:null,lastSavedAt:null}),n&&Ii(n,o.key)&&yt(D.getState()))},requestEntitySwitch(n){ie.getState().activeEntity?.logicalName!==n.logicalName&&(Wn()?(yt(D.getState()),e({pendingSwitch:{kind:"entity",entity:n}})):Wo({kind:"entity",entity:n}))},requestSolutionSwitch(n){ie.getState().activeSolution?.id!==n.id&&(Wn()?(yt(D.getState()),e({pendingSwitch:{kind:"solution",solution:n}})):Wo({kind:"solution",solution:n}))},resolveSwitch(n){const{pendingSwitch:o,target:i,pending:s}=t();if(o){if(n==="cancel"){e({pendingSwitch:null});return}n==="keep"&&!yt(D.getState())||(n==="discard"&&i&&!s&&ao(i),e({pendingSwitch:null,target:null,pending:null,pendingBaselineChanged:!1,saveFailed:!1}),ph(),Wo(o))}},releaseForConnectionChange(){const n=Wn(),o=n?yt(D.getState()):!1;return St=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null}),{hadChanges:n,kept:o}}})),Ja=e=>e?.trim().toLowerCase()==="production",Px=e=>Ja(e),Fx=(e,t)=>t.trim()!==""&&e.trim().toLowerCase()===t.trim().toLowerCase();function fh({prefix:e}){const t=ie(s=>s.connectionName),n=ie(s=>s.connectionUrl),o=ie(s=>s.environment);if(!t&&!n)return null;const i=Ja(o);return r.jsx(Te,{content:n||t,relationship:"description",children:r.jsxs("span",{"data-testid":"environment-badge",style:{display:"inline-flex",alignItems:"center",gap:m.spacingHorizontalXS,minWidth:0},children:[e&&r.jsx(F,{size:200,wrap:!1,style:{color:m.colorNeutralForeground3},children:e}),r.jsx(F,{size:200,weight:"semibold",truncate:!0,wrap:!1,style:{maxWidth:180},children:t||n}),o&&r.jsx(de,{size:"small",appearance:i?"filled":"tint",color:i?"warning":"informative",children:o})]})})}const hh=me({root:{height:"40px",display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`0 ${m.spacingHorizontalM}`,backgroundColor:m.colorNeutralBackground3,borderBottom:`1px solid ${m.colorNeutralStroke2}`,flexShrink:0},brand:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,marginRight:m.spacingHorizontalS},brandMark:{width:"24px",height:"24px",borderRadius:"4px",backgroundColor:m.colorBrandBackground,display:"flex",alignItems:"center",justifyContent:"center"},spacer:{flex:1},sep:{width:"1px",height:"20px",backgroundColor:m.colorNeutralStroke2,margin:`0 ${m.spacingHorizontalXS}`},paletteButton:{height:"28px",minWidth:"260px",display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`0 ${m.spacingHorizontalS}`,border:`1px solid ${m.colorNeutralStroke1}`,borderRadius:m.borderRadiusMedium,backgroundColor:m.colorNeutralBackground1,cursor:"pointer",color:m.colorNeutralForeground3,fontSize:m.fontSizeBase200,"&:hover":{border:`1px solid ${m.colorNeutralStroke1Hover}`,backgroundColor:m.colorNeutralBackground1Hover}},kbd:{padding:"1px 4px",border:`1px solid ${m.colorNeutralStroke2}`,borderRadius:"3px",fontSize:m.fontSizeBase100,backgroundColor:m.colorNeutralBackground2},solutionPickerSurface:{padding:m.spacingHorizontalM,minWidth:"360px",display:"flex",flexDirection:"column",gap:m.spacingVerticalS},solutionPickerHint:{color:m.colorNeutralForeground3}});function gh(){const e=hh(),[t,n]=L.useState("Loaded"),o=D(v=>v.past),i=D(v=>v.future),s=D(v=>v.undo),l=D(v=>v.redo),a=ie(v=>v.solutions),c=ie(v=>v.activeSolution),d=xe(v=>v.requestSolutionSwitch),u=ee(v=>v.openBulkPublish),p=ee(v=>v.openXmlDrawer),f=ee(v=>v.setCommandPaletteOpen),[h,y]=L.useState(!1),[x,b]=L.useState(""),g=L.useMemo(()=>a.filter(v=>!v.isManaged).map(v=>({value:v.id,children:v.friendlyName||v.uniqueName,searchText:`${v.friendlyName??""} ${v.uniqueName??""}`.toLowerCase(),solution:v})),[a]),S=Ku(x,g,{optionToText:v=>v.searchText,filter:(v,I)=>v.includes(I.toLowerCase()),optionToReactKey:v=>v.value,renderOption:v=>r.jsx(em,{value:v.value,text:v.solution.friendlyName??v.solution.uniqueName,children:r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[r.jsx(F,{size:200,weight:"semibold",children:v.solution.friendlyName||v.solution.uniqueName}),r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[v.solution.uniqueName," · v",v.solution.version,v.solution.publisherName?` · ${v.solution.publisherName}`:""]})]})},v.value),noOptionsMessage:a.length===0?"Loading solutions…":"No solutions match the filter."}),w=(v,I)=>{const A=a.find(R=>R.id===I.optionValue);A&&(d(A),y(!1),b(""))};return r.jsxs("header",{className:e.root,children:[r.jsxs("div",{className:e.brand,children:[r.jsx("div",{className:e.brandMark,children:r.jsx(F,{size:100,weight:"bold",style:{color:"white",lineHeight:1},children:"CBS"})}),r.jsx(F,{weight:"semibold",size:300,children:"Command Bar Studio"})]}),r.jsx("div",{className:e.sep}),r.jsx(fh,{}),r.jsx("div",{className:e.sep}),r.jsxs(Ju,{open:h,onOpenChange:(v,I)=>y(I.open),positioning:"below-start",trapFocus:!0,children:[r.jsx(Yu,{disableButtonEnhancement:!0,children:r.jsxs(J,{appearance:c?"subtle":"primary",size:"small",icon:r.jsx(Vl,{}),iconPosition:"before","aria-label":"Select solution",children:[r.jsx(F,{size:200,children:"Solution: "}),r.jsx(F,{size:200,weight:"semibold",children:c?.friendlyName??"Select solution…"}),c&&r.jsxs(r.Fragment,{children:[r.jsx(de,{appearance:"tint",color:c.isManaged?"informative":"success",size:"small",style:{marginLeft:m.spacingHorizontalXS},children:c.isManaged?"Managed":"Unmanaged"}),(()=>{const v=c.publisherPrefix||"new",I=v==="new"||/^defaultpublisher/i.test(c.publisherUniqueName??"");return r.jsxs(de,{appearance:"tint",color:I?"warning":"informative",size:"small",title:I?`Imports will land under the org's default publisher "${v}". To use your own publisher, create a new solution in maker.powerapps.com bound to it.`:`Publisher: ${c.publisherName||c.publisherUniqueName||v}`,style:{marginLeft:m.spacingHorizontalXS},children:[v,"_"]})})()]}),r.jsx(gt,{fontSize:12,style:{marginLeft:m.spacingHorizontalXS,color:m.colorNeutralForeground3}})]})}),r.jsxs(Zu,{className:e.solutionPickerSurface,children:[r.jsx(F,{size:200,weight:"semibold",children:"Select an unmanaged solution"}),r.jsx(Oe,{label:"Solution",children:r.jsx(Qu,{placeholder:a.length===0?"Loading solutions…":"Search by display name or unique name",value:x,onChange:v=>b(v.target.value),onOptionSelect:w,freeform:!0,clearable:!0,children:S})}),r.jsxs(F,{size:100,className:e.solutionPickerHint,children:[g.length," unmanaged solution",g.length!==1?"s":""," available"]})]})]}),r.jsx("div",{className:e.spacer}),r.jsxs("button",{type:"button",className:e.paletteButton,onClick:()=>f(!0),"aria-label":"Search buttons, commands, rules (Ctrl+K)",children:[r.jsx(ft,{fontSize:14}),r.jsx("span",{style:{flex:1,textAlign:"left"},children:"Search buttons, commands, rules…"}),r.jsx("kbd",{className:e.kbd,children:"Ctrl"}),r.jsx("kbd",{className:e.kbd,children:"K"})]}),r.jsx("div",{className:e.sep}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(vr,{}),disabled:o.length===0,onClick:s,title:"Undo (Ctrl+Z)","aria-label":"Undo"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Sr,{}),disabled:i.length===0,onClick:l,title:"Redo (Ctrl+Shift+Z)","aria-label":"Redo"}),r.jsx("div",{className:e.sep}),r.jsxs(dt,{value:t,onChange:(v,I)=>n(I.value),size:"small",title:"State simulator","aria-label":"State simulator",children:[r.jsx("option",{value:"Loaded",children:"Loaded"}),r.jsx("option",{value:"Empty",children:"Empty"}),r.jsx("option",{value:"Error",children:"Error"}),r.jsx("option",{value:"Publishing",children:"Publishing"})]}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(wr,{}),onClick:()=>{p()},title:"Import / Export RibbonDiffXml","aria-label":"Import/Export"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Cr,{}),title:"Settings","aria-label":"Settings"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ir,{}),title:"Help","aria-label":"Help"}),r.jsx("div",{className:e.sep}),r.jsx(J,{appearance:"secondary",size:"small",icon:r.jsx(Rr,{}),children:"Save"}),r.jsx(J,{appearance:"primary",size:"small",icon:r.jsx(Kl,{}),onClick:u,children:"Publish All"})]})}const bh=me({root:{height:"36px",display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`0 ${m.spacingHorizontalM}`,backgroundColor:m.colorNeutralBackground2,borderBottom:`1px solid ${m.colorNeutralStroke2}`,flexShrink:0,position:"relative"},breadcrumb:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,color:m.colorNeutralForeground3,fontSize:m.fontSizeBase200},separator:{color:m.colorNeutralForeground4},activeSegment:{color:m.colorNeutralForeground1,fontWeight:m.fontWeightSemibold},spacer:{flex:1}});function yh(){const e=bh(),t=D(p=>p.mutationsSincePublish),n=ie(p=>p.activeSolution),o=ie(p=>p.activeEntity),i=ie(p=>p.connectionUrl),s=ee(p=>p.openXmlDrawer),l=ee(p=>p.openImportXml),a=ee(p=>p.openDiffViewer),c=ee(p=>p.rightPaneMode),d=ee(p=>p.setRightPaneMode);async function u(){if(!i||!o?.logicalName)return;const p=`${i.replace(/\/$/,"")}/main.aspx?pagetype=entitylist&etn=${encodeURIComponent(o.logicalName)}`;await window.toolboxAPI?.utils.openInConnectionBrowser(p,"primary")}return r.jsxs("div",{className:e.root,children:[r.jsxs("nav",{"aria-label":"Breadcrumb",className:e.breadcrumb,children:[r.jsx("span",{children:"Solutions"}),r.jsx("span",{className:e.separator,children:"›"}),r.jsx("span",{children:n?.friendlyName??"—"}),r.jsx("span",{className:e.separator,children:"›"}),r.jsx("span",{children:"Tables"}),r.jsx("span",{className:e.separator,children:"›"}),r.jsx("span",{className:e.activeSegment,children:o?.displayName??"Select a table"})]}),r.jsx("div",{className:e.spacer}),t>0&&r.jsxs(de,{appearance:"tint",color:"warning",children:[t," change",t!==1?"s":""," since publish"]}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(It,{}),onClick:()=>{u()},disabled:!o?.logicalName,children:"Preview in app"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ut,{}),onClick:s,children:"RibbonDiffXml"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(wr,{}),onClick:()=>l(),children:"Import / Export"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(jr,{}),onClick:()=>a("compare"),children:"Compare"}),r.jsxs(dt,{size:"small",value:c,onChange:(p,f)=>d(f.value),"aria-label":"Properties pane mode",children:[r.jsx("option",{value:"docked",children:"Properties: Docked"}),r.jsx("option",{value:"floating",children:"Properties: Floating"}),r.jsx("option",{value:"hidden",children:"Properties: Hidden"})]})]})}function xh(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 vh='[role="dialog"], [role="alertdialog"], [role="menu"], [role="menubar"], [role="listbox"], .fui-PopoverSurface, .fui-MenuPopover',Ya=".fui-OverlayDrawer, .fui-InlineDrawer",_s=e=>!!e.closest(Ya)&&!e.matches('[role="alertdialog"]');function Sh(e){const t=e instanceof Element?e.closest(vh):null;return t&&!_s(t)?!0:Array.from(document.querySelectorAll('[aria-modal="true"], [role="alertdialog"]')).some(n=>!_s(n))}function wh(e){return e instanceof Element&&!!e.closest(Ya)}function Ch(){const e=ee(v=>v.setCommandPaletteOpen),t=ee(v=>v.openBulkPublish),n=ee(v=>v.announce),o=ee(v=>v.openHideInsteadOfDelete),i=D(v=>v.undo),s=D(v=>v.redo),l=D(v=>v.past),a=D(v=>v.future),c=te(v=>v.selectedButtonId),d=te(v=>v.selectedGroupId),u=te(v=>v.tabId),p=te(v=>v.location),f=D(v=>v.duplicateButton),h=D(v=>v.deleteButton),y=D(v=>v.moveButton),x=D(v=>v.ribbons),b=D(v=>v.baseline),g=te(v=>v.selectButtonInContext),S=te(v=>v.selectGroup),w=L.useRef(null);L.useEffect(()=>{const v=I=>{const R=navigator.platform.toUpperCase().includes("MAC")?I.metaKey:I.ctrlKey,k=I.target,N=I.key??"",W=I.altKey||I.getModifierState?.("AltGraph"),X=!W&&/^Key[A-Z]$/.test(I.code??"")&&!/^[a-z]$/i.test(N)?I.code.slice(3).toLowerCase():N.length===1?N.toLowerCase():N,O=R&&!I.shiftKey&&!W;if(I.key==="Escape"){e(!1);return}if(Sh(k)){O&&X==="s"&&I.preventDefault();return}if(O&&X==="k"){I.preventDefault(),e(!0),n("Command palette opened");return}if(O&&X==="s"){I.preventDefault(),t(),n("Bulk publish dialog opened");return}const T=xh(k);if(O&&X==="z"&&l.length>0&&!T){I.preventDefault(),i(),n("Undo");return}if(R&&!W&&(X==="y"||I.shiftKey&&X==="z")&&!T){I.preventDefault(),a.length>0&&(s(),n("Redo"));return}if(!wh(k)){if(O&&X==="d"){!T&&c&&d&&u&&p&&(I.preventDefault(),f(p,u,d,c),n("Button duplicated"));return}if(R&&!W&&X==="x"){if(!T&&c&&d&&u&&p){I.preventDefault();const z=x[p].tabs.find($=>$.id===u)?.groups.find($=>$.id===d);if(z&&Yn(z,c)){n("Menu items can't be cut. Delete the item and add a new one to the other menu.");return}w.current={location:p,tabId:u,groupId:d,buttonId:c},n("Button cut. Focus a destination group, then press paste.")}return}if(R&&!W&&X==="v"){const z=w.current;if(!T&&z&&d&&u&&p){I.preventDefault();const $=y({groupId:z.groupId,buttonId:z.buttonId,tabId:z.tabId,location:z.location},{groupId:d,tabId:u,location:p});if(w.current=null,!$){n("The button couldn't be moved there.");return}requestAnimationFrame(()=>{g(p,u,d,$),document.querySelector(`[data-ribbon-btn-id="${$}"]`)?.focus()}),n($===z.buttonId?"Button pasted to destination group.":"Pasted your copy of the button to the destination group; the original is hidden.")}return}if((I.key==="Delete"||I.key==="Backspace")&&c&&d&&u&&p&&!T){const z=x[p].tabs.find(V=>V.id===u),$=z?.groups.find(V=>V.id===d),M=en($,c);if(!M)return;if(I.preventDefault(),!Nn(M,b[p])){p==="Application"&&u==="Mscrm.GlobalTab"&&M.oob&&!M.custom?n(`"${M.label}" is read-only and can't be deleted.`):M.hidden?n(`"${M.label}" can't be deleted — only your own buttons can. It is already hidden.`):o({location:p,tabId:u,groupId:d,buttonId:c});return}const G=$?Yn($,c):void 0,K=G?G.section.controls.map(V=>({groupId:d,buttonId:V.id})):z?.groups.flatMap(V=>V.buttons.map(U=>({groupId:V.id,buttonId:U.id})))??[],Q=K.findIndex(V=>V.buttonId===c),P=K[Q+1]??K[Q-1]??(G?{groupId:d,buttonId:G.parent.id}:null),q=d;h(p,u,d,c),requestAnimationFrame(()=>{if(P){g(p,u,P.groupId,P.buttonId),document.querySelector(`[data-ribbon-btn-id="${P.buttonId}"]`)?.focus();return}q&&(S(q),document.querySelector(`[data-add-btn-group-id="${q}"]`)?.focus())}),n("Button deleted")}}};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[e,t,n,o,i,s,l.length,a.length,c,d,u,p,f,h,y,x,b,g,S])}const Ih=me({handleV:{width:"4px",cursor:"col-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:m.colorNeutralStroke2},":active":{backgroundColor:m.colorBrandStroke1},userSelect:"none"},handleH:{height:"4px",cursor:"row-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:m.colorNeutralStroke2},":active":{backgroundColor:m.colorBrandStroke1},userSelect:"none"}});function Go({direction:e,onResize:t,"aria-label":n=`Resize ${e} pane`}){const o=Ih(),i=L.useRef(0),s=L.useCallback(a=>{a.currentTarget.setPointerCapture(a.pointerId),i.current=e==="vertical"?a.clientX:a.clientY},[e]),l=L.useCallback(a=>{if(!a.currentTarget.hasPointerCapture(a.pointerId))return;const c=e==="vertical"?a.clientX:a.clientY,d=c-i.current;i.current=c,t(d)},[e,t]);return r.jsx("div",{className:e==="vertical"?o.handleV:o.handleH,role:"separator","aria-orientation":e==="vertical"?"vertical":"horizontal","aria-label":n,onPointerDown:s,onPointerMove:l})}class Et extends Ue.Component{state={hasError:!1,error:null};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[CBS ErrorBoundary]",this.props.label??"panel",t,n)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:r.jsxs(we,{intent:"error",style:{margin:8},children:[r.jsxs(Ce,{children:[r.jsx("strong",{children:this.props.label??"Panel"})," encountered an error:"," ",this.state.error?.message??"Unknown error"]}),r.jsx(Mt,{children:r.jsx(J,{size:"small",onClick:this.handleRetry,children:"Retry"})})]}):this.props.children}}const Rh=L.lazy(()=>Ne(()=>import("./XmlDrawer-DXyRtGs1.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),jh=L.lazy(()=>Ne(()=>import("./CommandEditorPanel-BfcpfNps.js"),__vite__mapDeps([7,1,2,3,8,9,5,4,6]),import.meta.url)),$h=L.lazy(()=>Ne(()=>import("./RuleEditorPanel-C26e1gMH.js"),__vite__mapDeps([10,1,2,3,11,5,8,9,6]),import.meta.url)),Nh=L.lazy(()=>Ne(()=>import("./BulkPublishModal-dGiT6nNQ.js"),__vite__mapDeps([12,1,2,3,13,11,9,5,6]),import.meta.url)),Th=L.lazy(()=>Ne(()=>import("./NewButtonModal-DqdSshXe.js"),__vite__mapDeps([14,1,2,3,5,6]),import.meta.url)),kh=L.lazy(()=>Ne(()=>import("./NewGroupModal-VysrEsbU.js"),__vite__mapDeps([15,1,2,3,5,6]),import.meta.url)),Ah=L.lazy(()=>Ne(()=>import("./NewTabModal-ChEmOjmh.js"),__vite__mapDeps([16,1,2,3,5,6]),import.meta.url)),Dh=L.lazy(()=>Ne(()=>import("./ImportXmlModal-DImDI43_.js"),__vite__mapDeps([17,1,2,3,13,11,9,4,5,6]),import.meta.url)),Eh=L.lazy(()=>Ne(()=>import("./CommandPalette-C4NOIuA3.js"),__vite__mapDeps([18,1,2,3,5,6]),import.meta.url)),Oh=L.lazy(()=>Ne(()=>import("./LocalizationEditor-CeAgqq85.js"),__vite__mapDeps([19,1,2,3,5,6]),import.meta.url)),zh=L.lazy(()=>Ne(()=>import("./IconPickerModal-B1AgGWq0.js"),__vite__mapDeps([20,1,2,3,21,5,6]),import.meta.url)),Bh=L.lazy(()=>Ne(()=>import("./TabDisplayRulesPanel-DR-c2-Km.js"),__vite__mapDeps([22,1,2,3,5,6]),import.meta.url)),Mh=L.lazy(()=>Ne(()=>import("./ScalingEditorPanel-f2Rmk9AG.js"),__vite__mapDeps([23,1,2,3,5,6]),import.meta.url)),Lh=L.lazy(()=>Ne(()=>import("./ConflictDrawer-CW1NLdAD.js"),__vite__mapDeps([24,1,2,3,5,6]),import.meta.url)),Ph=L.lazy(()=>Ne(()=>import("./WebResourceBrowser-D2RMaFeZ.js"),__vite__mapDeps([25,1,2,3,21,5,6]),import.meta.url)),Fh=L.lazy(()=>Ne(()=>import("./UrlComposerModal-DFwPOYL1.js"),__vite__mapDeps([26,1,2,3,5,6]),import.meta.url)),_h=L.lazy(()=>Ne(()=>import("./DiffViewer-R0g0dxLc.js"),__vite__mapDeps([27,2,3,1,5,6]),import.meta.url)),qh=L.lazy(()=>Ne(()=>import("./HideInsteadOfDeleteModal-DbfHSKmm.js"),__vite__mapDeps([28,1,2,3,5,6]),import.meta.url)),Hh=me({root:{display:"flex",flexDirection:"column",height:"100vh",overflow:"hidden",backgroundColor:m.colorNeutralBackground1,color:m.colorNeutralForeground1,fontFamily:m.fontFamilyBase},body:{display:"flex",flex:1,overflow:"hidden",position:"relative"},leftPane:{flexShrink:0,overflow:"hidden",borderRight:`1px solid ${m.colorNeutralStroke2}`},rightPane:{flexShrink:0,overflow:"hidden",borderLeft:`1px solid ${m.colorNeutralStroke2}`},bottomPanel:{flexShrink:0}});function Wh({children:e,leftPane:t,rightPane:n,bottomPanel:o}){const i=Hh(),s=ee(v=>v.leftPaneWidth),l=ee(v=>v.rightPaneWidth),a=ee(v=>v.rightPaneMode),c=ee(v=>v.setLeftPaneWidth),d=ee(v=>v.setRightPaneWidth),u=ee(v=>v.bottomPanelHeight),p=ee(v=>v.bottomCollapsed),f=ee(v=>v.setBottomPanelHeight),h=ee(v=>v.announcement),y=ee(v=>v.xmlDrawerOpen||v.commandEditorOpen||v.ruleEditorOpen||v.bulkPublishOpen||v.newButtonGroupId!==null||v.newGroupOpen||v.newTabOpen||v.importXmlOpen||v.commandPaletteOpen||v.localizationEditorOpen||v.iconPickerOpen||v.tabDisplayRulesOpen||v.scalingEditorOpen||v.conflictDrawerOpen||v.webResourceBrowserOpen||v.urlComposerOpen||v.diffViewerOpen||v.hideInsteadOfDelete!==null),x=L.useRef(null),b=L.useRef(!1);Ch(),L.useEffect(()=>{if(y&&!b.current){const v=document.activeElement;x.current=v instanceof HTMLElement?v:null}if(!y&&b.current){const v=x.current;requestAnimationFrame(()=>{!v||!v.isConnected||v.focus()})}b.current=y},[y]);const g=L.useCallback(v=>{c(Math.max(160,Math.min(500,s+v)))},[s,c]),S=L.useCallback(v=>{d(Math.max(200,Math.min(600,l-v)))},[l,d]),w=L.useCallback(v=>{const I=u-v;f(Math.max(120,Math.min(520,I)))},[u,f]);return r.jsxs("div",{className:i.root,children:[r.jsx(gh,{}),r.jsx(yh,{}),r.jsxs("div",{className:i.body,children:[r.jsx("div",{className:i.leftPane,style:{width:s},children:r.jsx(Et,{label:"Left pane",children:t})}),r.jsx(Go,{direction:"vertical",onResize:g,"aria-label":"Resize left pane"}),r.jsx(Et,{label:"Ribbon canvas",children:e}),a==="docked"&&r.jsxs(r.Fragment,{children:[r.jsx(Go,{direction:"vertical",onResize:S,"aria-label":"Resize right pane"}),r.jsx("div",{className:i.rightPane,style:{width:l},children:r.jsx(Et,{label:"Properties pane",children:n})})]}),a==="floating"&&r.jsx("div",{style:{position:"absolute",right:8,top:8,bottom:8,width:l,maxWidth:"90vw",border:`1px solid ${m.colorNeutralStroke2}`,backgroundColor:m.colorNeutralBackground1,boxShadow:m.shadow16,borderRadius:m.borderRadiusMedium,overflow:"hidden",zIndex:10},children:r.jsx(Et,{label:"Properties pane",children:n})})]}),!p&&r.jsx(Go,{direction:"horizontal",onResize:w,"aria-label":"Resize bottom panel"}),r.jsx("div",{className:i.bottomPanel,children:r.jsx(Et,{label:"Bottom panel",children:o})}),r.jsx(Et,{label:"Panels",children:r.jsxs(L.Suspense,{fallback:null,children:[r.jsx(Rh,{}),r.jsx(jh,{}),r.jsx($h,{}),r.jsx(Nh,{}),r.jsx(Th,{}),r.jsx(kh,{}),r.jsx(Ah,{}),r.jsx(Dh,{}),r.jsx(Eh,{}),r.jsx(Oh,{}),r.jsx(zh,{}),r.jsx(Bh,{}),r.jsx(Mh,{}),r.jsx(Lh,{}),r.jsx(Ph,{}),r.jsx(Fh,{}),r.jsx(_h,{}),r.jsx(qh,{})]})}),r.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",left:-9999,top:"auto"},children:h})]})}const Za="Unified Interface has no visible tabs: this tab's buttons appear in the table's command bar (or its overflow menu) wherever the tab's display rule applies.",ln=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Gh=e=>[e.icon,e.image16,e.image32].some(t=>!!t&&t.startsWith("$webresource:")),Uh=e=>!!e.source&&Hi(e)===e.source.modernImage&&(e.source.modernImage!==void 0||!e.icon),Xh=/^\$LocLabels:(.+)$/,mt=e=>e?Xh.exec(e)?.[1]??null:null,Vh=/^\s*<(EnableRule|DisplayRule)\b[^>]*?\sId="([^"]+)"/,cn=e=>new Set(e??[]);function Kh(e){const t=[];for(const n of Object.values(e.source?.attributes??{})){const o=mt(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 qs(e){return(e.menu?.sections??[]).map(t=>({id:t.id,title:t.title??"",sequence:t.sequence,displayMode:t.displayMode??"",controlsId:t.controlsId}))}function _x(e){const t=[],n=[],o=[],i=[],s=[],l=[],a=[],c=[],d=new Map,u=(P,q)=>{const V=mt(P);V&&d.set(V,new Set([...d.get(V)??[],q]))};for(const{baseline:P}of e.locations)for(const q of P.tabs){u(q.label,q.id);for(const V of q.groups){u(V.label,V.id);for(const U of $e(V))for(const j of Object.values(U.source?.attributes??{}))u(j,U.id)}}const p=new Set([...(e.locLabels??[]).map(P=>P.id),...cn(e.layer?.locLabelIds)]);let f=!1;const h=new Set,y=cn(e.layer?.containerIds),x=cn(e.layer?.locLabelIds),b=new Set,g=new Set,S=new Map,w=new Map,v=[],I=new Set(e.locations.flatMap(({current:P})=>Array.from(wt(P).values(),q=>q.button.id))),A=(P,q,V,U)=>{const j=mt(V);if(y.has(q)&&j&&x.has(j)&&!mt(U)&&U.trim())if([...d.get(j)??[]].some(C=>C!==q)){let C=`${q}.Title`;for(let B=2;C===j||p.has(C);B++)C=`${q}.Title${B}`;p.add(C),c.push({id:C,text:U,containerId:q,newLabel:!0})}else c.push({id:j,text:U,containerId:q});else t.push(`Renaming ${P} ${q} — only tabs and groups your unmanaged customizations add (with a translatable title) can be renamed`)};for(const{current:P,baseline:q}of e.locations){const V=Dp(P,q);V.newButtons+V.overriddenButtons+V.hiddenButtons+V.newTabs+V.newGroups>0&&(f=!0),V.scalingChanges>0&&t.push(`Scaling changes on ${P.location} (not supported yet)`);const U=ha(P,q);t.push(...U.problems);const j=cn(e.layer?.scalingStepIds);for(const[E,H]of Object.entries(q.scalingByTab??{})){const oe=P.tabs.find(re=>re.id===E),ne=[...H.maxSizes.filter(re=>j.has(re.id)).map(re=>({...re,kind:"MaxSize"})),...H.scales.filter(re=>j.has(re.id)).map(re=>({...re,kind:"Scale"})),...(oe?.groups??[]).map(re=>U.steps.get(re.id)).filter(re=>!!re).map(re=>({...re,kind:"MaxSize"}))];if(ne.length===0)continue;const je=Yr(E,{maxSizes:H.maxSizes.filter(re=>!j.has(re.id)).map(re=>re.sequence),scales:H.scales.filter(re=>!j.has(re.id)).map(re=>re.sequence)},ne);n.push(...je.changes.map(lp)),t.push(...je.problems)}const C=wt(P),B=wt(q);for(const{button:E}of C.values())for(const H of Vr(E))h.add(H);for(const[E,{button:H}]of C){const oe=Kh(H);oe.forEach(re=>b.add(re));const ne=B.get(E)?.button,je=!ne||ci(ne,H);for(const re of[yo(H.id),xo(H.id),vo(H.id)])je?g.add(re):oe.includes(re)||S.set(re,H);je&&oe.forEach(re=>g.add(re))}for(const[E,H]of B){const oe=H.button.id,ne=C.get(E);if(!ne){if(H.menu&&I.has(oe)&&I.has(H.menu.parentId)&&H.button.origin!=="unmanaged"){t.push(`Moving the menu of ${H.menu.parentId} to another location — its item "${H.button.label}" (${oe}) comes from another solution and can't be moved with it; move the flyout back`);continue}if(Ze(H.button.kind)&&I.has(oe)&&/<Menu[\s>/]/.test(H.button.source?.xml??"")){t.push(`Moving the <${bn[H.button.kind]}> "${H.button.label}" (${oe}) to another location — its menu may hold items of other solutions; move it within its location instead`);continue}vt(H.button)?o.push(oe):t.push(`Removing "${H.button.label}" (${oe}) — only your own unmanaged buttons can be deleted; hide it instead`);continue}H.button.hidden&&!ne.button.hidden&&i.push(oe),(ne.button.kind??"button")!==(H.button.kind??"button")&&t.push(`Changing the kind of "${ne.button.label}" (${oe}) — not supported yet`);const je=ci(H.button,ne.button);je&&Ze(ne.button.kind)&&t.push(`Editing the <${bn[ne.button.kind]}> "${ne.button.label}" (${oe}) — CBS shows it read-only; it can be hidden, or moved and deleted when it's your own`),je&&(Lt(ne.button.kind)||ne.button.menu)&&H.button.origin!=="unmanaged"&&t.push(`Editing the flyout / split button "${ne.button.label}" (${oe}) itself — only your own can be edited; its menu items can be edited, hidden or added to`),ln(qs(H.button),qs(ne.button))||t.push(`Adding, removing or changing menu sections of "${ne.button.label}" (${oe}) — not supported yet for an existing menu; add, edit or remove its items instead`),(ne.button.icon??"")!==(H.button.icon??"")&&!Gh(ne.button)&&!Uh(ne.button)&&t.push(`Changing the icon of "${ne.button.label}" (${oe}) to a built-in icon — not supported yet; choose an SVG web resource`),((ne.menu||H.menu?ne.menu?.controlsId!==H.menu?.controlsId:ne.groupId!==H.groupId)||ne.button.sequence!==H.button.sequence)&&(H.button.origin==="unmanaged"?l.push({id:oe,groupId:ne.groupId,sequence:ne.button.sequence,...ne.menu?{controlsId:ne.menu.controlsId}:{}}):t.push(`Moving or re-ordering "${ne.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[E,H]of C){if(B.has(E))continue;w.has(H.button.id)||w.set(H.button.id,{groupId:H.groupId,sequence:H.button.sequence,...H.menu?{controlsId:H.menu.controlsId}:{}});const oe=la(H.button.source?.attributes.PopulateDynamically);Lt(H.button.kind)&&!oe&&!Ct(H.button).some(ne=>!ne.hidden)&&v.push({id:H.button.id,label:H.button.label})}const Y=new Map(q.tabs.flatMap(E=>E.groups.map(H=>[H.id,H]))),le=new Map(q.tabs.map(E=>[E.id,E])),_=new Set(P.tabs.map(E=>E.id)),ce=new Set(P.tabs.flatMap(E=>E.groups.map(H=>H.id)));for(const E of P.tabs){const H=mt(E.label);H&&b.add(H);const oe=le.get(E.id);if(!oe){g.add(`${E.id}.Title`);const ne=mt(E.source?.titleToken);ne&&g.add(ne),E.commandId&&h.add(E.commandId),P.location==="Application"&&(E.tabDisplayRules??[]).length===0&&t.push(`New tab ${E.id} has no tab display rule, so it would never be shown — add one in Tab rules`),n.push(`New tab "${E.label}" (${E.id}): ${Za}`)}oe&&oe.label!==E.label&&A("tab",E.id,oe.label,E.label),oe&&!ln(oe.tabDisplayRules??[],E.tabDisplayRules??[])&&(y.has(E.id)?E.commandId?a.push(E.id):t.push(`Changing the display rules of tab ${E.id} — the tab has no Command to attach them to`):t.push(`Changing the display rules of tab ${E.id} — only tabs your unmanaged customizations add can be changed`));for(const ne of E.groups){const je=mt(ne.label);je&&b.add(je);const re=Y.get(ne.id);if(!re){g.add(`${ne.id}.Title`);const kt=mt(ne.source?.titleToken);kt&&g.add(kt)}re&&re.template!==ne.template&&t.push(`Re-templating group ${ne.id} — not supported yet`),re&&re.label!==ne.label&&A("group",ne.id,re.label,ne.label)}}const Ee=(E,H)=>t.push(`Removing ${E} ${H} — only tabs and groups your unmanaged customizations add can be deleted; hide it instead`);for(const E of q.tabs){if(!_.has(E.id)){y.has(E.id)?s.push(E.id):Ee("tab",E.id);continue}for(const H of E.groups)ce.has(H.id)||(y.has(H.id)?s.push(H.id):Ee("group",H.id))}}for(let P=o.length-1;P>=0;P--){const q=w.get(o[P]);q&&(l.push({id:o[P],...q}),o.splice(P,1))}for(const P of e.deletedOrphans??[]){for(const q of P.deleteControlIds)o.includes(q)||o.push(q);for(const q of P.deleteContainerIds)s.includes(q)||s.push(q)}for(const P of v)l.some(q=>q.id===P.id)||t.push(`New flyout / split button "${P.label}" has no menu items — add at least one item to its menu`);const R=e.layer?.commandIds?cn(e.layer.commandIds):null,k=new Set(e.uncustomisedCommandIds??[]),N=[...k].filter(P=>R?R.has(P):h.has(P)&&!e.excludeCommandIds?.has(P));for(const P of N)e.layer?.commandRefIds&&!Li(P,e.layer.commandRefIds)&&t.push(`Uncustomising ${P} — it is your own command (your customizations' buttons use it and no other solution defines it); undo the uncustomise`);N.includes(Be)&&h.has(Be)&&t.push(`Uncustomising ${Be} — its "Open record" buttons still use it; undo the uncustomise and turn the record open override off in the Advanced section instead`);for(const P of e.excludeCommandIds??[])h.delete(P);const W=new Set(e.customisedCommandIds??[]),X=new Map(e.baselineCommands.map(P=>[P.id,P])),O=e.commands.filter(P=>h.has(P.id)&&!k.has(P.id)&&(!X.has(P.id)||!ln(X.get(P.id),P)||W.has(P.id)&&!R?.has(P.id))).map(P=>P.id);for(const P of e.commands){if(!O.includes(P.id))continue;P.actions.some(V=>V.kind==="powerFx"||V.kind==="customApi")&&t.push(`Power Fx / Custom API action in command ${P.id} — classic ribbon commands can't run these; remove the action (#28)`);const q=P.id===Be?If(P):null;q&&t.push(q)}const T=new Set,z=new Set;for(const P of e.commands)if(!(!h.has(P.id)||k.has(P.id))){P.enableRules.forEach(q=>T.add(q)),P.displayRules.forEach(q=>z.add(q));for(const q of P.rawRuleRefs??[]){const V=Vh.exec(q.xml);V&&(V[1]==="EnableRule"?T:z).add(V[2])}}const $=(P,q,V)=>{const U=new Map(q.map(j=>[j.id,j]));return P.filter(j=>V.has(j.id)&&(!U.has(j.id)||!ln(U.get(j.id),j))).map(j=>j.id)},M=$(e.enableRules,e.baselineEnableRules,T),G=$(e.displayRules,e.baselineDisplayRules,z),K=[];if(e.locLabels&&e.baselineLocLabels){const P=new Map(e.baselineLocLabels.map(q=>[q.id,q]));for(const q of e.locLabels){const V=P.get(q.id);if(V&&ln(V,q)||g.has(q.id))continue;if(b.has(q.id)){x.has(q.id)?K.push(q.id):t.push(`Translations of label ${q.id} — it is defined by another solution; change the text in the properties pane instead`);continue}const U=S.get(q.id);U&&t.push(`Translations for "${U.label}" (${U.id}) — its text isn't a translatable label yet; change the text in the properties pane first, then add translations`)}}const Q=(e.unhiddenLayerHideIds??[]).filter(P=>!i.includes(P));return{hasChanges:f||O.length>0||N.length>0||M.length>0||G.length>0||o.length>0||i.length>0||Q.length>0||s.length>0||l.length>0||K.length>0||a.length>0||c.length>0,editedCommandIds:O,uncustomisedCommandIds:N,editedEnableRuleIds:M,editedDisplayRuleIds:G,deletedButtonIds:o,unhiddenButtonIds:[...i,...Q],deletedContainerIds:s,movedButtons:l,editedLocLabelIds:K,editedTabIds:a,renamedLabels:c,unsupported:[...new Set(t)],warnings:[...new Set(n)]}}const Jh=["HomepageGrid","SubGrid","Form"];function Yh(e,t){const n=new Map;for(const y of Object.values(t.baseline))for(const x of y.tabs)for(const b of x.groups)for(const g of b.buttons)n.set(g.id,g.origin);let o=!1,i=!1,s=pi(e);for(const[y,x]of Object.entries(t.ribbons))for(const b of x.tabs)for(const g of b.groups)for(const S of g.buttons)S.commandId===e&&(Jh.includes(y)?o=!0:i=!0,n.has(S.id)&&n.get(S.id)!=="unmanaged"&&(s=!0));const l=o||!i?"entity":"application",a=o&&i,c=t.layers[l],d=c?.commandIds?c.commandIds.includes(e):void 0,u=t.baselineCommands.find(y=>y.id===e),p=(y,x=l)=>({provenance:y,scope:x,sharedWithApplication:a});if(t.reloadRequiredCommandIds.includes(e))return p("reloadRequired");for(const y of["entity","application"])if(t.uncustomisedCommandIds[y].includes(e))return p("uncustomising",y);if(!u||!s&&d!==!1)return p("custom");if(d){const y=c?.commandRefIds?Li(e,c.commandRefIds):pi(e);return p(y?"customised":"custom")}const f=t.commands.find(y=>y.id===e),h=!!f&&JSON.stringify(f)!==JSON.stringify(u);return t.customisedCommandIds.includes(e)||h?p("customising"):p("oob")}const Zh={oob:"Out of the box",customising:"Customised (unpublished)",customised:"Customised in your layer",uncustomising:"Uncustomised (unpublished)",custom:"Custom",reloadRequired:"Uncustomised — reload the table"};function Qa(e){const t=D(d=>d.commands),n=D(d=>d.baselineCommands),o=D(d=>d.ribbons),i=D(d=>d.baseline),s=D(d=>d.layers),l=D(d=>d.customisedCommandIds),a=D(d=>d.uncustomisedCommandIds),c=D(d=>d.reloadRequiredCommandIds);return Ue.useMemo(()=>e&&t.some(d=>d.id===e)?Yh(e,{commands:t,baselineCommands:n,ribbons:o,baseline:i,layers:s,customisedCommandIds:l,uncustomisedCommandIds:a,reloadRequiredCommandIds:c}):null,[e,t,n,o,i,s,l,a,c])}function qx(e){return e?.provenance==="uncustomising"||e?.provenance==="reloadRequired"}function el({location:e,tabId:t,groupId:n,button:o,onDone:i}){const s=D(f=>f.customiseButton),l=D(f=>f.customiseCommand),a=ie(f=>f.activeSolution),c=ie(f=>f.publisherPrefix),d=te(f=>f.selectButtonInContext),u=ee(f=>f.openCommandEditor),p=Qa(o.commandId||void 0);return r.jsxs(r.Fragment,{children:[o.origin!=="unmanaged"&&r.jsx(fe,{icon:r.jsx(Jl,{}),disabled:!Zi(e,t,o),onClick:()=>{const f=a?.publisherPrefix?.trim()||c?.trim()||"new",h=s(e,t,n,o.id,f);h&&d(e,t,n,h),i()},children:"Customise button (copy, hide original)"}),p?.provenance==="oob"&&r.jsx(fe,{icon:r.jsx(Ut,{}),onClick:()=>{l(o.commandId)&&u(o.commandId),i()},children:"Customise command"})]})}function tl(e,t,n,o,i){const s=e.groups.filter(a=>a.id!==t&&!(n&&a.buttons.some(c=>c.id===n))).map(a=>({groupId:a.id,text:ue(a.label,o,i).trim()||a.id})),l=new Map;for(const a of s)l.set(a.text,(l.get(a.text)??0)+1);return s.map(a=>(l.get(a.text)??0)>1&&a.text!==a.groupId?{...a,text:`${a.text} (${a.groupId})`}:a)}const os=({open:e,buttonLabel:t,commandId:n,deleteBlockedReason:o,onConfirmHide:i,onConfirmDisplayRule:s,onCancel:l})=>r.jsx(Xt,{open:e,onOpenChange:()=>l(),children:r.jsxs(Vt,{style:{maxWidth:"560px"},children:[r.jsxs(Kt,{children:[r.jsx($r,{style:{marginRight:"8px",color:"var(--colorStatusWarningForeground1)"}}),o?`Can't delete "${t}"`:`Hide "${t}"`]}),r.jsxs(Jt,{children:[r.jsxs(Yt,{children:[o&&r.jsxs(F,{style:{display:"block",marginBottom:"12px"},children:[o," Only buttons your solution adds can be deleted — you can hide this one instead."]}),r.jsx(we,{intent:"warning",children:r.jsxs(Ce,{children:[r.jsx(F,{weight:"semibold",children:"A HideCustomAction removes the button from the ribbon."})," ","To show it again, use Unhide under “Hidden by customizations” in the Properties pane; in a managed solution a hide can't be undone with a patch."]})}),r.jsxs(F,{style:{display:"block",marginTop:"12px"},children:["The reversible alternative adds the display rules ",r.jsx("code",{children:"Mscrm.HideOnModern"})," +"," ",r.jsx("code",{children:"Mscrm.ShowOnlyOnModern"})," (never both true) to the button's command",n?r.jsxs(r.Fragment,{children:[" ",r.jsx("code",{children:n}),". Every button that uses this command is hidden too."]}):r.jsx(r.Fragment,{children:". This button has no command, so only the HideCustomAction is available."})]})]}),r.jsxs(Zt,{children:[r.jsx(J,{appearance:"secondary",onClick:l,children:"Cancel"}),r.jsx(J,{appearance:"secondary",onClick:s,disabled:!n,children:"Use display rules (reversible)"}),r.jsx(J,{appearance:"primary",onClick:i,children:"Use HideCustomAction (permanent)"})]})]})]})}),Qh=({open:e,initialLabel:t,onRename:n,onCancel:o})=>{const[i,s]=L.useState(t),l=i.trim(),a=()=>{l&&(l===t.trim()?o():n(l))};return r.jsx(Xt,{open:e,onOpenChange:(c,d)=>!d.open&&o(),children:r.jsx(Vt,{style:{maxWidth:"440px"},children:r.jsxs(Jt,{children:[r.jsx(Kt,{children:"Rename group"}),r.jsx(Yt,{children:r.jsx(Oe,{label:"Group title",required:!0,validationState:l?"none":"error",validationMessage:l?void 0:"Enter a title for the group.",children:r.jsx(qe,{value:i,onChange:(c,d)=>s(d.value),onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),a())},autoFocus:!0})})}),r.jsxs(Zt,{children:[r.jsx(J,{appearance:"secondary",onClick:o,children:"Cancel"}),r.jsx(J,{appearance:"primary",onClick:a,disabled:!l,children:"Rename"})]})]})})})},eg=e=>e.replace(/^Mscrm\.Templates\./,""),tg=({open:e,currentTemplate:t,customTemplateIds:n=[],loadedGroup:o=!1,onChange:i,onCancel:s})=>{const l=_i(t),[a,c]=L.useState(l),d=[...new Set([...Op,...n,l])],u=()=>{a===l?s():i(a)};return r.jsx(Xt,{open:e,onOpenChange:(p,f)=>!f.open&&s(),children:r.jsx(Vt,{style:{maxWidth:"480px"},children:r.jsxs(Jt,{children:[r.jsx(Kt,{children:"Change group template"}),r.jsxs(Yt,{children:[r.jsx(Oe,{label:"Group template",children:r.jsx(dt,{value:a,onChange:(p,f)=>c(f.value),children:d.map(p=>r.jsxs("option",{value:p,children:[eg(p),p===l?" (current)":""]},p))})}),r.jsx(F,{size:200,style:{display:"block",marginTop:"8px"},children:"The group template defines how buttons scale when the ribbon is resized."}),o&&r.jsx(we,{intent:"warning",style:{marginTop:"12px"},children:r.jsx(Ce,{children:"This group was loaded from the environment. Publishing can't change an existing group's template yet (it's reported as not supported); groups you add publish theirs."})})]}),r.jsxs(Zt,{children:[r.jsx(J,{appearance:"secondary",onClick:s,children:"Cancel"}),r.jsx(J,{appearance:"primary",onClick:u,disabled:a===l,children:"Change template"})]})]})})})},ng=me({destructive:{backgroundColor:m.colorStatusDangerBackground3,color:m.colorNeutralForegroundOnBrand,":hover":{backgroundColor:m.colorStatusDangerBackground3Hover,color:m.colorNeutralForegroundOnBrand},":hover:active":{backgroundColor:m.colorStatusDangerBackground3Pressed,color:m.colorNeutralForegroundOnBrand}}}),lo=({open:e,title:t,children:n,confirmLabel:o,cancelLabel:i="Cancel",destructive:s=!1,onConfirm:l,onCancel:a})=>{const c=ng();return r.jsx(Xt,{modalType:"alert",open:e,onOpenChange:(d,u)=>!u.open&&a(),children:r.jsx(Vt,{style:{maxWidth:"480px"},children:r.jsxs(Jt,{children:[r.jsx(Kt,{children:t}),r.jsx(Yt,{children:n}),r.jsxs(Zt,{children:[r.jsx(J,{appearance:"secondary",onClick:a,children:i}),r.jsx(J,{appearance:"primary",className:s?c.destructive:void 0,onClick:l,children:o})]})]})})})};function nl(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 ol={add:{regular:Ae,filled:_u},delete:{regular:_t,filled:Fu},edit:{regular:fo,filled:Pu},save:{regular:Rr,filled:Lu},copy:{regular:gn,filled:Mu},cut:{regular:Bu,filled:zu},clipboardpaste:{regular:Ou,filled:Eu},share:{regular:Du,filled:Au},mail:{regular:ku,filled:Tu},chat:{regular:Nu,filled:$u},phone:{regular:ju,filled:Ru},search:{regular:ft,filled:Iu},filter:{regular:Cu,filled:wu},arrowleft:{regular:Su,filled:vu},arrowright:{regular:xu,filled:yu},arrowup:{regular:bu,filled:gu},arrowdown:{regular:hu,filled:fu},chevrondown:{regular:gt,filled:pu},chevronup:{regular:Dr,filled:mu},navigation:{regular:uu,filled:du},home:{regular:cu,filled:lu},settings:{regular:Cr,filled:au},info:{regular:ru,filled:su},warning:{regular:$r,filled:iu},checkmark:{regular:ou,filled:nu},dismiss:{regular:po,filled:tu},questioncircle:{regular:Ir,filled:eu},lockclosed:{regular:Rt,filled:Qd},lockopen:{regular:Zd,filled:Yd},shield:{regular:Jd,filled:Kd},person:{regular:Ar,filled:Vd},people:{regular:Xd,filled:Ud},personadd:{regular:Gd,filled:Wd},building:{regular:Hd,filled:qd},briefcase:{regular:_d,filled:Fd},money:{regular:Pd,filled:Ld},creditcard:{regular:Md,filled:Bd},cart:{regular:zd,filled:Od},tag:{regular:Ed,filled:Dd},document:{regular:mo,filled:Ad},documentbulletlist:{regular:kd,filled:Td},folder:{regular:Nd,filled:$d},folderopen:{regular:jd,filled:Rd},attach:{regular:Id,filled:Cd},arrowdownload:{regular:wd,filled:Sd},arrowupload:{regular:vd,filled:xd},globe:{regular:kr,filled:yd},link:{regular:bd,filled:gd},open:{regular:hd,filled:fd},calendar:{regular:pd,filled:md},clock:{regular:ud,filled:dd},timer:{regular:cd,filled:ld},star:{regular:ad,filled:rd},heart:{regular:sd,filled:id},thumblike:{regular:od,filled:nd},thumbdislike:{regular:td,filled:ed},eye:{regular:It,filled:Qc},eyeoff:{regular:Ye,filled:Zc},zoomin:{regular:Yc,filled:Jc},zoomout:{regular:Kc,filled:Vc},maximize:{regular:Xc,filled:Uc},minimize:{regular:Gc,filled:Wc},grid:{regular:Hc,filled:qc},list:{regular:_c,filled:Fc},table:{regular:Tr,filled:Pc},tablesimple:{regular:Lc,filled:Mc},code:{regular:Ut,filled:Bc},bug:{regular:zc,filled:Oc},play:{regular:Ec,filled:Dc},pause:{regular:Ac,filled:kc},stop:{regular:Tc,filled:Nc},refresh:{regular:$c,filled:jc},arrowsync:{regular:Rc,filled:Ic},arrowundo:{regular:vr,filled:Cc},arrowredo:{regular:Sr,filled:wc},printer:{regular:Sc,filled:vc},send:{regular:xc,filled:yc},rocket:{regular:bc,filled:gc},sparkle:{regular:hc,filled:fc},trophy:{regular:pc,filled:mc},lightbulb:{regular:uc,filled:dc},bot:{regular:cc,filled:lc},databar:{regular:ac,filled:rc},chartmultiple:{regular:sc,filled:ic},poll:{regular:oc,filled:nc},layoutcolumntwo:{regular:tc,filled:ec},codeblock:{regular:Ql,filled:Zl},clockarrowcounterclockwise:{regular:Nr,filled:Yl}},Nt=({name:e,size:t=20,variant:n="regular",style:o,className:i,"aria-hidden":s=!0})=>{const l=nl(e).replace(/_/g,""),a=ol[l],c=n==="filled"?a?.filled??a?.regular??qt:a?.regular??qt;return r.jsx(c,{fontSize:t,"aria-hidden":s,className:i,style:{display:"inline-block",verticalAlign:"middle",flexShrink:0,color:m.colorNeutralForeground1,...o}})};async function Hx(e,t=32,n="regular"){const o=nl(e).replace(/_/g,""),i=ol[o],s=n==="filled"?i?.filled??i?.regular:i?.regular;if(!s)return null;const{renderToStaticMarkup:l}=await Ne(async()=>{const{renderToStaticMarkup:c}=await import("./server.browser-xEJRzS2D.js").then(d=>d.s);return{renderToStaticMarkup:c}},__vite__mapDeps([29,2,3]),import.meta.url);let a=l(Ue.createElement(s,{fontSize:t}));return a.includes("<svg")?(a.includes("xmlns")||(a=a.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),a=a.replace(/width="1em"/,`width="${t}"`).replace(/height="1em"/,`height="${t}"`),a=a.replace(/\s(?:class|aria-hidden|focusable|data-fui-icon|font-size)="[^"]*"/g,""),a):null}const il="__end__";function og(e,t){return`slot::${e}::${t??il}`}function ig(e){return`group::${e}`}function Hs(e){if(e.startsWith("slot::")){const[,t,n]=e.split("::");return{kind:"slot",groupId:t,beforeButtonId:n===il?null:n}}return e.startsWith("group::")?{kind:"group",groupId:e.slice(7)}:null}const Ot={root:{display:"flex",gap:m.spacingHorizontalM,flexWrap:"wrap",alignItems:"flex-start",minHeight:"120px",padding:`${m.spacingVerticalS} ${m.spacingHorizontalM}`},groupButtons:{display:"flex",gap:m.spacingHorizontalXS,flexWrap:"wrap",minHeight:"72px",alignItems:"flex-start",padding:m.spacingHorizontalXS},groupLabel:{textAlign:"center",fontSize:m.fontSizeBase100,color:m.colorNeutralForeground3,borderTop:`1px solid ${m.colorNeutralStroke2}`,paddingTop:m.spacingVerticalXS,paddingBottom:m.spacingVerticalXS,marginTop:"auto"},emptyTab:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:m.spacingVerticalM,minHeight:"160px",color:m.colorNeutralForeground3,flex:1,padding:"48px",textAlign:"center"},addGroupBtn:{minHeight:"96px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",border:`1px dashed ${m.colorNeutralStroke2}`,borderRadius:m.borderRadiusMedium,cursor:"pointer",color:m.colorNeutralForeground3,backgroundColor:"transparent"},addButtonGhost:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",width:"60px",minHeight:"72px",borderRadius:m.borderRadiusMedium,border:`1px dashed ${m.colorNeutralStroke2}`,backgroundColor:"transparent",cursor:"pointer",color:m.colorNeutralForeground3}};function sg({button:e}){const t=D(i=>i.locLabels),n=ue(e.label,t),o=e.icon||"apps_add_in";return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:m.borderRadiusMedium,border:`1px solid ${m.colorBrandStroke1}`,backgroundColor:m.colorNeutralBackground1,boxShadow:m.shadow16,opacity:.9,cursor:"grabbing",pointerEvents:"none",color:e.custom?m.colorBrandForeground1:m.colorNeutralForeground1},children:[r.jsx(Nt,{name:o,size:24}),r.jsx("span",{style:{fontSize:m.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:m.colorNeutralForeground1},children:n})]})}function rg({group:e,isDropTarget:t,children:n,...o}){const{setNodeRef:i,isOver:s}=qr({id:ig(e.id),data:{type:"group",groupId:e.id}});return r.jsx("div",{ref:i,style:{display:"flex",flexDirection:"column",minWidth:"80px",border:`1px solid ${s||t?m.colorBrandStroke1:m.colorNeutralStroke2}`,borderRadius:m.borderRadiusMedium,backgroundColor:s||t?m.colorBrandBackground2:m.colorNeutralBackground2,padding:`${m.spacingVerticalXS} ${m.spacingHorizontalXS}`,transition:"border-color 0.1s, background-color 0.1s"},...o,children:n})}function Ws({groupId:e,beforeButtonId:t}){const n=og(e,t),{setNodeRef:o,isOver:i}=qr({id:n,data:{type:"slot",groupId:e,beforeButtonId:t}});return r.jsx("div",{ref:o,style:{width:i?"2px":"0px",minHeight:"72px",backgroundColor:m.colorBrandStroke1,borderRadius:"2px",flexShrink:0,transition:"width 0.1s"},"aria-hidden":!0})}function ag({tab:e,location:t}){const n=D(E=>E.locLabels),o=D(E=>E.baseLanguageCode),i=E=>ue(E.label,n,o)||E.id,s=D(E=>E.baseline),l=D(E=>E.templates),a=D(E=>E.moveButton),c=D(E=>E.createGroup),d=D(E=>E.deleteButton),u=D(E=>E.layers),p=D(E=>E.duplicateButton),f=D(E=>E.duplicateGroup),h=D(E=>E.setGroupTemplate),y=D(E=>E.hideOobButton),x=D(E=>E.customizeOobButton),b=D(E=>E.setButtonProp),g=D(E=>E.renameGroup),S=D(E=>E.deleteGroup),w=ee(E=>E.openNewButton),v=ee(E=>E.openNewGroup),I=ee(E=>E.openIconPicker),A=ee(E=>E.openLocalizationEditor),R=te(E=>E.selectButtonInContext),k=te(E=>E.selectGroup),[N,W]=L.useState(null),[X,O]=L.useState(null),[T,z]=L.useState(null),[$,M]=L.useState(null),[G,K]=L.useState(null),[Q,P]=L.useState(null),[q,V]=L.useState(null),[U,j]=L.useState(null),C=L.useMemo(()=>{if(!q)return null;for(const E of e.groups){const H=E.buttons.find(oe=>oe.id===q);if(H)return{button:H,groupId:E.id}}return null},[q,e.groups]),B=Lr(Un(Fr,{activationConstraint:{distance:5}}),Un(Pr)),Y=E=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&E.oob&&!E.custom,le=E=>Ze(E.kind);function _(E){V(String(E.active.id))}function ce(E){const H=E.over;if(!H){j(null);return}const oe=Hs(String(H.id));j(oe?oe.groupId:null)}function Ee(E){const{active:H,over:oe}=E;if(V(null),j(null),!oe||!H)return;let ne=null;for(const kt of e.groups)if(kt.buttons.some(Xl=>Xl.id===H.id)){ne=kt.id;break}if(!ne)return;const je=Hs(String(oe.id));if(!je)return;let re=null;je.kind==="slot"?re=a({groupId:ne,buttonId:String(H.id),tabId:e.id,location:t},{groupId:je.groupId,beforeButtonId:je.beforeButtonId??void 0,tabId:e.id,location:t}):je.kind==="group"&&je.groupId!==ne&&(re=a({groupId:ne,buttonId:String(H.id),tabId:e.id,location:t},{groupId:je.groupId,tabId:e.id,location:t})),re&&re!==String(H.id)&&R(t,e.id,je.groupId,re)}return e.groups.length===0?r.jsxs("div",{style:Ot.emptyTab,children:[r.jsx(mo,{fontSize:36,"aria-hidden":!0}),r.jsx(F,{children:"This tab has no groups yet"}),r.jsxs("button",{type:"button",style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 16px",background:m.colorBrandBackground,color:m.colorNeutralForegroundInverted,border:"none",borderRadius:m.borderRadiusMedium,cursor:"pointer",fontSize:m.fontSizeBase300},onClick:()=>v(),children:[r.jsx(Ae,{fontSize:12})," Add first group"]})]}):r.jsxs(r.Fragment,{children:[t==="SubGrid"&&r.jsx(we,{intent:"info",style:{margin:`${m.spacingVerticalS} ${m.spacingHorizontalM} 0`},children:r.jsxs(Ce,{children:["Subgrid ribbons support only 3 native controls: ",r.jsx("strong",{children:"Add"}),","," ",r.jsx("strong",{children:"Show List"}),", and ",r.jsx("strong",{children:"Delete"}),". Their icons cannot be changed."]})}),r.jsxs(_r,{sensors:B,collisionDetection:$m,onDragStart:_,onDragOver:ce,onDragEnd:Ee,children:[r.jsxs("div",{style:Ot.root,role:"treegrid","aria-label":"Ribbon canvas","data-ribbon-canvas-root":"1",children:[e.groups.map(E=>r.jsxs(rg,{group:E,isDropTarget:U===E.id,role:"rowgroup","aria-label":i(E),tabIndex:0,"data-ribbon-group-id":E.id,onContextMenu:H=>{H.target.closest("[data-btn]")||(H.preventDefault(),O({group:E,x:H.clientX,y:H.clientY}))},onFocus:()=>k(E.id),onKeyDown:H=>{if((H.key==="Enter"||H.key===" ")&&E.buttons.length>0){H.preventDefault();const oe=E.buttons[0];if(!oe)return;R(t,e.id,E.id,oe.id),document.querySelector(`[data-ribbon-btn-id="${oe.id}"]`)?.focus()}},children:[r.jsxs("div",{style:Ot.groupButtons,children:[E.buttons.map(H=>r.jsxs(Ue.Fragment,{children:[q&&r.jsx(Ws,{groupId:E.id,beforeButtonId:H.id}),r.jsx(lg,{button:H,groupId:E.id,tabId:e.id,location:t,activeId:q,onContextMenu:oe=>W({groupId:E.id,button:H,x:oe.clientX,y:oe.clientY})})]},H.id)),q&&r.jsx(Ws,{groupId:E.id,beforeButtonId:null}),r.jsxs("button",{type:"button",style:Ot.addButtonGhost,"data-add-btn-group-id":E.id,onClick:()=>w(E.id),title:`Add button to ${i(E)}`,"aria-label":`Add button to ${i(E)}`,children:[r.jsx(Ae,{fontSize:16}),r.jsx(F,{size:100,style:{color:"inherit"},children:"Add"})]})]}),r.jsx(Te,{content:`Template: ${E.template||"Flexible2"}`,relationship:"description",children:r.jsx("div",{style:Ot.groupLabel,children:i(E)})})]},E.id)),r.jsx("button",{type:"button",style:Ot.addGroupBtn,onClick:()=>c({tabId:e.id,location:t,group:{label:"New Group",sequence:(e.groups.length+1)*10,template:"Flexible2",buttons:[]}}),title:"Add group","aria-label":"Add group",children:r.jsx(Ae,{fontSize:16})})]}),r.jsx(Nm,{dropAnimation:null,children:C?r.jsx(sg,{button:C.button}):null})]}),N&&r.jsxs(Zo,{open:!0,onOpenChange:(E,H)=>!H.open&&W(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:N.x,y:N.y,top:N.y,left:N.x,right:N.x,bottom:N.y,width:0,height:0,toJSON:()=>({})})}},children:[r.jsx(Qo,{disableButtonEnhancement:!0,children:r.jsx("span",{style:{display:"none"}})}),r.jsx(ei,{children:r.jsxs(ti,{children:[Y(N.button)&&r.jsx(fe,{disabled:!0,icon:r.jsx(Rt,{}),children:"OOB global command bar buttons cannot be customized."}),Y(N.button)&&r.jsx(pt,{}),r.jsx(fe,{icon:r.jsx(fo,{}),onClick:()=>{R(t,e.id,N.groupId,N.button.id),W(null)},children:"Edit properties"}),r.jsx(fe,{icon:r.jsx(Gn,{}),disabled:Y(N.button)||le(N.button),onClick:()=>{R(t,e.id,N.groupId,N.button.id),I(),W(null)},children:"Change icon…"}),r.jsx(fe,{icon:r.jsx(Er,{}),disabled:Y(N.button)||le(N.button),onClick:()=>{A(N.button.id),W(null)},children:"Edit labels…"}),r.jsx(pt,{}),N.button.hidden?r.jsx(fe,{icon:r.jsx(It,{}),disabled:Y(N.button),onClick:()=>{b(t,e.id,N.groupId,N.button.id,{hidden:!1}),W(null)},children:"Show button"}):r.jsx(fe,{icon:r.jsx(Ye,{}),disabled:Y(N.button),onClick:()=>{N.button.oob?z(N):b(t,e.id,N.groupId,N.button.id,{hidden:!0}),W(null)},children:"Hide button"}),(N.button.origin==="oob"||N.button.origin==="managed")&&r.jsx(fe,{icon:r.jsx(qt,{}),disabled:Y(N.button)||le(N.button),onClick:()=>{x(t,e.id,N.groupId,N.button.id),W(null)},children:"Create override…"}),r.jsx(el,{location:t,tabId:e.id,groupId:N.groupId,button:N.button,onDone:()=>W(null)}),r.jsx(pt,{}),r.jsx(fe,{icon:r.jsx(gn,{}),disabled:Y(N.button),onClick:()=>{p(t,e.id,N.groupId,N.button.id),W(null)},children:"Duplicate"}),tl(e,N.groupId,N.button.id,n,o).map(E=>r.jsxs(fe,{icon:r.jsx(Or,{}),disabled:Y(N.button),onClick:()=>{const H=a({groupId:N.groupId,buttonId:N.button.id,tabId:e.id,location:t},{groupId:E.groupId,tabId:e.id,location:t});H&&R(t,e.id,E.groupId,H),W(null)},children:["Move to: ",E.text]},E.groupId)),Nn(N.button,s[t])&&r.jsxs(r.Fragment,{children:[r.jsx(pt,{}),r.jsx(fe,{icon:r.jsx(_t,{}),disabled:Y(N.button),onClick:()=>{d(t,e.id,N.groupId,N.button.id),W(null)},children:"Delete"})]})]})})]}),X&&r.jsxs(Zo,{open:!0,onOpenChange:(E,H)=>!H.open&&O(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:X.x,y:X.y,top:X.y,left:X.x,right:X.x,bottom:X.y,width:0,height:0,toJSON:()=>({})})}},children:[r.jsx(Qo,{disableButtonEnhancement:!0,children:r.jsx("span",{style:{display:"none"}})}),r.jsx(ei,{children:r.jsxs(ti,{children:[Ca("group",X.group.id,s[t],Yi({layers:u},t))?r.jsx(fe,{icon:r.jsx(ps,{}),onClick:()=>{M(X.group),O(null)},children:"Rename…"}):r.jsx(fe,{icon:r.jsx(ps,{}),disabled:!0,title:Gi,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),r.jsx(fe,{icon:r.jsx(gn,{}),onClick:()=>{f(t,e.id,X.group.id),O(null)},children:"Duplicate group"}),r.jsx(fe,{icon:r.jsx(qt,{}),onClick:()=>{K(X.group),O(null)},children:"Change template…"}),Wi(X.group,s[t],oo({layers:u},t))&&r.jsxs(r.Fragment,{children:[r.jsx(pt,{}),r.jsx(fe,{icon:r.jsx(_t,{}),onClick:()=>{P(X.group),O(null)},children:"Delete group"})]})]})})]}),$&&r.jsx(Qh,{open:!0,initialLabel:i($),onRename:E=>{g(t,e.id,$.id,E),M(null)},onCancel:()=>M(null)}),G&&r.jsx(tg,{open:!0,currentTemplate:G.template,customTemplateIds:l.map(E=>E.id),loadedGroup:s[t].tabs.some(E=>E.id===e.id&&E.groups.some(H=>H.id===G.id)),onChange:E=>{h(t,e.id,G.id,E),K(null)},onCancel:()=>K(null)}),Q&&r.jsxs(lo,{open:!0,title:"Delete group",confirmLabel:"Delete group",destructive:!0,onConfirm:()=>{S(t,e.id,Q.id),P(null)},onCancel:()=>P(null),children:["Delete the group “",i(Q),"” and its ",Q.buttons.length," button",Q.buttons.length===1?"":"s","?"]}),T&&r.jsx(os,{open:!0,buttonLabel:ue(T.button.label,n),onConfirmHide:()=>{y(t,e.id,T.groupId,T.button.id),z(null)},commandId:T.button.commandId,onConfirmDisplayRule:()=>{D.getState().hideWithDisplayRules(T.button.commandId),z(null)},onCancel:()=>z(null)})]})}const lg=Ue.memo(function({button:t,groupId:n,tabId:o,location:i,activeId:s,onContextMenu:l}){const a=te(R=>R.selectedButtonId),c=te(R=>R.selectButtonInContext),d=D(R=>R.locLabels),u=a===t.id,p=i==="Application"&&o==="Mscrm.GlobalTab"&&t.oob&&!t.custom,f=ue(t.label,d),h=Ze(t.kind)?Vn[t.kind]:void 0,y=h?` (${h}, read-only)`:"",{attributes:x,listeners:b,setNodeRef:g,isDragging:S}=jm({id:t.id,data:{type:"button",button:t,groupId:n},disabled:t.managed||p}),w=S||s===t.id,v={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:m.borderRadiusMedium,cursor:"grab",border:u?`1px solid ${m.colorBrandStroke1}`:t.custom?`1px solid ${m.colorBrandStroke2}`:"1px solid transparent",backgroundColor:u?m.colorBrandBackground2:t.managed?m.colorNeutralBackground3:"transparent",opacity:w?.3:t.hidden?.4:1,position:"relative",userSelect:"none",color:t.custom?m.colorBrandForeground1:m.colorNeutralForeground1,transition:"opacity 0.15s, border-color 0.1s, background-color 0.1s"},I=t.icon||"apps_add_in",A=R=>{if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(R.key))return;R.preventDefault();const k=R.currentTarget.closest("[data-ribbon-canvas-root='1']");if(!k)return;const N=Array.from(k.querySelectorAll(`[data-ribbon-tab-id="${o}"][data-btn="1"]`)),W=N.findIndex(M=>M.dataset.ribbonBtnId===t.id);if(W<0||N.length===0)return;const X=R.key==="ArrowLeft"||R.key==="ArrowUp"?-1:1,O=Math.max(0,Math.min(N.length-1,W+X)),T=N[O],z=T?.dataset.ribbonGroupId,$=T?.dataset.ribbonBtnId;!T||!z||!$||(c(i,o,z,$),T.focus())};return r.jsx(Te,{content:p?"OOB global command bar buttons cannot be customized.":`${f}${y}${t.hidden?" — hidden":""}`,relationship:"label",children:r.jsxs("button",{ref:g,type:"button","data-btn":"1","data-ribbon-tab-id":o,"data-ribbon-group-id":n,"data-ribbon-btn-id":t.id,style:v,"aria-selected":u,"aria-label":`${f}${y}${t.hidden?" — hidden":""}${t.custom?" (custom)":""}${t.managed?" (read-only)":""}`,onClick:()=>c(i,o,n,t.id),onFocus:()=>c(i,o,n,t.id),onKeyDown:R=>{if(R.key==="Enter"||R.key===" "){R.preventDefault(),c(i,o,n,t.id);return}A(R)},onContextMenu:R=>{R.preventDefault(),R.stopPropagation(),c(i,o,n,t.id),l(R)},...x,...b,children:[r.jsx(Nt,{name:I,size:24,style:{filter:t.custom?"none":"grayscale(40%) opacity(0.85)"}}),r.jsx("span",{style:{fontSize:m.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:m.colorNeutralForeground1},children:f}),h&&r.jsx("span",{style:{fontSize:m.fontSizeBase100,lineHeight:"1",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:m.colorNeutralForeground3},children:h}),t.menu&&r.jsx(gt,{fontSize:10,"aria-label":"Has a menu"}),t.hidden&&r.jsx("span",{style:{position:"absolute",top:2,right:2},"aria-hidden":!0,children:r.jsx(Ye,{fontSize:10,style:{color:m.colorNeutralForeground3}})}),t.custom&&!t.managed&&r.jsx(de,{size:"extra-small",color:"brand",appearance:"tint",style:{position:"absolute",bottom:2,right:2},"aria-label":"Custom",children:"NEW"}),(t.managed||p)&&r.jsx("span",{style:{position:"absolute",top:2,left:2},title:p?"OOB global command bar buttons cannot be customized.":"Read-only (managed)",children:r.jsx(Rt,{fontSize:10,style:{color:m.colorNeutralForeground3}})})]})})}),be=$t()((e,t)=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],appFilter:"all",selectedCommandId:null,loadToken:0,beginLoad(n){const o=t().loadToken+1;return e({tableLogicalName:n,status:"loading",error:null,commands:[],apps:[],selectedCommandId:null,loadToken:o}),o},finishLoad(n,o){if(n!==t().loadToken)return;const{appFilter:i}=t(),s=i==="all"||o.apps.some(l=>l.id===i);e({status:o.error?"unavailable":"loaded",error:o.error??null,commands:o.commands,apps:o.apps,appFilter:s?i:"all"})},reset(){e(n=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],selectedCommandId:null,appFilter:"all",loadToken:n.loadToken+1}))},setAppFilter(n){e({appFilter:n?n.toLowerCase():"all"})},selectCommand(n){n&&te.getState().clearSelection(),e({selectedCommandId:n})}}));te.subscribe((e,t)=>{if(!be.getState().selectedCommandId)return;(e.selectedButtonId&&e.selectedButtonId!==t.selectedButtonId||e.location!==t.location||e.tabId!==t.tabId)&&be.setState({selectedCommandId:null})});const dn={Form:0,MainGrid:1,SubGrid:2,AssociatedGrid:3,GlobalHeader:5},sl={0:"Form",1:"Main grid",2:"Subgrid",3:"Associated grid",4:"Quick form",5:"Global header",6:"Dashboard"},rl="appaction_appactionrule_classicrules",cg=["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"],Uo="@OData.Community.Display.V1.FormattedValue",Re=e=>typeof e=="string"&&e.trim()!==""?e:typeof e=="number"?String(e):void 0,ct=e=>{if(e==null||e==="")return;const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0},Bn=e=>e===!0||e===1||e==="true"||e==="1",xt=e=>{const t=Re(e);return t?t.toLowerCase():null};function dg(e){switch(ct(e)){case 1:return"dropdown";case 2:return"split";case 3:return"group";default:return"button"}}function ug(e){const t=ct(e);return t===1?"formula":t===2?"javascript":"none"}function mg(e){const t=ct(e);return t===1?"formula":t===2?"classicRules":"none"}function pg(e){const t=ct(e);return t===1?"migrated":t===2?"enhancedMigrated":"default"}function Gs(e,t){const n={componentLibrary:Re(e[`${t}componentlibrary`]),componentName:Re(e[`${t}componentname`]),functionName:Re(e[`${t}functionname`])};return n.componentLibrary||n.componentName||n.functionName?n:void 0}function fg(e){return Array.isArray(e)?e.map(t=>{const n=xt(t.appactionruleid);return n?{id:n,name:Re(t.name)??Re(t.uniquename)??n,uniqueName:Re(t.uniquename),kind:ct(t.type)===0?"enable":"display"}:null}).filter(t=>t!==null):[]}function hg(e){const t=xt(e.appactionid);if(!t)return null;const n=ct(e.location);if(n===void 0)return null;const o=Re(e.name)??"",i=Re(e.uniquename)??o;return{id:t,name:o,uniqueName:i,label:Re(e.buttonlabeltext)??(o||i||t),tooltipTitle:Re(e.buttontooltiptitle),tooltipDescription:Re(e.buttontooltipdescription),accessibilityText:Re(e.buttonaccessibilitytext),appModuleId:xt(e._appmoduleid_value),appName:Re(e[`_appmoduleid_value${Uo}`]),scope:ct(e.context)===0?"all":"entity",contextValue:Re(e.contextvalue),contextEntityId:xt(e._contextentity_value)??void 0,location:n,type:dg(e.type),sequence:ct(e.sequence)??ct(e.buttonsequencepriority)??0,hidden:Bn(e.hidden),disabled:Bn(e.isdisabled),origin:pg(e.origin),managed:Bn(e.ismanaged),fontIcon:Re(e.fonticon),iconWebResourceId:xt(e._iconwebresourceid_value)??void 0,iconWebResourceName:Re(e[`_iconwebresourceid_value${Uo}`]),parentId:xt(e._parentappactionid_value),groupTitle:Re(e.grouptitle),groupTitleHidden:Bn(e.isgrouptitlehidden),action:ug(e.onclickeventtype),jsFunctionName:Re(e.onclickeventjavascriptfunctionname),jsParameters:Re(e.onclickeventjavascriptparameters),jsWebResourceId:xt(e._onclickeventjavascriptwebresourceid_value)??void 0,jsWebResourceName:Re(e[`_onclickeventjavascriptwebresourceid_value${Uo}`]),onSelectFormula:Gs(e,"onclickeventformula"),visibility:mg(e.visibilitytype),visibilityFormula:Gs(e,"visibilityformula"),classicRules:fg(e[rl])}}function gg(e){const t=new Map;for(const n of e){const o=hg(n);o&&!t.has(o.id)&&t.set(o.id,o)}return[...t.values()]}function bg(e){switch(e){case"HomepageGrid":return[dn.MainGrid];case"SubGrid":return[dn.SubGrid,dn.AssociatedGrid];case"Form":return[dn.Form];case"Application":return[dn.GlobalHeader]}}function yg(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 xg(e,t){return t==="all"||e.appModuleId===null||e.appModuleId===t.toLowerCase()}function vg(e,t){const n=new Set(bg(t.location));return e.filter(o=>n.has(o.location)&&xg(o,t.appFilter)&&yg(o,t.table))}const $i=(e,t)=>e.sequence-t.sequence||e.label.localeCompare(t.label)||e.id.localeCompare(t.id);function al(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 a=n.get(l.parentId)??[];a.push(l),n.set(l.parentId,a)}else o.push(l);const i=new Set,s=l=>{i.add(l.id);const a=(n.get(l.id)??[]).filter(c=>!i.has(c.id)).sort($i);return{command:l,children:a.map(s)}};return o.sort($i).map(s)}function ll(e){return e.flatMap(t=>[t.command,...ll(t.children)])}const cl=/\{!EntityLogicalName\}/gi,Sg=/(?:![A-Za-z0-9_]+)*!\d+$/;function wg(e,t){if(e.origin==="default")return[];const n=[],o=i=>{i.includes(".")&&!n.includes(i)&&n.push(i)};for(const i of[e.uniqueName,e.name]){if(!i)continue;const s=i.trim().replace(cl,t).replace(Sg,""),l=s.indexOf("_"),a=s.indexOf(".");l>0&&(a===-1||l<a)&&o(s.slice(l+1)),o(s)}return n}function Ni(e,t){return e.replace(cl,t).toLowerCase()}function Us(e,t){const n=Ni(e,t).split(".");return n.length<4||n[0]!=="mscrm"?null:[n[0],n[1],"*",...n.slice(3)].join(".")}function Xs(e,t,n,o={}){const i=new Map,s=new Map;for(const a of t){const c=Ni(a,n);i.has(c)||i.set(c,a);const d=Us(a,n);d&&!s.has(d)&&s.set(d,a)}const l=new Map;for(const a of e){if(a.disabled&&!o.includeDisabled)continue;const c=wg(a,n),d=c.map(p=>i.get(Ni(p,n))).find(Boolean)??c.map(p=>Us(p,n)).map(p=>p?s.get(p):void 0).find(Boolean);if(!d)continue;const u=l.get(d)??[];u.push({buttonId:d,command:a,effect:a.hidden?"hidden":"replaced"}),l.set(d,u)}return l}function Cg(e,t,n){const o=l=>l.toLowerCase(),i=`mscrm.${o(t)}.${o(n)}.maintab`,s=e.find(l=>l.id==="Mscrm.GlobalTab")?.id;return t==="Application"&&s?s:e.find(l=>o(l.id)===i)?.id??e.find(l=>/maintab$/i.test(l.id)&&!/\.allentities\./i.test(l.id))?.id??s??e[0]?.id}function dl(e){return(e.menu?.sections??[]).flatMap(t=>t.controls.flatMap(n=>[n,...dl(n)]))}function Ig(e){const{commands:t,tabs:n,location:o,entityLogicalName:i}=e,s=n.flatMap(g=>g.groups.flatMap(S=>S.buttons)),l=[...s,...s.flatMap(dl)].map(g=>g.id),a=new Map(t.map(g=>[g.id,g])),c=new Set([...Xs(t,l,i,{includeDisabled:!0}).values()].flat().map(g=>g.command.id)),d=new Map,u=(g,S=new Set)=>{const w=d.get(g.id);if(w!==void 0)return w;let v=g.parentId?a.get(g.parentId):void 0;for(const A=new Set;v?.type==="group"&&!c.has(v.id)&&!A.has(v.id);)A.add(v.id),v=v.parentId?a.get(v.parentId):void 0;const I=c.has(g.id)&&(!v||!S.has(v.id)&&u(v,S.add(g.id)));return d.set(g.id,I),I},f=(g=>{for(const[S,w]of g){const v=w.filter(I=>u(I.command));v.length>0?g.set(S,v):g.delete(S)}return g})(Xs(t,l,i)),h=new Set([...f.values()].flat().map(g=>g.command.id)),y=g=>{const S=new Set;for(let w=g.parentId;w&&!S.has(w);w=a.get(w)?.parentId??null){S.add(w);const v=a.get(w);if(v&&u(v))return w}},x=new Map,b=[];for(const g of t){const S=y(g);if(!S){u(g)||b.push(g);continue}if(h.has(g.id))continue;const w=x.get(S)??[];w.push(g),x.set(S,w)}for(const g of f.values())for(const S of g){const w=x.get(S.command.id);w&&(S.items=[...w].sort($i))}return{commandBarTabId:Cg(n,o,i),nodes:al(b),overrides:f,unmatchedMigrated:b.filter(g=>g.origin!=="default")}}function Rg(e,t){const n=new Map,o=[];for(const i of t){const s=e.find(a=>a.sequence>i.command.sequence);if(!s){o.push(i);continue}const l=n.get(s.id)??[];l.push(i),n.set(s.id,l)}return{before:n,trailing:o}}function Vs(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 jg(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 $g(e,t,n){const o=new Map(t.map(s=>[s.id.toLowerCase(),s])),i=new Map;for(const s of n??[]){const l=o.get(s.toLowerCase());l&&i.set(l.id.toLowerCase(),l)}if(n)return[...i.values()].sort((s,l)=>s.name.localeCompare(l.name)||s.id.localeCompare(l.id));for(const s of e)!s.appModuleId||i.has(s.appModuleId)||i.set(s.appModuleId,o.get(s.appModuleId)??{id:s.appModuleId,name:s.appName??s.appModuleId});return[...i.values()].sort((s,l)=>s.name.localeCompare(l.name)||s.id.localeCompare(l.id))}function Cn(e,t){return e.appModuleId===null?"All apps":t?.get(e.appModuleId)??e.appName??e.appModuleId}function is(e,t){const n=Cn(e.command,t),o=e.command.appModuleId===null?"in all apps":`in ${n}`,i=e.effect==="hidden"?`Hidden by modern command ${e.command.label} ${o}`:`Rendered as modern command ${e.command.label} ${o} (migrated)`;return e.items?.length?`${i}; its menu also has ${e.items.map(s=>s.label).join(", ")}`:i}function ul(e,t){if(!e?.length)return"";const n=e.find(o=>o.effect==="hidden");return n?` — ${is(n,t).replace(/^Hidden/,"hidden")}`:" — modern (migrated)"}const Ng={button:"Command",dropdown:"Dropdown",split:"Split button",group:"Group"},Tg={default:"Command designer",migrated:"Migrated from classic",enhancedMigrated:"Enhanced migrated from classic"};function ml(e,t){const n=[{label:"App",value:Cn(e,t)},{label:"Location",value:`${sl[e.location]??`Location ${e.location}`}${e.scope==="all"?" (all tables)":""}`},{label:"Type",value:Ng[e.type]},{label:"Order",value:String(e.sequence)},{label:"Origin",value:Tg[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:Vs(e.visibilityFormula)??"Power Fx formula"});else if(e.visibility==="classicRules"){const o=e.classicRules.filter(i=>i.kind==="display").map(i=>i.name);n.push({label:"Visibility",value:o.length?`Classic rules: ${o.join(", ")}`:"Classic rules"})}if(e.action==="formula")n.push({label:"OnSelect (Power Fx)",value:Vs(e.onSelectFormula)??"Power Fx formula"});else if(e.action==="javascript"){const o=e.jsWebResourceName??e.jsWebResourceId,i=e.jsFunctionName??"(no function)";n.push({label:"Action (JavaScript)",value:o?`${i} in ${o}`:i}),e.jsParameters&&n.push({label:"Parameters",value:e.jsParameters})}return n}function kg(){return window.dataverseAPI}const In=e=>e instanceof Error?e.message:String(e);async function co(e){const t=[],n=new Set;let o=e;for(;o&&!n.has(o);){n.add(o);const i=await kg().queryData(o);t.push(...i.value??[]);const s=i["@odata.nextLink"];o=s?s.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}function pl(e){return/\b40[13]\b|0x80040220|prvRead|privilege|unauthori[sz]ed|forbidden|not have permission/i.test(In(e))}const fl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ks(e,t){const n=[`contextvalue eq '${e.logicalName.replace(/'/g,"''")}'`];e.metadataId&&fl.test(e.metadataId)&&n.push(`_contextentity_value eq ${e.metadataId}`);const o=`statecode eq 0 and (context eq 0 or ${n.join(" or ")}) and (location eq 0 or location eq 1 or location eq 2 or location eq 3 or location eq 5)`,i=t?`&$expand=${rl}($select=appactionruleid,name,uniquename,type)`:"";return`appactions?$select=${cg.join(",")}&$filter=${o}${i}`}async function Ag(e){const t=se.getState();let n;try{n=await co(Ks(e,!0))}catch(o){if(pl(o))throw o;t.logInfo("dataverse",`Modern commands: classic rules couldn't be expanded (${In(o)}); retrying without them.`),n=await co(Ks(e,!1))}return gg(n)}async function Dg(e){const t=se.getState(),n="appmodules?$select=appmoduleid,appmoduleidunique,name,uniquename",o=e.metadataId&&fl.test(e.metadataId)?`appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 1 and objectid eq ${e.metadataId}`:null,[i,s]=await Promise.all([co(n),o?co(o).catch(d=>(t.logInfo("dataverse",`Modern commands: couldn't resolve which apps contain ${e.logicalName} (${In(d)}).`),null)):Promise.resolve(null)]),l=i,a=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(s){const d=new Set(s.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:a,containingAppIds:c}}async function Eg(e){const t=se.getState(),[n,o]=await Promise.allSettled([Ag(e),Dg(e)]);if(n.status==="rejected"){const a=In(n.reason);return t.logWarn("dataverse",pl(n.reason)?`No permission to read modern commands (appaction) for ${e.logicalName}; the canvas shows classic commands only. (${a})`:`Modern commands unavailable for ${e.logicalName}: ${a}`),{commands:[],apps:[],error:a}}o.status==="rejected"&&t.logInfo("dataverse",`Modern commands: app list unavailable (${In(o.reason)}); showing app ids from the commands.`);const{apps:i,containingAppIds:s}=o.status==="fulfilled"?o.value:{apps:[],containingAppIds:null},l=jg(n.value,s);return t.logInfo("dataverse",`Loaded ${l.length} modern command${l.length===1?"":"s"} for ${e.logicalName}.`),{commands:l,apps:$g(l,i,s)}}function Og(){const e=ie(n=>n.activeEntity?.logicalName),t=ie(n=>n.activeEntity?.metadataId);L.useEffect(()=>{const n=be.getState();if(!e||typeof window.dataverseAPI>"u"){n.reset();return}const o=n.beginLoad(e);Eg({logicalName:e,metadataId:t}).then(i=>be.getState().finishLoad(o,i))},[e,t])}function tn(){const e=be(n=>n.apps),t=be(n=>n.commands);return L.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 hl(e){const t=be(s=>s.commands),n=be(s=>s.appFilter),o=ie(s=>s.activeEntity?.logicalName),i=ie(s=>s.activeEntity?.metadataId);return L.useMemo(()=>o?vg(t,{location:e,appFilter:n,table:{logicalName:o,metadataId:i}}):[],[t,n,e,o,i])}const Ti=new Set;function zg(){Ti.clear()}function ss(e){const t=hl(e),n=ie(u=>u.activeEntity?.logicalName)??"",o=D(u=>u.ribbons[e]?.tabs),i=D(u=>u.ribbons[e]?.entityLogicalName??""),s=be(u=>u.status==="loaded"?u.tableLogicalName:null),l=(o?.length??0)>0&&(e==="Application"||i.toLowerCase()===n.toLowerCase()),a=L.useMemo(()=>Ig({commands:t,tabs:l?o??[]:[],location:e,entityLogicalName:n}),[t,o,l,e,n]),d=!!n&&s===n&&l?a.unmatchedMigrated.map(u=>u.uniqueName).join(", "):"";return L.useEffect(()=>{const u=`${n}|${e}|${d}`;!d||Ti.has(u)||(Ti.add(u),se.getState().logInfo("ribbon",`Migrated modern commands without a classic control in ${n} ${e}: ${d}`))},[d,n,e]),a}function rs(e,t){const n=ss(e);return L.useMemo(()=>{const o=t.groups.flatMap(s=>s.buttons.map(l=>({id:l.id,sequence:l.sequence}))),i=t.id===n.commandBarTabId?n.nodes:[];return{nodes:i,placement:Rg(o,i),overrides:n.overrides}},[n,t])}function Bg(e,t){const{overrides:n}=ss(e);return t&&n.get(t)||Mg}const Mg=[];function Lg(){const e=be(i=>i.selectedCommandId),t=te(i=>i.selectedButtonId),n=te(i=>i.location),o=hl(n);return L.useMemo(()=>{if(!e||t)return null;const i=o.find(l=>l.id===e);if(!i)return null;let s;for(const l of al(o))if(s=gl(l,e),s)break;return{command:i,children:s?ll(s.children):[]}},[e,t,o])}function gl(e,t){if(e.command.id===t)return e;for(const n of e.children){const o=gl(n,t);if(o)return o}}const bl=me({chip:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,height:"32px",padding:`0 ${m.spacingHorizontalS}`,borderRadius:m.borderRadiusMedium,border:`1px dashed ${m.colorPaletteBerryBorderActive}`,backgroundColor:m.colorPaletteBerryBackground1,color:m.colorNeutralForeground1,cursor:"default",whiteSpace:"nowrap",flexShrink:0,userSelect:"none",":hover":{backgroundColor:m.colorPaletteBerryBackground2},":focus-visible":{outline:`2px solid ${m.colorBrandStroke1}`,outlineOffset:"2px"}},selected:{border:`1px solid ${m.colorPaletteBerryForeground2}`,backgroundColor:m.colorPaletteBerryBackground2},muted:{opacity:.5},hidden:{textDecoration:"line-through"},tooltip:{display:"flex",flexDirection:"column",gap:"2px",maxWidth:"360px"},tooltipRow:{fontSize:m.fontSizeBase200,overflowWrap:"anywhere"}});function yl({node:e,appNames:t}){const n=bl(),o=e.command;return r.jsxs("div",{className:n.tooltip,children:[r.jsx(F,{weight:"semibold",children:o.label}),r.jsx(F,{className:n.tooltipRow,children:"Modern command — read-only in CBS; edit it in the command designer."}),ml(o,t).map(i=>r.jsxs(F,{className:n.tooltipRow,children:[r.jsxs("b",{children:[i.label,":"]})," ",i.value]},i.label)),e.children.length>0&&r.jsxs(F,{className:n.tooltipRow,children:[r.jsx("b",{children:"Items:"})," ",e.children.map(i=>i.command.label).join(", ")]})]})}function Pg({node:e,appNames:t,showApp:n,onDragRejected:o}){const i=bl(),s=e.command,l=be(y=>y.selectedCommandId),a=be(y=>y.selectCommand),c=te(y=>y.selectedButtonId),d=l===s.id&&!c,u=s.type==="dropdown"||s.type==="split"||e.children.length>0,p=s.fontIcon&&!s.fontIcon.startsWith("$")?s.fontIcon:"apps_add_in",f=`${s.hidden?" — hidden":""}${s.disabled?" — disabled":""}`,h=y=>{y.preventDefault(),y.stopPropagation(),y.dataTransfer.dropEffect="none",o?.()};return r.jsx(Te,{content:r.jsx(yl,{node:e,appNames:t}),relationship:"description",children:r.jsxs("button",{type:"button",draggable:!1,className:Ht(i.chip,d&&i.selected,(s.hidden||s.disabled)&&i.muted,s.hidden&&i.hidden),"aria-pressed":d,"aria-label":`${s.label} — modern command (read-only), ${Cn(s,t)}${f}`,onClick:()=>a(s.id),onDragStart:y=>y.preventDefault(),onDragOver:h,onDrop:h,onContextMenu:y=>{y.preventDefault(),a(s.id)},children:[r.jsx(Nt,{name:p,size:16}),r.jsx(F,{size:200,children:s.label}),u&&r.jsx(gt,{fontSize:12,"aria-hidden":!0}),s.hidden&&r.jsx(Ye,{fontSize:12,"aria-hidden":!0}),r.jsx(de,{size:"extra-small",appearance:"tint",color:"important",icon:r.jsx(Rt,{}),children:"Modern"}),n&&r.jsx(de,{size:"extra-small",appearance:"outline",color:"informative",children:Cn(s,t)})]})})}function as({overrides:e,appNames:t}){if(!e?.length)return null;const n=e.some(i=>i.effect==="hidden"),o=e.map(i=>is(i,t)).join(`
132
+ `);return r.jsx(de,{size:"extra-small",appearance:"tint",color:n?"warning":"important",title:o,"aria-label":o,children:n?"Hidden by modern":"Modern (migrated)"})}const Mn="application/x-rw-btn",Js="application/x-rw-se",Fg=me({root:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,padding:`${m.spacingHorizontalS} 0`,minHeight:"48px"},scrollRow:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,flex:1,minWidth:0,overflowX:"auto",overflowY:"hidden",paddingBottom:m.spacingHorizontalXS},button:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,height:"32px",padding:`0 ${m.spacingHorizontalS}`,borderRadius:m.borderRadiusMedium,border:"1px solid transparent",cursor:"pointer",backgroundColor:"transparent",color:m.colorNeutralForeground1,whiteSpace:"nowrap",position:"relative",userSelect:"none",":hover":{backgroundColor:m.colorNeutralBackground3,border:`1px solid ${m.colorNeutralStroke1}`},":focus-visible":{outline:`2px solid ${m.colorBrandStroke1}`,outlineOffset:"2px"}},buttonSelected:{backgroundColor:m.colorBrandBackground2,border:`1px solid ${m.colorBrandStroke1}`},buttonHidden:{opacity:.4,textDecoration:"line-through"},buttonCustom:{border:`1px solid ${m.colorBrandStroke2}`},lockIcon:{position:"absolute",top:"4px",left:"4px",color:m.colorNeutralForeground3,pointerEvents:"none"},dropLine:{width:"2px",height:"24px",backgroundColor:m.colorBrandStroke1,borderRadius:"2px",flexShrink:0},overflowBtn:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,height:"32px",padding:`0 ${m.spacingHorizontalS}`,borderRadius:m.borderRadiusMedium,border:`1px solid ${m.colorNeutralStroke2}`,backgroundColor:m.colorNeutralBackground2,cursor:"pointer",color:m.colorNeutralForeground3,flexShrink:0},trailingControls:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,flexShrink:0,paddingLeft:m.spacingHorizontalS,borderLeft:`1px solid ${m.colorNeutralStroke2}`,marginLeft:m.spacingHorizontalXS}});function _g({tab:e,location:t}){const n=Fg(),o=te(j=>j.selectedButtonId),i=te(j=>j.selectButtonInContext),s=D(j=>j.moveButton),l=D(j=>j.deleteButton),a=D(j=>j.baseline),c=D(j=>j.duplicateButton),d=D(j=>j.hideOobButton),u=D(j=>j.setButtonProp),p=D(j=>j.customizeOobButton),f=D(j=>j.locLabels),h=D(j=>j.baseLanguageCode),y=(j,C)=>ue(j,f,h)||C,x=ee(j=>j.openIconPicker),b=ee(j=>j.openLocalizationEditor),g=ee(j=>j.openNewButton),[S,w]=L.useState(null),[v,I]=L.useState(null),[A,R]=L.useState(null),[k,N]=L.useState(null),W=rs(t,e),X=tn(),O=be(j=>j.appFilter==="all"),T=j=>r.jsx(Pg,{node:j,appNames:X,showApp:O,onDragRejected:()=>w(null)},j.command.id),z=j=>ul(W.overrides.get(j.id),X),$=j=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&j.oob&&!j.custom,M=j=>Ze(j.kind),G=j=>M(j)?` (${Vn[j.kind]}, read-only)`:"",K=e.groups.flatMap(j=>j.buttons.map(C=>({button:C,groupId:j.id})));function Q(j,C,B){j.dataTransfer.setData(Mn,JSON.stringify({groupId:C,buttonId:B})),j.dataTransfer.effectAllowed="move",I(B)}function P(){I(null),w(null)}function q(j,C){const B=Array.from(j.dataTransfer.types??[]);!B.includes(Mn)&&!B.includes(Js)||(j.preventDefault(),j.dataTransfer.dropEffect=B.includes(Mn)?"move":"copy",w({beforeButtonId:C}))}const V=D(j=>j.createButton);function U(j,C,B){j.preventDefault(),j.stopPropagation();const Y=j.dataTransfer.getData(Mn);if(Y){try{const _=JSON.parse(Y);if(_?.buttonId){const ce=s({groupId:_.groupId,buttonId:_.buttonId,tabId:e.id,location:t},{groupId:C,beforeButtonId:B??void 0,tabId:e.id,location:t});ce&&ce!==_.buttonId&&i(t,e.id,C,ce)}}catch{}w(null),I(null);return}const le=j.dataTransfer.getData(Js);if(le){try{const ce=JSON.parse(le)?.button;if(ce){const Ee=`_copy_${Date.now()}`;V({location:t,tabId:e.id,groupId:C,button:{...Qn(ce,`${ce.id}${Ee}`,Hn(D.getState())),label:ce.label??"New Button",kind:ce.kind??"button",sequence:50,templateAlias:ce.templateAlias??"o1",commandId:ce.commandId??"",hidden:!1,oob:!1,custom:!0,managed:!1}})}}catch{}w(null),I(null);return}w(null),I(null)}return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:n.root,children:[r.jsxs("div",{className:n.scrollRow,onDragOver:j=>{j.preventDefault()},onDrop:j=>U(j,e.groups[0]?.id??"",null),children:[K.map(({button:j,groupId:C})=>r.jsxs(Ue.Fragment,{children:[W.placement.before.get(j.id)?.map(T),S?.beforeButtonId===j.id&&r.jsx("div",{className:n.dropLine,"aria-hidden":!0}),r.jsx(Te,{content:$(j)?"OOB global command bar buttons cannot be customized.":`${ue(j.label,f)}${G(j)}${j.hidden?" — hidden":""}${z(j)}`,relationship:"label",children:r.jsxs("button",{type:"button",className:[n.button,o===j.id?n.buttonSelected:"",j.hidden?n.buttonHidden:"",j.custom?n.buttonCustom:""].filter(Boolean).join(" "),"aria-selected":o===j.id,"aria-label":`${ue(j.label,f)}${G(j)}${j.hidden?" — hidden":""}${z(j)}`,onClick:()=>i(t,e.id,C,j.id),onContextMenu:B=>{B.preventDefault(),i(t,e.id,C,j.id),R({button:j,groupId:C,x:B.clientX,y:B.clientY})},draggable:!j.managed&&!$(j),onDragStart:B=>Q(B,C,j.id),onDragEnd:P,onDragOver:B=>q(B,j.id),onDrop:B=>U(B,C,j.id),style:{opacity:v===j.id?.3:void 0},children:[r.jsx(Nt,{name:j.icon||"apps_add_in",size:16}),r.jsx(F,{size:200,children:ue(j.label,f)}),M(j)&&r.jsx(de,{size:"extra-small",appearance:"outline",color:"informative",children:Vn[j.kind]}),j.menu&&r.jsx(gt,{fontSize:12,"aria-label":"Has a menu"}),j.hidden&&r.jsx(Ye,{fontSize:12,"aria-hidden":!0}),j.custom&&r.jsx(de,{size:"extra-small",color:"brand",appearance:"tint","aria-label":"Custom",children:"NEW"}),r.jsx(as,{overrides:W.overrides.get(j.id),appNames:X}),$(j)&&r.jsx("span",{className:n.lockIcon,title:"OOB global command bar buttons cannot be customized.",children:r.jsx(Rt,{fontSize:12})})]})})]},j.id)),W.placement.trailing.map(T)]}),r.jsx("div",{className:n.trailingControls,children:(()=>{const j=e.groups[0];return j?r.jsx(Te,{content:`Add a new button to "${y(j.label,j.id)}"`,relationship:"label",children:r.jsxs("button",{type:"button",className:n.overflowBtn,onClick:()=>g(j.id),"aria-label":"Add a new button",children:[r.jsx(Ae,{fontSize:14})," Add"]})}):r.jsx(Te,{content:'No groups in this tab yet. Switch to "Classic ribbon" view to add a group first.',relationship:"label",children:r.jsxs("button",{type:"button",className:n.overflowBtn,disabled:!0,children:[r.jsx(Ae,{fontSize:14})," Add"]})})})()})]}),A&&r.jsxs(Zo,{open:!0,onOpenChange:(j,C)=>!C.open&&R(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:A.x,y:A.y,top:A.y,left:A.x,right:A.x,bottom:A.y,width:0,height:0,toJSON:()=>({})})}},children:[r.jsx(Qo,{disableButtonEnhancement:!0,children:r.jsx("span",{style:{display:"none"}})}),r.jsx(ei,{children:r.jsxs(ti,{children:[$(A.button)&&r.jsx(fe,{disabled:!0,children:"OOB global command bar buttons cannot be customized."}),$(A.button)&&r.jsx(pt,{}),r.jsx(fe,{icon:r.jsx(fo,{}),onClick:()=>{i(t,e.id,A.groupId,A.button.id),R(null)},children:"Edit properties"}),r.jsx(fe,{icon:r.jsx(Gn,{}),disabled:$(A.button)||M(A.button),onClick:()=>{i(t,e.id,A.groupId,A.button.id),x(),R(null)},children:"Change icon…"}),r.jsx(fe,{icon:r.jsx(Er,{}),disabled:$(A.button)||M(A.button),onClick:()=>{b(A.button.id),R(null)},children:"Edit labels…"}),r.jsx(pt,{}),A.button.hidden?r.jsx(fe,{icon:r.jsx(It,{}),disabled:$(A.button),onClick:()=>{u(t,e.id,A.groupId,A.button.id,{hidden:!1}),R(null)},children:"Show button"}):r.jsx(fe,{icon:r.jsx(Ye,{}),disabled:$(A.button),onClick:()=>{A.button.oob?N(A):u(t,e.id,A.groupId,A.button.id,{hidden:!0}),R(null)},children:"Hide button"}),(A.button.origin==="oob"||A.button.origin==="managed")&&r.jsx(fe,{icon:r.jsx(qt,{}),disabled:$(A.button)||M(A.button),onClick:()=>{p(t,e.id,A.groupId,A.button.id),R(null)},children:"Create override…"}),r.jsx(el,{location:t,tabId:e.id,groupId:A.groupId,button:A.button,onDone:()=>R(null)}),r.jsx(pt,{}),r.jsx(fe,{icon:r.jsx(gn,{}),disabled:$(A.button),onClick:()=>{c(t,e.id,A.groupId,A.button.id),R(null)},children:"Duplicate"}),Nn(A.button,a[t])&&r.jsx(fe,{icon:r.jsx(_t,{}),disabled:$(A.button),onClick:()=>{l(t,e.id,A.groupId,A.button.id),R(null)},children:"Delete"}),tl(e,A.groupId,A.button.id,f,h).map(j=>r.jsxs(fe,{icon:r.jsx(Or,{}),disabled:$(A.button),onClick:()=>{const C=s({groupId:A.groupId,buttonId:A.button.id,tabId:e.id,location:t},{groupId:j.groupId,tabId:e.id,location:t});C&&i(t,e.id,j.groupId,C),R(null)},children:["Move to: ",j.text]},j.groupId))]})})]}),k&&r.jsx(os,{open:!0,buttonLabel:ue(k.button.label,f),onConfirmHide:()=>{d(t,e.id,k.groupId,k.button.id),N(null)},commandId:k.button.commandId,onConfirmDisplayRule:()=>{D.getState().hideWithDisplayRules(k.button.commandId),N(null)},onCancel:()=>N(null)})]})}const qg=e=>(tm({...e,renderRow:()=>null}),e),xl=L.createContext(void 0),Hg=void 0,Wg=()=>{var e;return(e=L.useContext(xl))!=null?e:Hg},Gg=xl.Provider,vl=L.createContext({current:null}),Ug={current:null},Sl=()=>{var e;return(e=L.useContext(vl))!=null?e:Ug},Xg=vl.Provider,wl=L.createContext({current:null}),Vg={current:null},Cl=()=>{var e;return(e=L.useContext(wl))!=null?e:Vg},Kg=wl.Provider,Jg=(e,t)=>{const{height:n,itemSize:o,width:i="100%",ariaRowIndexStart:s=2,children:l,listProps:a}=e,c=Sl(),d=Cl(),p=nm({...e,children:l},t),f=L.useCallback(({data:x,index:b,style:g,isScrolling:S})=>{const w=x[b];return L.createElement(Gg,{value:s+b},L.createElement(om,{value:w.rowId},l(w,g,b,S)))},[s,l]),h=L.useCallback(()=>{c.current&&d.current&&d.current.scroll({left:c.current.scrollLeft,behavior:"instant"})},[]),y=L.useCallback(x=>{var b;(b=c.current)==null||b.removeEventListener("scroll",h),c.current=x,x&&x.addEventListener("scroll",h)},[]);return{...p,itemSize:o,height:n,virtualizedRow:f,width:i,ariaRowIndexStart:s,listProps:a,outerRef:y}};function ki(){return ki=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},ki.apply(null,arguments)}function Ys(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ai(e,t){return Ai=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,o){return n.__proto__=o,n},Ai(e,t)}function Yg(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Ai(e,t)}var Zs=Number.isNaN||function(t){return typeof t=="number"&&t!==t};function Zg(e,t){return!!(e===t||Zs(e)&&Zs(t))}function Qg(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!Zg(e[n],t[n]))return!1;return!0}function Xo(e,t){t===void 0&&(t=Qg);var n,o=[],i,s=!1;function l(){for(var a=[],c=0;c<arguments.length;c++)a[c]=arguments[c];return s&&n===this&&t(a,o)||(i=e.apply(this,a),s=!0,n=this,o=a),i}return l}var eb=typeof performance=="object"&&typeof performance.now=="function",Qs=eb?function(){return performance.now()}:function(){return Date.now()};function er(e){cancelAnimationFrame(e.id)}function tb(e,t){var n=Qs();function o(){Qs()-n>=t?e.call(null):i.id=requestAnimationFrame(o)}var i={id:requestAnimationFrame(o)};return i}var Vo=-1;function tr(e){if(e===void 0&&(e=!1),Vo===-1||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",document.body.appendChild(t),Vo=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return Vo}var zt=null;function nr(e){if(e===void 0&&(e=!1),zt===null||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",n.direction="rtl";var o=document.createElement("div"),i=o.style;return i.width="100px",i.height="100px",t.appendChild(o),document.body.appendChild(t),t.scrollLeft>0?zt="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?zt="negative":zt="positive-ascending"),document.body.removeChild(t),zt}return zt}var nb=150,ob=function(t,n){return t};function ib(e){var t,n=e.getItemOffset,o=e.getEstimatedTotalSize,i=e.getItemSize,s=e.getOffsetForIndexAndAlignment,l=e.getStartIndexForOffset,a=e.getStopIndexForStartIndex,c=e.initInstanceProps,d=e.shouldResetStyleCacheOnItemSizeChange,u=e.validateProps;return t=(function(p){Yg(f,p);function f(y){var x;return x=p.call(this,y)||this,x._instanceProps=c(x.props,Ys(x)),x._outerRef=void 0,x._resetIsScrollingTimeoutId=null,x.state={instance:Ys(x),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof x.props.initialScrollOffset=="number"?x.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},x._callOnItemsRendered=void 0,x._callOnItemsRendered=Xo(function(b,g,S,w){return x.props.onItemsRendered({overscanStartIndex:b,overscanStopIndex:g,visibleStartIndex:S,visibleStopIndex:w})}),x._callOnScroll=void 0,x._callOnScroll=Xo(function(b,g,S){return x.props.onScroll({scrollDirection:b,scrollOffset:g,scrollUpdateWasRequested:S})}),x._getItemStyle=void 0,x._getItemStyle=function(b){var g=x.props,S=g.direction,w=g.itemSize,v=g.layout,I=x._getItemStyleCache(d&&w,d&&v,d&&S),A;if(I.hasOwnProperty(b))A=I[b];else{var R=n(x.props,b,x._instanceProps),k=i(x.props,b,x._instanceProps),N=S==="horizontal"||v==="horizontal",W=S==="rtl",X=N?R:0;I[b]=A={position:"absolute",left:W?void 0:X,right:W?X:void 0,top:N?0:R,height:N?"100%":k,width:N?k:"100%"}}return A},x._getItemStyleCache=void 0,x._getItemStyleCache=Xo(function(b,g,S){return{}}),x._onScrollHorizontal=function(b){var g=b.currentTarget,S=g.clientWidth,w=g.scrollLeft,v=g.scrollWidth;x.setState(function(I){if(I.scrollOffset===w)return null;var A=x.props.direction,R=w;if(A==="rtl")switch(nr()){case"negative":R=-w;break;case"positive-descending":R=v-S-w;break}return R=Math.max(0,Math.min(R,v-S)),{isScrolling:!0,scrollDirection:I.scrollOffset<R?"forward":"backward",scrollOffset:R,scrollUpdateWasRequested:!1}},x._resetIsScrollingDebounced)},x._onScrollVertical=function(b){var g=b.currentTarget,S=g.clientHeight,w=g.scrollHeight,v=g.scrollTop;x.setState(function(I){if(I.scrollOffset===v)return null;var A=Math.max(0,Math.min(v,w-S));return{isScrolling:!0,scrollDirection:I.scrollOffset<A?"forward":"backward",scrollOffset:A,scrollUpdateWasRequested:!1}},x._resetIsScrollingDebounced)},x._outerRefSetter=function(b){var g=x.props.outerRef;x._outerRef=b,typeof g=="function"?g(b):g!=null&&typeof g=="object"&&g.hasOwnProperty("current")&&(g.current=b)},x._resetIsScrollingDebounced=function(){x._resetIsScrollingTimeoutId!==null&&er(x._resetIsScrollingTimeoutId),x._resetIsScrollingTimeoutId=tb(x._resetIsScrolling,nb)},x._resetIsScrolling=function(){x._resetIsScrollingTimeoutId=null,x.setState({isScrolling:!1},function(){x._getItemStyleCache(-1,null)})},x}f.getDerivedStateFromProps=function(x,b){return sb(x,b),u(x),null};var h=f.prototype;return h.scrollTo=function(x){x=Math.max(0,x),this.setState(function(b){return b.scrollOffset===x?null:{scrollDirection:b.scrollOffset<x?"forward":"backward",scrollOffset:x,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},h.scrollToItem=function(x,b){b===void 0&&(b="auto");var g=this.props,S=g.itemCount,w=g.layout,v=this.state.scrollOffset;x=Math.max(0,Math.min(x,S-1));var I=0;if(this._outerRef){var A=this._outerRef;w==="vertical"?I=A.scrollWidth>A.clientWidth?tr():0:I=A.scrollHeight>A.clientHeight?tr():0}this.scrollTo(s(this.props,x,b,v,this._instanceProps,I))},h.componentDidMount=function(){var x=this.props,b=x.direction,g=x.initialScrollOffset,S=x.layout;if(typeof g=="number"&&this._outerRef!=null){var w=this._outerRef;b==="horizontal"||S==="horizontal"?w.scrollLeft=g:w.scrollTop=g}this._callPropsCallbacks()},h.componentDidUpdate=function(){var x=this.props,b=x.direction,g=x.layout,S=this.state,w=S.scrollOffset,v=S.scrollUpdateWasRequested;if(v&&this._outerRef!=null){var I=this._outerRef;if(b==="horizontal"||g==="horizontal")if(b==="rtl")switch(nr()){case"negative":I.scrollLeft=-w;break;case"positive-ascending":I.scrollLeft=w;break;default:var A=I.clientWidth,R=I.scrollWidth;I.scrollLeft=R-A-w;break}else I.scrollLeft=w;else I.scrollTop=w}this._callPropsCallbacks()},h.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&er(this._resetIsScrollingTimeoutId)},h.render=function(){var x=this.props,b=x.children,g=x.className,S=x.direction,w=x.height,v=x.innerRef,I=x.innerElementType,A=x.innerTagName,R=x.itemCount,k=x.itemData,N=x.itemKey,W=N===void 0?ob:N,X=x.layout,O=x.outerElementType,T=x.outerTagName,z=x.style,$=x.useIsScrolling,M=x.width,G=this.state.isScrolling,K=S==="horizontal"||X==="horizontal",Q=K?this._onScrollHorizontal:this._onScrollVertical,P=this._getRangeToRender(),q=P[0],V=P[1],U=[];if(R>0)for(var j=q;j<=V;j++)U.push(L.createElement(b,{data:k,key:W(j,k),index:j,isScrolling:$?G:void 0,style:this._getItemStyle(j)}));var C=o(this.props,this._instanceProps);return L.createElement(O||T||"div",{className:g,onScroll:Q,ref:this._outerRefSetter,style:ki({position:"relative",height:w,width:M,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:S},z)},L.createElement(I||A||"div",{children:U,ref:v,style:{height:K?"100%":C,pointerEvents:G?"none":void 0,width:K?C:"100%"}}))},h._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var x=this.props.itemCount;if(x>0){var b=this._getRangeToRender(),g=b[0],S=b[1],w=b[2],v=b[3];this._callOnItemsRendered(g,S,w,v)}}if(typeof this.props.onScroll=="function"){var I=this.state,A=I.scrollDirection,R=I.scrollOffset,k=I.scrollUpdateWasRequested;this._callOnScroll(A,R,k)}},h._getRangeToRender=function(){var x=this.props,b=x.itemCount,g=x.overscanCount,S=this.state,w=S.isScrolling,v=S.scrollDirection,I=S.scrollOffset;if(b===0)return[0,0,0,0];var A=l(this.props,I,this._instanceProps),R=a(this.props,A,I,this._instanceProps),k=!w||v==="backward"?Math.max(1,g):1,N=!w||v==="forward"?Math.max(1,g):1;return[Math.max(0,A-k),Math.max(0,Math.min(b-1,R+N)),A,R]},f})(L.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var sb=function(t,n){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,n.instance},rb=ib({getItemOffset:function(t,n){var o=t.itemSize;return n*o},getItemSize:function(t,n){var o=t.itemSize;return o},getEstimatedTotalSize:function(t){var n=t.itemCount,o=t.itemSize;return o*n},getOffsetForIndexAndAlignment:function(t,n,o,i,s,l){var a=t.direction,c=t.height,d=t.itemCount,u=t.itemSize,p=t.layout,f=t.width,h=a==="horizontal"||p==="horizontal",y=h?f:c,x=Math.max(0,d*u-y),b=Math.min(x,n*u),g=Math.max(0,n*u-y+u+l);switch(o==="smart"&&(i>=g-y&&i<=b+y?o="auto":o="center"),o){case"start":return b;case"end":return g;case"center":{var S=Math.round(g+(b-g)/2);return S<Math.ceil(y/2)?0:S>x+Math.floor(y/2)?x:S}default:return i>=g&&i<=b?i:i<g?g:b}},getStartIndexForOffset:function(t,n){var o=t.itemCount,i=t.itemSize;return Math.max(0,Math.min(o-1,Math.floor(n/i)))},getStopIndexForStartIndex:function(t,n,o){var i=t.direction,s=t.height,l=t.itemCount,a=t.itemSize,c=t.layout,d=t.width,u=i==="horizontal"||c==="horizontal",p=n*a,f=u?d:s,h=Math.ceil((f+o-p)/a);return Math.max(0,Math.min(l-1,n+h-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.itemSize}});const ab=e=>{const{slots:t,slotProps:n}=im(e),{dir:o}=zr();return L.createElement(t.root,n.root,L.createElement(rb,{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))},ls=L.forwardRef((e,t)=>{const n=Jg(e,t);return qg(n),ab(n)});ls.displayName="DataGridBody";const lb=(e,t)=>{var n;const{targetDocument:o}=zr(),i=sm({targetDocument:o}),s=L.useRef(null),l=L.useRef(null);let a=e.containerWidthOffset;a===void 0&&(a=e.selectionMode?-44:0,a-=i||0);const c=rm({...e,"aria-rowcount":e.items.length,containerWidthOffset:a},t);return e.resizableColumns&&((n=e.resizableColumnsOptions)==null?void 0:n.autoFitColumns)===!1&&c.root.style&&(c.root.style.minWidth="auto"),{...c,headerRef:s,bodyRef:l}},cb=(e,t)=>L.createElement(Kg,{value:e.headerRef},L.createElement(Xg,{value:e.bodyRef},am(e,t))),cs=L.forwardRef((e,t)=>{const n=lb(e,t);return lm(n),cb(n,cm(n))});cs.displayName="DataGrid";const db=(e,t)=>{const n=Wg();return dm({...e,"aria-rowindex":n},t)},ub=me({root:{minWidth:"fit-content"}}),mb=e=>{const t=ub();return e.root.className=Ht(t.root,e.root.className),um(e),e},Rn=L.forwardRef((e,t)=>{const n=db(e,t);return mb(n),mm(n)});Rn.displayName="DataGridRow";const pb=(e,t)=>{const n=Sl(),o=Cl(),i=L.useCallback(()=>{n.current&&o.current&&n.current.scroll({left:o.current.scrollLeft,behavior:"instant"})},[]),s=L.useCallback(a=>{var c;(c=o.current)==null||c.removeEventListener("scroll",i),o.current=a,a&&a.addEventListener("scroll",i)},[]),l=pm(e,t);return l.root.ref=fm(l.root.ref,s),l},fb=me({root:{overflowX:"auto",scrollbarWidth:"none","::-webkit-scrollbar":{width:0,height:0}}}),hb=e=>{const t=fb();return e.root.className=Ht(t.root,e.root.className),hm(e),e},ds=L.forwardRef((e,t)=>{const n=pb(e,t);return hb(n),gm(n)});ds.displayName="DataGridHeader";const gb=me({root:{marginTop:m.spacingVerticalM,display:"flex",flexDirection:"column",gap:m.spacingVerticalXS},header:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},row:{cursor:"pointer",backgroundColor:m.colorPaletteBerryBackground1,":hover":{backgroundColor:m.colorPaletteBerryBackground2}},rowSelected:{backgroundColor:m.colorPaletteBerryBackground2,outline:`1px solid ${m.colorPaletteBerryBorderActive}`},hidden:{opacity:.55,textDecoration:"line-through"},mono:{fontFamily:m.fontFamilyMonospace,color:m.colorNeutralForeground3}}),bb={button:"command",dropdown:"dropdown",split:"split",group:"group"};function yb({tab:e,location:t}){const n=gb(),{nodes:o}=rs(t,e),i=tn(),s=be(u=>u.selectedCommandId),l=be(u=>u.selectCommand),a=te(u=>u.selectedButtonId);if(o.length===0)return null;const c=[],d=(u,p)=>{for(const f of u)c.push({node:f,depth:p}),d(f.children,p+1)};return d(o,0),r.jsxs("section",{className:n.root,"aria-label":"Modern commands",children:[r.jsxs("div",{className:n.header,children:[r.jsx(F,{weight:"semibold",size:200,children:"Modern commands"}),r.jsx(de,{size:"small",appearance:"tint",color:"important",children:"read-only"}),r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"Built with the command designer (appaction). Edit them in the command designer."})]}),r.jsxs(bm,{size:"small","aria-label":"Modern commands (read-only)",children:[r.jsx(ym,{children:r.jsxs(fs,{children:[r.jsx(At,{style:{width:56},children:"#"}),r.jsx(At,{children:"Label"}),r.jsx(At,{children:"App"}),r.jsx(At,{children:"Location"}),r.jsx(At,{style:{width:90},children:"Type"}),r.jsx(At,{children:"Unique name"})]})}),r.jsx(xm,{children:c.map(({node:u,depth:p})=>{const f=u.command,h=s===f.id&&!a;return r.jsxs(fs,{className:Ht(n.row,h&&n.rowSelected),"aria-selected":h,tabIndex:0,onClick:()=>l(f.id),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),l(f.id))},children:[r.jsx(Dt,{children:f.sequence}),r.jsx(Dt,{children:r.jsx(Te,{content:r.jsx(yl,{node:u,appNames:i}),relationship:"description",children:r.jsxs("span",{className:f.hidden||f.disabled?n.hidden:void 0,style:{paddingLeft:p*16,display:"inline-flex",gap:4,alignItems:"center"},children:[f.label,f.hidden&&r.jsx(Ye,{fontSize:12,"aria-label":"hidden"}),r.jsx(de,{size:"extra-small",appearance:"tint",color:"important",children:"Modern"})]})})}),r.jsx(Dt,{children:Cn(f,i)}),r.jsx(Dt,{children:sl[f.location]??f.location}),r.jsx(Dt,{children:r.jsx(de,{size:"small",appearance:"outline",children:bb[f.type]})}),r.jsx(Dt,{children:r.jsx("span",{className:n.mono,title:f.uniqueName,children:f.uniqueName})})]},f.id)})})]})]})}const xb=me({root:{width:"100%"},gridWrap:{height:"min(560px, calc(100vh - 320px))",minHeight:"260px"},row:{cursor:"pointer",":hover":{backgroundColor:m.colorNeutralBackground3}},rowSelected:{backgroundColor:m.colorBrandBackground2},iconCell:{width:"20px",height:"20px",borderRadius:"3px",backgroundColor:m.colorNeutralBackground4,display:"flex",alignItems:"center",justifyContent:"center",fontSize:m.fontSizeBase100,color:m.colorNeutralForeground3},clip:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%"}});function vb({tab:e,location:t}){const n=xb(),o=te(g=>g.selectedButtonId),i=te(g=>g.selectButtonInContext),s=D(g=>g.setButtonProp),l=D(g=>g.locLabels),a=D(g=>g.baseLanguageCode),c=g=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&g.oob&&!g.custom,[d,u]=L.useState(""),{overrides:p}=rs(t,e),f=tn(),h=e.groups.flatMap(g=>g.buttons.map(S=>({button:S,label:ue(S.label,l),groupId:g.id,groupLabel:ue(g.label,l,a)}))),y=L.useMemo(()=>{const g=d.toLowerCase().trim();return g?h.filter(({button:S,label:w,groupLabel:v})=>S.id.toLowerCase().includes(g)||S.label.toLowerCase().includes(g)||w.toLowerCase().includes(g)||(S.commandId??"").toLowerCase().includes(g)||v.toLowerCase().includes(g)):h},[h,d]),x={seq:{defaultWidth:56,minWidth:48,idealWidth:56},icon:{defaultWidth:48,minWidth:40,idealWidth:48},label:{defaultWidth:260,minWidth:140,idealWidth:260},id:{defaultWidth:280,minWidth:160,idealWidth:280},kind:{defaultWidth:90,minWidth:72,idealWidth:90},group:{defaultWidth:160,minWidth:100,idealWidth:160},command:{defaultWidth:280,minWidth:160,idealWidth:280},visible:{defaultWidth:80,minWidth:64,idealWidth:80}},b=[rt({columnId:"seq",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"#"}),renderCell:({button:g})=>r.jsx(F,{size:200,children:g.sequence})}),rt({columnId:"icon",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"Icon"}),renderCell:({button:g})=>r.jsx("div",{className:n.iconCell,children:r.jsx(Nt,{name:g.icon||"apps_add_in",size:16})})}),rt({columnId:"label",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"Label"}),renderCell:({button:g,label:S})=>r.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,minWidth:0},children:[r.jsx(F,{size:200,className:n.clip,title:S,children:S}),r.jsx(as,{overrides:p.get(g.id),appNames:f})]})}),rt({columnId:"id",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"ID"}),renderCell:({button:g})=>r.jsx(F,{size:200,font:"monospace",className:n.clip,title:g.id,style:{color:m.colorNeutralForeground3},children:g.id})}),rt({columnId:"kind",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"Kind"}),renderCell:({button:g})=>r.jsx(de,{size:"small",appearance:"outline",children:g.kind})}),rt({columnId:"group",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"Group"}),renderCell:({groupLabel:g})=>r.jsx(F,{size:200,className:n.clip,title:g,children:g})}),rt({columnId:"command",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"Command"}),renderCell:({button:g})=>r.jsx(F,{size:200,font:"monospace",className:n.clip,title:g.commandId||"",style:{color:m.colorNeutralForeground3},children:g.commandId||"—"})}),rt({columnId:"visible",renderHeaderCell:()=>r.jsx(F,{size:200,weight:"semibold",children:"Visible"}),renderCell:({button:g,label:S,groupId:w})=>r.jsx(Ei,{checked:!g.hidden,label:g.hidden?r.jsx(Ye,{fontSize:14}):void 0,disabled:c(g),title:c(g)?"OOB global command bar buttons cannot be customized.":void 0,"aria-label":`Toggle visibility of ${S}`,onChange:(v,I)=>s(t,e.id,w,g.id,{hidden:!I.checked})})})];return r.jsxs("div",{className:n.root,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`${m.spacingVerticalXS} 0`},children:[r.jsx(qe,{size:"small",contentBefore:r.jsx(ft,{}),placeholder:`Filter ${h.length} button${h.length!==1?"s":""}…`,value:d,onChange:(g,S)=>u(S.value),style:{minWidth:0,flex:1,maxWidth:480}}),d&&r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[y.length," match",y.length!==1?"es":""]})]}),r.jsxs(cs,{className:n.gridWrap,items:y,columns:b,columnSizingOptions:x,resizableColumns:!0,getRowId:g=>g.button.id,focusMode:"composite",sortable:!0,selectionMode:"single",selectedItems:o?new Set([o]):new Set,onSelectionChange:(g,S)=>{const w=[...S.selectedItems][0],v=y.find(I=>I.button.id===w);v&&i(t,e.id,v.groupId,v.button.id)},children:[r.jsx(ds,{children:r.jsx(Rn,{children:({renderHeaderCell:g})=>r.jsx(Br,{children:g()})})}),r.jsx(ls,{itemSize:42,height:420,listProps:{width:"100%"},children:({item:g,rowId:S},w)=>r.jsx(Rn,{style:w,className:o===g.button.id?n.rowSelected:n.row,children:({renderCell:v})=>r.jsx(Mr,{children:v(g)})},S)})]}),r.jsx(yb,{tab:e,location:t})]})}const Il=me({root:{marginTop:m.spacingVerticalM,border:`1px solid ${m.colorNeutralStroke2}`,borderRadius:m.borderRadiusMedium,backgroundColor:m.colorNeutralBackground1,maxWidth:"520px"},header:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`${m.spacingVerticalS} ${m.spacingHorizontalM}`,borderBottom:`1px solid ${m.colorNeutralStroke2}`},spacer:{flex:1},body:{display:"flex",flexDirection:"column",gap:m.spacingVerticalS,padding:m.spacingHorizontalS},section:{display:"flex",flexDirection:"column",gap:"2px"},sectionHeader:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,padding:`2px ${m.spacingHorizontalXS}`,color:m.colorNeutralForeground3},item:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,width:"100%",minHeight:"28px",padding:`0 ${m.spacingHorizontalS}`,border:"1px solid transparent",borderRadius:m.borderRadiusMedium,backgroundColor:"transparent",color:m.colorNeutralForeground1,cursor:"pointer",textAlign:"left",":hover":{backgroundColor:m.colorNeutralBackground3},":focus-visible":{outline:`2px solid ${m.colorBrandStroke1}`}},itemSelected:{backgroundColor:m.colorBrandBackground2,border:`1px solid ${m.colorBrandStroke1}`},itemHidden:{opacity:.45,textDecoration:"line-through"},itemRow:{display:"flex",alignItems:"center",gap:"2px"},nested:{marginLeft:m.spacingHorizontalL,paddingLeft:m.spacingHorizontalS,borderLeft:`1px dashed ${m.colorNeutralStroke2}`},empty:{padding:`2px ${m.spacingHorizontalS}`,color:m.colorNeutralForeground3}});function Sb({tab:e,location:t}){const n=Il(),o=te(I=>I.selectedButtonId),i=te(I=>I.selectedGroupId),s=te(I=>I.selectButtonInContext),l=D(I=>I.baseline),a=D(I=>I.locLabels),c=D(I=>I.addMenuSection),d=D(I=>I.setMenuSectionProp),u=D(I=>I.deleteMenuSection),{overrides:p}=ss(t),f=tn(),h=e.groups.find(I=>I.id===i),y=Rp(h,o),x=L.useMemo(()=>{const I=new Set;for(const A of l[t]?.tabs??[])for(const R of A.groups)for(const k of $e(R))I.add(k.id);return I},[l,t]);if(!h||!y||!y.menu&&!Lt(y.kind))return null;const b=h.id,g=I=>ue(I.label,a),S=I=>la(I.source?.attributes.PopulateDynamically)?I.source?.attributes.PopulateQueryCommand??"a command":null,w=I=>{const A=[...I.menu?.sections??[]].sort((N,W)=>N.sequence-W.sequence),R=!x.has(I.id),k=S(I);return r.jsxs(r.Fragment,{children:[k&&r.jsxs(Me,{className:n.empty,children:["Populated when the menu opens, by ",k,". Static items below are kept as they are."]}),A.map(N=>r.jsx(wb,{section:N,parent:I,editable:R,onTitle:W=>d(t,e.id,b,I.id,N.id,{title:W}),onDisplayMode:W=>d(t,e.id,b,I.id,N.id,{displayMode:W}),onDelete:()=>u(t,e.id,b,I.id,N.id),renderItem:v},N.id)),A.length===0&&!k&&r.jsx(Me,{className:n.empty,children:"No menu sections yet."}),R&&r.jsx("div",{children:r.jsx(J,{size:"small",appearance:"subtle",icon:r.jsx(Ae,{}),onClick:()=>c(t,e.id,b,I.id,""),children:"Add section"})})]})},v=I=>{const A=I.id===o,R=p.get(I.id);return r.jsxs("div",{children:[r.jsxs("div",{className:n.itemRow,children:[r.jsxs("button",{type:"button",className:[n.item,A?n.itemSelected:"",I.hidden?n.itemHidden:""].filter(Boolean).join(" "),"aria-pressed":A,"aria-label":`Menu item ${g(I)}${I.hidden?" — hidden":""}${ul(R,f)}`,onClick:()=>s(t,e.id,b,I.id),children:[r.jsx(Nt,{name:I.icon||"apps_add_in",size:16}),r.jsx(F,{size:200,children:g(I)}),I.menu&&r.jsx(gt,{fontSize:12,"aria-hidden":!0}),r.jsx(as,{overrides:R,appNames:f}),I.custom&&!x.has(I.id)&&r.jsx(de,{size:"extra-small",color:"brand",appearance:"tint",children:"NEW"})]}),A&&r.jsx(Ib,{item:I,location:t,tabId:e.id,groupId:b,onDeleted:()=>s(t,e.id,b,y.id)})]}),I.menu&&r.jsx("div",{className:n.nested,children:w(I)})]},I.id)};return r.jsxs("section",{className:n.root,"aria-label":`Menu of ${g(y)}`,children:[r.jsxs("div",{className:n.header,children:[r.jsx(gt,{"aria-hidden":!0}),r.jsx(F,{weight:"semibold",size:300,children:g(y)}),r.jsx(de,{size:"small",appearance:"outline",children:y.kind==="splitButton"?"Split button menu":"Flyout menu"}),r.jsx("span",{className:n.spacer}),r.jsxs(Me,{children:[Ct(y).length," item(s)"]})]}),r.jsx("div",{className:n.body,children:w(y)})]})}function wb({section:e,parent:t,editable:n,onTitle:o,onDisplayMode:i,onDelete:s,renderItem:l}){const a=Il(),c=D(u=>u.locLabels),d=[...e.controls].sort((u,p)=>u.sequence-p.sequence);return r.jsxs("div",{className:a.section,children:[r.jsx("div",{className:a.sectionHeader,children:n?r.jsxs(r.Fragment,{children:[r.jsx(qe,{size:"small",placeholder:"Section title (optional)",value:e.title??"","aria-label":"Menu section title",onChange:(u,p)=>o(p.value)}),r.jsxs(dt,{size:"small","aria-label":"Menu section display mode",value:e.displayMode??"Menu16",onChange:(u,p)=>i(p.value),children:[r.jsx("option",{value:"Menu16",children:"16 px icons"}),r.jsx("option",{value:"Menu32",children:"32 px icons"}),r.jsx("option",{value:"Menu",children:"Text only"})]}),r.jsx(Te,{content:"Delete section and its items",relationship:"label",children:r.jsx(J,{size:"small",appearance:"subtle",icon:r.jsx(_t,{}),onClick:s})})]}):r.jsx(Me,{children:ue(e.title,c)||e.id})}),d.map(u=>l(u)),e.rawContent!==void 0&&r.jsx(Me,{className:a.empty,children:"Gallery / dynamic content (kept as is)"}),(e.rawControls?.length??0)>0&&r.jsxs(Me,{className:a.empty,children:[e.rawControls.length," other control(s) CBS doesn't edit (kept as they are)"]}),e.rawContent===void 0&&r.jsx(Cb,{parent:t,section:e})]})}function Cb({parent:e,section:t}){const n=te(f=>f.location),o=te(f=>f.tabId),i=te(f=>f.selectedGroupId),s=te(f=>f.selectButtonInContext),l=D(f=>f.addMenuItem),a=D(f=>f.upsertCommand),c=ie(f=>f.activeSolution),d=ie(f=>f.publisherPrefix),u=ie(f=>f.activeEntity),p=()=>{if(!i)return;const{ribbons:f,commands:h}=D.getState(),y=new Set(h.map(S=>S.id));for(const S of Object.values(f))for(const w of S.tabs)for(const v of w.groups)for(const I of $e(v))y.add(I.id);const x=c?.publisherPrefix?.trim()||d?.trim()||"new",{id:b,commandId:g}=$a(x,u?.logicalName??"global",n,"MenuItem",y);l({location:n,tabId:o,groupId:i,parentId:e.id,sectionId:t.id,item:{id:b,label:"Menu item",commandId:g}}),a({id:g,enableRules:[],displayRules:[],actions:[]}),s(n,o,i,b)};return r.jsx("div",{children:r.jsx(J,{size:"small",appearance:"subtle",icon:r.jsx(Ae,{}),onClick:p,children:"Add item"})})}function Ib({item:e,location:t,tabId:n,groupId:o,onDeleted:i}){const s=D(c=>c.setButtonProp),l=D(c=>c.deleteButton),a=D(c=>c.baseline[t]);return r.jsxs(r.Fragment,{children:[r.jsx(Te,{content:e.hidden?"Show item":"Hide item",relationship:"label",children:r.jsx(J,{size:"small",appearance:"subtle",icon:e.hidden?r.jsx(It,{}):r.jsx(Ye,{}),onClick:()=>s(t,n,o,e.id,{hidden:!e.hidden})})}),Nn(e,a)&&r.jsx(Te,{content:"Delete item",relationship:"label",children:r.jsx(J,{size:"small",appearance:"subtle",icon:r.jsx(_t,{}),onClick:()=>{l(t,n,o,e.id),i()}})})]})}function Rb(){const e=be(l=>l.status),t=be(l=>l.apps),n=be(l=>l.appFilter),o=be(l=>l.setAppFilter),i=be(l=>l.commands.length),s=be(l=>l.error);return e==="idle"?null:e==="loading"?r.jsx(Oi,{size:"extra-tiny","aria-label":"Loading modern commands"}):e==="unavailable"?r.jsx(Te,{content:`Modern commands couldn't be read: ${s??"unknown error"}`,relationship:"label",children:r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"Modern: n/a"})}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},children:[r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"App:"}),r.jsx(Te,{content:`${i} modern command${i===1?"":"s"} for this table (read-only). Pick an app to see its command bar.`,relationship:"description",children:r.jsxs(dt,{value:n,onChange:(l,a)=>o(a.value),size:"small","aria-label":"App for modern commands",style:{height:"26px",width:"170px"},children:[r.jsx("option",{value:"all",children:"All apps"}),t.map(l=>r.jsx("option",{value:l.id,children:l.name},l.id))]})})]})}const jb=me({root:{display:"flex",flexDirection:"column",flex:1,overflow:"hidden",backgroundColor:m.colorNeutralBackground1},locationRow:{display:"flex",alignItems:"center",gap:0,padding:`0 ${m.spacingHorizontalM}`,borderBottom:`1px solid ${m.colorNeutralStroke2}`,backgroundColor:m.colorNeutralBackground2,flexShrink:0,height:"36px"},locationTab:{height:"36px",padding:`0 ${m.spacingHorizontalM}`,display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,cursor:"pointer",borderBottom:"2px solid transparent",fontSize:m.fontSizeBase200,color:m.colorNeutralForeground2,":hover":{color:m.colorNeutralForeground1,backgroundColor:m.colorNeutralBackground3}},locationTabActive:{color:m.colorBrandForeground1,borderBottomColor:m.colorBrandStroke1,fontWeight:m.fontWeightSemibold},spacer:{flex:1},tabStrip:{display:"flex",alignItems:"center",gap:0,padding:`0 ${m.spacingHorizontalM}`,borderBottom:`1px solid ${m.colorNeutralStroke2}`,backgroundColor:m.colorNeutralBackground1,flexShrink:0,height:"32px"},ribbonTab:{height:"32px",padding:`0 ${m.spacingHorizontalM}`,display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"center",cursor:"pointer",borderBottom:"2px solid transparent",":hover":{backgroundColor:m.colorNeutralBackground3}},ribbonTabActive:{borderBottomColor:m.colorBrandStroke1},ribbonTabLabel:{fontSize:m.fontSizeBase200,fontWeight:m.fontWeightSemibold,lineHeight:1.2},ribbonTabMeta:{fontSize:m.fontSizeBase100,color:m.colorNeutralForeground3,lineHeight:1.2},addTabBtn:{height:"24px",width:"24px",minWidth:"24px",marginLeft:m.spacingHorizontalXS,borderRadius:m.borderRadiusMedium,border:`1px dashed ${m.colorNeutralStroke2}`,backgroundColor:"transparent",color:m.colorNeutralForeground3,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",":hover":{border:`1px solid ${m.colorNeutralStroke1}`,backgroundColor:m.colorNeutralBackground2}},inlineTabInput:{height:"28px",fontSize:m.fontSizeBase200,fontWeight:m.fontWeightSemibold,minWidth:"60px",maxWidth:"140px"},canvas:{flex:1,overflow:"auto",padding:m.spacingHorizontalM}}),$b=me({root:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"80px",gap:m.spacingHorizontalM,color:m.colorNeutralForeground3}}),Nb=[{value:"HomepageGrid",label:"Home Grid",icon:r.jsx(Tr,{}),desc:"Mscrm.HomepageGrid.{entity}"},{value:"SubGrid",label:"Sub Grid",icon:r.jsx(qu,{}),desc:"Mscrm.SubGrid.{entity}"},{value:"Form",label:"Form",icon:r.jsx(mo,{}),desc:"Mscrm.Form.{entity}"},{value:"Application",label:"Application",icon:r.jsx(kr,{}),desc:"applicationRibbon.xml"}];function Tb({isLoadingRibbon:e=!1,ribbonLoadError:t=null,layerReadError:n=null,onRetryRibbonLoad:o}){const i=jb(),s=te(_=>_.location),l=te(_=>_.tabId),a=te(_=>_.setLocation),c=te(_=>_.setTabId),d=D(_=>_.ribbons),u=D(_=>_.renameTab),p=D(_=>_.deleteTab),f=D(_=>_.locLabels),h=D(_=>_.baseLanguageCode),y=D(_=>_.baseline),x=D(_=>_.layers),b=D(_=>_.orphans.entity.filter(ce=>!_.pendingOrphanDeletes.entity.includes(ce.id)&&!ce.recentPublish?.published).length),g=te(_=>_.clearSelection),S=D(_=>_.reorderTabs),w=ee(_=>_.ribbonViewStyle),v=ee(_=>_.setRibbonViewStyle),I=ee(_=>_.openXmlDrawer),A=ee(_=>_.openTabDisplayRules),R=ee(_=>_.openNewGroup),k=ee(_=>_.openNewTab),[N,W]=L.useState(null),[X,O]=L.useState(""),T=L.useRef(null),[z,$]=L.useState(null),[M,G]=L.useState(!1),K=z?d[s].tabs.find(_=>_.id===z):void 0;L.useEffect(()=>{N&&T.current&&T.current.focus()},[N]);function Q(){const _=d[s].tabs.find(ce=>ce.id===N);_&&X.trim()&&X.trim()!==ue(_.label,f,h)&&u(s,_.id,X.trim()),W(null)}function P(_){return Ia(_,y[s],oo({layers:x},s))}function q(_){return Ca("tab",_.id,y[s],Yi({layers:x},s))}const[V,U]=L.useState(null);function j(_){if(!q(_)){U(_.id),se.getState().logInfo("canvas",`Tab ${_.id} can't be renamed: ${Gi}.`);return}W(_.id),O(ue(_.label,f,h))}const C=Lr(Un(Fr,{activationConstraint:{distance:5}}),Un(Pr)),B=L.useCallback(_=>{const{active:ce,over:Ee}=_;if(!Ee||ce.id===Ee.id)return;const E=d[s].tabs.map(ne=>ne.id),H=E.indexOf(String(ce.id)),oe=E.indexOf(String(Ee.id));H<0||oe<0||S(s,Tm(E,H,oe))},[s,d,S]),Y=d[s],le=Y.tabs.find(_=>_.id===l)??Y.tabs.find(_=>_.id===hn(Y.tabs));return L.useEffect(()=>{if(!Y.tabs.length)return;if(!Y.tabs.some(ce=>ce.id===l)){const ce=hn(Y.tabs);ce&&c(ce)}},[Y.tabs,l,c]),r.jsxs("main",{className:i.root,"aria-label":"Ribbon canvas",children:[r.jsxs("div",{className:i.locationRow,role:"tablist","aria-label":"Ribbon location",children:[Nb.map(_=>r.jsxs("div",{role:"tab","aria-selected":s===_.value,className:`${i.locationTab} ${s===_.value?i.locationTabActive:""}`,onClick:()=>{a(_.value);const ce=hn(d[_.value].tabs);ce&&c(ce)},title:_.desc,tabIndex:s===_.value?0:-1,children:[_.icon,r.jsx(F,{size:200,children:_.label})]},_.value)),r.jsx("div",{className:i.spacer}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},children:[r.jsx(Rb,{}),r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"View as:"}),r.jsxs(dt,{value:w,onChange:(_,ce)=>v(ce.value),size:"small",style:{height:"26px",width:"170px"},children:[r.jsx("option",{value:"classic",children:"Classic ribbon"}),r.jsx("option",{value:"modern",children:"Modern command bar"}),r.jsx("option",{value:"list",children:"List view"})]}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ut,{}),onClick:I,children:"XML"})]})]}),n&&!e&&!t&&r.jsxs(we,{intent:"warning",layout:"multiline",style:{flexShrink:0},children:[r.jsxs(Ce,{children:["Couldn't read your unmanaged ribbon customizations, so labels may show as ids and ownership (what you can edit or delete) is unknown. Reload before editing. Details:"," ",n]}),o&&r.jsx(Mt,{children:r.jsx(J,{size:"small",onClick:()=>Wn()?G(!0):o(),children:"Retry"})})]}),s==="Form"&&r.jsx(we,{intent:"info",style:{flexShrink:0},children:r.jsx(Ce,{children:"Form ribbon customizations target the legacy web client. On Unified Interface, form commands render in a flat command bar — tab layout and scaling are ignored, but button visibility and command actions work as configured (same behaviour as Ribbon Workbench). Microsoft does not officially support the tabbed ribbon UI on Unified Interface."})}),s==="SubGrid"&&r.jsx(we,{intent:"info",style:{flexShrink:0},children:r.jsx(Ce,{children:"Subgrid ribbons support only 3 native controls: Add, Show List, and Delete. Their icons cannot be changed."})}),s==="Application"&&r.jsx(we,{intent:"info",style:{flexShrink:0},children:r.jsx(Ce,{children:"Buttons added to GlobalTab appear in the persistent global command bar at the top of every page. OOB GlobalTab buttons are read-only and cannot be customized."})}),le&&!/^(Mscrm|Microsoft)\./.test(le.id)&&r.jsx(we,{intent:"info",style:{flexShrink:0},children:r.jsx(Ce,{children:Za})}),le&&Ro(le.id)&&r.jsx(we,{intent:"warning",style:{flexShrink:0},children:r.jsx(Ce,{children:"Unified Interface doesn't show this tab's buttons on the command bar, and they don't come back when the table is reloaded. Add buttons to the table's main tab instead."})}),s!=="Application"&&b>0&&r.jsxs(we,{intent:"warning",style:{flexShrink:0},children:[r.jsxs(Ce,{children:[b," element",b!==1?"s":""," of your customizations for this table",b!==1?" aren't":" isn't"," on the canvas: the ribbon doesn't return"," ",b!==1?"them":"it",". See ",r.jsx("strong",{children:"Orphaned customizations"})," in the Properties pane to delete ",b!==1?"them":"it","."]}),r.jsx(Mt,{children:r.jsx(J,{size:"small",onClick:g,children:"Show"})})]}),r.jsx(_r,{sensors:C,onDragEnd:B,children:r.jsx(km,{items:Y.tabs.map(_=>_.id),strategy:Am,children:r.jsxs("div",{className:i.tabStrip,role:"tablist","aria-label":"Ribbon tabs",children:[Y.tabs.map(_=>r.jsx(Ab,{tab:_,isActive:le?.id===_.id,isEditing:N===_.id,editValue:X,inputRef:_.id===N?T:void 0,onSelect:()=>{N!==_.id&&c(_.id),V!==_.id&&U(null)},onDoubleClick:()=>{c(_.id),j(_)},onF2:()=>j(_),renameRefused:V===_.id,onDelete:le?.id===_.id&&P(_)?()=>$(_.id):void 0,onEditChange:O,onEditCommit:Q,onEditCancel:()=>W(null),styles:i},_.id)),r.jsx("button",{type:"button",className:i.addTabBtn,title:"Add tab","aria-label":"Add tab",onClick:k,children:r.jsx(Ae,{fontSize:12})}),r.jsx("div",{className:i.spacer}),r.jsxs(J,{appearance:"subtle",size:"small",icon:r.jsx(It,{}),onClick:A,children:["Tab rules",le&&le.tabDisplayRules.length>0&&r.jsx(de,{size:"small",appearance:"tint",color:"brand",style:{marginLeft:4},children:le.tabDisplayRules.length})]})]})})}),r.jsx("div",{className:i.canvas,children:e?r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:r.jsx(Oi,{label:"Loading ribbon definition..."})}):t?r.jsxs(we,{intent:"error",children:[r.jsxs(Ce,{children:["Failed to load ribbon definition. ",t]}),o&&r.jsx(Mt,{containerAction:r.jsx(J,{appearance:"primary",size:"small",onClick:o,children:"Retry"})})]}):le?r.jsxs(r.Fragment,{children:[w==="classic"?r.jsx(ag,{tab:le,location:s}):w==="modern"?r.jsx(_g,{tab:le,location:s}):r.jsx(vb,{tab:le,location:s}),r.jsx(Sb,{tab:le,location:s})]}):r.jsx(kb,{onAddGroup:R})}),M&&o&&r.jsx(lo,{open:!0,title:"Reload the ribbon",confirmLabel:"Reload",onConfirm:()=>{G(!1),o()},onCancel:()=>G(!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."}),K&&r.jsxs(lo,{open:!0,title:"Delete tab",confirmLabel:"Delete tab",destructive:!0,onConfirm:()=>{p(s,K.id),$(null)},onCancel:()=>$(null),children:["Delete the tab “",ue(K.label,f,h),"” and its groups and buttons?"]})]})}function kb({onAddGroup:e}){const t=$b();return r.jsxs("div",{className:t.root,children:[r.jsx(mo,{fontSize:32,style:{opacity:.4}}),r.jsx(F,{size:300,children:"This tab has no groups yet"}),r.jsx(J,{appearance:"primary",size:"small",icon:r.jsx(Ae,{}),onClick:e,children:"Add first group"})]})}function Ab({tab:e,isActive:t,isEditing:n,editValue:o,inputRef:i,onSelect:s,onDoubleClick:l,onF2:a,onEditChange:c,onEditCommit:d,onEditCancel:u,onDelete:p,renameRefused:f,styles:h}){const{attributes:y,listeners:x,setNodeRef:b,transform:g,transition:S,isDragging:w}=Dm({id:e.id}),v=D(k=>k.locLabels),I=D(k=>k.baseLanguageCode),A=ue(e.label,v,I),R={transform:Em.Transform.toString(g),transition:S,opacity:w?.5:1,touchAction:"none"};return r.jsx("div",{ref:b,style:R,...y,...x,className:`${h.ribbonTab} ${t?h.ribbonTabActive:""}`,role:"tab","aria-selected":t,tabIndex:t?0:-1,onClick:s,onDoubleClick:l,title:f?`${Gi}.`:void 0,onKeyDown:k=>{k.key==="F2"&&a()},children:n?r.jsx(qe,{ref:i,className:h.inlineTabInput,value:o,onChange:(k,N)=>c(N.value),onBlur:d,onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),d()),k.key==="Escape"&&(k.preventDefault(),u()),k.stopPropagation()},onClick:k=>k.stopPropagation(),size:"small","aria-label":"Rename tab"}):r.jsxs(r.Fragment,{children:[r.jsx(F,{className:h.ribbonTabLabel,children:A}),r.jsx(F,{className:h.ribbonTabMeta,children:e.id}),p&&r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(po,{}),"aria-label":`Delete tab ${A}`,title:"Delete this tab and everything in it",onPointerDown:k=>k.stopPropagation(),onClick:k=>{k.stopPropagation(),p()}})]})})}let un=null;const Di={set(e){un=e},invoke(e){const t=un;un=null,t?.(e)},clear(){un=null},hasPending(){return un!==null}},Db=["button","flyout","splitButton","textBox","comboBox","checkBox"],Eb=me({root:{padding:`${m.spacingHorizontalM}`,display:"flex",flexDirection:"column",gap:m.spacingHorizontalS},sectionLabel:{color:m.colorNeutralForeground3,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:m.spacingHorizontalXS,marginTop:m.spacingHorizontalS},row:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},localeChips:{display:"flex",flexWrap:"wrap",gap:m.spacingHorizontalXS,alignItems:"center"},iconPreview:{width:"32px",height:"32px",borderRadius:"6px",backgroundColor:m.colorNeutralBackground4,color:m.colorNeutralForeground1,display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${m.colorNeutralStroke2}`,flexShrink:0},webResLink:{fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200,cursor:"pointer",color:m.colorBrandForeground1,textDecoration:"underline",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1,border:"none",background:"transparent",textAlign:"left"}});function Ob({button:e,location:t,tabId:n,groupId:o}){const i=Eb(),s=D(S=>S.setButtonProp),l=D(S=>S.locLabels),a=D(S=>S.baseLanguageCode),c=ee(S=>S.openIconPicker),d=ee(S=>S.openLocalizationEditor),u=ee(S=>S.openWebResourceBrowser),p=D(S=>S.customizeOobButton),f=D(S=>S.customiseButton),h=ie(S=>S.activeSolution),y=ie(S=>S.publisherPrefix),x=te(S=>S.selectButtonInContext);function b(S){s(t,n,o,e.id,S)}const g=Cp(e,l,a);return r.jsxs("div",{className:i.root,children:[(e.origin==="oob"||e.origin==="managed")&&r.jsx(we,{intent:"warning",children:r.jsx(Ce,{children:r.jsxs(F,{size:200,children:[e.origin==="oob"?r.jsxs(r.Fragment,{children:["This is an ",r.jsx("strong",{children:"out-of-the-box"})," (system) button. To change it, create an override."]}):r.jsxs(r.Fragment,{children:["This button comes from a ",r.jsx("strong",{children:"managed solution"}),e.solutionName?r.jsxs(r.Fragment,{children:[" ","(",r.jsx("strong",{children:e.solutionName}),")"]}):null,e.publisherName?r.jsxs(r.Fragment,{children:[" by ",e.publisherName]}):null,". You can't edit it directly — create an override to change it."]})," ",r.jsx(J,{size:"small",appearance:"subtle",onClick:()=>p(t,n,o,e.id),children:"Create override"}),Zi(t,n,e)&&r.jsx(J,{size:"small",appearance:"subtle",title:"Copy the button into your solution and hide the original, so the copy can be changed and moved",onClick:()=>{const S=h?.publisherPrefix?.trim()||y?.trim()||"new",w=f(t,n,o,e.id,S);w&&x(t,n,o,w)},children:"Customise button"})]})})}),r.jsx(F,{size:100,weight:"semibold",className:i.sectionLabel,children:"Identity"}),r.jsx(Oe,{label:"Label",children:r.jsx(qe,{value:e.label,onChange:(S,w)=>b({label:w.value})})}),r.jsx(Oe,{label:"Translations",children:r.jsxs("div",{className:i.localeChips,children:[g.map(S=>r.jsx(de,{appearance:"filled",color:"informative",style:{cursor:"pointer"},onClick:()=>d(e.id),children:S===1033?"en-US":String(S)},S)),g.length===0&&r.jsx(de,{appearance:"outline",color:"informative",children:"en-US (default)"}),r.jsx(J,{size:"small",appearance:"subtle",icon:r.jsx(Ae,{}),onClick:()=>d(e.id),children:"Add language…"})]})}),r.jsx(Oe,{label:"Tooltip title",children:r.jsx(qe,{value:e.tooltipTitle??"",onChange:(S,w)=>b({tooltipTitle:w.value})})}),r.jsx(Oe,{label:"Tooltip body",children:r.jsx(vm,{value:e.tooltipBody??"",onChange:(S,w)=>b({tooltipBody:w.value}),resize:"vertical"})}),r.jsx(Ve,{}),r.jsx(Oe,{label:"Icon",children:r.jsxs("div",{className:i.row,children:[r.jsx("div",{className:i.iconPreview,children:e.icon?r.jsx(Nt,{name:e.icon,size:20}):r.jsx(Gn,{style:{color:m.colorNeutralForeground3}})}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Gn,{}),onClick:c,children:"Change…"})]})}),e.icon&&r.jsx(Oe,{label:"ModernImage (auto)",children:r.jsx(qe,{value:Hi(e)??"(none)",readOnly:!0,contentAfter:r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"auto"})})}),e.image16&&r.jsx(Oe,{label:"Image16",children:r.jsx("div",{className:i.row,children:r.jsx("button",{type:"button",className:i.webResLink,onClick:()=>{Di.set(S=>{b({image16:`$webresource:${S.name}`,icon:S.name.split("/").pop()?.replace(/\..*$/,"")})}),u()},title:e.image16,children:e.image16})})}),e.image32&&r.jsx(Oe,{label:"Image32",children:r.jsx("div",{className:i.row,children:r.jsx("button",{type:"button",className:i.webResLink,onClick:()=>{Di.set(S=>{b({image32:`$webresource:${S.name}`})}),u()},title:e.image32,children:e.image32})})}),r.jsx(Ve,{}),r.jsx(Oe,{label:"Kind",children:r.jsx(dt,{value:e.kind,onChange:(S,w)=>b({kind:w.value}),children:Db.map(S=>r.jsx("option",{value:S,children:S},S))})}),r.jsxs("div",{className:i.row,style:{justifyContent:"space-between"},children:[r.jsx(F,{size:200,children:"Visible"}),r.jsx(Ei,{checked:!e.hidden,"aria-label":"Toggle button visibility",onChange:(S,w)=>b({hidden:!w.checked})})]}),r.jsx(Oe,{label:"Sequence",children:r.jsx(Sm,{value:e.sequence,step:10,min:0,onChange:(S,w)=>b({sequence:Number(w.value??e.sequence)})})}),r.jsx(Oe,{label:"Template alias",children:r.jsx(qe,{value:e.templateAlias,onChange:(S,w)=>b({templateAlias:w.value})})})]})}const zb=me({row:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:m.spacingHorizontalS}}),Bb={oob:"informative",customising:"warning",customised:"brand",uncustomising:"danger",custom:"success",reloadRequired:"danger"};function Ln(e){return e.scope==="application"?"the application ribbon's layer (every table)":e.sharedWithApplication?"this table's layer only (the application ribbon keeps the original)":"this table's layer"}function Mb({commandId:e,compact:t=!1}){const n=zb(),o=Qa(e),i=D(b=>b.customiseCommand),s=D(b=>b.uncustomiseCommand),l=D(b=>b.discardCommandChanges),a=D(b=>{const g=b.commands.find(w=>w.id===e),S=b.baselineCommands.find(w=>w.id===e);return!!g&&!!S&&JSON.stringify(g)!==JSON.stringify(S)}),[c,d]=L.useState(null);if(!o)return null;const u=(b,g,S)=>{a?d({what:b,confirmLabel:g,run:S}):S()},p=c&&r.jsxs(lo,{open:!0,title:"Discard unpublished changes?",confirmLabel:c.confirmLabel,destructive:!0,onConfirm:()=>{c.run(),d(null)},onCancel:()=>d(null),children:[c.what," discards your unpublished changes to ",r.jsx("code",{children:e}),"."]}),{provenance:f}=o,h=f==="oob"?r.jsx(J,{size:"small",appearance:"outline",onClick:()=>i(e),children:"Customise command"}):f==="customising"?r.jsx(J,{size:"small",appearance:"subtle",onClick:()=>u("Discarding the customisation","Discard customisation",()=>l(e)),children:"Discard customisation"}):f==="customised"?r.jsx(J,{size:"small",appearance:"subtle",onClick:()=>u("Uncustomising","Uncustomise",()=>s(e,o.scope)),children:"Uncustomise"}):f==="uncustomising"?r.jsx(J,{size:"small",appearance:"subtle",onClick:()=>l(e),children:"Undo uncustomise"}):null,y=r.jsx(de,{appearance:f==="oob"?"outline":"filled",color:Bb[f],size:"small",children:Zh[f]});if(t)return r.jsxs("div",{className:n.row,children:[y,h,p]});const x={oob:`Defined out of the box or by another solution. Customise it to copy the command — its actions, parameters and rule references — into ${Ln(o)}, where you can change it without touching its buttons. Editing it customises it too.`,customising:`On publish, this command is copied into ${Ln(o)} and replaces the original there. Rules keep their ids; a rule you edit is written to the layer as well.`,customised:`${Ln(o).replace(/^./,b=>b.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 ${Ln(o)} is removed (with rules only it used) and the original applies again. Reload the table after publishing to see the original definition.`,custom:"Your own command.",reloadRequired:"Your layer's copy of this command was removed, so the original applies. What is shown here is the removed copy: reload the table to load the original before changing or customising it again."};return r.jsx(we,{intent:f==="uncustomising"||f==="reloadRequired"?"warning":"info",children:r.jsxs(Ce,{children:[r.jsxs("div",{className:n.row,children:[y,r.jsx(F,{size:200,children:x[f]}),h]}),p]})})}const Lb=me({root:{padding:`${m.spacingHorizontalM}`,display:"flex",flexDirection:"column",gap:m.spacingHorizontalS},sectionLabel:{color:m.colorNeutralForeground3,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:m.spacingHorizontalXS},commandRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:m.spacingHorizontalS,padding:`${m.spacingHorizontalXS} ${m.spacingHorizontalS}`,borderRadius:m.borderRadiusMedium,border:`1px solid ${m.colorNeutralStroke2}`,backgroundColor:m.colorNeutralBackground3},commandId:{fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200,color:m.colorNeutralForeground1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function Pb({button:e,groupId:t,tabId:n,location:o}){const i=Lb(),s=D(x=>x.commands),l=D(x=>x.upsertCommand),a=D(x=>x.setButtonProp),c=D(x=>x.batch),d=ee(x=>x.openCommandEditor),[u,p]=Ue.useState(""),f=s.find(x=>x.id===e.commandId),h=()=>{const x=new Set(s.map(g=>g.id)),b=Xi("New","Command",x);c(()=>{l({id:b,enableRules:[],displayRules:[],actions:[]}),a(o,n,t,e.id,{commandId:b})}),d(b)},y=()=>{u&&(a(o,n,t,e.id,{commandId:u}),p(""))};return r.jsxs("div",{className:i.root,children:[r.jsx(Ve,{}),r.jsx(F,{size:100,weight:"semibold",className:i.sectionLabel,children:"Command"}),f?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:i.commandRow,children:[r.jsx(F,{className:i.commandId,children:f.id}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ut,{}),onClick:()=>d(f.id),children:"Edit"})]}),r.jsx(Mb,{commandId:f.id,compact:!0}),f.actions.length>0&&r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:f.actions.map((x,b)=>r.jsx(No,{size:"extra-small",appearance:"outline",children:x.kind==="javascript"?`JS: ${x.functionName}`:x.kind==="url"?`URL: ${x.address}`:x.kind==="powerFx"?`Fx: ${x.expression}`:x.kind==="customApi"?`API: ${x.actionName}`:x.kind==="outlookCommand"?`Outlook: ${x.actionType}`:`XML: ${x.tagName}`},b))}),f.enableRules.length>0&&r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"Enable rules:"}),f.enableRules.map(x=>r.jsx(No,{size:"extra-small",appearance:"outline",color:"success",children:x},x))]}),f.displayRules.length>0&&r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"Display rules:"}),f.displayRules.map(x=>r.jsx(No,{size:"extra-small",appearance:"outline",color:"informative",children:x},x))]})]}):e.commandId?r.jsx("div",{className:i.commandRow,children:r.jsxs(F,{className:i.commandId,style:{color:m.colorStatusWarningForeground3},children:[e.commandId," (not found)"]})}):r.jsxs(r.Fragment,{children:[r.jsx(Oe,{label:"Bind existing command",style:{width:"100%",minWidth:0},children:r.jsxs(dt,{size:"small",value:u,onChange:(x,b)=>p(b.value),style:{width:"100%",minWidth:0},children:[r.jsx("option",{value:"",children:"Select command…"}),s.map(x=>r.jsx("option",{value:x.id,children:x.id},x.id))]})}),r.jsxs("div",{style:{display:"flex",gap:m.spacingHorizontalXS},children:[r.jsx(J,{appearance:"outline",size:"small",onClick:y,children:"Bind selected"}),r.jsx(J,{appearance:"outline",size:"small",icon:r.jsx(Ae,{}),onClick:h,children:"Create and bind"})]})]})]})}const Fb=me({section:{display:"flex",flexDirection:"column",gap:m.spacingHorizontalXS},header:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS},pillList:{display:"flex",flexWrap:"wrap",gap:m.spacingHorizontalXS,maxWidth:"100%",minWidth:0},pill:{display:"inline-flex",alignItems:"center",gap:"4px",padding:`2px ${m.spacingHorizontalXS}`,border:`1px solid ${m.colorNeutralStroke2}`,borderRadius:m.borderRadiusCircular,fontSize:m.fontSizeBase200,fontFamily:m.fontFamilyMonospace,cursor:"pointer",backgroundColor:m.colorNeutralBackground2,maxWidth:"100%",minWidth:0,":hover":{backgroundColor:m.colorNeutralBackground3}},pillLabel:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},addBtn:{alignSelf:"flex-start"},note:{fontSize:m.fontSizeBase100,color:m.colorNeutralForeground3,fontStyle:"italic"}}),Rl=({kind:e})=>{const t=Fb(),n=te(T=>T.location),o=te(T=>T.tabId),i=te(T=>T.selectedGroupId),s=te(T=>T.selectedButtonId),l=D(T=>T.commands),a=D(T=>T.displayRules),c=D(T=>T.enableRules),d=D(T=>T.upsertCommand),u=D(T=>T.upsertDisplayRule),p=D(T=>T.upsertEnableRule),f=D(T=>T.batch),h=ee(T=>T.openRuleEditor),g=D(T=>T.ribbons)[n].tabs.find(T=>T.id===o)?.groups.find(T=>T.id===i),S=en(g,s),w=l.find(T=>T.id===S?.commandId),v=e==="display"?w?.displayRules??[]:w?.enableRules??[],I=e==="display"?a:c,[A,R]=Ue.useState(""),k=I.filter(T=>!v.includes(T.id)),N=T=>{if(!w)return;const z=v.filter($=>$!==T);d(e==="display"?{...w,displayRules:z}:{...w,enableRules:z})},W=e==="display"?"Display rules (ALL must pass)":"Enable rules (ALL must pass)",X=()=>{if(!w)return;if(e==="display"){const $=new Set(a.map(G=>G.id)),M=xn(ks(w.id),"Display",$);f(()=>{u({id:M,steps:[]}),d({...w,displayRules:[...w.displayRules,M]})}),h(M,"display");return}const T=new Set(c.map($=>$.id)),z=xn(ks(w.id),"Enable",T);f(()=>{p({id:z,steps:[]}),d({...w,enableRules:[...w.enableRules,z]})}),h(z,"enable")},O=()=>{!w||!A||(d(e==="display"?{...w,displayRules:[...w.displayRules,A]}:{...w,enableRules:[...w.enableRules,A]}),R(""))};return r.jsxs("div",{className:t.section,children:[r.jsxs("div",{className:t.header,children:[r.jsx(F,{size:200,weight:"semibold",children:W}),v.length>0&&r.jsx(de,{appearance:"tint",size:"small",color:"informative",children:v.length})]}),!w&&r.jsx(F,{className:t.note,children:"Bind a command first to manage rules."}),r.jsx("div",{className:t.pillList,children:v.map(T=>{const z=I.find($=>$.id===T);return r.jsxs("div",{className:t.pill,children:[r.jsx("span",{className:t.pillLabel,onClick:()=>h(T,e==="display"?"display":"enable"),title:`${T} — ${z?.steps.length??0} step(s)`,children:T}),r.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",color:m.colorNeutralForeground3},onClick:()=>N(T),"aria-label":`Remove rule ${T}`,children:r.jsx(po,{style:{fontSize:12}})})]},T)})}),w&&r.jsxs(r.Fragment,{children:[r.jsx(Oe,{label:`Bind existing ${e} rule`,style:{width:"100%",minWidth:0},children:r.jsxs(dt,{size:"small",value:A,onChange:(T,z)=>R(z.value),style:{width:"100%",minWidth:0},children:[r.jsx("option",{value:"",children:"Select rule…"}),k.map(T=>r.jsx("option",{value:T.id,children:T.id},T.id))]})}),r.jsxs("div",{style:{display:"flex",gap:m.spacingHorizontalXS},children:[r.jsx(J,{className:t.addBtn,appearance:"subtle",size:"small",onClick:O,disabled:!A,children:"Bind selected"}),r.jsxs(J,{className:t.addBtn,appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:X,children:["Create new ",e," rule"]})]})]}),e==="enable"&&r.jsxs(F,{className:t.note,children:["Note: Disabled buttons are ",r.jsx("strong",{children:"hidden"})," in the modern command bar (Unified Interface). In the classic ribbon (Legacy client), disabled buttons remain visible but do not respond to clicks."]})]})},_b=()=>r.jsx(Rl,{kind:"display"}),qb=()=>r.jsx(Rl,{kind:"enable"}),Hb=me({section:{display:"flex",flexDirection:"column",gap:m.spacingHorizontalXS},header:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS},stepRow:{display:"flex",flexDirection:"column",gap:"8px",padding:`${m.spacingVerticalXS} ${m.spacingHorizontalXS}`,border:`1px solid ${m.colorNeutralStroke2}`,borderRadius:m.borderRadiusMedium,backgroundColor:m.colorNeutralBackground2},stepBadge:{alignSelf:"flex-start"},note:{fontSize:m.fontSizeBase100,color:m.colorNeutralForeground3,fontStyle:"italic"},warningNote:{fontSize:m.fontSizeBase100,color:m.colorStatusWarningForeground1,backgroundColor:m.colorStatusWarningBackground1,padding:`2px ${m.spacingHorizontalXS}`,borderRadius:m.borderRadiusSmall}}),Wb=()=>{const e=Hb(),t=ee(c=>c.openScalingEditor),n=te(c=>c.location),o=te(c=>c.tabId),l=D(c=>c.ribbons)[n].tabs.find(c=>c.id===o),a=l?.groups.length??0;return r.jsxs("div",{className:e.section,children:[r.jsxs("div",{className:e.header,children:[r.jsx(F,{size:200,weight:"semibold",children:"Scaling"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(fo,{}),onClick:t,children:"Edit scaling"})]}),r.jsx("div",{className:e.warningNote,children:"⚠ Scaling applies only to the Classic ribbon (Legacy client / Outlook list views). The modern command bar (Unified Interface) ignores scaling."}),l?r.jsxs(F,{size:100,className:e.note,children:["Tab ",r.jsx("strong",{children:l.label})," has ",a," group(s). Open the Scaling Editor to configure MaxSize and Scale steps."]}):r.jsx(F,{size:100,className:e.note,children:"Select a tab to configure scaling."})]})},Gb=me({section:{display:"flex",flexDirection:"column",gap:m.spacingHorizontalXS},row:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},note:{fontSize:m.fontSizeBase100,color:m.colorNeutralForeground3}}),Ub=[{label:"Show on Unified Interface (Refresh)",value:"Refresh"},{label:"Show on Classic ribbon (Legacy)",value:"Legacy"},{label:"Show on Tablets (Modern)",value:"Modern"}],Xb=()=>{const e=Gb(),t=te($=>$.location),n=te($=>$.tabId),o=te($=>$.selectedGroupId),i=te($=>$.selectedButtonId),s=D($=>$.ribbons),l=D($=>$.upsertCommand),a=D($=>$.upsertDisplayRule),c=D($=>$.batch),d=D($=>$.commands),u=D($=>$.displayRules),p=ee($=>$.openCommandEditor),f=D($=>$.setOpenRecordOverride),h=te($=>$.clearSelection),y=ie($=>$.activeSolution),x=ie($=>$.publisherPrefix),b=s[t],S=b.tabs.find($=>$.id===n)?.groups.find($=>$.id===o),w=en(S,i),v=Na.includes(t),I=ka(b),A=I.length>0,R=I.map($=>Aa($)),k=R.includes("theirs"),N=!k&&R.includes("unknown"),W=!A&&!Da(b),X=Ji(b).filter($=>!Ta($.button)),O=$=>{const M=y?.publisherPrefix?.trim()||x?.trim()||"new";!$&&I.some(G=>G.button.id===i)&&h(),!(!f(t,$,M)||!$)&&p(Be)},T=()=>{if(w?.commandId)return d.find($=>$.id===w.commandId)},z=$=>{const M=T();if(!M)return;let K=u.find(q=>q.steps.length===1&&q.steps[0].kind==="CommandClientTypeRule"&&q.steps[0].type===$)?.id,Q;if(!K){const q=`${M.id}.${$}.DisplayRule`;K=q;let V=1;for(;u.some(j=>j.id===K);)K=`${q}.${V}`,V+=1;Q={id:K,steps:[{kind:"CommandClientTypeRule",type:$}]}}const P=K;c(()=>{Q&&a(Q),M.displayRules.includes(P)||l({...M,displayRules:[...M.displayRules,P]})})};return r.jsxs("div",{className:e.section,children:[r.jsx(F,{size:200,weight:"semibold",children:"Advanced"}),w&&r.jsx("div",{children:r.jsxs(F,{size:100,className:e.note,children:["Tab: ",r.jsx("code",{style:{fontFamily:m.fontFamilyMonospace},children:n})]})}),v&&r.jsxs("div",{children:[r.jsx(Ei,{label:`Override default record open behavior on the ${t==="SubGrid"?"sub-grid":"home grid"} (Mscrm.OpenRecordItem)`,checked:A,disabled:k||N||W,onChange:($,M)=>O(M.checked)}),r.jsxs(F,{size:100,className:e.note,children:[`When enabled, the table gets a CommandDefinition with Id="Mscrm.OpenRecordItem" whose action runs instead of opening the record when a user double-clicks a row of this table's `,t==="SubGrid"?"sub-grids (on any form)":"home grid",`, selects its primary column link or presses Enter on it. As in Microsoft's recipe, an "Open record" button using the command is added to this location's command bar — the override only reaches a grid through a button there; don't hide that button. `,r.jsx("strong",{children:"Unified Interface only."})," The Command Editor will open so you can set the real web resource and function name; Publish is blocked until you do. Turning it off removes that button, and the command once no button uses it."]}),k&&r.jsx(F,{size:100,className:e.note,children:`The "Open record" button here comes from another solution, so the override can't be turned off from your customizations.`}),N&&r.jsx(F,{size:100,className:e.note,children:`CBS doesn't know yet which solution the "Open record" button here comes from (its solution layers haven't loaded), so it isn't removed — reload the table if this doesn't clear.`}),X.length>0&&r.jsxs(F,{size:100,className:e.note,children:["Also using Mscrm.OpenRecordItem here:"," ",X.map($=>$.button.id).join(", "),". Turning the override off keeps ",X.length===1?"it":"them"," and the command."]}),W&&r.jsx(F,{size:100,className:e.note,children:"This location has no group to put the button in."})]}),t==="Form"&&r.jsx(F,{size:100,className:e.note,children:"Form command bar changes apply to every main form of this table (ImportExportXml/Entities/Entity/RibbonDiffXml). Form-specific ribbons (systemform/form/RibbonDiffXml) aren't supported on Unified Interface, so CBS doesn't write them (#14)."}),r.jsxs("div",{children:[r.jsx(F,{size:100,weight:"semibold",className:e.note,children:"Client type filter (adds a CommandClientTypeRule):"}),r.jsxs(F,{size:100,className:e.note,children:[r.jsx("strong",{children:"Refresh"})," = Unified Interface web client | ",r.jsx("strong",{children:"Legacy"})," = Classic ribbon / Outlook | ",r.jsx("strong",{children:"Modern"})," = Dynamics 365 for tablets"]}),r.jsx("div",{className:e.row,style:{marginTop:"4px"},children:Ub.map($=>r.jsx(de,{appearance:"outline",style:{cursor:"pointer"},title:`Add CommandClientTypeRule: ${$.value}`,onClick:()=>z($.value),children:$.label},$.value))})]})]})},Vb=me({banner:{marginBottom:m.spacingHorizontalXS}}),Kb=()=>{const e=Vb(),t=te(g=>g.selectedButtonId),n=te(g=>g.selectedGroupId),o=te(g=>g.location),i=te(g=>g.tabId),s=D(g=>g.conflicts),l=D(g=>g.ribbons),a=ee(g=>g.openConflictDrawer),u=l[o].tabs.find(g=>g.id===i)?.groups.find(g=>g.id===n),p=en(u,t),f=s.find(g=>g.elementId===t),h=p?.origin==="managed";if(!t||!h&&!f)return null;const y=p?.solutionName??f?.solutions[0]?.solutionName,x=p?.publisherName??f?.solutions[0]?.publisher,b=f?.solutions.length??(h?1:0);return r.jsxs(we,{intent:"warning",className:e.banner,children:[r.jsx(Ce,{children:r.jsx(F,{children:b>1?`This button is customized by ${b} solutions. The last imported solution wins.`:`This button belongs to a managed solution${y?` “${y}”`:""}${x?` by ${x}`:""}. Customizing it will create an unmanaged override.`})}),r.jsx(Mt,{children:r.jsx(J,{appearance:"transparent",size:"small",onClick:()=>t&&a(t),children:"View solution layers"})})]})},Jb=me({root:{display:"flex",flexDirection:"column",gap:m.spacingVerticalXS,padding:`${m.spacingVerticalS} ${m.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,minWidth:0},id:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200},pending:{textDecoration:"line-through",color:m.colorNeutralForeground3}});function Yb(){const e=Jb(),t=D(s=>s.layers),n=D(s=>s.pendingUnhides),o=D(s=>s.setLayerHideUnhidden),i=["entity","application"].flatMap(s=>(t[s]?.hides??[]).map(l=>({scope:s,...l})));return i.length===0?null:r.jsxs("section",{className:e.root,"aria-label":"Hidden by customizations",children:[r.jsx(jt,{children:"Hidden by customizations"}),r.jsx(Me,{children:"Hidden by a HideCustomAction in your unmanaged customizations, so they aren't on the canvas. Un-hiding takes effect when you publish; reload afterwards to see them."}),i.map(s=>{const l=n[s.scope].includes(s.location);return r.jsxs("div",{className:e.row,children:[r.jsx(Ye,{}),r.jsx(Te,{content:`${s.location} (${s.scope==="entity"?"this table":"application ribbon"})`,relationship:"description",children:r.jsx(F,{className:`${e.id} ${l?e.pending:""}`,children:s.location})}),r.jsx(J,{size:"small",appearance:l?"subtle":"secondary",onClick:()=>o(s.scope,s.location,!l),children:l?"Keep hidden":"Unhide"})]},`${s.scope}:${s.location}`)})]})}const Zb=me({root:{display:"flex",flexDirection:"column",gap:m.spacingVerticalXS,padding:`${m.spacingVerticalS} ${m.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"flex-start",gap:m.spacingHorizontalS,minWidth:0},icon:{flexShrink:0,marginTop:"2px",color:m.colorPaletteMarigoldForeground1},text:{display:"flex",flexDirection:"column",flex:1,minWidth:0},mono:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200},why:{color:m.colorNeutralForeground3},pending:{textDecoration:"line-through",color:m.colorNeutralForeground3}});function Qb(){const e=Zb(),t=D(a=>a.orphans),n=D(a=>a.pendingOrphanDeletes),o=D(a=>a.setOrphanDeleted),[i,s]=L.useState(null),l=["entity","application"].flatMap(a=>t[a].map(c=>({scope:a,...c})));return l.length===0?null:r.jsxs("section",{className:e.root,"aria-label":"Orphaned customizations",children:[r.jsx(jt,{children:"Orphaned customizations"}),r.jsx(Me,{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(a=>{const c=n[a.scope].includes(a.id),d=a.label&&a.label!==a.id?`“${a.label}” `:"",u=`${a.scope}:${a.id}`,p=!!a.recentPublish?.published,f=c?r.jsx(J,{size:"small",appearance:"subtle","aria-label":`Keep ${a.id}`,onClick:()=>o(a.scope,a.id,!1),children:"Keep"}):p?r.jsx(Te,{content:"Published from here moments ago: reload later — it most likely isn't loaded yet",relationship:"description",children:r.jsx(J,{size:"small",disabledFocusable:!0,"aria-label":`Delete ${a.id}`,children:"Delete"})}):a.recentPublish&&i!==u?r.jsx(J,{size:"small",appearance:"secondary","aria-label":`Delete ${a.id}`,onClick:()=>s(u),children:"Delete…"}):a.recentPublish?r.jsx(J,{size:"small",appearance:"primary","aria-label":`Delete ${a.id} anyway`,onClick:()=>{s(null),o(a.scope,a.id,!0)},children:"Delete anyway"}):r.jsx(J,{size:"small",appearance:"secondary","aria-label":`Delete ${a.id}`,onClick:()=>o(a.scope,a.id,!0),children:"Delete"});return r.jsxs("div",{className:e.row,children:[r.jsx(Hu,{className:e.icon}),r.jsxs("div",{className:e.text,children:[r.jsx(Te,{content:`${a.element} ${a.id} — CustomAction ${a.customActionId} at ${a.location}`,relationship:"description",children:r.jsxs(F,{className:Ht(e.mono,c&&e.pending),children:[d,a.id]})}),r.jsx(Me,{className:Ht(e.mono,e.why),children:a.location}),r.jsx(Me,{className:e.why,children:a.why})]}),f]},u)})]})}const ey=me({root:{display:"flex",flexDirection:"column",gap:m.spacingVerticalS,padding:`${m.spacingVerticalS} ${m.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS},field:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},mono:{fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200,overflowWrap:"anywhere"},xml:{margin:0,maxHeight:"240px",overflow:"auto",padding:m.spacingHorizontalS,borderRadius:m.borderRadiusMedium,backgroundColor:m.colorNeutralBackground3,fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase100,whiteSpace:"pre-wrap",overflowWrap:"anywhere"}});function ty({button:e,location:t,tabId:n,groupId:o}){const i=ey(),s=D(y=>y.locLabels),l=D(y=>y.setButtonProp),a=D(y=>y.hideOobButton),c=D(y=>y.hideWithDisplayRules),[d,u]=L.useState(!1),p=t==="Application"&&n==="Mscrm.GlobalTab"&&e.oob&&!e.custom,f=Vn[e.kind],h=(y,x)=>x?r.jsxs("div",{className:i.field,children:[r.jsx(Me,{children:y}),r.jsx(F,{className:i.mono,children:x})]}):null;return r.jsxs("section",{className:i.root,"aria-label":`${f} (read-only)`,children:[r.jsxs("div",{className:i.title,children:[r.jsx(Rt,{"aria-hidden":!0}),r.jsx(jt,{children:f})]}),r.jsxs(Me,{children:["Command Bar Studio shows this <",bn[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."]}),h("Label",ue(e.label,s)),h("Id",e.id),h("Command",e.commandId||void 0),r.jsx("div",{children:r.jsx(J,{size:"small",disabled:p,icon:e.hidden?r.jsx(It,{}):r.jsx(Ye,{}),onClick:()=>!e.hidden&&e.oob?u(!0):l(t,n,o,e.id,{hidden:!e.hidden}),children:e.hidden?"Unhide":"Hide"})}),d&&r.jsx(os,{open:!0,buttonLabel:e.label,commandId:e.commandId,onConfirmHide:()=>{a(t,n,o,e.id),u(!1)},onConfirmDisplayRule:()=>{c(e.commandId),u(!1)},onCancel:()=>u(!1)}),e.source?.xml&&r.jsxs("div",{className:i.field,children:[r.jsx(Me,{children:"XML"}),r.jsx("pre",{className:i.xml,children:e.source.xml})]})]})}const us=me({root:{display:"flex",flexDirection:"column",gap:m.spacingVerticalS,padding:`${m.spacingVerticalS} ${m.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,flexWrap:"wrap"},grid:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:m.spacingHorizontalM,rowGap:m.spacingVerticalXS,alignItems:"baseline"},key:{color:m.colorNeutralForeground3,fontSize:m.fontSizeBase200},value:{fontSize:m.fontSizeBase200,overflowWrap:"anywhere",minWidth:0},mono:{fontFamily:m.fontFamilyMonospace},list:{display:"flex",flexDirection:"column",gap:m.spacingVerticalXXS}});function st({label:e,value:t,mono:n}){const o=us();return t?r.jsxs(r.Fragment,{children:[r.jsx(F,{className:o.key,children:e}),r.jsx(F,{className:`${o.value} ${n?o.mono:""}`,children:t})]}):null}function ny({command:e,items:t}){const n=us(),o=tn(),i=be(a=>a.selectCommand),s=be(a=>e.parentId?a.commands.find(c=>c.id===e.parentId):void 0),l=e.visibility==="formula"||e.action==="formula";return r.jsxs("section",{className:n.root,"aria-label":"Modern command properties",children:[r.jsxs("div",{className:n.title,children:[r.jsx(jt,{children:e.label}),r.jsx(de,{appearance:"tint",color:"important",children:"Modern"}),e.managed&&r.jsx(de,{appearance:"outline",color:"informative",children:"Managed"})]}),r.jsx(we,{intent:"info",children:r.jsx(Ce,{children:"Modern commands are read-only in Command Bar Studio and are never published from here. Edit them in the command designer."})}),r.jsxs("div",{className:n.grid,children:[ml(e,o).map(a=>r.jsx(st,{label:a.label,value:a.value},a.label)),r.jsx(st,{label:"Tooltip title",value:e.tooltipTitle}),r.jsx(st,{label:"Tooltip text",value:e.tooltipDescription}),r.jsx(st,{label:"Accessibility text",value:e.accessibilityText}),r.jsx(st,{label:"Icon",value:e.fontIcon??e.iconWebResourceName??e.iconWebResourceId}),r.jsx(st,{label:"Group title",value:e.groupTitle}),r.jsx(st,{label:"Name",value:e.name}),r.jsx(st,{label:"Unique name",value:e.uniqueName,mono:!0}),r.jsx(st,{label:"Id",value:e.id,mono:!0})]}),l&&r.jsx(Me,{children:"Power Fx formulas are stored in the app's command component library, not on the command, so only the function reference is shown here."}),s&&r.jsxs(r.Fragment,{children:[r.jsx(Ve,{}),r.jsx(F,{className:n.key,children:"Inside"}),r.jsx(ni,{onClick:()=>i(s.id),children:s.label})]}),t.length>0&&r.jsxs(r.Fragment,{children:[r.jsx(Ve,{}),r.jsxs(F,{className:n.key,children:["Items (",t.length,")"]}),r.jsx("div",{className:n.list,children:t.map(a=>r.jsxs(ni,{onClick:()=>i(a.id),children:[a.label,a.hidden?" (hidden)":""]},a.id))})]}),e.classicRules.length>0&&r.jsxs(r.Fragment,{children:[r.jsx(Ve,{}),r.jsxs(F,{className:n.key,children:["Classic rules (",e.classicRules.length,")"]}),r.jsx("div",{className:n.list,children:e.classicRules.map(a=>r.jsxs(F,{className:`${n.value} ${n.mono}`,children:[a.kind==="enable"?"Enable":"Display",":"," ",a.uniqueName??a.name]},a.id))})]})]})}function oy({overrides:e}){const t=us(),n=tn(),o=be(s=>s.selectCommand);if(e.length===0)return null;const i=e.some(s=>s.effect==="hidden");return r.jsx("section",{className:t.root,"aria-label":"Modern command overrides",children:r.jsx(we,{intent:i?"warning":"info",children:r.jsx(Ce,{children:r.jsxs("div",{className:t.list,children:[e.map(s=>r.jsxs("span",{children:[is(s,n),"."," ",r.jsx(ni,{inline:!0,onClick:()=>o(s.command.id),children:"View"})]},s.command.id)),r.jsx(Me,{children:"Matched by the migrated command's unique name. Unified Interface may show the modern command instead of this button."})]})})})})}const iy=me({root:{display:"flex",flexDirection:"column",height:"100%",overflowY:"auto",backgroundColor:m.colorNeutralBackground2,borderLeft:`1px solid ${m.colorNeutralStroke2}`},header:{padding:`${m.spacingHorizontalS} ${m.spacingHorizontalM}`,borderBottom:`1px solid ${m.colorNeutralStroke2}`,flexShrink:0},empty:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:m.spacingHorizontalM,color:m.colorNeutralForeground3,padding:m.spacingHorizontalXL,textAlign:"center"},section:{padding:`${m.spacingHorizontalS} ${m.spacingHorizontalM}`}});function sy(){const e=iy(),t=te(y=>y.selectedButtonId),n=te(y=>y.selectedGroupId),o=te(y=>y.location),i=te(y=>y.tabId),c=D(y=>y.ribbons)[o].tabs.find(y=>y.id===i)?.groups.find(y=>y.id===n),d=en(c,t),u=c&&d?Yn(c,d.id):void 0,p=D(y=>y.locLabels),f=Lg(),h=Bg(o,d?.id);return r.jsxs("aside",{className:e.root,"aria-label":"Properties",children:[r.jsx("div",{className:e.header,children:r.jsx(jt,{children:"Properties"})}),!d&&f?r.jsx(ny,{command:f.command,items:f.children}):d?r.jsxs(r.Fragment,{children:[r.jsx(Kb,{}),r.jsx(oy,{overrides:h}),u&&r.jsx("div",{className:e.section,children:r.jsxs(Me,{children:["Menu item of “",ue(u.parent.label,p),"”",u.section.title?` — section “${u.section.title}”`:""]})}),Ze(d.kind)?r.jsx(ty,{button:d,location:o,tabId:i,groupId:n}):r.jsxs(r.Fragment,{children:[r.jsx(Ob,{button:d,location:o,tabId:i,groupId:n}),r.jsx(Ve,{}),r.jsx("div",{className:e.section,children:r.jsx(Pb,{button:d,groupId:n,tabId:i,location:o})}),r.jsx(Ve,{}),r.jsx("div",{className:e.section,children:r.jsx(_b,{})}),r.jsx(Ve,{}),r.jsx("div",{className:e.section,children:r.jsx(qb,{})}),r.jsx(Ve,{}),r.jsx("div",{className:e.section,children:r.jsx(Wb,{})}),r.jsx(Ve,{}),r.jsx("div",{className:e.section,children:r.jsx(Xb,{})})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.empty,children:[r.jsx(Wu,{fontSize:32,style:{opacity:.4}}),r.jsx(F,{size:300,children:"Select a button to view its properties"})]}),r.jsx(Yb,{}),r.jsx(Qb,{})]})]})}const uo=e=>e instanceof Error?e.message:String(e),ry=3e3;function ay(e,t){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>s(new Error(`no answer in ${t/1e3} s`)),t)});return Promise.race([e,o]).finally(()=>clearTimeout(n))}async function ly(e){const t=[],n=window.toolboxAPI?.utils?.copyToClipboard;if(n)try{return await ay(n(e),ry),{ok:!0}}catch(o){t.push(`host: ${uo(o)}`)}if(navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0}}catch(o){t.push(`browser: ${uo(o)}`)}return{ok:!1,error:t.join("; ")||"no clipboard is available here"}}async function Wx(e,t,n){const o=window.toolboxAPI?.fileSystem?.saveFile;if(o)try{const i=await o(e,t,n);return i?{ok:!0,path:i}:{ok:!1,canceled:!0}}catch(i){return{ok:!1,error:uo(i)}}try{const i=URL.createObjectURL(new Blob([t],{type:"application/xml"})),s=document.createElement("a");return s.href=i,s.download=e,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e4),{ok:!0}}catch(i){return{ok:!1,error:uo(i)}}}const jl=me({root:{display:"flex",flexDirection:"column",borderTop:`1px solid ${m.colorNeutralStroke2}`,backgroundColor:m.colorNeutralBackground2,flexShrink:0},tabRow:{display:"flex",alignItems:"center",borderBottom:`1px solid ${m.colorNeutralStroke2}`,gap:0,paddingRight:m.spacingHorizontalS,flexShrink:0},content:{flex:1,overflowY:"auto",padding:`${m.spacingHorizontalXS} ${m.spacingHorizontalM}`},toolbar:{display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,paddingBottom:m.spacingHorizontalXS,borderBottom:`1px solid ${m.colorNeutralStroke3}`,marginBottom:m.spacingHorizontalXS},table:{width:"100%",borderCollapse:"collapse",fontSize:m.fontSizeBase200},th:{textAlign:"left",padding:`4px ${m.spacingHorizontalS}`,fontWeight:m.fontWeightSemibold,color:m.colorNeutralForeground3,fontSize:m.fontSizeBase100,borderBottom:`1px solid ${m.colorNeutralStroke2}`,whiteSpace:"nowrap"},td:{padding:`4px ${m.spacingHorizontalS}`,borderBottom:`1px solid ${m.colorNeutralStroke3}`,verticalAlign:"middle"},mono:{fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200,cursor:"pointer",color:m.colorBrandForeground1,":hover":{textDecoration:"underline"}},chip:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:m.borderRadiusMedium,fontSize:m.fontSizeBase100,border:`1px solid ${m.colorNeutralStroke2}`,backgroundColor:m.colorNeutralBackground3,marginRight:"3px",fontFamily:m.fontFamilyMonospace},historyRow:{display:"flex",alignItems:"flex-start",gap:m.spacingHorizontalS,padding:`${m.spacingHorizontalXS} 0`,borderBottom:`1px solid ${m.colorNeutralStroke3}`},historyAvatar:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:m.colorBrandBackground2,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:"2px"},historyContent:{flex:1,minWidth:0},consoleRow:{padding:"2px 0",fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200,display:"flex",gap:m.spacingHorizontalS},consoleTs:{color:m.colorNeutralForeground4,flexShrink:0,fontSize:m.fontSizeBase100}});function cy(){const e=jl(),t=ee(C=>C.activeBottomTab),n=ee(C=>C.setActiveBottomTab),o=ee(C=>C.bottomPanelHeight),i=ee(C=>C.bottomCollapsed),s=ee(C=>C.setBottomCollapsed),l=D(C=>C.commands),a=D(C=>C.displayRules),c=D(C=>C.enableRules),d=D(C=>C.past),u=D(C=>C.ribbons),p=D(C=>C.restore),f=ie(C=>C.currentUserName),h=se(C=>C.entries),y=se(C=>C.clear),x=se(C=>C.logWarn),b=ee(C=>C.openCommandEditor),g=ee(C=>C.openRuleEditor),S=ee(C=>C.openDiffViewer),w=D(C=>C.upsertCommand),v=D(C=>C.upsertEnableRule),I=D(C=>C.upsertDisplayRule),[A,R]=L.useState(""),[k,N]=L.useState(""),[W,X]=L.useState(""),[O,T]=L.useState(""),z=L.useMemo(()=>{const C=A.toLowerCase().trim();return C?l.filter(B=>B.id.toLowerCase().includes(C)||B.enableRules.some(Y=>Y.toLowerCase().includes(C))||B.displayRules.some(Y=>Y.toLowerCase().includes(C))):l},[l,A]),$=L.useMemo(()=>{const C=k.toLowerCase().trim();return C?a.filter(B=>B.id.toLowerCase().includes(C)||B.steps.some(Y=>Y.kind.toLowerCase().includes(C))):a},[a,k]),M=L.useMemo(()=>{const C=W.toLowerCase().trim();return C?c.filter(B=>B.id.toLowerCase().includes(C)||B.steps.some(Y=>Y.kind.toLowerCase().includes(C))):c},[c,W]),G=L.useMemo(()=>{const C=O.toLowerCase().trim();return C?d.filter(B=>B.op.toLowerCase().includes(C)||B.target.toLowerCase().includes(C)||B.detail.toLowerCase().includes(C)||B.userName.toLowerCase().includes(C)):d},[d,O]),K=()=>{const C=new Set(l.map(Y=>Y.id)),B=Xi("New","Command",C);w({id:B,enableRules:[],displayRules:[],actions:[]}),b(B)},Q=()=>{const C=new Set(c.map(Y=>Y.id)),B=xn("New","Enable",C);v({id:B,steps:[]}),g(B,"enable")},P=()=>{const C=new Set(a.map(Y=>Y.id)),B=xn("New","Display",C);I({id:B,steps:[]}),g(B,"display")},q=L.useMemo(()=>{const C={};for(const B of Object.values(u))for(const Y of B.tabs)for(const le of Y.groups)for(const _ of $e(le))_.commandId&&(C[_.commandId]=(C[_.commandId]??0)+1);return C},[u]),V=L.useMemo(()=>{const C={};for(const B of l)for(const Y of[...B.enableRules,...B.displayRules])C[Y]=(C[Y]??0)+1;return C},[l]),U=i?32:o;function j(C){return C.userName&&C.userName!=="You"?C.userName:f||"You"}return r.jsxs("div",{className:e.root,style:{height:U},children:[r.jsxs("div",{className:e.tabRow,children:[r.jsxs(zi,{selectedValue:t,onTabSelect:(C,B)=>n(B.value),size:"small",style:{flex:1},children:[r.jsxs(Ke,{value:"commands",children:["Commands (",l.length,")"]}),r.jsxs(Ke,{value:"displayRules",children:["Display rules (",a.length,")"]}),r.jsxs(Ke,{value:"enableRules",children:["Enable rules (",c.length,")"]}),r.jsxs(Ke,{value:"history",children:["History (",d.length,")"]}),r.jsx(Ke,{value:"console",children:"Console"})]}),r.jsx(J,{appearance:"subtle",size:"small",icon:i?r.jsx(Dr,{}):r.jsx(gt,{}),onClick:()=>s(!i),"aria-label":i?"Expand panel":"Collapse panel"})]}),!i&&r.jsxs("div",{className:e.content,children:[t==="commands"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:K,children:"New command"}),r.jsx(qe,{size:"small",contentBefore:r.jsx(ft,{}),placeholder:`Filter ${l.length} command${l.length!==1?"s":""}…`,value:A,onChange:(C,B)=>R(B.value),style:{minWidth:0,flex:1,maxWidth:360}}),A&&r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[z.length," match",z.length!==1?"es":""]})]}),r.jsxs("table",{className:e.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:e.th,children:"Command"}),r.jsx("th",{className:e.th,children:"Actions"}),r.jsx("th",{className:e.th,children:"Enable rules"}),r.jsx("th",{className:e.th,children:"Display rules"}),r.jsx("th",{className:e.th,children:"Refs"}),r.jsx("th",{className:e.th})]})}),r.jsx("tbody",{children:z.map(C=>r.jsxs("tr",{children:[r.jsx("td",{className:e.td,children:r.jsx("span",{className:e.mono,onClick:()=>b(C.id),role:"button",tabIndex:0,onKeyDown:B=>B.key==="Enter"&&b(C.id),children:C.id})}),r.jsxs("td",{className:e.td,children:[C.actions.map((B,Y)=>r.jsx("span",{className:e.chip,children:B.kind==="javascript"?"JS":B.kind==="url"?"URL":B.kind==="powerFx"?"Fx":B.kind==="customApi"?"API":B.kind==="outlookCommand"?"Outlook":"XML"},Y)),C.actions.length===0&&r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"—"})]}),r.jsx("td",{className:e.td,children:C.enableRules.map(B=>r.jsx(Te,{content:B,relationship:"label",children:r.jsx("span",{className:e.chip,style:{cursor:"pointer",color:m.colorBrandForeground1},onClick:()=>g(B,"enable"),children:B.split(".").pop()})},B))}),r.jsx("td",{className:e.td,children:C.displayRules.map(B=>r.jsx(Te,{content:B,relationship:"label",children:r.jsx("span",{className:e.chip,style:{cursor:"pointer",color:m.colorBrandForeground1},onClick:()=>g(B,"display"),children:B.split(".").pop()})},B))}),r.jsx("td",{className:e.td,children:r.jsx(de,{size:"small",appearance:"tint",color:q[C.id]?"brand":"informative",children:q[C.id]??0})}),r.jsx("td",{className:e.td,children:r.jsx(J,{appearance:"subtle",size:"small",onClick:()=>b(C.id),children:"Edit"})})]},C.id))})]})]}),t==="displayRules"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:P,children:"New display rule"}),r.jsx(qe,{size:"small",contentBefore:r.jsx(ft,{}),placeholder:`Filter ${a.length} display rule${a.length!==1?"s":""}…`,value:k,onChange:(C,B)=>N(B.value),style:{minWidth:0,flex:1,maxWidth:360}}),k&&r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[$.length," match",$.length!==1?"es":""]})]}),r.jsx(or,{rules:$,kind:"display",ruleRefs:V,onEdit:C=>g(C,"display"),styles:e})]}),t==="enableRules"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:Q,children:"New enable rule"}),r.jsx(qe,{size:"small",contentBefore:r.jsx(ft,{}),placeholder:`Filter ${c.length} enable rule${c.length!==1?"s":""}…`,value:W,onChange:(C,B)=>X(B.value),style:{minWidth:0,flex:1,maxWidth:360}}),W&&r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[M.length," match",M.length!==1?"es":""]})]}),r.jsx(or,{rules:M,kind:"enable",ruleRefs:V,onEdit:C=>g(C,"enable"),styles:e})]}),t==="history"&&r.jsxs(r.Fragment,{children:[d.length>0&&r.jsxs("div",{className:e.toolbar,children:[r.jsx(qe,{size:"small",contentBefore:r.jsx(ft,{}),placeholder:`Filter ${d.length} entr${d.length!==1?"ies":"y"}…`,value:O,onChange:(C,B)=>T(B.value),style:{minWidth:0,flex:1,maxWidth:360}}),O&&r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[G.length," match",G.length!==1?"es":""]})]}),d.length===0?r.jsx(F,{size:200,style:{color:m.colorNeutralForeground3},children:"No history yet — make a change to see it here."}):G.slice().reverse().map((C,B)=>{const Y=d.indexOf(C);return r.jsxs("div",{className:e.historyRow,children:[r.jsx("div",{className:e.historyAvatar,"aria-hidden":!0,children:r.jsx(Ar,{fontSize:12,style:{color:m.colorBrandForeground1}})}),r.jsxs("div",{className:e.historyContent,children:[r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[r.jsx(F,{size:200,weight:"semibold",children:C.op}),r.jsxs(F,{size:200,children:["— ",r.jsx("strong",{children:C.target})]}),C.detail&&r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:C.detail})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2},children:[r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[j(C)," ·"," ",new Date(C.ts).toLocaleTimeString()]}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(jr,{}),onClick:()=>S("history"),children:"View diff"}),r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Nr,{}),title:"Undo this change and every later one (redo brings them back)",onClick:()=>p(Y),children:"Undo from here"})]})]})]},B)})]}),t==="console"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(gn,{}),disabled:h.length===0,onClick:()=>{const C=h.slice().reverse().map(B=>{const Y=new Date(B.ts).toLocaleTimeString();return`${B.scope} ${Y}
133
+ [${B.level.toUpperCase()}]
134
+ ${B.message}`}).join(`
135
+
136
+ `);ly(C).then(B=>{B.ok||x("ui",`Couldn't copy the log: ${B.error}.`)})},title:"Copy all log entries to clipboard",children:"Copy log"}),r.jsx(J,{appearance:"subtle",size:"small",onClick:y,children:"Clear log"})]}),r.jsx("div",{children:h.length===0?r.jsx(F,{size:200,style:{color:m.colorNeutralForeground3},children:"No runtime diagnostics yet."}):h.slice().reverse().map(C=>r.jsx(dy,{ts:`${C.scope} ${new Date(C.ts).toLocaleTimeString()}`,level:C.level,message:C.message},C.id))})]})]})]})}function or({rules:e,kind:t,ruleRefs:n,onEdit:o,styles:i}){return r.jsxs("table",{className:i.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:i.th,children:"Rule"}),r.jsx("th",{className:i.th,children:"Steps"}),r.jsx("th",{className:i.th,children:"Used by"}),r.jsx("th",{className:i.th,children:"Type"}),r.jsx("th",{className:i.th})]})}),r.jsx("tbody",{children:e.map(s=>r.jsxs("tr",{children:[r.jsx("td",{className:i.td,children:r.jsx("span",{className:i.mono,onClick:()=>o(s.id),role:"button",tabIndex:0,onKeyDown:l=>l.key==="Enter"&&o(s.id),children:s.id})}),r.jsxs("td",{className:i.td,children:[s.steps.slice(0,3).map((l,a)=>r.jsx("span",{className:i.chip,children:l.kind.replace(/Rule$/,"")},a)),s.steps.length>3&&r.jsxs("span",{className:i.chip,style:{color:m.colorNeutralForeground3},children:["+",s.steps.length-3]}),s.steps.length===0&&r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"—"})]}),r.jsx("td",{className:i.td,children:r.jsxs(de,{size:"small",appearance:"tint",color:n[s.id]?"brand":"informative",children:[n[s.id]??0," cmd",n[s.id]!==1?"s":""]})}),r.jsx("td",{className:i.td,children:r.jsx(de,{size:"small",appearance:"outline",color:t==="enable"?"success":"informative",children:t})}),r.jsx("td",{className:i.td,children:r.jsx(J,{appearance:"subtle",size:"small",onClick:()=>o(s.id),children:"Edit"})})]},s.id))})]})}function dy({ts:e,level:t,message:n}){const o=jl(),i=t==="error"?m.colorStatusDangerForeground1:t==="warn"?m.colorStatusWarningForeground1:m.colorNeutralForeground3;return r.jsxs("div",{className:o.consoleRow,children:[r.jsx("span",{className:o.consoleTs,children:e}),r.jsxs("span",{style:{color:i},children:["[",t.toUpperCase(),"]"]}),r.jsx("span",{style:{color:m.colorNeutralForeground1},children:n})]})}const $l=me({root:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:m.colorNeutralBackground2},header:{padding:`${m.spacingHorizontalS} ${m.spacingHorizontalM}`,borderBottom:`1px solid ${m.colorNeutralStroke2}`,flexShrink:0},searchBox:{padding:`${m.spacingHorizontalXS} ${m.spacingHorizontalS}`,flexShrink:0},scrollArea:{flex:1,overflow:"hidden",padding:`0 ${m.spacingHorizontalXS} ${m.spacingHorizontalXS}`},gridWrap:{height:"100%"},cell:{padding:0,minWidth:0,alignSelf:"stretch"},sectionHeader:{flex:1,alignSelf:"stretch",padding:`${m.spacingHorizontalXS} ${m.spacingHorizontalS}`,display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,cursor:"pointer",userSelect:"none",":hover":{backgroundColor:m.colorNeutralBackground3}},entityRow:{flex:1,alignSelf:"stretch",minWidth:0,display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`${m.spacingHorizontalS} ${m.spacingHorizontalM}`,cursor:"pointer",borderRadius:m.borderRadiusMedium,borderLeft:"3px solid transparent",":hover":{backgroundColor:m.colorNeutralBackground3}},entityRowActive:{borderLeftColor:m.colorBrandStroke1,backgroundColor:m.colorBrandBackground2,":hover":{backgroundColor:m.colorBrandBackground2Hover}},entityName:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function uy(){const e=$l(),t=ie(S=>S.entities),n=ie(S=>S.activeEntity),o=xe(S=>S.requestEntitySwitch),i=ie(S=>S.activeSolution),s=ie(S=>S.solutionEntityIds),[l,a]=L.useState(""),[c,d]=L.useState(!0),[u,p]=L.useState(!0),f=t,h=L.useMemo(()=>{const S=l.toLowerCase();return f.filter(w=>w.displayName.toLowerCase().includes(S)||w.logicalName.toLowerCase().includes(S))},[f,l]),y=h.filter(S=>S.isCustomEntity),x=h.filter(S=>!S.isCustomEntity),b=L.useMemo(()=>[...y.length>0?[{kind:"header",id:"custom-header",label:"CUSTOM",count:y.length}]:[],...c?y.map(S=>({kind:"entity",id:`custom-${S.logicalName}`,entity:S})):[],...x.length>0?[{kind:"header",id:"standard-header",label:"STANDARD",count:x.length}]:[],...u?x.map(S=>({kind:"entity",id:`std-${S.logicalName}`,entity:S})):[]],[y,c,x,u]),g=[rt({columnId:"table",renderHeaderCell:()=>r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:"Entity"}),renderCell:S=>{if(S.kind==="header"){const w=S.label==="CUSTOM"?c:u;return r.jsx("div",{className:e.sectionHeader,onClick:()=>S.label==="CUSTOM"?d(v=>!v):p(v=>!v),role:"button",tabIndex:0,"aria-expanded":w,onKeyDown:v=>{v.key!=="Enter"&&v.key!==" "||(v.preventDefault(),S.label==="CUSTOM"?d(I=>!I):p(I=>!I))},children:r.jsxs(F,{size:100,weight:"semibold",style:{color:m.colorNeutralForeground3},children:[w?"▾":"▸"," ",S.label," (",S.count,")"]})})}return r.jsx(my,{entity:S.entity,isActive:n?.logicalName===S.entity.logicalName,onClick:()=>o(S.entity)})}})];return r.jsxs("div",{className:e.root,children:[r.jsx("div",{className:e.header,children:r.jsx(jt,{children:"Tables"})}),r.jsx("div",{className:e.searchBox,children:r.jsx(qe,{contentBefore:r.jsx(ft,{}),placeholder:"Search tables…",size:"small",value:l,onChange:(S,w)=>a(w.value),style:{width:"100%"}})}),r.jsxs("div",{className:e.scrollArea,children:[!i&&r.jsx("div",{style:{padding:24,textAlign:"center"},children:r.jsx(F,{size:200,style:{color:m.colorNeutralForeground3},children:"Select a solution from the top bar to see its tables."})}),i&&s===null&&r.jsx("div",{style:{padding:24,textAlign:"center"},children:r.jsx(Oi,{size:"small",label:"Loading solution tables…"})}),i&&s!==null&&f.length===0&&r.jsx("div",{style:{padding:24,textAlign:"center"},children:r.jsxs(F,{size:200,style:{color:m.colorNeutralForeground3},children:["No tables to show for ",r.jsx("em",{children:i.friendlyName}),".",r.jsx("br",{}),r.jsx("br",{}),"Add a table to the solution in the maker portal (Solutions ›"," ",r.jsx("em",{children:i.friendlyName})," › Add existing › Table) and reload."]})}),i&&s!==null&&f.length>0&&r.jsxs(cs,{className:e.gridWrap,items:b,columns:g,getRowId:S=>S.id,focusMode:"none",children:[r.jsx(ds,{children:r.jsx(Rn,{children:({renderHeaderCell:S})=>r.jsx(Br,{children:S()})})}),r.jsx(ls,{itemSize:52,height:420,listProps:{width:"100%"},children:({item:S,rowId:w},v)=>r.jsx(Rn,{style:v,children:({renderCell:I})=>r.jsx(Mr,{className:e.cell,children:I(S)})},w)})]})]})]})}function my({entity:e,isActive:t,onClick:n}){const o=$l();return r.jsxs("div",{className:`${o.entityRow} ${t?o.entityRowActive:""}`,onClick:n,role:"button",tabIndex:0,"aria-pressed":t,onKeyDown:i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),n())},children:[r.jsxs("div",{className:o.entityName,children:[r.jsx(F,{size:200,weight:t?"semibold":"regular",children:e.displayName}),r.jsx("br",{}),r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3},children:e.logicalName})]}),e.isManaged&&r.jsx(Rt,{fontSize:12,style:{color:m.colorNeutralForeground3},"aria-label":"Managed"})]})}const py="application/x-rw-se",ir={HomepageGrid:"Home",SubGrid:"Sub",Form:"Form",Application:"App"},fy=me({root:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:m.colorNeutralBackground2},header:{padding:`${m.spacingHorizontalS} ${m.spacingHorizontalM}`,borderBottom:`1px solid ${m.colorNeutralStroke2}`,flexShrink:0},tabs:{flexShrink:0,borderBottom:`1px solid ${m.colorNeutralStroke2}`},scrollArea:{flex:1,overflowY:"auto",padding:m.spacingHorizontalXS},item:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`${m.spacingHorizontalXS} ${m.spacingHorizontalS}`,cursor:"pointer",borderRadius:m.borderRadiusMedium,":hover":{backgroundColor:m.colorNeutralBackground3}},draggableItem:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`${m.spacingHorizontalXS} ${m.spacingHorizontalS}`,cursor:"grab",borderRadius:m.borderRadiusMedium,userSelect:"none",":hover":{backgroundColor:m.colorNeutralBackground3},":active":{cursor:"grabbing"}},itemName:{flex:1,fontFamily:m.fontFamilyMonospace,fontSize:m.fontSizeBase200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},gripHandle:{color:m.colorNeutralForeground4,fontSize:m.fontSizeBase200,flexShrink:0,lineHeight:1}});function hy(){const e=fy(),[t,n]=L.useState("commands"),o=D(b=>b.commands),i=D(b=>b.displayRules),s=D(b=>b.enableRules),l=D(b=>b.templates),a=D(b=>b.ribbons),c=D(b=>b.baseline),d=D(b=>b.upsertCommand),u=D(b=>b.upsertEnableRule),p=ee(b=>b.openCommandEditor),f=ee(b=>b.openRuleEditor),h=L.useMemo(()=>{const b=[];for(const g of Object.keys(a)){const S=a[g],w=c[g];for(const v of S.tabs)for(const I of v.groups)for(const A of $e(I)){if(!A.custom)continue;const R=w.tabs.flatMap(k=>k.groups).flatMap(k=>$e(k)).some(k=>k.id===A.id);b.push({button:A,location:g,tabId:v.id,groupId:I.id,isNew:!R})}}return b},[a,c]),y=()=>{const b=new Set(o.map(S=>S.id)),g=Xi("New","Command",b);d({id:g,enableRules:[],displayRules:[],actions:[]}),p(g)},x=()=>{const b=new Set([...s.map(S=>S.id),...i.map(S=>S.id)]),g=xn("New","Enable",b);u({id:g,steps:[]}),f(g,"enable")};return r.jsxs("div",{className:e.root,children:[r.jsx("div",{className:e.header,children:r.jsx(jt,{children:"Solution Elements"})}),r.jsxs(zi,{className:e.tabs,selectedValue:t,onTabSelect:(b,g)=>n(g.value),size:"small",children:[r.jsxs(Ke,{value:"buttons",children:["Buttons (",h.length,")"]}),r.jsxs(Ke,{value:"commands",children:["Commands (",o.length,")"]}),r.jsxs(Ke,{value:"rules",children:["Rules (",s.length+i.length,")"]}),r.jsxs(Ke,{value:"templates",children:["Templates (",l.length,")"]})]}),r.jsxs("div",{className:e.scrollArea,children:[t==="buttons"&&r.jsxs(r.Fragment,{children:[r.jsx(F,{size:100,style:{color:m.colorNeutralForeground3,padding:`4px ${m.spacingHorizontalS}`,display:"block"},children:"Drag onto the ribbon canvas to add a button"}),h.map(({button:b,location:g,isNew:S})=>r.jsx(Te,{content:`${b.id} · ${ir[g]} ribbon`,relationship:"label",children:r.jsxs("div",{className:e.draggableItem,draggable:!0,onDragStart:w=>{w.dataTransfer.setData(py,JSON.stringify({button:b})),w.dataTransfer.effectAllowed="copy"},title:"Drag onto a ribbon group to add this button",children:[r.jsx("span",{className:e.gripHandle,children:"⋮⋮"}),r.jsx(qt,{fontSize:14,style:{color:m.colorNeutralForeground3,flexShrink:0}}),r.jsx(F,{className:e.itemName,children:b.label||b.id}),r.jsx(de,{size:"small",appearance:"outline",children:ir[g]}),S&&r.jsx(de,{size:"small",color:"brand",appearance:"tint",children:"NEW"})]})},`${g}::${b.id}`)),h.length===0&&r.jsxs(F,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:["No custom buttons yet. Add one from the ribbon canvas — in"," ",r.jsx("strong",{children:"Modern command bar"})," use the ",r.jsx("strong",{children:"+ Add"})," button at the end of the bar; in ",r.jsx("strong",{children:"Classic ribbon"})," use the ",r.jsx("strong",{children:"+"})," ","inside any group."]})]}),t==="commands"&&r.jsxs(r.Fragment,{children:[r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:y,style:{width:"100%",justifyContent:"flex-start",marginBottom:4},children:"New command"}),o.map(b=>r.jsxs("div",{className:e.item,onClick:()=>p(b.id),role:"button",tabIndex:0,onKeyDown:g=>g.key==="Enter"&&p(b.id),children:[r.jsx(Ut,{fontSize:14,style:{color:m.colorNeutralForeground3}}),r.jsx(F,{className:e.itemName,children:b.id}),r.jsxs(F,{size:100,style:{color:m.colorNeutralForeground3},children:[b.actions.length," action",b.actions.length!==1?"s":""]})]},b.id)),o.length===0&&r.jsx(F,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:"No commands yet"})]}),t==="rules"&&r.jsxs(r.Fragment,{children:[r.jsx(J,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:x,style:{width:"100%",justifyContent:"flex-start",marginBottom:4},children:"New rule"}),s.map(b=>r.jsxs("div",{className:e.item,onClick:()=>f(b.id,"enable"),role:"button",tabIndex:0,onKeyDown:g=>g.key==="Enter"&&f(b.id,"enable"),children:[r.jsx(F,{className:e.itemName,children:b.id}),r.jsx(de,{size:"small",color:"success",appearance:"tint",children:"Enable"})]},b.id)),i.map(b=>r.jsxs("div",{className:e.item,onClick:()=>f(b.id,"display"),role:"button",tabIndex:0,onKeyDown:g=>g.key==="Enter"&&f(b.id,"display"),children:[r.jsx(F,{className:e.itemName,children:b.id}),r.jsx(de,{size:"small",color:"informative",appearance:"tint",children:"Display"})]},b.id)),s.length===0&&i.length===0&&r.jsx(F,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:"No rules yet"})]}),t==="templates"&&r.jsxs(r.Fragment,{children:[l.map(b=>r.jsxs("div",{className:e.item,children:[r.jsx(Gu,{fontSize:14,style:{color:m.colorNeutralForeground3}}),r.jsx(F,{className:e.itemName,children:b.id})]},b.id)),l.length===0&&r.jsx(F,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:"No templates defined"})]})]})]})}function ms(){return window.dataverseAPI}async function gy(){const e=ms();se.getState().logInfo("dataverse","Loading solutions...");const i=((await e.queryData("solutions?$select=solutionid,uniquename,friendlyname,version,ismanaged,versionnumber,isvisible&$expand=publisherid($select=publisherid,uniquename,friendlyname,customizationprefix,customizationoptionvalueprefix)&$filter=isvisible eq true and uniquename ne 'Active' and uniquename ne 'Default'&$orderby=friendlyname asc")).value??[]).map(l=>{const a=l.publisherid??{};return{id:String(l.solutionid??""),uniqueName:String(l.uniquename??""),friendlyName:String(l.friendlyname??""),version:String(l.version??""),isManaged:!!l.ismanaged,publisherId:a.publisherid??"",publisherUniqueName:a.uniquename??"",publisherName:a.friendlyname??"",publisherPrefix:a.customizationprefix??"",publisherOptionValuePrefix:typeof a.customizationoptionvalueprefix=="number"?a.customizationoptionvalueprefix:void 0,versionNumber:l.versionnumber}});se.getState().logInfo("dataverse",`Loaded ${i.length} solution(s).`);const s=i.filter(l=>!l.isManaged).slice(0,5);for(const l of s)se.getState().logInfo("dataverse",` • "${l.friendlyName||l.uniqueName}" → prefix="${l.publisherPrefix||"(empty)"}" (publisher: ${l.publisherName||l.publisherUniqueName||"(empty)"})`);return i}async function by(e){if(!e)return[];const t=ms();se.getState().logInfo("dataverse",`Loading solution entity components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 1`,s=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return se.getState().logInfo("dataverse",`Solution contains ${s.length} table component(s).`),s}async function yy(e){if(!e)return[];const t=ms();se.getState().logInfo("dataverse",`Loading solution ribbon components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 50`,s=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return se.getState().logInfo("dataverse",`Solution contains ${s.length} ribbon-customization component(s).`),s}function xy(){return window.dataverseAPI}async function vy(e){if(e.length===0)return[];const t=xy(),n=se.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=(await Promise.all(e.map(async l=>{try{const a=await t.queryData(`EntityDefinitions(${l})?$select=${o}`);return{metadataId:String(a.MetadataId??""),logicalName:String(a.LogicalName??""),schemaName:a.SchemaName?String(a.SchemaName):void 0,displayName:a.DisplayName?.UserLocalizedLabel?.Label??String(a.LogicalName??""),isCustomEntity:!!a.IsCustomEntity,isManaged:!1,isIntersect:!!a.IsIntersect}}catch(a){return n.logWarn("dataverse",`Could not resolve entity for component ${l}: ${a instanceof Error?a.message:String(a)}`),null}}))).filter(l=>l!==null&&!l.isIntersect).sort((l,a)=>l.displayName.localeCompare(a.displayName));return n.logInfo("dataverse",`Loaded metadata for ${s.length} table(s).`),s}async function Nl(e){const t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);const o=Jf(n),i=Object.entries(o).find(([s])=>s.toLowerCase().endsWith("ribbonxml.xml"));if(!i){const s=Object.values(o)[0];if(s)return Sn(s);throw new Error("decompressRibbonZip: no RibbonXml.xml entry found in ZIP")}return Sn(i[1])}function Tl(){return window.dataverseAPI}async function Sy(){let e="the organization record has no languagecode";for(let t=0;t<2;t++)try{const o=(await Tl().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 wy=[/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 Cy(e){const t=e instanceof Error?`${e.message} ${String(e.code??"")}`:typeof e=="string"?e:JSON.stringify(e??"");return wy.some(n=>n.test(t))}const Iy={0:"Import",1:"Uninstall",2:"Export",3:"Publish",4:"PublishAll",5:"LanguageProvision",6:"ImportTranslation",7:"RibbonMetadataGeneration",8:"WorkflowSetState",10:"ExportLite",11:"UpdatingMissingPackages"},kl=30;async function Ry(e=kl,t=Date.now()){const n=t-e*6e4;try{return((await Tl().queryData("msdyn_solutionhistories?$select=msdyn_name,msdyn_operation,msdyn_status,msdyn_starttime&$orderby=msdyn_starttime desc&$top=25")).value??[]).filter(i=>typeof i.msdyn_operation=="number"&&(i.msdyn_status===0||i.msdyn_status===2)&&i.msdyn_operation!==2&&i.msdyn_operation!==10&&(!i.msdyn_starttime||Date.parse(i.msdyn_starttime)>=n)).map(i=>({operation:Iy[i.msdyn_operation??-1]??`operation ${i.msdyn_operation}`,name:i.msdyn_name??"",startedOn:i.msdyn_starttime??""}))}catch{return[]}}const Al=e=>new Promise(t=>setTimeout(t,e)),sr=e=>e.map(t=>t.name&&t.name!==t.operation?`${t.operation} (${t.name})`:t.operation).join(", ");async function Gx(e={}){const t=e.sleep??Al,n=e.now??Date.now,o=n()+(e.timeoutMs??10*6e4);for(;;){const i=await Ry(kl,n());if(i.length===0)return;if(n()>=o)throw new Error(`The environment is still busy (${sr(i)} running). Try again when it has finished — Solutions › History shows its progress.`);e.onProgress?.(`Waiting for another operation to finish: ${sr(i)}…`),await t(15e3)}}async function jy(e,t,n={}){const o=n.sleep??Al,i=n.now??Date.now,s=i()+(n.timeoutMs??10*6e4);for(let l=0;;l++)try{return await t()}catch(a){if(!Cy(a))throw a;const c=Math.min(6e4,15e3*2**l);if(i()+c>s)throw new Error(`${e} kept failing because another solution operation is running in the environment (${a instanceof Error?a.message:String(a)}). 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)}}const Dl=30,$y=Dl*6e4,El=(e,t)=>`cbs:lastPublish:${e.replace(/\/+$/,"")}:${t}`;function Ol(e,t){try{const n=sessionStorage.getItem(e);if(!n)return null;const o=JSON.parse(n);if(typeof o.at!="number"||!o.publishedAt||typeof o.publishedAt!="object")return null;const i=Object.fromEntries(Object.entries(o.publishedAt).filter(s=>typeof s[1]=="number"&&t-s[1]<$y));return{at:o.at,publishedAt:i}}catch{return null}}function Ux(e,t,n,o=Date.now()){const i=El(e,t),s={...Ol(i,o)?.publishedAt??{}};for(const l of n){const a=/^customActions:ca:(.+)$/.exec(l)?.[1];a&&(s[a]=o)}try{sessionStorage.setItem(i,JSON.stringify({at:o,publishedAt:s}))}catch{}}function Ny(e,t,n=Date.now()){return Ol(El(e,t),n)}const rr=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]),Ko=new Set(["Tab","Group"]),ar=/^(.+)\._children$/;function lr(e){return e?Array.from(e.children):[]}function jn(e,t){return t?e.split("{!EntityLogicalName}").join(t):e}function Ty(e,t){const n=new Map,o=(i,s)=>n.set(jn(i,t),s);for(const i of e)for(const s of i.tabs){o(`${s.id}.Groups`,s.id);for(const l of s.groups){o(`${l.id}.Controls`,s.id);for(const a of $e(l))for(const c of a.menu?.sections??[])o(c.controlsId,s.id)}}return n}function ky(e,t){const n=new Set,o=i=>n.add(jn(i,t));for(const i of e)for(const s of i.tabs){o(s.id);for(const l of s.groups){o(l.id);for(const a of $e(l))o(a.id)}}return n}function cr(e){return[e,...Array.from(e.getElementsByTagName("*"))].flatMap(t=>t.getAttribute("Id")??[])}function Ay(e,t,n,o={}){const{locLabels:i=[],languageCode:s=1033}=o,l=[...t],a=R=>jn(R,n),c=ky(l,n),d=Ty(l,n),u=[...go(e).map(R=>R.location),...o.otherHides??[]].map(a),p=new Set(u),f=new Set,h=[...e.customActions.values()].map(R=>new DOMParser().parseFromString(R,"application/xml").documentElement);for(const R of h)if(R.tagName==="CustomAction")for(const k of Array.from(R.getElementsByTagName("*")))p.has(a(k.getAttribute("Id")??""))&&cr(k).forEach(N=>f.add(a(N)));const y=R=>f.has(R)||u.some(k=>R===k||R.startsWith(`${k}.`)),x=new Set(["Mscrm.Tabs",`Mscrm.SubGrid.${n}.ContextualTabs`]),b=(R,k)=>{const N=d.get(k);return N&&Ro(N)?{reason:"hidden-tab",why:`It is on the tab ${N}, which Unified Interface doesn't show; the ribbon doesn't return what is added there.`}:N||x.has(k)?{reason:"not-returned",why:R==="Tab"?`The ribbon doesn't return this tab at ${k}, so Command Bar Studio can't place it (it may still show in Unified Interface).`:`${k} is on the canvas, but the ribbon doesn't return this ${R.toLowerCase()} there (for example a control added to a new group in a separate CustomAction).`}:{reason:"missing-location",why:/^(Mscrm|Microsoft)\./.test(k)?`${k} isn't in this table's ribbon as loaded: it is not shown — possibly hidden by another solution — or it was removed.`:`${k} isn't in this table's ribbon as loaded: the group, tab or menu was removed or renamed, the Location is misspelled, or it is hidden by another solution.`}},g=R=>{const k=R.getAttribute("LabelText")??R.getAttribute("Title")??R.getAttribute("Alt")??"";return ue(k,i,s)||(R.getAttribute("Id")??"")},S=[],w=(R,k,N)=>{const W=R.getAttribute("Id")??"",X=ar.exec(k)?.[1]??k;if(!W||c.has(a(W))||y(a(W))||y(a(X)))return;const O=Ko.has(R.tagName);S.push({orphan:{id:W,element:R.tagName,label:g(R),location:k,customActionId:N,...b(R.tagName,a(X)),deleteControlIds:O?[]:[W],deleteContainerIds:O?[W]:[]},parent:X,inside:new Set(cr(R))})};for(const R of h){if(R.tagName!=="CustomAction")continue;const k=R.getAttribute("Location")??"";if(!ar.test(k)||/\.Scaling\._children$/.test(k))continue;const N=lr(lr(R).find(O=>O.tagName==="CommandUIDefinition"))[0],W=N?.getAttribute("Id");if(!N||!W||!(Ko.has(N.tagName)||rr.has(N.tagName)))continue;const X=R.getAttribute("Id")??"";if(!c.has(a(W))){w(N,k,X);continue}for(const O of Array.from(N.getElementsByTagName("*"))){const T=O.parentElement;T?.tagName!=="Controls"&&T?.tagName!=="Groups"||!Ko.has(O.tagName)&&!rr.has(O.tagName)||w(O,`${T.getAttribute("Id")??""}._children`,X)}}const v=R=>S.find(k=>k!==R&&k.inside.has(R.parent)&&!R.inside.has(k.parent)),I=R=>{const k=new Set([R]);let N=R;for(let W=v(N);W&&!k.has(W);W=v(N))k.add(W),N=W;return N},A=S.filter(R=>!v(R));for(const R of S){const k=I(R);if(k===R||!A.includes(k))continue;const N=(W,X)=>X.forEach(O=>W.includes(O)||W.push(O));N(k.orphan.deleteControlIds,R.orphan.deleteControlIds),N(k.orphan.deleteContainerIds,R.orphan.deleteContainerIds)}return A.map(R=>R.orphan)}function Dy(e,t,n=Date.now()){if(!t)return e;const o=Dl*6e4,i=s=>Math.max(0,Math.floor((n-s)/6e4));return e.map(s=>{const l=t.publishedAt[s.customActionId];if(l!==void 0&&n-l<o){const c=i(l);return{...s,recentPublish:{minutesAgo:c,published:!0},why:`Published from here ${c} min before this table was loaded: the ribbon may not have caught up yet (it can lag 10 minutes or more). Reload the table later before deleting it. ${s.why}`}}if(n-t.at>=o)return s;const a=i(t.at);return{...s,recentPublish:{minutesAgo:a,published:!1},why:`The table was published from here ${a} min before this table was loaded, and the ribbon may not have caught up yet. ${s.why}`}})}const zl=window.dataverseAPI;function Pn(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 Bl(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 Ml(e){return Bl(e)[0]}function Ey(e,t,n={}){const o={HomepageGrid:[],SubGrid:[],Form:[]};for(const s of e)s.id.startsWith("Mscrm.Form.")?o.Form.push(s):s.id.startsWith("Mscrm.SubGrid.")?o.SubGrid.push(s):s.id.startsWith("Mscrm.HomepageGrid.")?o.HomepageGrid.push(s):o[Ml(s)??"HomepageGrid"].push(s);const i=s=>{const l=Object.fromEntries(o[s].filter(a=>n[a.id]).map(a=>[a.id,n[a.id]]));return{location:s,entityLogicalName:t,tabs:o[s],...Object.keys(l).length>0?{scalingByTab:l}:{}}};return{HomepageGrid:i("HomepageGrid"),SubGrid:i("SubGrid"),Form:i("Form")}}const Oy="Microsoft.Dynamics.CRM.RibbonLocationFilters'All'";function zy(e){return`RetrieveEntityRibbon(EntityName=@e,RibbonLocationFilter=@f)?@e='${encodeURIComponent(e.replace(/'/g,"''"))}'&@f=${Oy}`}async function By(e,t=[]){se.getState().logInfo("dataverse",`RetrieveEntityRibbon(${e}, All)`);const n=await zl.queryData(zy(e));if(typeof n?.CompressedEntityXml!="string"||!n.CompressedEntityXml)throw new Error(`Dataverse returned no ribbon for ${e} (RetrieveEntityRibbon had no CompressedEntityXml).`);const o=await Nl(n.CompressedEntityXml),i=Io(o,"HomepageGrid",e,t),s=Ey(i.ribbon.tabs,e,i.ribbon.scalingByTab);if(i.ribbon.templateLayouts)for(const l of Object.values(s))l.templateLayouts=i.ribbon.templateLayouts;return se.getState().logInfo("dataverse",`RetrieveEntityRibbon succeeded for ${e} (Form=${s.Form.tabs.length}, HomepageGrid=${s.HomepageGrid.tabs.length}, SubGrid=${s.SubGrid.tabs.length})`),{ribbons:s,commands:i.commands,displayRules:i.displayRules,enableRules:i.enableRules,locLabels:i.locLabels}}async function My(e=[]){se.getState().logInfo("dataverse","RetrieveApplicationRibbon()");const n=(await zl.execute({operationName:"RetrieveApplicationRibbon",operationType:"function"}))?.CompressedApplicationRibbonXml;if(typeof n!="string"||!n)throw new Error("Dataverse returned no application ribbon (RetrieveApplicationRibbon had no CompressedApplicationRibbonXml).");const o=await Nl(n);return se.getState().logInfo("dataverse","RetrieveApplicationRibbon succeeded"),Io(o,"Application","{!EntityLogicalName}",e)}function Jo(e,t,n,o=[]){const i={added:[],replaced:[]};if(n.commandDefinitions.size+n.enableRules.size+n.displayRules.size===0)return i;const s=vf(n),l=(h,y)=>JSON.stringify(h,dr)===JSON.stringify(y,dr),a=(h,y)=>{const x=new Map(y.map(b=>[b.id,b]));for(let b=0;b<h.length;b++){const g=x.get(h[b].id);g&&!l(g,h[b])&&(h[b]=g,i.replaced.push(g.id))}};a(t.commands,s.commands),a(t.enableRules,s.enableRules),a(t.displayRules,s.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 y of h.tabs)for(const x of y.groups)for(const b of $e(x))b.commandId&&!c.has(b.commandId)&&n.commandDefinitions.has(b.commandId)&&d.add(b.commandId);const u=s.commands.filter(h=>d.has(h.id));t.commands.push(...u),i.added.push(...u.map(h=>h.id));const p=new Set(t.enableRules.map(h=>h.id)),f=new Set(t.displayRules.map(h=>h.id));for(const h of t.commands){for(const y of h.enableRules){const x=s.enableRules.find(b=>b.id===y);x&&!p.has(y)&&(t.enableRules.push(x),p.add(y),i.added.push(y))}for(const y of h.displayRules){const x=s.displayRules.find(b=>b.id===y);x&&!f.has(y)&&(t.displayRules.push(x),f.add(y),i.added.push(y))}}return i}function dr(e,t){if(typeof t!="string"||!t.trimStart().startsWith("<"))return t;try{return Wt(t)}catch{return t}}function Ly(e,t){const n=(o,i)=>new Map([...o].filter(([s])=>!i?.has(s)));return{...e,commandDefinitions:n(e.commandDefinitions,t?.commandDefinitions),enableRules:n(e.enableRules,t?.enableRules),displayRules:n(e.displayRules,t?.displayRules)}}function Py(e,t,n){if(n!==1033)for(const o of e)for(const i of o.tabs)for(const s of i.groups)for(const l of $e(s)){for(const d of l.menu?.sections??[]){const u=d.attributes?.Title;u?.startsWith("$LocLabels:")&&(d.title=ue(u,t,n))}const a=l.source;if(!a)continue;const c=[[a.labelToken,"label"],[a.tooltipTitleToken,"tooltipTitle"],[a.tooltipBodyToken,"tooltipBody"]];for(const[d,u]of c)d?.startsWith("$LocLabels:")&&(l[u]=ue(d,t,n))}}function ur(e,t,n,o){const i=new Set(Object.values(e).flatMap(f=>f?.tabs.map(h=>h.id)??[])),s=new Set(go(t).map(f=>f.location)),l=n?`Mscrm.SubGrid.${n}.ContextualTabs._children`:null,a=[];for(const f of oa(t.customActions).values()){const h=new DOMParser().parseFromString(f,"application/xml").documentElement;if(h.tagName!=="CustomAction")continue;const y=jn(h.getAttribute("Location")??"",n??void 0);if(y!=="Mscrm.Tabs._children"&&y!==l)continue;const x=Array.from(h.getElementsByTagName("CommandUIDefinition")[0]?.children??[])[0],b=x?.tagName==="Tab"?x.getAttribute("Id"):null;!b||i.has(jn(b,n??void 0))||a.push({xml:new XMLSerializer().serializeToString(x),subGrid:y===l})}if(a.length===0)return[];const c=`<RibbonDefinitions><RibbonDefinition><UI><Ribbon><Tabs>${a.map(f=>f.xml).join("")}</Tabs></Ribbon></UI><RuleDefinitions><TabDisplayRules>${[...t.tabDisplayRules.values()].join("")}</TabDisplayRules></RuleDefinitions></RibbonDefinition></RibbonDefinitions>`,d=Io(c,n?"HomepageGrid":"Application",n??"{!EntityLogicalName}",o);d.ribbon.tabs=d.ribbon.tabs.filter(f=>!s.has(f.id));for(const f of d.ribbon.tabs){f.groups=f.groups.filter(h=>!s.has(h.id));for(const h of f.groups){h.buttons=h.buttons.filter(y=>!s.has(y.id));for(const y of $e(h))s.has(y.id)&&da(h,y.id)}}const u=new Set(a.filter(f=>f.subGrid).map(f=>new DOMParser().parseFromString(f.xml,"application/xml").documentElement.getAttribute("Id"))),p=f=>n?u.has(f.id)?"SubGrid":Ml(f)??"HomepageGrid":"Application";for(const f of d.ribbon.tabs){const h=n&&!u.has(f.id)?Bl(f).slice(1):[];h.length>0&&se.getState().logWarn("ribbon",`Tab ${f.id} shows on the ${p(f)} and on the ${h.join(" and ")} (its display rules); Command Bar Studio lists it under ${p(f)} only.`);const y=e[p(f)];if(!y)continue;y.tabs.push(f),y.tabs.sort((b,g)=>b.sequence-g.sequence);const x=d.ribbon.scalingByTab?.[f.id];x&&(y.scalingByTab={...y.scalingByTab??{},[f.id]:x})}return d.ribbon.tabs.map(f=>f.id)}function Yo(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);se.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 Fy(e){const t=se.getState(),n=[],o=y=>x=>(n.push(`${y}: ${x instanceof Error?x.message:String(x)}`),null),[i,s,l]=await Promise.all([gi(e).catch(o(`the ${e} table's customizations`)),gi(null).catch(o("the application ribbon's customizations")),Sy().catch(y=>{t.logWarn("dataverse",`${y instanceof Error?y.message:String(y)} Labels are shown in English; publishing reads it again and stops if it still can't.`)})]),a=i?bi(i):[],c=s?bi(s):[],[d,u]=await Promise.all([By(e,[...a,...c]),My(c)]);if(i){const y=ur(d.ribbons,i,e,[...a,...c]);y.length>0&&t.logInfo("ribbon",`Loaded tab(s) ${y.join(", ")} from the table's unmanaged layer.`);const x=Jn(i);for(const b of Object.values(d.ribbons))Rs(b,x);Yo("RetrieveEntityRibbon",Jo(Object.values(d.ribbons),d,i,[Be]))}s&&(ur({Application:u.ribbon},s,null,c),Rs(u.ribbon,Jn(s)),Yo("RetrieveApplicationRibbon",Jo([u.ribbon],u,s)),Yo("RetrieveEntityRibbon",Jo(Object.values(d.ribbons),d,Ly(s,i))));const p=Pn([...d.locLabels,...u.locLabels]),f=l??1033;Py([...Object.values(d.ribbons),u.ribbon],p,f);const h=i?Ay(i,Object.values(d.ribbons),e,{locLabels:p,languageCode:f,otherHides:s?go(s).map(y=>y.location):[]}):[];return h.length>0&&t.logWarn("ribbon",`${h.length} element(s) of the table's unmanaged customizations aren't on the canvas — the ribbon doesn't return them (see "Orphaned customizations"): ${h.map(y=>`${y.id} at ${y.location}`).join(", ")}.`),{ribbons:{HomepageGrid:d.ribbons.HomepageGrid,SubGrid:d.ribbons.SubGrid,Form:d.ribbons.Form,Application:u.ribbon},commands:Pn([...d.commands,...u.commands]),displayRules:Pn([...d.displayRules,...u.displayRules]),enableRules:Pn([...d.enableRules,...u.enableRules]),locLabels:p,layers:{entity:i?no(i):null,application:s?no(s):null},baseLanguageCode:l,orphans:h,...n.length>0?{layerReadError:n.join("; ")}:{}}}const mr=window.dataverseAPI,pr="Active";function _y(e){if(!e||!e.includes("<"))return[];try{const t=new DOMParser().parseFromString(e,"application/xml");if(t.querySelector("parsererror"))return[];const n=new Set;return t.querySelectorAll("CustomAction").forEach(o=>{const s=o.querySelector("CommandUIDefinition")?.firstElementChild?.getAttribute("Id");s&&n.add(s)}),[...n]}catch{return[]}}async function qy(e){const t=se.getState(),n=new Map;if(!e||e==="{!EntityLogicalName}")return n;try{const o=e.replace(/'/g,"''"),s=((await mr.queryData(`ribboncustomizations?$select=ribboncustomizationid&$filter=entity eq '${o}'`)).value??[]).map(c=>c.ribboncustomizationid).filter(c=>!!c);if(s.length===0)return t.logInfo("provenance",`No RibbonCustomization for ${e} — buttons resolve via heuristic (OOB vs custom).`),n;const l=new Map,a=new Set;for(const c of s){const u=(await mr.queryData(`msdyn_componentlayers?$select=msdyn_componentjson,msdyn_changes,msdyn_solutionname,msdyn_publishername,msdyn_order&$filter=msdyn_componentid eq '${c}'&$orderby=msdyn_order asc`)).value??[];t.logInfo("provenance",`RibbonCustomization ${c}: ${u.length} solution layer(s).`);for(const p of u){const f=p.msdyn_componentjson||p.msdyn_changes||"",h=_y(f),y=(p.msdyn_solutionname??"")===pr;for(const x of h)y?a.add(x):l.has(x)||l.set(x,{origin:"managed",solutionName:p.msdyn_solutionname,publisherName:p.msdyn_publishername})}}for(const[c,d]of l)a.has(c)||n.set(c,d);for(const c of a)n.set(c,{origin:"unmanaged",solutionName:pr});t.logInfo("provenance",`Resolved solution-layer provenance for ${n.size} button(s) of ${e}.`)}catch(o){t.logWarn("provenance",`Solution-layer provenance unavailable for ${e} (${o instanceof Error?o.message:String(o)}); using heuristic. This is non-fatal.`)}return n}function Hy(){return window.dataverseAPI}async function Wy(){const e=Hy();se.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 se.getState().logWarn("dataverse","WhoAmI returned no user id."),{id:"",name:""};const i=(await e.retrieve("systemuser",n,["fullname"])).fullname?.trim(),s={id:n,name:i&&i.length>0?i:"Current User"};return se.getState().logInfo("dataverse",`Current user resolved: ${s.name}.`),s}function Gy(){L.useEffect(()=>{const e=ch();return e>0&&se.getState().logInfo("ribbon",`Discarded ${e} unsaved-changes draft(s) older than ${Ha} days, or saved by an earlier version of Command Bar Studio (they can't be restored correctly).`),uh()},[])}function Uy(){const e=xe(n=>n.saveFailed),t=xe(n=>n.lastSavedAt);return e?r.jsx(we,{intent:"error",layout:"multiline",style:{position:"absolute",top:0,left:0,right:0,zIndex:1e3},children:r.jsxs(Ce,{children:["Your latest changes can't be saved as a draft: the browser storage is full."," ",t?r.jsxs(r.Fragment,{children:["The last saved draft is from ",new Date(t).toLocaleString(),"; publish your changes, or the ones made since are lost when Command Bar Studio closes."]}):r.jsx(r.Fragment,{children:"Publish them, or they are lost when Command Bar Studio closes."})]})}):null}function Xy(){const e=ie(i=>i.connectionNotice),t=ie(i=>i.dismissConnectionNotice);if(!e)return null;const n=`${e.from.name||e.from.url} (${e.from.environment})`,o=`${e.to.name||e.to.url} (${e.to.environment})`;return r.jsxs(we,{intent:e.draftLost?"error":e.to.environment==="Production"?"warning":"info",layout:"multiline",role:"alert",style:{position:"absolute",top:0,left:0,right:0,zIndex:1e3},children:[r.jsxs(Ce,{children:[r.jsxs(wm,{children:["Connection changed to ",o]}),"The solution and table loaded from ",n," were closed; pick a solution to continue in ",o,"."," ",e.draftKept&&r.jsxs(r.Fragment,{children:["Your unpublished changes were kept as a draft: switch the tool back to"," ",n," and open the table to restore them."]}),e.draftLost&&r.jsx(r.Fragment,{children:"Your unpublished changes couldn't be saved as a draft (the browser storage is full) and are lost."})]}),r.jsx(Mt,{containerAction:r.jsx(J,{"aria-label":"Dismiss",appearance:"transparent",icon:r.jsx(po,{}),onClick:t})})]})}function Vy(){const e=xe(s=>s.pending),t=xe(s=>s.pendingBaselineChanged),n=xe(s=>s.restoreError),o=xe(s=>s.restoreDraft),i=xe(s=>s.discardDraft);return e?r.jsx(Xt,{open:!0,modalType:"alert",children:r.jsx(Vt,{style:{maxWidth:"520px"},children:r.jsxs(Jt,{children:[r.jsx(Kt,{children:"Unpublished changes"}),r.jsxs(Yt,{children:[r.jsxs(F,{block:!0,children:["You have unpublished changes to this table from a previous session (saved"," ",new Date(e.savedAt).toLocaleString(),"). Restore them on top of the ribbon as it is now, or discard them?"]}),t&&r.jsx(we,{intent:"warning",layout:"multiline",style:{marginTop:"12px"},children:r.jsx(Ce,{children:"The table's ribbon has changed since then (published from another session, or by someone else): review the publish plan before publishing."})}),n&&r.jsx(we,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:r.jsxs(Ce,{children:["These changes couldn't be restored (",n,"). Discard them to continue; the details are in the runtime log."]})})]}),r.jsxs(Zt,{children:[r.jsx(J,{appearance:"secondary",onClick:i,children:"Discard"}),r.jsx(J,{appearance:"primary",disabled:!!n,onClick:()=>o(),children:"Restore"})]})]})})}):null}function Ky(){const e=xe(d=>d.pendingSwitch),t=xe(d=>d.pending!==null),n=xe(d=>d.saveFailed),o=xe(d=>d.resolveSwitch),i=ie(d=>d.activeEntity),s=ie(d=>d.activeSolution);if(!e)return null;const l=i?.displayName||i?.logicalName||"this table",a=e.kind==="entity"?`table ${e.entity.displayName||e.entity.logicalName}`:`solution ${e.solution.friendlyName||e.solution.uniqueName}`,c=s?.friendlyName||s?.uniqueName||"this solution";return r.jsx(Xt,{open:!0,modalType:"alert",onOpenChange:(d,u)=>!u.open&&o("cancel"),children:r.jsx(Vt,{style:{maxWidth:"520px"},children:r.jsxs(Jt,{children:[r.jsx(Kt,{children:"Unpublished changes"}),r.jsxs(Yt,{children:[r.jsxs(F,{block:!0,children:[l," has changes that aren't published. Switch to ",a,"?"]}),r.jsx(F,{block:!0,style:{marginTop:"8px"},children:t?r.jsxs(r.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."]}):r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Keep as draft"})," saves them on this computer: they are offered again when you open ",l," ","in ",c,". ",r.jsx("strong",{children:"Discard"})," deletes them."]})}),n&&!t&&r.jsx(we,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:r.jsx(Ce,{children:"The changes can't be saved as a draft: the browser storage is full. Publish them first, or discard them to switch."})})]}),r.jsxs(Zt,{children:[r.jsx(J,{appearance:"secondary",onClick:()=>o("cancel"),children:"Cancel"}),r.jsxs(J,{appearance:"secondary",onClick:()=>o("discard"),children:["Discard",t?" and switch":""]}),!t&&r.jsx(J,{appearance:"primary",disabled:n,onClick:()=>o("keep"),children:"Keep as draft"})]})]})})})}const Jy=me({leftPaneTabs:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},tabList:{flexShrink:0,borderBottom:`1px solid ${m.colorNeutralStroke2}`},tabContent:{flex:1,overflow:"hidden"}});function Yy(){const e=Jy(),[t,n]=L.useState("tables");return r.jsxs("div",{className:e.leftPaneTabs,children:[r.jsxs(zi,{className:e.tabList,selectedValue:t,onTabSelect:(o,i)=>n(i.value),size:"small",children:[r.jsx(Ke,{value:"tables",children:"Tables"}),r.jsx(Ke,{value:"elements",children:"Solution"})]}),r.jsx("div",{className:e.tabContent,children:t==="tables"?r.jsx(uy,{}):r.jsx(hy,{})})]})}function Zy(){const e=ie(R=>R.setSolutions),t=ie(R=>R.setEntities),n=ie(R=>R.setCurrentUser),o=ie(R=>R.setSolutionEntityIds),i=ie(R=>R.setSolutionRibbonComponentIds),s=ie(R=>R.activeSolution),l=ie(R=>R.activeEntity),a=ie(R=>R.connectionVersion),c=D(R=>R.loadWorkspace),d=te(R=>R.setTabId),u=ee(R=>R.themeMode),p=se(R=>R.logInfo),f=se(R=>R.logWarn),h=se(R=>R.logError);Gy(),Og();const[y,x]=L.useState("idle"),[b,g]=L.useState(null),[S,w]=L.useState(null),[v,I]=L.useState(0);L.useEffect(()=>{p("runtime","Loading solutions and current user...");let R=!1;return gy().then(k=>{R||(e(k),p("runtime",`Loaded ${k.length} solution(s). Pick one to load its tables.`))}).catch(k=>{R||h("runtime",`Failed to load solutions: ${k instanceof Error?k.message:String(k)}`)}),Wy().then(k=>{R||!k.id||(n(k.id,k.name),p("runtime",`Current user: ${k.name}.`))}).catch(k=>{f("runtime",`Failed to resolve current user: ${k instanceof Error?k.message:String(k)}`)}),()=>{R=!0}},[e,n,p,f,h,a]),L.useEffect(()=>{if(!s){o(null),i(null),t([]);return}let R=!1;return(async()=>{try{const[k,N]=await Promise.all([by(s.id),yy(s.id)]);if(R)return;if(o(k),i(N),k.length===0){t([]);return}const W=await vy(k);if(R)return;t(W)}catch(k){if(R)return;h("runtime",`Failed to load solution tables: ${k instanceof Error?k.message:String(k)}`),o([]),i([]),t([])}})(),()=>{R=!0}},[s,t,o,i,h]),L.useEffect(()=>{if(xe.getState().beginLoad(),!l?.logicalName){x("idle"),g(null),w(null);return}let R=!1;const k=mh(l.logicalName);return x("loading"),g(null),w(null),p("ribbon",`Loading ribbon workspace for ${l.logicalName}...`),Promise.all([Fy(l.logicalName),qy(l.logicalName).catch(()=>new Map)]).then(([N,W])=>{if(R)return;of(N.ribbons,W);const X=[],O=new Set;for(const G of Object.values(N.ribbons))for(const K of G.tabs)for(const Q of K.groups)for(const P of $e(Q))P.origin==="managed"&&!O.has(P.id)&&(O.add(P.id),X.push({elementId:P.id,elementKind:"button",solutions:[{solutionId:"",solutionName:P.solutionName??"Managed Solution",publisher:P.publisherName??"",managed:!0,wins:!0,importedOn:void 0}]}));D.getState().setConflicts(X),c({ribbons:N.ribbons,commands:N.commands,displayRules:N.displayRules,enableRules:N.enableRules,locLabels:N.locLabels,layers:N.layers,baseLanguageCode:N.baseLanguageCode,baseLanguageUnknown:N.baseLanguageCode===void 0,labelsUnknown:N.layerReadError!==void 0,orphans:{entity:Dy(N.orphans??[],Ny(ie.getState().connectionUrl,l.logicalName))}});const{location:T,tabId:z}=te.getState(),$=N.ribbons[T]?.tabs??[];if(!($.some(G=>G.id===z)&&!Ro(z))){const G=hn($);G&&d(G)}xe.getState().workspaceLoaded(k),w(N.layerReadError??null),N.layerReadError&&f("ribbon",`Unmanaged layer not read: ${N.layerReadError}`),x("idle"),p("ribbon",`Ribbon workspace loaded for ${l.logicalName}.`)}).catch(N=>{if(R)return;const W=N instanceof Error?N.message:"Failed to load ribbon";x("error"),g(W),h("ribbon",`Ribbon load failed for ${l.logicalName}: ${W}`)}),()=>{R=!0}},[l?.logicalName,c,v,d,p,f,h]);function A(){I(R=>R+1)}return r.jsxs(Cm,{theme:u==="dark"?Im:Rm,children:[r.jsxs(Wh,{leftPane:r.jsx(Yy,{}),rightPane:r.jsx(sy,{}),bottomPanel:r.jsx(cy,{}),children:[r.jsx(Uy,{}),r.jsx(Xy,{}),r.jsx(Tb,{isLoadingRibbon:y==="loading",ribbonLoadError:b,layerReadError:S,onRetryRibbonLoad:A})]}),r.jsx(Vy,{}),r.jsx(Ky,{})]})}const Qy=5e3,fr=3e4,Ll="1.2.7";function hr(e,t,n){let o;return Promise.race([e,new Promise((i,s)=>{o=setTimeout(()=>s(new Error(n)),t)})]).finally(()=>clearTimeout(o))}async function ex(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 ${Ll} or later.`);const i=[];let s="light";try{const a=t.utils?.getCurrentTheme;if(typeof a!="function")throw new Error("the host has no theme API");s=await hr(a(),Qy,"the host didn't answer")==="dark"?"dark":"light"}catch(a){i.push(`Couldn't read the host theme (${Fl(a)}); using the light theme.`)}const l=await hr(o(),fr,`Power Platform ToolBox didn't return the active connection within ${fr/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:s,warnings:i}}function Pl(e,t,n="Command Bar Studio couldn't start"){const o=e.ownerDocument,i=(c,d)=>{const u=o.createElement(c);return d&&(u.textContent=d),u},s=i("div");s.setAttribute("role","alert"),s.style.cssText="font-family: 'Segoe UI', system-ui, sans-serif; padding: 24px; max-width: 720px; line-height: 1.5;",s.append(i("h1",n));const l=i("p",Fl(t));l.style.fontWeight="600",s.append(l);const a=i("ul");for(const c of["Close the Command Bar Studio tab and open the tool again.",`Use Power Platform ToolBox ${Ll} 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."])a.append(i("li",c));s.append(a),e.replaceChildren(s)}function Fl(e){return e instanceof Error?e.message:String(e)}class tx extends L.Component{state={error:void 0};box=L.createRef();static getDerivedStateFromError(t){return{error:t??new Error("Unknown error")}}componentDidCatch(t,n){console.error("[CBS RootErrorBoundary]",t,n),se.getState().logError("app",t instanceof Error?t.message:String(t))}componentDidMount(){this.componentDidUpdate()}componentDidUpdate(){this.state.error!==void 0&&this.box.current&&Pl(this.box.current,this.state.error,"Command Bar Studio stopped working")}render(){return this.state.error===void 0?this.props.children:r.jsx("div",{ref:this.box})}}function Tt(){const e=window.dataverseAPI;if(!e)throw new Error("dataverseAPI is not available in the current runtime");return e}const _l={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 ql(e){return _l[e]??"xml"}async function nx(e,t){let n="webresourceset?$select=webresourceid,name,displayname,description,webresourcetype,modifiedon,ismanaged&$orderby=name asc";if(t!==void 0){const i=Object.entries(_l).find(([,s])=>s===t)?.[0];i&&(n+=`&$filter=webresourcetype eq ${i}`)}return(await e.queryData(n)).value.map(i=>{const s=i;return{id:String(s.webresourceid??""),name:String(s.name??""),displayName:s.displayname?String(s.displayname):void 0,description:s.description?String(s.description):void 0,webResourceType:ql(Number(s.webresourcetype??3)),modifiedOn:s.modifiedon?String(s.modifiedon):void 0,isCustom:s.ismanaged===!1}})}async function ox(e,t){const n=await e.retrieve("webresource",t,["content"]);return n.content?String(n.content):""}const Hl=61;async function Wl(e,t,n,o=ho){await o("Adding the web resource to the solution"),await e.execute({operationName:"AddSolutionComponent",operationType:"action",parameters:{ComponentId:t,ComponentType:Hl,SolutionUniqueName:n,AddRequiredComponents:!1}})}class ix extends Error{constructor(t){super(`Web resource ${t} already exists; it was left as it is.`),this.name="WebResourceSaveCancelled"}}async function sx(e,t,n,o,i={}){const s=i.guard??Um(),{displayName:l,solutionUniqueName:a,onExisting:c}=i;let d=i.keepExisting??!1;const u=await e.queryData(`webresourceset?$select=webresourceid,ismanaged&$filter=name eq '${t.replace(/'/g,"''")}'&$top=1`),p={name:t,content:n,webresourcetype:o,...l?{displayname:l}:{}};let f;if(u.value.length>0){const h=u.value[0],y=String(h.webresourceid??"");if(!d&&c){const x=h.ismanaged===!0,b=await c({id:y,name:t,managed:x});if(b==="cancel")throw new ix(t);if(b==="replace"&&x)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=b==="keep"}d||(await s("Saving the web resource"),await e.update("webresource",y,p)),f={id:y,created:!1,updated:!d}}else{await s("Saving the web resource");const h=await e.create("webresource",p);f={id:String(h.id??""),created:!0,updated:!1}}if(a&&f.id){try{await Wl(e,f.id,a,s)}catch(h){throw new Error(`Web resource ${t} was saved but could not be added to solution ${a}: ${h instanceof Error?h.message:String(h)}`)}f.solutionUniqueName=a}return f}const gr=40,br=(e,t)=>Array.from({length:Math.ceil(e.length/t)},(n,o)=>e.slice(o*t,(o+1)*t)),rx=e=>`'${e.replace(/'/g,"''").replace(/[^A-Za-z0-9/._\-'~]/gu,t=>encodeURIComponent(t))}'`,yr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function ax(e,t,n){const o=t.map(c=>c.split(/[?#]/)[0].trim()).filter(Boolean),i=o.filter((c,d)=>o.findIndex(u=>u.toLowerCase()===c.toLowerCase())===d),s={};for(const c of i)s[c.toLowerCase()]={exists:!1,inSolution:!1};if(i.length===0)return s;const l=new Map;for(const c of br(i,gr)){const d=c.map(p=>`name eq ${rx(p)}`).join(" or "),u=await e.queryData(`webresourceset?$select=webresourceid,name,ismanaged&$filter=${d}`);for(const p of u.value??[]){const f=p,h=String(f.name??"").toLowerCase();if(!(h in s))continue;s[h]={exists:!0,inSolution:!1,managed:f.ismanaged===!0};const y=String(f.webresourceid??"").toLowerCase();yr.test(y)&&l.set(y,h)}}const a=n?.replace(/[{}]/g,"");if(a&&yr.test(a)&&l.size>0)for(const c of br([...l.keys()],gr)){const d=c.map(p=>`objectid eq ${p}`).join(" or "),u=await e.queryData(`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${a} and componenttype eq ${Hl} and (${d})`);for(const p of u.value??[]){const f=l.get(String(p.objectid??"").toLowerCase());f&&(s[f].inSolution=!0)}}return s}async function Xx(e,t){return ax(Tt(),e,t)}async function Vx(e){return nx(Tt(),e)}async function Kx(e){return ox(Tt(),e)}async function lx(e){const t=Tt(),n=e.replace(/'/g,"''"),o=await t.queryData(`webresourceset?$select=webresourceid,name,displayname,webresourcetype,ismanaged&$filter=name eq '${n}'&$top=1`);if(!o.value?.length)return null;const i=o.value[0];return{id:String(i.webresourceid??""),name:String(i.name??""),displayName:i.displayname?String(i.displayname):void 0,webResourceType:ql(Number(i.webresourcetype??3)),isCustom:i.ismanaged===!1}}async function cx(e,t,n,o={}){const i=ie.getState().activeSolution,s=o.solutionUniqueName??(i&&!i.isManaged?i.uniqueName:void 0),l=await sx(Tt(),e,t,n,{...o,solutionUniqueName:s});if(!s){const a=i?`the active solution ${i.uniqueName} is managed`:"no solution is selected";l.solutionWarning=`Web resource ${e} was saved but not added to any solution because ${a}. It is only in the Default solution — select an unmanaged solution and save it again so it travels with your customizations.`,se.getState().logWarn("webresource",l.solutionWarning)}return l}async function Jx(e,t,n=ho){const o=t??await lx(e);if(!o?.id)throw new Error(`No web resource named ${e} exists in this environment.`);const i=o.id;if(o.isCustom===!1){const 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 se.getState().logWarn("webresource",l),{solutionWarning:l}}const s=ie.getState().activeSolution;if(!s||s.isManaged){const l=s?`the active solution ${s.uniqueName} is managed`:"no solution is selected",a=`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 se.getState().logWarn("webresource",a),{solutionWarning:a}}return await Wl(Tt(),i,s.uniqueName,n),{solutionUniqueName:s.uniqueName}}async function dx(e,t=ho){const n=Tt(),o=`<importexportxml><webresources><webresource>${e}</webresource></webresources></importexportxml>`;await t("Publishing the web resource"),await n.execute({operationName:"PublishXml",operationType:"action",parameters:{ParameterXml:o}})}function ux(e){return e.replace(/([A-Z])/g,(t,n,o)=>(o>0?"_":"")+t.toLowerCase())}function mx(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 Gl(e,t="regular"){return`${ux(e)}${t==="filled"?".filled":""}.svg`}function px(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/${Gl(t,n)}`}const fx=11,hx=2*6e4,xr={save:cx,publish:dx},Ul=new Set;function gx(){Ul.clear()}async function Yx(e,t,n,o,i={}){const s=i.save??xr.save,l=i.publish??xr.publish,a=i.published??Ul,c=px(n,e,t),d=await o(e,20,t);if(!d)throw new Error(`Could not convert the Fluent icon "${e}" to SVG`);const u=await s(c,mx(d),fx,{displayName:`${Gl(e,t)} (CBS icon)`,keepExisting:!0,guard:i.guard}),p={name:c,id:u.id,created:u.created};if(!a.has(u.id))try{await jy(`Publishing icon web resource ${c}`,()=>l(u.id,i.guard),{timeoutMs:hx,...i.busy}),a.add(u.id)}catch(f){p.publishError=f instanceof Error?f.message:String(f)}return p}const bx=["commandEditorOpen","ruleEditorOpen","xmlDrawerOpen","iconPickerOpen","localizationEditorOpen","newGroupOpen","importXmlOpen","conflictDrawerOpen","webResourceBrowserOpen","urlComposerOpen","diffViewerOpen","tabDisplayRulesOpen","scalingEditorOpen","newTabOpen"];function yx(e){if(!e)return"none";const t=ie.getState(),n=se.getState();if(Xn(e)===Xn({id:t.connectionId,url:t.connectionUrl}))return e.name===t.connectionName&&e.environment===t.environment?"none":(t.setConnection(e.url,e.name,e.environment,e.id),n.logInfo("startup",`Connection details updated: ${e.name} (${e.environment}).`),"details");const i=`${t.connectionName||t.connectionUrl} (${t.environment})`,s=`${e.name} (${e.environment})`,{hadChanges:l,kept:a}=xe.getState().releaseForConnectionChange();D.getState().resetWorkspace(),te.getState().clearSelection(),be.getState().reset(),gx(),zg(),Di.clear(),t.switchConnection(e,{draftKept:l&&a,draftLost:l&&!a});try{ee.setState(Object.fromEntries(bx.map(c=>[c,!1])))}catch(c){n.logWarn("startup",`Couldn't close the open panels after the connection change: ${c instanceof Error?c.message:String(c)}`)}return n.logWarn("startup",`The tool's connection changed from ${i} to ${s}. The loaded solution and table were closed.`),l&&a&&n.logInfo("startup",`The unpublished changes were kept as a draft for ${i}.`),l&&!a&&n.logError("startup",`The unpublished changes on ${i} couldn't be saved as a draft (browser storage full) and are lost.`),"switched"}async function xx(){const e=se.getState().logInfo,t=window,n=t.toolboxAPI,{connection:o,theme:i,warnings:s}=await ex({toolboxAPI:n,dataverseAPI:t.dataverseAPI});e("startup","Connected to PPTB host runtime.");for(const f of s)se.getState().logWarn("startup",f);e("startup",`Host theme loaded: ${i}.`);const{setConnection:l}=ie.getState(),{setThemeMode:a}=ee.getState(),c=await Bi().catch(()=>null)??o;l(c.url,c.name,c.environment,c.id),a(i),e("startup",`Connected to ${c.name} (${c.environment}).`),Gm(f=>yx(f));const d=()=>{n.utils.getCurrentTheme().then(f=>{ee.getState().setThemeMode(f==="dark"?"dark":"light")}).catch(f=>{se.getState().logWarn("startup",`Theme refresh failed: ${f instanceof Error?f.message:String(f)}`)})};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&d()}),n.events?.on((f,h)=>{h?.event==="settings:updated"&&d()});const u=document.getElementById("root");if(!u)throw new Error("No #root element found");Fm.createRoot(u).render(r.jsx(L.StrictMode,{children:r.jsx(tx,{children:r.jsx(Zy,{})})}))}xx().catch(e=>{se.getState().logError("startup",e instanceof Error?e.message:String(e)),console.error(e);const t=document.getElementById("root")??document.body;Pl(t,e)});export{Px as $,sa as A,Li as B,Mb as C,Vr as D,fh as E,Tx as F,kx as G,Pi as H,Ax as I,jx as J,Nx as K,Rx as L,Ty as M,ae as N,se as O,Sy as P,Gx as Q,Ox as R,Lx as S,so as T,lp as U,jy as V,Cy as W,$x as X,ie as Y,Bi as Z,Ja as _,ee as a,Fx as a0,_x as a1,Xx as a2,Ux as a3,Bx as a4,Be as a5,Ta as a6,la as a7,Is as a8,Ro as a9,ds as aA,Rn as aB,ls as aC,os as aD,zx as aE,te as aa,$a as ab,on as ac,Ts as ad,Mx as ae,Za as af,Io as ag,Ze as ah,Gr as ai,ci as aj,eo as ak,ue as al,xe as am,en as an,Dx as ao,yo as ap,xo as aq,vo as ar,Nt as as,ux as at,px as au,ix as av,Yx as aw,Hx as ax,Jx as ay,cs as az,Qa as b,ly as c,$e as d,xn as e,lx as f,Ex as g,Kx as h,qx as i,cx as j,Um as k,Vx as l,Qt as m,Mi as n,tf as o,Ix as p,Yp as q,Qp as r,Wx as s,Zp as t,D as u,ma as v,Di as w,gi as x,Jn as y,ia as z};