@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.
- package/CHANGELOG.md +48 -0
- package/README.md +7 -0
- package/dist/assets/BulkPublishModal-dGiT6nNQ.js +36 -0
- package/dist/assets/{CommandEditorPanel-1tDOtoTt.js → CommandEditorPanel-BfcpfNps.js} +1 -1
- package/dist/assets/CommandPalette-C4NOIuA3.js +1 -0
- package/dist/assets/{ConflictDrawer-CjObt6DP.js → ConflictDrawer-CW1NLdAD.js} +1 -1
- package/dist/assets/{DiffViewer-Dfu_9b4v.js → DiffViewer-R0g0dxLc.js} +1 -1
- package/dist/assets/{HideInsteadOfDeleteModal-C64qc-fw.js → HideInsteadOfDeleteModal-DbfHSKmm.js} +1 -1
- package/dist/assets/{IconPickerModal-D6hQ_Aqx.js → IconPickerModal-B1AgGWq0.js} +1 -1
- package/dist/assets/ImportXmlModal-DImDI43_.js +1 -0
- package/dist/assets/LocalizationEditor-CeAgqq85.js +1 -0
- package/dist/assets/{MonacoEditor-CBUJNFgC.js → MonacoEditor-BRCY30rO.js} +1 -1
- package/dist/assets/{NewButtonModal-B_ugATAS.js → NewButtonModal-DqdSshXe.js} +1 -1
- package/dist/assets/{NewGroupModal-Dvg8CSJr.js → NewGroupModal-VysrEsbU.js} +1 -1
- package/dist/assets/{NewTabModal-CjMNMXb5.js → NewTabModal-ChEmOjmh.js} +1 -1
- package/dist/assets/{RuleEditorPanel-B5or3M9d.js → RuleEditorPanel-C26e1gMH.js} +1 -1
- package/dist/assets/{ScalingEditorPanel-CzQtkicj.js → ScalingEditorPanel-f2Rmk9AG.js} +1 -1
- package/dist/assets/{TabDisplayRulesPanel-BqzSpzqp.js → TabDisplayRulesPanel-DR-c2-Km.js} +1 -1
- package/dist/assets/{UrlComposerModal-BDP57HQn.js → UrlComposerModal-DFwPOYL1.js} +1 -1
- package/dist/assets/{WebResourceBrowser-BK_G_Q_c.js → WebResourceBrowser-D2RMaFeZ.js} +1 -1
- package/dist/assets/XmlDrawer-DXyRtGs1.js +2 -0
- package/dist/assets/index-CKs2IGe0.js +136 -0
- package/dist/assets/{useReplaceWebResourceConfirm-Dx7RdpEN.js → useReplaceWebResourceConfirm-C4vg9hxg.js} +1 -1
- package/dist/assets/xmlValidator-TOuV4jko.js +3 -0
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/BulkPublishModal-CF7sSmBT.js +0 -29
- package/dist/assets/CommandPalette-BBM1PJH0.js +0 -1
- package/dist/assets/ImportXmlModal-DXwUce5n.js +0 -1
- package/dist/assets/LocalizationEditor-DXqbD2ZN.js +0 -1
- package/dist/assets/XmlDrawer-C4lJ7_MF.js +0 -2
- package/dist/assets/index-CL8TmfXp.js +0 -139
- package/dist/assets/xmlValidator-DvDaU5OO.js +0 -3
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./XmlDrawer-C4lJ7_MF.js","./fluent-icons-DUgjkNjy.js","./monaco-BIO15LCS.js","./monaco-DdLsZAcA.css","./MonacoEditor-CBUJNFgC.js","./fluent-ui-Dde22_ZN.js","./dnd-BmqIZ1-i.js","./CommandEditorPanel-1tDOtoTt.js","./CrmParameterEditor-CQD0gNNH.js","./crmParameters-rgfZhhzN.js","./RuleEditorPanel-B5or3M9d.js","./ruleKinds-B9hACGaq.js","./BulkPublishModal-CF7sSmBT.js","./xmlValidator-DvDaU5OO.js","./NewButtonModal-B_ugATAS.js","./NewGroupModal-Dvg8CSJr.js","./NewTabModal-CjMNMXb5.js","./ImportXmlModal-DXwUce5n.js","./CommandPalette-BBM1PJH0.js","./LocalizationEditor-DXqbD2ZN.js","./IconPickerModal-D6hQ_Aqx.js","./useReplaceWebResourceConfirm-Dx7RdpEN.js","./TabDisplayRulesPanel-BqzSpzqp.js","./ScalingEditorPanel-CzQtkicj.js","./ConflictDrawer-CjObt6DP.js","./WebResourceBrowser-BK_G_Q_c.js","./UrlComposerModal-BDP57HQn.js","./DiffViewer-Dfu_9b4v.js","./HideInsteadOfDeleteModal-C64qc-fw.js","./server.browser-xEJRzS2D.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{y as s,z as le,i as gt,B as ql,E as ft,F as hr,G as gr,H as br,J as yr,Q as xr,K as vr,L as Hl,M as Ct,N as Gt,O as Sr,P as Wl,U as wr,V as Gl,X as Cr,Y as Ul,Z as Xl,$ as Vl,a0 as Kl,a1 as Jl,a2 as Yl,a3 as Zl,a4 as Ql,a5 as ec,a6 as tc,a7 as nc,a8 as oc,a9 as ic,aa as sc,ab as rc,ac,ad as lc,ae as cc,af as dc,ag as uc,ah as mc,ai as pc,aj as fc,ak as hc,al as gc,am as bc,an as yc,ao as xc,ap as vc,aq as Sc,ar as wc,as as Cc,at as Ic,au as Rc,av as jc,aw as $c,ax as Nc,ay as Tc,az as kc,aA as Ac,aB as Dc,aC as Ec,aD as Ir,aE as Oc,aF as zc,aG as Bc,aH as Mc,aI as Lc,aJ as Pc,aK as Fc,aL as _c,aM as qc,aN as Hc,aO as Wc,aP as Gc,aQ as Uc,aR as Ye,aS as Xc,aT as Vc,aU as Kc,aV as Jc,aW as Yc,aX as Zc,aY as Qc,aZ as ed,a_ as td,a$ as nd,b0 as od,b1 as id,b2 as sd,b3 as rd,b4 as ad,b5 as ld,b6 as cd,b7 as dd,b8 as ud,b9 as md,ba as Rr,bb as pd,bc as fd,bd as hd,be as gd,bf as bd,bg as yd,bh as xd,bi as vd,bj as Sd,bk as wd,bl as Cd,bm as Id,bn as Rd,bo as so,bp as jd,bq as $d,br as Nd,bs as Td,bt as kd,bu as Ad,bv as Dd,bw as Ed,bx as Od,by as zd,bz as Bd,bA as Md,bB as Ld,bC as Pd,bD as Fd,bE as _d,bF as qd,bG as jr,bH as Hd,bI as Wd,bJ as Gd,bK as Ud,bL as Xd,bM as It,bN as Vd,bO as Kd,h as ro,g as Jd,bP as Yd,w as Zd,x as Qd,bQ as eu,bR as tu,bS as nu,bT as ou,bU as iu,bV as su,bW as ru,bX as $r,bY as au,bZ as lu,A as cu,b_ as du,s as uu,b$ as mu,c0 as pu,c1 as fu,c2 as hu,c3 as gu,c4 as bu,c5 as yu,c6 as xu,c7 as vu,c8 as Su,c9 as wu,ca as Cu,cb as Iu,cc as Ru,cd as ju,ce as $u,cf as Nu,cg as Tu,ch as ku,ci as Au,cj as fn,ck as Du,cl as Eu,cm as ao,cn as Ou,co as Ft,cp as zu,cq as Ae,cr as _t,cs as qn,ct as Nr,cu as Tr,cv as cs,m as qt,cw as Bu,cx as Mu,cy as Lu,cz as Pu}from"./fluent-icons-DUgjkNjy.js";import{l as Fu,m as _u,R as Ue,_ as $e,a as M}from"./monaco-BIO15LCS.js";import{a as qu,T as Ne,t as m,b as P,B as ae,u as Hu,P as Wu,c as Gu,d as K,e as Uu,F as Ee,C as Xu,S as dt,O as Vu,M as Ce,f as Ie,g as hn,h as me,D as Ut,i as Xt,j as Vt,k as Kt,l as Jt,m as Yt,I as qe,n as Xo,o as Vo,p as Ko,q as Jo,s as pt,v as Ku,w as Ju,x as Yu,y as Zu,z as kr,A as Qu,E as em,G as tm,H as nm,J as om,K as im,L as sm,N as rm,Q as am,R as lm,U as cm,V as dm,W as um,X as mm,Y as ds,Z as kt,_ as pm,$ as At,a0 as rt,a1 as Ni,a2 as Ar,a3 as Dr,a4 as Be,a5 as Ti,a6 as fm,a7 as Ve,a8 as hm,a9 as wo,aa as Rt,ab as Yo,ac as ki,ad as Ke,ae as gm,af as bm,ag as ym,ah as xm}from"./fluent-ui-Dde22_ZN.js";import{u as vm,a as Er,b as Hn,K as Or,P as zr,D as Br,c as Sm,d as wm,e as Mr,f as Cm,S as Im,h as Rm,g as jm,C as $m}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 r of i)if(r.type==="childList")for(const l of r.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&o(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const r={};return i.integrity&&(r.integrity=i.integrity),i.referrerPolicy&&(r.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?r.credentials="include":i.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function o(i){if(i.ep)return;i.ep=!0;const r=n(i);fetch(i.href,r)}})();function Nm(e){return new Worker(""+new URL("editor.worker-D1TDBLlL.js",import.meta.url).href,{name:e?.name})}function Tm(e){return new Worker(""+new URL("json.worker-BggoxaER.js",import.meta.url).href,{name:e?.name})}function km(e){return new Worker(""+new URL("ts.worker-BrLZGe_E.js",import.meta.url).href,{name:e?.name})}function Am(e){return new Worker(""+new URL("css.worker-C_6RgliQ.js",import.meta.url).href,{name:e?.name})}function Dm(e){return new Worker(""+new URL("html.worker-CLyYFd_g.js",import.meta.url).href,{name:e?.name})}Fu.config({monaco:_u});self.MonacoEnvironment={getWorker(e,t){return t==="json"?new Tm:t==="typescript"||t==="javascript"?new km:t==="css"||t==="scss"||t==="less"?new Am:t==="html"||t==="handlebars"||t==="razor"?new Dm:new Nm}};var kn={},us;function Em(){if(us)return kn;us=1;var e=qu();return kn.createRoot=e.createRoot,kn.hydrateRoot=e.hydrateRoot,kn}var Om=Em();const ms=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(b=>b(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},zm=(e=>e?ms(e):ms),Bm=e=>e;function Mm(e,t=Bm){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 Lm=e=>{const t=zm(e),n=o=>Mm(t,o);return Object.assign(n,t),n},jt=(e=>Lm);function Wn(e){if(!e||!e.id&&!e.url)return"";const t=(e.url??"").trim().replace(/\/+$/,"").toLowerCase();return`${e.id??""}|${t}`}function Lr(){return window.toolboxAPI?.connections}async function Ai(){const e=Lr();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 Zo 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 un,Qo=0;function ps(e){const t=Wn(e);un!==void 0&&t!==un&&Qo++,un=t}async function lo(e){const t=Lr();if(un===void 0||!t?.getConnection&&!t?.getActiveConnection)return;let n;try{n=Wn(await Ai())}catch{throw new Zo(e)}if(n!==un)throw new Zo(e)}function Pm(e){const t=window.toolboxAPI?.events;if(typeof t?.on!="function")return()=>{};let n=0;const o=(i,r)=>{const l=r?.event;if(l!=="connection:updated"&&l!=="connection:created"&&l!=="connection:deleted")return;const a=++n;Ai().then(c=>{a===n&&e(c)}).catch(()=>{})};return t.on(o),()=>t.off?.(o)}function Fm(){const e=Qo;return async t=>{if(Qo!==e)throw new Zo(t);await lo(t)}}const ei=new Set;function _m(e){return ei.add(e),()=>ei.delete(e)}const ne=jt()((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,r=t().connectionId)=>{ps({id:r,url:n}),e({connectionId:r,connectionUrl:n,connectionName:o,environment:i})},switchConnection:(n,o)=>{const i=t();ps(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=>{$e(async()=>{const{useRuntimeLogStore:i}=await Promise.resolve().then(()=>Vm);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 ei)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})})),qm=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 b=l(f);if(!u(p,b)){const v=p;a(p=b,v)}},c?.fireImmediately&&a(p,p)}return i(d)}),e(t,n,o)},Hm=qm;function Wm(e,t){let n;try{n=e()}catch{return}return{getItem:i=>{var r;const l=c=>c===null?null:JSON.parse(c,void 0),a=(r=n.getItem(i))!=null?r:null;return a instanceof Promise?a.then(l):l(a)},setItem:(i,r)=>n.setItem(i,JSON.stringify(r,void 0)),removeItem:i=>n.removeItem(i)}}const ti=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(o){return ti(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return ti(o)(n)}}}},Gm=(e,t)=>(n,o,i)=>{let r={storage:Wm(()=>window.localStorage),partialize:h=>h,version:0,merge:(h,y)=>({...y,...h}),...t},l=!1,a=0;const c=new Set,d=new Set;let u=r.storage;if(!u)return e((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${r.name}', the given storage is currently unavailable.`),n(...h)},o,i);const p=()=>{const h=r.partialize({...o()});return u.setItem(r.name,{state:h,version:r.version})},f=i.setState;i.setState=(h,y)=>(f(h,y),p());const b=e((...h)=>(n(...h),p()),o,i);i.getInitialState=()=>b;let v;const x=()=>{var h,y;if(!u)return;const w=++a;l=!1,c.forEach(S=>{var C;return S((C=o())!=null?C:b)});const I=((y=r.onRehydrateStorage)==null?void 0:y.call(r,(h=o())!=null?h:b))||void 0;return ti(u.getItem.bind(u))(r.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==r.version){if(r.migrate){const C=r.migrate(S.state,S.version);return C instanceof Promise?C.then($=>[!0,$]):[!0,C]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var C;if(w!==a)return;const[$,R]=S;if(v=r.merge(R,(C=o())!=null?C:b),n(v,!0),$)return p()}).then(()=>{w===a&&(I?.(o(),void 0),v=o(),l=!0,d.forEach(S=>S(v)))}).catch(S=>{w===a&&I?.(void 0,S)})};return i.persist={setOptions:h=>{r={...r,...h},h.storage&&(u=h.storage)},clearStorage:()=>{++a,u?.removeItem(r.name)},getOptions:()=>r,rehydrate:()=>x(),hasHydrated:()=>l,onHydrate:h=>(c.add(h),()=>{c.delete(h)}),onFinishHydration:h=>(d.add(h),()=>{d.delete(h)})},r.skipHydration||x(),v||b},Um=Gm,Xm=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:"",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=>e({importXmlOpen:!0,importXmlSeed:typeof t=="string"?t:""}),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})}),Y=jt()(Um(Xm,{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})})),ie=jt()((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:[]})})),Vm=Object.freeze(Object.defineProperty({__proto__:null,useRuntimeLogStore:ie},Symbol.toStringTag,{value:"Module"})),Km=new Set(["Default","InvertResult","PropertyValue","ExpectedValue","TrackedInCrm","PassParams","AllowCustomRelationship","AllowSystemRelationship"]),fs=["EnableRules","DisplayRules","Actions"];function Jm(e,t){return Km.has(t)||e.tagName==="BoolParameter"&&t==="Value"}function Ym(e){const t=e.trim();return t==="1"?"true":t==="0"?"false":t}function Zm(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/"/g,""")}function Ln(e,t,n){const o=Array.from(e.attributes).map(l=>[l.name,Jm(e,l.name)?Ym(l.value):l.value]).sort(([l],[a])=>l<a?-1:l>a?1:0).map(([l,a])=>` ${l}="${Zm(a)}"`).join(""),i=[];let r=[];for(const l of Array.from(e.childNodes))if(l.nodeType===1)r.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(r.map(d=>[d.tagName,d])),a=r.filter(d=>!fs.includes(d.tagName)),c=fs.map(d=>{const u=l.get(d);return u?Ln(u,t,`${n} `):`${n} <${d}/>`});r=[],i.push(...c,...a.map(d=>Ln(d,t,`${n} `)))}for(const l of r)i.push(Ln(l,t,`${n} `));return i.length===0?`${n}<${e.tagName}${o}/>`:`${n}<${e.tagName}${o}>
|
|
3
|
-
${i.join(`
|
|
4
|
-
`)}
|
|
5
|
-
${n}</${e.tagName}>`}function Pr(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 Ht(e,t={}){const n=typeof e=="string"?Pr(e):e;return Ln(n,t,"")}function Qm(e,t,n={}){try{return Ht(e,n)===Ht(t,n)}catch{return!1}}const gn={button:"Button",flyout:"FlyoutAnchor",splitButton:"SplitButton",textBox:"TextBox",comboBox:"ComboBox",checkBox:"CheckBox",toggleButton:"ToggleButton",label:"Label",dropDown:"DropDown",mruSplitButton:"MRUSplitButton",spinner:"Spinner",galleryButton:"GalleryButton"},Fr=Object.fromEntries(Object.entries(gn).map(([e,t])=>[t,e])),ep=new Set(["toggleButton","label","dropDown","mruSplitButton","spinner","galleryButton"]);function Ze(e){return!!e&&ep.has(e)}const _r=["Command","QueryCommand","MenuCommand","PopulateQueryCommand","CommandMenuOpen","CommandMenuClose","CommandPreview","CommandPreviewRevert","CommandRevert"],qr=new RegExp(`\\s(?:${_r.join("|")})="([^"]+)"`,"g");function Hr(e){const t=new Set(e.commandId?[e.commandId]:[]);if(Ze(e.kind))for(const n of e.source?.xml?.matchAll(qr)??[])t.add(n[1]);return[...t]}function tp(e,t,n){const o=i=>i.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<");return e.replace(qr,(i,r)=>r===t||r===o(t)?i.replace(`"${r}"`,`"${o(n)}"`):i)}const Gn={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 Wr(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 Gr(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 Ur(e,t,n){const o=[],i=[],r=new Set([...t.maxSizes,...t.scales]),l=(f,b)=>{o.push({tabId:e,id:f.id,kind:f.kind,groupId:f.groupId,from:f.sequence,to:b}),r.add(b)},a=n.filter(f=>f.kind==="Scale"),c=[];for(const f of a)r.has(f.sequence)?c.push(f):r.add(f.sequence);for(const f of c)l(f,Math.max(0,...r)+1);const d=[...t.scales,...a.map(f=>o.find(b=>b.id===f.id&&b.kind==="Scale")?.to??f.sequence)],u=Wr(t.maxSizes,d),p=[];for(const f of n.filter(b=>b.kind==="MaxSize"))f.sequence<u.before&&!r.has(f.sequence)?r.add(f.sequence):p.push(f);for(const f of p){const b=Gr(u,r);b===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,b)}return{changes:o,problems:i}}function np(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 Zt(){return{customActions:new Map,templates:new Map,commandDefinitions:new Map,tabDisplayRules:new Map,displayRules:new Map,enableRules:new Map,locLabels:new Map}}const jn=()=>new XMLSerializer;function Xr(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 pe(e,t){return at(e,t)[0]}function Vr(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 gx(e){const t=Zt(),o=Xr(e).documentElement;if(o.tagName!=="RibbonDiffXml")throw new Error(`Expected <RibbonDiffXml> root, got <${o.tagName}>`);const i=jn();for(const a of Array.from(pe(o,"CustomActions")?.children??[])){const c=Vr(a);c&&t.customActions.set(c,i.serializeToString(a))}const r=pe(pe(o,"Templates"),"RibbonTemplates");for(const a of Array.from(r?.children??[])){const c=a.getAttribute("Id");c&&t.templates.set(c,i.serializeToString(a))}for(const a of at(pe(o,"CommandDefinitions"),"CommandDefinition")){const c=a.getAttribute("Id");c&&t.commandDefinitions.set(c,i.serializeToString(a))}const l=pe(o,"RuleDefinitions");for(const a of at(pe(l,"TabDisplayRules"),"TabDisplayRule")){const c=a.getAttribute("TabCommand");c&&t.tabDisplayRules.set(c,i.serializeToString(a))}for(const a of at(pe(l,"DisplayRules"),"DisplayRule")){const c=a.getAttribute("Id");c&&t.displayRules.set(c,i.serializeToString(a))}for(const a of at(pe(l,"EnableRules"),"EnableRule")){const c=a.getAttribute("Id");c&&t.enableRules.set(c,i.serializeToString(a))}for(const a of at(pe(o,"LocLabels"),"LocLabel")){const c=a.getAttribute("Id");c&&t.locLabels.set(c,i.serializeToString(a))}return t}function ge(e){return Xr(e).documentElement}function op(e){const t=Zt();for(const n of e.diffs){const o=n.rdx?.trim();if(!o)continue;const i=ge(o);switch(n.difftype){case 3:{const r=i.getAttribute("Id")??n.diffid;r&&t.locLabels.set(r,o);break}case 2:{const r=i.getAttribute("Id")??n.diffid;r&&t.templates.set(r,o);break}default:{const r=Vr(i);r&&t.customActions.set(r,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 r=i.getAttribute("TabCommand")??n.ruleid;r&&t.tabDisplayRules.set(r,o)}else if(n.ruletype===1||i.tagName==="EnableRule"){const r=i.getAttribute("Id")??n.ruleid;r&&t.enableRules.set(r,o)}else{const r=i.getAttribute("Id")??n.ruleid;r&&t.displayRules.set(r,o)}}return t}function Di(e,t){const n=Zt();for(const o of Object.keys(n)){for(const[i,r]of e[o])n[o].set(i,r);for(const[i,r]of t[o])n[o].set(i,r)}return n}function bx(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 ip(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 hs(e,t){const n=ge(t);if(e==="commandDefinitions")for(const o of Array.from(n.getElementsByTagName("JavaScriptFunction")))ip(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((r,l)=>Number(r.getAttribute("languagecode"))-Number(l.getAttribute("languagecode")));for(const r of i)o.appendChild(r)}return Ht(n,{normalizeCommands:e==="commandDefinitions"})}const Kr=(e,t,n)=>{try{return hs(e,t)===hs(e,n)}catch{return t===n}},gs=e=>Array.from(ge(e).getElementsByTagName("Title")).map(t=>`${t.getAttribute("languagecode")}=${t.getAttribute("description")??""}`);function sp(e,t,n){if(e!=="locLabels")return Kr(e,t,n);try{const o=new Set(gs(t)),i=gs(n);return i.length>0&&i.every(r=>o.has(r))}catch{return t===n}}function yx(e,t){const n=[];for(const o of Object.keys(t))for(const[i,r]of t[o]){const l=e[o].get(i);(l===void 0||!Kr(o,l,r))&&n.push(`${o}:${i}`)}return n}function xx(e,t,n={}){const o=[],i=[],r=[],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}`)&&!sp(a,d,u)&&r.push(`${a}:${c}`)}for(const c of t[a].keys())e[a].has(c)||i.push(`${a}:${c}`)}return{missing:o,unexpected:i,differing:r}}function vx(e){return Object.values(e).reduce((t,n)=>t+n.size,0)}function Co(e){const t=ge(e);return t.tagName!=="CustomAction"?null:pe(t,"CommandUIDefinition")?.firstElementChild??null}function Je(e){return!!e&&e.endsWith("._children")}const rp=new Set(["Menu","MenuSection","Controls"]);function ni(e){return e.tagName==="Tab"||e.tagName==="Group"?[]:Array.from(e.getElementsByTagName("*")).filter(t=>!rp.has(t.tagName)&&!!t.getAttribute("Id")&&t.parentElement?.tagName==="Controls")}const bn=e=>e?.tagName==="Tab"||e?.tagName==="Group",bs=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Jr(e){return Array.from(e.getElementsByTagName("Controls")).flatMap(t=>Array.from(t.children))}function Yr(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 Un(e){return bn(e)?Jr(e):ni(e)}function Xn(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=pe(o,"CommandUIDefinition")?.firstElementChild,r=i?.getAttribute("Id");if(r&&t.add(r),i)for(const l of Un(i)){const a=l.getAttribute("Id");a&&t.add(a)}}return t}function Zr(e,t){const n=new Map(e),o=jn(),i=t?new Set(t):void 0;for(let r=!0;r;){r=!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=pe(d,"CommandUIDefinition")?.firstElementChild;if(bn(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=pe(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[,b,v]=u,x=ge(n.get(f)),h=Yr(x,b);if(!h||h.tagName!==(v==="Controls"?"Group":"Tab"))continue;const y=x.ownerDocument;let w=pe(h,v);if(!w){w=y.createElement(v),w.setAttribute("Id",`${b}.${v}`);const $=v==="Scaling"?pe(h,"Groups"):void 0;h.insertBefore(w,$??null)}const I=y.importNode(p,!0),S=d.getAttribute("Sequence");!I.getAttribute("Sequence")&&S&&I.setAttribute("Sequence",S);const C=I.tagName==="MaxSize"?pe(w,"Scale"):void 0;w.insertBefore(I,C??null),n.set(f,o.serializeToString(x)),i?.add(f),n.delete(a),r=!0;break}}return n}function ap(e,t){const n=pe(e,"CommandUIDefinition")?.firstElementChild??null;return n?n.getAttribute("Id")===t?n:Un(n).find(o=>o.getAttribute("Id")===t)??null:null}function Qr(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=pe(o,"CommandUIDefinition")?.firstElementChild;if(!i||i.tagName!=="Tab"&&i.tagName!=="Group")continue;const r=i.getAttribute("Id");r&&t.add(r);for(const l of Array.from(i.getElementsByTagName("Group"))){const a=l.getAttribute("Id");a&&t.add(a)}}return t}function co(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 lp(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 _r){const i=n.getAttribute(o);i&&t.push(i)}return t}function ea(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 cp(e){return/^(Mscrm|Microsoft)\./.test(e)}function Ei(e,t){if(cp(e))return!0;for(const n of t)if(n===e)return!1;return!0}function dp(e){const t=e?.match(/^(.+)\.(?:Controls|Groups)\._children$/);return t?t[1]:null}function Fn(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 ys(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 up(e,t,n){const o=at(e,"Menu")[0],i=at(t,"Menu")[0];if(!o){for(const a of ni(t))n(a.getAttribute("Id")??"")&&a.parentNode?.removeChild(a);return Fn(t,e)}const r=o.cloneNode(!0),l=(a,c)=>[r,...Array.from(r.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){ys(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 ni(t)){const c=a.getAttribute("Id")??"";if(n(c))continue;const d=l(null,c);if(d){ys(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(r),t}const Io=/\$LocLabels:([^"'\s]+)/g,mp=/<(EnableRule|DisplayRule)\b[^>]*?\sId="([^"]+)"/g;function Sx(e,t,n={}){const o=new Set(n.editedCommandIds??[]),i=new Set(n.editedEnableRuleIds??[]),r=new Set(n.editedDisplayRuleIds??[]),l=new Set(n.deletedControlIds??[]),a=new Set(n.unhiddenControlIds??[]),c=new Set(n.retainedCommandIds??[]),d=jn(),u=Di(e,Zt()),p=new Map,f=new Map,b=[];for(const[D,L]of e.customActions){const j=Co(L),B=ge(L);if(B.tagName!=="CustomAction")continue;const N=B.getAttribute("Location");if(j?.getAttribute("Id")&&Je(N)){p.set(j.getAttribute("Id"),D);for(const W of Un(j)){const U=W.getAttribute("Id");U&&b.push([U,D])}}else N&&f.set(N,D)}for(const[D,L]of b)p.has(D)||p.set(D,L);const v=(D,L)=>{const j=u.customActions.get(D);if(!j)return{ca:null,el:null,nested:!1};const B=ge(j),N=ap(B,L);return{ca:B,el:N,nested:!!N&&N.parentElement?.tagName!=="CommandUIDefinition"}},x=new Set;for(const[D,L]of t.customActions){const j=ge(L),B=Co(L),N=B?.getAttribute("Id")??null,W=N?p.get(N):void 0,U=j.tagName==="CustomAction"&&Je(j.getAttribute("Location"));U&&N&&x.add(N);const X=B?.tagName==="Tab"||B?.tagName==="Group";if(U&&X)for(const G of Jr(B)){const g=G.getAttribute("Id");if(!g)continue;x.add(g);const k=p.get(g),A=k?v(k,g):null;!k||!A?.ca||!A.el||(A.nested?(A.el.parentNode.removeChild(A.el),u.customActions.set(k,d.serializeToString(A.ca))):u.customActions.delete(k))}const Q=j.tagName==="CustomAction"&&B&&N&&W&&!(U&&X),q=Q?v(W,N):null;if(Q&&q?.ca&&q.el&&q.nested){const{ca:G,el:g}=q;if(U)g.parentNode.removeChild(g),u.customActions.set(D,L);else{const k=Fn(G.ownerDocument.importNode(B,!0),g);g.parentNode.replaceChild(k,g)}u.customActions.set(W,d.serializeToString(G));continue}if(Q&&q?.ca&&q.el){const{ca:G,el:g,nested:k}=q;if(U&&k){g.parentNode.removeChild(g),u.customActions.set(W,d.serializeToString(G)),u.customActions.set(D,L);continue}let A=G.ownerDocument.importNode(B,!0);if(U?A=up(g,A,te=>{const de=p.get(te);return!!de&&de!==W}):A=Fn(A,g),g.parentNode.replaceChild(A,g),!k){U&&G.setAttribute("Location",j.getAttribute("Location"));const te=B.getAttribute("Sequence")??(U?j.getAttribute("Sequence"):null);te&&G.setAttribute("Sequence",te)}u.customActions.set(W,d.serializeToString(G));continue}const F=j.getAttribute("Location"),J=j.tagName==="CustomAction"&&F?f.get(F):void 0;if(J&&B){const G=Co(e.customActions.get(J)),g=ge(L),k=pe(g,"CommandUIDefinition");k?.firstElementChild&&Fn(k.firstElementChild,G),u.customActions.delete(J),u.customActions.set(D,d.serializeToString(g));continue}u.customActions.set(D,L)}for(const D of n.movedControls??[]){const L=p.get(D.id),j=L?v(L,D.id):null;if(!L||!j?.ca||!j.el){if(x.has(D.id))continue;throw new Error(`Can't move ${D.id}: it isn't in this table's unmanaged customizations.`)}const{ca:B,el:N}=j,W=D.controlsId??`${D.groupId}.Controls`;if(N.setAttribute("Sequence",String(D.sequence)),!j.nested)B.setAttribute("Location",`${W}._children`),B.setAttribute("Sequence",String(D.sequence));else if(N.parentElement?.getAttribute("Id")!==W){const U=Array.from(B.getElementsByTagName("Controls")).find(X=>X.getAttribute("Id")===W);if(N.parentNode.removeChild(N),U)U.appendChild(N);else{let X=`${D.id}.CustomAction`;for(;u.customActions.has(`ca:${X}`);)X+="_";u.customActions.set(`ca:${X}`,`<CustomAction Id="${bs(X)}" Location="${bs(`${W}._children`)}" Sequence="${D.sequence}"><CommandUIDefinition>${d.serializeToString(N)}</CommandUIDefinition></CustomAction>`)}}u.customActions.set(L,d.serializeToString(B))}const h=new Set,y=new Set;for(const[D,L]of Array.from(u.customActions)){const j=ge(L);if(j.tagName==="HideCustomAction"){a.has(j.getAttribute("Location")??"")&&u.customActions.delete(D);continue}const B=pe(j,"CommandUIDefinition")?.firstElementChild??null,N=B?.getAttribute("Id");if(!B||!Je(j.getAttribute("Location")))continue;if(N&&l.has(N)&&!x.has(N)){u.customActions.delete(D);for(const U of L.matchAll(Io))y.add(U[1]);for(const U of Pn(B))h.add(U);continue}const W=Un(B).filter(U=>{const X=U.getAttribute("Id")??"";return l.has(X)&&!x.has(X)});if(W.length!==0){for(const U of W){const X=d.serializeToString(U);for(const Q of X.matchAll(Io))y.add(Q[1]);for(const Q of Pn(U))h.add(Q);U.parentNode?.removeChild(U)}u.customActions.set(D,d.serializeToString(j))}}const w=new Set,I=new Set(n.deletedContainerIds??[]),S=(D,L)=>{for(const j of lp(D))I.add(j);for(const j of Pn(D))h.add(j);for(const j of[D,...Array.from(D.getElementsByTagName("Tab"))]){const B=j.tagName==="Tab"?j.getAttribute("Command"):null;B&&w.add(B)}for(const j of L.matchAll(Io))y.add(j[1])};for(let D=I.size>0;D;){D=!1;for(const[L,j]of Array.from(u.customActions)){const B=ge(j),N=B.getAttribute("Location");if(B.tagName==="HideCustomAction"){N&&I.has(N)&&(u.customActions.delete(L),D=!0);continue}const W=pe(B,"CommandUIDefinition")?.firstElementChild??null,U=W?.getAttribute("Id")??null,X=dp(N);if(!!U&&I.has(U)&&Je(N)||!!X&&I.has(X)||!Je(N)&&!!N&&I.has(N)||!!W?.getAttribute("GroupId")&&I.has(W.getAttribute("GroupId"))){u.customActions.delete(L),W&&S(W,j),D=!0;continue}if(W?.tagName!=="Tab")continue;const q=Array.from(W.getElementsByTagName("*")).filter(F=>F.tagName==="Group"?I.has(F.getAttribute("Id")??""):(F.tagName==="MaxSize"||F.tagName==="Scale")&&I.has(F.getAttribute("GroupId")??""));if(q.length!==0){for(const F of q)S(F,d.serializeToString(F)),F.parentNode?.removeChild(F);u.customActions.set(L,d.serializeToString(B)),D=!0}}}const C=new Set;for(const[D,L]of u.customActions)e.customActions.get(D)!==L&&C.add(D);u.customActions=Zr(u.customActions,C);const $=(D,L)=>{for(const[j,B]of t[D])e[D].has(j)&&!L.has(j)||u[D].set(j,B)};$("commandDefinitions",o),$("enableRules",i),$("displayRules",r);const R=Array.from(u.customActions.values()).join(`
|
|
33
|
-
`);for(const D of h){if(c.has(D)||!u.commandDefinitions.has(D)||R.includes(`Command="${D}"`))continue;const L=u.commandDefinitions.get(D);u.commandDefinitions.delete(D);const j=Array.from(u.commandDefinitions.values()).join(`
|
|
34
|
-
`);for(const B of L.matchAll(/<EnableRule\s+Id="([^"]+)"/g))j.includes(`Id="${B[1]}"`)||u.enableRules.delete(B[1]);for(const B of L.matchAll(/<DisplayRule\s+Id="([^"]+)"/g))j.includes(`Id="${B[1]}"`)||u.displayRules.delete(B[1])}const E={EnableRule:new Set(n.retainedEnableRuleIds??[]),DisplayRule:new Set(n.retainedDisplayRuleIds??[])},T=ea(u);for(const D of n.uncustomisedCommandIds??[]){const L=u.commandDefinitions.get(D);if(L===void 0||t.commandDefinitions.has(D)||!Ei(D,T))continue;u.commandDefinitions.delete(D);const j=Array.from(u.commandDefinitions.values()).join(`
|
|
35
|
-
`);for(const B of L.matchAll(mp)){const N=B[1],W=N==="EnableRule"?u.enableRules:u.displayRules;(N==="EnableRule"?t.enableRules:t.displayRules).has(B[2])||E[N].has(B[2])||j.includes(`<${N} Id="${B[2]}"`)||W.delete(B[2])}}for(const[D,L]of t.tabDisplayRules)u.tabDisplayRules.set(D,L);for(const[D,L]of t.templates)u.templates.set(D,L);const _=D=>Array.from(u.customActions.values()).some(L=>L.includes(D));for(const D of y)!t.locLabels.has(D)&&!_(`$LocLabels:${D}"`)&&u.locLabels.delete(D);for(const D of w)!t.tabDisplayRules.has(D)&&!_(`Command="${D}"`)&&u.tabDisplayRules.delete(D);for(const D of n.removedTabCommands??[])t.tabDisplayRules.has(D)||u.tabDisplayRules.delete(D);for(const[D,L]of t.locLabels){if(e.locLabels.get(D)){const B=Array.from(ge(L).querySelectorAll("Title")).map(N=>N.getAttribute("description"));if(B.length>0&&B.every(N=>N===D))continue}u.locLabels.set(D,L)}return u}function wx(e,t,n){const o=Di(e,Zt());for(const[i,r]of o.customActions){const l=ge(r);if(l.tagName!=="CustomAction"||!Je(l.getAttribute("Location")))continue;const a=pe(l,"CommandUIDefinition")?.firstElementChild;if(!bn(a))continue;const c=Yr(a,t);if(!(!c||!bn(c))){c.setAttribute("Title",n),o.customActions.set(i,jn().serializeToString(l));break}}return o}function Oi(e){const t=[],n=(o,i,r)=>({id:o.getAttribute("Id")??"",kind:o.tagName,groupId:o.getAttribute("GroupId")??"",sequence:Number(o.getAttribute("Sequence")??"0"),size:o.getAttribute("Size")??"",tabId:i,key:r});for(const[o,i]of e.customActions){const r=ge(i);if(r.tagName!=="CustomAction")continue;const l=pe(r,"CommandUIDefinition")?.firstElementChild;if(!l)continue;const a=/^(.+)\.Scaling\._children$/.exec(r.getAttribute("Location")??"");if(a&&(l.tagName==="MaxSize"||l.tagName==="Scale")&&t.push(n(l,a[1],o)),l.tagName==="Tab"&&Je(r.getAttribute("Location"))){const c=l.getAttribute("Id")??"";for(const d of Array.from(pe(l,"Scaling")?.children??[]))(d.tagName==="MaxSize"||d.tagName==="Scale")&&t.push(n(d,c,o))}}return t}function Cx(e,t){const n=Oi(e),o=new Map;for(const c of n)o.set(c.tabId,[...o.get(c.tabId)??[],c]);const i=[],r=[];for(const[c,d]of o){const u=Ur(c,t[c]??{maxSizes:[],scales:[]},d);i.push(...u.changes),r.push(...u.problems)}if(i.length===0)return{parts:e,changes:i,problems:r};const l=Di(e,Zt()),a=jn();for(const c of i){const d=n.find(b=>b.id===c.id&&b.kind===c.kind&&b.tabId===c.tabId),u=ge(l.customActions.get(d.key)),p=pe(u,"CommandUIDefinition").firstElementChild;(p.tagName==="Tab"?Array.from(pe(p,"Scaling")?.children??[]).find(b=>b.tagName===c.kind&&b.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:r}}function pp(e,t){const n=new Map;for(const i of t.customActions.values()){const r=ge(i);if(r.tagName!=="CustomAction"||!Je(r.getAttribute("Location")))continue;const l=pe(r,"CommandUIDefinition")?.firstElementChild;if(bn(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 r=n.get(i.id);r&&(i.label=r);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 Oi(t)){if(!o.has(i.tabId))continue;e.scalingByTab=e.scalingByTab??{};const r=e.scalingByTab[i.tabId]=e.scalingByTab[i.tabId]??{tabId:i.tabId,maxSizes:[],scales:[]},l=i.kind==="MaxSize"?r.maxSizes:r.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 ta(e){return`$LocLabels:${e}`}function fp(e){const t=e.match(/^\$LocLabels:(.+)$/);return t?t[1]:null}const xs=128;function uo(e,t){const n=`${e}.${t}`;if(n.length<=xs)return n;const o=hp(e),i=xs-t.length-o.length-2;return`${e.slice(0,i)}_${o}.${t}`}function hp(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function mo(e){return uo(e,"LabelText")}function po(e){return uo(e,"ToolTipTitle")}function fo(e){return uo(e,"ToolTipDescription")}function gp(e){return uo(e,"Title")}function bp(e,t){const n=(o,i)=>(o?fp(o):null)??i;return{label:n(t?.labelToken,mo(e)),tooltipTitle:n(t?.tooltipTitleToken,po(e)),tooltipBody:n(t?.tooltipBodyToken,fo(e))}}function yp(e,t,n=1033){const o=new Set(Object.values(bp(e.id,e.source))),i=new Set;for(const r of t)o.has(r.id)&&r.titles.forEach(l=>i.add(l.languageCode));return[...i].sort((r,l)=>r===n?-1:l===n?1:r-l)}function ce(e,t,n=1033){if(!e)return"";const o=e.match(/^\$LocLabels:(.+)$/);if(o){const r=o[1],l=t.find(a=>a.id===r);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??r}return r}const i=e.match(/^\$Resources(?:\([^)]*\))?:(.+)$/);return i?i[1]:e}function zi(e){return!!e&&/^\$Resources(\([^)]*\))?:/.test(e)}function xp(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 Mt=e=>e==="flyout"||e==="splitButton",na=e=>["true","1"].includes(e?.trim().toLowerCase()??"");function wt(e){const t=[];for(const n of e.menu?.sections??[])for(const o of n.controls)t.push(o),t.push(...wt(o));return t}function oa(e){return e.flatMap(t=>[t,...wt(t)])}function je(e){return oa(e.buttons)}function ho(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 r=ho(o.controls,t);if(r)return r}}function Vn(e,t){if(!e.buttons.some(n=>n.id===t))return ho(e.buttons,t)}function Qt(e,t){if(!e||!t)return;const n=e.buttons.find(i=>i.id===t);if(n)return n;const o=ho(e.buttons,t);return o?.section.controls[o.index]}function vp(e,t){if(!(!e||!t))return e.buttons.find(n=>n.id===t||wt(n).some(o=>o.id===t))}function ia(e,t){const n=ho(e.buttons,t);return n?(n.section.controls.splice(n.index,1),!0):!1}function Ro(e){return{id:`${e}.Menu`,sections:[oi(e,[])]}}function oi(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 r=`${e}.MenuSection${o}`;return{id:r,title:n,sequence:o*10,displayMode:"Menu16",controlsId:`${r}.Controls`,controls:[]}}function Sp(e,t,n){if(!e)return;const o=new Set,i=new Map,r=a=>{const c=i.get(a);if(c)return c;let d=a.startsWith(t)?`${n}${a.slice(t.length)}`:`${n}.${a.split(".").pop()||"Item"}`;for(let u=2;o.has(d);u++)d=`${d.replace(/_\d+$/,"")}_${u}`;return o.add(d),i.set(a,d),d},l=a=>a.replace(/(\sId=")([^"]*)(")/g,(c,d,u,p)=>`${d}${r(u)}${p}`);return{...e,id:r(e.id),sections:e.sections.map(a=>({...a,id:r(a.id),controlsId:r(a.controlsId),controls:a.controls.map(c=>Kn(c,r(c.id))),...a.rawControls?{rawControls:a.rawControls.map(c=>({...c,xml:l(c.xml)}))}:{},...a.rawContent!==void 0?{rawContent:l(a.rawContent)}:{}}))}}function wp(e,t,n){return e.replace(/(\s(?:Id|InitialItem)=")([^"]*)(")/g,(o,i,r,l)=>`${i}${r.startsWith(t)?`${n}${r.slice(t.length)}`:`${n}.${r}`}${l}`)}const Cp=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand"];function Kn(e,t){const n=Cp.filter(d=>e.source?.attributes[d]!==void 0),o=xp(e.source),i={...o?.attributes??{},...Object.fromEntries(n.map(d=>[d,e.source.attributes[d]]))},r=d=>zi(d)?d:void 0,l={labelToken:r(e.source?.labelToken),tooltipTitleToken:r(e.source?.tooltipTitleToken),tooltipBodyToken:r(e.source?.tooltipBodyToken)},a=Object.fromEntries(Object.entries(l).filter(([,d])=>d!==void 0)),c=e.source?.xml?wp(e.source.xml,e.id,t):void 0;return{...e,id:t,source:Object.keys(i).length+Object.keys(a).length>0||c?{...o?.modernImage?{modernImage:o.modernImage}:{},...a,attributes:i,...c?{xml:c}:{}}:void 0,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0,menu:Sp(e.menu,e.id,t)}}const Ip=["label","icon","image16","image32","tooltipTitle","tooltipBody","commandId","templateAlias"];function ii(e,t){for(const n of Ip)if((e[n]??"")!==(t[n]??""))return!0;return!1}function St(e){const t=new Map,n=new Map,o=(i,r,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:r,tabId:l,menu:a}:{button:i,groupId:r,tabId:l});for(const u of i.menu?.sections??[])for(const p of u.controls)o(p,r,l,{parentKey:d,parentId:i.id,sectionId:u.id,controlsId:u.controlsId})};for(const i of e.tabs)for(const r of i.groups)for(const l of r.buttons)o(l,r.id,i.id);return t}function sa(e,t){const n=St(t),o=St(e),i=l=>{for(let a=l.menu?.parentKey;a;a=o.get(a)?.menu?.parentKey)if(!n.has(a))return!0;return!1},r=[];for(const[l,a]of o){const c=n.get(l)?.button,d=a.button;if(i(a)){d.hidden&&r.push({entry:a,change:"hide"});continue}c?d.hidden&&!c.hidden?r.push({entry:a,change:"hide"}):ii(c,d)&&r.push({entry:a,change:"override"}):(d.hidden&&(d.oob||d.managed)||r.push({entry:a,change:"new"}),d.hidden&&r.push({entry:a,change:"hide"}))}return r}function ra(e){return e.commandId||`${e.id}.Command`}function Rp(e,t){return e==="SubGrid"?`Mscrm.SubGrid.${t}.ContextualTabs._children`:"Mscrm.Tabs._children"}function aa(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 jp(e,t,n){const o=ra(e),i=(e.tabDisplayRules??[]).map(r=>({...r,tabCommand:r.tabCommand||o}));return{...e,commandId:o,tabDisplayRules:i.length>0?i:aa(t,n,o)}}function Ix(e){const{current:t,baseline:n,commands:o,enableRules:i,displayRules:r,locLabels:l}=e,a=e.languageCode??1033,c=e.location==="Application",d=new Set,u=new Set;for(const G of n.tabs){d.add(G.id);for(const g of G.groups)u.add(g.id)}const p=St(n),f=new Map;for(const[G,g]of St(t))f.set(g.button,p.get(G)?.button);const b=t.tabs.filter(G=>!d.has(G.id)).map(G=>jp(G,e.location,e.entityLogicalName)),v=[],x=[],h=[],y=[],w=[],I=G=>w.push(G),S=[],C=G=>{const g=[];for(const k of G.buttons)k.hidden||f.get(k)||(g.push(go(k,l,I,a,!0)),S.push(k,...wt(k)));return g},$=new Set,R=ca(t,n).steps;for(const G of b){const g=new Map(G.groups.map(k=>[k.id,C(k)]));for(const k of G.groups)for(const A of k.buttons)!A.hidden&&!f.get(A)&&$.add(A);v.push(zp(G,t.scalingByTab?.[G.id],Rp(e.location,e.entityLogicalName),g,R,I,a,l))}const E=[];for(const G of t.tabs)if(d.has(G.id)){for(const g of G.groups)if(!u.has(g.id)){for(const A of g.buttons)!A.hidden&&!f.get(A)&&$.add(A);x.push(Op(g,G.id,C(g),I,a,l));const k=R.get(g.id);k&&E.push(ri(G.id,"MaxSize",k))}}x.push(...E);for(const{entry:G,change:g}of sa(t,n)){const{button:k,groupId:A,menu:te}=G;if(!$.has(k))if(g==="hide")y.push(Ep(k));else if(g==="new"){const de=te?`${te.controlsId}._children`:`${A}.Controls._children`;h.push(Ap(k,de,l,I,a)),S.push(k,...wt(k))}else h.push(Dp(k,l,I,a)),S.push(k)}const T=new Set;for(const G of S)for(const g of Hr(G))T.add(g);const _=[];for(const G of b){const g=G.commandId;T.add(g),o.some(k=>k.id===g)||_.push({id:g,enableRules:[],displayRules:[],actions:[]})}const D=[...o.filter(G=>T.has(G.id)&&(!$o(G.id)||G.actions.length>0)),..._],L=new Set,j=new Set;for(const G of D)G.enableRules.forEach(g=>L.add(g)),G.displayRules.forEach(g=>j.add(g));const B=i.filter(G=>L.has(G.id)&&!$o(G.id)),N=r.filter(G=>j.has(G.id)&&!$o(G.id)),W=qp(w),U=D.map(Up).join(`
|
|
36
|
-
`),X=B.map(Xp).join(`
|
|
37
|
-
`),Q=N.map(Vp).join(`
|
|
38
|
-
`),q=W.map(Kp).join(`
|
|
39
|
-
`),F=[...v,...x,...Np(t,n,d),...h,...y],J=b.filter(G=>G.tabDisplayRules.length>0).map(G=>Jp(G,c)).filter(Boolean).join(`
|
|
40
|
-
`);return`<RibbonDiffXml>
|
|
41
|
-
<CustomActions>
|
|
42
|
-
${F.join(`
|
|
43
|
-
`)}
|
|
44
|
-
</CustomActions>
|
|
45
|
-
<Templates><RibbonTemplates Id="Mscrm.Templates"/></Templates>
|
|
46
|
-
<CommandDefinitions>
|
|
47
|
-
${U}
|
|
48
|
-
</CommandDefinitions>
|
|
49
|
-
<RuleDefinitions>
|
|
50
|
-
<TabDisplayRules>
|
|
51
|
-
${J}
|
|
52
|
-
</TabDisplayRules>
|
|
53
|
-
<DisplayRules>
|
|
54
|
-
${Q}
|
|
55
|
-
</DisplayRules>
|
|
56
|
-
<EnableRules>
|
|
57
|
-
${X}
|
|
58
|
-
</EnableRules>
|
|
59
|
-
</RuleDefinitions>
|
|
60
|
-
<LocLabels>
|
|
61
|
-
${q}
|
|
62
|
-
</LocLabels>
|
|
63
|
-
</RibbonDiffXml>`}function $p(e,t){const n=new Set,o=new Set;for(const v of t.tabs){n.add(v.id);for(const x of v.groups)o.add(x.id)}let i=0,r=0,l=0,a=0,c=0,d=0;for(const v of e.tabs){n.has(v.id)||a++,v.tabDisplayRules&&v.tabDisplayRules.length>0&&(d+=v.tabDisplayRules.length);for(const x of v.groups)!o.has(x.id)&&n.has(v.id)&&c++}for(const{change:v}of sa(e,t))v==="hide"?l++:v==="new"?i++:r++;const u=e.scalingByTab??{},p=t.scalingByTab??{};let f=0;for(const[v,x]of Object.entries(u))JSON.stringify(x)!==JSON.stringify(p[v])&&f++;const b=i+r+l+a+c+f>0;return{newButtons:i,overriddenButtons:r,hiddenButtons:l,newTabs:a,newGroups:c,scalingChanges:f,tabDisplayRules:d,hasAnyChange:b}}function Np(e,t,n){const o=[],i=[];for(const[r,l]of Object.entries(e.scalingByTab??{})){if(!n.has(r))continue;const a=t.scalingByTab?.[r],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(ri(r,"MaxSize",d));for(const d of l.scales)c(d,a?.scales)||i.push(ri(r,"Scale",d))}return[...o,...i]}function si(e,t){return`<${e} Id="${re(t.id)}" GroupId="${re(t.groupId)}" Sequence="${t.sequence}" Size="${re(t.size)}"/>`}function ri(e,t,n){return`<CustomAction Id="${re(n.id)}.CustomAction"
|
|
64
|
-
Location="${re(e)}.Scaling._children"
|
|
65
|
-
Sequence="${n.sequence}">
|
|
66
|
-
<CommandUIDefinition>
|
|
67
|
-
${si(t,n)}
|
|
68
|
-
</CommandUIDefinition>
|
|
69
|
-
</CustomAction>`}const la={"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"},Tp=Object.keys(la);function kp(e){return la[Bi(e.template)]}function ca(e,t){const n=new Map,o=[],i=new Set(t.tabs.map(l=>l.id)),r=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(b=>b.sequence),u=(c?.scales??[]).map(b=>b.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=Wr(d,u);for(const b of l.groups){if(!a&&r.has(b.id)||c?.maxSizes.some(h=>h.groupId===b.id))continue;const v=kp(b);if(!v)continue;const x=Gr(f,p);if(x===void 0){o.push(`No free scaling position for the new group "${b.label}" (${b.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(b.id,{id:`${b.id}.MaxSize`,groupId:b.id,size:v,sequence:x})}}return{steps:n,problems:o}}function Ap(e,t,n,o,i=1033){return`<CustomAction Id="${re(e.id)}.CustomAction"
|
|
70
|
-
Location="${re(t)}"
|
|
71
|
-
Sequence="${e.sequence}">
|
|
72
|
-
<CommandUIDefinition>
|
|
73
|
-
${go(e,n,o,i,!0)}
|
|
74
|
-
</CommandUIDefinition>
|
|
75
|
-
</CustomAction>`}function Dp(e,t,n,o=1033){return`<CustomAction Id="${re(e.id)}.Override.CustomAction"
|
|
76
|
-
Location="${re(e.id)}"
|
|
77
|
-
Sequence="${e.sequence}">
|
|
78
|
-
<CommandUIDefinition>
|
|
79
|
-
${go(e,t,n,o)}
|
|
80
|
-
</CommandUIDefinition>
|
|
81
|
-
</CustomAction>`}function Ep(e,t){return`<HideCustomAction HideActionId="${re(e.id)}.HideAction"
|
|
82
|
-
Location="${re(e.id)}"/>`}function Op(e,t,n,o,i=1033,r=[]){return`<CustomAction Id="${re(e.id)}.CustomAction"
|
|
83
|
-
Location="${re(t)}.Groups._children"
|
|
84
|
-
Sequence="${e.sequence}">
|
|
85
|
-
<CommandUIDefinition>
|
|
86
|
-
${da(e,o,n,i,r)}
|
|
87
|
-
</CommandUIDefinition>
|
|
88
|
-
</CustomAction>`}function zp(e,t,n,o,i,r,l=1033,a=[]){const c=ua(e,r,l,a),d=e.commandId?` Command="${re(e.commandId)}"`:"",u=e.groups.map(v=>da(v,r,o.get(v.id)??[],l,a)).join(`
|
|
89
|
-
`),f=[...(t?.maxSizes.length?t.maxSizes:e.groups.map(v=>i.get(v.id)).filter(v=>!!v)).map(v=>si("MaxSize",v)),...(t?.scales??[]).map(v=>si("Scale",v))],b=f.length===0?`<Scaling Id="${re(e.id)}.Scaling"/>`:`<Scaling Id="${re(e.id)}.Scaling">
|
|
90
|
-
${f.join(`
|
|
91
|
-
`)}
|
|
92
|
-
</Scaling>`;return`<CustomAction Id="${re(e.id)}.CustomAction"
|
|
93
|
-
Location="${re(n)}"
|
|
94
|
-
Sequence="${e.sequence}">
|
|
95
|
-
<CommandUIDefinition>
|
|
96
|
-
<Tab Id="${re(e.id)}"${d} Title="${re(c)}"${ma(e,a,r)} Sequence="${e.sequence}"${pa(e)}>
|
|
97
|
-
${b}
|
|
98
|
-
<Groups Id="${re(e.id)}.Groups">
|
|
99
|
-
${u}
|
|
100
|
-
</Groups>
|
|
101
|
-
</Tab>
|
|
102
|
-
</CommandUIDefinition>
|
|
103
|
-
</CustomAction>`}function da(e,t,n=[],o=1033,i=[]){const r=ua(e,t,o,i),l=Bi(e.template),a=n.length===0?`<Controls Id="${re(e.id)}.Controls"/>`:`<Controls Id="${re(e.id)}.Controls">
|
|
104
|
-
${n.join(`
|
|
105
|
-
`)}
|
|
106
|
-
</Controls>`;return`<Group Id="${re(e.id)}" Title="${re(r)}"${ma(e,i,t)} Sequence="${e.sequence}" Template="${re(l)}"${pa(e)}>
|
|
107
|
-
${a}
|
|
108
|
-
</Group>`}function ua(e,t,n,o){const i=`${e.id}.Title`;if(e.source&&e.label){const r=mn(e.label,e.source.titleToken,i,o,t,n);if(r)return r}return t({id:i,titles:[{languageCode:n,description:e.label}]}),ta(i)}function ma(e,t,n){const o=e.description,i=o?.startsWith("$LocLabels:")?t.find(r=>r.id===o.slice(11)):void 0;return i&&n(i),V("Description",o)}const Bp=new Set(["Id","Command","Title","Description","Sequence","Template"]);function pa(e){return Object.entries(e.source?.attributes??{}).filter(([t])=>!Bp.has(t)&&!Mi.has(t)).map(([t,n])=>` ${t}="${re(n)}"`).join("")}function Bi(e){const t=e?.trim();return t?t.includes(".")?t:`Mscrm.Templates.${t}`:"Mscrm.Templates.Flexible2"}function Mp(e,t,n,o,i=1033){const r=e??"";if(r.startsWith("$LocLabels:")){const c=r.slice(11),d=n.find(u=>u.id===c);return o(d??{id:c,titles:[{languageCode:i,description:c}]}),r}if(zi(r))return r;const l=[{languageCode:i,description:r}],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}),ta(t)}const jo=["ModernImage","Image16by16","Image32by32"],Lp={textBox:["LabelText",...jo],comboBox:["LabelText",...jo],checkBox:jo},Mi=new Set(["SolutionUniqueName"]);function Pp(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 mn(e,t,n,o,i,r=1033){if(t!==void 0&&(e??"")===ce(t,o,r)){if(t.startsWith("$LocLabels:")){const a=o.find(c=>c.id===t.slice(11));a&&i(a)}return t}if(!e)return;const l=t?.startsWith("$LocLabels:")?t.slice(11):n;return Mp(e,l,o,i,r)}function Li(e){const t=e.source,n=i=>!!i?.startsWith("$webresource:"),o=[[e.image32,"Image32by32"],[e.image16,"Image16by16"]].filter(([i,r])=>n(i)&&i!==t?.attributes[r]).map(([i])=>i);return t&&Pp(t.modernImage)===e.icon&&o.length===0?t.modernImage:o[0]??[e.image32,e.image16,e.icon].find(n)}function go(e,t,n,o=1033,i=!1){const r=Hp(e.kind),l=e.source;if(l?.xml&&Ze(e.kind))return Wp(e,l.xml,t,n);const a=new Map;for(const[f,b]of Object.entries(l?.attributes??{}))Mi.has(f)||a.set(f,b);const c=(f,b)=>b===void 0||b===""?a.delete(f):a.set(f,b);c("Id",e.id),c("Command",e.commandId||void 0),c("LabelText",mn(e.label,l?.labelToken,mo(e.id),t,n,o)??""),a.has("LabelText")||a.set("LabelText",""),c("ToolTipTitle",mn(e.tooltipTitle,l?.tooltipTitleToken,po(e.id),t,n,o)),c("ToolTipDescription",mn(e.tooltipBody,l?.tooltipBodyToken,fo(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",Li(e)),c("Image16by16",d(e.image16)?e.image16:void 0),c("Image32by32",d(e.image32)?e.image32:void 0);for(const f of Lp[e.kind]??[])a.delete(f);const u=Array.from(a.entries()).map(([f,b])=>`${f}="${re(b)}"`).join(" "),p=i&&e.menu&&Fp.has(r)?_p(e.menu,t,n,o):"";return p?`<${r} ${u}>${p}</${r}>`:`<${r} ${u}/>`}const Fp=new Set(["FlyoutAnchor","SplitButton","ComboBox"]);function _p(e,t,n,o){const i=e.sections.map(a=>{const c=new Map(Object.entries(a.attributes??{})),d=(b,v)=>v===void 0||v===""?c.delete(b):c.set(b,v);d("Id",a.id),d("Title",mn(a.title,a.attributes?.Title,gp(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(([b,v])=>` ${b}="${re(v)}"`).join("");if(a.rawContent!==void 0)return`<MenuSection${p}>${a.rawContent}</MenuSection>`;const f=a.controls.map(b=>go(b,t,n,o,!0));for(const b of[...a.rawControls??[]].sort((v,x)=>v.index-x.index))f.splice(Math.min(b.index,f.length),0,b.xml);return`<MenuSection${p}><Controls Id="${re(a.controlsId)}">${f.join("")}</Controls></MenuSection>`}),r=new Map(Object.entries(e.attributes??{}));return r.set("Id",e.id),`<Menu${Array.from(r.entries()).map(([a,c])=>` ${a}="${re(c)}"`).join("")}>${i.join("")}</Menu>`}function $o(e){return/^(Mscrm|Microsoft)\./.test(e)}function qp(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 Hp(e){return gn[e]??"Button"}function Wp(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 Mi)l.removeAttribute(a);i.setAttribute("Id",e.id),(i.hasAttribute("Sequence")||e.sequence!==0)&&i.setAttribute("Sequence",String(e.sequence));const r=new XMLSerializer().serializeToString(i);for(const l of r.matchAll(/\$LocLabels:([^"'\s<]+)/g)){const a=n.find(c=>c.id===l[1]);a&&o(a)}return r}function Gp(e){const t=(e??"").trim();return!t||/^\$webresource:/i.test(t)||/^https?:\/\//i.test(t)||t.startsWith("/")?t:`$webresource:${t}`}function V(e,t){return t===void 0?"":` ${e}="${re(String(t))}"`}function nt(e,t,n,o){return n.length===0?`<${e}${t}/>`:`<${e}${t}>
|
|
109
|
-
${n.map(i=>`${o} ${i}`).join(`
|
|
110
|
-
`)}
|
|
111
|
-
${o}</${e}>`}function fa(e,t=" "){switch(e.kind){case"javascript":return nt("JavaScriptFunction",`${V("FunctionName",e.functionName)}${V("Library",Gp(e.library))}`,e.params.map(n=>ai(n,!1)),t);case"url":return nt("Url",`${V("Address",e.address)}${V("PassParams",e.passParams)}${V("WinMode",e.winMode)}${V("WinParams",e.winParams)}`,e.params.map(n=>ai(n,!0)),t);case"outlookCommand":return`<OutlookCommand${V("ActionType",e.actionType)}${V("Data",e.data)}/>`;case"raw":return e.xml;default:return""}}function Up(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="${re(l)}"/>`)),i=n("DisplayRules",e.displayRules.map(l=>`<DisplayRule Id="${re(l)}"/>`)),r=e.actions.map(l=>fa(l,`${t} `)).filter(Boolean);return`<CommandDefinition Id="${re(e.id)}">
|
|
112
|
-
${t} ${nt("EnableRules","",o,`${t} `)}
|
|
113
|
-
${t} ${nt("DisplayRules","",i,`${t} `)}
|
|
114
|
-
${t} ${nt("Actions","",r,`${t} `)}
|
|
115
|
-
${t}</CommandDefinition>`}function ai(e,t){const n=t?V("Name",e.name??""):"";switch(e.kind){case"CrmParameter":return`<CrmParameter${n}${V("Value",e.value)}/>`;case"BoolParameter":return`<BoolParameter${n}${V("Value",e.value)}/>`;case"IntParameter":return`<IntParameter${n}${V("Value",e.value)}/>`;case"DecimalParameter":return`<DecimalParameter${n}${V("Value",e.value)}/>`;case"StringParameter":return`<StringParameter${n}${V("Value",e.value)}/>`}}function Xp(e){return nt("EnableRule",V("Id",e.id),e.steps.map(t=>bo(t," "))," ")}function Vp(e){return nt("DisplayRule",V("Id",e.id),e.steps.map(t=>bo(t," "))," ")}function bo(e,t=""){if(e.kind==="RawRule")return e.xml;if(e.kind==="OrRule"){const i=e.groups.map(r=>nt("Or","",r.map(l=>bo(l,`${t} `)),`${t} `));return nt("OrRule","",i,t)}const n=`${V("Default",e.default)}${V("InvertResult",e.invertResult)}`,o=(i,r)=>`<${i}${r}${n}/>`;switch(e.kind){case"SelectionCountRule":return o("SelectionCountRule",`${V("AppliesTo",e.appliesTo)}${V("Minimum",e.minimum)}${V("Maximum",e.maximum)}`);case"EntityRule":return o("EntityRule",`${V("EntityName",e.entityName)}${V("AppliesTo",e.appliesTo)}${V("Context",e.context)}`);case"FormStateRule":return o("FormStateRule",V("State",e.state));case"CommandClientTypeRule":return o("CommandClientTypeRule",V("Type",e.type));case"CrmClientTypeRule":return o("CrmClientTypeRule",V("Type",e.type));case"CustomRule":return nt("CustomRule",`${V("FunctionName",e.functionName)}${V("Library",e.library)}${n}`,(e.params??[]).map(i=>ai(i,!1)),t);case"FeatureControlRule":return o("FeatureControlRule",`${V("FeatureControlBit",e.featureControlBit)}${V("ExpectedValue",e.expectedValue)}`);case"MiscellaneousPrivilegeRule":return o("MiscellaneousPrivilegeRule",`${V("PrivilegeName",e.privilegeName)}${V("PrivilegeDepth",e.privilegeDepth)}`);case"FormTypeRule":return o("FormTypeRule",V("Type",e.type));case"ValueRule":return o("ValueRule",`${V("Field",e.field)}${V("Value",e.value)}`);case"SkuRule":return o("SkuRule",V("Sku",e.sku));case"HideForTabletExperienceRule":return o("HideForTabletExperienceRule","");case"OrganizationSettingRule":return o("OrganizationSettingRule",V("Setting",e.setting));case"EntityPrivilegeRule":return o("EntityPrivilegeRule",`${V("PrivilegeType",e.privilegeType)}${V("PrivilegeDepth",e.privilegeDepth)}${V("AppliesTo",e.appliesTo)}${V("EntityName",e.entityName)}`);case"EntityPropertyRule":return o("EntityPropertyRule",`${V("EntityName",e.entityName)}${V("AppliesTo",e.appliesTo)}${V("PropertyName",e.propertyName)}${V("PropertyValue",e.propertyValue)}`);case"DeviceTypeRule":return o("DeviceTypeRule",V("Type",e.type));case"RelationshipTypeRule":return o("RelationshipTypeRule",`${V("AppliesTo",e.appliesTo)}${V("RelationshipType",e.relationshipType)}${V("AllowCustomRelationship",e.allowCustomRelationship)}${V("AllowSystemRelationship",e.allowSystemRelationship)}`);case"RecordPrivilegeRule":return o("RecordPrivilegeRule",`${V("PrivilegeType",e.privilegeType)}${V("AppliesTo",e.appliesTo)}`);case"FormEntityContextRule":return o("FormEntityContextRule",V("EntityName",e.entityName));case"PageRule":return o("PageRule",V("Address",e.address));case"ReferencingAttributeRequiredRule":return o("ReferencingAttributeRequiredRule","");case"OutlookItemTrackingRule":return o("OutlookItemTrackingRule",`${V("TrackedInCrm",e.trackedInCrm)}${V("AppliesTo",e.appliesTo)}`);case"OutlookRenderTypeRule":return o("OutlookRenderTypeRule",V("Type",e.type));case"OutlookVersionRule":return o("OutlookVersionRule",V("Version",e.version));case"CrmOfflineAccessStateRule":return o("CrmOfflineAccessStateRule",V("State",e.state));case"CrmOutlookClientTypeRule":return o("CrmOutlookClientTypeRule",V("Type",e.type));case"CrmOutlookClientVersionRule":return o("CrmOutlookClientVersionRule",`${V("Major",e.major)}${V("Minor",e.minor)}${V("Build",e.build)}${V("Revision",e.revision)}`);case"OptionSetRule":return o("OptionSetRule",`${V("OptionSet",e.optionSet)}${V("StateCode",e.stateCode)}${V("ObjectTypeCode",e.objectTypeCode)}`);default:{const i=e;throw new Error(`Unknown rule kind: ${i.kind}`)}}}function Kp(e){const t=e.titles.map(n=>`<Title languagecode="${n.languageCode}" description="${re(n.description)}"/>`).join(`
|
|
116
|
-
`);return`<LocLabel Id="${re(e.id)}">
|
|
117
|
-
<Titles>
|
|
118
|
-
${t}
|
|
119
|
-
</Titles>
|
|
120
|
-
</LocLabel>`}function Jp(e,t){return e.tabDisplayRules.map(n=>{const o=n.rules.map(i=>i.kind==="EntityRule"?`<EntityRule${V("EntityName",i.entityName)}${V("AppliesTo",i.appliesTo)}${V("Context",i.context)}/>`:i.kind==="PageRule"&&t?`<PageRule${V("Address",i.address)}/>`:"").filter(Boolean);return o.length===0?"":`<TabDisplayRule TabCommand="${re(n.tabCommand)}">
|
|
121
|
-
${o.join(`
|
|
122
|
-
`)}
|
|
123
|
-
</TabDisplayRule>`}).filter(Boolean).join(`
|
|
124
|
-
`)}function re(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Rx(e){const t=e.entities??[];return`<?xml version="1.0" encoding="utf-8"?>
|
|
125
|
-
<ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">${t.length===0?"":`
|
|
126
|
-
<Entities>
|
|
127
|
-
${t.map(o=>` <Entity>
|
|
128
|
-
<Name LocalizedName="${re(o.localizedName)}" OriginalName="${re(o.localizedName)}">${re(o.schemaName)}</Name>
|
|
129
|
-
${o.ribbonDiffXml}
|
|
130
|
-
</Entity>`).join(`
|
|
131
|
-
`)}
|
|
132
|
-
</Entities>`}
|
|
133
|
-
${e.applicationRibbonDiffXml??""}
|
|
134
|
-
</ImportExportXml>`}function li(e){return/^(Mscrm|Microsoft)\./.test(e)}function Jn(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 Yp(e,t){return t?"unmanaged":li(e)?"oob":"unmanaged"}function vs(e,t){for(const n of e.tabs)for(const o of n.groups)for(const i of je(o))t.has(i.id)?Jn(i,{origin:"unmanaged"}):i.origin==="unmanaged"&&Jn(i,{origin:"managed"})}function vt(e){return e.origin==="unmanaged"}function $n(e,t){return ga(ha(t),[e])}function ha(e){const t=new Map;for(const n of e.tabs)for(const o of n.groups)for(const i of je(o))t.set(i.id,(t.get(i.id)??!0)&&vt(i));return t}function ga(e,t){return oa(t).every(n=>e.get(n.id)??vt(n))}function Yn(e,t,n){return t?n?"has"in n?n.has(e):n.includes(e):!1:!0}function Pi(e,t,n){const o=t.tabs.some(i=>i.groups.some(r=>r.id===e.id));return Yn(e.id,o,n)&&ga(ha(t),e.buttons)}const Fi="Only tabs and groups your unmanaged customizations add (with a translatable title), or new ones, can be renamed";function ba(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(!Yn(t,!0,o?.containerIds))return!1;const r=/^\$LocLabels:(.+)$/.exec(i.label??"")?.[1];return!!r&&Yn(r,!0,o?.locLabelIds)}function ya(e,t,n){const o=t.tabs.some(i=>i.id===e.id);return Yn(e.id,o,n)&&e.groups.every(i=>Pi(i,t,n))}function jx(e,t){const n=t.tabs.flatMap(l=>l.groups.flatMap(a=>je(a))).filter(l=>l.id===e.id),o=n.find(l=>!vt(l)),i=o??n[0]??e,r=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 ${r??"another solution"}, and that one can't be deleted.`:r&&vt(e)?`It is your override of a button from ${r}: the original stays in the ribbon underneath it.`:r?`It comes from ${r}.`:vt(i)?"Its menu holds items from another solution.":"It comes from another solution."}function Zp(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 r of je(i)){const l=t.get(r.id);l&&Jn(r,l)}}function yo(e,t,n,o=[]){const r=new DOMParser().parseFromString(e,"application/xml"),l=r.querySelector("parsererror");if(l)throw new Error(`Ribbon XML parse error: ${l.textContent??"Unknown"}`);const a=Qp(r),c=ef(r);nf(r,a);const d=new af,u=lf(r,d),p=df(r,d),f=uf(r,d);d.flush();const b=[...ff(r)];for(const y of o)b.some(w=>w.id===y.id)||b.push(y);const v=new Set,x=new Set;r.querySelectorAll("CustomAction").forEach(y=>{const w=y.querySelector("CommandUIDefinition");if(w?.firstElementChild){const I=w.firstElementChild.getAttribute("Id")??"";I&&v.add(I)}}),r.querySelectorAll("HideCustomAction").forEach(y=>{const w=y.getAttribute("Location")??"";w&&x.add(w)});for(const y of a)for(const w of y.groups)for(const I of je(w)){const S=v.has(I.id);Jn(I,{origin:Yp(I.id,S)}),I.hidden=x.has(I.id),I.source&&(I.source.labelToken=I.source.attributes.LabelText,I.source.tooltipTitleToken=I.source.attributes.ToolTipTitle,I.source.tooltipBodyToken=I.source.attributes.ToolTipDescription),I.label=ce(I.label,b),I.tooltipTitle&&(I.tooltipTitle=ce(I.tooltipTitle,b)),I.tooltipBody&&(I.tooltipBody=ce(I.tooltipBody,b));for(const C of I.menu?.sections??[])C.title&&(C.title=ce(C.title,b))}const h=tf(r,a);return{ribbon:{location:t,entityLogicalName:n,tabs:a,...Object.keys(c).length>0?{scalingByTab:c}:{},...Object.keys(h).length?{templateLayouts:h}:{}},commands:u,displayRules:f,enableRules:p,locLabels:b}}const xa="Ribbon > Tabs > Tab, Ribbon > ContextualTabs > ContextualGroup > Tab";function Ss(e){const t=e.getAttribute("Description");return t===null?{}:{description:t}}function Qp(e){const t=[];return e.querySelectorAll(xa).forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const i=n.getAttribute("Title")??o,r=[];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=>{Fr[f.tagName]&&va(f,p)}),r.push({id:a,label:c,sequence:d,template:u,...Ss(l),buttons:p})}),t.push({id:o,label:i,sequence:parseInt(n.getAttribute("Sequence")??"0",10),commandId:n.getAttribute("Command")??void 0,...Ss(n),tabDisplayRules:[],groups:r})}),t.sort((n,o)=>n.sequence-o.sequence)}function ef(e){const t={};return e.querySelectorAll(xa).forEach(n=>{const o=n.getAttribute("Id"),i=Array.from(n.children).find(a=>a.tagName==="Scaling");if(!o||!i||t[o])return;const r=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(r),scales:l.filter(a=>a.tagName==="Scale").map(r)}}),t}function tf(e,t){const n=new Set(t.flatMap(i=>i.groups.map(r=>r.template)).filter(Boolean)),o={};return e.querySelectorAll("GroupTemplate").forEach(i=>{const r=i.getAttribute("Id");!r||!n.has(r)||(o[r]=Array.from(i.querySelectorAll(":scope > Layout")).map(l=>l.getAttribute("Title")??"").filter(Boolean))}),o}function nf(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")??"",r=n.get(i);if(!r)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&&r.tabDisplayRules.push({tabCommand:i,rules:l})})}function va(e,t){const n=e.getAttribute("Id")??"";if(!n)return;const o=Fr[e.tagName]??"button",i=Ze(o),r=e.getAttribute("LabelText")??n,l=rf(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:r,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:ci(e),...i?{xml:Wt().serializeToString(e)}:{}},menu:i?void 0:sf(e)})}const of=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]);function ci(e){return Object.fromEntries(Array.from(e.attributes).map(t=>[t.name,t.value]))}function sf(e){const t=Le(e).find(i=>i.tagName==="Menu");if(!t)return;const n=ci(t),o=[];for(const i of Le(t)){if(i.tagName!=="MenuSection")continue;const r=i.getAttribute("Id")??"",l=Le(i).find(u=>u.tagName==="Controls"),a=[],c=[];Le(l).forEach((u,p)=>{of.has(u.tagName)&&u.getAttribute("Id")?va(u,a):c.push({index:p,xml:Wt().serializeToString(u)})});const d=ci(i);o.push({id:r,title:i.getAttribute("Title")??void 0,sequence:parseInt(i.getAttribute("Sequence")??"0",10),displayMode:i.getAttribute("DisplayMode")??void 0,controlsId:l?.getAttribute("Id")??`${r}.Controls`,controls:a,attributes:d,...c.length?{rawControls:c}:{},...l?{}:{rawContent:Le(i).map(u=>Wt().serializeToString(u)).join("")}})}return{id:t.getAttribute("Id")??`${e.getAttribute("Id")}.Menu`,sections:o,attributes:n}}function rf(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 Wt=()=>new XMLSerializer;function Le(e){return e?Array.from(e.childNodes).filter(t=>t.nodeType===Node.ELEMENT_NODE):[]}class af{pending=[];add(t){this.pending.push(t)}flush(){for(const t of[0,1]){const n=this.pending.filter(r=>r.phase===t);if(n.length===0)continue;const o=n.map(r=>r.generate());let i=null;try{const r=Pr(`<v>${o.map(l=>`<i>${l}</i>`).join("")}</v>`);i=Le(r).map(l=>Le(l)[0])}catch{i=null}n.forEach((r,l)=>{(i?i[l]&&Ht(i[l])===Ht(r.source):Qm(o[l],r.source))||r.fallback()})}this.pending=[]}}function lf(e,t){const n=[];return e.querySelectorAll("CommandDefinition").forEach(o=>{const i=o.getAttribute("Id")??"";if(!i)return;const r=Le(o),l=f=>r.find(b=>b.tagName===f),a=[],c=(f,b)=>{const v=[];return Le(l(f)).forEach((x,h)=>{const y=x.getAttribute("Id");x.tagName===b&&y&&x.attributes.length===1&&Le(x).length===0?v.push(y):a.push({container:f,index:h,xml:Wt().serializeToString(x)})}),v},d=c("EnableRules","EnableRule"),u=c("DisplayRules","DisplayRule"),p=[];Le(l("Actions")).forEach((f,b)=>{const v=cf(f);if(!v){p.push(ws(f));return}p.push(v),t.add({source:f,generate:()=>fa(v),fallback:()=>p[b]=ws(f),phase:0})}),n.push({id:i,enableRules:d,displayRules:u,actions:p,...a.length>0?{rawRuleRefs:a}:{}})}),n}function ws(e){return{kind:"raw",tagName:e.tagName,xml:Wt().serializeToString(e)}}function cf(e){switch(e.tagName){case"JavaScriptFunction":{const t=di(e);return t?{kind:"javascript",library:e.getAttribute("Library")??"",functionName:e.getAttribute("FunctionName")??"",params:t}:null}case"Url":{const t=di(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 di(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 df(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > EnableRules > EnableRule").forEach(o=>{const i=o.getAttribute("Id")??"";i&&n.push({id:i,steps:_i(o,t)})}),n}function uf(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > DisplayRules > DisplayRule").forEach(o=>{const i=o.getAttribute("Id")??"";i&&n.push({id:i,steps:_i(o,t)})}),n}function _i(e,t){const n=[];return Le(e).forEach((o,i)=>{const r=pf(o,t);if(!r){n.push(Cs(o));return}n.push(r),t.add({source:o,generate:()=>bo(n[i]),fallback:()=>n[i]=Cs(o),phase:r.kind==="OrRule"?1:0})}),n}function Cs(e){return{kind:"RawRule",tagName:e.tagName,xml:Wt().serializeToString(e)}}function mf(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 tn(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 ue(e,t){return e.getAttribute(t)??""}function pf(e,t){const n=mf(e);switch(e.tagName){case"OrRule":{const o=Le(e);return o.some(i=>i.tagName!=="Or")?null:{kind:"OrRule",groups:o.map(i=>_i(i,t))}}case"SelectionCountRule":return{kind:"SelectionCountRule",minimum:tn(e,"Minimum"),maximum:tn(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:ue(e,"State"),...n};case"CommandClientTypeRule":return{kind:"CommandClientTypeRule",type:ue(e,"Type"),...n};case"CustomRule":{const o=di(e);return o?{kind:"CustomRule",library:ue(e,"Library"),functionName:ue(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:ue(e,"FeatureControlBit"),expectedValue:o,...n}}case"MiscellaneousPrivilegeRule":return{kind:"MiscellaneousPrivilegeRule",privilegeName:ue(e,"PrivilegeName"),privilegeDepth:We(e,"PrivilegeDepth"),...n};case"CrmClientTypeRule":return{kind:"CrmClientTypeRule",type:ue(e,"Type"),...n};case"FormTypeRule":return{kind:"FormTypeRule",type:ue(e,"Type"),...n};case"ValueRule":return{kind:"ValueRule",field:ue(e,"Field"),value:ue(e,"Value"),...n};case"SkuRule":return{kind:"SkuRule",sku:ue(e,"Sku"),...n};case"HideForTabletExperienceRule":return{kind:"HideForTabletExperienceRule",...n};case"OrganizationSettingRule":return{kind:"OrganizationSettingRule",setting:ue(e,"Setting"),...n};case"EntityPrivilegeRule":return{kind:"EntityPrivilegeRule",entityName:We(e,"EntityName"),appliesTo:We(e,"AppliesTo"),privilegeType:ue(e,"PrivilegeType"),privilegeDepth:ue(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:ue(e,"PropertyName"),propertyValue:o,...n}}case"DeviceTypeRule":return{kind:"DeviceTypeRule",type:ue(e,"Type"),...n};case"OptionSetRule":return{kind:"OptionSetRule",optionSet:ue(e,"OptionSet"),stateCode:ue(e,"StateCode"),objectTypeCode:ue(e,"ObjectTypeCode"),...n};case"RecordPrivilegeRule":return{kind:"RecordPrivilegeRule",privilegeType:ue(e,"PrivilegeType"),appliesTo:We(e,"AppliesTo"),...n};case"FormEntityContextRule":return{kind:"FormEntityContextRule",entityName:ue(e,"EntityName"),...n};case"PageRule":return{kind:"PageRule",address:ue(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:ue(e,"Type"),...n};case"OutlookVersionRule":return{kind:"OutlookVersionRule",version:ue(e,"Version"),...n};case"CrmOfflineAccessStateRule":return{kind:"CrmOfflineAccessStateRule",state:ue(e,"State"),...n};case"CrmOutlookClientTypeRule":return{kind:"CrmOutlookClientTypeRule",type:ue(e,"Type"),...n};case"CrmOutlookClientVersionRule":return{kind:"CrmOutlookClientVersionRule",major:parseInt(ue(e,"Major"),10),minor:tn(e,"Minor"),build:tn(e,"Build"),revision:tn(e,"Revision"),...n};default:return null}}function ff(e){const t=[];return e.querySelectorAll("LocLabel").forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const i=[];n.querySelectorAll("Title").forEach(r=>{const l=parseInt(r.getAttribute("languagecode")??"1033",10),a=r.getAttribute("description")??"";i.push({languageCode:l,description:a})}),t.push({id:o,titles:i})}),t}function Zn(e){return{controlIds:[...Xn(e)],containerIds:[...Qr(e)],locLabelIds:[...e.locLabels.keys()],hides:co(e),scalingStepIds:Oi(e).map(t=>t.id),commandIds:[...e.commandDefinitions.keys()],commandRefIds:[...ea(e)]}}async function $x(e){try{return Zn(await ui(e))}catch{return null}}function hf(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=yo(t,"HomepageGrid","");return{commands:n.commands,enableRules:n.enableRules,displayRules:n.displayRules}}function gf(){return window.dataverseAPI}async function No(e){const t=[];let n=e;for(;n;){const o=await gf().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 ui(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([No(`ribbondiffs?$select=diffid,difftype,rdx,sequence&$filter=${t}&$orderby=sequence asc,diffid asc`),No(`ribboncommands?$select=command,commanddefinition&$filter=${t}&$orderby=command asc`),No(`ribbonrules?$select=ruleid,ruletype,ruledefinition&$filter=${t}&$orderby=ruleid asc`)]);return op({diffs:n,commands:o,rules:i})}function mi(e){const t=[];for(const[n,o]of e.locLabels){const i=new DOMParser().parseFromString(o,"application/xml"),r=Array.from(i.querySelectorAll("Title")).map(l=>({languageCode:Number(l.getAttribute("languagecode")??1033),description:l.getAttribute("description")??""}));t.push({id:n,titles:r})}return t}function Is(e,t,n,o){const r=`${Hi()}.${Lt(e)}.${Lt(t)}.${Lt(n)}`;return Wi(r,o)}function qi(e,t,n){const i=`${Hi()}.${Lt(e)}.${Lt(t)}.Command`;return Wi(i,n)}function yn(e,t,n){const i=`${Hi()}.${Lt(e)}.${t}Rule`;return Wi(i,n)}function Rs(e){return e.replace(/\.Command$/,"").split(".").pop()||"Rule"}function Hi(){try{return ne.getState().publisherPrefix||"new"}catch{return"new"}}function Lt(e){return e.replace(/[^a-zA-Z0-9._]/g,"").replace(/^[^a-zA-Z]/,"x")}function Wi(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n++;return`${e}${n}`}function Sa(e,t,n,o,i){const r=o.replace(/[^a-zA-Z0-9_]/g,"")||"Button",l=`${e}.${t}.${n}.${r}`;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 Nx(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 Z=jt()(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 xo(e){return/\.AllEntities\./.test(e)||/\.VisualizationTab$/.test(e)}function pn(e){const t=e.filter(n=>!xo(n.id));return(t.find(n=>/\.MainTab$/.test(n.id))??t[0]??e[0])?.id}const ze="Mscrm.OpenRecordItem",wa=["HomepageGrid","SubGrid"],bf=/\.(HomepageGrid|SubGrid)\.OpenRecordItem\d*\.Button$/;function Ca(e){return e.commandId===ze&&bf.test(e.id)}function Gi(e){const t=[];for(const n of e?.tabs??[])for(const o of n.groups)for(const i of je(o))i.commandId===ze&&t.push({tabId:n.id,groupId:o.id,button:i});return t}function Ia(e){return Gi(e).filter(t=>Ca(t.button))}function Ra(e){const t=e.button.origin;return t==="unmanaged"?"yours":t===void 0?"unknown":"theirs"}function ja(e){const t=e?.tabs??[],n=pn(t.filter(r=>r.groups.length>0)),o=t.find(r=>r.id===n),i=o?.groups.find(r=>/\.Management$/.test(r.id))??o?.groups[0];return o&&i?{tabId:o.id,groupId:i.id}:null}function yf(){return{id:ze,enableRules:[],displayRules:[],actions:[{kind:"javascript",library:"$webresource:",functionName:"YourNamespace.openRecord",params:[{kind:"CrmParameter",value:"SelectedControlSelectedItemReferences"}]}]}}function xf(e){for(const t of e.actions){if(t.kind!=="javascript")continue;if(!t.library.trim().replace(/^\$webresource:/i,"").trim()||!t.functionName.trim())return`${ze} has a JavaScript action without a web resource or function — set them in the Command Editor, or turn the override off`}return null}const vf=["Mscrm.HideOnModern","Mscrm.ShowOnlyOnModern"];function nn(e,t){const n=new Set;for(const o of[t,e.baseline])for(const i of Object.values(o??{}))for(const r of i.tabs){n.add(r.id);for(const l of r.groups){n.add(l.id);for(const a of je(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 Qn(e,t){return Ui(e,t)?.containerIds}function Ui(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 xe(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 Sf=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)<Sf)return{...t,past:[...e.past.slice(0,-1),{...i,...n}],mutationsSincePublish:e.mutationsSincePublish+1};const r={...n,coalesceKey:o,snapshot:et(e)};return{...t,past:[...e.past,r].slice(-80),future:[],mutationsSincePublish:e.mutationsSincePublish+1}}function ve(e,t,n,o){const i=Pe(e.ribbons);return t(i),ke(e,{ribbons:i},n,o)}function _n(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 on(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 js={entity:null,application:null},To={entity:[],application:[]},$s=["HomepageGrid","SubGrid","Form"];function wf(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 Cf(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 r=o>0?e[o-1].sequence:0,l=i<e.length-1?e[i+1].sequence:1/0;if(l-r-1>=i-o+1){let d=r;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 ko={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 r=e[t].tabs.find(a=>a.id===n)?.groups.find(a=>a.id===o),l=Qt(r,i);return r&&l?{group:r,button:l}:void 0}function Fe(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob===!0&&n.custom!==!0}function Xi(e,t,n){return n.origin!=="unmanaged"&&!n.hidden&&n.kind!=="flyout"&&n.kind!=="splitButton"&&!Ze(n.kind)&&!Fe(e,t,n)}function If(e,t,n){for(const o of e.baseline[t].tabs)for(const i of o.groups){const r=i.buttons.find(l=>l.id===n);if(r)return r}}function Rf(e,t,n){if(t.location!==n.location||t.tabId!==n.tabId||t.groupId!==n.groupId)return!1;const o=e.buttons.findIndex(r=>r.id===t.buttonId),i=e.buttons[o+1]?.id;return n.beforeButtonId?n.beforeButtonId===t.buttonId||n.beforeButtonId===i:i===void 0}const eo=/^\$LocLabels:/;function jf(e){if(!e)return;const t=o=>o&&!eo.test(o)?o:void 0,n={};for(const[o,i]of Object.entries(e.attributes))o!=="Id"&&!eo.test(i)&&(n[o]=i);return{...e,labelToken:t(e.labelToken),tooltipTitleToken:t(e.tooltipTitleToken),tooltipBodyToken:t(e.tooltipBodyToken),attributes:n}}const Ao=(e,t)=>({entity:e.entity.filter(n=>n!==t),application:e.application.filter(n=>n!==t)});function Ns(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 O=jt()(Hm((e,t)=>({ribbons:Pe(ko),baseline:Pe(ko),baselineCommands:[],baselineEnableRules:[],baselineDisplayRules:[],baselineLocLabels:[],layers:{...js},pendingUnhides:{entity:[],application:[]},orphans:{entity:[],application:[]},pendingOrphanDeletes:{entity:[],application:[]},baseLanguageCode:1033,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]},xe("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:{...js,...n.layers??{}},pendingUnhides:{...To},orphans:{entity:[],application:[],...n.orphans??{}},pendingOrphanDeletes:{...To},baseLanguageCode:n.baseLanguageCode??1033,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(r=>{const l=c=>{const d=r.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({...r,...a}))===JSON.stringify(et(r))?r:ke(r,a,xe("restored","unsaved changes",o,"history"))})},resetWorkspace(){t().loadWorkspace({ribbons:ko,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:_n({...n,...o.snapshot})?n.mutationsSincePublish+1:0})},restore(n){const o=t(),{past:i}=o;if(n<0||n>=i.length||_e)return;let r=et(o),l=o.future;for(let c=i.length-1;c>=n;c--)l=[{...i[c],coalesceKey:void 0,snapshot:r},...l],r=i[c].snapshot;const a=i.length-n;e({...r,past:i.slice(0,n),future:l,mutationsSincePublish:_n({...o,...r})?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(r=>({past:[...r.past,{...i,snapshot:o}].slice(-80),future:[],mutationsSincePublish:r.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=If(i,n.location,a.id)?.origin;if(d!==void 0&&d!=="unmanaged"&&!a.menu&&!Mt(a.kind)&&!Fe(n.location,n.tabId,a)){if(Rf(l,n,o))return null;const p=y=>(ie.getState().logWarn("ribbon",`Can't move ${a.id}: ${y}`),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:b}=ne.getState(),v=f?.publisherPrefix?.trim()||b?.trim()||"new";let x=null,h=!1;return t().batch(()=>{const y=t().customiseButton(n.location,n.tabId,n.groupId,n.buttonId,v);y&&(h=!0,x=t().moveButton({...n,buttonId:y},o),ie.getState().logInfo("ribbon",`${a.id} isn't yours, so it can't be moved: moved your copy ${y} instead and hid the original.`))}),h&&!x&&t().undo(),h?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=>ve(p,f=>{const b=f[n.location].tabs.find($=>$.id===n.tabId);if(!b)return;const v=b.groups.find($=>$.id===n.groupId);if(!v)return;const x=v.buttons.findIndex($=>$.id===n.buttonId);if(x===-1||Fe(n.location,n.tabId,v.buttons[x]))return;const y=(n.tabId===o.tabId&&n.location===o.location?b:f[o.location].tabs.find($=>$.id===o.tabId))?.groups.find($=>$.id===o.groupId);if(!y)return;const[w]=v.buttons.splice(x,1),I=o.beforeButtonId?y.buttons.findIndex($=>$.id===o.beforeButtonId):y.buttons.length,S=I<0?y.buttons.length:I;y.buttons.splice(S,0,w);const C=wf(w.sequence,y.buttons[S-1]?.sequence,y.buttons[S+1]?.sequence);if(C!==void 0)w.sequence=C;else{const $=new Set(p.layers[o.location==="Application"?"application":"entity"]?.controlIds??[]),R=new Set(p.baseline[o.location].tabs.flatMap(E=>E.groups.flatMap(T=>T.buttons.map(_=>_.id))));Cf(y.buttons,S,E=>E===w||$.has(E.id)||!R.has(E.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,r,l){const c=Object.values(l).every(d=>typeof d=="string")?`button:${n}:${r}:${Object.keys(l).sort().join(",")}`:void 0;e(d=>ve(d,u=>{const p=Qe(u,n,o,i,r)?.button;p&&(Fe(n,o,p)||(Object.assign(p,l),Mt(p.kind)&&!p.menu&&(p.menu=Ro(p.id))))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l.label??r,detail:Object.keys(l).join(", "),icon:"edit",color:"info"},c))},deleteButton(n,o,i,r){const l=t(),a=Qe(l.ribbons,n,o,i,r)?.button;if(a&&!$n(a,l.baseline[n])){ie.getState().logWarn("ribbon",`"${a.label}" (${r}) was not deleted: only your own buttons can be deleted — hide it instead.`);return}e(c=>ve(c,d=>{const u=Qe(d,n,o,i,r);if(!u)return;const{group:p,button:f}=u;Fe(n,o,f)||ia(p,r)||(p.buttons=p.buttons.filter(b=>b.id!==r))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:r,detail:i,icon:"delete",color:"danger"}))},addMenuItem({location:n,tabId:o,groupId:i,parentId:r,sectionId:l,item:a}){e(c=>ve(c,d=>{const u=Qe(d,n,o,i,r)?.button;if(!u||Fe(n,o,u))return;u.menu=u.menu??Ro(u.id),u.menu.sections.length===0&&u.menu.sections.push(oi(u.id,[]));const p=u.menu.sections.find(b=>b.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 ${r}`,icon:"add",color:"success"}))},addMenuSection(n,o,i,r,l){e(a=>ve(a,c=>{const d=Qe(c,n,o,i,r)?.button;!d||Fe(n,o,d)||(d.menu=d.menu??{id:`${d.id}.Menu`,sections:[]},d.menu.sections.push(oi(d.id,d.menu.sections,l)))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:l??"Menu section",detail:`menu of ${r}`,icon:"add",color:"success"}))},setMenuSectionProp(n,o,i,r,l,a){e(c=>ve(c,d=>{const u=Qe(d,n,o,i,r)?.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,r,l){e(a=>ve(a,c=>{const d=Qe(c,n,o,i,r)?.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 ${r}`,icon:"delete",color:"danger"}))},duplicateButton(n,o,i,r){e(l=>ve(l,a=>{const c=Qe(a,n,o,i,r);if(c){const{group:d,button:u}=c;if(Fe(n,o,u))return;const p=zi(u.source?.labelToken),f={...Kn(u,`${u.id}_copy_${Date.now()}`),label:Ze(u.kind)||p?u.label:`${u.label} (copy)`,sequence:u.sequence+5},b=Vn(d,r),v=b?b.section.controls:d.buttons,x=v.findIndex(h=>h.id===r);v.splice(x+1,0,f)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:r,detail:i,icon:"copy",color:"info"}))},createButton({tabId:n,groupId:o,location:i,button:r}){e(l=>ve(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(v=>v.sequence)),p=Math.max(0,...d.buttons.map(v=>v.sequence))+10,f=r.sequence!==void 0&&!u.has(r.sequence)?r.sequence:p,b={...r,id:r.id??`new_${Date.now()}`,label:r.label??"New Button",kind:r.kind??"button",sequence:f,templateAlias:r.templateAlias??"o1",commandId:r.commandId??"",hidden:r.hidden??!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"};Mt(b.kind)&&!b.menu&&(b.menu=Ro(b.id)),d.buttons.push(b)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:r.label??"New Button",detail:o,icon:"add",color:"success"}))},createGroup({tabId:n,location:o,group:i}){e(r=>ve(r,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??Is(d,`${o}.${i.label??"New Group"}`,"Group",nn(r,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,r){e(l=>ve(l,a=>{const d=a[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===i);d&&(d.label=r)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:i,detail:r,icon:"edit",color:"info"}))},duplicateGroup(n,o,i){e(r=>ve(r,l=>{const a=l[n].tabs.find(f=>f.id===o);if(!a)return;const c=a.groups.find(f=>f.id===i);if(!c)return;const d=`_copy_${Date.now()}`,u={...JSON.parse(JSON.stringify(c)),id:`${c.id}${d}`,label:`${ce(c.label,r.locLabels,r.baseLanguageCode)} (copy)`,source:void 0,description:void 0,sequence:c.sequence+5,buttons:c.buttons.map(f=>Kn(f,`${f.id}${d}`))},p=a.groups.findIndex(f=>f.id===i);a.groups.splice(p+1,0,u)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:i,detail:o,icon:"copy",color:"info"}))},setGroupTemplate(n,o,i,r){e(l=>ve(l,a=>{const d=a[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===i);d&&(d.template=r)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:i,detail:`template → ${r}`,icon:"edit",color:"info"}))},deleteGroup(n,o,i){const r=t(),l=r.ribbons[n].tabs.find(a=>a.id===o)?.groups.find(a=>a.id===i);if(l&&!Pi(l,r.baseline[n],Qn(r,n))){ie.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=>ve(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&&nn(i,i.ribbons).has(o.id)?{}:ve(i,r=>{const l=r[n],a=n==="Application"?"global":l.entityLogicalName,c=o.id??Is(a,`${n}.${o.label??"New Tab"}`,"Tab",nn(i,r)),d=ra({...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:aa(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(r=>ve(r,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(),r=i.ribbons[n].tabs.find(l=>l.id===o);if(r&&!ya(r,i.baseline[n],Qn(i,n))){ie.getState().logWarn("ribbon",`Tab "${r.label}" (${o}) was not deleted: only your own tabs, with only your own groups and buttons in them, can be deleted.`);return}e(l=>ve(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=>ve(i,r=>{const l=r[n].tabs;r[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(r=>ve(r,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(r=>ve(r,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,r){e(l=>ve(l,a=>{const c=Qe(a,n,o,i,r)?.button;c&&(Fe(n,o,c)||(c.hidden=!0))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"hid",target:r,detail:i,icon:"eye_off",color:"warn"}))},customizeOobButton(n,o,i,r){e(l=>ve(l,a=>{const c=Qe(a,n,o,i,r)?.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:r,detail:"OOB override",icon:"edit",color:"info"}))},customiseButton(n,o,i,r,l){const a=t(),c=a.ribbons[n].tabs.find(h=>h.id===o)?.groups.find(h=>h.id===i)?.buttons.find(h=>h.id===r);if(!c||!Xi(n,o,c))return null;const d=nn(a,a.ribbons),u=`${(l||"new").trim()}.${c.id}`;let p=u;for(let h=2;d.has(p);h++)p=`${u}.${h}`;const f=[],b=[],v=[[c.source?.labelToken,mo(p)],[c.source?.tooltipTitleToken,po(p)],[c.source?.tooltipBodyToken,fo(p)]];for(const[h,y]of v){if(!h||!eo.test(h))continue;const w=a.locLabels.find(I=>I.id===h.replace(eo,""));w?f.push({id:y,titles:w.titles.map(I=>({...I}))}):b.push(h)}b.length>0&&ie.getState().logWarn("ribbon",`Customise button ${c.id}: the translations of ${b.join(", ")} aren't loaded, so the copy ${p} gets its text in the base language only. Add the other languages in the Localization editor.`);const x=new Set(f.map(h=>h.id));return e(h=>{const y=Pe(h.ribbons),w=y[n].tabs.find(R=>R.id===o)?.groups.find(R=>R.id===i),I=w?.buttons.findIndex(R=>R.id===r)??-1;if(!w||I<0)return{};const S=w.buttons[I],C={...S,id:p,source:jf(S.source),hidden:!1,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0},$=w.buttons[I+1]?.sequence;return($===void 0||S.sequence+1<$)&&(C.sequence=S.sequence+1),S.hidden=!0,w.buttons.splice(I+1,0,C),ke(h,{ribbons:y,...f.length>0?{locLabels:[...h.locLabels.filter(R=>!x.has(R.id)),...f]}:{}},xe("customised",r,`copied to ${p}, original hidden`+(b.length>0?" (translations not loaded: base language only)":""),"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(r=>r!==n),n],uncustomisedCommandIds:Ao(i.uncustomisedCommandIds,n)},xe("customised",n,"command copied to your layer on publish","code"))),!0)},uncustomiseCommand(n,o){e(i=>ke(i,{commands:Ns(i,n),customisedCommandIds:i.customisedCommandIds.filter(r=>r!==n),uncustomisedCommandIds:{...Ao(i.uncustomisedCommandIds,n),[o]:[...i.uncustomisedCommandIds[o].filter(r=>r!==n),n]}},xe("uncustomised",n,`command removed from the ${o==="entity"?"table's":"application ribbon's"} layer on publish`,"arrow_undo")))},discardCommandChanges(n){const o=t(),i=Ns(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:Ao(l.uncustomisedCommandIds,n)},xe("discarded",n,"command changes","arrow_undo")))},setOpenRecordOverride(n,o,i){if(!wa.includes(n))return!1;const r=t(),l=r.ribbons[n],a=Ia(l);if(o){if(a.length>0)return!0;const c=ja(l);if(!c)return!1;const d=nn(r,r.ribbons);for(const p of r.commands)d.add(p.id);const{id:u}=Sa(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 ${ze} action for the selected row, as opening a row does.`,kind:"button",templateAlias:"o1",commandId:ze,hidden:!1,oob:!1,custom:!0,managed:!1}}),t().commands.some(p=>p.id===ze)||t().upsertCommand(yf())}),!0}return a.length===0?!0:a.some(c=>Ra(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=>Gi(u).length>0)&&!c.baselineCommands.some(u=>u.id===ze)&&e(u=>ke(u,{commands:u.commands.filter(p=>p.id!==ze)},xe("removed",ze,"grid open override","delete","danger")))}),!0)},hideWithDisplayRules(n){const o=n?t().commands.find(r=>r.id===n):void 0;if(!o)return!1;const i=[...o.displayRules];for(const r of vf)i.includes(r)||i.push(r);return e(r=>{const l=on(r.commands,{...o,displayRules:i});return l?ke(r,{commands:l},xe("hid",o.id,"with display rules","eye_off","warn")):r}),!0},upsertCommand(n){e(o=>{const i=on(o.commands,n);if(!i)return o;const r=i.length>o.commands.length;return ke(o,{commands:i},r?xe("added",n.id,"command","add","success"):xe("edited",n.id,"command","edit"),r?void 0:`command:${n.id}`)})},renameCommandId(n,o){const i=t();return!n||!o||n===o?!0:i.commands.some(r=>r.id===o)?!1:(e(r=>{const l=Pe(r.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 je(u))p.commandId===n&&(p.commandId=o),p.source?.xml&&(p.source.xml=tp(p.source.xml,n,o));const a=r.commands.map(c=>c.id===n?{...c,id:o}:c);return ke(r,{ribbons:l,commands:a},xe("renamed",n,`command -> ${o}`,"edit"))}),!0)},upsertDisplayRule(n){e(o=>{const i=on(o.displayRules,n);if(!i)return o;const r=i.length>o.displayRules.length;return ke(o,{displayRules:i},r?xe("added",n.id,"display rule","add","success"):xe("edited",n.id,"display rule","edit"),r?void 0:`displayRule:${n.id}`)})},renameDisplayRuleId(n,o){const i=t();return!n||!o||n===o?!0:i.displayRules.some(r=>r.id===o)?!1:(e(r=>{const l=r.displayRules.map(c=>c.id===n?{...c,id:o}:c),a=r.commands.map(c=>({...c,displayRules:c.displayRules.map(d=>d===n?o:d)}));return ke(r,{displayRules:l,commands:a},xe("renamed",n,`display rule -> ${o}`,"edit"))}),!0)},upsertEnableRule(n){e(o=>{const i=on(o.enableRules,n);if(!i)return o;const r=i.length>o.enableRules.length;return ke(o,{enableRules:i},r?xe("added",n.id,"enable rule","add","success"):xe("edited",n.id,"enable rule","edit"),r?void 0:`enableRule:${n.id}`)})},renameEnableRuleId(n,o){const i=t();return!n||!o||n===o?!0:i.enableRules.some(r=>r.id===o)?!1:(e(r=>{const l=r.enableRules.map(c=>c.id===n?{...c,id:o}:c),a=r.commands.map(c=>({...c,enableRules:c.enableRules.map(d=>d===n?o:d)}));return ke(r,{enableRules:l,commands:a},xe("renamed",n,`enable rule -> ${o}`,"edit"))}),!0)},upsertLocLabel(n){e(o=>{const i=on(o.locLabels,n);return i?ke(o,{locLabels:i},xe("edited",n.id,"label","translate"),`locLabel:${n.id}`):o})},setLayerHideUnhidden(n,o,i){e(r=>{if(r.pendingUnhides[n].includes(o)===i)return r;const l=r.pendingUnhides[n].filter(a=>a!==o);return i&&l.push(o),ke(r,{pendingUnhides:{...r.pendingUnhides,[n]:l}},i?xe("un-hid",o,"on publish","eye"):xe("kept hidden",o,"by customizations","eye_off"))})},setOrphanDeleted(n,o,i){e(r=>{const l=r.orphans[n].find(c=>c.id===o);if(!l||i&&l.recentPublish?.published||r.pendingOrphanDeletes[n].includes(o)===i)return r;const a=r.pendingOrphanDeletes[n].filter(c=>c!==o);return i&&a.push(o),ke(r,{pendingOrphanDeletes:{...r.pendingOrphanDeletes,[n]:a}},i?xe("deleted",o,"not on the canvas — removed on publish","delete","danger"):xe("kept",o,"not on the canvas","arrow_undo"))})},setLayerSnapshot(n,o){e(i=>({layers:{...i.layers,[n]:o}}))},markPublished(n,o){e(i=>{const r=Object.keys(i.ribbons),l=n??r,a=Pe(i.baseline),c=Pe(i.ribbons);let d=i.locLabels,u=i.baselineLocLabels;const p=(j,B)=>[...j.filter(N=>!B.some(W=>W.id===N.id)),...B];for(const[j,B]of Object.entries(o??{})){const N=j==="entity"?$s:["Application"];for(const U of N)l.includes(U)&&pp(c[U],B);const W=mi(B);d=p(d,W),u=p(u,JSON.parse(JSON.stringify(W)))}for(const j of l)a[j]=Pe(c)[j];const f=r.every(j=>l.includes(j)),b={...i.layers},v={...i.pendingUnhides},x={entity:[],application:[]},h=[["entity",$s.every(j=>l.includes(j))],["application",l.includes("Application")]];for(const[j,B]of h){const N=o?.[j];if(!B||!N)continue;const W=b[j],U=(X,Q)=>[...new Set([...X,...Q])];b[j]=W?{...W,containerIds:U(W.containerIds,Qr(N)),controlIds:U(W.controlIds,Xn(N)),locLabelIds:U(W.locLabelIds,new Set(N.locLabels.keys()))}:Zn(N)}for(const[j,B]of h){if(!B||v[j].length===0)continue;const N=b[j];N&&(b[j]={...N,hides:N.hides.filter(W=>!v[j].includes(W.location))}),x[j]=v[j],v[j]=[]}const y={...i.orphans},w={...i.pendingOrphanDeletes},I={entity:[],application:[]};for(const[j,B]of h)!B||w[j].length===0||(y[j]=y[j].filter(N=>!w[j].includes(N.id)),I[j]=w[j],w[j]=[]);const S={...i.uncustomisedCommandIds},C=[...i.reloadRequiredCommandIds],$={entity:[],application:[]};for(const[j,B]of h)if(B){for(const N of S[j])C.includes(N)||C.push(N);$[j]=S[j],S[j]=[]}const R=(j,B)=>({entity:j.entity.filter(N=>!B.entity.includes(N)),application:j.application.filter(N=>!B.application.includes(N))}),E=j=>({...j,snapshot:{...j.snapshot,pendingUnhides:R(j.snapshot.pendingUnhides,x),pendingOrphanDeletes:R(j.snapshot.pendingOrphanDeletes??To,I),uncustomisedCommandIds:R(j.snapshot.uncustomisedCommandIds,$)}}),T=[x,$,I].reduce((j,B)=>j+B.entity.length+B.application.length,0)>0,_=i.past.map((j,B)=>{const N=T?E(j):j;return B===i.past.length-1&&N.coalesceKey?{...N,coalesceKey:void 0}:N}),D={ribbons:c,locLabels:d,baselineLocLabels:u,baseline:a,layers:b,pendingUnhides:v,uncustomisedCommandIds:S,orphans:y,pendingOrphanDeletes:w,...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:[]}:{}},L=_n({...i,...D});return{...D,past:_,future:T?i.future.map(E):i.future,reloadRequiredCommandIds:C,mutationsSincePublish:L?Math.max(1,i.mutationsSincePublish):0}})}})));_m(()=>{O.getState().resetWorkspace(),Z.getState().clearSelection()});var Se=Uint8Array,He=Uint16Array,Vi=Int32Array,vo=new Se([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]),So=new Se([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]),pi=new Se([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$a=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 Vi(n[30]),o=1;o<30;++o)for(var r=n[o];r<n[o+1];++r)i[r]=r-n[o]<<5|o;return{b:n,r:i}},Na=$a(vo,2),Ta=Na.b,fi=Na.r;Ta[28]=258,fi[258]=28;var ka=$a(So,0),$f=ka.b,Ts=ka.r,hi=new He(32768);for(var he=0;he<32768;++he){var ut=(he&43690)>>1|(he&21845)<<1;ut=(ut&52428)>>2|(ut&13107)<<2,ut=(ut&61680)>>4|(ut&3855)<<4,hi[he]=((ut&65280)>>8|(ut&255)<<8)>>1}var ot=(function(e,t,n){for(var o=e.length,i=0,r=new He(t);i<o;++i)e[i]&&++r[e[i]-1];var l=new He(t);for(i=1;i<t;++i)l[i]=l[i-1]+r[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[hi[p]>>c]=d}else for(a=new He(o),i=0;i<o;++i)e[i]&&(a[i]=hi[l[e[i]-1]++]>>15-e[i]);return a}),bt=new Se(288);for(var he=0;he<144;++he)bt[he]=8;for(var he=144;he<256;++he)bt[he]=9;for(var he=256;he<280;++he)bt[he]=7;for(var he=280;he<288;++he)bt[he]=8;var xn=new Se(32);for(var he=0;he<32;++he)xn[he]=5;var Nf=ot(bt,9,0),Tf=ot(bt,9,1),kf=ot(xn,5,0),Af=ot(xn,5,1),Do=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},Eo=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ki=function(e){return(e+7)/8|0},Nn=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Se(e.subarray(t,n))},Df=["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"],Oe=function(e,t,n){var o=new Error(t||Df[e]);if(o.code=e,Error.captureStackTrace&&Error.captureStackTrace(o,Oe),!n)throw o;return o},Ef=function(e,t,n,o){var i=e.length,r=o?o.length:0;if(!i||t.f&&!t.l)return n||new Se(0);var l=!n,a=l||t.i!=2,c=t.i;l&&(n=new Se(i*3));var d=function(Me){var z=n.length;if(Me>z){var H=new Se(Math.max(z*2,Me));H.set(n),n=H}},u=t.f||0,p=t.p||0,f=t.b||0,b=t.l,v=t.d,x=t.m,h=t.n,y=i*8;do{if(!b){u=Xe(e,p,1);var w=Xe(e,p+1,3);if(p+=3,w)if(w==1)b=Tf,v=Af,x=9,h=5;else if(w==2){var $=Xe(e,p,31)+257,R=Xe(e,p+10,15)+4,E=$+Xe(e,p+5,31)+1;p+=14;for(var T=new Se(E),_=new Se(19),D=0;D<R;++D)_[pi[D]]=Xe(e,p+D*3,7);p+=R*3;for(var L=Do(_),j=(1<<L)-1,B=ot(_,L,1),D=0;D<E;){var N=B[Xe(e,p,j)];p+=N&15;var I=N>>4;if(I<16)T[D++]=I;else{var W=0,U=0;for(I==16?(U=3+Xe(e,p,3),p+=2,W=T[D-1]):I==17?(U=3+Xe(e,p,7),p+=3):I==18&&(U=11+Xe(e,p,127),p+=7);U--;)T[D++]=W}}var X=T.subarray(0,$),Q=T.subarray($);x=Do(X),h=Do(Q),b=ot(X,x,1),v=ot(Q,h,1)}else Oe(1);else{var I=Ki(p)+4,S=e[I-4]|e[I-3]<<8,C=I+S;if(C>i){c&&Oe(0);break}a&&d(f+S),n.set(e.subarray(I,C),f),t.b=f+=S,t.p=p=C*8,t.f=u;continue}if(p>y){c&&Oe(0);break}}a&&d(f+131072);for(var q=(1<<x)-1,F=(1<<h)-1,J=p;;J=p){var W=b[Eo(e,p)&q],G=W>>4;if(p+=W&15,p>y){c&&Oe(0);break}if(W||Oe(2),G<256)n[f++]=G;else if(G==256){J=p,b=null;break}else{var g=G-254;if(G>264){var D=G-257,k=vo[D];g=Xe(e,p,(1<<k)-1)+Ta[D],p+=k}var A=v[Eo(e,p)&F],te=A>>4;A||Oe(3),p+=A&15;var Q=$f[te];if(te>3){var k=So[te];Q+=Eo(e,p)&(1<<k)-1,p+=k}if(p>y){c&&Oe(0);break}a&&d(f+131072);var de=f+g;if(f<Q){var Te=r-Q,be=Math.min(Q,de);for(Te+f<0&&Oe(3);f<be;++f)n[f]=o[Te+f]}for(;f<de;++f)n[f]=n[f-Q]}}t.l=b,t.p=J,t.b=f,t.f=u,b&&(u=1,t.m=x,t.d=v,t.n=h)}while(!u);return f!=n.length&&l?Nn(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},sn=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},Oo=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,r=n.slice();if(!i)return{t:Da,l:0};if(i==1){var l=new Se(n[0].s+1);return l[n[0].s]=1,{t:l,l:1}}n.sort(function(C,$){return C.f-$.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=r[0].s,o=1;o<i;++o)r[o].s>f&&(f=r[o].s);var b=new He(f+1),v=gi(n[u-1],b,0);if(v>t){var o=0,x=0,h=v-t,y=1<<h;for(r.sort(function($,R){return b[R.s]-b[$.s]||$.f-R.f});o<i;++o){var w=r[o].s;if(b[w]>t)x+=y-(1<<v-b[w]),b[w]=t;else break}for(x>>=h;x>0;){var I=r[o].s;b[I]<t?x-=1<<t-b[I]++-1:++o}for(;o>=0&&x;--o){var S=r[o].s;b[S]==t&&(--b[S],++x)}v=t}return{t:new Se(b),l:v}},gi=function(e,t,n){return e.s==-1?Math.max(gi(e.l,t,n+1),gi(e.r,t,n+1)):t[e.s]=n},ks=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new He(++t),o=0,i=e[0],r=1,l=function(c){n[o++]=c},a=1;a<=t;++a)if(e[a]==i&&a!=t)++r;else{if(!i&&r>2){for(;r>138;r-=138)l(32754);r>2&&(l(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(l(i),--r;r>6;r-=6)l(8304);r>2&&(l(r-3<<5|8208),r=0)}for(;r--;)l(i);r=1,i=e[a]}return{c:n.subarray(0,o),n:t}},rn=function(e,t){for(var n=0,o=0;o<t.length;++o)n+=e[o]*t[o];return n},Aa=function(e,t,n){var o=n.length,i=Ki(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 r=0;r<o;++r)e[i+r+4]=n[r];return(i+4+o)*8},As=function(e,t,n,o,i,r,l,a,c,d,u){it(t,u++,n),++i[256];for(var p=Oo(i,15),f=p.t,b=p.l,v=Oo(r,15),x=v.t,h=v.l,y=ks(f),w=y.c,I=y.n,S=ks(x),C=S.c,$=S.n,R=new He(19),E=0;E<w.length;++E)++R[w[E]&31];for(var E=0;E<C.length;++E)++R[C[E]&31];for(var T=Oo(R,7),_=T.t,D=T.l,L=19;L>4&&!_[pi[L-1]];--L);var j=d+5<<3,B=rn(i,bt)+rn(r,xn)+l,N=rn(i,f)+rn(r,x)+l+14+3*L+rn(R,_)+2*R[16]+3*R[17]+7*R[18];if(c>=0&&j<=B&&j<=N)return Aa(t,u,e.subarray(c,c+d));var W,U,X,Q;if(it(t,u,1+(N<B)),u+=2,N<B){W=ot(f,b,0),U=f,X=ot(x,h,0),Q=x;var q=ot(_,D,0);it(t,u,I-257),it(t,u+5,$-1),it(t,u+10,L-4),u+=14;for(var E=0;E<L;++E)it(t,u+3*E,_[pi[E]]);u+=3*L;for(var F=[w,C],J=0;J<2;++J)for(var G=F[J],E=0;E<G.length;++E){var g=G[E]&31;it(t,u,q[g]),u+=_[g],g>15&&(it(t,u,G[E]>>5&127),u+=G[E]>>12)}}else W=Nf,U=bt,X=kf,Q=xn;for(var E=0;E<a;++E){var k=o[E];if(k>255){var g=k>>18&31;sn(t,u,W[g+257]),u+=U[g+257],g>7&&(it(t,u,k>>23&31),u+=vo[g]);var A=k&31;sn(t,u,X[A]),u+=Q[A],A>3&&(sn(t,u,k>>5&8191),u+=So[A])}else sn(t,u,W[k]),u+=U[k]}return sn(t,u,W[256]),u+U[256]},Of=new Vi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Da=new Se(0),zf=function(e,t,n,o,i,r){var l=r.z||e.length,a=new Se(o+l+5*(1+Math.ceil(l/7e3))+i),c=a.subarray(o,a.length-i),d=r.l,u=(r.r||0)&7;if(t){u&&(c[0]=r.r>>3);for(var p=Of[t-1],f=p>>13,b=p&8191,v=(1<<n)-1,x=r.p||new He(32768),h=r.h||new He(v+1),y=Math.ceil(n/3),w=2*y,I=function(oe){return(e[oe]^e[oe+1]<<y^e[oe+2]<<w)&v},S=new Vi(25e3),C=new He(288),$=new He(32),R=0,E=0,T=r.i||0,_=0,D=r.w||0,L=0;T+2<l;++T){var j=I(T),B=T&32767,N=h[j];if(x[B]=N,h[j]=B,D<=T){var W=l-T;if((R>7e3||_>24576)&&(W>423||!d)){u=As(e,c,0,S,C,$,E,_,L,T-L,u),_=R=E=0,L=T;for(var U=0;U<286;++U)C[U]=0;for(var U=0;U<30;++U)$[U]=0}var X=2,Q=0,q=b,F=B-N&32767;if(W>2&&j==I(T-F))for(var J=Math.min(f,W)-1,G=Math.min(32767,T),g=Math.min(258,W);F<=G&&--q&&B!=N;){if(e[T+X]==e[T+X-F]){for(var k=0;k<g&&e[T+k]==e[T+k-F];++k);if(k>X){if(X=k,Q=F,k>J)break;for(var A=Math.min(F,k-2),te=0,U=0;U<A;++U){var de=T-F+U&32767,Te=x[de],be=de-Te&32767;be>te&&(te=be,N=de)}}}B=N,N=x[B],F+=B-N&32767}if(Q){S[_++]=268435456|fi[X]<<18|Ts[Q];var Me=fi[X]&31,z=Ts[Q]&31;E+=vo[Me]+So[z],++C[257+Me],++$[z],D=T+X,++R}else S[_++]=e[T],++C[e[T]]}}for(T=Math.max(T,D);T<l;++T)S[_++]=e[T],++C[e[T]];u=As(e,c,d,S,C,$,E,_,L,T-L,u),d||(r.r=u&7|c[u/8|0]<<3,u-=7,r.h=h,r.p=x,r.i=T,r.w=D)}else{for(var T=r.w||0;T<l+d;T+=65535){var H=T+65535;H>=l&&(c[u/8|0]=d,H=l),u=Aa(c,u+1,e.subarray(T,H))}r.i=l}return Nn(a,0,o+Ki(u)+i)},Bf=(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})(),Mf=function(){var e=-1;return{p:function(t){for(var n=e,o=0;o<t.length;++o)n=Bf[n&255^t[o]]^n>>>8;e=n},d:function(){return~e}}},Lf=function(e,t,n,o,i){if(!i&&(i={l:1},t.dictionary)){var r=t.dictionary.subarray(-32768),l=new Se(r.length+e.length);l.set(r),l.set(e,r.length),e=l,i.w=r.length}return zf(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)},Ea=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},zo=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 Oa(e,t){return Lf(e,t||{},0,0)}function za(e,t){return Ef(e,{i:2},t&&t.out,t&&t.dictionary)}var Ba=function(e,t,n,o){for(var i in e){var r=e[i],l=t+i,a=o;Array.isArray(r)&&(a=Ea(o,r[1]),r=r[0]),ArrayBuffer.isView(r)?n[l]=[r,a]:(n[l+="/"]=[new Se(0),a],Ba(r,l,n,o))}},Ds=typeof TextEncoder<"u"&&new TextEncoder,bi=typeof TextDecoder<"u"&&new TextDecoder,Pf=0;try{bi.decode(Da,{stream:!0}),Pf=1}catch{}var Ff=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:Nn(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 to(e,t){if(t){for(var n=new Se(e.length),o=0;o<e.length;++o)n[o]=e.charCodeAt(o);return n}if(Ds)return Ds.encode(e);for(var i=e.length,r=new Se(e.length+(e.length>>1)),l=0,a=function(u){r[l++]=u},o=0;o<i;++o){if(l+5>r.length){var c=new Se(l+8+(i-o<<1));c.set(r),r=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 Nn(r,0,l)}function vn(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(bi)return bi.decode(e);var i=Ff(e),r=i.s,n=i.r;return n.length&&Oe(8),r}}var _f=function(e,t){return t+30+tt(e,t+26)+tt(e,t+28)},qf=function(e,t,n){var o=tt(e,t+28),i=tt(e,t+30),r=vn(e.subarray(t+46,t+46+o),!(tt(e,t+8)&2048)),l=t+46+o,a=Hf(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,r,l+i+tt(e,t+32),u]},Hf=function(e,t,n,o,i,r,l){var a=i==4294967295,c=r==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?zo(e,t+4+8*c):i,c?zo(e,t+4):r,d?zo(e,t+4+8*(c+a)):l,1];o<2&&Oe(13)}return[i,r,l,0]},yi=function(e){var t=0;if(e)for(var n in e){var o=e[n].length;o>65535&&Oe(9),t+=o+4}return t},Es=function(e,t,n,o,i,r,l,a){var c=o.length,d=n.extra,u=a&&a.length,p=yi(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|(r<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),b=f.getFullYear()-1980;if((b<0||b>119)&&Oe(10),De(e,t,b<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,r!=-1&&(De(e,t,n.crc),De(e,t+4,r<0?-r-2:r),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 v in d){var x=d[v],h=x.length;De(e,t,+v),De(e,t+2,h),e.set(x,t+4),t+=4+h}return u&&(e.set(a,t),t+=u),t},Wf=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 Tx(e,t){t||(t={});var n={},o=[];Ba(e,"",n,t);var i=0,r=0;for(var l in n){var a=n[l],c=a[0],d=a[1],u=d.level==0?0:8,p=to(l),f=p.length,b=d.comment,v=b&&to(b),x=v&&v.length,h=yi(d.extra);f>65535&&Oe(11);var y=u?Oa(c,d):c,w=y.length,I=Mf();I.p(c),o.push(Ea(d,{size:c.length,crc:I.d(),c:y,f:p,m:v,u:f!=l.length||v&&b.length!=x,o:i,compression:u})),i+=30+f+h+w,r+=76+2*(f+h)+(x||0)+w}for(var S=new Se(r+22),C=i,$=r-i,R=0;R<o.length;++R){var p=o[R];Es(S,p.o,p,p.f,p.u,p.c.length);var E=30+p.f.length+yi(p.extra);S.set(p.c,p.o+E),Es(S,i,p,p.f,p.u,p.c.length,p.o,p.m),i+=16+E+(p.m?p.m.length:0)}return Wf(S,i,o.length,$,C),S}function Gf(e,t){for(var n={},o=e.length-22;Ge(e,o)!=101010256;--o)(!o||e.length-o>65558)&&Oe(13);var i=tt(e,o+8);if(!i)return{};var r=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),r=Ge(e,a+48))}for(var c=0;c<i;++c){var d=qf(e,r,l),u=d[0],p=d[1],f=d[2],b=d[3],v=d[4],x=d[5],h=_f(e,x);r=v,u?u==8?n[b]=za(e.subarray(h,h+p),{out:new Se(f)}):Oe(14,"unknown compression type "+u):n[b]=Nn(e,h,h+p)}return n}const Ji=4,Ma=30,La=`cbs:draft:v${Ji}:`,Uf=["cbs:ribbon:","cbs:draft:"],Pt={commands:"baselineCommands",enableRules:"baselineEnableRules",displayRules:"baselineDisplayRules",locLabels:"baselineLocLabels"},Yi=["HomepageGrid","SubGrid","Form","Application"];function Pa(e){return{orgUrl:e.orgUrl.trim().replace(/\/+$/,"").toLowerCase(),solutionId:e.solutionId.trim().toLowerCase(),entityLogicalName:e.entityLogicalName.trim().toLowerCase()}}function Sn(e){const t=Pa(e);return`${La}${encodeURIComponent(t.orgUrl)}:${encodeURIComponent(t.solutionId)}:${encodeURIComponent(t.entityLogicalName)}`}function xi(e,t){return!e||!t?!1:Sn(e)===Sn(t)}function Xf(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 An=null;function Fa(e){const t=[e.baseline,e.baselineCommands,e.baselineEnableRules,e.baselineDisplayRules,e.baselineLocLabels,e.layers,e.baseLanguageCode];if(An&&An.of.every((o,i)=>o===t[i]))return An.value;const n=Xf(JSON.stringify(t));return An={of:t,value:n},n}const Os=new WeakMap;function Dn(e){let t=Os.get(e);return t===void 0&&(t=JSON.stringify(e),Os.set(e,t)),t}const zt=e=>JSON.parse(JSON.stringify(e)),Tn={},_a={list:"groups",child:{list:"buttons",child:Tn}};function qa(e){const t=new Map;for(const n of e)t.set(n.id,t.has(n.id)?null:n);return t}function Bo(e,t,n){if(!n.list||!Array.isArray(e[n.list]))return e;const o=t?.[n.list]??[];return{...e,[n.list]:vi(e[n.list],o,n.child??Tn)}}function En(e,t,n){if(!n.list||e[n.list]===void 0)return e;const o=t?.[n.list]??[];return{...e,[n.list]:Si(e[n.list],o,n.child??Tn)}}function vi(e,t,n){const o=qa(t),i=new Set(e.map(r=>r.id));if(i.size===e.length&&o.size===t.length){const r=t.filter(a=>i.has(a.id)),l=e.slice(r.length);if(r.every((a,c)=>e[c].id===a.id)&&l.every(a=>!o.has(a.id)))return{set:e.slice(0,r.length).filter(a=>Dn(o.get(a.id))!==Dn(a)).map(a=>Bo(a,o.get(a.id),n)),drop:t.filter(a=>!i.has(a.id)).map(a=>a.id),add:l.map(a=>Bo(a,void 0,n))}}return e.map(r=>{const l=o.get(r.id)??void 0;return l&&Dn(l)===Dn(r)?r.id:Bo(r,l,n)})}function Si(e,t,n){const o=qa(t);if(Array.isArray(e)){const c=[];for(const d of e)if(typeof d!="string")c.push(En(d,o.get(d.id)??void 0,n));else{const u=o.get(d);u&&c.push(zt(u))}return c}const i=new Set(e.drop),r=new Map(e.set.map(c=>[c.id,c])),l=[];for(const c of e.add)o.has(c.id)?r.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=>r.has(c.id)?En(r.get(c.id),c,n):zt(c)),...[...r.values()].filter(c=>!a.has(c.id)).map(c=>En(c,void 0,n)),...l.map(c=>En(c,void 0,n))]}const Vf=e=>!Array.isArray(e)&&e.set.length+e.drop.length+e.add.length===0,no=e=>e;function Kf(e){const t=et(e),n={};for(const r of Yi){const l=t.ribbons[r],a=e.baseline[r];if(!l)continue;const c=vi(l.tabs,a?.tabs??[],_a),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));(!Vf(c)||Object.keys(d).length+u.length>0)&&(n[r]={props:d,unset:u,tabs:c})}const o={};for(const r of Object.keys(Pt))o[r]=vi(no(t[r]),no(e[Pt[r]]),Tn);const i={...t};delete i.ribbons;for(const r of Object.keys(Pt))delete i[r];return{ribbons:n,lists:o,other:i}}function Jf(e,t){const{delta:n}=e,o={};for(const r of Yi){const l=n.ribbons[r],a=t.baseline[r];if(!l){o[r]=zt(a);continue}const c={...zt(a),...zt(l.props)};for(const d of l.unset)delete c[d];c.tabs=Si(l.tabs,no(a?.tabs??[]),_a),o[r]=c}const i={...et(t),...zt(n.other),ribbons:o};for(const r of Object.keys(Pt))i[r]=Si(n.lists[r],no(t[Pt[r]]),Tn);return i}function Yf(e){return btoa(vn(Oa(to(JSON.stringify(e)),{level:9}),!0))}function Zf(e){return JSON.parse(vn(za(to(atob(e),!0))))}const ht=e=>Array.isArray(e),Mo=e=>!!e&&typeof e=="object"&&!Array.isArray(e),zs=e=>{if(ht(e))return!0;const t=e;return!!t&&typeof t=="object"&&ht(t.set)&&ht(t.drop)&&ht(t.add)},Qf=e=>!!e&&typeof e=="object"&&ht(e.entity)&&ht(e.application);function eh(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,r])=>Yi.includes(i)&&zs(r?.tabs)&&Mo(r?.props)&&ht(r?.unset))&&Mo(t.lists)&&Object.keys(Pt).every(i=>zs(t.lists[i]))&&Mo(t.other)&&["pendingUnhides","uncustomisedCommandIds"].every(i=>!(i in o)||Qf(o[i]))&&(!("customisedCommandIds"in o)||ht(o.customisedCommandIds))}function th(e,t){try{const n={format:Ji,key:Pa(e),savedAt:new Date().toISOString(),baselineFingerprint:Fa(t),data:Yf(Kf(t))};return localStorage.setItem(Sn(e),JSON.stringify(n)),n.savedAt}catch{return null}}function nh(e){const t=Sn(e);let n;try{n=localStorage.getItem(t)}catch{return null}if(!n)return null;try{const o=JSON.parse(n);if(o.format===Ji&&xi(o.key,e)&&typeof o.data=="string"){const i=Zf(o.data);if(eh(i)){const r=o;return{format:r.format,key:r.key,savedAt:r.savedAt,baselineFingerprint:r.baselineFingerprint,delta:i}}}}catch{}return oo(e),null}function oo(e){try{localStorage.removeItem(Sn(e))}catch{}}function oh(e,t){try{const n=Date.parse(JSON.parse(e??"").savedAt??"");return!(t-n<=Ma*864e5)}catch{return!0}}function ih(e=Date.now()){const t=[];try{for(let n=0;n<localStorage.length;n++){const o=localStorage.key(n);o&&(o.startsWith(La)?oh(localStorage.getItem(o),e):Uf.some(i=>o.startsWith(i)))&&t.push(o)}for(const n of t)localStorage.removeItem(n)}catch{return 0}return t.length}function Ha(e){return e.mutationsSincePublish>0||_n(e)}function Lo(){return ye.getState().target!==null&&Ha(O.getState())}let Bt=null;function yt(e){const{target:t,pending:n}=ye.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(!Ha(e))Bt!==null&&e.future.some(a=>a.op==="restored"&&a.ts===Bt)||(oo(t),ye.setState({lastSavedAt:null}));else{const l=th(t,e);i=l!==null,l&&ye.setState({lastSavedAt:l})}const{saveFailed:r}=ye.getState();return!i&&!r&&ie.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===r&&ye.setState({saveFailed:!i}),i}const sh=["mutationsSincePublish","ribbons","commands","enableRules","displayRules","locLabels","pendingUnhides","customisedCommandIds","uncustomisedCommandIds","baseline","baselineCommands","baselineEnableRules","baselineDisplayRules","baselineLocLabels","layers"];function rh(){return O.subscribe((e,t)=>{sh.every(n=>e[n]===t[n])||yt(e)})}function ah(e){const t=ne.getState();return{orgUrl:t.connectionUrl,solutionId:t.activeSolution?.id??"",entityLogicalName:e}}function lh(){const e=O.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 Po(e){ye.setState({target:null,pending:null,pendingBaselineChanged:!1});const t=ne.getState();e.kind==="entity"?t.setActiveEntity(e.entity):t.setActiveSolution(e.solution)}const ye=jt()((e,t)=>({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null,beginLoad(){Bt=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,saveFailed:!1,lastSavedAt:null})},workspaceLoaded(n){const o=nh(n);Bt=null,e({target:n,pending:o,restoreError:null,lastSavedAt:o?.savedAt??null,pendingBaselineChanged:!!o&&o.baselineFingerprint!==Fa(O.getState())})},restoreDraft(){const{target:n,pending:o}=t();if(!n||!o||!xi(n,o.key))return!1;const i=O.getState();try{i.restoreWorkspace(Jf(o,i),`saved ${new Date(o.savedAt).toLocaleString()}`)}catch(a){const c=a instanceof Error?a.message:String(a);return ie.getState().logError("ribbon",`The unsaved changes saved ${o.savedAt} couldn't be restored: ${c}`),e({restoreError:c}),!1}const r=O.getState(),l=r.past[r.past.length-1];return r.past.length>i.past.length&&l?.op==="restored"&&(Bt=l.ts),e({pending:null,pendingBaselineChanged:!1,restoreError:null}),yt(r),!0},discardDraft(){const{target:n,pending:o}=t();o&&(oo(o.key),e({pending:null,pendingBaselineChanged:!1,restoreError:null,lastSavedAt:null}),n&&xi(n,o.key)&&yt(O.getState()))},requestEntitySwitch(n){ne.getState().activeEntity?.logicalName!==n.logicalName&&(Lo()?(yt(O.getState()),e({pendingSwitch:{kind:"entity",entity:n}})):Po({kind:"entity",entity:n}))},requestSolutionSwitch(n){ne.getState().activeSolution?.id!==n.id&&(Lo()?(yt(O.getState()),e({pendingSwitch:{kind:"solution",solution:n}})):Po({kind:"solution",solution:n}))},resolveSwitch(n){const{pendingSwitch:o,target:i,pending:r}=t();if(o){if(n==="cancel"){e({pendingSwitch:null});return}n==="keep"&&!yt(O.getState())||(n==="discard"&&i&&!r&&oo(i),e({pendingSwitch:null,target:null,pending:null,pendingBaselineChanged:!1,saveFailed:!1}),lh(),Po(o))}},releaseForConnectionChange(){const n=Lo(),o=n?yt(O.getState()):!1;return Bt=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null}),{hadChanges:n,kept:o}}})),Wa=e=>e?.trim().toLowerCase()==="production",kx=e=>Wa(e),Ax=(e,t)=>t.trim()!==""&&e.trim().toLowerCase()===t.trim().toLowerCase();function ch({prefix:e}){const t=ne(r=>r.connectionName),n=ne(r=>r.connectionUrl),o=ne(r=>r.environment);if(!t&&!n)return null;const i=Wa(o);return s.jsx(Ne,{content:n||t,relationship:"description",children:s.jsxs("span",{"data-testid":"environment-badge",style:{display:"inline-flex",alignItems:"center",gap:m.spacingHorizontalXS,minWidth:0},children:[e&&s.jsx(P,{size:200,wrap:!1,style:{color:m.colorNeutralForeground3},children:e}),s.jsx(P,{size:200,weight:"semibold",truncate:!0,wrap:!1,style:{maxWidth:180},children:t||n}),o&&s.jsx(ae,{size:"small",appearance:i?"filled":"tint",color:i?"warning":"informative",children:o})]})})}const dh=le({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 uh(){const e=dh(),[t,n]=M.useState("Loaded"),o=O(S=>S.past),i=O(S=>S.future),r=O(S=>S.undo),l=O(S=>S.redo),a=ne(S=>S.solutions),c=ne(S=>S.activeSolution),d=ye(S=>S.requestSolutionSwitch),u=Y(S=>S.openBulkPublish),p=Y(S=>S.openXmlDrawer),f=Y(S=>S.setCommandPaletteOpen),[b,v]=M.useState(!1),[x,h]=M.useState(""),y=M.useMemo(()=>a.filter(S=>!S.isManaged).map(S=>({value:S.id,children:S.friendlyName||S.uniqueName,searchText:`${S.friendlyName??""} ${S.uniqueName??""}`.toLowerCase(),solution:S})),[a]),w=Hu(x,y,{optionToText:S=>S.searchText,filter:(S,C)=>S.includes(C.toLowerCase()),optionToReactKey:S=>S.value,renderOption:S=>s.jsx(Vu,{value:S.value,text:S.solution.friendlyName??S.solution.uniqueName,children:s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[s.jsx(P,{size:200,weight:"semibold",children:S.solution.friendlyName||S.solution.uniqueName}),s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[S.solution.uniqueName," · v",S.solution.version,S.solution.publisherName?` · ${S.solution.publisherName}`:""]})]})},S.value),noOptionsMessage:a.length===0?"Loading solutions…":"No solutions match the filter."}),I=(S,C)=>{const $=a.find(R=>R.id===C.optionValue);$&&(d($),v(!1),h(""))};return s.jsxs("header",{className:e.root,children:[s.jsxs("div",{className:e.brand,children:[s.jsx("div",{className:e.brandMark,children:s.jsx(P,{size:100,weight:"bold",style:{color:"white",lineHeight:1},children:"CBS"})}),s.jsx(P,{weight:"semibold",size:300,children:"Command Bar Studio"})]}),s.jsx("div",{className:e.sep}),s.jsx(ch,{}),s.jsx("div",{className:e.sep}),s.jsxs(Wu,{open:b,onOpenChange:(S,C)=>v(C.open),positioning:"below-start",trapFocus:!0,children:[s.jsx(Gu,{disableButtonEnhancement:!0,children:s.jsxs(K,{appearance:c?"subtle":"primary",size:"small",icon:s.jsx(ql,{}),iconPosition:"before","aria-label":"Select solution",children:[s.jsx(P,{size:200,children:"Solution: "}),s.jsx(P,{size:200,weight:"semibold",children:c?.friendlyName??"Select solution…"}),c&&s.jsxs(s.Fragment,{children:[s.jsx(ae,{appearance:"tint",color:c.isManaged?"informative":"success",size:"small",style:{marginLeft:m.spacingHorizontalXS},children:c.isManaged?"Managed":"Unmanaged"}),(()=>{const S=c.publisherPrefix||"new",C=S==="new"||/^defaultpublisher/i.test(c.publisherUniqueName??"");return s.jsxs(ae,{appearance:"tint",color:C?"warning":"informative",size:"small",title:C?`Imports will land under the org's default publisher "${S}". To use your own publisher, create a new solution in maker.powerapps.com bound to it.`:`Publisher: ${c.publisherName||c.publisherUniqueName||S}`,style:{marginLeft:m.spacingHorizontalXS},children:[S,"_"]})})()]}),s.jsx(gt,{fontSize:12,style:{marginLeft:m.spacingHorizontalXS,color:m.colorNeutralForeground3}})]})}),s.jsxs(Uu,{className:e.solutionPickerSurface,children:[s.jsx(P,{size:200,weight:"semibold",children:"Select an unmanaged solution"}),s.jsx(Ee,{label:"Solution",children:s.jsx(Xu,{placeholder:a.length===0?"Loading solutions…":"Search by display name or unique name",value:x,onChange:S=>h(S.target.value),onOptionSelect:I,freeform:!0,clearable:!0,children:w})}),s.jsxs(P,{size:100,className:e.solutionPickerHint,children:[y.length," unmanaged solution",y.length!==1?"s":""," available"]})]})]}),s.jsx("div",{className:e.spacer}),s.jsxs("button",{type:"button",className:e.paletteButton,onClick:()=>f(!0),"aria-label":"Search buttons, commands, rules (Ctrl+K)",children:[s.jsx(ft,{fontSize:14}),s.jsx("span",{style:{flex:1,textAlign:"left"},children:"Search buttons, commands, rules…"}),s.jsx("kbd",{className:e.kbd,children:"Ctrl"}),s.jsx("kbd",{className:e.kbd,children:"K"})]}),s.jsx("div",{className:e.sep}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(hr,{}),disabled:o.length===0,onClick:r,title:"Undo (Ctrl+Z)","aria-label":"Undo"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(gr,{}),disabled:i.length===0,onClick:l,title:"Redo (Ctrl+Shift+Z)","aria-label":"Redo"}),s.jsx("div",{className:e.sep}),s.jsxs(dt,{value:t,onChange:(S,C)=>n(C.value),size:"small",title:"State simulator","aria-label":"State simulator",children:[s.jsx("option",{value:"Loaded",children:"Loaded"}),s.jsx("option",{value:"Empty",children:"Empty"}),s.jsx("option",{value:"Error",children:"Error"}),s.jsx("option",{value:"Publishing",children:"Publishing"})]}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(br,{}),onClick:()=>{p()},title:"Import / Export RibbonDiffXml","aria-label":"Import/Export"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(yr,{}),title:"Settings","aria-label":"Settings"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(xr,{}),title:"Help","aria-label":"Help"}),s.jsx("div",{className:e.sep}),s.jsx(K,{appearance:"secondary",size:"small",icon:s.jsx(vr,{}),children:"Save"}),s.jsx(K,{appearance:"primary",size:"small",icon:s.jsx(Hl,{}),onClick:u,children:"Publish All"})]})}const mh=le({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 ph(){const e=mh(),t=O(p=>p.mutationsSincePublish),n=ne(p=>p.activeSolution),o=ne(p=>p.activeEntity),i=ne(p=>p.connectionUrl),r=Y(p=>p.openXmlDrawer),l=Y(p=>p.openImportXml),a=Y(p=>p.openDiffViewer),c=Y(p=>p.rightPaneMode),d=Y(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 s.jsxs("div",{className:e.root,children:[s.jsxs("nav",{"aria-label":"Breadcrumb",className:e.breadcrumb,children:[s.jsx("span",{children:"Solutions"}),s.jsx("span",{className:e.separator,children:"›"}),s.jsx("span",{children:n?.friendlyName??"—"}),s.jsx("span",{className:e.separator,children:"›"}),s.jsx("span",{children:"Tables"}),s.jsx("span",{className:e.separator,children:"›"}),s.jsx("span",{className:e.activeSegment,children:o?.displayName??"Select a table"})]}),s.jsx("div",{className:e.spacer}),t>0&&s.jsxs(ae,{appearance:"tint",color:"warning",children:[t," change",t!==1?"s":""," since publish"]}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Ct,{}),onClick:()=>{u()},disabled:!o?.logicalName,children:"Preview in app"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Gt,{}),onClick:r,children:"RibbonDiffXml"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(br,{}),onClick:()=>l(),children:"Import / Export"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Sr,{}),onClick:()=>a("compare"),children:"Compare"}),s.jsxs(dt,{size:"small",value:c,onChange:(p,f)=>d(f.value),"aria-label":"Properties pane mode",children:[s.jsx("option",{value:"docked",children:"Properties: Docked"}),s.jsx("option",{value:"floating",children:"Properties: Floating"}),s.jsx("option",{value:"hidden",children:"Properties: Hidden"})]})]})}function fh(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 hh='[role="dialog"], [role="alertdialog"], [role="menu"], [role="menubar"], [role="listbox"], .fui-PopoverSurface, .fui-MenuPopover',Ga=".fui-OverlayDrawer, .fui-InlineDrawer",Bs=e=>!!e.closest(Ga)&&!e.matches('[role="alertdialog"]');function gh(e){const t=e instanceof Element?e.closest(hh):null;return t&&!Bs(t)?!0:Array.from(document.querySelectorAll('[aria-modal="true"], [role="alertdialog"]')).some(n=>!Bs(n))}function bh(e){return e instanceof Element&&!!e.closest(Ga)}function yh(){const e=Y(S=>S.setCommandPaletteOpen),t=Y(S=>S.openBulkPublish),n=Y(S=>S.announce),o=Y(S=>S.openHideInsteadOfDelete),i=O(S=>S.undo),r=O(S=>S.redo),l=O(S=>S.past),a=O(S=>S.future),c=Z(S=>S.selectedButtonId),d=Z(S=>S.selectedGroupId),u=Z(S=>S.tabId),p=Z(S=>S.location),f=O(S=>S.duplicateButton),b=O(S=>S.deleteButton),v=O(S=>S.moveButton),x=O(S=>S.ribbons),h=O(S=>S.baseline),y=Z(S=>S.selectButtonInContext),w=Z(S=>S.selectGroup),I=M.useRef(null);M.useEffect(()=>{const S=C=>{const R=navigator.platform.toUpperCase().includes("MAC")?C.metaKey:C.ctrlKey,E=C.target;if(C.key==="Escape"){e(!1);return}if(gh(E)){R&&C.key==="s"&&C.preventDefault();return}if(R&&C.key==="k"){C.preventDefault(),e(!0),n("Command palette opened");return}if(R&&C.key==="s"){C.preventDefault(),t(),n("Bulk publish dialog opened");return}const T=fh(E);if(R&&C.key==="z"&&!C.shiftKey&&l.length>0&&!T){C.preventDefault(),i(),n("Undo");return}if((R&&C.key==="y"||R&&C.shiftKey&&C.key==="z")&&!T){C.preventDefault(),a.length>0&&(r(),n("Redo"));return}if(!bh(E)){if(R&&C.key==="d"){!T&&c&&d&&u&&p&&(C.preventDefault(),f(p,u,d,c),n("Button duplicated"));return}if(R&&C.key.toLowerCase()==="x"){if(!T&&c&&d&&u&&p){C.preventDefault();const _=x[p].tabs.find(D=>D.id===u)?.groups.find(D=>D.id===d);if(_&&Vn(_,c)){n("Menu items can't be cut. Delete the item and add a new one to the other menu.");return}I.current={location:p,tabId:u,groupId:d,buttonId:c},n("Button cut. Focus a destination group, then press paste.")}return}if(R&&C.key.toLowerCase()==="v"){const _=I.current;if(!T&&_&&d&&u&&p){C.preventDefault();const D=v({groupId:_.groupId,buttonId:_.buttonId,tabId:_.tabId,location:_.location},{groupId:d,tabId:u,location:p});if(I.current=null,!D){n("The button couldn't be moved there.");return}requestAnimationFrame(()=>{y(p,u,d,D),document.querySelector(`[data-ribbon-btn-id="${D}"]`)?.focus()}),n(D===_.buttonId?"Button pasted to destination group.":"Pasted your copy of the button to the destination group; the original is hidden.")}return}if((C.key==="Delete"||C.key==="Backspace")&&c&&d&&u&&p&&!T){const _=x[p].tabs.find(X=>X.id===u),D=_?.groups.find(X=>X.id===d),L=Qt(D,c);if(!L)return;if(C.preventDefault(),!$n(L,h[p])){p==="Application"&&u==="Mscrm.GlobalTab"&&L.oob&&!L.custom?n(`"${L.label}" is read-only and can't be deleted.`):L.hidden?n(`"${L.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 j=D?Vn(D,c):void 0,B=j?j.section.controls.map(X=>({groupId:d,buttonId:X.id})):_?.groups.flatMap(X=>X.buttons.map(Q=>({groupId:X.id,buttonId:Q.id})))??[],N=B.findIndex(X=>X.buttonId===c),W=B[N+1]??B[N-1]??(j?{groupId:d,buttonId:j.parent.id}:null),U=d;b(p,u,d,c),requestAnimationFrame(()=>{if(W){y(p,u,W.groupId,W.buttonId),document.querySelector(`[data-ribbon-btn-id="${W.buttonId}"]`)?.focus();return}U&&(w(U),document.querySelector(`[data-add-btn-group-id="${U}"]`)?.focus())}),n("Button deleted")}}};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[e,t,n,o,i,r,l.length,a.length,c,d,u,p,f,b,v,x,h,y,w])}const xh=le({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 Fo({direction:e,onResize:t,"aria-label":n=`Resize ${e} pane`}){const o=xh(),i=M.useRef(0),r=M.useCallback(a=>{a.currentTarget.setPointerCapture(a.pointerId),i.current=e==="vertical"?a.clientX:a.clientY},[e]),l=M.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 s.jsx("div",{className:e==="vertical"?o.handleV:o.handleH,role:"separator","aria-orientation":e==="vertical"?"vertical":"horizontal","aria-label":n,onPointerDown:r,onPointerMove:l})}class Dt 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:s.jsxs(Ce,{intent:"error",style:{margin:8},children:[s.jsxs(Ie,{children:[s.jsx("strong",{children:this.props.label??"Panel"})," encountered an error:"," ",this.state.error?.message??"Unknown error"]}),s.jsx(hn,{children:s.jsx(K,{size:"small",onClick:this.handleRetry,children:"Retry"})})]}):this.props.children}}const vh=M.lazy(()=>$e(()=>import("./XmlDrawer-C4lJ7_MF.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),Sh=M.lazy(()=>$e(()=>import("./CommandEditorPanel-1tDOtoTt.js"),__vite__mapDeps([7,1,2,3,8,9,5,4,6]),import.meta.url)),wh=M.lazy(()=>$e(()=>import("./RuleEditorPanel-B5or3M9d.js"),__vite__mapDeps([10,1,2,3,11,5,8,9,6]),import.meta.url)),Ch=M.lazy(()=>$e(()=>import("./BulkPublishModal-CF7sSmBT.js"),__vite__mapDeps([12,1,2,3,13,11,9,5,6]),import.meta.url)),Ih=M.lazy(()=>$e(()=>import("./NewButtonModal-B_ugATAS.js"),__vite__mapDeps([14,1,2,3,5,6]),import.meta.url)),Rh=M.lazy(()=>$e(()=>import("./NewGroupModal-Dvg8CSJr.js"),__vite__mapDeps([15,1,2,3,5,6]),import.meta.url)),jh=M.lazy(()=>$e(()=>import("./NewTabModal-CjMNMXb5.js"),__vite__mapDeps([16,1,2,3,5,6]),import.meta.url)),$h=M.lazy(()=>$e(()=>import("./ImportXmlModal-DXwUce5n.js"),__vite__mapDeps([17,1,2,3,13,11,9,4,5,6]),import.meta.url)),Nh=M.lazy(()=>$e(()=>import("./CommandPalette-BBM1PJH0.js"),__vite__mapDeps([18,1,2,3,5,6]),import.meta.url)),Th=M.lazy(()=>$e(()=>import("./LocalizationEditor-DXqbD2ZN.js"),__vite__mapDeps([19,1,2,3,5,6]),import.meta.url)),kh=M.lazy(()=>$e(()=>import("./IconPickerModal-D6hQ_Aqx.js"),__vite__mapDeps([20,1,2,3,21,5,6]),import.meta.url)),Ah=M.lazy(()=>$e(()=>import("./TabDisplayRulesPanel-BqzSpzqp.js"),__vite__mapDeps([22,1,2,3,5,6]),import.meta.url)),Dh=M.lazy(()=>$e(()=>import("./ScalingEditorPanel-CzQtkicj.js"),__vite__mapDeps([23,1,2,3,5,6]),import.meta.url)),Eh=M.lazy(()=>$e(()=>import("./ConflictDrawer-CjObt6DP.js"),__vite__mapDeps([24,1,2,3,5,6]),import.meta.url)),Oh=M.lazy(()=>$e(()=>import("./WebResourceBrowser-BK_G_Q_c.js"),__vite__mapDeps([25,1,2,3,21,5,6]),import.meta.url)),zh=M.lazy(()=>$e(()=>import("./UrlComposerModal-BDP57HQn.js"),__vite__mapDeps([26,1,2,3,5,6]),import.meta.url)),Bh=M.lazy(()=>$e(()=>import("./DiffViewer-Dfu_9b4v.js"),__vite__mapDeps([27,2,3,1,5,6]),import.meta.url)),Mh=M.lazy(()=>$e(()=>import("./HideInsteadOfDeleteModal-C64qc-fw.js"),__vite__mapDeps([28,1,2,3,5,6]),import.meta.url)),Lh=le({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 Ph({children:e,leftPane:t,rightPane:n,bottomPanel:o}){const i=Lh(),r=Y(S=>S.leftPaneWidth),l=Y(S=>S.rightPaneWidth),a=Y(S=>S.rightPaneMode),c=Y(S=>S.setLeftPaneWidth),d=Y(S=>S.setRightPaneWidth),u=Y(S=>S.bottomPanelHeight),p=Y(S=>S.bottomCollapsed),f=Y(S=>S.setBottomPanelHeight),b=Y(S=>S.announcement),v=Y(S=>S.xmlDrawerOpen||S.commandEditorOpen||S.ruleEditorOpen||S.bulkPublishOpen||S.newButtonGroupId!==null||S.newGroupOpen||S.newTabOpen||S.importXmlOpen||S.commandPaletteOpen||S.localizationEditorOpen||S.iconPickerOpen||S.tabDisplayRulesOpen||S.scalingEditorOpen||S.conflictDrawerOpen||S.webResourceBrowserOpen||S.urlComposerOpen||S.diffViewerOpen||S.hideInsteadOfDelete!==null),x=M.useRef(null),h=M.useRef(!1);yh(),M.useEffect(()=>{if(v&&!h.current){const S=document.activeElement;x.current=S instanceof HTMLElement?S:null}if(!v&&h.current){const S=x.current;requestAnimationFrame(()=>{!S||!S.isConnected||S.focus()})}h.current=v},[v]);const y=M.useCallback(S=>{c(Math.max(160,Math.min(500,r+S)))},[r,c]),w=M.useCallback(S=>{d(Math.max(200,Math.min(600,l-S)))},[l,d]),I=M.useCallback(S=>{const C=u-S;f(Math.max(120,Math.min(520,C)))},[u,f]);return s.jsxs("div",{className:i.root,children:[s.jsx(uh,{}),s.jsx(ph,{}),s.jsxs("div",{className:i.body,children:[s.jsx("div",{className:i.leftPane,style:{width:r},children:s.jsx(Dt,{label:"Left pane",children:t})}),s.jsx(Fo,{direction:"vertical",onResize:y,"aria-label":"Resize left pane"}),s.jsx(Dt,{label:"Ribbon canvas",children:e}),a==="docked"&&s.jsxs(s.Fragment,{children:[s.jsx(Fo,{direction:"vertical",onResize:w,"aria-label":"Resize right pane"}),s.jsx("div",{className:i.rightPane,style:{width:l},children:s.jsx(Dt,{label:"Properties pane",children:n})})]}),a==="floating"&&s.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:s.jsx(Dt,{label:"Properties pane",children:n})})]}),!p&&s.jsx(Fo,{direction:"horizontal",onResize:I,"aria-label":"Resize bottom panel"}),s.jsx("div",{className:i.bottomPanel,children:s.jsx(Dt,{label:"Bottom panel",children:o})}),s.jsx(Dt,{label:"Panels",children:s.jsxs(M.Suspense,{fallback:null,children:[s.jsx(vh,{}),s.jsx(Sh,{}),s.jsx(wh,{}),s.jsx(Ch,{}),s.jsx(Ih,{}),s.jsx(Rh,{}),s.jsx(jh,{}),s.jsx($h,{}),s.jsx(Nh,{}),s.jsx(Th,{}),s.jsx(kh,{}),s.jsx(Ah,{}),s.jsx(Dh,{}),s.jsx(Eh,{}),s.jsx(Oh,{}),s.jsx(zh,{}),s.jsx(Bh,{}),s.jsx(Mh,{})]})}),s.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:b})]})}const Ua="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.",an=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Fh=e=>[e.icon,e.image16,e.image32].some(t=>!!t&&t.startsWith("$webresource:")),_h=e=>!!e.source&&Li(e)===e.source.modernImage&&(e.source.modernImage!==void 0||!e.icon),qh=/^\$LocLabels:(.+)$/,mt=e=>e?qh.exec(e)?.[1]??null:null,Hh=/^\s*<(EnableRule|DisplayRule)\b[^>]*?\sId="([^"]+)"/,ln=e=>new Set(e??[]);function Wh(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 Ms(e){return(e.menu?.sections??[]).map(t=>({id:t.id,title:t.title??"",sequence:t.sequence,displayMode:t.displayMode??"",controlsId:t.controlsId}))}function Dx(e){const t=[],n=[],o=[],i=[],r=[],l=[],a=[],c=[],d=new Map,u=(q,F)=>{const J=mt(q);J&&d.set(J,new Set([...d.get(J)??[],F]))};for(const{baseline:q}of e.locations)for(const F of q.tabs){u(F.label,F.id);for(const J of F.groups){u(J.label,J.id);for(const G of je(J))for(const g of Object.values(G.source?.attributes??{}))u(g,G.id)}}const p=new Set([...(e.locLabels??[]).map(q=>q.id),...ln(e.layer?.locLabelIds)]);let f=!1;const b=new Set,v=ln(e.layer?.containerIds),x=ln(e.layer?.locLabelIds),h=new Set,y=new Set,w=new Map,I=new Map,S=[],C=new Set(e.locations.flatMap(({current:q})=>Array.from(St(q).values(),F=>F.button.id))),$=(q,F,J,G)=>{const g=mt(J);if(v.has(F)&&g&&x.has(g)&&!mt(G)&&G.trim())if([...d.get(g)??[]].some(k=>k!==F)){let k=`${F}.Title`;for(let A=2;k===g||p.has(k);A++)k=`${F}.Title${A}`;p.add(k),c.push({id:k,text:G,containerId:F,newLabel:!0})}else c.push({id:g,text:G,containerId:F});else t.push(`Renaming ${q} ${F} — only tabs and groups your unmanaged customizations add (with a translatable title) can be renamed`)};for(const{current:q,baseline:F}of e.locations){const J=$p(q,F);J.newButtons+J.overriddenButtons+J.hiddenButtons+J.newTabs+J.newGroups>0&&(f=!0),J.scalingChanges>0&&t.push(`Scaling changes on ${q.location} (not supported yet)`);const G=ca(q,F);t.push(...G.problems);const g=ln(e.layer?.scalingStepIds);for(const[z,H]of Object.entries(F.scalingByTab??{})){const oe=q.tabs.find(se=>se.id===z),ee=[...H.maxSizes.filter(se=>g.has(se.id)).map(se=>({...se,kind:"MaxSize"})),...H.scales.filter(se=>g.has(se.id)).map(se=>({...se,kind:"Scale"})),...(oe?.groups??[]).map(se=>G.steps.get(se.id)).filter(se=>!!se).map(se=>({...se,kind:"MaxSize"}))];if(ee.length===0)continue;const Re=Ur(z,{maxSizes:H.maxSizes.filter(se=>!g.has(se.id)).map(se=>se.sequence),scales:H.scales.filter(se=>!g.has(se.id)).map(se=>se.sequence)},ee);n.push(...Re.changes.map(np)),t.push(...Re.problems)}const k=St(q),A=St(F);for(const{button:z}of k.values())for(const H of Hr(z))b.add(H);for(const[z,{button:H}]of k){const oe=Wh(H);oe.forEach(se=>h.add(se));const ee=A.get(z)?.button,Re=!ee||ii(ee,H);for(const se of[mo(H.id),po(H.id),fo(H.id)])Re?y.add(se):oe.includes(se)||w.set(se,H);Re&&oe.forEach(se=>y.add(se))}for(const[z,H]of A){const oe=H.button.id,ee=k.get(z);if(!ee){if(H.menu&&C.has(oe)&&C.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)&&C.has(oe)&&/<Menu[\s>/]/.test(H.button.source?.xml??"")){t.push(`Moving the <${gn[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&&!ee.button.hidden&&i.push(oe),(ee.button.kind??"button")!==(H.button.kind??"button")&&t.push(`Changing the kind of "${ee.button.label}" (${oe}) — not supported yet`);const Re=ii(H.button,ee.button);Re&&Ze(ee.button.kind)&&t.push(`Editing the <${gn[ee.button.kind]}> "${ee.button.label}" (${oe}) — CBS shows it read-only; it can be hidden, or moved and deleted when it's your own`),Re&&(Mt(ee.button.kind)||ee.button.menu)&&H.button.origin!=="unmanaged"&&t.push(`Editing the flyout / split button "${ee.button.label}" (${oe}) itself — only your own can be edited; its menu items can be edited, hidden or added to`),an(Ms(H.button),Ms(ee.button))||t.push(`Adding, removing or changing menu sections of "${ee.button.label}" (${oe}) — not supported yet for an existing menu; add, edit or remove its items instead`),(ee.button.icon??"")!==(H.button.icon??"")&&!Fh(ee.button)&&!_h(ee.button)&&t.push(`Changing the icon of "${ee.button.label}" (${oe}) to a built-in icon — not supported yet; choose an SVG web resource`),((ee.menu||H.menu?ee.menu?.controlsId!==H.menu?.controlsId:ee.groupId!==H.groupId)||ee.button.sequence!==H.button.sequence)&&(H.button.origin==="unmanaged"?l.push({id:oe,groupId:ee.groupId,sequence:ee.button.sequence,...ee.menu?{controlsId:ee.menu.controlsId}:{}}):t.push(`Moving or re-ordering "${ee.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[z,H]of k){if(A.has(z))continue;I.has(H.button.id)||I.set(H.button.id,{groupId:H.groupId,sequence:H.button.sequence,...H.menu?{controlsId:H.menu.controlsId}:{}});const oe=na(H.button.source?.attributes.PopulateDynamically);Mt(H.button.kind)&&!oe&&!wt(H.button).some(ee=>!ee.hidden)&&S.push({id:H.button.id,label:H.button.label})}const te=new Map(F.tabs.flatMap(z=>z.groups.map(H=>[H.id,H]))),de=new Map(F.tabs.map(z=>[z.id,z])),Te=new Set(q.tabs.map(z=>z.id)),be=new Set(q.tabs.flatMap(z=>z.groups.map(H=>H.id)));for(const z of q.tabs){const H=mt(z.label);H&&h.add(H);const oe=de.get(z.id);if(!oe){y.add(`${z.id}.Title`);const ee=mt(z.source?.titleToken);ee&&y.add(ee),z.commandId&&b.add(z.commandId),q.location==="Application"&&(z.tabDisplayRules??[]).length===0&&t.push(`New tab ${z.id} has no tab display rule, so it would never be shown — add one in Tab rules`),n.push(`New tab "${z.label}" (${z.id}): ${Ua}`)}oe&&oe.label!==z.label&&$("tab",z.id,oe.label,z.label),oe&&!an(oe.tabDisplayRules??[],z.tabDisplayRules??[])&&(v.has(z.id)?z.commandId?a.push(z.id):t.push(`Changing the display rules of tab ${z.id} — the tab has no Command to attach them to`):t.push(`Changing the display rules of tab ${z.id} — only tabs your unmanaged customizations add can be changed`));for(const ee of z.groups){const Re=mt(ee.label);Re&&h.add(Re);const se=te.get(ee.id);if(!se){y.add(`${ee.id}.Title`);const Tt=mt(ee.source?.titleToken);Tt&&y.add(Tt)}se&&se.template!==ee.template&&t.push(`Re-templating group ${ee.id} — not supported yet`),se&&se.label!==ee.label&&$("group",ee.id,se.label,ee.label)}}const Me=(z,H)=>t.push(`Removing ${z} ${H} — only tabs and groups your unmanaged customizations add can be deleted; hide it instead`);for(const z of F.tabs){if(!Te.has(z.id)){v.has(z.id)?r.push(z.id):Me("tab",z.id);continue}for(const H of z.groups)be.has(H.id)||(v.has(H.id)?r.push(H.id):Me("group",H.id))}}for(let q=o.length-1;q>=0;q--){const F=I.get(o[q]);F&&(l.push({id:o[q],...F}),o.splice(q,1))}for(const q of e.deletedOrphans??[]){for(const F of q.deleteControlIds)o.includes(F)||o.push(F);for(const F of q.deleteContainerIds)r.includes(F)||r.push(F)}for(const q of S)l.some(F=>F.id===q.id)||t.push(`New flyout / split button "${q.label}" has no menu items — add at least one item to its menu`);const R=e.layer?.commandIds?ln(e.layer.commandIds):null,E=new Set(e.uncustomisedCommandIds??[]),T=[...E].filter(q=>R?R.has(q):b.has(q)&&!e.excludeCommandIds?.has(q));for(const q of T)e.layer?.commandRefIds&&!Ei(q,e.layer.commandRefIds)&&t.push(`Uncustomising ${q} — it is your own command (your customizations' buttons use it and no other solution defines it); undo the uncustomise`);T.includes(ze)&&b.has(ze)&&t.push(`Uncustomising ${ze} — its "Open record" buttons still use it; undo the uncustomise and turn the record open override off in the Advanced section instead`);for(const q of e.excludeCommandIds??[])b.delete(q);const _=new Set(e.customisedCommandIds??[]),D=new Map(e.baselineCommands.map(q=>[q.id,q])),L=e.commands.filter(q=>b.has(q.id)&&!E.has(q.id)&&(!D.has(q.id)||!an(D.get(q.id),q)||_.has(q.id)&&!R?.has(q.id))).map(q=>q.id);for(const q of e.commands){if(!L.includes(q.id))continue;q.actions.some(J=>J.kind==="powerFx"||J.kind==="customApi")&&t.push(`Power Fx / Custom API action in command ${q.id} — classic ribbon commands can't run these; remove the action (#28)`);const F=q.id===ze?xf(q):null;F&&t.push(F)}const j=new Set,B=new Set;for(const q of e.commands)if(!(!b.has(q.id)||E.has(q.id))){q.enableRules.forEach(F=>j.add(F)),q.displayRules.forEach(F=>B.add(F));for(const F of q.rawRuleRefs??[]){const J=Hh.exec(F.xml);J&&(J[1]==="EnableRule"?j:B).add(J[2])}}const N=(q,F,J)=>{const G=new Map(F.map(g=>[g.id,g]));return q.filter(g=>J.has(g.id)&&(!G.has(g.id)||!an(G.get(g.id),g))).map(g=>g.id)},W=N(e.enableRules,e.baselineEnableRules,j),U=N(e.displayRules,e.baselineDisplayRules,B),X=[];if(e.locLabels&&e.baselineLocLabels){const q=new Map(e.baselineLocLabels.map(F=>[F.id,F]));for(const F of e.locLabels){const J=q.get(F.id);if(J&&an(J,F)||y.has(F.id))continue;if(h.has(F.id)){x.has(F.id)?X.push(F.id):t.push(`Translations of label ${F.id} — it is defined by another solution; change the text in the properties pane instead`);continue}const G=w.get(F.id);G&&t.push(`Translations for "${G.label}" (${G.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(q=>!i.includes(q));return{hasChanges:f||L.length>0||T.length>0||W.length>0||U.length>0||o.length>0||i.length>0||Q.length>0||r.length>0||l.length>0||X.length>0||a.length>0||c.length>0,editedCommandIds:L,uncustomisedCommandIds:T,editedEnableRuleIds:W,editedDisplayRuleIds:U,deletedButtonIds:o,unhiddenButtonIds:[...i,...Q],deletedContainerIds:r,movedButtons:l,editedLocLabelIds:X,editedTabIds:a,renamedLabels:c,unsupported:[...new Set(t)],warnings:[...new Set(n)]}}const Gh=["HomepageGrid","SubGrid","Form"];function Uh(e,t){const n=new Map;for(const v of Object.values(t.baseline))for(const x of v.tabs)for(const h of x.groups)for(const y of h.buttons)n.set(y.id,y.origin);let o=!1,i=!1,r=li(e);for(const[v,x]of Object.entries(t.ribbons))for(const h of x.tabs)for(const y of h.groups)for(const w of y.buttons)w.commandId===e&&(Gh.includes(v)?o=!0:i=!0,n.has(w.id)&&n.get(w.id)!=="unmanaged"&&(r=!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(v=>v.id===e),p=(v,x=l)=>({provenance:v,scope:x,sharedWithApplication:a});if(t.reloadRequiredCommandIds.includes(e))return p("reloadRequired");for(const v of["entity","application"])if(t.uncustomisedCommandIds[v].includes(e))return p("uncustomising",v);if(!u||!r&&d!==!1)return p("custom");if(d){const v=c?.commandRefIds?Ei(e,c.commandRefIds):li(e);return p(v?"customised":"custom")}const f=t.commands.find(v=>v.id===e),b=!!f&&JSON.stringify(f)!==JSON.stringify(u);return t.customisedCommandIds.includes(e)||b?p("customising"):p("oob")}const Xh={oob:"Out of the box",customising:"Customised (unpublished)",customised:"Customised in your layer",uncustomising:"Uncustomised (unpublished)",custom:"Custom",reloadRequired:"Uncustomised — reload the table"};function Xa(e){const t=O(d=>d.commands),n=O(d=>d.baselineCommands),o=O(d=>d.ribbons),i=O(d=>d.baseline),r=O(d=>d.layers),l=O(d=>d.customisedCommandIds),a=O(d=>d.uncustomisedCommandIds),c=O(d=>d.reloadRequiredCommandIds);return Ue.useMemo(()=>e&&t.some(d=>d.id===e)?Uh(e,{commands:t,baselineCommands:n,ribbons:o,baseline:i,layers:r,customisedCommandIds:l,uncustomisedCommandIds:a,reloadRequiredCommandIds:c}):null,[e,t,n,o,i,r,l,a,c])}function Ex(e){return e?.provenance==="uncustomising"||e?.provenance==="reloadRequired"}function Va({location:e,tabId:t,groupId:n,button:o,onDone:i}){const r=O(f=>f.customiseButton),l=O(f=>f.customiseCommand),a=ne(f=>f.activeSolution),c=ne(f=>f.publisherPrefix),d=Z(f=>f.selectButtonInContext),u=Y(f=>f.openCommandEditor),p=Xa(o.commandId||void 0);return s.jsxs(s.Fragment,{children:[o.origin!=="unmanaged"&&s.jsx(me,{icon:s.jsx(Wl,{}),disabled:!Xi(e,t,o),onClick:()=>{const f=a?.publisherPrefix?.trim()||c?.trim()||"new",b=r(e,t,n,o.id,f);b&&d(e,t,n,b),i()},children:"Customise button (copy, hide original)"}),p?.provenance==="oob"&&s.jsx(me,{icon:s.jsx(Gt,{}),onClick:()=>{l(o.commandId)&&u(o.commandId),i()},children:"Customise command"})]})}function Ka(e,t,n,o,i){const r=e.groups.filter(a=>a.id!==t&&!(n&&a.buttons.some(c=>c.id===n))).map(a=>({groupId:a.id,text:ce(a.label,o,i).trim()||a.id})),l=new Map;for(const a of r)l.set(a.text,(l.get(a.text)??0)+1);return r.map(a=>(l.get(a.text)??0)>1&&a.text!==a.groupId?{...a,text:`${a.text} (${a.groupId})`}:a)}const Zi=({open:e,buttonLabel:t,commandId:n,deleteBlockedReason:o,onConfirmHide:i,onConfirmDisplayRule:r,onCancel:l})=>s.jsx(Ut,{open:e,onOpenChange:()=>l(),children:s.jsxs(Xt,{style:{maxWidth:"560px"},children:[s.jsxs(Vt,{children:[s.jsx(wr,{style:{marginRight:"8px",color:"var(--colorStatusWarningForeground1)"}}),o?`Can't delete "${t}"`:`Hide "${t}"`]}),s.jsxs(Kt,{children:[s.jsxs(Jt,{children:[o&&s.jsxs(P,{style:{display:"block",marginBottom:"12px"},children:[o," Only buttons your solution adds can be deleted — you can hide this one instead."]}),s.jsx(Ce,{intent:"warning",children:s.jsxs(Ie,{children:[s.jsx(P,{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."]})}),s.jsxs(P,{style:{display:"block",marginTop:"12px"},children:["The reversible alternative adds the display rules ",s.jsx("code",{children:"Mscrm.HideOnModern"})," +"," ",s.jsx("code",{children:"Mscrm.ShowOnlyOnModern"})," (never both true) to the button's command",n?s.jsxs(s.Fragment,{children:[" ",s.jsx("code",{children:n}),". Every button that uses this command is hidden too."]}):s.jsx(s.Fragment,{children:". This button has no command, so only the HideCustomAction is available."})]})]}),s.jsxs(Yt,{children:[s.jsx(K,{appearance:"secondary",onClick:l,children:"Cancel"}),s.jsx(K,{appearance:"secondary",onClick:r,disabled:!n,children:"Use display rules (reversible)"}),s.jsx(K,{appearance:"primary",onClick:i,children:"Use HideCustomAction (permanent)"})]})]})]})}),Vh=({open:e,initialLabel:t,onRename:n,onCancel:o})=>{const[i,r]=M.useState(t),l=i.trim(),a=()=>{l&&(l===t.trim()?o():n(l))};return s.jsx(Ut,{open:e,onOpenChange:(c,d)=>!d.open&&o(),children:s.jsx(Xt,{style:{maxWidth:"440px"},children:s.jsxs(Kt,{children:[s.jsx(Vt,{children:"Rename group"}),s.jsx(Jt,{children:s.jsx(Ee,{label:"Group title",required:!0,validationState:l?"none":"error",validationMessage:l?void 0:"Enter a title for the group.",children:s.jsx(qe,{value:i,onChange:(c,d)=>r(d.value),onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),a())},autoFocus:!0})})}),s.jsxs(Yt,{children:[s.jsx(K,{appearance:"secondary",onClick:o,children:"Cancel"}),s.jsx(K,{appearance:"primary",onClick:a,disabled:!l,children:"Rename"})]})]})})})},Kh=e=>e.replace(/^Mscrm\.Templates\./,""),Jh=({open:e,currentTemplate:t,customTemplateIds:n=[],loadedGroup:o=!1,onChange:i,onCancel:r})=>{const l=Bi(t),[a,c]=M.useState(l),d=[...new Set([...Tp,...n,l])],u=()=>{a===l?r():i(a)};return s.jsx(Ut,{open:e,onOpenChange:(p,f)=>!f.open&&r(),children:s.jsx(Xt,{style:{maxWidth:"480px"},children:s.jsxs(Kt,{children:[s.jsx(Vt,{children:"Change group template"}),s.jsxs(Jt,{children:[s.jsx(Ee,{label:"Group template",children:s.jsx(dt,{value:a,onChange:(p,f)=>c(f.value),children:d.map(p=>s.jsxs("option",{value:p,children:[Kh(p),p===l?" (current)":""]},p))})}),s.jsx(P,{size:200,style:{display:"block",marginTop:"8px"},children:"The group template defines how buttons scale when the ribbon is resized."}),o&&s.jsx(Ce,{intent:"warning",style:{marginTop:"12px"},children:s.jsx(Ie,{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."})})]}),s.jsxs(Yt,{children:[s.jsx(K,{appearance:"secondary",onClick:r,children:"Cancel"}),s.jsx(K,{appearance:"primary",onClick:u,disabled:a===l,children:"Change template"})]})]})})})},Yh=le({destructive:{backgroundColor:m.colorStatusDangerBackground3,color:m.colorNeutralForegroundOnBrand,":hover":{backgroundColor:m.colorStatusDangerBackground3Hover,color:m.colorNeutralForegroundOnBrand},":hover:active":{backgroundColor:m.colorStatusDangerBackground3Pressed,color:m.colorNeutralForegroundOnBrand}}}),Qi=({open:e,title:t,children:n,confirmLabel:o,cancelLabel:i="Cancel",destructive:r=!1,onConfirm:l,onCancel:a})=>{const c=Yh();return s.jsx(Ut,{modalType:"alert",open:e,onOpenChange:(d,u)=>!u.open&&a(),children:s.jsx(Xt,{style:{maxWidth:"480px"},children:s.jsxs(Kt,{children:[s.jsx(Vt,{children:t}),s.jsx(Jt,{children:n}),s.jsxs(Yt,{children:[s.jsx(K,{appearance:"secondary",onClick:a,children:i}),s.jsx(K,{appearance:"primary",className:r?c.destructive:void 0,onClick:l,children:o})]})]})})})};function Ja(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 Ya={add:{regular:Ae,filled:zu},delete:{regular:Ft,filled:Ou},edit:{regular:ao,filled:Eu},save:{regular:vr,filled:Du},copy:{regular:fn,filled:Au},cut:{regular:ku,filled:Tu},clipboardpaste:{regular:Nu,filled:$u},share:{regular:ju,filled:Ru},mail:{regular:Iu,filled:Cu},chat:{regular:wu,filled:Su},phone:{regular:vu,filled:xu},search:{regular:ft,filled:yu},filter:{regular:bu,filled:gu},arrowleft:{regular:hu,filled:fu},arrowright:{regular:pu,filled:mu},arrowup:{regular:uu,filled:du},arrowdown:{regular:cu,filled:lu},chevrondown:{regular:gt,filled:au},chevronup:{regular:$r,filled:ru},navigation:{regular:su,filled:iu},home:{regular:ou,filled:nu},settings:{regular:yr,filled:tu},info:{regular:eu,filled:Qd},warning:{regular:wr,filled:Zd},checkmark:{regular:Yd,filled:Jd},dismiss:{regular:ro,filled:Kd},questioncircle:{regular:xr,filled:Vd},lockclosed:{regular:It,filled:Xd},lockopen:{regular:Ud,filled:Gd},shield:{regular:Wd,filled:Hd},person:{regular:jr,filled:qd},people:{regular:_d,filled:Fd},personadd:{regular:Pd,filled:Ld},building:{regular:Md,filled:Bd},briefcase:{regular:zd,filled:Od},money:{regular:Ed,filled:Dd},creditcard:{regular:Ad,filled:kd},cart:{regular:Td,filled:Nd},tag:{regular:$d,filled:jd},document:{regular:so,filled:Rd},documentbulletlist:{regular:Id,filled:Cd},folder:{regular:wd,filled:Sd},folderopen:{regular:vd,filled:xd},attach:{regular:yd,filled:bd},arrowdownload:{regular:gd,filled:hd},arrowupload:{regular:fd,filled:pd},globe:{regular:Rr,filled:md},link:{regular:ud,filled:dd},open:{regular:cd,filled:ld},calendar:{regular:ad,filled:rd},clock:{regular:sd,filled:id},timer:{regular:od,filled:nd},star:{regular:td,filled:ed},heart:{regular:Qc,filled:Zc},thumblike:{regular:Yc,filled:Jc},thumbdislike:{regular:Kc,filled:Vc},eye:{regular:Ct,filled:Xc},eyeoff:{regular:Ye,filled:Uc},zoomin:{regular:Gc,filled:Wc},zoomout:{regular:Hc,filled:qc},maximize:{regular:_c,filled:Fc},minimize:{regular:Pc,filled:Lc},grid:{regular:Mc,filled:Bc},list:{regular:zc,filled:Oc},table:{regular:Ir,filled:Ec},tablesimple:{regular:Dc,filled:Ac},code:{regular:Gt,filled:kc},bug:{regular:Tc,filled:Nc},play:{regular:$c,filled:jc},pause:{regular:Rc,filled:Ic},stop:{regular:Cc,filled:wc},refresh:{regular:Sc,filled:vc},arrowsync:{regular:xc,filled:yc},arrowundo:{regular:hr,filled:bc},arrowredo:{regular:gr,filled:gc},printer:{regular:hc,filled:fc},send:{regular:pc,filled:mc},rocket:{regular:uc,filled:dc},sparkle:{regular:cc,filled:lc},trophy:{regular:ac,filled:rc},lightbulb:{regular:sc,filled:ic},bot:{regular:oc,filled:nc},databar:{regular:tc,filled:ec},chartmultiple:{regular:Ql,filled:Zl},poll:{regular:Yl,filled:Jl},layoutcolumntwo:{regular:Kl,filled:Vl},codeblock:{regular:Xl,filled:Ul},clockarrowcounterclockwise:{regular:Cr,filled:Gl}},$t=({name:e,size:t=20,variant:n="regular",style:o,className:i,"aria-hidden":r=!0})=>{const l=Ja(e).replace(/_/g,""),a=Ya[l],c=n==="filled"?a?.filled??a?.regular??_t:a?.regular??_t;return s.jsx(c,{fontSize:t,"aria-hidden":r,className:i,style:{display:"inline-block",verticalAlign:"middle",flexShrink:0,color:m.colorNeutralForeground1,...o}})};async function Ox(e,t=32,n="regular"){const o=Ja(e).replace(/_/g,""),i=Ya[o],r=n==="filled"?i?.filled??i?.regular:i?.regular;if(!r)return null;const{renderToStaticMarkup:l}=await $e(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(r,{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 Za="__end__";function Zh(e,t){return`slot::${e}::${t??Za}`}function Qh(e){return`group::${e}`}function Ls(e){if(e.startsWith("slot::")){const[,t,n]=e.split("::");return{kind:"slot",groupId:t,beforeButtonId:n===Za?null:n}}return e.startsWith("group::")?{kind:"group",groupId:e.slice(7)}:null}const Et={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 eg({button:e}){const t=O(i=>i.locLabels),n=ce(e.label,t),o=e.icon||"apps_add_in";return s.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:[s.jsx($t,{name:o,size:24}),s.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 tg({group:e,isDropTarget:t,children:n,...o}){const{setNodeRef:i,isOver:r}=Mr({id:Qh(e.id),data:{type:"group",groupId:e.id}});return s.jsx("div",{ref:i,style:{display:"flex",flexDirection:"column",minWidth:"80px",border:`1px solid ${r||t?m.colorBrandStroke1:m.colorNeutralStroke2}`,borderRadius:m.borderRadiusMedium,backgroundColor:r||t?m.colorBrandBackground2:m.colorNeutralBackground2,padding:`${m.spacingVerticalXS} ${m.spacingHorizontalXS}`,transition:"border-color 0.1s, background-color 0.1s"},...o,children:n})}function Ps({groupId:e,beforeButtonId:t}){const n=Zh(e,t),{setNodeRef:o,isOver:i}=Mr({id:n,data:{type:"slot",groupId:e,beforeButtonId:t}});return s.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 ng({tab:e,location:t}){const n=O(z=>z.locLabels),o=O(z=>z.baseLanguageCode),i=z=>ce(z.label,n,o)||z.id,r=O(z=>z.baseline),l=O(z=>z.templates),a=O(z=>z.moveButton),c=O(z=>z.createGroup),d=O(z=>z.deleteButton),u=O(z=>z.layers),p=O(z=>z.duplicateButton),f=O(z=>z.duplicateGroup),b=O(z=>z.setGroupTemplate),v=O(z=>z.hideOobButton),x=O(z=>z.customizeOobButton),h=O(z=>z.setButtonProp),y=O(z=>z.renameGroup),w=O(z=>z.deleteGroup),I=Y(z=>z.openNewButton),S=Y(z=>z.openNewGroup),C=Y(z=>z.openIconPicker),$=Y(z=>z.openLocalizationEditor),R=Z(z=>z.selectButtonInContext),E=Z(z=>z.selectGroup),[T,_]=M.useState(null),[D,L]=M.useState(null),[j,B]=M.useState(null),[N,W]=M.useState(null),[U,X]=M.useState(null),[Q,q]=M.useState(null),[F,J]=M.useState(null),[G,g]=M.useState(null),k=M.useMemo(()=>{if(!F)return null;for(const z of e.groups){const H=z.buttons.find(oe=>oe.id===F);if(H)return{button:H,groupId:z.id}}return null},[F,e.groups]),A=Er(Hn(zr,{activationConstraint:{distance:5}}),Hn(Or)),te=z=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&z.oob&&!z.custom,de=z=>Ze(z.kind);function Te(z){J(String(z.active.id))}function be(z){const H=z.over;if(!H){g(null);return}const oe=Ls(String(H.id));g(oe?oe.groupId:null)}function Me(z){const{active:H,over:oe}=z;if(J(null),g(null),!oe||!H)return;let ee=null;for(const Tt of e.groups)if(Tt.buttons.some(_l=>_l.id===H.id)){ee=Tt.id;break}if(!ee)return;const Re=Ls(String(oe.id));if(!Re)return;let se=null;Re.kind==="slot"?se=a({groupId:ee,buttonId:String(H.id),tabId:e.id,location:t},{groupId:Re.groupId,beforeButtonId:Re.beforeButtonId??void 0,tabId:e.id,location:t}):Re.kind==="group"&&Re.groupId!==ee&&(se=a({groupId:ee,buttonId:String(H.id),tabId:e.id,location:t},{groupId:Re.groupId,tabId:e.id,location:t})),se&&se!==String(H.id)&&R(t,e.id,Re.groupId,se)}return e.groups.length===0?s.jsxs("div",{style:Et.emptyTab,children:[s.jsx(so,{fontSize:36,"aria-hidden":!0}),s.jsx(P,{children:"This tab has no groups yet"}),s.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:()=>S(),children:[s.jsx(Ae,{fontSize:12})," Add first group"]})]}):s.jsxs(s.Fragment,{children:[t==="SubGrid"&&s.jsx(Ce,{intent:"info",style:{margin:`${m.spacingVerticalS} ${m.spacingHorizontalM} 0`},children:s.jsxs(Ie,{children:["Subgrid ribbons support only 3 native controls: ",s.jsx("strong",{children:"Add"}),","," ",s.jsx("strong",{children:"Show List"}),", and ",s.jsx("strong",{children:"Delete"}),". Their icons cannot be changed."]})}),s.jsxs(Br,{sensors:A,collisionDetection:Sm,onDragStart:Te,onDragOver:be,onDragEnd:Me,children:[s.jsxs("div",{style:Et.root,role:"treegrid","aria-label":"Ribbon canvas","data-ribbon-canvas-root":"1",children:[e.groups.map(z=>s.jsxs(tg,{group:z,isDropTarget:G===z.id,role:"rowgroup","aria-label":i(z),tabIndex:0,"data-ribbon-group-id":z.id,onContextMenu:H=>{H.target.closest("[data-btn]")||(H.preventDefault(),L({group:z,x:H.clientX,y:H.clientY}))},onFocus:()=>E(z.id),onKeyDown:H=>{if((H.key==="Enter"||H.key===" ")&&z.buttons.length>0){H.preventDefault();const oe=z.buttons[0];if(!oe)return;R(t,e.id,z.id,oe.id),document.querySelector(`[data-ribbon-btn-id="${oe.id}"]`)?.focus()}},children:[s.jsxs("div",{style:Et.groupButtons,children:[z.buttons.map(H=>s.jsxs(Ue.Fragment,{children:[F&&s.jsx(Ps,{groupId:z.id,beforeButtonId:H.id}),s.jsx(og,{button:H,groupId:z.id,tabId:e.id,location:t,activeId:F,onContextMenu:oe=>_({groupId:z.id,button:H,x:oe.clientX,y:oe.clientY})})]},H.id)),F&&s.jsx(Ps,{groupId:z.id,beforeButtonId:null}),s.jsxs("button",{type:"button",style:Et.addButtonGhost,"data-add-btn-group-id":z.id,onClick:()=>I(z.id),title:`Add button to ${i(z)}`,"aria-label":`Add button to ${i(z)}`,children:[s.jsx(Ae,{fontSize:16}),s.jsx(P,{size:100,style:{color:"inherit"},children:"Add"})]})]}),s.jsx(Ne,{content:`Template: ${z.template||"Flexible2"}`,relationship:"description",children:s.jsx("div",{style:Et.groupLabel,children:i(z)})})]},z.id)),s.jsx("button",{type:"button",style:Et.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:s.jsx(Ae,{fontSize:16})})]}),s.jsx(wm,{dropAnimation:null,children:k?s.jsx(eg,{button:k.button}):null})]}),T&&s.jsxs(Xo,{open:!0,onOpenChange:(z,H)=>!H.open&&_(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:T.x,y:T.y,top:T.y,left:T.x,right:T.x,bottom:T.y,width:0,height:0,toJSON:()=>({})})}},children:[s.jsx(Vo,{disableButtonEnhancement:!0,children:s.jsx("span",{style:{display:"none"}})}),s.jsx(Ko,{children:s.jsxs(Jo,{children:[te(T.button)&&s.jsx(me,{disabled:!0,icon:s.jsx(It,{}),children:"OOB global command bar buttons cannot be customized."}),te(T.button)&&s.jsx(pt,{}),s.jsx(me,{icon:s.jsx(ao,{}),onClick:()=>{R(t,e.id,T.groupId,T.button.id),_(null)},children:"Edit properties"}),s.jsx(me,{icon:s.jsx(qn,{}),disabled:te(T.button)||de(T.button),onClick:()=>{R(t,e.id,T.groupId,T.button.id),C(),_(null)},children:"Change icon…"}),s.jsx(me,{icon:s.jsx(Nr,{}),disabled:te(T.button)||de(T.button),onClick:()=>{$(T.button.id),_(null)},children:"Edit labels…"}),s.jsx(pt,{}),T.button.hidden?s.jsx(me,{icon:s.jsx(Ct,{}),disabled:te(T.button),onClick:()=>{h(t,e.id,T.groupId,T.button.id,{hidden:!1}),_(null)},children:"Show button"}):s.jsx(me,{icon:s.jsx(Ye,{}),disabled:te(T.button),onClick:()=>{T.button.oob?B(T):h(t,e.id,T.groupId,T.button.id,{hidden:!0}),_(null)},children:"Hide button"}),(T.button.origin==="oob"||T.button.origin==="managed")&&s.jsx(me,{icon:s.jsx(_t,{}),disabled:te(T.button)||de(T.button),onClick:()=>{x(t,e.id,T.groupId,T.button.id),_(null)},children:"Create override…"}),s.jsx(Va,{location:t,tabId:e.id,groupId:T.groupId,button:T.button,onDone:()=>_(null)}),s.jsx(pt,{}),s.jsx(me,{icon:s.jsx(fn,{}),disabled:te(T.button),onClick:()=>{p(t,e.id,T.groupId,T.button.id),_(null)},children:"Duplicate"}),Ka(e,T.groupId,T.button.id,n,o).map(z=>s.jsxs(me,{icon:s.jsx(Tr,{}),disabled:te(T.button),onClick:()=>{const H=a({groupId:T.groupId,buttonId:T.button.id,tabId:e.id,location:t},{groupId:z.groupId,tabId:e.id,location:t});H&&R(t,e.id,z.groupId,H),_(null)},children:["Move to: ",z.text]},z.groupId)),$n(T.button,r[t])&&s.jsxs(s.Fragment,{children:[s.jsx(pt,{}),s.jsx(me,{icon:s.jsx(Ft,{}),disabled:te(T.button),onClick:()=>{d(t,e.id,T.groupId,T.button.id),_(null)},children:"Delete"})]})]})})]}),D&&s.jsxs(Xo,{open:!0,onOpenChange:(z,H)=>!H.open&&L(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:D.x,y:D.y,top:D.y,left:D.x,right:D.x,bottom:D.y,width:0,height:0,toJSON:()=>({})})}},children:[s.jsx(Vo,{disableButtonEnhancement:!0,children:s.jsx("span",{style:{display:"none"}})}),s.jsx(Ko,{children:s.jsxs(Jo,{children:[ba("group",D.group.id,r[t],Ui({layers:u},t))?s.jsx(me,{icon:s.jsx(cs,{}),onClick:()=>{W(D.group),L(null)},children:"Rename…"}):s.jsx(me,{icon:s.jsx(cs,{}),disabled:!0,title:Fi,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),s.jsx(me,{icon:s.jsx(fn,{}),onClick:()=>{f(t,e.id,D.group.id),L(null)},children:"Duplicate group"}),s.jsx(me,{icon:s.jsx(_t,{}),onClick:()=>{X(D.group),L(null)},children:"Change template…"}),Pi(D.group,r[t],Qn({layers:u},t))&&s.jsxs(s.Fragment,{children:[s.jsx(pt,{}),s.jsx(me,{icon:s.jsx(Ft,{}),onClick:()=>{q(D.group),L(null)},children:"Delete group"})]})]})})]}),N&&s.jsx(Vh,{open:!0,initialLabel:i(N),onRename:z=>{y(t,e.id,N.id,z),W(null)},onCancel:()=>W(null)}),U&&s.jsx(Jh,{open:!0,currentTemplate:U.template,customTemplateIds:l.map(z=>z.id),loadedGroup:r[t].tabs.some(z=>z.id===e.id&&z.groups.some(H=>H.id===U.id)),onChange:z=>{b(t,e.id,U.id,z),X(null)},onCancel:()=>X(null)}),Q&&s.jsxs(Qi,{open:!0,title:"Delete group",confirmLabel:"Delete group",destructive:!0,onConfirm:()=>{w(t,e.id,Q.id),q(null)},onCancel:()=>q(null),children:["Delete the group “",i(Q),"” and its ",Q.buttons.length," button",Q.buttons.length===1?"":"s","?"]}),j&&s.jsx(Zi,{open:!0,buttonLabel:ce(j.button.label,n),onConfirmHide:()=>{v(t,e.id,j.groupId,j.button.id),B(null)},commandId:j.button.commandId,onConfirmDisplayRule:()=>{O.getState().hideWithDisplayRules(j.button.commandId),B(null)},onCancel:()=>B(null)})]})}const og=Ue.memo(function({button:t,groupId:n,tabId:o,location:i,activeId:r,onContextMenu:l}){const a=Z(R=>R.selectedButtonId),c=Z(R=>R.selectButtonInContext),d=O(R=>R.locLabels),u=a===t.id,p=i==="Application"&&o==="Mscrm.GlobalTab"&&t.oob&&!t.custom,f=ce(t.label,d),b=Ze(t.kind)?Gn[t.kind]:void 0,v=b?` (${b}, read-only)`:"",{attributes:x,listeners:h,setNodeRef:y,isDragging:w}=vm({id:t.id,data:{type:"button",button:t,groupId:n},disabled:t.managed||p}),I=w||r===t.id,S={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:I?.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"},C=t.icon||"apps_add_in",$=R=>{if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(R.key))return;R.preventDefault();const E=R.currentTarget.closest("[data-ribbon-canvas-root='1']");if(!E)return;const T=Array.from(E.querySelectorAll(`[data-ribbon-tab-id="${o}"][data-btn="1"]`)),_=T.findIndex(W=>W.dataset.ribbonBtnId===t.id);if(_<0||T.length===0)return;const D=R.key==="ArrowLeft"||R.key==="ArrowUp"?-1:1,L=Math.max(0,Math.min(T.length-1,_+D)),j=T[L],B=j?.dataset.ribbonGroupId,N=j?.dataset.ribbonBtnId;!j||!B||!N||(c(i,o,B,N),j.focus())};return s.jsx(Ne,{content:p?"OOB global command bar buttons cannot be customized.":`${f}${v}${t.hidden?" — hidden":""}`,relationship:"label",children:s.jsxs("button",{ref:y,type:"button","data-btn":"1","data-ribbon-tab-id":o,"data-ribbon-group-id":n,"data-ribbon-btn-id":t.id,style:S,"aria-selected":u,"aria-label":`${f}${v}${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}$(R)},onContextMenu:R=>{R.preventDefault(),R.stopPropagation(),c(i,o,n,t.id),l(R)},...x,...h,children:[s.jsx($t,{name:C,size:24,style:{filter:t.custom?"none":"grayscale(40%) opacity(0.85)"}}),s.jsx("span",{style:{fontSize:m.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:m.colorNeutralForeground1},children:f}),b&&s.jsx("span",{style:{fontSize:m.fontSizeBase100,lineHeight:"1",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:m.colorNeutralForeground3},children:b}),t.menu&&s.jsx(gt,{fontSize:10,"aria-label":"Has a menu"}),t.hidden&&s.jsx("span",{style:{position:"absolute",top:2,right:2},"aria-hidden":!0,children:s.jsx(Ye,{fontSize:10,style:{color:m.colorNeutralForeground3}})}),t.custom&&!t.managed&&s.jsx(ae,{size:"extra-small",color:"brand",appearance:"tint",style:{position:"absolute",bottom:2,right:2},"aria-label":"Custom",children:"NEW"}),(t.managed||p)&&s.jsx("span",{style:{position:"absolute",top:2,left:2},title:p?"OOB global command bar buttons cannot be customized.":"Read-only (managed)",children:s.jsx(It,{fontSize:10,style:{color:m.colorNeutralForeground3}})})]})})}),fe=jt()((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(),r=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:r?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&&Z.getState().clearSelection(),e({selectedCommandId:n})}}));Z.subscribe((e,t)=>{if(!fe.getState().selectedCommandId)return;(e.selectedButtonId&&e.selectedButtonId!==t.selectedButtonId||e.location!==t.location||e.tabId!==t.tabId)&&fe.setState({selectedCommandId:null})});const cn={Form:0,MainGrid:1,SubGrid:2,AssociatedGrid:3,GlobalHeader:5},Qa={0:"Form",1:"Main grid",2:"Subgrid",3:"Associated grid",4:"Quick form",5:"Global header",6:"Dashboard"},el="appaction_appactionrule_classicrules",ig=["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"],_o="@OData.Community.Display.V1.FormattedValue",we=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},On=e=>e===!0||e===1||e==="true"||e==="1",xt=e=>{const t=we(e);return t?t.toLowerCase():null};function sg(e){switch(ct(e)){case 1:return"dropdown";case 2:return"split";case 3:return"group";default:return"button"}}function rg(e){const t=ct(e);return t===1?"formula":t===2?"javascript":"none"}function ag(e){const t=ct(e);return t===1?"formula":t===2?"classicRules":"none"}function lg(e){const t=ct(e);return t===1?"migrated":t===2?"enhancedMigrated":"default"}function Fs(e,t){const n={componentLibrary:we(e[`${t}componentlibrary`]),componentName:we(e[`${t}componentname`]),functionName:we(e[`${t}functionname`])};return n.componentLibrary||n.componentName||n.functionName?n:void 0}function cg(e){return Array.isArray(e)?e.map(t=>{const n=xt(t.appactionruleid);return n?{id:n,name:we(t.name)??we(t.uniquename)??n,uniqueName:we(t.uniquename),kind:ct(t.type)===0?"enable":"display"}:null}).filter(t=>t!==null):[]}function dg(e){const t=xt(e.appactionid);if(!t)return null;const n=ct(e.location);if(n===void 0)return null;const o=we(e.name)??"",i=we(e.uniquename)??o;return{id:t,name:o,uniqueName:i,label:we(e.buttonlabeltext)??(o||i||t),tooltipTitle:we(e.buttontooltiptitle),tooltipDescription:we(e.buttontooltipdescription),accessibilityText:we(e.buttonaccessibilitytext),appModuleId:xt(e._appmoduleid_value),appName:we(e[`_appmoduleid_value${_o}`]),scope:ct(e.context)===0?"all":"entity",contextValue:we(e.contextvalue),contextEntityId:xt(e._contextentity_value)??void 0,location:n,type:sg(e.type),sequence:ct(e.sequence)??ct(e.buttonsequencepriority)??0,hidden:On(e.hidden),disabled:On(e.isdisabled),origin:lg(e.origin),managed:On(e.ismanaged),fontIcon:we(e.fonticon),iconWebResourceId:xt(e._iconwebresourceid_value)??void 0,iconWebResourceName:we(e[`_iconwebresourceid_value${_o}`]),parentId:xt(e._parentappactionid_value),groupTitle:we(e.grouptitle),groupTitleHidden:On(e.isgrouptitlehidden),action:rg(e.onclickeventtype),jsFunctionName:we(e.onclickeventjavascriptfunctionname),jsParameters:we(e.onclickeventjavascriptparameters),jsWebResourceId:xt(e._onclickeventjavascriptwebresourceid_value)??void 0,jsWebResourceName:we(e[`_onclickeventjavascriptwebresourceid_value${_o}`]),onSelectFormula:Fs(e,"onclickeventformula"),visibility:ag(e.visibilitytype),visibilityFormula:Fs(e,"visibilityformula"),classicRules:cg(e[el])}}function ug(e){const t=new Map;for(const n of e){const o=dg(n);o&&!t.has(o.id)&&t.set(o.id,o)}return[...t.values()]}function mg(e){switch(e){case"HomepageGrid":return[cn.MainGrid];case"SubGrid":return[cn.SubGrid,cn.AssociatedGrid];case"Form":return[cn.Form];case"Application":return[cn.GlobalHeader]}}function pg(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 fg(e,t){return t==="all"||e.appModuleId===null||e.appModuleId===t.toLowerCase()}function hg(e,t){const n=new Set(mg(t.location));return e.filter(o=>n.has(o.location)&&fg(o,t.appFilter)&&pg(o,t.table))}const wi=(e,t)=>e.sequence-t.sequence||e.label.localeCompare(t.label)||e.id.localeCompare(t.id);function tl(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,r=l=>{i.add(l.id);const a=(n.get(l.id)??[]).filter(c=>!i.has(c.id)).sort(wi);return{command:l,children:a.map(r)}};return o.sort(wi).map(r)}function nl(e){return e.flatMap(t=>[t.command,...nl(t.children)])}const ol=/\{!EntityLogicalName\}/gi,gg=/(?:![A-Za-z0-9_]+)*!\d+$/;function bg(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 r=i.trim().replace(ol,t).replace(gg,""),l=r.indexOf("_"),a=r.indexOf(".");l>0&&(a===-1||l<a)&&o(r.slice(l+1)),o(r)}return n}function Ci(e,t){return e.replace(ol,t).toLowerCase()}function _s(e,t){const n=Ci(e,t).split(".");return n.length<4||n[0]!=="mscrm"?null:[n[0],n[1],"*",...n.slice(3)].join(".")}function qs(e,t,n,o={}){const i=new Map,r=new Map;for(const a of t){const c=Ci(a,n);i.has(c)||i.set(c,a);const d=_s(a,n);d&&!r.has(d)&&r.set(d,a)}const l=new Map;for(const a of e){if(a.disabled&&!o.includeDisabled)continue;const c=bg(a,n),d=c.map(p=>i.get(Ci(p,n))).find(Boolean)??c.map(p=>_s(p,n)).map(p=>p?r.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 yg(e,t,n){const o=l=>l.toLowerCase(),i=`mscrm.${o(t)}.${o(n)}.maintab`,r=e.find(l=>l.id==="Mscrm.GlobalTab")?.id;return t==="Application"&&r?r:e.find(l=>o(l.id)===i)?.id??e.find(l=>/maintab$/i.test(l.id)&&!/\.allentities\./i.test(l.id))?.id??r??e[0]?.id}function il(e){return(e.menu?.sections??[]).flatMap(t=>t.controls.flatMap(n=>[n,...il(n)]))}function xg(e){const{commands:t,tabs:n,location:o,entityLogicalName:i}=e,r=n.flatMap(y=>y.groups.flatMap(w=>w.buttons)),l=[...r,...r.flatMap(il)].map(y=>y.id),a=new Map(t.map(y=>[y.id,y])),c=new Set([...qs(t,l,i,{includeDisabled:!0}).values()].flat().map(y=>y.command.id)),d=new Map,u=(y,w=new Set)=>{const I=d.get(y.id);if(I!==void 0)return I;let S=y.parentId?a.get(y.parentId):void 0;for(const $=new Set;S?.type==="group"&&!c.has(S.id)&&!$.has(S.id);)$.add(S.id),S=S.parentId?a.get(S.parentId):void 0;const C=c.has(y.id)&&(!S||!w.has(S.id)&&u(S,w.add(y.id)));return d.set(y.id,C),C},f=(y=>{for(const[w,I]of y){const S=I.filter(C=>u(C.command));S.length>0?y.set(w,S):y.delete(w)}return y})(qs(t,l,i)),b=new Set([...f.values()].flat().map(y=>y.command.id)),v=y=>{const w=new Set;for(let I=y.parentId;I&&!w.has(I);I=a.get(I)?.parentId??null){w.add(I);const S=a.get(I);if(S&&u(S))return I}},x=new Map,h=[];for(const y of t){const w=v(y);if(!w){u(y)||h.push(y);continue}if(b.has(y.id))continue;const I=x.get(w)??[];I.push(y),x.set(w,I)}for(const y of f.values())for(const w of y){const I=x.get(w.command.id);I&&(w.items=[...I].sort(wi))}return{commandBarTabId:yg(n,o,i),nodes:tl(h),overrides:f,unmatchedMigrated:h.filter(y=>y.origin!=="default")}}function vg(e,t){const n=new Map,o=[];for(const i of t){const r=e.find(a=>a.sequence>i.command.sequence);if(!r){o.push(i);continue}const l=n.get(r.id)??[];l.push(i),n.set(r.id,l)}return{before:n,trailing:o}}function Hs(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 Sg(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 wg(e,t,n){const o=new Map(t.map(r=>[r.id.toLowerCase(),r])),i=new Map;for(const r of n??[]){const l=o.get(r.toLowerCase());l&&i.set(l.id.toLowerCase(),l)}if(n)return[...i.values()].sort((r,l)=>r.name.localeCompare(l.name)||r.id.localeCompare(l.id));for(const r of e)!r.appModuleId||i.has(r.appModuleId)||i.set(r.appModuleId,o.get(r.appModuleId)??{id:r.appModuleId,name:r.appName??r.appModuleId});return[...i.values()].sort((r,l)=>r.name.localeCompare(l.name)||r.id.localeCompare(l.id))}function wn(e,t){return e.appModuleId===null?"All apps":t?.get(e.appModuleId)??e.appName??e.appModuleId}function es(e,t){const n=wn(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(r=>r.label).join(", ")}`:i}function sl(e,t){if(!e?.length)return"";const n=e.find(o=>o.effect==="hidden");return n?` — ${es(n,t).replace(/^Hidden/,"hidden")}`:" — modern (migrated)"}const Cg={button:"Command",dropdown:"Dropdown",split:"Split button",group:"Group"},Ig={default:"Command designer",migrated:"Migrated from classic",enhancedMigrated:"Enhanced migrated from classic"};function rl(e,t){const n=[{label:"App",value:wn(e,t)},{label:"Location",value:`${Qa[e.location]??`Location ${e.location}`}${e.scope==="all"?" (all tables)":""}`},{label:"Type",value:Cg[e.type]},{label:"Order",value:String(e.sequence)},{label:"Origin",value:Ig[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:Hs(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:Hs(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 Rg(){return window.dataverseAPI}const Cn=e=>e instanceof Error?e.message:String(e);async function io(e){const t=[],n=new Set;let o=e;for(;o&&!n.has(o);){n.add(o);const i=await Rg().queryData(o);t.push(...i.value??[]);const r=i["@odata.nextLink"];o=r?r.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}function al(e){return/\b40[13]\b|0x80040220|prvRead|privilege|unauthori[sz]ed|forbidden|not have permission/i.test(Cn(e))}const ll=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ws(e,t){const n=[`contextvalue eq '${e.logicalName.replace(/'/g,"''")}'`];e.metadataId&&ll.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=${el}($select=appactionruleid,name,uniquename,type)`:"";return`appactions?$select=${ig.join(",")}&$filter=${o}${i}`}async function jg(e){const t=ie.getState();let n;try{n=await io(Ws(e,!0))}catch(o){if(al(o))throw o;t.logInfo("dataverse",`Modern commands: classic rules couldn't be expanded (${Cn(o)}); retrying without them.`),n=await io(Ws(e,!1))}return ug(n)}async function $g(e){const t=ie.getState(),n="appmodules?$select=appmoduleid,appmoduleidunique,name,uniquename",o=e.metadataId&&ll.test(e.metadataId)?`appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 1 and objectid eq ${e.metadataId}`:null,[i,r]=await Promise.all([io(n),o?io(o).catch(d=>(t.logInfo("dataverse",`Modern commands: couldn't resolve which apps contain ${e.logicalName} (${Cn(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(r){const d=new Set(r.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 Ng(e){const t=ie.getState(),[n,o]=await Promise.allSettled([jg(e),$g(e)]);if(n.status==="rejected"){const a=Cn(n.reason);return t.logWarn("dataverse",al(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 (${Cn(o.reason)}); showing app ids from the commands.`);const{apps:i,containingAppIds:r}=o.status==="fulfilled"?o.value:{apps:[],containingAppIds:null},l=Sg(n.value,r);return t.logInfo("dataverse",`Loaded ${l.length} modern command${l.length===1?"":"s"} for ${e.logicalName}.`),{commands:l,apps:wg(l,i,r)}}function Tg(){const e=ne(n=>n.activeEntity?.logicalName),t=ne(n=>n.activeEntity?.metadataId);M.useEffect(()=>{const n=fe.getState();if(!e||typeof window.dataverseAPI>"u"){n.reset();return}const o=n.beginLoad(e);Ng({logicalName:e,metadataId:t}).then(i=>fe.getState().finishLoad(o,i))},[e,t])}function en(){const e=fe(n=>n.apps),t=fe(n=>n.commands);return M.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 cl(e){const t=fe(r=>r.commands),n=fe(r=>r.appFilter),o=ne(r=>r.activeEntity?.logicalName),i=ne(r=>r.activeEntity?.metadataId);return M.useMemo(()=>o?hg(t,{location:e,appFilter:n,table:{logicalName:o,metadataId:i}}):[],[t,n,e,o,i])}const Ii=new Set;function kg(){Ii.clear()}function ts(e){const t=cl(e),n=ne(u=>u.activeEntity?.logicalName)??"",o=O(u=>u.ribbons[e]?.tabs),i=O(u=>u.ribbons[e]?.entityLogicalName??""),r=fe(u=>u.status==="loaded"?u.tableLogicalName:null),l=(o?.length??0)>0&&(e==="Application"||i.toLowerCase()===n.toLowerCase()),a=M.useMemo(()=>xg({commands:t,tabs:l?o??[]:[],location:e,entityLogicalName:n}),[t,o,l,e,n]),d=!!n&&r===n&&l?a.unmatchedMigrated.map(u=>u.uniqueName).join(", "):"";return M.useEffect(()=>{const u=`${n}|${e}|${d}`;!d||Ii.has(u)||(Ii.add(u),ie.getState().logInfo("ribbon",`Migrated modern commands without a classic control in ${n} ${e}: ${d}`))},[d,n,e]),a}function ns(e,t){const n=ts(e);return M.useMemo(()=>{const o=t.groups.flatMap(r=>r.buttons.map(l=>({id:l.id,sequence:l.sequence}))),i=t.id===n.commandBarTabId?n.nodes:[];return{nodes:i,placement:vg(o,i),overrides:n.overrides}},[n,t])}function Ag(e,t){const{overrides:n}=ts(e);return t&&n.get(t)||Dg}const Dg=[];function Eg(){const e=fe(i=>i.selectedCommandId),t=Z(i=>i.selectedButtonId),n=Z(i=>i.location),o=cl(n);return M.useMemo(()=>{if(!e||t)return null;const i=o.find(l=>l.id===e);if(!i)return null;let r;for(const l of tl(o))if(r=dl(l,e),r)break;return{command:i,children:r?nl(r.children):[]}},[e,t,o])}function dl(e,t){if(e.command.id===t)return e;for(const n of e.children){const o=dl(n,t);if(o)return o}}const ul=le({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 ml({node:e,appNames:t}){const n=ul(),o=e.command;return s.jsxs("div",{className:n.tooltip,children:[s.jsx(P,{weight:"semibold",children:o.label}),s.jsx(P,{className:n.tooltipRow,children:"Modern command — read-only in CBS; edit it in the command designer."}),rl(o,t).map(i=>s.jsxs(P,{className:n.tooltipRow,children:[s.jsxs("b",{children:[i.label,":"]})," ",i.value]},i.label)),e.children.length>0&&s.jsxs(P,{className:n.tooltipRow,children:[s.jsx("b",{children:"Items:"})," ",e.children.map(i=>i.command.label).join(", ")]})]})}function Og({node:e,appNames:t,showApp:n,onDragRejected:o}){const i=ul(),r=e.command,l=fe(v=>v.selectedCommandId),a=fe(v=>v.selectCommand),c=Z(v=>v.selectedButtonId),d=l===r.id&&!c,u=r.type==="dropdown"||r.type==="split"||e.children.length>0,p=r.fontIcon&&!r.fontIcon.startsWith("$")?r.fontIcon:"apps_add_in",f=`${r.hidden?" — hidden":""}${r.disabled?" — disabled":""}`,b=v=>{v.preventDefault(),v.stopPropagation(),v.dataTransfer.dropEffect="none",o?.()};return s.jsx(Ne,{content:s.jsx(ml,{node:e,appNames:t}),relationship:"description",children:s.jsxs("button",{type:"button",draggable:!1,className:qt(i.chip,d&&i.selected,(r.hidden||r.disabled)&&i.muted,r.hidden&&i.hidden),"aria-pressed":d,"aria-label":`${r.label} — modern command (read-only), ${wn(r,t)}${f}`,onClick:()=>a(r.id),onDragStart:v=>v.preventDefault(),onDragOver:b,onDrop:b,onContextMenu:v=>{v.preventDefault(),a(r.id)},children:[s.jsx($t,{name:p,size:16}),s.jsx(P,{size:200,children:r.label}),u&&s.jsx(gt,{fontSize:12,"aria-hidden":!0}),r.hidden&&s.jsx(Ye,{fontSize:12,"aria-hidden":!0}),s.jsx(ae,{size:"extra-small",appearance:"tint",color:"important",icon:s.jsx(It,{}),children:"Modern"}),n&&s.jsx(ae,{size:"extra-small",appearance:"outline",color:"informative",children:wn(r,t)})]})})}function os({overrides:e,appNames:t}){if(!e?.length)return null;const n=e.some(i=>i.effect==="hidden"),o=e.map(i=>es(i,t)).join(`
|
|
135
|
-
`);return s.jsx(ae,{size:"extra-small",appearance:"tint",color:n?"warning":"important",title:o,"aria-label":o,children:n?"Hidden by modern":"Modern (migrated)"})}const zn="application/x-rw-btn",Gs="application/x-rw-se",zg=le({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 Bg({tab:e,location:t}){const n=zg(),o=Z(g=>g.selectedButtonId),i=Z(g=>g.selectButtonInContext),r=O(g=>g.moveButton),l=O(g=>g.deleteButton),a=O(g=>g.baseline),c=O(g=>g.duplicateButton),d=O(g=>g.hideOobButton),u=O(g=>g.setButtonProp),p=O(g=>g.customizeOobButton),f=O(g=>g.locLabels),b=O(g=>g.baseLanguageCode),v=(g,k)=>ce(g,f,b)||k,x=Y(g=>g.openIconPicker),h=Y(g=>g.openLocalizationEditor),y=Y(g=>g.openNewButton),[w,I]=M.useState(null),[S,C]=M.useState(null),[$,R]=M.useState(null),[E,T]=M.useState(null),_=ns(t,e),D=en(),L=fe(g=>g.appFilter==="all"),j=g=>s.jsx(Og,{node:g,appNames:D,showApp:L,onDragRejected:()=>I(null)},g.command.id),B=g=>sl(_.overrides.get(g.id),D),N=g=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&g.oob&&!g.custom,W=g=>Ze(g.kind),U=g=>W(g)?` (${Gn[g.kind]}, read-only)`:"",X=e.groups.flatMap(g=>g.buttons.map(k=>({button:k,groupId:g.id})));function Q(g,k,A){g.dataTransfer.setData(zn,JSON.stringify({groupId:k,buttonId:A})),g.dataTransfer.effectAllowed="move",C(A)}function q(){C(null),I(null)}function F(g,k){const A=Array.from(g.dataTransfer.types??[]);!A.includes(zn)&&!A.includes(Gs)||(g.preventDefault(),g.dataTransfer.dropEffect=A.includes(zn)?"move":"copy",I({beforeButtonId:k}))}const J=O(g=>g.createButton);function G(g,k,A){g.preventDefault(),g.stopPropagation();const te=g.dataTransfer.getData(zn);if(te){try{const Te=JSON.parse(te);if(Te?.buttonId){const be=r({groupId:Te.groupId,buttonId:Te.buttonId,tabId:e.id,location:t},{groupId:k,beforeButtonId:A??void 0,tabId:e.id,location:t});be&&be!==Te.buttonId&&i(t,e.id,k,be)}}catch{}I(null),C(null);return}const de=g.dataTransfer.getData(Gs);if(de){try{const be=JSON.parse(de)?.button;if(be){const Me=`_copy_${Date.now()}`;J({location:t,tabId:e.id,groupId:k,button:{...Kn(be,`${be.id}${Me}`),label:be.label??"New Button",kind:be.kind??"button",sequence:50,templateAlias:be.templateAlias??"o1",commandId:be.commandId??"",hidden:!1,oob:!1,custom:!0,managed:!1}})}}catch{}I(null),C(null);return}I(null),C(null)}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:n.root,children:[s.jsxs("div",{className:n.scrollRow,onDragOver:g=>{g.preventDefault()},onDrop:g=>G(g,e.groups[0]?.id??"",null),children:[X.map(({button:g,groupId:k})=>s.jsxs(Ue.Fragment,{children:[_.placement.before.get(g.id)?.map(j),w?.beforeButtonId===g.id&&s.jsx("div",{className:n.dropLine,"aria-hidden":!0}),s.jsx(Ne,{content:N(g)?"OOB global command bar buttons cannot be customized.":`${ce(g.label,f)}${U(g)}${g.hidden?" — hidden":""}${B(g)}`,relationship:"label",children:s.jsxs("button",{type:"button",className:[n.button,o===g.id?n.buttonSelected:"",g.hidden?n.buttonHidden:"",g.custom?n.buttonCustom:""].filter(Boolean).join(" "),"aria-selected":o===g.id,"aria-label":`${ce(g.label,f)}${U(g)}${g.hidden?" — hidden":""}${B(g)}`,onClick:()=>i(t,e.id,k,g.id),onContextMenu:A=>{A.preventDefault(),i(t,e.id,k,g.id),R({button:g,groupId:k,x:A.clientX,y:A.clientY})},draggable:!g.managed&&!N(g),onDragStart:A=>Q(A,k,g.id),onDragEnd:q,onDragOver:A=>F(A,g.id),onDrop:A=>G(A,k,g.id),style:{opacity:S===g.id?.3:void 0},children:[s.jsx($t,{name:g.icon||"apps_add_in",size:16}),s.jsx(P,{size:200,children:ce(g.label,f)}),W(g)&&s.jsx(ae,{size:"extra-small",appearance:"outline",color:"informative",children:Gn[g.kind]}),g.menu&&s.jsx(gt,{fontSize:12,"aria-label":"Has a menu"}),g.hidden&&s.jsx(Ye,{fontSize:12,"aria-hidden":!0}),g.custom&&s.jsx(ae,{size:"extra-small",color:"brand",appearance:"tint","aria-label":"Custom",children:"NEW"}),s.jsx(os,{overrides:_.overrides.get(g.id),appNames:D}),N(g)&&s.jsx("span",{className:n.lockIcon,title:"OOB global command bar buttons cannot be customized.",children:s.jsx(It,{fontSize:12})})]})})]},g.id)),_.placement.trailing.map(j)]}),s.jsx("div",{className:n.trailingControls,children:(()=>{const g=e.groups[0];return g?s.jsx(Ne,{content:`Add a new button to "${v(g.label,g.id)}"`,relationship:"label",children:s.jsxs("button",{type:"button",className:n.overflowBtn,onClick:()=>y(g.id),"aria-label":"Add a new button",children:[s.jsx(Ae,{fontSize:14})," Add"]})}):s.jsx(Ne,{content:'No groups in this tab yet. Switch to "Classic ribbon" view to add a group first.',relationship:"label",children:s.jsxs("button",{type:"button",className:n.overflowBtn,disabled:!0,children:[s.jsx(Ae,{fontSize:14})," Add"]})})})()})]}),$&&s.jsxs(Xo,{open:!0,onOpenChange:(g,k)=>!k.open&&R(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:$.x,y:$.y,top:$.y,left:$.x,right:$.x,bottom:$.y,width:0,height:0,toJSON:()=>({})})}},children:[s.jsx(Vo,{disableButtonEnhancement:!0,children:s.jsx("span",{style:{display:"none"}})}),s.jsx(Ko,{children:s.jsxs(Jo,{children:[N($.button)&&s.jsx(me,{disabled:!0,children:"OOB global command bar buttons cannot be customized."}),N($.button)&&s.jsx(pt,{}),s.jsx(me,{icon:s.jsx(ao,{}),onClick:()=>{i(t,e.id,$.groupId,$.button.id),R(null)},children:"Edit properties"}),s.jsx(me,{icon:s.jsx(qn,{}),disabled:N($.button)||W($.button),onClick:()=>{i(t,e.id,$.groupId,$.button.id),x(),R(null)},children:"Change icon…"}),s.jsx(me,{icon:s.jsx(Nr,{}),disabled:N($.button)||W($.button),onClick:()=>{h($.button.id),R(null)},children:"Edit labels…"}),s.jsx(pt,{}),$.button.hidden?s.jsx(me,{icon:s.jsx(Ct,{}),disabled:N($.button),onClick:()=>{u(t,e.id,$.groupId,$.button.id,{hidden:!1}),R(null)},children:"Show button"}):s.jsx(me,{icon:s.jsx(Ye,{}),disabled:N($.button),onClick:()=>{$.button.oob?T($):u(t,e.id,$.groupId,$.button.id,{hidden:!0}),R(null)},children:"Hide button"}),($.button.origin==="oob"||$.button.origin==="managed")&&s.jsx(me,{icon:s.jsx(_t,{}),disabled:N($.button)||W($.button),onClick:()=>{p(t,e.id,$.groupId,$.button.id),R(null)},children:"Create override…"}),s.jsx(Va,{location:t,tabId:e.id,groupId:$.groupId,button:$.button,onDone:()=>R(null)}),s.jsx(pt,{}),s.jsx(me,{icon:s.jsx(fn,{}),disabled:N($.button),onClick:()=>{c(t,e.id,$.groupId,$.button.id),R(null)},children:"Duplicate"}),$n($.button,a[t])&&s.jsx(me,{icon:s.jsx(Ft,{}),disabled:N($.button),onClick:()=>{l(t,e.id,$.groupId,$.button.id),R(null)},children:"Delete"}),Ka(e,$.groupId,$.button.id,f,b).map(g=>s.jsxs(me,{icon:s.jsx(Tr,{}),disabled:N($.button),onClick:()=>{const k=r({groupId:$.groupId,buttonId:$.button.id,tabId:e.id,location:t},{groupId:g.groupId,tabId:e.id,location:t});k&&i(t,e.id,g.groupId,k),R(null)},children:["Move to: ",g.text]},g.groupId))]})})]}),E&&s.jsx(Zi,{open:!0,buttonLabel:ce(E.button.label,f),onConfirmHide:()=>{d(t,e.id,E.groupId,E.button.id),T(null)},commandId:E.button.commandId,onConfirmDisplayRule:()=>{O.getState().hideWithDisplayRules(E.button.commandId),T(null)},onCancel:()=>T(null)})]})}const Mg=e=>(Ku({...e,renderRow:()=>null}),e),pl=M.createContext(void 0),Lg=void 0,Pg=()=>{var e;return(e=M.useContext(pl))!=null?e:Lg},Fg=pl.Provider,fl=M.createContext({current:null}),_g={current:null},hl=()=>{var e;return(e=M.useContext(fl))!=null?e:_g},qg=fl.Provider,gl=M.createContext({current:null}),Hg={current:null},bl=()=>{var e;return(e=M.useContext(gl))!=null?e:Hg},Wg=gl.Provider,Gg=(e,t)=>{const{height:n,itemSize:o,width:i="100%",ariaRowIndexStart:r=2,children:l,listProps:a}=e,c=hl(),d=bl(),p=Ju({...e,children:l},t),f=M.useCallback(({data:x,index:h,style:y,isScrolling:w})=>{const I=x[h];return M.createElement(Fg,{value:r+h},M.createElement(Yu,{value:I.rowId},l(I,y,h,w)))},[r,l]),b=M.useCallback(()=>{c.current&&d.current&&d.current.scroll({left:c.current.scrollLeft,behavior:"instant"})},[]),v=M.useCallback(x=>{var h;(h=c.current)==null||h.removeEventListener("scroll",b),c.current=x,x&&x.addEventListener("scroll",b)},[]);return{...p,itemSize:o,height:n,virtualizedRow:f,width:i,ariaRowIndexStart:r,listProps:a,outerRef:v}};function Ri(){return Ri=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},Ri.apply(null,arguments)}function Us(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ji(e,t){return ji=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,o){return n.__proto__=o,n},ji(e,t)}function Ug(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,ji(e,t)}var Xs=Number.isNaN||function(t){return typeof t=="number"&&t!==t};function Xg(e,t){return!!(e===t||Xs(e)&&Xs(t))}function Vg(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!Xg(e[n],t[n]))return!1;return!0}function qo(e,t){t===void 0&&(t=Vg);var n,o=[],i,r=!1;function l(){for(var a=[],c=0;c<arguments.length;c++)a[c]=arguments[c];return r&&n===this&&t(a,o)||(i=e.apply(this,a),r=!0,n=this,o=a),i}return l}var Kg=typeof performance=="object"&&typeof performance.now=="function",Vs=Kg?function(){return performance.now()}:function(){return Date.now()};function Ks(e){cancelAnimationFrame(e.id)}function Jg(e,t){var n=Vs();function o(){Vs()-n>=t?e.call(null):i.id=requestAnimationFrame(o)}var i={id:requestAnimationFrame(o)};return i}var Ho=-1;function Js(e){if(e===void 0&&(e=!1),Ho===-1||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",document.body.appendChild(t),Ho=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return Ho}var Ot=null;function Ys(e){if(e===void 0&&(e=!1),Ot===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?Ot="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?Ot="negative":Ot="positive-ascending"),document.body.removeChild(t),Ot}return Ot}var Yg=150,Zg=function(t,n){return t};function Qg(e){var t,n=e.getItemOffset,o=e.getEstimatedTotalSize,i=e.getItemSize,r=e.getOffsetForIndexAndAlignment,l=e.getStartIndexForOffset,a=e.getStopIndexForStartIndex,c=e.initInstanceProps,d=e.shouldResetStyleCacheOnItemSizeChange,u=e.validateProps;return t=(function(p){Ug(f,p);function f(v){var x;return x=p.call(this,v)||this,x._instanceProps=c(x.props,Us(x)),x._outerRef=void 0,x._resetIsScrollingTimeoutId=null,x.state={instance:Us(x),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof x.props.initialScrollOffset=="number"?x.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},x._callOnItemsRendered=void 0,x._callOnItemsRendered=qo(function(h,y,w,I){return x.props.onItemsRendered({overscanStartIndex:h,overscanStopIndex:y,visibleStartIndex:w,visibleStopIndex:I})}),x._callOnScroll=void 0,x._callOnScroll=qo(function(h,y,w){return x.props.onScroll({scrollDirection:h,scrollOffset:y,scrollUpdateWasRequested:w})}),x._getItemStyle=void 0,x._getItemStyle=function(h){var y=x.props,w=y.direction,I=y.itemSize,S=y.layout,C=x._getItemStyleCache(d&&I,d&&S,d&&w),$;if(C.hasOwnProperty(h))$=C[h];else{var R=n(x.props,h,x._instanceProps),E=i(x.props,h,x._instanceProps),T=w==="horizontal"||S==="horizontal",_=w==="rtl",D=T?R:0;C[h]=$={position:"absolute",left:_?void 0:D,right:_?D:void 0,top:T?0:R,height:T?"100%":E,width:T?E:"100%"}}return $},x._getItemStyleCache=void 0,x._getItemStyleCache=qo(function(h,y,w){return{}}),x._onScrollHorizontal=function(h){var y=h.currentTarget,w=y.clientWidth,I=y.scrollLeft,S=y.scrollWidth;x.setState(function(C){if(C.scrollOffset===I)return null;var $=x.props.direction,R=I;if($==="rtl")switch(Ys()){case"negative":R=-I;break;case"positive-descending":R=S-w-I;break}return R=Math.max(0,Math.min(R,S-w)),{isScrolling:!0,scrollDirection:C.scrollOffset<R?"forward":"backward",scrollOffset:R,scrollUpdateWasRequested:!1}},x._resetIsScrollingDebounced)},x._onScrollVertical=function(h){var y=h.currentTarget,w=y.clientHeight,I=y.scrollHeight,S=y.scrollTop;x.setState(function(C){if(C.scrollOffset===S)return null;var $=Math.max(0,Math.min(S,I-w));return{isScrolling:!0,scrollDirection:C.scrollOffset<$?"forward":"backward",scrollOffset:$,scrollUpdateWasRequested:!1}},x._resetIsScrollingDebounced)},x._outerRefSetter=function(h){var y=x.props.outerRef;x._outerRef=h,typeof y=="function"?y(h):y!=null&&typeof y=="object"&&y.hasOwnProperty("current")&&(y.current=h)},x._resetIsScrollingDebounced=function(){x._resetIsScrollingTimeoutId!==null&&Ks(x._resetIsScrollingTimeoutId),x._resetIsScrollingTimeoutId=Jg(x._resetIsScrolling,Yg)},x._resetIsScrolling=function(){x._resetIsScrollingTimeoutId=null,x.setState({isScrolling:!1},function(){x._getItemStyleCache(-1,null)})},x}f.getDerivedStateFromProps=function(x,h){return eb(x,h),u(x),null};var b=f.prototype;return b.scrollTo=function(x){x=Math.max(0,x),this.setState(function(h){return h.scrollOffset===x?null:{scrollDirection:h.scrollOffset<x?"forward":"backward",scrollOffset:x,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},b.scrollToItem=function(x,h){h===void 0&&(h="auto");var y=this.props,w=y.itemCount,I=y.layout,S=this.state.scrollOffset;x=Math.max(0,Math.min(x,w-1));var C=0;if(this._outerRef){var $=this._outerRef;I==="vertical"?C=$.scrollWidth>$.clientWidth?Js():0:C=$.scrollHeight>$.clientHeight?Js():0}this.scrollTo(r(this.props,x,h,S,this._instanceProps,C))},b.componentDidMount=function(){var x=this.props,h=x.direction,y=x.initialScrollOffset,w=x.layout;if(typeof y=="number"&&this._outerRef!=null){var I=this._outerRef;h==="horizontal"||w==="horizontal"?I.scrollLeft=y:I.scrollTop=y}this._callPropsCallbacks()},b.componentDidUpdate=function(){var x=this.props,h=x.direction,y=x.layout,w=this.state,I=w.scrollOffset,S=w.scrollUpdateWasRequested;if(S&&this._outerRef!=null){var C=this._outerRef;if(h==="horizontal"||y==="horizontal")if(h==="rtl")switch(Ys()){case"negative":C.scrollLeft=-I;break;case"positive-ascending":C.scrollLeft=I;break;default:var $=C.clientWidth,R=C.scrollWidth;C.scrollLeft=R-$-I;break}else C.scrollLeft=I;else C.scrollTop=I}this._callPropsCallbacks()},b.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&Ks(this._resetIsScrollingTimeoutId)},b.render=function(){var x=this.props,h=x.children,y=x.className,w=x.direction,I=x.height,S=x.innerRef,C=x.innerElementType,$=x.innerTagName,R=x.itemCount,E=x.itemData,T=x.itemKey,_=T===void 0?Zg:T,D=x.layout,L=x.outerElementType,j=x.outerTagName,B=x.style,N=x.useIsScrolling,W=x.width,U=this.state.isScrolling,X=w==="horizontal"||D==="horizontal",Q=X?this._onScrollHorizontal:this._onScrollVertical,q=this._getRangeToRender(),F=q[0],J=q[1],G=[];if(R>0)for(var g=F;g<=J;g++)G.push(M.createElement(h,{data:E,key:_(g,E),index:g,isScrolling:N?U:void 0,style:this._getItemStyle(g)}));var k=o(this.props,this._instanceProps);return M.createElement(L||j||"div",{className:y,onScroll:Q,ref:this._outerRefSetter,style:Ri({position:"relative",height:I,width:W,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:w},B)},M.createElement(C||$||"div",{children:G,ref:S,style:{height:X?"100%":k,pointerEvents:U?"none":void 0,width:X?k:"100%"}}))},b._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var x=this.props.itemCount;if(x>0){var h=this._getRangeToRender(),y=h[0],w=h[1],I=h[2],S=h[3];this._callOnItemsRendered(y,w,I,S)}}if(typeof this.props.onScroll=="function"){var C=this.state,$=C.scrollDirection,R=C.scrollOffset,E=C.scrollUpdateWasRequested;this._callOnScroll($,R,E)}},b._getRangeToRender=function(){var x=this.props,h=x.itemCount,y=x.overscanCount,w=this.state,I=w.isScrolling,S=w.scrollDirection,C=w.scrollOffset;if(h===0)return[0,0,0,0];var $=l(this.props,C,this._instanceProps),R=a(this.props,$,C,this._instanceProps),E=!I||S==="backward"?Math.max(1,y):1,T=!I||S==="forward"?Math.max(1,y):1;return[Math.max(0,$-E),Math.max(0,Math.min(h-1,R+T)),$,R]},f})(M.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var eb=function(t,n){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,n.instance},tb=Qg({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,r,l){var a=t.direction,c=t.height,d=t.itemCount,u=t.itemSize,p=t.layout,f=t.width,b=a==="horizontal"||p==="horizontal",v=b?f:c,x=Math.max(0,d*u-v),h=Math.min(x,n*u),y=Math.max(0,n*u-v+u+l);switch(o==="smart"&&(i>=y-v&&i<=h+v?o="auto":o="center"),o){case"start":return h;case"end":return y;case"center":{var w=Math.round(y+(h-y)/2);return w<Math.ceil(v/2)?0:w>x+Math.floor(v/2)?x:w}default:return i>=y&&i<=h?i:i<y?y:h}},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,r=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:r,b=Math.ceil((f+o-p)/a);return Math.max(0,Math.min(l-1,n+b-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.itemSize}});const nb=e=>{const{slots:t,slotProps:n}=Zu(e),{dir:o}=kr();return M.createElement(t.root,n.root,M.createElement(tb,{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))},is=M.forwardRef((e,t)=>{const n=Gg(e,t);return Mg(n),nb(n)});is.displayName="DataGridBody";const ob=(e,t)=>{var n;const{targetDocument:o}=kr(),i=Qu({targetDocument:o}),r=M.useRef(null),l=M.useRef(null);let a=e.containerWidthOffset;a===void 0&&(a=e.selectionMode?-44:0,a-=i||0);const c=em({...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:r,bodyRef:l}},ib=(e,t)=>M.createElement(Wg,{value:e.headerRef},M.createElement(qg,{value:e.bodyRef},tm(e,t))),ss=M.forwardRef((e,t)=>{const n=ob(e,t);return nm(n),ib(n,om(n))});ss.displayName="DataGrid";const sb=(e,t)=>{const n=Pg();return im({...e,"aria-rowindex":n},t)},rb=le({root:{minWidth:"fit-content"}}),ab=e=>{const t=rb();return e.root.className=qt(t.root,e.root.className),sm(e),e},In=M.forwardRef((e,t)=>{const n=sb(e,t);return ab(n),rm(n)});In.displayName="DataGridRow";const lb=(e,t)=>{const n=hl(),o=bl(),i=M.useCallback(()=>{n.current&&o.current&&n.current.scroll({left:o.current.scrollLeft,behavior:"instant"})},[]),r=M.useCallback(a=>{var c;(c=o.current)==null||c.removeEventListener("scroll",i),o.current=a,a&&a.addEventListener("scroll",i)},[]),l=am(e,t);return l.root.ref=lm(l.root.ref,r),l},cb=le({root:{overflowX:"auto",scrollbarWidth:"none","::-webkit-scrollbar":{width:0,height:0}}}),db=e=>{const t=cb();return e.root.className=qt(t.root,e.root.className),cm(e),e},rs=M.forwardRef((e,t)=>{const n=lb(e,t);return db(n),dm(n)});rs.displayName="DataGridHeader";const ub=le({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}}),mb={button:"command",dropdown:"dropdown",split:"split",group:"group"};function pb({tab:e,location:t}){const n=ub(),{nodes:o}=ns(t,e),i=en(),r=fe(u=>u.selectedCommandId),l=fe(u=>u.selectCommand),a=Z(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),s.jsxs("section",{className:n.root,"aria-label":"Modern commands",children:[s.jsxs("div",{className:n.header,children:[s.jsx(P,{weight:"semibold",size:200,children:"Modern commands"}),s.jsx(ae,{size:"small",appearance:"tint",color:"important",children:"read-only"}),s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"Built with the command designer (appaction). Edit them in the command designer."})]}),s.jsxs(um,{size:"small","aria-label":"Modern commands (read-only)",children:[s.jsx(mm,{children:s.jsxs(ds,{children:[s.jsx(kt,{style:{width:56},children:"#"}),s.jsx(kt,{children:"Label"}),s.jsx(kt,{children:"App"}),s.jsx(kt,{children:"Location"}),s.jsx(kt,{style:{width:90},children:"Type"}),s.jsx(kt,{children:"Unique name"})]})}),s.jsx(pm,{children:c.map(({node:u,depth:p})=>{const f=u.command,b=r===f.id&&!a;return s.jsxs(ds,{className:qt(n.row,b&&n.rowSelected),"aria-selected":b,tabIndex:0,onClick:()=>l(f.id),onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),l(f.id))},children:[s.jsx(At,{children:f.sequence}),s.jsx(At,{children:s.jsx(Ne,{content:s.jsx(ml,{node:u,appNames:i}),relationship:"description",children:s.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&&s.jsx(Ye,{fontSize:12,"aria-label":"hidden"}),s.jsx(ae,{size:"extra-small",appearance:"tint",color:"important",children:"Modern"})]})})}),s.jsx(At,{children:wn(f,i)}),s.jsx(At,{children:Qa[f.location]??f.location}),s.jsx(At,{children:s.jsx(ae,{size:"small",appearance:"outline",children:mb[f.type]})}),s.jsx(At,{children:s.jsx("span",{className:n.mono,title:f.uniqueName,children:f.uniqueName})})]},f.id)})})]})]})}const fb=le({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 hb({tab:e,location:t}){const n=fb(),o=Z(y=>y.selectedButtonId),i=Z(y=>y.selectButtonInContext),r=O(y=>y.setButtonProp),l=O(y=>y.locLabels),a=O(y=>y.baseLanguageCode),c=y=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&y.oob&&!y.custom,[d,u]=M.useState(""),{overrides:p}=ns(t,e),f=en(),b=e.groups.flatMap(y=>y.buttons.map(w=>({button:w,label:ce(w.label,l),groupId:y.id,groupLabel:ce(y.label,l,a)}))),v=M.useMemo(()=>{const y=d.toLowerCase().trim();return y?b.filter(({button:w,label:I,groupLabel:S})=>w.id.toLowerCase().includes(y)||w.label.toLowerCase().includes(y)||I.toLowerCase().includes(y)||(w.commandId??"").toLowerCase().includes(y)||S.toLowerCase().includes(y)):b},[b,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}},h=[rt({columnId:"seq",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"#"}),renderCell:({button:y})=>s.jsx(P,{size:200,children:y.sequence})}),rt({columnId:"icon",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"Icon"}),renderCell:({button:y})=>s.jsx("div",{className:n.iconCell,children:s.jsx($t,{name:y.icon||"apps_add_in",size:16})})}),rt({columnId:"label",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"Label"}),renderCell:({button:y,label:w})=>s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,minWidth:0},children:[s.jsx(P,{size:200,className:n.clip,title:w,children:w}),s.jsx(os,{overrides:p.get(y.id),appNames:f})]})}),rt({columnId:"id",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"ID"}),renderCell:({button:y})=>s.jsx(P,{size:200,font:"monospace",className:n.clip,title:y.id,style:{color:m.colorNeutralForeground3},children:y.id})}),rt({columnId:"kind",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"Kind"}),renderCell:({button:y})=>s.jsx(ae,{size:"small",appearance:"outline",children:y.kind})}),rt({columnId:"group",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"Group"}),renderCell:({groupLabel:y})=>s.jsx(P,{size:200,className:n.clip,title:y,children:y})}),rt({columnId:"command",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"Command"}),renderCell:({button:y})=>s.jsx(P,{size:200,font:"monospace",className:n.clip,title:y.commandId||"",style:{color:m.colorNeutralForeground3},children:y.commandId||"—"})}),rt({columnId:"visible",renderHeaderCell:()=>s.jsx(P,{size:200,weight:"semibold",children:"Visible"}),renderCell:({button:y,label:w,groupId:I})=>s.jsx(Ni,{checked:!y.hidden,label:y.hidden?s.jsx(Ye,{fontSize:14}):void 0,disabled:c(y),title:c(y)?"OOB global command bar buttons cannot be customized.":void 0,"aria-label":`Toggle visibility of ${w}`,onChange:(S,C)=>r(t,e.id,I,y.id,{hidden:!C.checked})})})];return s.jsxs("div",{className:n.root,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS,padding:`${m.spacingVerticalXS} 0`},children:[s.jsx(qe,{size:"small",contentBefore:s.jsx(ft,{}),placeholder:`Filter ${b.length} button${b.length!==1?"s":""}…`,value:d,onChange:(y,w)=>u(w.value),style:{minWidth:0,flex:1,maxWidth:480}}),d&&s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[v.length," match",v.length!==1?"es":""]})]}),s.jsxs(ss,{className:n.gridWrap,items:v,columns:h,columnSizingOptions:x,resizableColumns:!0,getRowId:y=>y.button.id,focusMode:"composite",sortable:!0,selectionMode:"single",selectedItems:o?new Set([o]):new Set,onSelectionChange:(y,w)=>{const I=[...w.selectedItems][0],S=v.find(C=>C.button.id===I);S&&i(t,e.id,S.groupId,S.button.id)},children:[s.jsx(rs,{children:s.jsx(In,{children:({renderHeaderCell:y})=>s.jsx(Ar,{children:y()})})}),s.jsx(is,{itemSize:42,height:420,listProps:{width:"100%"},children:({item:y,rowId:w},I)=>s.jsx(In,{style:I,className:o===y.button.id?n.rowSelected:n.row,children:({renderCell:S})=>s.jsx(Dr,{children:S(y)})},w)})]}),s.jsx(pb,{tab:e,location:t})]})}const yl=le({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 gb({tab:e,location:t}){const n=yl(),o=Z(C=>C.selectedButtonId),i=Z(C=>C.selectedGroupId),r=Z(C=>C.selectButtonInContext),l=O(C=>C.baseline),a=O(C=>C.locLabels),c=O(C=>C.addMenuSection),d=O(C=>C.setMenuSectionProp),u=O(C=>C.deleteMenuSection),{overrides:p}=ts(t),f=en(),b=e.groups.find(C=>C.id===i),v=vp(b,o),x=M.useMemo(()=>{const C=new Set;for(const $ of l[t]?.tabs??[])for(const R of $.groups)for(const E of je(R))C.add(E.id);return C},[l,t]);if(!b||!v||!v.menu&&!Mt(v.kind))return null;const h=b.id,y=C=>ce(C.label,a),w=C=>na(C.source?.attributes.PopulateDynamically)?C.source?.attributes.PopulateQueryCommand??"a command":null,I=C=>{const $=[...C.menu?.sections??[]].sort((T,_)=>T.sequence-_.sequence),R=!x.has(C.id),E=w(C);return s.jsxs(s.Fragment,{children:[E&&s.jsxs(Be,{className:n.empty,children:["Populated when the menu opens, by ",E,". Static items below are kept as they are."]}),$.map(T=>s.jsx(bb,{section:T,parent:C,editable:R,onTitle:_=>d(t,e.id,h,C.id,T.id,{title:_}),onDisplayMode:_=>d(t,e.id,h,C.id,T.id,{displayMode:_}),onDelete:()=>u(t,e.id,h,C.id,T.id),renderItem:S},T.id)),$.length===0&&!E&&s.jsx(Be,{className:n.empty,children:"No menu sections yet."}),R&&s.jsx("div",{children:s.jsx(K,{size:"small",appearance:"subtle",icon:s.jsx(Ae,{}),onClick:()=>c(t,e.id,h,C.id,""),children:"Add section"})})]})},S=C=>{const $=C.id===o,R=p.get(C.id);return s.jsxs("div",{children:[s.jsxs("div",{className:n.itemRow,children:[s.jsxs("button",{type:"button",className:[n.item,$?n.itemSelected:"",C.hidden?n.itemHidden:""].filter(Boolean).join(" "),"aria-pressed":$,"aria-label":`Menu item ${y(C)}${C.hidden?" — hidden":""}${sl(R,f)}`,onClick:()=>r(t,e.id,h,C.id),children:[s.jsx($t,{name:C.icon||"apps_add_in",size:16}),s.jsx(P,{size:200,children:y(C)}),C.menu&&s.jsx(gt,{fontSize:12,"aria-hidden":!0}),s.jsx(os,{overrides:R,appNames:f}),C.custom&&!x.has(C.id)&&s.jsx(ae,{size:"extra-small",color:"brand",appearance:"tint",children:"NEW"})]}),$&&s.jsx(xb,{item:C,location:t,tabId:e.id,groupId:h,onDeleted:()=>r(t,e.id,h,v.id)})]}),C.menu&&s.jsx("div",{className:n.nested,children:I(C)})]},C.id)};return s.jsxs("section",{className:n.root,"aria-label":`Menu of ${y(v)}`,children:[s.jsxs("div",{className:n.header,children:[s.jsx(gt,{"aria-hidden":!0}),s.jsx(P,{weight:"semibold",size:300,children:y(v)}),s.jsx(ae,{size:"small",appearance:"outline",children:v.kind==="splitButton"?"Split button menu":"Flyout menu"}),s.jsx("span",{className:n.spacer}),s.jsxs(Be,{children:[wt(v).length," item(s)"]})]}),s.jsx("div",{className:n.body,children:I(v)})]})}function bb({section:e,parent:t,editable:n,onTitle:o,onDisplayMode:i,onDelete:r,renderItem:l}){const a=yl(),c=O(u=>u.locLabels),d=[...e.controls].sort((u,p)=>u.sequence-p.sequence);return s.jsxs("div",{className:a.section,children:[s.jsx("div",{className:a.sectionHeader,children:n?s.jsxs(s.Fragment,{children:[s.jsx(qe,{size:"small",placeholder:"Section title (optional)",value:e.title??"","aria-label":"Menu section title",onChange:(u,p)=>o(p.value)}),s.jsxs(dt,{size:"small","aria-label":"Menu section display mode",value:e.displayMode??"Menu16",onChange:(u,p)=>i(p.value),children:[s.jsx("option",{value:"Menu16",children:"16 px icons"}),s.jsx("option",{value:"Menu32",children:"32 px icons"}),s.jsx("option",{value:"Menu",children:"Text only"})]}),s.jsx(Ne,{content:"Delete section and its items",relationship:"label",children:s.jsx(K,{size:"small",appearance:"subtle",icon:s.jsx(Ft,{}),onClick:r})})]}):s.jsx(Be,{children:ce(e.title,c)||e.id})}),d.map(u=>l(u)),e.rawContent!==void 0&&s.jsx(Be,{className:a.empty,children:"Gallery / dynamic content (kept as is)"}),(e.rawControls?.length??0)>0&&s.jsxs(Be,{className:a.empty,children:[e.rawControls.length," other control(s) CBS doesn't edit (kept as they are)"]}),e.rawContent===void 0&&s.jsx(yb,{parent:t,section:e})]})}function yb({parent:e,section:t}){const n=Z(f=>f.location),o=Z(f=>f.tabId),i=Z(f=>f.selectedGroupId),r=Z(f=>f.selectButtonInContext),l=O(f=>f.addMenuItem),a=O(f=>f.upsertCommand),c=ne(f=>f.activeSolution),d=ne(f=>f.publisherPrefix),u=ne(f=>f.activeEntity),p=()=>{if(!i)return;const{ribbons:f,commands:b}=O.getState(),v=new Set(b.map(w=>w.id));for(const w of Object.values(f))for(const I of w.tabs)for(const S of I.groups)for(const C of je(S))v.add(C.id);const x=c?.publisherPrefix?.trim()||d?.trim()||"new",{id:h,commandId:y}=Sa(x,u?.logicalName??"global",n,"MenuItem",v);l({location:n,tabId:o,groupId:i,parentId:e.id,sectionId:t.id,item:{id:h,label:"Menu item",commandId:y}}),a({id:y,enableRules:[],displayRules:[],actions:[]}),r(n,o,i,h)};return s.jsx("div",{children:s.jsx(K,{size:"small",appearance:"subtle",icon:s.jsx(Ae,{}),onClick:p,children:"Add item"})})}function xb({item:e,location:t,tabId:n,groupId:o,onDeleted:i}){const r=O(c=>c.setButtonProp),l=O(c=>c.deleteButton),a=O(c=>c.baseline[t]);return s.jsxs(s.Fragment,{children:[s.jsx(Ne,{content:e.hidden?"Show item":"Hide item",relationship:"label",children:s.jsx(K,{size:"small",appearance:"subtle",icon:e.hidden?s.jsx(Ct,{}):s.jsx(Ye,{}),onClick:()=>r(t,n,o,e.id,{hidden:!e.hidden})})}),$n(e,a)&&s.jsx(Ne,{content:"Delete item",relationship:"label",children:s.jsx(K,{size:"small",appearance:"subtle",icon:s.jsx(Ft,{}),onClick:()=>{l(t,n,o,e.id),i()}})})]})}function vb(){const e=fe(l=>l.status),t=fe(l=>l.apps),n=fe(l=>l.appFilter),o=fe(l=>l.setAppFilter),i=fe(l=>l.commands.length),r=fe(l=>l.error);return e==="idle"?null:e==="loading"?s.jsx(Ti,{size:"extra-tiny","aria-label":"Loading modern commands"}):e==="unavailable"?s.jsx(Ne,{content:`Modern commands couldn't be read: ${r??"unknown error"}`,relationship:"label",children:s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"Modern: n/a"})}):s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},children:[s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"App:"}),s.jsx(Ne,{content:`${i} modern command${i===1?"":"s"} for this table (read-only). Pick an app to see its command bar.`,relationship:"description",children:s.jsxs(dt,{value:n,onChange:(l,a)=>o(a.value),size:"small","aria-label":"App for modern commands",style:{height:"26px",width:"170px"},children:[s.jsx("option",{value:"all",children:"All apps"}),t.map(l=>s.jsx("option",{value:l.id,children:l.name},l.id))]})})]})}const Sb=le({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}}),wb=le({root:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"80px",gap:m.spacingHorizontalM,color:m.colorNeutralForeground3}}),Cb=[{value:"HomepageGrid",label:"Home Grid",icon:s.jsx(Ir,{}),desc:"Mscrm.HomepageGrid.{entity}"},{value:"SubGrid",label:"Sub Grid",icon:s.jsx(Bu,{}),desc:"Mscrm.SubGrid.{entity}"},{value:"Form",label:"Form",icon:s.jsx(so,{}),desc:"Mscrm.Form.{entity}"},{value:"Application",label:"Application",icon:s.jsx(Rr,{}),desc:"applicationRibbon.xml"}];function Ib({isLoadingRibbon:e=!1,ribbonLoadError:t=null,onRetryRibbonLoad:n}){const o=Sb(),i=Z(A=>A.location),r=Z(A=>A.tabId),l=Z(A=>A.setLocation),a=Z(A=>A.setTabId),c=O(A=>A.ribbons),d=O(A=>A.renameTab),u=O(A=>A.deleteTab),p=O(A=>A.locLabels),f=O(A=>A.baseLanguageCode),b=O(A=>A.baseline),v=O(A=>A.layers),x=O(A=>A.orphans.entity.filter(te=>!A.pendingOrphanDeletes.entity.includes(te.id)&&!te.recentPublish?.published).length),h=Z(A=>A.clearSelection),y=O(A=>A.reorderTabs),w=Y(A=>A.ribbonViewStyle),I=Y(A=>A.setRibbonViewStyle),S=Y(A=>A.openXmlDrawer),C=Y(A=>A.openTabDisplayRules),$=Y(A=>A.openNewGroup),R=Y(A=>A.openNewTab),[E,T]=M.useState(null),[_,D]=M.useState(""),L=M.useRef(null),[j,B]=M.useState(null),N=j?c[i].tabs.find(A=>A.id===j):void 0;M.useEffect(()=>{E&&L.current&&L.current.focus()},[E]);function W(){const A=c[i].tabs.find(te=>te.id===E);A&&_.trim()&&_.trim()!==ce(A.label,p,f)&&d(i,A.id,_.trim()),T(null)}function U(A){return ya(A,b[i],Qn({layers:v},i))}function X(A){return ba("tab",A.id,b[i],Ui({layers:v},i))}const[Q,q]=M.useState(null);function F(A){if(!X(A)){q(A.id),ie.getState().logInfo("canvas",`Tab ${A.id} can't be renamed: ${Fi}.`);return}T(A.id),D(ce(A.label,p,f))}const J=Er(Hn(zr,{activationConstraint:{distance:5}}),Hn(Or)),G=M.useCallback(A=>{const{active:te,over:de}=A;if(!de||te.id===de.id)return;const Te=c[i].tabs.map(z=>z.id),be=Te.indexOf(String(te.id)),Me=Te.indexOf(String(de.id));be<0||Me<0||y(i,Cm(Te,be,Me))},[i,c,y]),g=c[i],k=g.tabs.find(A=>A.id===r)??g.tabs.find(A=>A.id===pn(g.tabs));return M.useEffect(()=>{if(!g.tabs.length)return;if(!g.tabs.some(te=>te.id===r)){const te=pn(g.tabs);te&&a(te)}},[g.tabs,r,a]),s.jsxs("main",{className:o.root,"aria-label":"Ribbon canvas",children:[s.jsxs("div",{className:o.locationRow,role:"tablist","aria-label":"Ribbon location",children:[Cb.map(A=>s.jsxs("div",{role:"tab","aria-selected":i===A.value,className:`${o.locationTab} ${i===A.value?o.locationTabActive:""}`,onClick:()=>{l(A.value);const te=pn(c[A.value].tabs);te&&a(te)},title:A.desc,tabIndex:i===A.value?0:-1,children:[A.icon,s.jsx(P,{size:200,children:A.label})]},A.value)),s.jsx("div",{className:o.spacer}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},children:[s.jsx(vb,{}),s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"View as:"}),s.jsxs(dt,{value:w,onChange:(A,te)=>I(te.value),size:"small",style:{height:"26px",width:"170px"},children:[s.jsx("option",{value:"classic",children:"Classic ribbon"}),s.jsx("option",{value:"modern",children:"Modern command bar"}),s.jsx("option",{value:"list",children:"List view"})]}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Gt,{}),onClick:S,children:"XML"})]})]}),i==="Form"&&s.jsx(Ce,{intent:"info",style:{flexShrink:0},children:s.jsx(Ie,{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."})}),i==="SubGrid"&&s.jsx(Ce,{intent:"info",style:{flexShrink:0},children:s.jsx(Ie,{children:"Subgrid ribbons support only 3 native controls: Add, Show List, and Delete. Their icons cannot be changed."})}),i==="Application"&&s.jsx(Ce,{intent:"info",style:{flexShrink:0},children:s.jsx(Ie,{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."})}),k&&!/^(Mscrm|Microsoft)\./.test(k.id)&&s.jsx(Ce,{intent:"info",style:{flexShrink:0},children:s.jsx(Ie,{children:Ua})}),k&&xo(k.id)&&s.jsx(Ce,{intent:"warning",style:{flexShrink:0},children:s.jsx(Ie,{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."})}),i!=="Application"&&x>0&&s.jsxs(Ce,{intent:"warning",style:{flexShrink:0},children:[s.jsxs(Ie,{children:[x," element",x!==1?"s":""," of your customizations for this table",x!==1?" aren't":" isn't"," on the canvas: the ribbon doesn't return"," ",x!==1?"them":"it",". See ",s.jsx("strong",{children:"Orphaned customizations"})," in the Properties pane to delete ",x!==1?"them":"it","."]}),s.jsx(hn,{children:s.jsx(K,{size:"small",onClick:h,children:"Show"})})]}),s.jsx(Br,{sensors:J,onDragEnd:G,children:s.jsx(Im,{items:g.tabs.map(A=>A.id),strategy:Rm,children:s.jsxs("div",{className:o.tabStrip,role:"tablist","aria-label":"Ribbon tabs",children:[g.tabs.map(A=>s.jsx(jb,{tab:A,isActive:k?.id===A.id,isEditing:E===A.id,editValue:_,inputRef:A.id===E?L:void 0,onSelect:()=>{E!==A.id&&a(A.id),Q!==A.id&&q(null)},onDoubleClick:()=>{a(A.id),F(A)},onF2:()=>F(A),renameRefused:Q===A.id,onDelete:k?.id===A.id&&U(A)?()=>B(A.id):void 0,onEditChange:D,onEditCommit:W,onEditCancel:()=>T(null),styles:o},A.id)),s.jsx("button",{type:"button",className:o.addTabBtn,title:"Add tab","aria-label":"Add tab",onClick:R,children:s.jsx(Ae,{fontSize:12})}),s.jsx("div",{className:o.spacer}),s.jsxs(K,{appearance:"subtle",size:"small",icon:s.jsx(Ct,{}),onClick:C,children:["Tab rules",k&&k.tabDisplayRules.length>0&&s.jsx(ae,{size:"small",appearance:"tint",color:"brand",style:{marginLeft:4},children:k.tabDisplayRules.length})]})]})})}),s.jsx("div",{className:o.canvas,children:e?s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:s.jsx(Ti,{label:"Loading ribbon definition..."})}):t?s.jsxs(Ce,{intent:"error",children:[s.jsxs(Ie,{children:["Failed to load ribbon definition. ",t]}),n&&s.jsx(hn,{containerAction:s.jsx(K,{appearance:"primary",size:"small",onClick:n,children:"Retry"})})]}):k?s.jsxs(s.Fragment,{children:[w==="classic"?s.jsx(ng,{tab:k,location:i}):w==="modern"?s.jsx(Bg,{tab:k,location:i}):s.jsx(hb,{tab:k,location:i}),s.jsx(gb,{tab:k,location:i})]}):s.jsx(Rb,{onAddGroup:$})}),N&&s.jsxs(Qi,{open:!0,title:"Delete tab",confirmLabel:"Delete tab",destructive:!0,onConfirm:()=>{u(i,N.id),B(null)},onCancel:()=>B(null),children:["Delete the tab “",ce(N.label,p,f),"” and its groups and buttons?"]})]})}function Rb({onAddGroup:e}){const t=wb();return s.jsxs("div",{className:t.root,children:[s.jsx(so,{fontSize:32,style:{opacity:.4}}),s.jsx(P,{size:300,children:"This tab has no groups yet"}),s.jsx(K,{appearance:"primary",size:"small",icon:s.jsx(Ae,{}),onClick:e,children:"Add first group"})]})}function jb({tab:e,isActive:t,isEditing:n,editValue:o,inputRef:i,onSelect:r,onDoubleClick:l,onF2:a,onEditChange:c,onEditCommit:d,onEditCancel:u,onDelete:p,renameRefused:f,styles:b}){const{attributes:v,listeners:x,setNodeRef:h,transform:y,transition:w,isDragging:I}=jm({id:e.id}),S=O(E=>E.locLabels),C=O(E=>E.baseLanguageCode),$=ce(e.label,S,C),R={transform:$m.Transform.toString(y),transition:w,opacity:I?.5:1,touchAction:"none"};return s.jsx("div",{ref:h,style:R,...v,...x,className:`${b.ribbonTab} ${t?b.ribbonTabActive:""}`,role:"tab","aria-selected":t,tabIndex:t?0:-1,onClick:r,onDoubleClick:l,title:f?`${Fi}.`:void 0,onKeyDown:E=>{E.key==="F2"&&a()},children:n?s.jsx(qe,{ref:i,className:b.inlineTabInput,value:o,onChange:(E,T)=>c(T.value),onBlur:d,onKeyDown:E=>{E.key==="Enter"&&(E.preventDefault(),d()),E.key==="Escape"&&(E.preventDefault(),u()),E.stopPropagation()},onClick:E=>E.stopPropagation(),size:"small","aria-label":"Rename tab"}):s.jsxs(s.Fragment,{children:[s.jsx(P,{className:b.ribbonTabLabel,children:$}),s.jsx(P,{className:b.ribbonTabMeta,children:e.id}),p&&s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(ro,{}),"aria-label":`Delete tab ${$}`,title:"Delete this tab and everything in it",onPointerDown:E=>E.stopPropagation(),onClick:E=>{E.stopPropagation(),p()}})]})})}let dn=null;const $i={set(e){dn=e},invoke(e){const t=dn;dn=null,t?.(e)},clear(){dn=null},hasPending(){return dn!==null}},$b=["button","flyout","splitButton","textBox","comboBox","checkBox"],Nb=le({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 Tb({button:e,location:t,tabId:n,groupId:o}){const i=Nb(),r=O(w=>w.setButtonProp),l=O(w=>w.locLabels),a=O(w=>w.baseLanguageCode),c=Y(w=>w.openIconPicker),d=Y(w=>w.openLocalizationEditor),u=Y(w=>w.openWebResourceBrowser),p=O(w=>w.customizeOobButton),f=O(w=>w.customiseButton),b=ne(w=>w.activeSolution),v=ne(w=>w.publisherPrefix),x=Z(w=>w.selectButtonInContext);function h(w){r(t,n,o,e.id,w)}const y=yp(e,l,a);return s.jsxs("div",{className:i.root,children:[(e.origin==="oob"||e.origin==="managed")&&s.jsx(Ce,{intent:"warning",children:s.jsx(Ie,{children:s.jsxs(P,{size:200,children:[e.origin==="oob"?s.jsxs(s.Fragment,{children:["This is an ",s.jsx("strong",{children:"out-of-the-box"})," (system) button. To change it, create an override."]}):s.jsxs(s.Fragment,{children:["This button comes from a ",s.jsx("strong",{children:"managed solution"}),e.solutionName?s.jsxs(s.Fragment,{children:[" ","(",s.jsx("strong",{children:e.solutionName}),")"]}):null,e.publisherName?s.jsxs(s.Fragment,{children:[" by ",e.publisherName]}):null,". You can't edit it directly — create an override to change it."]})," ",s.jsx(K,{size:"small",appearance:"subtle",onClick:()=>p(t,n,o,e.id),children:"Create override"}),Xi(t,n,e)&&s.jsx(K,{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 w=b?.publisherPrefix?.trim()||v?.trim()||"new",I=f(t,n,o,e.id,w);I&&x(t,n,o,I)},children:"Customise button"})]})})}),s.jsx(P,{size:100,weight:"semibold",className:i.sectionLabel,children:"Identity"}),s.jsx(Ee,{label:"Label",children:s.jsx(qe,{value:e.label,onChange:(w,I)=>h({label:I.value})})}),s.jsx(Ee,{label:"Translations",children:s.jsxs("div",{className:i.localeChips,children:[y.map(w=>s.jsx(ae,{appearance:"filled",color:"informative",style:{cursor:"pointer"},onClick:()=>d(e.id),children:w===1033?"en-US":String(w)},w)),y.length===0&&s.jsx(ae,{appearance:"outline",color:"informative",children:"en-US (default)"}),s.jsx(K,{size:"small",appearance:"subtle",icon:s.jsx(Ae,{}),onClick:()=>d(e.id),children:"Add language…"})]})}),s.jsx(Ee,{label:"Tooltip title",children:s.jsx(qe,{value:e.tooltipTitle??"",onChange:(w,I)=>h({tooltipTitle:I.value})})}),s.jsx(Ee,{label:"Tooltip body",children:s.jsx(fm,{value:e.tooltipBody??"",onChange:(w,I)=>h({tooltipBody:I.value}),resize:"vertical"})}),s.jsx(Ve,{}),s.jsx(Ee,{label:"Icon",children:s.jsxs("div",{className:i.row,children:[s.jsx("div",{className:i.iconPreview,children:e.icon?s.jsx($t,{name:e.icon,size:20}):s.jsx(qn,{style:{color:m.colorNeutralForeground3}})}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(qn,{}),onClick:c,children:"Change…"})]})}),e.icon&&s.jsx(Ee,{label:"ModernImage (auto)",children:s.jsx(qe,{value:Li(e)??"(none)",readOnly:!0,contentAfter:s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"auto"})})}),e.image16&&s.jsx(Ee,{label:"Image16",children:s.jsx("div",{className:i.row,children:s.jsx("button",{type:"button",className:i.webResLink,onClick:()=>{$i.set(w=>{h({image16:`$webresource:${w.name}`,icon:w.name.split("/").pop()?.replace(/\..*$/,"")})}),u()},title:e.image16,children:e.image16})})}),e.image32&&s.jsx(Ee,{label:"Image32",children:s.jsx("div",{className:i.row,children:s.jsx("button",{type:"button",className:i.webResLink,onClick:()=>{$i.set(w=>{h({image32:`$webresource:${w.name}`})}),u()},title:e.image32,children:e.image32})})}),s.jsx(Ve,{}),s.jsx(Ee,{label:"Kind",children:s.jsx(dt,{value:e.kind,onChange:(w,I)=>h({kind:I.value}),children:$b.map(w=>s.jsx("option",{value:w,children:w},w))})}),s.jsxs("div",{className:i.row,style:{justifyContent:"space-between"},children:[s.jsx(P,{size:200,children:"Visible"}),s.jsx(Ni,{checked:!e.hidden,"aria-label":"Toggle button visibility",onChange:(w,I)=>h({hidden:!I.checked})})]}),s.jsx(Ee,{label:"Sequence",children:s.jsx(hm,{value:e.sequence,step:10,min:0,onChange:(w,I)=>h({sequence:Number(I.value??e.sequence)})})}),s.jsx(Ee,{label:"Template alias",children:s.jsx(qe,{value:e.templateAlias,onChange:(w,I)=>h({templateAlias:I.value})})})]})}const kb=le({row:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:m.spacingHorizontalS}}),Ab={oob:"informative",customising:"warning",customised:"brand",uncustomising:"danger",custom:"success",reloadRequired:"danger"};function Bn(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 Db({commandId:e,compact:t=!1}){const n=kb(),o=Xa(e),i=O(h=>h.customiseCommand),r=O(h=>h.uncustomiseCommand),l=O(h=>h.discardCommandChanges),a=O(h=>{const y=h.commands.find(I=>I.id===e),w=h.baselineCommands.find(I=>I.id===e);return!!y&&!!w&&JSON.stringify(y)!==JSON.stringify(w)}),[c,d]=M.useState(null);if(!o)return null;const u=(h,y,w)=>{a?d({what:h,confirmLabel:y,run:w}):w()},p=c&&s.jsxs(Qi,{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 ",s.jsx("code",{children:e}),"."]}),{provenance:f}=o,b=f==="oob"?s.jsx(K,{size:"small",appearance:"outline",onClick:()=>i(e),children:"Customise command"}):f==="customising"?s.jsx(K,{size:"small",appearance:"subtle",onClick:()=>u("Discarding the customisation","Discard customisation",()=>l(e)),children:"Discard customisation"}):f==="customised"?s.jsx(K,{size:"small",appearance:"subtle",onClick:()=>u("Uncustomising","Uncustomise",()=>r(e,o.scope)),children:"Uncustomise"}):f==="uncustomising"?s.jsx(K,{size:"small",appearance:"subtle",onClick:()=>l(e),children:"Undo uncustomise"}):null,v=s.jsx(ae,{appearance:f==="oob"?"outline":"filled",color:Ab[f],size:"small",children:Xh[f]});if(t)return s.jsxs("div",{className:n.row,children:[v,b,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 ${Bn(o)}, where you can change it without touching its buttons. Editing it customises it too.`,customising:`On publish, this command is copied into ${Bn(o)} and replaces the original there. Rules keep their ids; a rule you edit is written to the layer as well.`,customised:`${Bn(o).replace(/^./,h=>h.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 ${Bn(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 s.jsx(Ce,{intent:f==="uncustomising"||f==="reloadRequired"?"warning":"info",children:s.jsxs(Ie,{children:[s.jsxs("div",{className:n.row,children:[v,s.jsx(P,{size:200,children:x[f]}),b]}),p]})})}const Eb=le({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 Ob({button:e,groupId:t,tabId:n,location:o}){const i=Eb(),r=O(x=>x.commands),l=O(x=>x.upsertCommand),a=O(x=>x.setButtonProp),c=O(x=>x.batch),d=Y(x=>x.openCommandEditor),[u,p]=Ue.useState(""),f=r.find(x=>x.id===e.commandId),b=()=>{const x=new Set(r.map(y=>y.id)),h=qi("New","Command",x);c(()=>{l({id:h,enableRules:[],displayRules:[],actions:[]}),a(o,n,t,e.id,{commandId:h})}),d(h)},v=()=>{u&&(a(o,n,t,e.id,{commandId:u}),p(""))};return s.jsxs("div",{className:i.root,children:[s.jsx(Ve,{}),s.jsx(P,{size:100,weight:"semibold",className:i.sectionLabel,children:"Command"}),f?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:i.commandRow,children:[s.jsx(P,{className:i.commandId,children:f.id}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Gt,{}),onClick:()=>d(f.id),children:"Edit"})]}),s.jsx(Db,{commandId:f.id,compact:!0}),f.actions.length>0&&s.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:f.actions.map((x,h)=>s.jsx(wo,{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}`},h))}),f.enableRules.length>0&&s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"Enable rules:"}),f.enableRules.map(x=>s.jsx(wo,{size:"extra-small",appearance:"outline",color:"success",children:x},x))]}),f.displayRules.length>0&&s.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"Display rules:"}),f.displayRules.map(x=>s.jsx(wo,{size:"extra-small",appearance:"outline",color:"informative",children:x},x))]})]}):e.commandId?s.jsx("div",{className:i.commandRow,children:s.jsxs(P,{className:i.commandId,style:{color:m.colorStatusWarningForeground3},children:[e.commandId," (not found)"]})}):s.jsxs(s.Fragment,{children:[s.jsx(Ee,{label:"Bind existing command",style:{width:"100%",minWidth:0},children:s.jsxs(dt,{size:"small",value:u,onChange:(x,h)=>p(h.value),style:{width:"100%",minWidth:0},children:[s.jsx("option",{value:"",children:"Select command…"}),r.map(x=>s.jsx("option",{value:x.id,children:x.id},x.id))]})}),s.jsxs("div",{style:{display:"flex",gap:m.spacingHorizontalXS},children:[s.jsx(K,{appearance:"outline",size:"small",onClick:v,children:"Bind selected"}),s.jsx(K,{appearance:"outline",size:"small",icon:s.jsx(Ae,{}),onClick:b,children:"Create and bind"})]})]})]})}const zb=le({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"}}),xl=({kind:e})=>{const t=zb(),n=Z(j=>j.location),o=Z(j=>j.tabId),i=Z(j=>j.selectedGroupId),r=Z(j=>j.selectedButtonId),l=O(j=>j.commands),a=O(j=>j.displayRules),c=O(j=>j.enableRules),d=O(j=>j.upsertCommand),u=O(j=>j.upsertDisplayRule),p=O(j=>j.upsertEnableRule),f=O(j=>j.batch),b=Y(j=>j.openRuleEditor),y=O(j=>j.ribbons)[n].tabs.find(j=>j.id===o)?.groups.find(j=>j.id===i),w=Qt(y,r),I=l.find(j=>j.id===w?.commandId),S=e==="display"?I?.displayRules??[]:I?.enableRules??[],C=e==="display"?a:c,[$,R]=Ue.useState(""),E=C.filter(j=>!S.includes(j.id)),T=j=>{if(!I)return;const B=S.filter(N=>N!==j);d(e==="display"?{...I,displayRules:B}:{...I,enableRules:B})},_=e==="display"?"Display rules (ALL must pass)":"Enable rules (ALL must pass)",D=()=>{if(!I)return;if(e==="display"){const N=new Set(a.map(U=>U.id)),W=yn(Rs(I.id),"Display",N);f(()=>{u({id:W,steps:[]}),d({...I,displayRules:[...I.displayRules,W]})}),b(W,"display");return}const j=new Set(c.map(N=>N.id)),B=yn(Rs(I.id),"Enable",j);f(()=>{p({id:B,steps:[]}),d({...I,enableRules:[...I.enableRules,B]})}),b(B,"enable")},L=()=>{!I||!$||(d(e==="display"?{...I,displayRules:[...I.displayRules,$]}:{...I,enableRules:[...I.enableRules,$]}),R(""))};return s.jsxs("div",{className:t.section,children:[s.jsxs("div",{className:t.header,children:[s.jsx(P,{size:200,weight:"semibold",children:_}),S.length>0&&s.jsx(ae,{appearance:"tint",size:"small",color:"informative",children:S.length})]}),!I&&s.jsx(P,{className:t.note,children:"Bind a command first to manage rules."}),s.jsx("div",{className:t.pillList,children:S.map(j=>{const B=C.find(N=>N.id===j);return s.jsxs("div",{className:t.pill,children:[s.jsx("span",{className:t.pillLabel,onClick:()=>b(j,e==="display"?"display":"enable"),title:`${j} — ${B?.steps.length??0} step(s)`,children:j}),s.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",color:m.colorNeutralForeground3},onClick:()=>T(j),"aria-label":`Remove rule ${j}`,children:s.jsx(ro,{style:{fontSize:12}})})]},j)})}),I&&s.jsxs(s.Fragment,{children:[s.jsx(Ee,{label:`Bind existing ${e} rule`,style:{width:"100%",minWidth:0},children:s.jsxs(dt,{size:"small",value:$,onChange:(j,B)=>R(B.value),style:{width:"100%",minWidth:0},children:[s.jsx("option",{value:"",children:"Select rule…"}),E.map(j=>s.jsx("option",{value:j.id,children:j.id},j.id))]})}),s.jsxs("div",{style:{display:"flex",gap:m.spacingHorizontalXS},children:[s.jsx(K,{className:t.addBtn,appearance:"subtle",size:"small",onClick:L,disabled:!$,children:"Bind selected"}),s.jsxs(K,{className:t.addBtn,appearance:"subtle",size:"small",icon:s.jsx(Ae,{}),onClick:D,children:["Create new ",e," rule"]})]})]}),e==="enable"&&s.jsxs(P,{className:t.note,children:["Note: Disabled buttons are ",s.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."]})]})},Bb=()=>s.jsx(xl,{kind:"display"}),Mb=()=>s.jsx(xl,{kind:"enable"}),Lb=le({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}}),Pb=()=>{const e=Lb(),t=Y(c=>c.openScalingEditor),n=Z(c=>c.location),o=Z(c=>c.tabId),l=O(c=>c.ribbons)[n].tabs.find(c=>c.id===o),a=l?.groups.length??0;return s.jsxs("div",{className:e.section,children:[s.jsxs("div",{className:e.header,children:[s.jsx(P,{size:200,weight:"semibold",children:"Scaling"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(ao,{}),onClick:t,children:"Edit scaling"})]}),s.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?s.jsxs(P,{size:100,className:e.note,children:["Tab ",s.jsx("strong",{children:l.label})," has ",a," group(s). Open the Scaling Editor to configure MaxSize and Scale steps."]}):s.jsx(P,{size:100,className:e.note,children:"Select a tab to configure scaling."})]})},Fb=le({section:{display:"flex",flexDirection:"column",gap:m.spacingHorizontalXS},row:{display:"flex",alignItems:"center",gap:m.spacingHorizontalS},note:{fontSize:m.fontSizeBase100,color:m.colorNeutralForeground3}}),_b=[{label:"Show on Unified Interface (Refresh)",value:"Refresh"},{label:"Show on Classic ribbon (Legacy)",value:"Legacy"},{label:"Show on Tablets (Modern)",value:"Modern"}],qb=()=>{const e=Fb(),t=Z(N=>N.location),n=Z(N=>N.tabId),o=Z(N=>N.selectedGroupId),i=Z(N=>N.selectedButtonId),r=O(N=>N.ribbons),l=O(N=>N.upsertCommand),a=O(N=>N.upsertDisplayRule),c=O(N=>N.batch),d=O(N=>N.commands),u=O(N=>N.displayRules),p=Y(N=>N.openCommandEditor),f=O(N=>N.setOpenRecordOverride),b=Z(N=>N.clearSelection),v=ne(N=>N.activeSolution),x=ne(N=>N.publisherPrefix),h=r[t],w=h.tabs.find(N=>N.id===n)?.groups.find(N=>N.id===o),I=Qt(w,i),S=wa.includes(t),C=Ia(h),$=C.length>0,R=C.map(N=>Ra(N)),E=R.includes("theirs"),T=!E&&R.includes("unknown"),_=!$&&!ja(h),D=Gi(h).filter(N=>!Ca(N.button)),L=N=>{const W=v?.publisherPrefix?.trim()||x?.trim()||"new";!N&&C.some(U=>U.button.id===i)&&b(),!(!f(t,N,W)||!N)&&p(ze)},j=()=>{if(I?.commandId)return d.find(N=>N.id===I.commandId)},B=N=>{const W=j();if(!W)return;let X=u.find(F=>F.steps.length===1&&F.steps[0].kind==="CommandClientTypeRule"&&F.steps[0].type===N)?.id,Q;if(!X){const F=`${W.id}.${N}.DisplayRule`;X=F;let J=1;for(;u.some(g=>g.id===X);)X=`${F}.${J}`,J+=1;Q={id:X,steps:[{kind:"CommandClientTypeRule",type:N}]}}const q=X;c(()=>{Q&&a(Q),W.displayRules.includes(q)||l({...W,displayRules:[...W.displayRules,q]})})};return s.jsxs("div",{className:e.section,children:[s.jsx(P,{size:200,weight:"semibold",children:"Advanced"}),I&&s.jsx("div",{children:s.jsxs(P,{size:100,className:e.note,children:["Tab: ",s.jsx("code",{style:{fontFamily:m.fontFamilyMonospace},children:n})]})}),S&&s.jsxs("div",{children:[s.jsx(Ni,{label:`Override default record open behavior on the ${t==="SubGrid"?"sub-grid":"home grid"} (Mscrm.OpenRecordItem)`,checked:$,disabled:E||T||_,onChange:(N,W)=>L(W.checked)}),s.jsxs(P,{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. `,s.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."]}),E&&s.jsx(P,{size:100,className:e.note,children:`The "Open record" button here comes from another solution, so the override can't be turned off from your customizations.`}),T&&s.jsx(P,{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.`}),D.length>0&&s.jsxs(P,{size:100,className:e.note,children:["Also using Mscrm.OpenRecordItem here:"," ",D.map(N=>N.button.id).join(", "),". Turning the override off keeps ",D.length===1?"it":"them"," and the command."]}),_&&s.jsx(P,{size:100,className:e.note,children:"This location has no group to put the button in."})]}),t==="Form"&&s.jsx(P,{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)."}),s.jsxs("div",{children:[s.jsx(P,{size:100,weight:"semibold",className:e.note,children:"Client type filter (adds a CommandClientTypeRule):"}),s.jsxs(P,{size:100,className:e.note,children:[s.jsx("strong",{children:"Refresh"})," = Unified Interface web client | ",s.jsx("strong",{children:"Legacy"})," = Classic ribbon / Outlook | ",s.jsx("strong",{children:"Modern"})," = Dynamics 365 for tablets"]}),s.jsx("div",{className:e.row,style:{marginTop:"4px"},children:_b.map(N=>s.jsx(ae,{appearance:"outline",style:{cursor:"pointer"},title:`Add CommandClientTypeRule: ${N.value}`,onClick:()=>B(N.value),children:N.label},N.value))})]})]})},Hb=le({banner:{marginBottom:m.spacingHorizontalXS}}),Wb=()=>{const e=Hb(),t=Z(y=>y.selectedButtonId),n=Z(y=>y.selectedGroupId),o=Z(y=>y.location),i=Z(y=>y.tabId),r=O(y=>y.conflicts),l=O(y=>y.ribbons),a=Y(y=>y.openConflictDrawer),u=l[o].tabs.find(y=>y.id===i)?.groups.find(y=>y.id===n),p=Qt(u,t),f=r.find(y=>y.elementId===t),b=p?.origin==="managed";if(!t||!b&&!f)return null;const v=p?.solutionName??f?.solutions[0]?.solutionName,x=p?.publisherName??f?.solutions[0]?.publisher,h=f?.solutions.length??(b?1:0);return s.jsxs(Ce,{intent:"warning",className:e.banner,children:[s.jsx(Ie,{children:s.jsx(P,{children:h>1?`This button is customized by ${h} solutions. The last imported solution wins.`:`This button belongs to a managed solution${v?` “${v}”`:""}${x?` by ${x}`:""}. Customizing it will create an unmanaged override.`})}),s.jsx(hn,{children:s.jsx(K,{appearance:"transparent",size:"small",onClick:()=>t&&a(t),children:"View solution layers"})})]})},Gb=le({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 Ub(){const e=Gb(),t=O(r=>r.layers),n=O(r=>r.pendingUnhides),o=O(r=>r.setLayerHideUnhidden),i=["entity","application"].flatMap(r=>(t[r]?.hides??[]).map(l=>({scope:r,...l})));return i.length===0?null:s.jsxs("section",{className:e.root,"aria-label":"Hidden by customizations",children:[s.jsx(Rt,{children:"Hidden by customizations"}),s.jsx(Be,{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(r=>{const l=n[r.scope].includes(r.location);return s.jsxs("div",{className:e.row,children:[s.jsx(Ye,{}),s.jsx(Ne,{content:`${r.location} (${r.scope==="entity"?"this table":"application ribbon"})`,relationship:"description",children:s.jsx(P,{className:`${e.id} ${l?e.pending:""}`,children:r.location})}),s.jsx(K,{size:"small",appearance:l?"subtle":"secondary",onClick:()=>o(r.scope,r.location,!l),children:l?"Keep hidden":"Unhide"})]},`${r.scope}:${r.location}`)})]})}const Xb=le({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 Vb(){const e=Xb(),t=O(a=>a.orphans),n=O(a=>a.pendingOrphanDeletes),o=O(a=>a.setOrphanDeleted),[i,r]=M.useState(null),l=["entity","application"].flatMap(a=>t[a].map(c=>({scope:a,...c})));return l.length===0?null:s.jsxs("section",{className:e.root,"aria-label":"Orphaned customizations",children:[s.jsx(Rt,{children:"Orphaned customizations"}),s.jsx(Be,{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?s.jsx(K,{size:"small",appearance:"subtle","aria-label":`Keep ${a.id}`,onClick:()=>o(a.scope,a.id,!1),children:"Keep"}):p?s.jsx(Ne,{content:"Published from here moments ago: reload later — it most likely isn't loaded yet",relationship:"description",children:s.jsx(K,{size:"small",disabledFocusable:!0,"aria-label":`Delete ${a.id}`,children:"Delete"})}):a.recentPublish&&i!==u?s.jsx(K,{size:"small",appearance:"secondary","aria-label":`Delete ${a.id}`,onClick:()=>r(u),children:"Delete…"}):a.recentPublish?s.jsx(K,{size:"small",appearance:"primary","aria-label":`Delete ${a.id} anyway`,onClick:()=>{r(null),o(a.scope,a.id,!0)},children:"Delete anyway"}):s.jsx(K,{size:"small",appearance:"secondary","aria-label":`Delete ${a.id}`,onClick:()=>o(a.scope,a.id,!0),children:"Delete"});return s.jsxs("div",{className:e.row,children:[s.jsx(Mu,{className:e.icon}),s.jsxs("div",{className:e.text,children:[s.jsx(Ne,{content:`${a.element} ${a.id} — CustomAction ${a.customActionId} at ${a.location}`,relationship:"description",children:s.jsxs(P,{className:qt(e.mono,c&&e.pending),children:[d,a.id]})}),s.jsx(Be,{className:qt(e.mono,e.why),children:a.location}),s.jsx(Be,{className:e.why,children:a.why})]}),f]},u)})]})}const Kb=le({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 Jb({button:e,location:t,tabId:n,groupId:o}){const i=Kb(),r=O(v=>v.locLabels),l=O(v=>v.setButtonProp),a=O(v=>v.hideOobButton),c=O(v=>v.hideWithDisplayRules),[d,u]=M.useState(!1),p=t==="Application"&&n==="Mscrm.GlobalTab"&&e.oob&&!e.custom,f=Gn[e.kind],b=(v,x)=>x?s.jsxs("div",{className:i.field,children:[s.jsx(Be,{children:v}),s.jsx(P,{className:i.mono,children:x})]}):null;return s.jsxs("section",{className:i.root,"aria-label":`${f} (read-only)`,children:[s.jsxs("div",{className:i.title,children:[s.jsx(It,{"aria-hidden":!0}),s.jsx(Rt,{children:f})]}),s.jsxs(Be,{children:["Command Bar Studio shows this <",gn[e.kind],"> but doesn't edit it. You can hide it, and move or delete it when your customizations add it; its XML is published as it was loaded."]}),b("Label",ce(e.label,r)),b("Id",e.id),b("Command",e.commandId||void 0),s.jsx("div",{children:s.jsx(K,{size:"small",disabled:p,icon:e.hidden?s.jsx(Ct,{}):s.jsx(Ye,{}),onClick:()=>!e.hidden&&e.oob?u(!0):l(t,n,o,e.id,{hidden:!e.hidden}),children:e.hidden?"Unhide":"Hide"})}),d&&s.jsx(Zi,{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&&s.jsxs("div",{className:i.field,children:[s.jsx(Be,{children:"XML"}),s.jsx("pre",{className:i.xml,children:e.source.xml})]})]})}const as=le({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=as();return t?s.jsxs(s.Fragment,{children:[s.jsx(P,{className:o.key,children:e}),s.jsx(P,{className:`${o.value} ${n?o.mono:""}`,children:t})]}):null}function Yb({command:e,items:t}){const n=as(),o=en(),i=fe(a=>a.selectCommand),r=fe(a=>e.parentId?a.commands.find(c=>c.id===e.parentId):void 0),l=e.visibility==="formula"||e.action==="formula";return s.jsxs("section",{className:n.root,"aria-label":"Modern command properties",children:[s.jsxs("div",{className:n.title,children:[s.jsx(Rt,{children:e.label}),s.jsx(ae,{appearance:"tint",color:"important",children:"Modern"}),e.managed&&s.jsx(ae,{appearance:"outline",color:"informative",children:"Managed"})]}),s.jsx(Ce,{intent:"info",children:s.jsx(Ie,{children:"Modern commands are read-only in Command Bar Studio and are never published from here. Edit them in the command designer."})}),s.jsxs("div",{className:n.grid,children:[rl(e,o).map(a=>s.jsx(st,{label:a.label,value:a.value},a.label)),s.jsx(st,{label:"Tooltip title",value:e.tooltipTitle}),s.jsx(st,{label:"Tooltip text",value:e.tooltipDescription}),s.jsx(st,{label:"Accessibility text",value:e.accessibilityText}),s.jsx(st,{label:"Icon",value:e.fontIcon??e.iconWebResourceName??e.iconWebResourceId}),s.jsx(st,{label:"Group title",value:e.groupTitle}),s.jsx(st,{label:"Name",value:e.name}),s.jsx(st,{label:"Unique name",value:e.uniqueName,mono:!0}),s.jsx(st,{label:"Id",value:e.id,mono:!0})]}),l&&s.jsx(Be,{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."}),r&&s.jsxs(s.Fragment,{children:[s.jsx(Ve,{}),s.jsx(P,{className:n.key,children:"Inside"}),s.jsx(Yo,{onClick:()=>i(r.id),children:r.label})]}),t.length>0&&s.jsxs(s.Fragment,{children:[s.jsx(Ve,{}),s.jsxs(P,{className:n.key,children:["Items (",t.length,")"]}),s.jsx("div",{className:n.list,children:t.map(a=>s.jsxs(Yo,{onClick:()=>i(a.id),children:[a.label,a.hidden?" (hidden)":""]},a.id))})]}),e.classicRules.length>0&&s.jsxs(s.Fragment,{children:[s.jsx(Ve,{}),s.jsxs(P,{className:n.key,children:["Classic rules (",e.classicRules.length,")"]}),s.jsx("div",{className:n.list,children:e.classicRules.map(a=>s.jsxs(P,{className:`${n.value} ${n.mono}`,children:[a.kind==="enable"?"Enable":"Display",":"," ",a.uniqueName??a.name]},a.id))})]})]})}function Zb({overrides:e}){const t=as(),n=en(),o=fe(r=>r.selectCommand);if(e.length===0)return null;const i=e.some(r=>r.effect==="hidden");return s.jsx("section",{className:t.root,"aria-label":"Modern command overrides",children:s.jsx(Ce,{intent:i?"warning":"info",children:s.jsx(Ie,{children:s.jsxs("div",{className:t.list,children:[e.map(r=>s.jsxs("span",{children:[es(r,n),"."," ",s.jsx(Yo,{inline:!0,onClick:()=>o(r.command.id),children:"View"})]},r.command.id)),s.jsx(Be,{children:"Matched by the migrated command's unique name. Unified Interface may show the modern command instead of this button."})]})})})})}const Qb=le({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 ey(){const e=Qb(),t=Z(v=>v.selectedButtonId),n=Z(v=>v.selectedGroupId),o=Z(v=>v.location),i=Z(v=>v.tabId),c=O(v=>v.ribbons)[o].tabs.find(v=>v.id===i)?.groups.find(v=>v.id===n),d=Qt(c,t),u=c&&d?Vn(c,d.id):void 0,p=O(v=>v.locLabels),f=Eg(),b=Ag(o,d?.id);return s.jsxs("aside",{className:e.root,"aria-label":"Properties",children:[s.jsx("div",{className:e.header,children:s.jsx(Rt,{children:"Properties"})}),!d&&f?s.jsx(Yb,{command:f.command,items:f.children}):d?s.jsxs(s.Fragment,{children:[s.jsx(Wb,{}),s.jsx(Zb,{overrides:b}),u&&s.jsx("div",{className:e.section,children:s.jsxs(Be,{children:["Menu item of “",ce(u.parent.label,p),"”",u.section.title?` — section “${u.section.title}”`:""]})}),Ze(d.kind)?s.jsx(Jb,{button:d,location:o,tabId:i,groupId:n}):s.jsxs(s.Fragment,{children:[s.jsx(Tb,{button:d,location:o,tabId:i,groupId:n}),s.jsx(Ve,{}),s.jsx("div",{className:e.section,children:s.jsx(Ob,{button:d,groupId:n,tabId:i,location:o})}),s.jsx(Ve,{}),s.jsx("div",{className:e.section,children:s.jsx(Bb,{})}),s.jsx(Ve,{}),s.jsx("div",{className:e.section,children:s.jsx(Mb,{})}),s.jsx(Ve,{}),s.jsx("div",{className:e.section,children:s.jsx(Pb,{})}),s.jsx(Ve,{}),s.jsx("div",{className:e.section,children:s.jsx(qb,{})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:e.empty,children:[s.jsx(Lu,{fontSize:32,style:{opacity:.4}}),s.jsx(P,{size:300,children:"Select a button to view its properties"})]}),s.jsx(Ub,{}),s.jsx(Vb,{})]})]})}const vl=le({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 ty(){const e=vl(),t=Y(g=>g.activeBottomTab),n=Y(g=>g.setActiveBottomTab),o=Y(g=>g.bottomPanelHeight),i=Y(g=>g.bottomCollapsed),r=Y(g=>g.setBottomCollapsed),l=O(g=>g.commands),a=O(g=>g.displayRules),c=O(g=>g.enableRules),d=O(g=>g.past),u=O(g=>g.ribbons),p=O(g=>g.restore),f=ne(g=>g.currentUserName),b=ie(g=>g.entries),v=ie(g=>g.clear),x=Y(g=>g.openCommandEditor),h=Y(g=>g.openRuleEditor),y=Y(g=>g.openDiffViewer),w=O(g=>g.upsertCommand),I=O(g=>g.upsertEnableRule),S=O(g=>g.upsertDisplayRule),[C,$]=M.useState(""),[R,E]=M.useState(""),[T,_]=M.useState(""),[D,L]=M.useState(""),j=M.useMemo(()=>{const g=C.toLowerCase().trim();return g?l.filter(k=>k.id.toLowerCase().includes(g)||k.enableRules.some(A=>A.toLowerCase().includes(g))||k.displayRules.some(A=>A.toLowerCase().includes(g))):l},[l,C]),B=M.useMemo(()=>{const g=R.toLowerCase().trim();return g?a.filter(k=>k.id.toLowerCase().includes(g)||k.steps.some(A=>A.kind.toLowerCase().includes(g))):a},[a,R]),N=M.useMemo(()=>{const g=T.toLowerCase().trim();return g?c.filter(k=>k.id.toLowerCase().includes(g)||k.steps.some(A=>A.kind.toLowerCase().includes(g))):c},[c,T]),W=M.useMemo(()=>{const g=D.toLowerCase().trim();return g?d.filter(k=>k.op.toLowerCase().includes(g)||k.target.toLowerCase().includes(g)||k.detail.toLowerCase().includes(g)||k.userName.toLowerCase().includes(g)):d},[d,D]),U=()=>{const g=new Set(l.map(A=>A.id)),k=qi("New","Command",g);w({id:k,enableRules:[],displayRules:[],actions:[]}),x(k)},X=()=>{const g=new Set(c.map(A=>A.id)),k=yn("New","Enable",g);I({id:k,steps:[]}),h(k,"enable")},Q=()=>{const g=new Set(a.map(A=>A.id)),k=yn("New","Display",g);S({id:k,steps:[]}),h(k,"display")},q=M.useMemo(()=>{const g={};for(const k of Object.values(u))for(const A of k.tabs)for(const te of A.groups)for(const de of je(te))de.commandId&&(g[de.commandId]=(g[de.commandId]??0)+1);return g},[u]),F=M.useMemo(()=>{const g={};for(const k of l)for(const A of[...k.enableRules,...k.displayRules])g[A]=(g[A]??0)+1;return g},[l]),J=i?32:o;function G(g){return g.userName&&g.userName!=="You"?g.userName:f||"You"}return s.jsxs("div",{className:e.root,style:{height:J},children:[s.jsxs("div",{className:e.tabRow,children:[s.jsxs(ki,{selectedValue:t,onTabSelect:(g,k)=>n(k.value),size:"small",style:{flex:1},children:[s.jsxs(Ke,{value:"commands",children:["Commands (",l.length,")"]}),s.jsxs(Ke,{value:"displayRules",children:["Display rules (",a.length,")"]}),s.jsxs(Ke,{value:"enableRules",children:["Enable rules (",c.length,")"]}),s.jsxs(Ke,{value:"history",children:["History (",d.length,")"]}),s.jsx(Ke,{value:"console",children:"Console"})]}),s.jsx(K,{appearance:"subtle",size:"small",icon:i?s.jsx($r,{}):s.jsx(gt,{}),onClick:()=>r(!i),"aria-label":i?"Expand panel":"Collapse panel"})]}),!i&&s.jsxs("div",{className:e.content,children:[t==="commands"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:e.toolbar,children:[s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Ae,{}),onClick:U,children:"New command"}),s.jsx(qe,{size:"small",contentBefore:s.jsx(ft,{}),placeholder:`Filter ${l.length} command${l.length!==1?"s":""}…`,value:C,onChange:(g,k)=>$(k.value),style:{minWidth:0,flex:1,maxWidth:360}}),C&&s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[j.length," match",j.length!==1?"es":""]})]}),s.jsxs("table",{className:e.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{className:e.th,children:"Command"}),s.jsx("th",{className:e.th,children:"Actions"}),s.jsx("th",{className:e.th,children:"Enable rules"}),s.jsx("th",{className:e.th,children:"Display rules"}),s.jsx("th",{className:e.th,children:"Refs"}),s.jsx("th",{className:e.th})]})}),s.jsx("tbody",{children:j.map(g=>s.jsxs("tr",{children:[s.jsx("td",{className:e.td,children:s.jsx("span",{className:e.mono,onClick:()=>x(g.id),role:"button",tabIndex:0,onKeyDown:k=>k.key==="Enter"&&x(g.id),children:g.id})}),s.jsxs("td",{className:e.td,children:[g.actions.map((k,A)=>s.jsx("span",{className:e.chip,children:k.kind==="javascript"?"JS":k.kind==="url"?"URL":k.kind==="powerFx"?"Fx":k.kind==="customApi"?"API":k.kind==="outlookCommand"?"Outlook":"XML"},A)),g.actions.length===0&&s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"—"})]}),s.jsx("td",{className:e.td,children:g.enableRules.map(k=>s.jsx(Ne,{content:k,relationship:"label",children:s.jsx("span",{className:e.chip,style:{cursor:"pointer",color:m.colorBrandForeground1},onClick:()=>h(k,"enable"),children:k.split(".").pop()})},k))}),s.jsx("td",{className:e.td,children:g.displayRules.map(k=>s.jsx(Ne,{content:k,relationship:"label",children:s.jsx("span",{className:e.chip,style:{cursor:"pointer",color:m.colorBrandForeground1},onClick:()=>h(k,"display"),children:k.split(".").pop()})},k))}),s.jsx("td",{className:e.td,children:s.jsx(ae,{size:"small",appearance:"tint",color:q[g.id]?"brand":"informative",children:q[g.id]??0})}),s.jsx("td",{className:e.td,children:s.jsx(K,{appearance:"subtle",size:"small",onClick:()=>x(g.id),children:"Edit"})})]},g.id))})]})]}),t==="displayRules"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:e.toolbar,children:[s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Ae,{}),onClick:Q,children:"New display rule"}),s.jsx(qe,{size:"small",contentBefore:s.jsx(ft,{}),placeholder:`Filter ${a.length} display rule${a.length!==1?"s":""}…`,value:R,onChange:(g,k)=>E(k.value),style:{minWidth:0,flex:1,maxWidth:360}}),R&&s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[B.length," match",B.length!==1?"es":""]})]}),s.jsx(Zs,{rules:B,kind:"display",ruleRefs:F,onEdit:g=>h(g,"display"),styles:e})]}),t==="enableRules"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:e.toolbar,children:[s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Ae,{}),onClick:X,children:"New enable rule"}),s.jsx(qe,{size:"small",contentBefore:s.jsx(ft,{}),placeholder:`Filter ${c.length} enable rule${c.length!==1?"s":""}…`,value:T,onChange:(g,k)=>_(k.value),style:{minWidth:0,flex:1,maxWidth:360}}),T&&s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[N.length," match",N.length!==1?"es":""]})]}),s.jsx(Zs,{rules:N,kind:"enable",ruleRefs:F,onEdit:g=>h(g,"enable"),styles:e})]}),t==="history"&&s.jsxs(s.Fragment,{children:[d.length>0&&s.jsxs("div",{className:e.toolbar,children:[s.jsx(qe,{size:"small",contentBefore:s.jsx(ft,{}),placeholder:`Filter ${d.length} entr${d.length!==1?"ies":"y"}…`,value:D,onChange:(g,k)=>L(k.value),style:{minWidth:0,flex:1,maxWidth:360}}),D&&s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[W.length," match",W.length!==1?"es":""]})]}),d.length===0?s.jsx(P,{size:200,style:{color:m.colorNeutralForeground3},children:"No history yet — make a change to see it here."}):W.slice().reverse().map((g,k)=>{const A=d.indexOf(g);return s.jsxs("div",{className:e.historyRow,children:[s.jsx("div",{className:e.historyAvatar,"aria-hidden":!0,children:s.jsx(jr,{fontSize:12,style:{color:m.colorBrandForeground1}})}),s.jsxs("div",{className:e.historyContent,children:[s.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[s.jsx(P,{size:200,weight:"semibold",children:g.op}),s.jsxs(P,{size:200,children:["— ",s.jsx("strong",{children:g.target})]}),g.detail&&s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:g.detail})]}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2},children:[s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[G(g)," ·"," ",new Date(g.ts).toLocaleTimeString()]}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Sr,{}),onClick:()=>y("history"),children:"View diff"}),s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Cr,{}),title:"Undo this change and every later one (redo brings them back)",onClick:()=>p(A),children:"Undo from here"})]})]})]},k)})]}),t==="console"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:e.toolbar,children:[s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(fn,{}),disabled:b.length===0,onClick:()=>{const g=b.slice().reverse().map(k=>{const A=new Date(k.ts).toLocaleTimeString();return`${k.scope} ${A}
|
|
136
|
-
[${k.level.toUpperCase()}]
|
|
137
|
-
${k.message}`}).join(`
|
|
138
|
-
|
|
139
|
-
`);window.toolboxAPI?.utils.copyToClipboard(g).catch(()=>{navigator.clipboard?.writeText(g)})},title:"Copy all log entries to clipboard",children:"Copy log"}),s.jsx(K,{appearance:"subtle",size:"small",onClick:v,children:"Clear log"})]}),s.jsx("div",{children:b.length===0?s.jsx(P,{size:200,style:{color:m.colorNeutralForeground3},children:"No runtime diagnostics yet."}):b.slice().reverse().map(g=>s.jsx(ny,{ts:`${g.scope} ${new Date(g.ts).toLocaleTimeString()}`,level:g.level,message:g.message},g.id))})]})]})]})}function Zs({rules:e,kind:t,ruleRefs:n,onEdit:o,styles:i}){return s.jsxs("table",{className:i.table,children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{className:i.th,children:"Rule"}),s.jsx("th",{className:i.th,children:"Steps"}),s.jsx("th",{className:i.th,children:"Used by"}),s.jsx("th",{className:i.th,children:"Type"}),s.jsx("th",{className:i.th})]})}),s.jsx("tbody",{children:e.map(r=>s.jsxs("tr",{children:[s.jsx("td",{className:i.td,children:s.jsx("span",{className:i.mono,onClick:()=>o(r.id),role:"button",tabIndex:0,onKeyDown:l=>l.key==="Enter"&&o(r.id),children:r.id})}),s.jsxs("td",{className:i.td,children:[r.steps.slice(0,3).map((l,a)=>s.jsx("span",{className:i.chip,children:l.kind.replace(/Rule$/,"")},a)),r.steps.length>3&&s.jsxs("span",{className:i.chip,style:{color:m.colorNeutralForeground3},children:["+",r.steps.length-3]}),r.steps.length===0&&s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"—"})]}),s.jsx("td",{className:i.td,children:s.jsxs(ae,{size:"small",appearance:"tint",color:n[r.id]?"brand":"informative",children:[n[r.id]??0," cmd",n[r.id]!==1?"s":""]})}),s.jsx("td",{className:i.td,children:s.jsx(ae,{size:"small",appearance:"outline",color:t==="enable"?"success":"informative",children:t})}),s.jsx("td",{className:i.td,children:s.jsx(K,{appearance:"subtle",size:"small",onClick:()=>o(r.id),children:"Edit"})})]},r.id))})]})}function ny({ts:e,level:t,message:n}){const o=vl(),i=t==="error"?m.colorStatusDangerForeground1:t==="warn"?m.colorStatusWarningForeground1:m.colorNeutralForeground3;return s.jsxs("div",{className:o.consoleRow,children:[s.jsx("span",{className:o.consoleTs,children:e}),s.jsxs("span",{style:{color:i},children:["[",t.toUpperCase(),"]"]}),s.jsx("span",{style:{color:m.colorNeutralForeground1},children:n})]})}const Sl=le({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%"},sectionHeader:{padding:`${m.spacingHorizontalXS} ${m.spacingHorizontalS}`,display:"flex",alignItems:"center",gap:m.spacingHorizontalXS,cursor:"pointer",userSelect:"none",":hover":{backgroundColor:m.colorNeutralBackground3}},entityRow:{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 oy(){const e=Sl(),t=ne(w=>w.entities),n=ne(w=>w.activeEntity),o=ye(w=>w.requestEntitySwitch),i=ne(w=>w.activeSolution),r=ne(w=>w.solutionEntityIds),[l,a]=M.useState(""),[c,d]=M.useState(!0),[u,p]=M.useState(!0),f=t,b=M.useMemo(()=>{const w=l.toLowerCase();return f.filter(I=>I.displayName.toLowerCase().includes(w)||I.logicalName.toLowerCase().includes(w))},[f,l]),v=b.filter(w=>w.isCustomEntity),x=b.filter(w=>!w.isCustomEntity),h=M.useMemo(()=>[...v.length>0?[{kind:"header",id:"custom-header",label:"CUSTOM",count:v.length}]:[],...c?v.map(w=>({kind:"entity",id:`custom-${w.logicalName}`,entity:w})):[],...x.length>0?[{kind:"header",id:"standard-header",label:"STANDARD",count:x.length}]:[],...u?x.map(w=>({kind:"entity",id:`std-${w.logicalName}`,entity:w})):[]],[v,c,x,u]),y=[rt({columnId:"table",renderHeaderCell:()=>s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:"Entity"}),renderCell:w=>{if(w.kind==="header"){const I=w.label==="CUSTOM"?c:u;return s.jsx("div",{className:e.sectionHeader,onClick:()=>w.label==="CUSTOM"?d(S=>!S):p(S=>!S),role:"button","aria-expanded":I,children:s.jsxs(P,{size:100,weight:"semibold",style:{color:m.colorNeutralForeground3},children:[I?"▾":"▸"," ",w.label," (",w.count,")"]})})}return s.jsx(iy,{entity:w.entity,isActive:n?.logicalName===w.entity.logicalName,onClick:()=>o(w.entity)})}})];return s.jsxs("div",{className:e.root,children:[s.jsx("div",{className:e.header,children:s.jsx(Rt,{children:"Tables"})}),s.jsx("div",{className:e.searchBox,children:s.jsx(qe,{contentBefore:s.jsx(ft,{}),placeholder:"Search tables…",size:"small",value:l,onChange:(w,I)=>a(I.value),style:{width:"100%"}})}),s.jsxs("div",{className:e.scrollArea,children:[!i&&s.jsx("div",{style:{padding:24,textAlign:"center"},children:s.jsx(P,{size:200,style:{color:m.colorNeutralForeground3},children:"Select a solution from the top bar to see its tables."})}),i&&r===null&&s.jsx("div",{style:{padding:24,textAlign:"center"},children:s.jsx(Ti,{size:"small",label:"Loading solution tables…"})}),i&&r!==null&&f.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center"},children:s.jsxs(P,{size:200,style:{color:m.colorNeutralForeground3},children:["No tables to show for ",s.jsx("em",{children:i.friendlyName}),".",s.jsx("br",{}),s.jsx("br",{}),"Add a table to the solution in the maker portal (Solutions ›"," ",s.jsx("em",{children:i.friendlyName})," › Add existing › Table) and reload."]})}),i&&r!==null&&f.length>0&&s.jsxs(ss,{className:e.gridWrap,items:h,columns:y,getRowId:w=>w.id,focusMode:"none",children:[s.jsx(rs,{children:s.jsx(In,{children:({renderHeaderCell:w})=>s.jsx(Ar,{children:w()})})}),s.jsx(is,{itemSize:52,height:420,listProps:{width:"100%"},children:({item:w,rowId:I},S)=>s.jsx(In,{style:S,children:({renderCell:C})=>s.jsx(Dr,{children:C(w)})},I)})]})]})]})}function iy({entity:e,isActive:t,onClick:n}){const o=Sl();return s.jsxs("div",{className:`${o.entityRow} ${t?o.entityRowActive:""}`,onClick:n,role:"button",tabIndex:0,"aria-pressed":t,onKeyDown:i=>i.key==="Enter"&&n(),children:[s.jsxs("div",{className:o.entityName,children:[s.jsx(P,{size:200,weight:t?"semibold":"regular",children:e.displayName}),s.jsx("br",{}),s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3},children:e.logicalName})]}),e.isManaged&&s.jsx(It,{fontSize:12,style:{color:m.colorNeutralForeground3},"aria-label":"Managed"})]})}const sy="application/x-rw-se",Qs={HomepageGrid:"Home",SubGrid:"Sub",Form:"Form",Application:"App"},ry=le({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 ay(){const e=ry(),[t,n]=M.useState("commands"),o=O(h=>h.commands),i=O(h=>h.displayRules),r=O(h=>h.enableRules),l=O(h=>h.templates),a=O(h=>h.ribbons),c=O(h=>h.baseline),d=O(h=>h.upsertCommand),u=O(h=>h.upsertEnableRule),p=Y(h=>h.openCommandEditor),f=Y(h=>h.openRuleEditor),b=M.useMemo(()=>{const h=[];for(const y of Object.keys(a)){const w=a[y],I=c[y];for(const S of w.tabs)for(const C of S.groups)for(const $ of je(C)){if(!$.custom)continue;const R=I.tabs.flatMap(E=>E.groups).flatMap(E=>je(E)).some(E=>E.id===$.id);h.push({button:$,location:y,tabId:S.id,groupId:C.id,isNew:!R})}}return h},[a,c]),v=()=>{const h=new Set(o.map(w=>w.id)),y=qi("New","Command",h);d({id:y,enableRules:[],displayRules:[],actions:[]}),p(y)},x=()=>{const h=new Set([...r.map(w=>w.id),...i.map(w=>w.id)]),y=yn("New","Enable",h);u({id:y,steps:[]}),f(y,"enable")};return s.jsxs("div",{className:e.root,children:[s.jsx("div",{className:e.header,children:s.jsx(Rt,{children:"Solution Elements"})}),s.jsxs(ki,{className:e.tabs,selectedValue:t,onTabSelect:(h,y)=>n(y.value),size:"small",children:[s.jsxs(Ke,{value:"buttons",children:["Buttons (",b.length,")"]}),s.jsxs(Ke,{value:"commands",children:["Commands (",o.length,")"]}),s.jsxs(Ke,{value:"rules",children:["Rules (",r.length+i.length,")"]}),s.jsxs(Ke,{value:"templates",children:["Templates (",l.length,")"]})]}),s.jsxs("div",{className:e.scrollArea,children:[t==="buttons"&&s.jsxs(s.Fragment,{children:[s.jsx(P,{size:100,style:{color:m.colorNeutralForeground3,padding:`4px ${m.spacingHorizontalS}`,display:"block"},children:"Drag onto the ribbon canvas to add a button"}),b.map(({button:h,location:y,isNew:w})=>s.jsx(Ne,{content:`${h.id} · ${Qs[y]} ribbon`,relationship:"label",children:s.jsxs("div",{className:e.draggableItem,draggable:!0,onDragStart:I=>{I.dataTransfer.setData(sy,JSON.stringify({button:h})),I.dataTransfer.effectAllowed="copy"},title:"Drag onto a ribbon group to add this button",children:[s.jsx("span",{className:e.gripHandle,children:"⋮⋮"}),s.jsx(_t,{fontSize:14,style:{color:m.colorNeutralForeground3,flexShrink:0}}),s.jsx(P,{className:e.itemName,children:h.label||h.id}),s.jsx(ae,{size:"small",appearance:"outline",children:Qs[y]}),w&&s.jsx(ae,{size:"small",color:"brand",appearance:"tint",children:"NEW"})]})},`${y}::${h.id}`)),b.length===0&&s.jsxs(P,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:["No custom buttons yet. Add one from the ribbon canvas — in"," ",s.jsx("strong",{children:"Modern command bar"})," use the ",s.jsx("strong",{children:"+ Add"})," button at the end of the bar; in ",s.jsx("strong",{children:"Classic ribbon"})," use the ",s.jsx("strong",{children:"+"})," ","inside any group."]})]}),t==="commands"&&s.jsxs(s.Fragment,{children:[s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Ae,{}),onClick:v,style:{width:"100%",justifyContent:"flex-start",marginBottom:4},children:"New command"}),o.map(h=>s.jsxs("div",{className:e.item,onClick:()=>p(h.id),role:"button",tabIndex:0,onKeyDown:y=>y.key==="Enter"&&p(h.id),children:[s.jsx(Gt,{fontSize:14,style:{color:m.colorNeutralForeground3}}),s.jsx(P,{className:e.itemName,children:h.id}),s.jsxs(P,{size:100,style:{color:m.colorNeutralForeground3},children:[h.actions.length," action",h.actions.length!==1?"s":""]})]},h.id)),o.length===0&&s.jsx(P,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:"No commands yet"})]}),t==="rules"&&s.jsxs(s.Fragment,{children:[s.jsx(K,{appearance:"subtle",size:"small",icon:s.jsx(Ae,{}),onClick:x,style:{width:"100%",justifyContent:"flex-start",marginBottom:4},children:"New rule"}),r.map(h=>s.jsxs("div",{className:e.item,onClick:()=>f(h.id,"enable"),role:"button",tabIndex:0,onKeyDown:y=>y.key==="Enter"&&f(h.id,"enable"),children:[s.jsx(P,{className:e.itemName,children:h.id}),s.jsx(ae,{size:"small",color:"success",appearance:"tint",children:"Enable"})]},h.id)),i.map(h=>s.jsxs("div",{className:e.item,onClick:()=>f(h.id,"display"),role:"button",tabIndex:0,onKeyDown:y=>y.key==="Enter"&&f(h.id,"display"),children:[s.jsx(P,{className:e.itemName,children:h.id}),s.jsx(ae,{size:"small",color:"informative",appearance:"tint",children:"Display"})]},h.id)),r.length===0&&i.length===0&&s.jsx(P,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:"No rules yet"})]}),t==="templates"&&s.jsxs(s.Fragment,{children:[l.map(h=>s.jsxs("div",{className:e.item,children:[s.jsx(Pu,{fontSize:14,style:{color:m.colorNeutralForeground3}}),s.jsx(P,{className:e.itemName,children:h.id})]},h.id)),l.length===0&&s.jsx(P,{size:200,style:{color:m.colorNeutralForeground3,padding:8,display:"block"},children:"No templates defined"})]})]})]})}function ls(){return window.dataverseAPI}async function ly(){const e=ls();ie.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'&$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}});ie.getState().logInfo("dataverse",`Loaded ${i.length} solution(s).`);const r=i.filter(l=>!l.isManaged).slice(0,5);for(const l of r)ie.getState().logInfo("dataverse",` • "${l.friendlyName||l.uniqueName}" → prefix="${l.publisherPrefix||"(empty)"}" (publisher: ${l.publisherName||l.publisherUniqueName||"(empty)"})`);return i}async function cy(e){if(!e)return[];const t=ls();ie.getState().logInfo("dataverse",`Loading solution entity components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 1`,r=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return ie.getState().logInfo("dataverse",`Solution contains ${r.length} table component(s).`),r}async function dy(e){if(!e)return[];const t=ls();ie.getState().logInfo("dataverse",`Loading solution ribbon components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 50`,r=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return ie.getState().logInfo("dataverse",`Solution contains ${r.length} ribbon-customization component(s).`),r}function uy(){return window.dataverseAPI}async function my(e){if(e.length===0)return[];const t=uy(),n=ie.getState();n.logInfo("dataverse",`Loading metadata for ${e.length} solution entit${e.length===1?"y":"ies"}...`);const o="MetadataId,LogicalName,SchemaName,DisplayName,IsCustomEntity,IsIntersect",r=(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 ${r.length} table(s).`),r}async function wl(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);const o=Gf(n),i=Object.entries(o).find(([r])=>r.toLowerCase().endsWith("ribbonxml.xml"));if(!i){const r=Object.values(o)[0];if(r)return vn(r);throw new Error("decompressRibbonZip: no RibbonXml.xml entry found in ZIP")}return vn(i[1])}function Cl(){return window.dataverseAPI}async function py(){try{return(await Cl().queryData("organizations?$select=languagecode")).value?.[0]?.languagecode??1033}catch{return 1033}}const fy=[/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 hy(e){const t=e instanceof Error?`${e.message} ${String(e.code??"")}`:typeof e=="string"?e:JSON.stringify(e??"");return fy.some(n=>n.test(t))}const gy={0:"Import",1:"Uninstall",2:"Export",3:"Publish",4:"PublishAll",5:"LanguageProvision",6:"ImportTranslation",7:"RibbonMetadataGeneration",8:"WorkflowSetState",10:"ExportLite",11:"UpdatingMissingPackages"},Il=30;async function by(e=Il,t=Date.now()){const n=t-e*6e4;try{return((await Cl().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:gy[i.msdyn_operation??-1]??`operation ${i.msdyn_operation}`,name:i.msdyn_name??"",startedOn:i.msdyn_starttime??""}))}catch{return[]}}const Rl=e=>new Promise(t=>setTimeout(t,e)),er=e=>e.map(t=>t.name&&t.name!==t.operation?`${t.operation} (${t.name})`:t.operation).join(", ");async function zx(e={}){const t=e.sleep??Rl,n=e.now??Date.now,o=n()+(e.timeoutMs??10*6e4);for(;;){const i=await by(Il,n());if(i.length===0)return;if(n()>=o)throw new Error(`The environment is still busy (${er(i)} running). Try again when it has finished — Solutions › History shows its progress.`);e.onProgress?.(`Waiting for another operation to finish: ${er(i)}…`),await t(15e3)}}async function yy(e,t,n={}){const o=n.sleep??Rl,i=n.now??Date.now,r=i()+(n.timeoutMs??10*6e4);for(let l=0;;l++)try{return await t()}catch(a){if(!hy(a))throw a;const c=Math.min(6e4,15e3*2**l);if(i()+c>r)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 jl=30,xy=jl*6e4,$l=(e,t)=>`cbs:lastPublish:${e.replace(/\/+$/,"")}:${t}`;function Nl(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(r=>typeof r[1]=="number"&&t-r[1]<xy));return{at:o.at,publishedAt:i}}catch{return null}}function Bx(e,t,n,o=Date.now()){const i=$l(e,t),r={...Nl(i,o)?.publishedAt??{}};for(const l of n){const a=/^customActions:ca:(.+)$/.exec(l)?.[1];a&&(r[a]=o)}try{sessionStorage.setItem(i,JSON.stringify({at:o,publishedAt:r}))}catch{}}function vy(e,t,n=Date.now()){return Nl($l(e,t),n)}const tr=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]),Wo=new Set(["Tab","Group"]),nr=/^(.+)\._children$/;function or(e){return e?Array.from(e.children):[]}function Rn(e,t){return t?e.split("{!EntityLogicalName}").join(t):e}function Sy(e,t){const n=new Map,o=(i,r)=>n.set(Rn(i,t),r);for(const i of e)for(const r of i.tabs){o(`${r.id}.Groups`,r.id);for(const l of r.groups){o(`${l.id}.Controls`,r.id);for(const a of je(l))for(const c of a.menu?.sections??[])o(c.controlsId,r.id)}}return n}function wy(e,t){const n=new Set,o=i=>n.add(Rn(i,t));for(const i of e)for(const r of i.tabs){o(r.id);for(const l of r.groups){o(l.id);for(const a of je(l))o(a.id)}}return n}function ir(e){return[e,...Array.from(e.getElementsByTagName("*"))].flatMap(t=>t.getAttribute("Id")??[])}function Cy(e,t,n,o={}){const{locLabels:i=[],languageCode:r=1033}=o,l=[...t],a=R=>Rn(R,n),c=wy(l,n),d=Sy(l,n),u=[...co(e).map(R=>R.location),...o.otherHides??[]].map(a),p=new Set(u),f=new Set,b=[...e.customActions.values()].map(R=>new DOMParser().parseFromString(R,"application/xml").documentElement);for(const R of b)if(R.tagName==="CustomAction")for(const E of Array.from(R.getElementsByTagName("*")))p.has(a(E.getAttribute("Id")??""))&&ir(E).forEach(T=>f.add(a(T)));const v=R=>f.has(R)||u.some(E=>R===E||R.startsWith(`${E}.`)),x=new Set(["Mscrm.Tabs",`Mscrm.SubGrid.${n}.ContextualTabs`]),h=(R,E)=>{const T=d.get(E);return T&&xo(T)?{reason:"hidden-tab",why:`It is on the tab ${T}, which Unified Interface doesn't show; the ribbon doesn't return what is added there.`}:T||x.has(E)?{reason:"not-returned",why:R==="Tab"?`The ribbon doesn't return this tab at ${E}, so Command Bar Studio can't place it (it may still show in Unified Interface).`:`${E} 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(E)?`${E} isn't in this table's ribbon as loaded: it is not shown — possibly hidden by another solution — or it was removed.`:`${E} 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.`}},y=R=>{const E=R.getAttribute("LabelText")??R.getAttribute("Title")??R.getAttribute("Alt")??"";return ce(E,i,r)||(R.getAttribute("Id")??"")},w=[],I=(R,E,T)=>{const _=R.getAttribute("Id")??"",D=nr.exec(E)?.[1]??E;if(!_||c.has(a(_))||v(a(_))||v(a(D)))return;const L=Wo.has(R.tagName);w.push({orphan:{id:_,element:R.tagName,label:y(R),location:E,customActionId:T,...h(R.tagName,a(D)),deleteControlIds:L?[]:[_],deleteContainerIds:L?[_]:[]},parent:D,inside:new Set(ir(R))})};for(const R of b){if(R.tagName!=="CustomAction")continue;const E=R.getAttribute("Location")??"";if(!nr.test(E)||/\.Scaling\._children$/.test(E))continue;const T=or(or(R).find(L=>L.tagName==="CommandUIDefinition"))[0],_=T?.getAttribute("Id");if(!T||!_||!(Wo.has(T.tagName)||tr.has(T.tagName)))continue;const D=R.getAttribute("Id")??"";if(!c.has(a(_))){I(T,E,D);continue}for(const L of Array.from(T.getElementsByTagName("*"))){const j=L.parentElement;j?.tagName!=="Controls"&&j?.tagName!=="Groups"||!Wo.has(L.tagName)&&!tr.has(L.tagName)||I(L,`${j.getAttribute("Id")??""}._children`,D)}}const S=R=>w.find(E=>E!==R&&E.inside.has(R.parent)&&!R.inside.has(E.parent)),C=R=>{const E=new Set([R]);let T=R;for(let _=S(T);_&&!E.has(_);_=S(T))E.add(_),T=_;return T},$=w.filter(R=>!S(R));for(const R of w){const E=C(R);if(E===R||!$.includes(E))continue;const T=(_,D)=>D.forEach(L=>_.includes(L)||_.push(L));T(E.orphan.deleteControlIds,R.orphan.deleteControlIds),T(E.orphan.deleteContainerIds,R.orphan.deleteContainerIds)}return $.map(R=>R.orphan)}function Iy(e,t,n=Date.now()){if(!t)return e;const o=jl*6e4,i=r=>Math.max(0,Math.floor((n-r)/6e4));return e.map(r=>{const l=t.publishedAt[r.customActionId];if(l!==void 0&&n-l<o){const c=i(l);return{...r,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. ${r.why}`}}if(n-t.at>=o)return r;const a=i(t.at);return{...r,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. ${r.why}`}})}const Tl=window.dataverseAPI;function Mn(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 kl(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 Al(e){return kl(e)[0]}function Ry(e,t,n={}){const o={HomepageGrid:[],SubGrid:[],Form:[]};for(const r of e)r.id.startsWith("Mscrm.Form.")?o.Form.push(r):r.id.startsWith("Mscrm.SubGrid.")?o.SubGrid.push(r):r.id.startsWith("Mscrm.HomepageGrid.")?o.HomepageGrid.push(r):o[Al(r)??"HomepageGrid"].push(r);const i=r=>{const l=Object.fromEntries(o[r].filter(a=>n[a.id]).map(a=>[a.id,n[a.id]]));return{location:r,entityLogicalName:t,tabs:o[r],...Object.keys(l).length>0?{scalingByTab:l}:{}}};return{HomepageGrid:i("HomepageGrid"),SubGrid:i("SubGrid"),Form:i("Form")}}const jy="Microsoft.Dynamics.CRM.RibbonLocationFilters'All'";function $y(e){return`RetrieveEntityRibbon(EntityName=@e,RibbonLocationFilter=@f)?@e='${encodeURIComponent(e.replace(/'/g,"''"))}'&@f=${jy}`}async function Ny(e,t=[]){ie.getState().logInfo("dataverse",`RetrieveEntityRibbon(${e}, All)`);const n=await Tl.queryData($y(e)),o=await wl(n.CompressedEntityXml),i=yo(o,"HomepageGrid",e,t),r=Ry(i.ribbon.tabs,e,i.ribbon.scalingByTab);if(i.ribbon.templateLayouts)for(const l of Object.values(r))l.templateLayouts=i.ribbon.templateLayouts;return ie.getState().logInfo("dataverse",`RetrieveEntityRibbon succeeded for ${e} (Form=${r.Form.tabs.length}, HomepageGrid=${r.HomepageGrid.tabs.length}, SubGrid=${r.SubGrid.tabs.length})`),{ribbons:r,commands:i.commands,displayRules:i.displayRules,enableRules:i.enableRules,locLabels:i.locLabels}}async function Ty(e=[]){ie.getState().logInfo("dataverse","RetrieveApplicationRibbon()");const t=await Tl.execute({operationName:"RetrieveApplicationRibbon",operationType:"function"}),n=await wl(t.CompressedApplicationRibbonXml);return ie.getState().logInfo("dataverse","RetrieveApplicationRibbon succeeded"),yo(n,"Application","{!EntityLogicalName}",e)}function Go(e,t,n,o=[]){const i={added:[],replaced:[]};if(n.commandDefinitions.size+n.enableRules.size+n.displayRules.size===0)return i;const r=hf(n),l=(b,v)=>JSON.stringify(b,sr)===JSON.stringify(v,sr),a=(b,v)=>{const x=new Map(v.map(h=>[h.id,h]));for(let h=0;h<b.length;h++){const y=x.get(b[h].id);y&&!l(y,b[h])&&(b[h]=y,i.replaced.push(y.id))}};a(t.commands,r.commands),a(t.enableRules,r.enableRules),a(t.displayRules,r.displayRules);const c=new Set(t.commands.map(b=>b.id)),d=new Set(o.filter(b=>!c.has(b)&&n.commandDefinitions.has(b)));for(const b of e)for(const v of b.tabs)for(const x of v.groups)for(const h of je(x))h.commandId&&!c.has(h.commandId)&&n.commandDefinitions.has(h.commandId)&&d.add(h.commandId);const u=r.commands.filter(b=>d.has(b.id));t.commands.push(...u),i.added.push(...u.map(b=>b.id));const p=new Set(t.enableRules.map(b=>b.id)),f=new Set(t.displayRules.map(b=>b.id));for(const b of t.commands){for(const v of b.enableRules){const x=r.enableRules.find(h=>h.id===v);x&&!p.has(v)&&(t.enableRules.push(x),p.add(v),i.added.push(v))}for(const v of b.displayRules){const x=r.displayRules.find(h=>h.id===v);x&&!f.has(v)&&(t.displayRules.push(x),f.add(v),i.added.push(v))}}return i}function sr(e,t){if(typeof t!="string"||!t.trimStart().startsWith("<"))return t;try{return Ht(t)}catch{return t}}function ky(e,t){const n=(o,i)=>new Map([...o].filter(([r])=>!i?.has(r)));return{...e,commandDefinitions:n(e.commandDefinitions,t?.commandDefinitions),enableRules:n(e.enableRules,t?.enableRules),displayRules:n(e.displayRules,t?.displayRules)}}function Ay(e,t,n){if(n!==1033)for(const o of e)for(const i of o.tabs)for(const r of i.groups)for(const l of je(r)){for(const d of l.menu?.sections??[]){const u=d.attributes?.Title;u?.startsWith("$LocLabels:")&&(d.title=ce(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]=ce(d,t,n))}}function rr(e,t,n,o){const i=new Set(Object.values(e).flatMap(f=>f?.tabs.map(b=>b.id)??[])),r=new Set(co(t).map(f=>f.location)),l=n?`Mscrm.SubGrid.${n}.ContextualTabs._children`:null,a=[];for(const f of Zr(t.customActions).values()){const b=new DOMParser().parseFromString(f,"application/xml").documentElement;if(b.tagName!=="CustomAction")continue;const v=Rn(b.getAttribute("Location")??"",n??void 0);if(v!=="Mscrm.Tabs._children"&&v!==l)continue;const x=Array.from(b.getElementsByTagName("CommandUIDefinition")[0]?.children??[])[0],h=x?.tagName==="Tab"?x.getAttribute("Id"):null;!h||i.has(Rn(h,n??void 0))||a.push({xml:new XMLSerializer().serializeToString(x),subGrid:v===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=yo(c,n?"HomepageGrid":"Application",n??"{!EntityLogicalName}",o);d.ribbon.tabs=d.ribbon.tabs.filter(f=>!r.has(f.id));for(const f of d.ribbon.tabs){f.groups=f.groups.filter(b=>!r.has(b.id));for(const b of f.groups){b.buttons=b.buttons.filter(v=>!r.has(v.id));for(const v of je(b))r.has(v.id)&&ia(b,v.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":Al(f)??"HomepageGrid":"Application";for(const f of d.ribbon.tabs){const b=n&&!u.has(f.id)?kl(f).slice(1):[];b.length>0&&ie.getState().logWarn("ribbon",`Tab ${f.id} shows on the ${p(f)} and on the ${b.join(" and ")} (its display rules); Command Bar Studio lists it under ${p(f)} only.`);const v=e[p(f)];if(!v)continue;v.tabs.push(f),v.tabs.sort((h,y)=>h.sequence-y.sequence);const x=d.ribbon.scalingByTab?.[f.id];x&&(v.scalingByTab={...v.scalingByTab??{},[f.id]:x})}return d.ribbon.tabs.map(f=>f.id)}function Uo(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);ie.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 Dy(e){const t=ie.getState(),[n,o,i]=await Promise.all([ui(e).catch(()=>null),ui(null).catch(()=>null),py()]),r=n?mi(n):[],l=o?mi(o):[],[a,c]=await Promise.all([Ny(e,[...r,...l]),Ty(l)]);if(n){const p=rr(a.ribbons,n,e,[...r,...l]);p.length>0&&t.logInfo("ribbon",`Loaded tab(s) ${p.join(", ")} from the table's unmanaged layer.`);const f=Xn(n);for(const b of Object.values(a.ribbons))vs(b,f);Uo("RetrieveEntityRibbon",Go(Object.values(a.ribbons),a,n,[ze]))}o&&(rr({Application:c.ribbon},o,null,l),vs(c.ribbon,Xn(o)),Uo("RetrieveApplicationRibbon",Go([c.ribbon],c,o)),Uo("RetrieveEntityRibbon",Go(Object.values(a.ribbons),a,ky(o,n))));const d=Mn([...a.locLabels,...c.locLabels]);Ay([...Object.values(a.ribbons),c.ribbon],d,i);const u=n?Cy(n,Object.values(a.ribbons),e,{locLabels:d,languageCode:i,otherHides:o?co(o).map(p=>p.location):[]}):[];return u.length>0&&t.logWarn("ribbon",`${u.length} element(s) of the table's unmanaged customizations aren't on the canvas — the ribbon doesn't return them (see "Orphaned customizations"): ${u.map(p=>`${p.id} at ${p.location}`).join(", ")}.`),{ribbons:{HomepageGrid:a.ribbons.HomepageGrid,SubGrid:a.ribbons.SubGrid,Form:a.ribbons.Form,Application:c.ribbon},commands:Mn([...a.commands,...c.commands]),displayRules:Mn([...a.displayRules,...c.displayRules]),enableRules:Mn([...a.enableRules,...c.enableRules]),locLabels:d,layers:{entity:n?Zn(n):null,application:o?Zn(o):null},baseLanguageCode:i,orphans:u}}const ar=window.dataverseAPI,lr="Active";function Ey(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 r=o.querySelector("CommandUIDefinition")?.firstElementChild?.getAttribute("Id");r&&n.add(r)}),[...n]}catch{return[]}}async function Oy(e){const t=ie.getState(),n=new Map;if(!e||e==="{!EntityLogicalName}")return n;try{const o=e.replace(/'/g,"''"),r=((await ar.queryData(`ribboncustomizations?$select=ribboncustomizationid&$filter=entity eq '${o}'`)).value??[]).map(c=>c.ribboncustomizationid).filter(c=>!!c);if(r.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 r){const u=(await ar.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||"",b=Ey(f),v=(p.msdyn_solutionname??"")===lr;for(const x of b)v?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:lr});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 zy(){return window.dataverseAPI}async function By(){const e=zy();ie.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 ie.getState().logWarn("dataverse","WhoAmI returned no user id."),{id:"",name:""};const i=(await e.retrieve("systemuser",n,["fullname"])).fullname?.trim(),r={id:n,name:i&&i.length>0?i:"Current User"};return ie.getState().logInfo("dataverse",`Current user resolved: ${r.name}.`),r}function My(){M.useEffect(()=>{const e=ih();return e>0&&ie.getState().logInfo("ribbon",`Discarded ${e} unsaved-changes draft(s) older than ${Ma} days, or saved by an earlier version of Command Bar Studio (they can't be restored correctly).`),rh()},[])}function Ly(){const e=ye(n=>n.saveFailed),t=ye(n=>n.lastSavedAt);return e?s.jsx(Ce,{intent:"error",layout:"multiline",style:{position:"absolute",top:0,left:0,right:0,zIndex:1e3},children:s.jsxs(Ie,{children:["Your latest changes can't be saved as a draft: the browser storage is full."," ",t?s.jsxs(s.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."]}):s.jsx(s.Fragment,{children:"Publish them, or they are lost when Command Bar Studio closes."})]})}):null}function Py(){const e=ne(i=>i.connectionNotice),t=ne(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 s.jsxs(Ce,{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:[s.jsxs(Ie,{children:[s.jsxs(gm,{children:["Connection changed to ",o]}),"The solution and table loaded from ",n," were closed; pick a solution to continue in ",o,"."," ",e.draftKept&&s.jsxs(s.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&&s.jsx(s.Fragment,{children:"Your unpublished changes couldn't be saved as a draft (the browser storage is full) and are lost."})]}),s.jsx(hn,{containerAction:s.jsx(K,{"aria-label":"Dismiss",appearance:"transparent",icon:s.jsx(ro,{}),onClick:t})})]})}function Fy(){const e=ye(r=>r.pending),t=ye(r=>r.pendingBaselineChanged),n=ye(r=>r.restoreError),o=ye(r=>r.restoreDraft),i=ye(r=>r.discardDraft);return e?s.jsx(Ut,{open:!0,modalType:"alert",children:s.jsx(Xt,{style:{maxWidth:"520px"},children:s.jsxs(Kt,{children:[s.jsx(Vt,{children:"Unpublished changes"}),s.jsxs(Jt,{children:[s.jsxs(P,{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&&s.jsx(Ce,{intent:"warning",layout:"multiline",style:{marginTop:"12px"},children:s.jsx(Ie,{children:"The table's ribbon has changed since then (published from another session, or by someone else): review the publish plan before publishing."})}),n&&s.jsx(Ce,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:s.jsxs(Ie,{children:["These changes couldn't be restored (",n,"). Discard them to continue; the details are in the runtime log."]})})]}),s.jsxs(Yt,{children:[s.jsx(K,{appearance:"secondary",onClick:i,children:"Discard"}),s.jsx(K,{appearance:"primary",disabled:!!n,onClick:()=>o(),children:"Restore"})]})]})})}):null}function _y(){const e=ye(d=>d.pendingSwitch),t=ye(d=>d.pending!==null),n=ye(d=>d.saveFailed),o=ye(d=>d.resolveSwitch),i=ne(d=>d.activeEntity),r=ne(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=r?.friendlyName||r?.uniqueName||"this solution";return s.jsx(Ut,{open:!0,modalType:"alert",onOpenChange:(d,u)=>!u.open&&o("cancel"),children:s.jsx(Xt,{style:{maxWidth:"520px"},children:s.jsxs(Kt,{children:[s.jsx(Vt,{children:"Unpublished changes"}),s.jsxs(Jt,{children:[s.jsxs(P,{block:!0,children:[l," has changes that aren't published. Switch to ",a,"?"]}),s.jsx(P,{block:!0,style:{marginTop:"8px"},children:t?s.jsxs(s.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."]}):s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"Keep as draft"})," saves them on this computer: they are offered again when you open ",l," ","in ",c,". ",s.jsx("strong",{children:"Discard"})," deletes them."]})}),n&&!t&&s.jsx(Ce,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:s.jsx(Ie,{children:"The changes can't be saved as a draft: the browser storage is full. Publish them first, or discard them to switch."})})]}),s.jsxs(Yt,{children:[s.jsx(K,{appearance:"secondary",onClick:()=>o("cancel"),children:"Cancel"}),s.jsxs(K,{appearance:"secondary",onClick:()=>o("discard"),children:["Discard",t?" and switch":""]}),!t&&s.jsx(K,{appearance:"primary",disabled:n,onClick:()=>o("keep"),children:"Keep as draft"})]})]})})})}const qy=le({leftPaneTabs:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},tabList:{flexShrink:0,borderBottom:`1px solid ${m.colorNeutralStroke2}`},tabContent:{flex:1,overflow:"hidden"}});function Hy(){const e=qy(),[t,n]=M.useState("tables");return s.jsxs("div",{className:e.leftPaneTabs,children:[s.jsxs(ki,{className:e.tabList,selectedValue:t,onTabSelect:(o,i)=>n(i.value),size:"small",children:[s.jsx(Ke,{value:"tables",children:"Tables"}),s.jsx(Ke,{value:"elements",children:"Solution"})]}),s.jsx("div",{className:e.tabContent,children:t==="tables"?s.jsx(oy,{}):s.jsx(ay,{})})]})}function Wy(){const e=ne(C=>C.setSolutions),t=ne(C=>C.setEntities),n=ne(C=>C.setCurrentUser),o=ne(C=>C.setSolutionEntityIds),i=ne(C=>C.setSolutionRibbonComponentIds),r=ne(C=>C.activeSolution),l=ne(C=>C.activeEntity),a=ne(C=>C.connectionVersion),c=O(C=>C.loadWorkspace),d=Z(C=>C.setTabId),u=Y(C=>C.themeMode),p=ie(C=>C.logInfo),f=ie(C=>C.logWarn),b=ie(C=>C.logError);My(),Tg();const[v,x]=M.useState("idle"),[h,y]=M.useState(null),[w,I]=M.useState(0);M.useEffect(()=>{p("runtime","Loading solutions and current user...");let C=!1;return ly().then($=>{C||(e($),p("runtime",`Loaded ${$.length} solution(s). Pick one to load its tables.`))}).catch($=>{C||b("runtime",`Failed to load solutions: ${$ instanceof Error?$.message:String($)}`)}),By().then($=>{C||!$.id||(n($.id,$.name),p("runtime",`Current user: ${$.name}.`))}).catch($=>{f("runtime",`Failed to resolve current user: ${$ instanceof Error?$.message:String($)}`)}),()=>{C=!0}},[e,n,p,f,b,a]),M.useEffect(()=>{if(!r){o(null),i(null),t([]);return}let C=!1;return(async()=>{try{const[$,R]=await Promise.all([cy(r.id),dy(r.id)]);if(C)return;if(o($),i(R),$.length===0){t([]);return}const E=await my($);if(C)return;t(E)}catch($){if(C)return;b("runtime",`Failed to load solution tables: ${$ instanceof Error?$.message:String($)}`),o([]),i([]),t([])}})(),()=>{C=!0}},[r,t,o,i,b]),M.useEffect(()=>{if(ye.getState().beginLoad(),!l?.logicalName){x("idle"),y(null);return}let C=!1;const $=ah(l.logicalName);return x("loading"),y(null),p("ribbon",`Loading ribbon workspace for ${l.logicalName}...`),Promise.all([Dy(l.logicalName),Oy(l.logicalName).catch(()=>new Map)]).then(([R,E])=>{if(C)return;Zp(R.ribbons,E);const T=[],_=new Set;for(const N of Object.values(R.ribbons))for(const W of N.tabs)for(const U of W.groups)for(const X of je(U))X.origin==="managed"&&!_.has(X.id)&&(_.add(X.id),T.push({elementId:X.id,elementKind:"button",solutions:[{solutionId:"",solutionName:X.solutionName??"Managed Solution",publisher:X.publisherName??"",managed:!0,wins:!0,importedOn:void 0}]}));O.getState().setConflicts(T),c({ribbons:R.ribbons,commands:R.commands,displayRules:R.displayRules,enableRules:R.enableRules,locLabels:R.locLabels,layers:R.layers,baseLanguageCode:R.baseLanguageCode,orphans:{entity:Iy(R.orphans??[],vy(ne.getState().connectionUrl,l.logicalName))}});const{location:D,tabId:L}=Z.getState(),j=R.ribbons[D]?.tabs??[];if(!(j.some(N=>N.id===L)&&!xo(L))){const N=pn(j);N&&d(N)}ye.getState().workspaceLoaded($),x("idle"),p("ribbon",`Ribbon workspace loaded for ${l.logicalName}.`)}).catch(R=>{if(C)return;const E=R instanceof Error?R.message:"Failed to load ribbon";x("error"),y(E),b("ribbon",`Ribbon load failed for ${l.logicalName}: ${E}`)}),()=>{C=!0}},[l?.logicalName,c,w,d,p,b]);function S(){I(C=>C+1)}return s.jsxs(bm,{theme:u==="dark"?ym:xm,children:[s.jsxs(Ph,{leftPane:s.jsx(Hy,{}),rightPane:s.jsx(ey,{}),bottomPanel:s.jsx(ty,{}),children:[s.jsx(Ly,{}),s.jsx(Py,{}),s.jsx(Ib,{isLoadingRibbon:v==="loading",ribbonLoadError:h,onRetryRibbonLoad:S})]}),s.jsx(Fy,{}),s.jsx(_y,{})]})}const Gy=5e3,cr=3e4,Dl="1.2.7";function dr(e,t,n){let o;return Promise.race([e,new Promise((i,r)=>{o=setTimeout(()=>r(new Error(n)),t)})]).finally(()=>clearTimeout(o))}async function Uy(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 ${Dl} or later.`);const i=[];let r="light";try{const a=t.utils?.getCurrentTheme;if(typeof a!="function")throw new Error("the host has no theme API");r=await dr(a(),Gy,"the host didn't answer")==="dark"?"dark":"light"}catch(a){i.push(`Couldn't read the host theme (${Ol(a)}); using the light theme.`)}const l=await dr(o(),cr,`Power Platform ToolBox didn't return the active connection within ${cr/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:r,warnings:i}}function El(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},r=i("div");r.setAttribute("role","alert"),r.style.cssText="font-family: 'Segoe UI', system-ui, sans-serif; padding: 24px; max-width: 720px; line-height: 1.5;",r.append(i("h1",n));const l=i("p",Ol(t));l.style.fontWeight="600",r.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 ${Dl} 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));r.append(a),e.replaceChildren(r)}function Ol(e){return e instanceof Error?e.message:String(e)}class Xy extends M.Component{state={error:void 0};box=M.createRef();static getDerivedStateFromError(t){return{error:t??new Error("Unknown error")}}componentDidCatch(t,n){console.error("[CBS RootErrorBoundary]",t,n),ie.getState().logError("app",t instanceof Error?t.message:String(t))}componentDidMount(){this.componentDidUpdate()}componentDidUpdate(){this.state.error!==void 0&&this.box.current&&El(this.box.current,this.state.error,"Command Bar Studio stopped working")}render(){return this.state.error===void 0?this.props.children:s.jsx("div",{ref:this.box})}}function Nt(){const e=window.dataverseAPI;if(!e)throw new Error("dataverseAPI is not available in the current runtime");return e}const zl={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 Bl(e){return zl[e]??"xml"}async function Vy(e,t){let n="webresourceset?$select=webresourceid,name,displayname,description,webresourcetype,modifiedon,ismanaged&$orderby=name asc";if(t!==void 0){const i=Object.entries(zl).find(([,r])=>r===t)?.[0];i&&(n+=`&$filter=webresourcetype eq ${i}`)}return(await e.queryData(n)).value.map(i=>{const r=i;return{id:String(r.webresourceid??""),name:String(r.name??""),displayName:r.displayname?String(r.displayname):void 0,description:r.description?String(r.description):void 0,webResourceType:Bl(Number(r.webresourcetype??3)),modifiedOn:r.modifiedon?String(r.modifiedon):void 0,isCustom:r.ismanaged===!1}})}async function Ky(e,t){const n=await e.retrieve("webresource",t,["content"]);return n.content?String(n.content):""}const Ml=61;async function Ll(e,t,n,o=lo){await o("Adding the web resource to the solution"),await e.execute({operationName:"AddSolutionComponent",operationType:"action",parameters:{ComponentId:t,ComponentType:Ml,SolutionUniqueName:n,AddRequiredComponents:!1}})}class Jy extends Error{constructor(t){super(`Web resource ${t} already exists; it was left as it is.`),this.name="WebResourceSaveCancelled"}}async function Yy(e,t,n,o,i={}){const r=i.guard??Fm(),{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 b=u.value[0],v=String(b.webresourceid??"");if(!d&&c){const x=b.ismanaged===!0,h=await c({id:v,name:t,managed:x});if(h==="cancel")throw new Jy(t);if(h==="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=h==="keep"}d||(await r("Saving the web resource"),await e.update("webresource",v,p)),f={id:v,created:!1,updated:!d}}else{await r("Saving the web resource");const b=await e.create("webresource",p);f={id:String(b.id??""),created:!0,updated:!1}}if(a&&f.id){try{await Ll(e,f.id,a,r)}catch(b){throw new Error(`Web resource ${t} was saved but could not be added to solution ${a}: ${b instanceof Error?b.message:String(b)}`)}f.solutionUniqueName=a}return f}const ur=40,mr=(e,t)=>Array.from({length:Math.ceil(e.length/t)},(n,o)=>e.slice(o*t,(o+1)*t)),Zy=e=>`'${e.replace(/'/g,"''").replace(/[^A-Za-z0-9/._\-'~]/gu,t=>encodeURIComponent(t))}'`,pr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Qy(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),r={};for(const c of i)r[c.toLowerCase()]={exists:!1,inSolution:!1};if(i.length===0)return r;const l=new Map;for(const c of mr(i,ur)){const d=c.map(p=>`name eq ${Zy(p)}`).join(" or "),u=await e.queryData(`webresourceset?$select=webresourceid,name,ismanaged&$filter=${d}`);for(const p of u.value??[]){const f=p,b=String(f.name??"").toLowerCase();if(!(b in r))continue;r[b]={exists:!0,inSolution:!1,managed:f.ismanaged===!0};const v=String(f.webresourceid??"").toLowerCase();pr.test(v)&&l.set(v,b)}}const a=n?.replace(/[{}]/g,"");if(a&&pr.test(a)&&l.size>0)for(const c of mr([...l.keys()],ur)){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 ${Ml} and (${d})`);for(const p of u.value??[]){const f=l.get(String(p.objectid??"").toLowerCase());f&&(r[f].inSolution=!0)}}return r}async function Mx(e,t){return Qy(Nt(),e,t)}async function Lx(e){return Vy(Nt(),e)}async function Px(e){return Ky(Nt(),e)}async function ex(e){const t=Nt(),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:Bl(Number(i.webresourcetype??3)),isCustom:i.ismanaged===!1}}async function tx(e,t,n,o={}){const i=ne.getState().activeSolution,r=o.solutionUniqueName??(i&&!i.isManaged?i.uniqueName:void 0),l=await Yy(Nt(),e,t,n,{...o,solutionUniqueName:r});if(!r){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.`,ie.getState().logWarn("webresource",l.solutionWarning)}return l}async function Fx(e,t,n=lo){const o=t??await ex(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 ie.getState().logWarn("webresource",l),{solutionWarning:l}}const r=ne.getState().activeSolution;if(!r||r.isManaged){const l=r?`the active solution ${r.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 ie.getState().logWarn("webresource",a),{solutionWarning:a}}return await Ll(Nt(),i,r.uniqueName,n),{solutionUniqueName:r.uniqueName}}async function nx(e,t=lo){const n=Nt(),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 ox(e){return e.replace(/([A-Z])/g,(t,n,o)=>(o>0?"_":"")+t.toLowerCase())}function ix(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 Pl(e,t="regular"){return`${ox(e)}${t==="filled"?".filled":""}.svg`}function sx(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/${Pl(t,n)}`}const rx=11,ax=2*6e4,fr={save:tx,publish:nx},Fl=new Set;function lx(){Fl.clear()}async function _x(e,t,n,o,i={}){const r=i.save??fr.save,l=i.publish??fr.publish,a=i.published??Fl,c=sx(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 r(c,ix(d),rx,{displayName:`${Pl(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 yy(`Publishing icon web resource ${c}`,()=>l(u.id,i.guard),{timeoutMs:ax,...i.busy}),a.add(u.id)}catch(f){p.publishError=f instanceof Error?f.message:String(f)}return p}const cx=["commandEditorOpen","ruleEditorOpen","xmlDrawerOpen","iconPickerOpen","localizationEditorOpen","newGroupOpen","importXmlOpen","conflictDrawerOpen","webResourceBrowserOpen","urlComposerOpen","diffViewerOpen","tabDisplayRulesOpen","scalingEditorOpen","newTabOpen"];function dx(e){if(!e)return"none";const t=ne.getState(),n=ie.getState();if(Wn(e)===Wn({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})`,r=`${e.name} (${e.environment})`,{hadChanges:l,kept:a}=ye.getState().releaseForConnectionChange();O.getState().resetWorkspace(),Z.getState().clearSelection(),fe.getState().reset(),lx(),kg(),$i.clear(),t.switchConnection(e,{draftKept:l&&a,draftLost:l&&!a});try{Y.setState(Object.fromEntries(cx.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 ${r}. 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 ux(){const e=ie.getState().logInfo,t=window,n=t.toolboxAPI,{connection:o,theme:i,warnings:r}=await Uy({toolboxAPI:n,dataverseAPI:t.dataverseAPI});e("startup","Connected to PPTB host runtime.");for(const f of r)ie.getState().logWarn("startup",f);e("startup",`Host theme loaded: ${i}.`);const{setConnection:l}=ne.getState(),{setThemeMode:a}=Y.getState(),c=await Ai().catch(()=>null)??o;l(c.url,c.name,c.environment,c.id),a(i),e("startup",`Connected to ${c.name} (${c.environment}).`),Pm(f=>dx(f));const d=()=>{n.utils.getCurrentTheme().then(f=>{Y.getState().setThemeMode(f==="dark"?"dark":"light")}).catch(f=>{ie.getState().logWarn("startup",`Theme refresh failed: ${f instanceof Error?f.message:String(f)}`)})};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&d()}),n.events?.on((f,b)=>{b?.event==="settings:updated"&&d()});const u=document.getElementById("root");if(!u)throw new Error("No #root element found");Om.createRoot(u).render(s.jsx(M.StrictMode,{children:s.jsx(Xy,{children:s.jsx(Wy,{})})}))}ux().catch(e=>{ie.getState().logError("startup",e instanceof Error?e.message:String(e)),console.error(e);const t=document.getElementById("root")??document.body;El(t,e)});export{Dx as $,Hr as A,Sx as B,Db as C,wx as D,ch as E,Oi as F,Cx as G,yx as H,vx as I,bx as J,Sy as K,re as L,ie as M,py as N,zx as O,Rx as P,Tx as Q,to as R,np as S,yy as T,hy as U,xx as V,ne as W,Ai as X,Wa as Y,kx as Z,Ax as _,Y as a,Mx as a0,Bx as a1,$x as a2,ze as a3,Ca as a4,na as a5,xs as a6,xo as a7,Z as a8,Sa as a9,nn as aa,Is as ab,Nx as ac,Ua as ad,yo as ae,Ze as af,Fr as ag,ii as ah,Jn as ai,ce as aj,ye as ak,Qt as al,bp as am,$t as an,ox as ao,sx as ap,Jy as aq,_x as ar,Ox as as,Fx as at,ss as au,rs as av,In as aw,is as ax,Zi as ay,jx as az,Xa as b,je as c,yn as d,ex as e,Px as f,Ix as g,Fm as h,Ex as i,Zt as j,Jp as k,Lx as l,Di as m,Up as n,Vp as o,gx as p,Xp as q,ra as r,tx as s,ui as t,O as u,Xn as v,$i as w,Qr as x,ea as y,Ei as z};
|