@mohsinonxrm/pptb-commandbar-studio 0.9.0-beta.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +179 -0
- package/README.md +11 -13
- package/SECURITY.md +4 -4
- package/dist/assets/BulkPublishModal-BWRed6Fv.js +36 -0
- package/dist/assets/CommandEditorPanel-B7W3Sqiu.js +1 -0
- package/dist/assets/CommandPalette-Fc4MPKvd.js +1 -0
- package/dist/assets/CompareView-D1FOwnU1.js +7 -0
- package/dist/assets/CrmParameterEditor-DO6Rt764.js +1 -0
- package/dist/assets/EditorDrawer-BtFb9OzQ.js +2 -0
- package/dist/assets/HideInsteadOfDeleteModal-fdtkLfSG.js +1 -0
- package/dist/assets/IconPickerModal-FyQ9ud3R.js +1 -0
- package/dist/assets/ImportXmlModal-BZq0Iglk.js +1 -0
- package/dist/assets/MonacoEditor-CEYP9b6u.js +2 -0
- package/dist/assets/NewButtonModal-5nQ-f2by.js +1 -0
- package/dist/assets/NewGroupModal-vEuxSpnD.js +1 -0
- package/dist/assets/NewTabModal-DNzMru8E.js +1 -0
- package/dist/assets/RuleEditorPanel-B0u4b6vi.js +1 -0
- package/dist/assets/ScriptView-Ct4i8Jja.js +1 -0
- package/dist/assets/TabDisplayRulesPanel-HMmGkIxe.js +1 -0
- package/dist/assets/TranslationsView-DT4Ce3_W.js +1 -0
- package/dist/assets/WebResourceBrowser-L3R7UTNR.js +1 -0
- package/dist/assets/XmlView-CyLtgYex.js +2 -0
- package/dist/assets/{dnd-C1w9VFfC.js → dnd-iy5K5XAJ.js} +2 -2
- package/dist/assets/fluent-ui-CQyNN9H3.js +59 -0
- package/dist/assets/index-D7TexD30.js +136 -0
- package/dist/assets/monaco-DQA8g3bM.css +1 -0
- package/dist/assets/monaco-cQE5XS3B.js +1010 -0
- package/dist/assets/monacoSetup-BIq1zGyP.js +1 -0
- package/dist/assets/preload-helper-PPVm8Dsz.js +1 -0
- package/dist/assets/{server.browser-xEJRzS2D.js → server.browser-DTeSoizu.js} +1 -1
- package/dist/assets/useReplaceWebResourceConfirm-BdTw98QF.js +1 -0
- package/dist/assets/useStableKeys-49o4VnxU.js +1 -0
- package/dist/assets/{xmlValidator-PbODaIQV.js → xmlValidator-xIq-x9Ub.js} +2 -2
- package/dist/icons/icon.svg +4 -7
- package/dist/index.html +4 -6
- package/package.json +3 -1
- package/dist/assets/BulkPublishModal-DzDZJg0U.js +0 -36
- package/dist/assets/CommandEditorPanel-DsCP9yG4.js +0 -1
- package/dist/assets/CommandPalette-ID3kRJ9l.js +0 -1
- package/dist/assets/CompareView-DGsrcdoN.js +0 -7
- package/dist/assets/CrmParameterEditor-C22QGWff.js +0 -1
- package/dist/assets/EditorDrawer-CvCe9WeO.js +0 -2
- package/dist/assets/HideInsteadOfDeleteModal-3j9g-E9l.js +0 -1
- package/dist/assets/IconPickerModal-BLoDLbLR.js +0 -1
- package/dist/assets/ImportXmlModal-BD-L1QzJ.js +0 -1
- package/dist/assets/MonacoEditor-BMKRZv-g.js +0 -2
- package/dist/assets/NewButtonModal-COYXwEyk.js +0 -1
- package/dist/assets/NewGroupModal-boP_t1fI.js +0 -1
- package/dist/assets/NewTabModal-BI4afbC5.js +0 -1
- package/dist/assets/RuleEditorPanel-l8QnRFj6.js +0 -1
- package/dist/assets/ScriptView-BVyCmRvD.js +0 -1
- package/dist/assets/TabDisplayRulesPanel-gORq6MO7.js +0 -1
- package/dist/assets/TranslationsView-DubBATog.js +0 -1
- package/dist/assets/WebResourceBrowser-BATScmTw.js +0 -1
- package/dist/assets/XmlView-Bn4KlTw3.js +0 -2
- package/dist/assets/abap-DLDM7-KI.js +0 -1
- package/dist/assets/apex-DNDY2TF8.js +0 -1
- package/dist/assets/azcli-Y6nb8tq_.js +0 -1
- package/dist/assets/bat-BwHxbl9M.js +0 -1
- package/dist/assets/bicep-CFznDFnq.js +0 -2
- package/dist/assets/cameligo-Bf6VGUru.js +0 -1
- package/dist/assets/clojure-Dnu-v4kV.js +0 -1
- package/dist/assets/coffee-Bd8akH9Z.js +0 -1
- package/dist/assets/cpp-BbWJElDN.js +0 -1
- package/dist/assets/csharp-Co3qMtFm.js +0 -1
- package/dist/assets/csp-D-4FJmMZ.js +0 -1
- package/dist/assets/css-DdJfP1eB.js +0 -3
- package/dist/assets/css.worker-C_6RgliQ.js +0 -97
- package/dist/assets/cssMode-yNaVDuBb.js +0 -1
- package/dist/assets/cypher-cTPe9QuQ.js +0 -1
- package/dist/assets/dart-BOtBlQCF.js +0 -1
- package/dist/assets/dockerfile-BG73LgW2.js +0 -1
- package/dist/assets/ecl-BEgZUVRK.js +0 -1
- package/dist/assets/elixir-BkW5O-1t.js +0 -1
- package/dist/assets/flow9-BeJ5waoc.js +0 -1
- package/dist/assets/fluent-icons-CQEhzzaC.js +0 -1
- package/dist/assets/fluent-ui-BEjALNLO.js +0 -59
- package/dist/assets/freemarker2-CzWSO7cF.js +0 -3
- package/dist/assets/fsharp-PahG7c26.js +0 -1
- package/dist/assets/go-acbASCJo.js +0 -1
- package/dist/assets/graphql-BxJiqAUM.js +0 -1
- package/dist/assets/handlebars-BpG2O9CH.js +0 -1
- package/dist/assets/hcl-DtV1sZF8.js +0 -1
- package/dist/assets/html-Bm7ESfBq.js +0 -1
- package/dist/assets/html.worker-CLyYFd_g.js +0 -474
- package/dist/assets/htmlMode--CmpAV7s.js +0 -1
- package/dist/assets/index-6so8O90C.js +0 -136
- package/dist/assets/ini-Kd9XrMLS.js +0 -1
- package/dist/assets/java-CXBNlu9o.js +0 -1
- package/dist/assets/javascript-DYy3TIq5.js +0 -1
- package/dist/assets/json.worker-BggoxaER.js +0 -62
- package/dist/assets/jsonMode-DwsyQ3o1.js +0 -7
- package/dist/assets/julia-cl7-CwDS.js +0 -1
- package/dist/assets/kotlin-s7OhZKlX.js +0 -1
- package/dist/assets/less-9HpZscsL.js +0 -2
- package/dist/assets/lexon-OrD6JF1K.js +0 -1
- package/dist/assets/liquid-qkuWCPaY.js +0 -1
- package/dist/assets/lspLanguageFeatures-Cgd9CNvq.js +0 -4
- package/dist/assets/lua-Cyyb5UIc.js +0 -1
- package/dist/assets/m3-B8OfTtLu.js +0 -1
- package/dist/assets/markdown-BFxVWTOG.js +0 -1
- package/dist/assets/mdx-CtHfOclF.js +0 -1
- package/dist/assets/mips-CiqrrVzr.js +0 -1
- package/dist/assets/monaco-BIO15LCS.js +0 -1005
- package/dist/assets/monaco-DdLsZAcA.css +0 -1
- package/dist/assets/msdax-DmeGPVcC.js +0 -1
- package/dist/assets/mysql-C_tMU-Nz.js +0 -1
- package/dist/assets/objective-c-BDtDVThU.js +0 -1
- package/dist/assets/pascal-vHIfCaH5.js +0 -1
- package/dist/assets/pascaligo-DtZ0uQbO.js +0 -1
- package/dist/assets/perl-Ub6l9XKa.js +0 -1
- package/dist/assets/pgsql-BlNEE0v7.js +0 -1
- package/dist/assets/php-BBUBE1dy.js +0 -1
- package/dist/assets/pla-DSh2-awV.js +0 -1
- package/dist/assets/postiats-CocnycG-.js +0 -1
- package/dist/assets/powerquery-tScXyioY.js +0 -1
- package/dist/assets/powershell-COWaemsV.js +0 -1
- package/dist/assets/protobuf-Brw8urJB.js +0 -2
- package/dist/assets/pug-8SOpv6rk.js +0 -1
- package/dist/assets/python-CazlH6B-.js +0 -1
- package/dist/assets/qsharp-Bw9ernYp.js +0 -1
- package/dist/assets/r-j7ic8hl3.js +0 -1
- package/dist/assets/razor-BfGfB6aB.js +0 -1
- package/dist/assets/redis-Bu5POkcn.js +0 -1
- package/dist/assets/redshift-Bs9aos_-.js +0 -1
- package/dist/assets/restructuredtext-CqXO7rUv.js +0 -1
- package/dist/assets/ruby-zBfavPgS.js +0 -1
- package/dist/assets/rust-BzKRNQWT.js +0 -1
- package/dist/assets/sb-BBc9UKZt.js +0 -1
- package/dist/assets/scala-D9hQfWCl.js +0 -1
- package/dist/assets/scheme-BPhDTwHR.js +0 -1
- package/dist/assets/scss-CBJaRo0y.js +0 -3
- package/dist/assets/shell-DiJ1NA_G.js +0 -1
- package/dist/assets/solidity-Db0IVjzk.js +0 -1
- package/dist/assets/sophia-CnS9iZB_.js +0 -1
- package/dist/assets/sparql-CJmd_6j2.js +0 -1
- package/dist/assets/sql-ClhHkBeG.js +0 -1
- package/dist/assets/st-CHwy0fLd.js +0 -1
- package/dist/assets/swift-CnmFD0ga.js +0 -1
- package/dist/assets/systemverilog-Bs9z6M-B.js +0 -1
- package/dist/assets/tcl-Dm6ycUr_.js +0 -1
- package/dist/assets/tsMode-BZv6gTt6.js +0 -11
- package/dist/assets/twig-Csy3S7wG.js +0 -1
- package/dist/assets/typescript-BgDL1fzP.js +0 -1
- package/dist/assets/typespec-Btyra-wh.js +0 -1
- package/dist/assets/useReplaceWebResourceConfirm-DND-V0vw.js +0 -1
- package/dist/assets/useStableKeys-BkDn7til.js +0 -1
- package/dist/assets/vb-Db0cS2oM.js +0 -1
- package/dist/assets/wgsl-BTesnYfV.js +0 -298
- package/dist/assets/workers-BZ4mXA5s.js +0 -1
- package/dist/assets/xml-Cl6spsD4.js +0 -1
- package/dist/assets/yaml-El-x4GhS.js +0 -1
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./EditorDrawer-BtFb9OzQ.js","./preload-helper-PPVm8Dsz.js","./fluent-ui-CQyNN9H3.js","./dnd-iy5K5XAJ.js","./BulkPublishModal-BWRed6Fv.js","./MonacoEditor-CEYP9b6u.js","./xmlValidator-xIq-x9Ub.js","./ruleKinds-BKTUiZ1-.js","./crmParameters-rgfZhhzN.js","./NewButtonModal-5nQ-f2by.js","./NewGroupModal-vEuxSpnD.js","./NewTabModal-DNzMru8E.js","./ImportXmlModal-BZq0Iglk.js","./CommandPalette-Fc4MPKvd.js","./IconPickerModal-FyQ9ud3R.js","./useReplaceWebResourceConfirm-BdTw98QF.js","./WebResourceBrowser-L3R7UTNR.js","./HideInsteadOfDeleteModal-fdtkLfSG.js","./server.browser-DTeSoizu.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{b as Rm,W as tt,m as me,j as a,T as pe,c as V,B as xe,t as h,r as E,C as la,O as cr,d as xi,e as Ie,L as un,D as $m,f as Tm,g as Nm,h as km,i as Am,k as K,l as cn,n as Om,o as dr,p as Mm,S as Hl,u as Gl,P as ca,q as da,s as Ul,v as it,w as Vl,x as ua,F as _e,I as Et,y as ma,z as Dm,A as Ft,E as on,G as pa,H as fa,J as Em,M as Ke,K as Ye,N as Mn,Q as Je,R as Ze,U as ha,V as Xl,X as fe,Y as Bm,Z as ao,_ as Sn,$ as Dt,a0 as Kl,a1 as ga,a2 as ba,a3 as us,a4 as ya,a5 as Lm,a6 as $t,a7 as Tt,a8 as Yl,a9 as ms,aa as Tn,ab as zm,ac as ur,ad as Jl,ae as Zl,af as Pm,ag as vi,ah as sn,ai as Ql,aj as Si,ak as Fm,al as Dn,am as Bt,an as ro,ao as yo,ap as mr,aq as En,ar as _t,as as xa,at as ke,au as pr,av as _m,aw as qm,ax as Wm,ay as ec,az as Hm,aA as Gm,aB as Um,aC as Vm,aD as Xm,aE as Km,aF as Ym,aG as Jm,aH as Zm,aI as wi,aJ as Qm,aK as ep,aL as tp,aM as tc,aN as np,aO as op,aP as sp,aQ as ip,aR as ap,aS as rp,aT as lp,aU as nc,aV as cp,aW as dp,aX as up,aY as mp,aZ as pp,a_ as fp,a$ as hp,b0 as oc,b1 as gp,b2 as bp,b3 as yp,b4 as xp,b5 as vp,b6 as Sp,b7 as wp,b8 as Cp,b9 as Ip,ba as jp,bb as sc,bc as Rp,bd as va,be as $p,bf as Tp,bg as Np,bh as ic,bi as kp,bj as Ap,bk as Op,bl as Mp,bm as Dp,bn as Ep,bo as Bp,bp as Lp,bq as zp,br as Pp,bs as Fp,bt as _p,bu as qp,bv as Wp,bw as Hp,bx as Gp,by as Up,bz as Bo,bA as Vp,bB as Xp,bC as Kp,bD as Yp,bE as Jp,bF as Zp,bG as Qp,bH as ef,bI as ac,bJ as tf,bK as rc,bL as nf,bM as of,bN as sf,bO as af,bP as rf,bQ as lf,bR as cf,bS as df,bT as uf,bU as lc,bV as mf,bW as pf,bX as ff,bY as ps,bZ as hf,b_ as gf,b$ as bf,c0 as yf,c1 as xf,c2 as vf,c3 as Sf,c4 as Ci,c5 as wf,c6 as cc,c7 as Cf,c8 as If,c9 as jf,ca as Rf,cb as $f,cc as dc,cd as Tf,ce as uc,cf as Nf,cg as kf,ch as Af,ci as Of,cj as Mf,ck as Df,cl as Ef,cm as Bf,cn as mc,co as Lf,cp as zf,cq as Ii,cr as Pf,cs as Ff,ct as _f,cu as qf,cv as Wf,cw as Hf,cx as Gf,cy as pc,cz as Uf,cA as Vf,cB as Xf,cC as Kf,cD as Yf,cE as Jf,cF as Zf,cG as Qf,cH as eh,cI as th,cJ as fc,cK as nh,cL as oh,cM as sh,cN as ih,cO as ah,cP as rh,cQ as ji,cR as lh,cS as ch,cT as dh,cU as uh,cV as mh,cW as ph,cX as fh,cY as hh,cZ as hc,c_ as gh,c$ as bh,d0 as yh,d1 as xh,d2 as vh,d3 as Sh,d4 as wh,d5 as Ch,d6 as Ih,d7 as jh,d8 as Rh,d9 as $h,da as Th,db as Nh,dc as fr,dd as kh,de as hr,df as Ah,dg as Oh,dh as Mh,di as gr,dj as Dh,dk as Eh,dl as br,dm as Bh,dn as Lh,dp as zh,dq as Ls,dr as Ph,ds as yr,dt as Io,du as Fh,dv as jo,dw as _h,dx as xr,dy as qh,dz as vr,dA as gc,dB as bc,dC as yc,dD as Wh,dE as Hh,dF as Gh,dG as Uh,dH as Sr,dI as Fn,dJ as Vh,dK as _n,dL as lo,dM as xc,dN as qe,dO as Sa,dP as an,dQ as Xh,dR as Kh,dS as Yh,dT as wr,dU as vc,dV as Jh,dW as Sc,dX as Qe,dY as Zh,dZ as wa,d_ as qt,d$ as Qh,e0 as eg,e1 as tg,e2 as Cr,e3 as wc,e4 as Cc,e5 as Ic,e6 as jc,e7 as ng,e8 as og,e9 as Rc,ea as Ca,eb as Ia,ec as sg,ed as Lo,ee as zs,ef as ig,eg as ag,eh as rg,ei as xn,ej as lg,ek as cg,el as dg,em as ug,en as mg,eo as $c,ep as pg,eq as fg,er as hg,es as gg,et as bg,eu as yg,ev as xg,ew as vg,ex as Sg,ey as wg,ez as Cg,eA as Ig,eB as jg,eC as Zn,eD as Wt,eE as Ht,eF as Rg,eG as $g,eH as Tg,eI as Ng,eJ as kg}from"./fluent-ui-CQyNN9H3.js";import{_ as ht}from"./preload-helper-PPVm8Dsz.js";import{u as Ag,a as Tc,b as Uo,D as Nc,c as kc,d as Ac,K as Oc,P as Mc,e as ja,p as Ir,s as Og,S as Mg,v as Dg,f as Eg,C as Bg,g as Lg}from"./dnd-iy5K5XAJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&o(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();var Ro={},jr;function zg(){if(jr)return Ro;jr=1;var e=Rm();return Ro.createRoot=e.createRoot,Ro.hydrateRoot=e.hydrateRoot,Ro}var Pg=zg();const Rr=e=>{let t;const n=new Set,o=(d,u)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const m=t;t=u??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(g=>g(t,m))}},s=()=>t,r={setState:o,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(o,s,r);return r},Fg=(e=>e?Rr(e):Rr),_g=e=>e;function qg(e,t=_g){const n=tt.useSyncExternalStore(e.subscribe,tt.useCallback(()=>t(e.getState()),[e,t]),tt.useCallback(()=>t(e.getInitialState()),[e,t]));return tt.useDebugValue(n),n}const Wg=e=>{const t=Fg(e),n=o=>qg(t,o);return Object.assign(n,t),n},Kt=(e=>Wg);function Vo(e){if(!e||!e.id&&!e.url)return"";const t=(e.url??"").trim().replace(/\/+$/,"").toLowerCase();return`${e.id??""}|${t}`}function Dc(){return window.toolboxAPI?.connections}async function Ra(){const e=Dc();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 Ri extends Error{constructor(t){super(`${t} was stopped: the tool's connection changed in Power Platform ToolBox. Nothing was written to the newly selected environment; anything already written by this operation went to the environment it started on.`),this.name="ConnectionChangedError"}}let Qn,$i=0;function $r(e){const t=Vo(e);Qn!==void 0&&t!==Qn&&$i++,Qn=t}async function fs(e){const t=Dc();if(Qn===void 0||!t?.getConnection&&!t?.getActiveConnection)return;let n;try{n=Vo(await Ra())}catch{throw new Ri(e)}if(n!==Qn)throw new Ri(e)}function Hg(e){const t=window.toolboxAPI?.events;if(typeof t?.on!="function")return()=>{};let n=0;const o=(s,i)=>{const l=i?.event;if(l!=="connection:updated"&&l!=="connection:created"&&l!=="connection:deleted")return;const r=++n;Ra().then(c=>{r===n&&e(c)}).catch(()=>{})};return t.on(o),()=>t.off?.(o)}function Ec(){const e=$i;return async t=>{if($i!==e)throw new Ri(t);await fs(t)}}const Ti=new Set;function Gg(e){return Ti.add(e),()=>Ti.delete(e)}const ae=Kt()((e,t)=>({connectionId:"",connectionUrl:"",connectionName:"",environment:"Dev",publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:0,connectionNotice:null,setConnection:(n,o,s,i=t().connectionId)=>{$r({id:i,url:n}),e({connectionId:i,connectionUrl:n,connectionName:o,environment:s})},switchConnection:(n,o)=>{const s=t();$r(n),e({connectionId:n.id,connectionUrl:n.url,connectionName:n.name,environment:n.environment,publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:s.connectionVersion+1,connectionNotice:{...o,from:{name:s.connectionName,url:s.connectionUrl,environment:s.environment},to:{name:n.name,url:n.url,environment:n.environment}}})},dismissConnectionNotice:()=>e({connectionNotice:null}),setSolutions:n=>e({solutions:n}),setActiveSolution:n=>{ht(async()=>{const{useRuntimeLogStore:s}=await Promise.resolve().then(()=>Zg);return{useRuntimeLogStore:s}},void 0,import.meta.url).then(({useRuntimeLogStore:s})=>{s.getState().logInfo("dataverse",`Active solution: "${n.friendlyName||n.uniqueName}" — publisher="${n.publisherUniqueName||"(empty)"}", prefix="${n.publisherPrefix||"(empty)"}"`),(!n.publisherPrefix||n.publisherPrefix==="new"||/^defaultpublisher/i.test(n.publisherUniqueName??""))&&s.getState().logWarn("dataverse",`Solution "${n.friendlyName||n.uniqueName}" uses the org's default publisher (prefix="${n.publisherPrefix||"new"}"). All IDs and imports from CBS will land under that publisher. To use your own (e.g. "mxrm"), create a new solution in maker.powerapps.com bound to your custom publisher and pick that one here.`)});const o=t().activeSolution?.id!==n.id;if(e({activeSolution:n,publisherPrefix:n.publisherPrefix||"new",...o?{activeEntity:null,entities:[],solutionEntityIds:null,solutionRibbonComponentIds:null}:{}}),o)for(const s of Ti)s()},setEntities:n=>e({entities:n}),setActiveEntity:n=>e({activeEntity:n}),setSolutionEntityIds:n=>e({solutionEntityIds:n}),setSolutionRibbonComponentIds:n=>e({solutionRibbonComponentIds:n}),setCurrentUser:(n,o)=>e({currentUserId:n,currentUserName:o}),setPublisherPrefix:n=>e({publisherPrefix:n})})),Ug=e=>(t,n,o)=>{const s=o.subscribe;return o.subscribe=((l,r,c)=>{let d=l;if(r){const u=c?.equalityFn||Object.is;let p=l(o.getState());d=m=>{const g=l(m);if(!u(p,g)){const b=p;r(p=g,b)}},c?.fireImmediately&&r(p,p)}return s(d)}),e(t,n,o)},Vg=Ug;function Bc(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),r=(i=n.getItem(s))!=null?i:null;return r instanceof Promise?r.then(l):l(r)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const Ni=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(o){return Ni(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return Ni(o)(n)}}}},Xg=(e,t)=>(n,o,s)=>{let i={storage:Bc(()=>window.localStorage),partialize:y=>y,version:0,merge:(y,x)=>({...x,...y}),...t},l=!1,r=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return e((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...y)},o,s);const p=()=>{const y=i.partialize({...o()});return u.setItem(i.name,{state:y,version:i.version})},m=s.setState;s.setState=(y,x)=>(m(y,x),p());const g=e((...y)=>(n(...y),p()),o,s);s.getInitialState=()=>g;let b;const f=()=>{var y,x;if(!u)return;const v=++r;l=!1,c.forEach($=>{var A;return $((A=o())!=null?A:g)});const C=((x=i.onRehydrateStorage)==null?void 0:x.call(i,(y=o())!=null?y:g))||void 0;return Ni(u.getItem.bind(u))(i.name).then($=>{if($)if(typeof $.version=="number"&&$.version!==i.version){if(i.migrate){const A=i.migrate($.state,$.version);return A instanceof Promise?A.then(j=>[!0,j]):[!0,A]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,$.state];return[!1,void 0]}).then($=>{var A;if(v!==r)return;const[j,T]=$;if(b=i.merge(T,(A=o())!=null?A:g),n(b,!0),j)return p()}).then(()=>{v===r&&(C?.(o(),void 0),b=o(),l=!0,d.forEach($=>$(b)))}).catch($=>{v===r&&C?.(void 0,$)})};return s.persist={setOptions:y=>{i={...i,...y},y.storage&&(u=y.storage)},clearStorage:()=>{++r,u?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>f(),hasHydrated:()=>l,onHydrate:y=>(c.add(y),()=>{c.delete(y)}),onFinishHydration:y=>(d.add(y),()=>{d.delete(y)})},i.skipHydration||f(),b||g},Kg=Xg;function Yg(e,t=250){const n=new Map;let o;const s=()=>{o!==void 0&&clearTimeout(o),o=void 0;for(const[i,l]of n)try{e().setItem(i,l)}catch{}n.clear()};return typeof window<"u"&&(window.addEventListener("pagehide",s),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&s()})),{getItem:i=>{const l=n.get(i);if(l!==void 0)return l;try{return e().getItem(i)}catch{return null}},setItem:(i,l)=>{n.set(i,l),o??=setTimeout(s,t)},removeItem:i=>{n.delete(i);try{e().removeItem(i)}catch{}}}}function ot(e){const t=e.find(l=>l.kind==="command"),n=e[e.length-1],o=n?.kind==="rule"?n:null,s=e.find(l=>l.kind==="translations"),i=[...e].reverse().find(l=>l.kind==="diff");return{editorStack:e,commandEditorOpen:!!t,commandEditorId:t?.id??null,ruleEditorOpen:!!o,ruleEditorId:o?.id??null,ruleEditorKind:o?.ruleKind??null,tabDisplayRulesOpen:e.some(l=>l.kind==="tabRules"),xmlDrawerOpen:e.some(l=>l.kind==="xml"),diffViewerOpen:!!i,diffViewerMode:i?.id??"compare",localizationEditorOpen:!!s,localizationEditorButtonId:s?.id??null}}function Qt(e,t){return e[e.length-1]?.kind===t.kind?[...e.slice(0,-1),t]:[...e,t]}const Jg=e=>({leftPaneWidth:260,leftPaneTab:"structure",rightPaneWidth:340,bottomPanelHeight:220,bottomCollapsed:!0,rightPaneMode:"docked",themeMode:"light",ribbonViewStyle:"groups",activeBottomTab:"commands",editorStack:[],commandEditorOpen:!1,commandEditorId:null,ruleEditorOpen:!1,ruleEditorId:null,ruleEditorKind:null,commandEditorTab:"actions",xmlDrawerOpen:!1,bulkPublishOpen:!1,iconPickerOpen:!1,localizationEditorOpen:!1,localizationEditorButtonId:null,newGroupOpen:!1,newButtonGroupId:null,importXmlOpen:!1,importXmlSeed:"",importXmlNote:"",webResourceBrowserOpen:!1,diffViewerOpen:!1,diffViewerMode:"compare",tabDisplayRulesOpen:!1,commandPaletteOpen:!1,solutionPickerOpen:!1,tablePickerOpen:!1,propertiesRequested:!1,newTabOpen:!1,hideInsteadOfDelete:null,announcement:"",setLeftPaneWidth:t=>e({leftPaneWidth:t}),setRightPaneWidth:t=>e({rightPaneWidth:t}),setBottomPanelHeight:t=>e({bottomPanelHeight:t}),setBottomCollapsed:t=>e({bottomCollapsed:t}),setRightPaneMode:t=>e({rightPaneMode:t}),setThemeMode:t=>e({themeMode:t}),setRibbonViewStyle:t=>e({ribbonViewStyle:t}),setActiveBottomTab:t=>e({activeBottomTab:t}),openCommandEditor:t=>e(n=>({...ot(t?Qt(n.editorStack,{kind:"command",id:t}):[]),commandEditorTab:t&&t===n.commandEditorId?n.commandEditorTab:"actions"})),closeCommandEditor:()=>e(ot([])),openRuleEditor:(t,n)=>e(o=>ot(t?Qt(o.editorStack,{kind:"rule",id:t,ruleKind:n}):o.editorStack)),closeRuleEditor:()=>e(t=>ot(t.editorStack[t.editorStack.length-1]?.kind==="rule"?t.editorStack.slice(0,-1):t.editorStack)),setCommandEditorTab:t=>e({commandEditorTab:t}),openScriptView:(t,n)=>e(o=>ot(Qt(o.editorStack,{kind:"script",id:t,editable:n}))),editorBack:()=>e(t=>ot(t.editorStack.slice(0,-1))),closeEditor:()=>e(ot([])),openXmlDrawer:t=>e(n=>ot(Qt(n.editorStack,{kind:"xml",id:t}))),closeXmlDrawer:()=>e(t=>ot(t.editorStack.filter(n=>n.kind!=="xml"))),openBulkPublish:()=>e({bulkPublishOpen:!0}),closeBulkPublish:()=>e({bulkPublishOpen:!1}),openIconPicker:()=>e({iconPickerOpen:!0}),closeIconPicker:()=>e({iconPickerOpen:!1}),openLocalizationEditor:t=>e(n=>ot(Qt(n.editorStack,{kind:"translations",id:t}))),closeLocalizationEditor:()=>e(t=>ot(t.editorStack.filter(n=>n.kind!=="translations"))),openNewGroup:()=>e({newGroupOpen:!0}),closeNewGroup:()=>e({newGroupOpen:!1}),openNewButton:t=>e({newButtonGroupId:t}),closeNewButton:()=>e({newButtonGroupId:null}),openImportXml:(t,n)=>e({importXmlOpen:!0,importXmlSeed:typeof t=="string"?t:"",importXmlNote:typeof n=="string"?n:""}),closeImportXml:()=>e({importXmlOpen:!1}),openWebResourceBrowser:()=>e({webResourceBrowserOpen:!0}),closeWebResourceBrowser:()=>e({webResourceBrowserOpen:!1}),openDiffViewer:(t,n)=>e(o=>ot(Qt(o.editorStack,{kind:"diff",id:t,historyIndex:n}))),closeDiffViewer:()=>e(t=>ot(t.editorStack.filter(n=>n.kind!=="diff"))),openTabDisplayRules:(t,n)=>e(o=>ot(Qt(o.editorStack,{kind:"tabRules",id:n,location:t}))),setCommandPaletteOpen:t=>e({commandPaletteOpen:t}),setSolutionPickerOpen:t=>e({solutionPickerOpen:t}),setTablePickerOpen:t=>e({tablePickerOpen:t}),setLeftPaneTab:t=>e({leftPaneTab:t}),structureChoice:0,noteStructureChoice:()=>e(t=>({structureChoice:t.structureChoice+1})),setPropertiesRequested:t=>e({propertiesRequested:t}),openNewTab:()=>e({newTabOpen:!0}),closeNewTab:()=>e({newTabOpen:!1}),openHideInsteadOfDelete:t=>e({hideInsteadOfDelete:t}),closeHideInsteadOfDelete:()=>e({hideInsteadOfDelete:null}),announce:t=>e({announcement:t})}),Z=Kt()(Kg(Jg,{name:"cbs:ui",storage:Bc(()=>Yg(()=>localStorage)),partialize:e=>({leftPaneWidth:e.leftPaneWidth,leftPaneTab:e.leftPaneTab,rightPaneWidth:e.rightPaneWidth,bottomPanelHeight:e.bottomPanelHeight,bottomCollapsed:e.bottomCollapsed,rightPaneMode:e.rightPaneMode,themeMode:e.themeMode,ribbonViewStyle:e.ribbonViewStyle})})),ce=Kt()((e,t)=>({entries:[],append:n=>{const s={id:`${Date.now()}-${t().entries.length+1}`,ts:new Date().toISOString(),...n};e({entries:[...t().entries,s].slice(-400)})},logInfo:(n,o)=>t().append({scope:n,level:"info",message:o}),logWarn:(n,o)=>t().append({scope:n,level:"warn",message:o}),logError:(n,o)=>t().append({scope:n,level:"error",message:o}),clear:()=>e({entries:[]})})),Zg=Object.freeze(Object.defineProperty({__proto__:null,useRuntimeLogStore:ce},Symbol.toStringTag,{value:"Module"})),Qg=new Set(["Default","InvertResult","PropertyValue","ExpectedValue","TrackedInCrm","PassParams","AllowCustomRelationship","AllowSystemRelationship"]),Tr=["EnableRules","DisplayRules","Actions"];function eb(e,t){return Qg.has(t)||e.tagName==="BoolParameter"&&t==="Value"}function tb(e){const t=e.trim();return t==="1"?"true":t==="0"?"false":t}function nb(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/"/g,""")}function zo(e,t,n){const o=Array.from(e.attributes).map(l=>[l.name,eb(e,l.name)?tb(l.value):l.value]).sort(([l],[r])=>l<r?-1:l>r?1:0).map(([l,r])=>` ${l}="${nb(r)}"`).join(""),s=[];let i=[];for(const l of Array.from(e.childNodes))if(l.nodeType===1)i.push(l);else if(l.nodeType===3||l.nodeType===4){const r=(l.textContent??"").trim();r&&s.push(`${n} #text ${r}`)}if(t.normalizeCommands&&e.tagName==="CommandDefinition"){const l=new Map(i.map(d=>[d.tagName,d])),r=i.filter(d=>!Tr.includes(d.tagName)),c=Tr.map(d=>{const u=l.get(d);return u?zo(u,t,`${n} `):`${n} <${d}/>`});i=[],s.push(...c,...r.map(d=>zo(d,t,`${n} `)))}for(const l of i)s.push(zo(l,t,`${n} `));return s.length===0?`${n}<${e.tagName}${o}/>`:`${n}<${e.tagName}${o}>
|
|
3
|
+
${s.join(`
|
|
4
|
+
`)}
|
|
5
|
+
${n}</${e.tagName}>`}function Lc(e){const t=new DOMParser().parseFromString(e,"application/xml"),n=t.querySelector("parsererror");if(n)throw new Error(`XML parse error: ${n.textContent??"unknown"}`);return t.documentElement}function Nn(e,t={}){const n=typeof e=="string"?Lc(e):e;return zo(n,t,"")}function ob(e,t,n={}){try{return Nn(e,n)===Nn(t,n)}catch{return!1}}const wn={button:"Button",flyout:"FlyoutAnchor",splitButton:"SplitButton",textBox:"TextBox",comboBox:"ComboBox",checkBox:"CheckBox",toggleButton:"ToggleButton",label:"Label",dropDown:"DropDown",mruSplitButton:"MRUSplitButton",spinner:"Spinner",galleryButton:"GalleryButton"},zc=Object.fromEntries(Object.entries(wn).map(([e,t])=>[t,e])),sb=new Set(["toggleButton","label","dropDown","mruSplitButton","spinner","galleryButton"]);function dt(e){return!!e&&sb.has(e)}const Pc=["Command","QueryCommand","MenuCommand","PopulateQueryCommand","CommandMenuOpen","CommandMenuClose","CommandPreview","CommandPreviewRevert","CommandRevert"],Fc=new RegExp(`\\s(?:${Pc.join("|")})="([^"]+)"`,"g");function _c(e){const t=new Set(e.commandId?[e.commandId]:[]),n=e.source?.attributes.PopulateQueryCommand;if(n&&(e.kind==="flyout"||e.kind==="splitButton")&&t.add(n),dt(e.kind))for(const o of e.source?.xml?.matchAll(Fc)??[])t.add(o[1]);return[...t]}function ib(e,t,n){const o=s=>s.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<");return e.replace(Fc,(s,i)=>i===t||i===o(t)?s.replace(`"${i}"`,`"${o(n)}"`):s)}const xt={button:"Button",flyout:"Flyout",splitButton:"Split button",textBox:"Text box",comboBox:"Combo box",checkBox:"Check box",toggleButton:"Toggle button",label:"Label",dropDown:"Drop-down",mruSplitButton:"MRU split button",spinner:"Spinner",galleryButton:"Gallery button"};function qc(e,t){const n=t.length>0?Math.min(...t):1/0,o=e.filter(s=>s<n);return{after:o.length>0?Math.max(...o):0,before:n}}function Wc(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 Hc(e,t,n){const o=[],s=[],i=new Set([...t.maxSizes,...t.scales]),l=(m,g)=>{o.push({tabId:e,id:m.id,kind:m.kind,groupId:m.groupId,from:m.sequence,to:g}),i.add(g)},r=n.filter(m=>m.kind==="Scale"),c=[];for(const m of r)i.has(m.sequence)?c.push(m):i.add(m.sequence);for(const m of c)l(m,Math.max(0,...i)+1);const d=[...t.scales,...r.map(m=>o.find(g=>g.id===m.id&&g.kind==="Scale")?.to??m.sequence)],u=qc(t.maxSizes,d),p=[];for(const m of n.filter(g=>g.kind==="MaxSize"))m.sequence<u.before&&!i.has(m.sequence)?i.add(m.sequence):p.push(m);for(const m of p){const g=Wc(u,i);g===void 0?s.push(`The scaling of tab ${e} has no free position for MaxSize ${m.id} (Sequence ${m.sequence}): it must come before the first Scale (${u.before}) and use a Sequence no other step uses`):l(m,g)}return{changes:o,problems:s}}function ab(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 Bn(){return{customActions:new Map,templates:new Map,commandDefinitions:new Map,tabDisplayRules:new Map,displayRules:new Map,enableRules:new Map,locLabels:new Map}}const kn=()=>new XMLSerializer;function Gc(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 ve(e,t){return At(e,t)[0]}function Uc(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 Y0(e){const t=Bn(),o=Gc(e).documentElement;if(o.tagName!=="RibbonDiffXml")throw new Error(`Expected <RibbonDiffXml> root, got <${o.tagName}>`);const s=kn();for(const r of Array.from(ve(o,"CustomActions")?.children??[])){const c=Uc(r);c&&t.customActions.set(c,s.serializeToString(r))}const i=ve(ve(o,"Templates"),"RibbonTemplates");for(const r of Array.from(i?.children??[])){const c=r.getAttribute("Id");c&&t.templates.set(c,s.serializeToString(r))}for(const r of At(ve(o,"CommandDefinitions"),"CommandDefinition")){const c=r.getAttribute("Id");c&&t.commandDefinitions.set(c,s.serializeToString(r))}const l=ve(o,"RuleDefinitions");for(const r of At(ve(l,"TabDisplayRules"),"TabDisplayRule")){const c=r.getAttribute("TabCommand");c&&t.tabDisplayRules.set(c,s.serializeToString(r))}for(const r of At(ve(l,"DisplayRules"),"DisplayRule")){const c=r.getAttribute("Id");c&&t.displayRules.set(c,s.serializeToString(r))}for(const r of At(ve(l,"EnableRules"),"EnableRule")){const c=r.getAttribute("Id");c&&t.enableRules.set(c,s.serializeToString(r))}for(const r of At(ve(o,"LocLabels"),"LocLabel")){const c=r.getAttribute("Id");c&&t.locLabels.set(c,s.serializeToString(r))}return t}function Se(e){return Gc(e).documentElement}function rb(e){const t=Bn();for(const n of e.diffs){const o=n.rdx?.trim();if(!o)continue;const s=Se(o);switch(n.difftype){case 3:{const i=s.getAttribute("Id")??n.diffid;i&&t.locLabels.set(i,o);break}case 2:{const i=s.getAttribute("Id")??n.diffid;i&&t.templates.set(i,o);break}default:{const i=Uc(s);i&&t.customActions.set(i,o)}}}for(const n of e.commands){const o=n.commanddefinition?.trim(),s=n.command??(o?Se(o).getAttribute("Id"):null);o&&s&&t.commandDefinitions.set(s,o)}for(const n of e.rules){const o=n.ruledefinition?.trim();if(!o)continue;const s=Se(o);if(n.ruletype===3||s.tagName==="TabDisplayRule"){const i=s.getAttribute("TabCommand")??n.ruleid;i&&t.tabDisplayRules.set(i,o)}else if(n.ruletype===1||s.tagName==="EnableRule"){const i=s.getAttribute("Id")??n.ruleid;i&&t.enableRules.set(i,o)}else{const i=s.getAttribute("Id")??n.ruleid;i&&t.displayRules.set(i,o)}}return t}function $a(e,t){const n=Bn();for(const o of Object.keys(n)){for(const[s,i]of e[o])n[o].set(s,i);for(const[s,i]of t[o])n[o].set(s,i)}return n}function J0(e){const t=(n,o)=>Array.from(n.values()).map(s=>`${o}${s}`).join(`
|
|
6
|
+
`);return`<RibbonDiffXml>
|
|
7
|
+
<CustomActions>
|
|
8
|
+
${t(e.customActions," ")}
|
|
9
|
+
</CustomActions>
|
|
10
|
+
<Templates>
|
|
11
|
+
<RibbonTemplates Id="Mscrm.Templates">
|
|
12
|
+
${t(e.templates," ")}
|
|
13
|
+
</RibbonTemplates>
|
|
14
|
+
</Templates>
|
|
15
|
+
<CommandDefinitions>
|
|
16
|
+
${t(e.commandDefinitions," ")}
|
|
17
|
+
</CommandDefinitions>
|
|
18
|
+
<RuleDefinitions>
|
|
19
|
+
<TabDisplayRules>
|
|
20
|
+
${t(e.tabDisplayRules," ")}
|
|
21
|
+
</TabDisplayRules>
|
|
22
|
+
<DisplayRules>
|
|
23
|
+
${t(e.displayRules," ")}
|
|
24
|
+
</DisplayRules>
|
|
25
|
+
<EnableRules>
|
|
26
|
+
${t(e.enableRules," ")}
|
|
27
|
+
</EnableRules>
|
|
28
|
+
</RuleDefinitions>
|
|
29
|
+
<LocLabels>
|
|
30
|
+
${t(e.locLabels," ")}
|
|
31
|
+
</LocLabels>
|
|
32
|
+
</RibbonDiffXml>`}function lb(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 Nr(e,t){const n=Se(t);if(e==="commandDefinitions")for(const o of Array.from(n.getElementsByTagName("JavaScriptFunction")))lb(o)&&o.parentNode?.replaceChild(n.ownerDocument.createElement("PlatformJavaScriptFunction"),o);if(e==="locLabels")for(const o of Array.from(n.getElementsByTagName("Titles"))){const s=Array.from(o.children).sort((i,l)=>Number(i.getAttribute("languagecode"))-Number(l.getAttribute("languagecode")));for(const i of s)o.appendChild(i)}return Nn(n,{normalizeCommands:e==="commandDefinitions"})}const Vc=(e,t,n)=>{try{return Nr(e,t)===Nr(e,n)}catch{return t===n}},kr=e=>Array.from(Se(e).getElementsByTagName("Title")).map(t=>`${t.getAttribute("languagecode")}=${t.getAttribute("description")??""}`);function cb(e,t,n){if(e!=="locLabels")return Vc(e,t,n);try{const o=new Set(kr(t)),s=kr(n);return s.length>0&&s.every(i=>o.has(i))}catch{return t===n}}function Z0(e,t){const n=[];for(const o of Object.keys(t))for(const[s,i]of t[o]){const l=e[o].get(s);(l===void 0||!Vc(o,l,i))&&n.push(`${o}:${s}`)}return n}function Q0(e,t,n={}){const o=[],s=[],i=[],l=new Set(n.contentKeys??[]);for(const r of Object.keys(e)){for(const[c,d]of e[r]){const u=t[r].get(c);u===void 0?o.push(`${r}:${c}`):l.has(`${r}:${c}`)&&!cb(r,d,u)&&i.push(`${r}:${c}`)}for(const c of t[r].keys())e[r].has(c)||s.push(`${r}:${c}`)}return{missing:o,unexpected:s,differing:i}}function eI(e){return Object.values(e).reduce((t,n)=>t+n.size,0)}function Ps(e){const t=Se(e);return t.tagName!=="CustomAction"?null:ve(t,"CommandUIDefinition")?.firstElementChild??null}function yt(e){return!!e&&e.endsWith("._children")}const db=new Set(["Menu","MenuSection","Controls"]);function ki(e){return e.tagName==="Tab"||e.tagName==="Group"?[]:Array.from(e.getElementsByTagName("*")).filter(t=>!db.has(t.tagName)&&!!t.getAttribute("Id")&&t.parentElement?.tagName==="Controls")}const co=e=>e?.tagName==="Tab"||e?.tagName==="Group",Ar=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Xc(e){return Array.from(e.getElementsByTagName("Controls")).flatMap(t=>Array.from(t.children))}function Kc(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 Xo(e){return co(e)?Xc(e):ki(e)}function Ko(e){const t=new Set;for(const n of e.customActions.values()){const o=Se(n);if(o.tagName!=="CustomAction"||!yt(o.getAttribute("Location")))continue;const s=ve(o,"CommandUIDefinition")?.firstElementChild,i=s?.getAttribute("Id");if(i&&t.add(i),s)for(const l of Xo(s)){const r=l.getAttribute("Id");r&&t.add(r)}}return t}function Yc(e,t){const n=new Map(e),o=kn(),s=t?new Set(t):void 0;for(let i=!0;i;){i=!1;const l=new Map;for(const[r,c]of n){const d=Se(c);if(d.tagName!=="CustomAction"||!yt(d.getAttribute("Location")))continue;const u=ve(d,"CommandUIDefinition")?.firstElementChild;if(co(u))for(const p of[u,...Array.from(u.getElementsByTagName("Group"))]){const m=p.getAttribute("Id");m&&!l.has(m)&&l.set(m,r)}}for(const[r,c]of n){const d=Se(c);if(d.tagName!=="CustomAction")continue;const u=/^(.+)\.(Controls|Groups|Scaling)\._children$/.exec(d.getAttribute("Location")??""),p=ve(d,"CommandUIDefinition")?.firstElementChild,m=u?l.get(u[1]):void 0;if(!u||!p||!m||m===r||s&&!s.has(r)&&!s.has(m))continue;const[,g,b]=u,f=Se(n.get(m)),y=Kc(f,g);if(!y||y.tagName!==(b==="Controls"?"Group":"Tab"))continue;const x=f.ownerDocument;let v=ve(y,b);if(!v){v=x.createElement(b),v.setAttribute("Id",`${g}.${b}`);const j=b==="Scaling"?ve(y,"Groups"):void 0;y.insertBefore(v,j??null)}const C=x.importNode(p,!0),$=d.getAttribute("Sequence");!C.getAttribute("Sequence")&&$&&C.setAttribute("Sequence",$);const A=C.tagName==="MaxSize"?ve(v,"Scale"):void 0;v.insertBefore(C,A??null),n.set(m,o.serializeToString(f)),s?.add(m),n.delete(r),i=!0;break}}return n}function ub(e,t){const n=ve(e,"CommandUIDefinition")?.firstElementChild??null;return n?n.getAttribute("Id")===t?n:Xo(n).find(o=>o.getAttribute("Id")===t)??null:null}function Jc(e){const t=new Set;for(const n of e.customActions.values()){const o=Se(n);if(o.tagName!=="CustomAction"||!yt(o.getAttribute("Location")))continue;const s=ve(o,"CommandUIDefinition")?.firstElementChild;if(!s||s.tagName!=="Tab"&&s.tagName!=="Group")continue;const i=s.getAttribute("Id");i&&t.add(i);for(const l of Array.from(s.getElementsByTagName("Group"))){const r=l.getAttribute("Id");r&&t.add(r)}}return t}function hs(e){const t=[];for(const n of e.customActions.values()){const o=Se(n);if(o.tagName!=="HideCustomAction")continue;const s=o.getAttribute("Location");s&&t.push({hideActionId:o.getAttribute("HideActionId")??"",location:s})}return t}function mb(e){const t=[],n=e.getAttribute("Id");n&&t.push(n);for(const o of Array.from(e.getElementsByTagName("*"))){const s=o.getAttribute("Id");s&&t.push(s)}return t}function eo(e){const t=[];for(const n of[e,...Array.from(e.getElementsByTagName("*"))])for(const o of Pc){const s=n.getAttribute(o);s&&t.push(s)}return t}function Zc(e){const t=new Set;for(const n of e.customActions.values()){const o=Se(n);if(o.tagName==="CustomAction")for(const s of eo(o))t.add(s)}return t}function pb(e){return/^(Mscrm|Microsoft)\./.test(e)}function Ta(e,t){if(pb(e))return!0;for(const n of t)if(n===e)return!1;return!0}function fb(e){const t=e?.match(/^(.+)\.(?:Controls|Groups)\._children$/);return t?t[1]:null}function Po(e,t){if(!t||e.children.length>0||t.children.length===0)return e;for(const n of Array.from(t.children))e.appendChild(e.ownerDocument.importNode(n,!0));return e}function Or(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 hb(e,t,n){const o=At(e,"Menu")[0],s=At(t,"Menu")[0];if(!o){for(const r of ki(t))n(r.getAttribute("Id")??"")&&r.parentNode?.removeChild(r);return Po(t,e)}const i=o.cloneNode(!0),l=(r,c)=>[i,...Array.from(i.getElementsByTagName("*"))].find(d=>d.getAttribute("Id")===c&&(r?d.tagName===r:d.parentElement?.tagName==="Controls"));if(s){for(const r of Array.from(s.getElementsByTagName("MenuSection"))){const c=l("MenuSection",r.getAttribute("Id")??"");if(c){Or(r,c);continue}const d=l("Menu",r.parentElement?.getAttribute("Id")??"");if(!d)continue;const u=r.cloneNode(!0);for(const p of Array.from(u.getElementsByTagName("*")))p.parentElement?.tagName==="Controls"&&n(p.getAttribute("Id")??"")&&p.parentNode?.removeChild(p);d.appendChild(u)}for(const r of ki(t)){const c=r.getAttribute("Id")??"";if(n(c))continue;const d=l(null,c);if(d){Or(r,d);continue}const u=l("Controls",r.parentElement?.getAttribute("Id")??"");u&&u.appendChild(r.cloneNode(!0))}}for(const r of At(t,"Menu"))t.removeChild(r);return t.appendChild(i),t}const Fs=/\$LocLabels:([^"'\s]+)/g;function Mr(e){const t=new Set;for(const n of e)for(const o of eo(Se(n)))t.add(o);return t}function gb(e){const t=new Set;for(const n of e){const o=Se(n);for(const s of[o,...Array.from(o.getElementsByTagName("*"))])for(const i of Array.from(s.attributes))i.value.startsWith("$LocLabels:")&&t.add(i.value.slice(11))}return t}function $o(e){const t={EnableRule:new Set,DisplayRule:new Set};for(const n of e){const o=Se(n);for(const s of["EnableRule","DisplayRule"])for(const i of Array.from(o.getElementsByTagName(s))){const l=i.getAttribute("Id");l&&t[s].add(l)}}return t}function tI(e,t,n={}){const o=new Set(n.editedCommandIds??[]),s=new Set(n.editedEnableRuleIds??[]),i=new Set(n.editedDisplayRuleIds??[]),l=new Set(n.deletedControlIds??[]),r=new Set(n.unhiddenControlIds??[]),c=new Set(n.retainedCommandIds??[]),d=kn(),u=$a(e,Bn()),p=new Map,m=new Map,g=[];for(const[O,S]of e.customActions){const k=Ps(S),w=Se(S);if(w.tagName!=="CustomAction")continue;const D=w.getAttribute("Location");if(k?.getAttribute("Id")&&yt(D)){p.set(k.getAttribute("Id"),O);for(const F of Xo(k)){const X=F.getAttribute("Id");X&&g.push([X,O])}}else D&&m.set(D,O)}for(const[O,S]of g)p.has(O)||p.set(O,S);const b=(O,S)=>{const k=u.customActions.get(O);if(!k)return{ca:null,el:null,nested:!1};const w=Se(k),D=ub(w,S);return{ca:w,el:D,nested:!!D&&D.parentElement?.tagName!=="CommandUIDefinition"}},f=new Set;for(const[O,S]of t.customActions){const k=Se(S),w=Ps(S),D=w?.getAttribute("Id")??null,F=D?p.get(D):void 0,X=k.tagName==="CustomAction"&&yt(k.getAttribute("Location"));X&&D&&f.add(D);const ne=w?.tagName==="Tab"||w?.tagName==="Group";if(X&&ne)for(const U of Xc(w)){const W=U.getAttribute("Id");if(!W)continue;f.add(W);const te=p.get(W),P=te?b(te,W):null;!te||!P?.ca||!P.el||(P.nested?(P.el.parentNode.removeChild(P.el),u.customActions.set(te,d.serializeToString(P.ca))):u.customActions.delete(te))}const re=k.tagName==="CustomAction"&&w&&D&&F&&!(X&&ne),le=re?b(F,D):null;if(re&&le?.ca&&le.el&&le.nested){const{ca:U,el:W}=le;if(X)W.parentNode.removeChild(W),u.customActions.set(O,S);else{const te=Po(U.ownerDocument.importNode(w,!0),W);W.parentNode.replaceChild(te,W)}u.customActions.set(F,d.serializeToString(U));continue}if(re&&le?.ca&&le.el){const{ca:U,el:W,nested:te}=le;if(X&&te){W.parentNode.removeChild(W),u.customActions.set(F,d.serializeToString(U)),u.customActions.set(O,S);continue}let P=U.ownerDocument.importNode(w,!0);if(X?P=hb(W,P,Q=>{const be=p.get(Q);return!!be&&be!==F}):P=Po(P,W),W.parentNode.replaceChild(P,W),!te){X&&U.setAttribute("Location",k.getAttribute("Location"));const Q=w.getAttribute("Sequence")??(X?k.getAttribute("Sequence"):null);Q&&U.setAttribute("Sequence",Q)}u.customActions.set(F,d.serializeToString(U));continue}const _=k.getAttribute("Location"),L=k.tagName==="CustomAction"&&_?m.get(_):void 0;if(L&&w){const U=Ps(e.customActions.get(L)),W=Se(S),te=ve(W,"CommandUIDefinition");te?.firstElementChild&&Po(te.firstElementChild,U),u.customActions.delete(L),u.customActions.set(O,d.serializeToString(W));continue}u.customActions.set(O,S)}for(const{id:O,sequence:S}of n.resequencedContainers??[])for(const[k,w]of u.customActions){const D=Se(w),F=ve(D,"CommandUIDefinition");if(D.tagName!=="CustomAction"||!F)continue;const X=F.firstElementChild,ne=X?.getAttribute("Id")===O?X:Array.from(F.getElementsByTagName("*")).find(re=>(re.tagName==="Group"||re.tagName==="Tab")&&re.getAttribute("Id")===O);ne&&(ne.setAttribute("Sequence",String(S)),ne===X&&D.setAttribute("Sequence",String(S)),u.customActions.set(k,kn().serializeToString(D)))}for(const O of n.movedControls??[]){const S=p.get(O.id),k=S?b(S,O.id):null;if(!S||!k?.ca||!k.el){if(f.has(O.id))continue;throw new Error(`Can't move ${O.id}: it isn't in this table's unmanaged customizations.`)}const{ca:w,el:D}=k,F=O.controlsId??`${O.groupId}.Controls`;if(D.setAttribute("Sequence",String(O.sequence)),!k.nested)w.setAttribute("Location",`${F}._children`),w.setAttribute("Sequence",String(O.sequence));else if(D.parentElement?.getAttribute("Id")!==F){const X=Array.from(w.getElementsByTagName("Controls")).find(ne=>ne.getAttribute("Id")===F);if(D.parentNode.removeChild(D),X)X.appendChild(D);else{let ne=`${O.id}.CustomAction`;for(;u.customActions.has(`ca:${ne}`);)ne+="_";u.customActions.set(`ca:${ne}`,`<CustomAction Id="${Ar(ne)}" Location="${Ar(`${F}._children`)}" Sequence="${O.sequence}"><CommandUIDefinition>${d.serializeToString(D)}</CommandUIDefinition></CustomAction>`)}}u.customActions.set(S,d.serializeToString(w))}const y=new Set,x=new Set;for(const[O,S]of Array.from(u.customActions)){const k=Se(S);if(k.tagName==="HideCustomAction"){r.has(k.getAttribute("Location")??"")&&u.customActions.delete(O);continue}const w=ve(k,"CommandUIDefinition")?.firstElementChild??null,D=w?.getAttribute("Id");if(!w||!yt(k.getAttribute("Location")))continue;if(D&&l.has(D)&&!f.has(D)){u.customActions.delete(O);for(const X of S.matchAll(Fs))x.add(X[1]);for(const X of eo(w))y.add(X);continue}const F=Xo(w).filter(X=>{const ne=X.getAttribute("Id")??"";return l.has(ne)&&!f.has(ne)});if(F.length!==0){for(const X of F){const ne=d.serializeToString(X);for(const re of ne.matchAll(Fs))x.add(re[1]);for(const re of eo(X))y.add(re);X.parentNode?.removeChild(X)}u.customActions.set(O,d.serializeToString(k))}}const v=new Set,C=new Set(n.deletedContainerIds??[]),$=(O,S)=>{for(const k of mb(O))C.add(k);for(const k of eo(O))y.add(k);for(const k of[O,...Array.from(O.getElementsByTagName("Tab"))]){const w=k.tagName==="Tab"?k.getAttribute("Command"):null;w&&v.add(w)}for(const k of S.matchAll(Fs))x.add(k[1])};for(let O=C.size>0;O;){O=!1;for(const[S,k]of Array.from(u.customActions)){const w=Se(k),D=w.getAttribute("Location");if(w.tagName==="HideCustomAction"){D&&C.has(D)&&(u.customActions.delete(S),O=!0);continue}const F=ve(w,"CommandUIDefinition")?.firstElementChild??null,X=F?.getAttribute("Id")??null,ne=fb(D);if(!!X&&C.has(X)&&yt(D)||!!ne&&C.has(ne)||!yt(D)&&!!D&&C.has(D)||!!F?.getAttribute("GroupId")&&C.has(F.getAttribute("GroupId"))){u.customActions.delete(S),F&&$(F,k),O=!0;continue}if(F?.tagName!=="Tab")continue;const le=Array.from(F.getElementsByTagName("*")).filter(_=>_.tagName==="Group"?C.has(_.getAttribute("Id")??""):(_.tagName==="MaxSize"||_.tagName==="Scale")&&C.has(_.getAttribute("GroupId")??""));if(le.length!==0){for(const _ of le)$(_,d.serializeToString(_)),_.parentNode?.removeChild(_);u.customActions.set(S,d.serializeToString(w)),O=!0}}}const A=new Set;for(const[O,S]of u.customActions)e.customActions.get(O)!==S&&A.add(O);u.customActions=Yc(u.customActions,A);const j=(O,S)=>{for(const[k,w]of t[O])e[O].has(k)&&!S.has(k)||u[O].set(k,w)};j("commandDefinitions",o),j("enableRules",s),j("displayRules",i);const T=Mr(u.customActions.values());for(const O of y){if(c.has(O)||!u.commandDefinitions.has(O)||T.has(O))continue;const S=u.commandDefinitions.get(O);u.commandDefinitions.delete(O);const k=$o([S]),w=$o(u.commandDefinitions.values());for(const D of k.EnableRule)w.EnableRule.has(D)||u.enableRules.delete(D);for(const D of k.DisplayRule)w.DisplayRule.has(D)||u.displayRules.delete(D)}const R={EnableRule:new Set(n.retainedEnableRuleIds??[]),DisplayRule:new Set(n.retainedDisplayRuleIds??[])},I=Zc(u);for(const O of n.uncustomisedCommandIds??[]){const S=u.commandDefinitions.get(O);if(S===void 0||t.commandDefinitions.has(O)||!Ta(O,I))continue;u.commandDefinitions.delete(O);const k=$o(u.commandDefinitions.values()),w=$o([S]);for(const D of["EnableRule","DisplayRule"])for(const F of w[D]){const X=D==="EnableRule"?u.enableRules:u.displayRules;(D==="EnableRule"?t.enableRules:t.displayRules).has(F)||R[D].has(F)||k[D].has(F)||X.delete(F)}}for(const[O,S]of t.tabDisplayRules)u.tabDisplayRules.set(O,S);for(const[O,S]of t.templates)u.templates.set(O,S);const N=gb(u.customActions.values());for(const O of x)!t.locLabels.has(O)&&!N.has(O)&&u.locLabels.delete(O);const B=Mr(u.customActions.values());for(const O of v)!t.tabDisplayRules.has(O)&&!B.has(O)&&u.tabDisplayRules.delete(O);for(const O of n.removedTabCommands??[])t.tabDisplayRules.has(O)||u.tabDisplayRules.delete(O);for(const[O,S]of t.locLabels){if(e.locLabels.get(O)){const w=Array.from(Se(S).querySelectorAll("Title")).map(D=>D.getAttribute("description"));if(w.length>0&&w.every(D=>D===O))continue}u.locLabels.set(O,S)}return u}function nI(e,t,n){const o=$a(e,Bn());for(const[s,i]of o.customActions){const l=Se(i);if(l.tagName!=="CustomAction"||!yt(l.getAttribute("Location")))continue;const r=ve(l,"CommandUIDefinition")?.firstElementChild;if(!co(r))continue;const c=Kc(r,t);if(!(!c||!co(c))){c.setAttribute("Title",n),o.customActions.set(s,kn().serializeToString(l));break}}return o}function Na(e){const t=[],n=(o,s,i)=>({id:o.getAttribute("Id")??"",kind:o.tagName,groupId:o.getAttribute("GroupId")??"",sequence:Number(o.getAttribute("Sequence")??"0"),size:o.getAttribute("Size")??"",tabId:s,key:i});for(const[o,s]of e.customActions){const i=Se(s);if(i.tagName!=="CustomAction")continue;const l=ve(i,"CommandUIDefinition")?.firstElementChild;if(!l)continue;const r=/^(.+)\.Scaling\._children$/.exec(i.getAttribute("Location")??"");if(r&&(l.tagName==="MaxSize"||l.tagName==="Scale")&&t.push(n(l,r[1],o)),l.tagName==="Tab"&&yt(i.getAttribute("Location"))){const c=l.getAttribute("Id")??"";for(const d of Array.from(ve(l,"Scaling")?.children??[]))(d.tagName==="MaxSize"||d.tagName==="Scale")&&t.push(n(d,c,o))}}return t}function oI(e,t){const n=Na(e),o=new Map;for(const c of n)o.set(c.tabId,[...o.get(c.tabId)??[],c]);const s=[],i=[];for(const[c,d]of o){const u=Hc(c,t[c]??{maxSizes:[],scales:[]},d);s.push(...u.changes),i.push(...u.problems)}if(s.length===0)return{parts:e,changes:s,problems:i};const l=$a(e,Bn()),r=kn();for(const c of s){const d=n.find(g=>g.id===c.id&&g.kind===c.kind&&g.tabId===c.tabId),u=Se(l.customActions.get(d.key)),p=ve(u,"CommandUIDefinition").firstElementChild;(p.tagName==="Tab"?Array.from(ve(p,"Scaling")?.children??[]).find(g=>g.tagName===c.kind&&g.getAttribute("Id")===c.id):p)?.setAttribute("Sequence",String(c.to)),p.tagName!=="Tab"&&u.setAttribute("Sequence",String(c.to)),l.customActions.set(d.key,r.serializeToString(u))}return{parts:l,changes:s,problems:i}}function bb(e,t){const n=new Map;for(const s of t.customActions.values()){const i=Se(s);if(i.tagName!=="CustomAction"||!yt(i.getAttribute("Location")))continue;const l=ve(i,"CommandUIDefinition")?.firstElementChild;if(co(l))for(const r of[l,...Array.from(l.getElementsByTagName("Group"))]){const c=r.getAttribute("Id"),d=r.getAttribute("Title");c&&d?.startsWith("$LocLabels:")&&n.set(c,d)}}for(const s of e.tabs){const i=n.get(s.id);i&&(s.label=i);for(const l of s.groups){const r=n.get(l.id);r&&(l.label=r)}}const o=new Set(e.tabs.map(s=>s.id));for(const s of Na(t)){if(!o.has(s.tabId))continue;e.scalingByTab=e.scalingByTab??{};const i=e.scalingByTab[s.tabId]=e.scalingByTab[s.tabId]??{tabId:s.tabId,maxSizes:[],scales:[]},l=s.kind==="MaxSize"?i.maxSizes:i.scales,r={id:s.id,groupId:s.groupId,size:s.size,sequence:s.sequence},c=l.findIndex(d=>d.id===s.id);c>=0?l[c]=r:l.push(r)}}function Ge(e,t,n=1033){if(!e)return"";const o=e.match(/^\$LocLabels:(.+)$/);if(o){const i=o[1],l=t.find(r=>r.id===i);if(l){const r=l.titles.find(u=>u.languageCode===n),c=l.titles.find(u=>u.languageCode===1033),d=l.titles[0];return r?.description??c?.description??d?.description??i}return i}const s=e.match(/^\$Resources(?:\([^)]*\))?:(.+)$/);return s?s[1]:e}function to(e){return!!e&&/^\$Resources(\([^)]*\))?:/.test(e)}function Qc(e){return`$LocLabels:${e}`}function ed(e){const t=e.match(/^\$LocLabels:(.+)$/);return t?t[1]:null}const Dr=128;function gs(e,t){const n=`${e}.${t}`;if(n.length<=Dr)return n;const o=yb(e),s=Dr-t.length-o.length-2;return`${e.slice(0,s)}_${o}.${t}`}function yb(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 bs(e){return gs(e,"LabelText")}function ys(e){return gs(e,"ToolTipTitle")}function xs(e){return gs(e,"ToolTipDescription")}function xb(e){return gs(e,"Title")}function vb(e,t){const n=(o,s)=>(o?ed(o):null)??s;return{label:n(t?.labelToken,bs(e)),tooltipTitle:n(t?.tooltipTitleToken,ys(e)),tooltipBody:n(t?.tooltipBodyToken,xs(e))}}function sI(e,t,n,o,s=1033){const i=e?ed(e):null;return i?o.some(l=>l.id===i)?i:(n??"")===Ge(e,[...o],s)?null:t:t}function Sb(e,t,n=1033){const o=new Set(Object.values(vb(e.id,e.source))),s=new Set;for(const i of t)o.has(i.id)&&i.titles.forEach(l=>s.add(l.languageCode));return[...s].sort((i,l)=>i===n?-1:l===n?1:i-l)}const Vt={HomepageGrid:{label:"Main grid",title:"Main grid",body:"The command bar above the table's full-page list of records. Unified Interface shows this ribbon as one flat bar: tabs, group layout and scaling are ignored, and commands that don't fit move under More commands (⋮).",ribbonId:"Mscrm.HomepageGrid.{table}"},Form:{label:"Main form",title:"Main form",body:"The command bar at the top of the table's main form. Unified Interface shows it as one flat bar: tab layout and scaling are ignored, but button visibility and command actions work as configured, as in Ribbon Workbench. Microsoft doesn't support the tabbed ribbon on Unified Interface.",ribbonId:"Mscrm.Form.{table}"},SubGrid:{label:"Sub-grid",title:"Sub-grid",body:"The command bar on this table's sub-grids on other tables' forms, and on the Related tab's associated view. A sub-grid has room for only a few commands before More commands. Of the built-in controls, only Add, Show List and Delete are supported, and their icons can't be changed.",ribbonId:"Mscrm.SubGrid.{table}"},Application:{label:"Application",title:"Application ribbon",body:"Changes here apply to every table. Buttons on GlobalTab appear in the global command bar at the top of every page. Built-in GlobalTab buttons are read-only.",ribbonId:"Application ribbon"}};function wb(e,t){return Vt[e].ribbonId.replace("{table}",t||"<table>")}function Cb(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 Cn=e=>e==="flyout"||e==="splitButton",ka=["button","flyout"],td=e=>["true","1"].includes(e?.trim().toLowerCase()??"");function dn(e){const t=[];for(const n of e.menu?.sections??[])for(const o of n.controls)t.push(o),t.push(...dn(o));return t}function nd(e){return e.flatMap(t=>[t,...dn(t)])}function Te(e){return nd(e.buttons)}function Ib(e,t){const n=[];for(const o of Object.keys(e))for(const s of e[o].tabs)for(const i of s.groups)for(const l of Te(i))l.commandId===t&&n.push({location:o,tab:s,group:i,button:l});return n}function od(e,t,n,o,s){const i=[];for(const{location:l,button:r}of Ib(e,t))if(r.id!==n){const c=s&&l!==s?` (${Vt[l].label.toLowerCase()})`:"",d=(o(r)||r.id)+c;i.includes(d)||i.push(d)}return i}function vs(e,t){for(const n of e)for(const o of n.menu?.sections??[]){const s=o.controls.findIndex(l=>l.id===t);if(s>=0)return{parent:n,section:o,index:s};const i=vs(o.controls,t);if(i)return i}}function Yo(e,t){if(!e.buttons.some(n=>n.id===t))return vs(e.buttons,t)}function Ss(e,t){if(!e||!t)return;const n=e.buttons.find(s=>s.id===t);if(n)return n;const o=vs(e.buttons,t);return o?.section.controls[o.index]}function jb(e,t){if(!(!e||!t))return e.buttons.find(n=>n.id===t||dn(n).some(o=>o.id===t))}function sd(e,t){const n=vs(e.buttons,t);return n?(n.section.controls.splice(n.index,1),!0):!1}function _s(e){return{id:`${e}.Menu`,sections:[Ai(e,[])]}}function Ai(e,t,n){let o=t.length+1;const s=new Set(t.map(l=>l.id));for(;s.has(`${e}.MenuSection${o}`);)o++;const i=`${e}.MenuSection${o}`;return{id:i,title:n,sequence:o*10,displayMode:"Menu16",controlsId:`${i}.Controls`,controls:[]}}function Rb(e,t,n,o){if(!e)return;const s=new Set,i=new Map,l=c=>{const d=i.get(c);if(d)return d;let u=c.startsWith(t)?`${n}${c.slice(t.length)}`:`${n}.${c.split(".").pop()||"Item"}`;for(let p=2;s.has(u);p++)u=`${u.replace(/_\d+$/,"")}_${p}`;return s.add(u),i.set(c,u),u},r=c=>c.replace(/(\sId=")([^"]*)(")/g,(d,u,p,m)=>`${u}${l(p)}${m}`);return{...e,id:l(e.id),sections:e.sections.map(c=>({...c,id:l(c.id),controlsId:l(c.controlsId),controls:c.controls.map(d=>Jo(d,l(d.id),o)),...c.rawControls?{rawControls:c.rawControls.map(d=>({...d,xml:r(d.xml)}))}:{},...c.rawContent!==void 0?{rawContent:r(c.rawContent)}:{}}))}}function $b(e,t,n){return e.replace(/(\s(?:Id|InitialItem)=")([^"]*)(")/g,(o,s,i,l)=>`${s}${i.startsWith(t)?`${n}${i.slice(t.length)}`:`${n}.${i}`}${l}`)}const Tb=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand"];function no(e,t){return!!t&&!!e?.startsWith("$LocLabels:")&&!t.has(e.slice(11))}function Jo(e,t,n){const o=Tb.filter(u=>e.source?.attributes[u]!==void 0),s=Cb(e.source),i={...s?.attributes??{},...Object.fromEntries(o.map(u=>[u,e.source.attributes[u]]))},l=u=>to(u)||no(u,n)?u:void 0,r={labelToken:l(e.source?.labelToken),tooltipTitleToken:l(e.source?.tooltipTitleToken),tooltipBodyToken:l(e.source?.tooltipBodyToken)},c=Object.fromEntries(Object.entries(r).filter(([,u])=>u!==void 0)),d=e.source?.xml?$b(e.source.xml,e.id,t):void 0;return{...e,id:t,source:Object.keys(i).length+Object.keys(c).length>0||d?{...s?.modernImage?{modernImage:s.modernImage}:{},...c,attributes:i,...d?{xml:d}:{}}:void 0,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0,menu:Rb(e.menu,e.id,t,n)}}const Nb=["label","icon","image16","image32","tooltipTitle","tooltipBody","commandId","templateAlias"];function Oi(e,t){for(const n of Nb)if((e[n]??"")!==(t[n]??""))return!0;return!1}function It(e){const t=new Map,n=new Map,o=(s,i,l,r)=>{const c=n.get(s.id)??0;n.set(s.id,c+1);const d=`${s.id}#${c}`;t.set(d,r?{button:s,groupId:i,tabId:l,menu:r}:{button:s,groupId:i,tabId:l});for(const u of s.menu?.sections??[])for(const p of u.controls)o(p,i,l,{parentKey:d,parentId:s.id,sectionId:u.id,controlsId:u.controlsId})};for(const s of e.tabs)for(const i of s.groups)for(const l of i.buttons)o(l,i.id,s.id);return t}function Aa(e,t){const n=It(t),o=It(e),s=l=>{for(let r=l.menu?.parentKey;r;r=o.get(r)?.menu?.parentKey)if(!n.has(r))return!0;return!1},i=[];for(const[l,r]of o){const c=n.get(l)?.button,d=r.button;if(s(r)){d.hidden&&i.push({entry:r,change:"hide"});continue}c?d.hidden&&!c.hidden?i.push({entry:r,change:"hide"}):Oi(c,d)&&i.push({entry:r,change:"override"}):(d.hidden&&(d.oob||d.managed)||i.push({entry:r,change:"new"}),d.hidden&&i.push({entry:r,change:"hide"}))}return i}function id(e){return e.commandId||`${e.id}.Command`}function kb(e,t){return e==="SubGrid"?`Mscrm.SubGrid.${t}.ContextualTabs._children`:"Mscrm.Tabs._children"}function ad(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 Ab(e,t,n){const o=id(e),s=(e.tabDisplayRules??[]).map(i=>({...i,tabCommand:i.tabCommand||o}));return{...e,commandId:o,tabDisplayRules:s.length>0?s:ad(t,n,o)}}function iI(e){const{current:t,baseline:n,commands:o,enableRules:s,displayRules:i,locLabels:l}=e,r=e.languageCode??1033,c=e.location==="Application",d=new Set,u=new Set;for(const L of n.tabs){d.add(L.id);for(const U of L.groups)u.add(U.id)}const p=It(n),m=new Map;for(const[L,U]of It(t))m.set(U.button,p.get(L)?.button);const g=t.tabs.filter(L=>!d.has(L.id)).map(L=>Ab(L,e.location,e.entityLogicalName)),b=[],f=[],y=[],x=[],v=[],C=L=>v.push(L),$=[],A=L=>{const U=[];for(const W of L.buttons)W.hidden||m.get(W)||(U.push(ws(W,l,C,r,!0)),$.push(W,...dn(W)));return U},j=new Set,T=ld(t,n).steps;for(const L of g){const U=new Map(L.groups.map(W=>[W.id,A(W)]));for(const W of L.groups)for(const te of W.buttons)!te.hidden&&!m.get(te)&&j.add(te);b.push(Fb(L,t.scalingByTab?.[L.id],kb(e.location,e.entityLogicalName),U,T,C,r,l))}const R=[];for(const L of t.tabs)if(d.has(L.id)){for(const U of L.groups)if(!u.has(U.id)){for(const te of U.buttons)!te.hidden&&!m.get(te)&&j.add(te);f.push(Pb(U,L.id,A(U),C,r,l));const W=T.get(U.id);W&&R.push(Di(L.id,"MaxSize",W))}}f.push(...R);for(const{entry:L,change:U}of Aa(t,n)){const{button:W,groupId:te,menu:P}=L;if(!j.has(W))if(U==="hide")x.push(zb(W));else if(U==="new"){const Q=P?`${P.controlsId}._children`:`${te}.Controls._children`;y.push(Bb(W,Q,l,C,r)),$.push(W,...dn(W))}else y.push(Lb(W,l,C,r)),$.push(W)}const I=new Set;for(const L of $)for(const U of _c(L))I.add(U);for(const L of t.tabs)for(const U of L.groups){const W=U.source?.attributes.Command;W&&!u.has(U.id)&&I.add(W)}const N=[];for(const L of g){const U=L.commandId;I.add(U),o.some(W=>W.id===U)||N.push({id:U,enableRules:[],displayRules:[],actions:[]})}const B=[...o.filter(L=>I.has(L.id)&&(!Hs(L.id)||L.actions.length>0)),...N],O=new Set,S=new Set;for(const L of B)L.enableRules.forEach(U=>O.add(U)),L.displayRules.forEach(U=>S.add(U));const k=s.filter(L=>O.has(L.id)&&!Hs(L.id)),w=i.filter(L=>S.has(L.id)&&!Hs(L.id)),D=Xb(v),F=B.map(Jb).join(`
|
|
33
|
+
`),X=k.map(Zb).join(`
|
|
34
|
+
`),ne=w.map(Qb).join(`
|
|
35
|
+
`),re=D.map(ey).join(`
|
|
36
|
+
`),le=[...b,...f,...Mb(t,n,d),...y,...x],_=g.filter(L=>L.tabDisplayRules.length>0).map(L=>ty(L,c)).filter(Boolean).join(`
|
|
37
|
+
`);return`<RibbonDiffXml>
|
|
38
|
+
<CustomActions>
|
|
39
|
+
${le.join(`
|
|
40
|
+
`)}
|
|
41
|
+
</CustomActions>
|
|
42
|
+
<Templates><RibbonTemplates Id="Mscrm.Templates"/></Templates>
|
|
43
|
+
<CommandDefinitions>
|
|
44
|
+
${F}
|
|
45
|
+
</CommandDefinitions>
|
|
46
|
+
<RuleDefinitions>
|
|
47
|
+
<TabDisplayRules>
|
|
48
|
+
${_}
|
|
49
|
+
</TabDisplayRules>
|
|
50
|
+
<DisplayRules>
|
|
51
|
+
${ne}
|
|
52
|
+
</DisplayRules>
|
|
53
|
+
<EnableRules>
|
|
54
|
+
${X}
|
|
55
|
+
</EnableRules>
|
|
56
|
+
</RuleDefinitions>
|
|
57
|
+
<LocLabels>
|
|
58
|
+
${re}
|
|
59
|
+
</LocLabels>
|
|
60
|
+
</RibbonDiffXml>`}function Ob(e,t){const n=new Set,o=new Set;for(const b of t.tabs){n.add(b.id);for(const f of b.groups)o.add(f.id)}let s=0,i=0,l=0,r=0,c=0,d=0;for(const b of e.tabs){n.has(b.id)||r++,b.tabDisplayRules&&b.tabDisplayRules.length>0&&(d+=b.tabDisplayRules.length);for(const f of b.groups)!o.has(f.id)&&n.has(b.id)&&c++}for(const{change:b}of Aa(e,t))b==="hide"?l++:b==="new"?s++:i++;const u=e.scalingByTab??{},p=t.scalingByTab??{};let m=0;for(const[b,f]of Object.entries(u))JSON.stringify(f)!==JSON.stringify(p[b])&&m++;const g=s+i+l+r+c+m>0;return{newButtons:s,overriddenButtons:i,hiddenButtons:l,newTabs:r,newGroups:c,scalingChanges:m,tabDisplayRules:d,hasAnyChange:g}}function Mb(e,t,n){const o=[],s=[];for(const[i,l]of Object.entries(e.scalingByTab??{})){if(!n.has(i))continue;const r=t.scalingByTab?.[i],c=(d,u)=>u?.some(p=>JSON.stringify(p)===JSON.stringify(d))??!1;for(const d of l.maxSizes)c(d,r?.maxSizes)||o.push(Di(i,"MaxSize",d));for(const d of l.scales)c(d,r?.scales)||s.push(Di(i,"Scale",d))}return[...o,...s]}function Mi(e,t){const n=e==="Scale"&&t.popupSize?` PopupSize="${he(t.popupSize)}"`:"";return`<${e} Id="${he(t.id)}" GroupId="${he(t.groupId)}" Sequence="${t.sequence}" Size="${he(t.size)}"${n}/>`}function Di(e,t,n){return`<CustomAction Id="${he(n.id)}.CustomAction"
|
|
61
|
+
Location="${he(e)}.Scaling._children"
|
|
62
|
+
Sequence="${n.sequence}">
|
|
63
|
+
<CommandUIDefinition>
|
|
64
|
+
${Mi(t,n)}
|
|
65
|
+
</CommandUIDefinition>
|
|
66
|
+
</CustomAction>`}const rd={"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"},Db=Object.keys(rd);function Eb(e){return rd[Oa(e.template)]}function ld(e,t){const n=new Map,o=[],s=new Set(t.tabs.map(l=>l.id)),i=new Set(t.tabs.flatMap(l=>l.groups.map(r=>r.id)));for(const l of e.tabs){const r=!s.has(l.id),c=e.scalingByTab?.[l.id],d=(c?.maxSizes??[]).map(g=>g.sequence),u=(c?.scales??[]).map(g=>g.sequence),p=new Set([...d,...u]);if(r&&p.size<d.length+u.length&&o.push(`The scaling of new tab ${l.id} uses a Sequence more than once — give every MaxSize and Scale its own`),r&&d.length>0)continue;const m=qc(d,u);for(const g of l.groups){if(!r&&i.has(g.id)||c?.maxSizes.some(y=>y.groupId===g.id))continue;const b=Eb(g);if(!b)continue;const f=Wc(m,p);if(f===void 0){o.push(`No free scaling position for the new group "${g.label}" (${g.id}) on tab ${l.id}: its MaxSize must come after the tab's last MaxSize (${m.after}) and before its first Scale (${m.before}), and no Sequence is free there`);continue}p.add(f),n.set(g.id,{id:`${g.id}.MaxSize`,groupId:g.id,size:b,sequence:f})}}return{steps:n,problems:o}}function Bb(e,t,n,o,s=1033){return`<CustomAction Id="${he(e.id)}.CustomAction"
|
|
67
|
+
Location="${he(t)}"
|
|
68
|
+
Sequence="${e.sequence}">
|
|
69
|
+
<CommandUIDefinition>
|
|
70
|
+
${ws(e,n,o,s,!0)}
|
|
71
|
+
</CommandUIDefinition>
|
|
72
|
+
</CustomAction>`}function Lb(e,t,n,o=1033){return`<CustomAction Id="${he(e.id)}.Override.CustomAction"
|
|
73
|
+
Location="${he(e.id)}"
|
|
74
|
+
Sequence="${e.sequence}">
|
|
75
|
+
<CommandUIDefinition>
|
|
76
|
+
${ws(e,t,n,o)}
|
|
77
|
+
</CommandUIDefinition>
|
|
78
|
+
</CustomAction>`}function zb(e,t){return`<HideCustomAction HideActionId="${he(e.id)}.HideAction"
|
|
79
|
+
Location="${he(e.id)}"/>`}function Pb(e,t,n,o,s=1033,i=[]){return`<CustomAction Id="${he(e.id)}.CustomAction"
|
|
80
|
+
Location="${he(t)}.Groups._children"
|
|
81
|
+
Sequence="${e.sequence}">
|
|
82
|
+
<CommandUIDefinition>
|
|
83
|
+
${cd(e,o,n,s,i)}
|
|
84
|
+
</CommandUIDefinition>
|
|
85
|
+
</CustomAction>`}function Fb(e,t,n,o,s,i,l=1033,r=[]){const c=dd(e,i,l,r),d=e.commandId?` Command="${he(e.commandId)}"`:"",u=e.groups.map(b=>cd(b,i,o.get(b.id)??[],l,r)).join(`
|
|
86
|
+
`),m=[...(t?.maxSizes.length?t.maxSizes:e.groups.map(b=>s.get(b.id)).filter(b=>!!b)).map(b=>Mi("MaxSize",b)),...(t?.scales??[]).map(b=>Mi("Scale",b))],g=m.length===0?`<Scaling Id="${he(e.id)}.Scaling"/>`:`<Scaling Id="${he(e.id)}.Scaling">
|
|
87
|
+
${m.join(`
|
|
88
|
+
`)}
|
|
89
|
+
</Scaling>`;return`<CustomAction Id="${he(e.id)}.CustomAction"
|
|
90
|
+
Location="${he(n)}"
|
|
91
|
+
Sequence="${e.sequence}">
|
|
92
|
+
<CommandUIDefinition>
|
|
93
|
+
<Tab Id="${he(e.id)}"${d} Title="${he(c)}"${ud(e,r,i)} Sequence="${e.sequence}"${md(e)}>
|
|
94
|
+
${g}
|
|
95
|
+
<Groups Id="${he(e.id)}.Groups">
|
|
96
|
+
${u}
|
|
97
|
+
</Groups>
|
|
98
|
+
</Tab>
|
|
99
|
+
</CommandUIDefinition>
|
|
100
|
+
</CustomAction>`}function cd(e,t,n=[],o=1033,s=[]){const i=dd(e,t,o,s),l=Oa(e.template),r=n.length===0?`<Controls Id="${he(e.id)}.Controls"/>`:`<Controls Id="${he(e.id)}.Controls">
|
|
101
|
+
${n.join(`
|
|
102
|
+
`)}
|
|
103
|
+
</Controls>`;return`<Group Id="${he(e.id)}" Title="${he(i)}"${ud(e,s,t)} Sequence="${e.sequence}" Template="${he(l)}"${md(e)}>
|
|
104
|
+
${r}
|
|
105
|
+
</Group>`}function dd(e,t,n,o){const s=`${e.id}.Title`;if(e.source&&e.label){const i=oo(e.label,e.source.titleToken,s,o,t,n);if(i)return i}return t({id:s,titles:[{languageCode:n,description:e.label}]}),Qc(s)}function ud(e,t,n){const o=e.description,s=o?.startsWith("$LocLabels:")?t.find(i=>i.id===o.slice(11)):void 0;return s&&n(s),ee("Description",o)}const _b=new Set(["Id","Command","Title","Description","Sequence","Template"]);function md(e){const t="buttons"in e;return Object.entries(e.source?.attributes??{}).filter(([n])=>t&&n==="Command"||!_b.has(n)).filter(([n])=>!Ma.has(n)).map(([n,o])=>` ${n}="${he(o)}"`).join("")}function Oa(e){const t=e?.trim();return t?t.includes(".")?t:`Mscrm.Templates.${t}`:"Mscrm.Templates.Flexible2"}function qb(e,t,n,o,s=1033){const i=e??"";if(i.startsWith("$LocLabels:")){const c=i.slice(11),d=n.find(u=>u.id===c);return d&&o(d),i}if(to(i))return i;const l=[{languageCode:s,description:i}],r=n.find(c=>c.id===t);if(r)for(const c of r.titles)c.languageCode!==s&&l.push(c);return o({id:t,titles:l}),Qc(t)}const Wb=["ToolTipTitle","ToolTipDescription","ToolTipHelpKeyWord","ToolTipShortcutKey","ToolTipImage32by32","ToolTipImage32by32Class","ToolTipImage32by32Left","ToolTipImage32by32Top"],qs=["Image16by16","Image16by16Class","Image16by16Left","Image16by16Top","Image32by32","Image32by32Class","Image32by32Left","Image32by32Top","ModernImage"],fn=["Id","Command","Sequence","TemplateAlias",...Wb],Ws=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand","CacheMenuVersions"],Hb={Button:new Set([...fn,...qs,"Alt","CommandType","CommandValueId","Description","LabelCss","LabelText","MenuItemId","ModernCommandType","Priority"]),FlyoutAnchor:new Set([...fn,...qs,...Ws,"Alt","CommandMenuClose","CommandType","LabelText","ModernCommandType","ToolTipSelectedItemTitle"]),SplitButton:new Set([...fn,...qs,...Ws,"Alt","CommandMenuClose","CommandMenuOpen","CommandType","LabelText","MenuAlt","MenuCommand","ToolTipSelectedItemTitle"]),CheckBox:new Set([...fn,"Alt","LabelText","MenuItemId","QueryCommand"]),TextBox:new Set([...fn,"ImeEnabled","MaxLength","QueryCommand","ShowAsLabel","Width"]),ComboBox:new Set([...fn,...Ws,"AllowFreeForm","Alt","AltArrow","AutoComplete","AutoCompleteDelay","CommandMenuClose","CommandMenuOpen","CommandPreview","CommandPreviewRevert","ImeEnabled","InitialItem","QueryCommand","ToolTipSelectedItemTitle","Width"])},Ma=new Set(["SolutionUniqueName"]);function Gb(e){if(e)return e.includes("_")?e.toLowerCase():e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function oo(e,t,n,o,s,i=1033){if(t!==void 0&&(e??"")===Ge(t,o,i)){if(t.startsWith("$LocLabels:")){const c=o.find(d=>d.id===t.slice(11));c&&s(c)}return t}if(!e)return;const l=t?.startsWith("$LocLabels:")?t.slice(11):void 0,r=l&&o.some(c=>c.id===l)?l:n;return qb(e,r,o,s,i)}function Da(e){const t=e.source,n=r=>!!r?.startsWith("$webresource:"),o=r=>r&&!r.startsWith("/")&&/[/.]/.test(r)?Ea(r):r,s=o(e.image32),i=o(e.image16),l=[[e.image32,s,"Image32by32"],[e.image16,i,"Image16by16"]].filter(([r,c,d])=>n(c)&&r!==t?.attributes[d]).map(([,r])=>r);return t&&Gb(t.modernImage)===e.icon&&l.length===0?t.modernImage:l[0]??[s,i,e.icon].find(n)}function ws(e,t,n,o=1033,s=!1){const i=Kb(e.kind),l=e.source;if(l?.xml&&dt(e.kind))return Yb(e,l.xml,t,n);const r=new Map;for(const[b,f]of Object.entries(l?.attributes??{}))Ma.has(b)||r.set(b,f);const c=(b,f)=>f===void 0||f===""?r.delete(b):r.set(b,f);c("Id",e.id),c("Command",e.commandId||void 0),c("LabelText",oo(e.label,l?.labelToken,bs(e.id),t,n,o)??""),r.has("LabelText")||r.set("LabelText",""),c("ToolTipTitle",oo(e.tooltipTitle,l?.tooltipTitleToken,ys(e.id),t,n,o)),c("ToolTipDescription",oo(e.tooltipBody,l?.tooltipBodyToken,xs(e.id),t,n,o)),c("TemplateAlias",e.templateAlias),c("Sequence",l&&!("Sequence"in l.attributes)&&e.sequence===0?void 0:String(e.sequence));const d=b=>!!b&&(b.startsWith("$webresource:")||b.includes("/")||b.includes(".")),u=b=>d(b)?Ea(b):void 0;c("ModernImage",Da(e)),c("Image16by16",u(e.image16)),c("Image32by32",u(e.image32));const p=Hb[i];if(p)for(const b of[...r.keys()])p.has(b)||r.delete(b);const m=Array.from(r.entries()).map(([b,f])=>`${b}="${he(f)}"`).join(" "),g=s&&e.menu&&Ub.has(i)?Vb(e.menu,t,n,o):"";return g?`<${i} ${m}>${g}</${i}>`:`<${i} ${m}/>`}const Ub=new Set(["FlyoutAnchor","SplitButton","ComboBox"]);function Vb(e,t,n,o){const s=e.sections.map(r=>{const c=new Map(Object.entries(r.attributes??{})),d=(g,b)=>b===void 0||b===""?c.delete(g):c.set(g,b);d("Id",r.id),d("Title",oo(r.title,r.attributes?.Title,xb(r.id),t,n,o));const u=!!r.attributes&&!("Sequence"in r.attributes)&&r.sequence===0;d("Sequence",u?void 0:String(r.sequence)),d("DisplayMode",r.displayMode);const p=Array.from(c.entries()).map(([g,b])=>` ${g}="${he(b)}"`).join("");if(r.rawContent!==void 0)return`<MenuSection${p}>${r.rawContent}</MenuSection>`;const m=r.controls.map(g=>ws(g,t,n,o,!0));for(const g of[...r.rawControls??[]].sort((b,f)=>b.index-f.index))m.splice(Math.min(g.index,m.length),0,g.xml);return`<MenuSection${p}><Controls Id="${he(r.controlsId)}">${m.join("")}</Controls></MenuSection>`}),i=new Map(Object.entries(e.attributes??{}));return i.set("Id",e.id),`<Menu${Array.from(i.entries()).map(([r,c])=>` ${r}="${he(c)}"`).join("")}>${s.join("")}</Menu>`}function Hs(e){return/^(Mscrm|Microsoft)\./.test(e)}function Xb(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 Kb(e){return wn[e]??"Button"}function Yb(e,t,n,o){const s=new DOMParser().parseFromString(t,"application/xml").documentElement;for(const l of[s,...Array.from(s.getElementsByTagName("*"))])for(const r of Ma)l.removeAttribute(r);s.setAttribute("Id",e.id),(s.hasAttribute("Sequence")||e.sequence!==0)&&s.setAttribute("Sequence",String(e.sequence));const i=new XMLSerializer().serializeToString(s);for(const l of i.matchAll(/\$LocLabels:([^"'\s<]+)/g)){const r=n.find(c=>c.id===l[1]);r&&o(r)}return i}function Ea(e){const t=(e??"").trim();if(!t||/^\$webresource:/i.test(t)||/^https?:\/\//i.test(t))return t;const n=t.match(/^\/?WebResources\/(.+)$/i);return n?`$webresource:${n[1]}`:t.startsWith("/")||t.startsWith(".")?t:`$webresource:${t}`}function pd(e){const t=(e??"").trim();return t.startsWith("/")?t:Ea(t)}function ee(e,t){return t===void 0?"":` ${e}="${he(String(t))}"`}function jt(e,t,n,o){return n.length===0?`<${e}${t}/>`:`<${e}${t}>
|
|
106
|
+
${n.map(s=>`${o} ${s}`).join(`
|
|
107
|
+
`)}
|
|
108
|
+
${o}</${e}>`}function fd(e,t=" "){switch(e.kind){case"javascript":return jt("JavaScriptFunction",`${ee("FunctionName",e.functionName)}${ee("Library",pd(e.library))}`,e.params.map(n=>Ei(n,!1)),t);case"url":return jt("Url",`${ee("Address",e.address)}${ee("PassParams",e.passParams)}${ee("WinMode",e.winMode)}${ee("WinParams",e.winParams)}`,e.params.map(n=>Ei(n,!0)),t);case"outlookCommand":return`<OutlookCommand${ee("ActionType",e.actionType)}${ee("Data",e.data)}/>`;case"raw":return e.xml;default:return""}}function Jb(e){const t=" ",n=(l,r)=>{const c=[...r];for(const d of e.rawRuleRefs??[])d.container===l&&c.splice(Math.min(d.index,c.length),0,d.xml);return c},o=n("EnableRules",e.enableRules.map(l=>`<EnableRule Id="${he(l)}"/>`)),s=n("DisplayRules",e.displayRules.map(l=>`<DisplayRule Id="${he(l)}"/>`)),i=e.actions.map(l=>fd(l,`${t} `)).filter(Boolean);return`<CommandDefinition Id="${he(e.id)}">
|
|
109
|
+
${t} ${jt("EnableRules","",o,`${t} `)}
|
|
110
|
+
${t} ${jt("DisplayRules","",s,`${t} `)}
|
|
111
|
+
${t} ${jt("Actions","",i,`${t} `)}
|
|
112
|
+
${t}</CommandDefinition>`}function Ei(e,t){const n=t?ee("Name",e.name??""):"";switch(e.kind){case"CrmParameter":return`<CrmParameter${n}${ee("Value",e.value)}/>`;case"BoolParameter":return`<BoolParameter${n}${ee("Value",e.value)}/>`;case"IntParameter":return`<IntParameter${n}${ee("Value",e.value)}/>`;case"DecimalParameter":return`<DecimalParameter${n}${ee("Value",e.value)}/>`;case"StringParameter":return`<StringParameter${n}${ee("Value",e.value)}/>`}}function Zb(e){return jt("EnableRule",ee("Id",e.id),e.steps.map(t=>Cs(t," "))," ")}function Qb(e){return jt("DisplayRule",ee("Id",e.id),e.steps.map(t=>Cs(t," "))," ")}function Cs(e,t=""){if(e.kind==="RawRule")return e.xml;if(e.kind==="OrRule"){const s=e.groups.map(i=>jt("Or","",i.map(l=>Cs(l,`${t} `)),`${t} `));return jt("OrRule","",s,t)}const n=`${ee("Default",e.default)}${ee("InvertResult",e.invertResult)}`,o=(s,i)=>`<${s}${i}${n}/>`;switch(e.kind){case"SelectionCountRule":return o("SelectionCountRule",`${ee("AppliesTo",e.appliesTo)}${ee("Minimum",e.minimum)}${ee("Maximum",e.maximum)}`);case"EntityRule":return o("EntityRule",`${ee("EntityName",e.entityName)}${ee("AppliesTo",e.appliesTo)}${ee("Context",e.context)}`);case"FormStateRule":return o("FormStateRule",ee("State",e.state));case"CommandClientTypeRule":return o("CommandClientTypeRule",ee("Type",e.type));case"CrmClientTypeRule":return o("CrmClientTypeRule",ee("Type",e.type));case"CustomRule":return jt("CustomRule",`${ee("FunctionName",e.functionName)}${ee("Library",e.library===void 0?void 0:pd(e.library))}${n}`,(e.params??[]).map(s=>Ei(s,!1)),t);case"FeatureControlRule":return o("FeatureControlRule",`${ee("FeatureControlBit",e.featureControlBit)}${ee("ExpectedValue",e.expectedValue)}`);case"MiscellaneousPrivilegeRule":return o("MiscellaneousPrivilegeRule",`${ee("PrivilegeName",e.privilegeName)}${ee("PrivilegeDepth",e.privilegeDepth)}`);case"FormTypeRule":return o("FormTypeRule",ee("Type",e.type));case"ValueRule":return o("ValueRule",`${ee("Field",e.field)}${ee("Value",e.value)}`);case"SkuRule":return o("SkuRule",ee("Sku",e.sku));case"HideForTabletExperienceRule":return o("HideForTabletExperienceRule","");case"OrganizationSettingRule":return o("OrganizationSettingRule",ee("Setting",e.setting));case"EntityPrivilegeRule":return o("EntityPrivilegeRule",`${ee("PrivilegeType",e.privilegeType)}${ee("PrivilegeDepth",e.privilegeDepth)}${ee("AppliesTo",e.appliesTo)}${ee("EntityName",e.entityName)}`);case"EntityPropertyRule":return o("EntityPropertyRule",`${ee("EntityName",e.entityName)}${ee("AppliesTo",e.appliesTo)}${ee("PropertyName",e.propertyName)}${ee("PropertyValue",e.propertyValue)}`);case"DeviceTypeRule":return o("DeviceTypeRule",ee("Type",e.type));case"RelationshipTypeRule":return o("RelationshipTypeRule",`${ee("AppliesTo",e.appliesTo)}${ee("RelationshipType",e.relationshipType)}${ee("AllowCustomRelationship",e.allowCustomRelationship)}${ee("AllowSystemRelationship",e.allowSystemRelationship)}`);case"RecordPrivilegeRule":return o("RecordPrivilegeRule",`${ee("PrivilegeType",e.privilegeType)}${ee("AppliesTo",e.appliesTo)}`);case"FormEntityContextRule":return o("FormEntityContextRule",ee("EntityName",e.entityName));case"PageRule":return o("PageRule",ee("Address",e.address));case"ReferencingAttributeRequiredRule":return o("ReferencingAttributeRequiredRule","");case"OutlookItemTrackingRule":return o("OutlookItemTrackingRule",`${ee("TrackedInCrm",e.trackedInCrm)}${ee("AppliesTo",e.appliesTo)}`);case"OutlookRenderTypeRule":return o("OutlookRenderTypeRule",ee("Type",e.type));case"OutlookVersionRule":return o("OutlookVersionRule",ee("Version",e.version));case"CrmOfflineAccessStateRule":return o("CrmOfflineAccessStateRule",ee("State",e.state));case"CrmOutlookClientTypeRule":return o("CrmOutlookClientTypeRule",ee("Type",e.type));case"CrmOutlookClientVersionRule":return o("CrmOutlookClientVersionRule",`${ee("Major",e.major)}${ee("Minor",e.minor)}${ee("Build",e.build)}${ee("Revision",e.revision)}`);case"OptionSetRule":return o("OptionSetRule",`${ee("OptionSet",e.optionSet)}${ee("StateCode",e.stateCode)}${ee("ObjectTypeCode",e.objectTypeCode)}`);default:{const s=e;throw new Error(`Unknown rule kind: ${s.kind}`)}}}function ey(e){const t=e.titles.map(n=>`<Title languagecode="${n.languageCode}" description="${he(n.description)}"/>`).join(`
|
|
113
|
+
`);return`<LocLabel Id="${he(e.id)}">
|
|
114
|
+
<Titles>
|
|
115
|
+
${t}
|
|
116
|
+
</Titles>
|
|
117
|
+
</LocLabel>`}function ty(e,t){const n=new Map;for(const o of e.tabDisplayRules){const s=o.rules.map(i=>i.kind==="EntityRule"?`<EntityRule${ee("EntityName",i.entityName)}${ee("AppliesTo",i.appliesTo)}${ee("Context",i.context)}/>`:i.kind==="PageRule"&&t?`<PageRule${ee("Address",i.address)}/>`:"").filter(Boolean);n.set(o.tabCommand,[...n.get(o.tabCommand)??[],...s])}return[...n].filter(([,o])=>o.length>0).map(([o,s])=>`<TabDisplayRule TabCommand="${he(o)}">
|
|
118
|
+
${s.join(`
|
|
119
|
+
`)}
|
|
120
|
+
</TabDisplayRule>`).join(`
|
|
121
|
+
`)}function he(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function aI(e){const t=e.entities??[];return`<?xml version="1.0" encoding="utf-8"?>
|
|
122
|
+
<ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">${t.length===0?"":`
|
|
123
|
+
<Entities>
|
|
124
|
+
${t.map(o=>` <Entity>
|
|
125
|
+
<Name LocalizedName="${he(o.localizedName)}" OriginalName="${he(o.localizedName)}">${he(o.schemaName)}</Name>
|
|
126
|
+
${o.ribbonDiffXml}
|
|
127
|
+
</Entity>`).join(`
|
|
128
|
+
`)}
|
|
129
|
+
</Entities>`}
|
|
130
|
+
${e.applicationRibbonDiffXml??""}
|
|
131
|
+
</ImportExportXml>`}function Bi(e){return/^(Mscrm|Microsoft)\./.test(e)}function Zo(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 ny(e,t){return t?"unmanaged":Bi(e)?"oob":"unmanaged"}function Er(e,t){for(const n of e.tabs)for(const o of n.groups)for(const s of Te(o))t.has(s.id)?Zo(s,{origin:"unmanaged"}):s.origin==="unmanaged"&&Zo(s,{origin:"managed"})}function rn(e){return e.origin==="unmanaged"}function Ba(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob&&!n.custom}function Is(e,t){return gd(hd(t),[e])}function hd(e){const t=new Map;for(const n of e.tabs)for(const o of n.groups)for(const s of Te(o))t.set(s.id,(t.get(s.id)??!0)&&rn(s));return t}function gd(e,t){return nd(t).every(n=>e.get(n.id)??rn(n))}function Qo(e,t,n){return t?n?"has"in n?n.has(e):n.includes(e):!1:!0}function La(e,t,n){const o=t.tabs.some(s=>s.groups.some(i=>i.id===e.id));return Qo(e.id,o,n)&&gd(hd(t),e.buttons)}const Fo="Only tabs and groups your unmanaged customizations add (with a translatable title), or new ones, can be renamed";function Li(e,t,n,o){const s=e==="tab"?n.tabs.find(l=>l.id===t):new Map(n.tabs.flatMap(l=>l.groups.map(r=>[r.id,r]))).get(t);if(!s)return!0;if(!Qo(t,!0,o?.containerIds))return!1;const i=/^\$LocLabels:(.+)$/.exec(s.label??"")?.[1];return!!i&&Qo(i,!0,o?.locLabelIds)}function bd(e,t,n){const o=t.tabs.some(s=>s.id===e.id);return Qo(e.id,o,n)&&e.groups.every(s=>La(s,t,n))}function rI(e,t){const n=t.tabs.flatMap(l=>l.groups.flatMap(r=>Te(r))).filter(l=>l.id===e.id),o=n.find(l=>!rn(l)),s=o??n[0]??e,i=s.origin==="oob"?"the out-of-the-box ribbon":s.origin==="managed"?s.solutionName?`the managed solution "${s.solutionName}"`:"a managed solution":void 0;return o&&n.some(rn)?`The ribbon also places a button with this id from ${i??"another solution"}, and that one can't be deleted.`:i&&rn(e)?`It is your override of a button from ${i}: the original stays in the ribbon underneath it.`:i?`It comes from ${i}.`:rn(s)?"Its menu holds items from another solution.":"It comes from another solution."}function oy(e,t,n=new Set){if(t.size!==0)for(const o of Object.keys(e))for(const s of e[o].tabs)for(const i of s.groups)for(const l of Te(i)){const r=t.get(l.id);r&&!n.has(l.id)&&l.origin!=="oob"&&Zo(l,r)}}function js(e,t,n,o=[]){const i=new DOMParser().parseFromString(e,"application/xml"),l=i.querySelector("parsererror");if(l)throw new Error(`Ribbon XML parse error: ${l.textContent??"Unknown"}`);const r=sy(i),c=iy(i);ry(i,r);const d=new uy,u=my(i,d),p=fy(i,d),m=hy(i,d);d.flush();const g=[...yy(i)];for(const x of o)g.some(v=>v.id===x.id)||g.push(x);const b=new Set,f=new Set;i.querySelectorAll("CustomAction").forEach(x=>{const v=x.querySelector("CommandUIDefinition");if(v?.firstElementChild){const C=v.firstElementChild.getAttribute("Id")??"";C&&b.add(C)}}),i.querySelectorAll("HideCustomAction").forEach(x=>{const v=x.getAttribute("Location")??"";v&&f.add(v)});for(const x of r)for(const v of x.groups)for(const C of Te(v)){const $=b.has(C.id);Zo(C,{origin:ny(C.id,$)}),C.hidden=f.has(C.id),C.source&&(C.source.labelToken=C.source.attributes.LabelText,C.source.tooltipTitleToken=C.source.attributes.ToolTipTitle,C.source.tooltipBodyToken=C.source.attributes.ToolTipDescription),C.label=Ge(C.label,g),C.tooltipTitle&&(C.tooltipTitle=Ge(C.tooltipTitle,g)),C.tooltipBody&&(C.tooltipBody=Ge(C.tooltipBody,g));for(const A of C.menu?.sections??[])A.title&&(A.title=Ge(A.title,g))}const y=ay(i,r);return{ribbon:{location:t,entityLogicalName:n,tabs:r,...Object.keys(c).length>0?{scalingByTab:c}:{},...Object.keys(y).length?{templateLayouts:y}:{}},commands:u,displayRules:m,enableRules:p,locLabels:g}}const yd="Ribbon > Tabs > Tab, Ribbon > ContextualTabs > ContextualGroup > Tab";function Br(e){const t=e.getAttribute("Description");return t===null?{}:{description:t}}function sy(e){const t=[];return e.querySelectorAll(yd).forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const s=n.getAttribute("Title")??o,i=[];n.querySelectorAll(":scope > Groups > Group").forEach(l=>{const r=l.getAttribute("Id")??"";if(!r)return;const c=l.getAttribute("Title")??l.getAttribute("Label")??r,d=parseInt(l.getAttribute("Sequence")??"0",10),u=l.getAttribute("Template")??"",p=[];l.querySelectorAll(":scope > Controls > *").forEach(m=>{zc[m.tagName]&&xd(m,p)}),i.push({id:r,label:c,sequence:d,template:u,...Br(l),buttons:p})}),t.push({id:o,label:s,sequence:parseInt(n.getAttribute("Sequence")??"0",10),commandId:n.getAttribute("Command")??void 0,...Br(n),tabDisplayRules:[],groups:i})}),t.sort((n,o)=>n.sequence-o.sequence)}function iy(e){const t={};return e.querySelectorAll(yd).forEach(n=>{const o=n.getAttribute("Id"),s=Array.from(n.children).find(r=>r.tagName==="Scaling");if(!o||!s||t[o])return;const i=r=>({id:r.getAttribute("Id")??"",groupId:r.getAttribute("GroupId")??"",size:r.getAttribute("Size")??"",sequence:parseInt(r.getAttribute("Sequence")??"0",10),...r.getAttribute("PopupSize")?{popupSize:r.getAttribute("PopupSize")}:{}}),l=Array.from(s.children);t[o]={tabId:o,maxSizes:l.filter(r=>r.tagName==="MaxSize").map(i),scales:l.filter(r=>r.tagName==="Scale").map(i)}}),t}function ay(e,t){const n=new Set(t.flatMap(s=>s.groups.map(i=>i.template)).filter(Boolean)),o={};return e.querySelectorAll("GroupTemplate").forEach(s=>{const i=s.getAttribute("Id");!i||!n.has(i)||(o[i]=Array.from(s.querySelectorAll(":scope > Layout")).map(l=>l.getAttribute("Title")??"").filter(Boolean))}),o}function ry(e,t){const n=new Map;for(const o of t)o.commandId&&n.set(o.commandId,o);e.querySelectorAll("RuleDefinitions > TabDisplayRules > TabDisplayRule").forEach(o=>{const s=o.getAttribute("TabCommand")??"",i=n.get(s);if(!i)return;const l=[];for(const c of Array.from(o.children))c.tagName==="EntityRule"?l.push({kind:"EntityRule",entityName:c.getAttribute("EntityName")??void 0,appliesTo:c.getAttribute("AppliesTo")??void 0,context:c.getAttribute("Context")??void 0}):c.tagName==="PageRule"&&l.push({kind:"PageRule",address:c.getAttribute("Address")??""});if(l.length===0)return;const r=i.tabDisplayRules.find(c=>c.tabCommand===s);r?r.rules.push(...l):i.tabDisplayRules.push({tabCommand:s,rules:l})})}function xd(e,t){const n=e.getAttribute("Id")??"";if(!n)return;const o=zc[e.tagName]??"button",s=dt(o),i=e.getAttribute("LabelText")??n,l=dy(e.getAttribute("ModernImage")??void 0),r=parseInt(e.getAttribute("Sequence")??"0",10),c=e.getAttribute("TemplateAlias")??"",d=e.getAttribute("Command")??"";t.push({id:n,label:i,icon:l,sequence:r,templateAlias:c,commandId:d,kind:o,hidden:!1,oob:!0,custom:!1,managed:!1,tooltipTitle:e.getAttribute("ToolTipTitle")??void 0,tooltipBody:e.getAttribute("ToolTipDescription")??void 0,image16:e.getAttribute("Image16by16")??void 0,image32:e.getAttribute("Image32by32")??void 0,source:{modernImage:e.getAttribute("ModernImage")??void 0,attributes:zi(e),...s?{xml:An().serializeToString(e)}:{}},menu:s?void 0:cy(e)})}const ly=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]);function zi(e){return Object.fromEntries(Array.from(e.attributes).map(t=>[t.name,t.value]))}function cy(e){const t=st(e).find(s=>s.tagName==="Menu");if(!t)return;const n=zi(t),o=[];for(const s of st(t)){if(s.tagName!=="MenuSection")continue;const i=s.getAttribute("Id")??"",l=st(s).find(u=>u.tagName==="Controls"),r=[],c=[];st(l).forEach((u,p)=>{ly.has(u.tagName)&&u.getAttribute("Id")?xd(u,r):c.push({index:p,xml:An().serializeToString(u)})});const d=zi(s);o.push({id:i,title:s.getAttribute("Title")??void 0,sequence:parseInt(s.getAttribute("Sequence")??"0",10),displayMode:s.getAttribute("DisplayMode")??void 0,controlsId:l?.getAttribute("Id")??`${i}.Controls`,controls:r,attributes:d,...c.length?{rawControls:c}:{},...l?{}:{rawContent:st(s).map(u=>An().serializeToString(u)).join("")}})}return{id:t.getAttribute("Id")??`${e.getAttribute("Id")}.Menu`,sections:o,attributes:n}}function dy(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 An=()=>new XMLSerializer;function st(e){return e?Array.from(e.childNodes).filter(t=>t.nodeType===Node.ELEMENT_NODE):[]}class uy{pending=[];add(t){this.pending.push(t)}flush(){for(const t of[0,1]){const n=this.pending.filter(i=>i.phase===t);if(n.length===0)continue;const o=n.map(i=>i.generate());let s=null;try{const i=Lc(`<v>${o.map(l=>`<i>${l}</i>`).join("")}</v>`);s=st(i).map(l=>st(l)[0])}catch{s=null}n.forEach((i,l)=>{(s?s[l]&&Nn(s[l])===Nn(i.source):ob(o[l],i.source))||i.fallback()})}this.pending=[]}}function my(e,t){const n=[];return e.querySelectorAll("CommandDefinition").forEach(o=>{const s=o.getAttribute("Id")??"";if(!s)return;const i=st(o),l=m=>i.find(g=>g.tagName===m),r=[],c=(m,g)=>{const b=[];return st(l(m)).forEach((f,y)=>{const x=f.getAttribute("Id");f.tagName===g&&x&&f.attributes.length===1&&st(f).length===0?b.push(x):r.push({container:m,index:y,xml:An().serializeToString(f)})}),b},d=c("EnableRules","EnableRule"),u=c("DisplayRules","DisplayRule"),p=[];st(l("Actions")).forEach((m,g)=>{const b=py(m);if(!b){p.push(Lr(m));return}p.push(b),t.add({source:m,generate:()=>fd(b),fallback:()=>p[g]=Lr(m),phase:0})}),n.push({id:s,enableRules:d,displayRules:u,actions:p,...r.length>0?{rawRuleRefs:r}:{}})}),n}function Lr(e){return{kind:"raw",tagName:e.tagName,xml:An().serializeToString(e)}}function py(e){switch(e.tagName){case"JavaScriptFunction":{const t=Pi(e);return t?{kind:"javascript",library:e.getAttribute("Library")??"",functionName:e.getAttribute("FunctionName")??"",params:t}:null}case"Url":{const t=Pi(e);if(!t)return null;const n=e.getAttribute("WinMode");return{kind:"url",address:e.getAttribute("Address")??"",passParams:Ot(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 Ot(e){if(e===null)return;const t=e.trim();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}function Pi(e){const t=[];for(const n of st(e)){const o=n.getAttribute("Name")??void 0,s=n.getAttribute("Value")??"";switch(n.tagName){case"CrmParameter":t.push({kind:"CrmParameter",name:o,value:s});break;case"BoolParameter":t.push({kind:"BoolParameter",name:o,value:Ot(s)??!1});break;case"IntParameter":t.push({kind:"IntParameter",name:o,value:parseInt(s,10)});break;case"DecimalParameter":t.push({kind:"DecimalParameter",name:o,value:parseFloat(s)});break;case"StringParameter":t.push({kind:"StringParameter",name:o,value:s});break;default:return null}}return t}function fy(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > EnableRules > EnableRule").forEach(o=>{const s=o.getAttribute("Id")??"";s&&n.push({id:s,steps:za(o,t)})}),n}function hy(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > DisplayRules > DisplayRule").forEach(o=>{const s=o.getAttribute("Id")??"";s&&n.push({id:s,steps:za(o,t)})}),n}function za(e,t){const n=[];return st(e).forEach((o,s)=>{const i=by(o,t);if(!i){n.push(zr(o));return}n.push(i),t.add({source:o,generate:()=>Cs(n[s]),fallback:()=>n[s]=zr(o),phase:i.kind==="OrRule"?1:0})}),n}function zr(e){return{kind:"RawRule",tagName:e.tagName,xml:An().serializeToString(e)}}function gy(e){const t={},n=Ot(e.getAttribute("Default")),o=Ot(e.getAttribute("InvertResult"));return n!==void 0&&(t.default=n),o!==void 0&&(t.invertResult=o),t}function qn(e,t){const n=e.getAttribute(t);return n===null?void 0:parseInt(n,10)}function mt(e,t){return e.getAttribute(t)??void 0}function Ce(e,t){return e.getAttribute(t)??""}function by(e,t){const n=gy(e);switch(e.tagName){case"OrRule":{const o=st(e);return o.some(s=>s.tagName!=="Or")?null:{kind:"OrRule",groups:o.map(s=>za(s,t))}}case"SelectionCountRule":return{kind:"SelectionCountRule",minimum:qn(e,"Minimum"),maximum:qn(e,"Maximum"),appliesTo:mt(e,"AppliesTo"),...n};case"EntityRule":return{kind:"EntityRule",entityName:mt(e,"EntityName"),context:mt(e,"Context"),appliesTo:mt(e,"AppliesTo"),...n};case"FormStateRule":return{kind:"FormStateRule",state:Ce(e,"State"),...n};case"CommandClientTypeRule":return{kind:"CommandClientTypeRule",type:Ce(e,"Type"),...n};case"CustomRule":{const o=Pi(e);return o?{kind:"CustomRule",library:Ce(e,"Library"),functionName:Ce(e,"FunctionName"),...o.length>0?{params:o}:{},...n}:null}case"FeatureControlRule":{const o=Ot(e.getAttribute("ExpectedValue"));return o===void 0?null:{kind:"FeatureControlRule",featureControlBit:Ce(e,"FeatureControlBit"),expectedValue:o,...n}}case"MiscellaneousPrivilegeRule":return{kind:"MiscellaneousPrivilegeRule",privilegeName:Ce(e,"PrivilegeName"),privilegeDepth:mt(e,"PrivilegeDepth"),...n};case"CrmClientTypeRule":return{kind:"CrmClientTypeRule",type:Ce(e,"Type"),...n};case"FormTypeRule":return{kind:"FormTypeRule",type:Ce(e,"Type"),...n};case"ValueRule":return{kind:"ValueRule",field:Ce(e,"Field"),value:Ce(e,"Value"),...n};case"SkuRule":return{kind:"SkuRule",sku:Ce(e,"Sku"),...n};case"HideForTabletExperienceRule":return{kind:"HideForTabletExperienceRule",...n};case"OrganizationSettingRule":return{kind:"OrganizationSettingRule",setting:Ce(e,"Setting"),...n};case"EntityPrivilegeRule":return{kind:"EntityPrivilegeRule",entityName:mt(e,"EntityName"),appliesTo:mt(e,"AppliesTo"),privilegeType:Ce(e,"PrivilegeType"),privilegeDepth:Ce(e,"PrivilegeDepth"),...n};case"EntityPropertyRule":{const o=Ot(e.getAttribute("PropertyValue"));return o===void 0?null:{kind:"EntityPropertyRule",entityName:mt(e,"EntityName"),appliesTo:mt(e,"AppliesTo"),propertyName:Ce(e,"PropertyName"),propertyValue:o,...n}}case"DeviceTypeRule":return{kind:"DeviceTypeRule",type:Ce(e,"Type"),...n};case"OptionSetRule":return{kind:"OptionSetRule",optionSet:Ce(e,"OptionSet"),stateCode:Ce(e,"StateCode"),objectTypeCode:Ce(e,"ObjectTypeCode"),...n};case"RecordPrivilegeRule":return{kind:"RecordPrivilegeRule",privilegeType:Ce(e,"PrivilegeType"),appliesTo:mt(e,"AppliesTo"),...n};case"FormEntityContextRule":return{kind:"FormEntityContextRule",entityName:Ce(e,"EntityName"),...n};case"PageRule":return{kind:"PageRule",address:Ce(e,"Address"),...n};case"RelationshipTypeRule":return{kind:"RelationshipTypeRule",appliesTo:"SelectedEntity",relationshipType:mt(e,"RelationshipType"),allowCustomRelationship:Ot(e.getAttribute("AllowCustomRelationship")),allowSystemRelationship:Ot(e.getAttribute("AllowSystemRelationship")),...n};case"ReferencingAttributeRequiredRule":return{kind:"ReferencingAttributeRequiredRule",...n};case"OutlookItemTrackingRule":{const o=Ot(e.getAttribute("TrackedInCrm"));return o===void 0?null:{kind:"OutlookItemTrackingRule",trackedInCrm:o,appliesTo:mt(e,"AppliesTo"),...n}}case"OutlookRenderTypeRule":return{kind:"OutlookRenderTypeRule",type:Ce(e,"Type"),...n};case"OutlookVersionRule":return{kind:"OutlookVersionRule",version:Ce(e,"Version"),...n};case"CrmOfflineAccessStateRule":return{kind:"CrmOfflineAccessStateRule",state:Ce(e,"State"),...n};case"CrmOutlookClientTypeRule":return{kind:"CrmOutlookClientTypeRule",type:Ce(e,"Type"),...n};case"CrmOutlookClientVersionRule":return{kind:"CrmOutlookClientVersionRule",major:parseInt(Ce(e,"Major"),10),minor:qn(e,"Minor"),build:qn(e,"Build"),revision:qn(e,"Revision"),...n};default:return null}}function yy(e){const t=[];return e.querySelectorAll("LocLabel").forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const s=[];n.querySelectorAll("Title").forEach(i=>{const l=parseInt(i.getAttribute("languagecode")??"1033",10),r=i.getAttribute("description")??"";s.push({languageCode:l,description:r})}),t.push({id:o,titles:s})}),t}function es(e){return{controlIds:[...Ko(e)],containerIds:[...Jc(e)],locLabelIds:[...e.locLabels.keys()],hides:hs(e),scalingStepIds:Na(e).map(t=>t.id),commandIds:[...e.commandDefinitions.keys()],commandRefIds:[...Zc(e)]}}async function lI(e){try{return es(await Fi(e))}catch{return null}}function xy(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=js(t,"HomepageGrid","");return{commands:n.commands,enableRules:n.enableRules,displayRules:n.displayRules}}function vy(){return window.dataverseAPI}async function In(e){const t=[];let n=e;for(;n;){const o=await vy().queryData(n);t.push(...o.value??[]);const s=o["@odata.nextLink"];n=s?s.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}async function Fi(e){const t=e===null?"entity eq null and ismanaged eq false":`entity eq '${e.replace(/'/g,"''")}' and ismanaged eq false`,[n,o,s]=await Promise.all([In(`ribbondiffs?$select=diffid,difftype,rdx,sequence&$filter=${t}&$orderby=sequence asc,diffid asc`),In(`ribboncommands?$select=command,commanddefinition&$filter=${t}&$orderby=command asc`),In(`ribbonrules?$select=ruleid,ruletype,ruledefinition&$filter=${t}&$orderby=ruleid asc`)]);return rb({diffs:n,commands:o,rules:s})}function _i(e){const t=[];for(const[n,o]of e.locLabels){const s=new DOMParser().parseFromString(o,"application/xml"),i=Array.from(s.querySelectorAll("Title")).map(l=>({languageCode:Number(l.getAttribute("languagecode")??1033),description:l.getAttribute("description")??""}));t.push({id:n,titles:i})}return t}function Pr(e,t,n,o){const i=`${Fa()}.${jn(e)}.${jn(t)}.${jn(n)}`;return _a(i,o)}function Pa(e,t,n){const s=`${Fa()}.${jn(e)}.${jn(t)}.Command`;return _a(s,n)}function uo(e,t,n){const s=`${Fa()}.${jn(e)}.${t}Rule`;return _a(s,n)}function Fr(e){return e.replace(/\.Command$/,"").split(".").pop()||"Rule"}function Fa(){try{return ae.getState().publisherPrefix||"new"}catch{return"new"}}function jn(e){return e.replace(/[^a-zA-Z0-9._]/g,"").replace(/^[^a-zA-Z]/,"x")}function _a(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n++;return`${e}${n}`}function vd(e,t,n,o,s){const i=o.replace(/[^a-zA-Z0-9_]/g,"")||"Button",l=`${e}.${t}.${n}.${i}`;let r=l;for(let c=2;s.has(`${r}.Button`)||s.has(`${r}.Command`);c++)r=`${l}${c}`;return{id:`${r}.Button`,commandId:`${r}.Command`}}function cI(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 Y=Kt()(e=>({location:"HomepageGrid",tabId:"MainTab",selectedButtonId:null,selectedGroupId:null,setLocation(t){e({location:t,tabId:"MainTab",selectedButtonId:null,selectedGroupId:null})},setTabId(t){e({tabId:t,selectedButtonId:null,selectedGroupId:null})},selectGroup(t){e({selectedGroupId:t,selectedButtonId:null})},selectButton(t,n){e({selectedGroupId:t,selectedButtonId:n})},selectButtonInContext(t,n,o,s){e({location:t,tabId:n,selectedGroupId:o,selectedButtonId:s})},clearSelection(){e({selectedButtonId:null,selectedGroupId:null})}}));function xo(e){return/\.AllEntities\./.test(e)||/\.VisualizationTab$/.test(e)}function mo(e){const t=e.filter(n=>!xo(n.id));return(t.find(n=>/\.MainTab$/.test(n.id))??t[0]??e[0])?.id}const Xe="Mscrm.OpenRecordItem",Sd=["HomepageGrid","SubGrid"],Sy=/\.(HomepageGrid|SubGrid)\.OpenRecordItem\d*\.Button$/;function wd(e){return e.commandId===Xe&&Sy.test(e.id)}function qa(e){const t=[];for(const n of e?.tabs??[])for(const o of n.groups)for(const s of Te(o))s.commandId===Xe&&t.push({tabId:n.id,groupId:o.id,button:s});return t}function Cd(e){return qa(e).filter(t=>wd(t.button))}function Id(e){const t=e.button.origin;return t==="unmanaged"?"yours":t===void 0?"unknown":"theirs"}function jd(e){const t=e?.tabs??[],n=mo(t.filter(i=>i.groups.length>0)),o=t.find(i=>i.id===n),s=o?.groups.find(i=>/\.Management$/.test(i.id))??o?.groups[0];return o&&s?{tabId:o.id,groupId:s.id}:null}function wy(){return{id:Xe,enableRules:[],displayRules:[],actions:[{kind:"javascript",library:"$webresource:",functionName:"YourNamespace.openRecord",params:[{kind:"CrmParameter",value:"SelectedControlSelectedItemReferences"}]}]}}function Cy(e){for(const t of e.actions){if(t.kind!=="javascript")continue;if(!t.library.trim().replace(/^\$webresource:/i,"").trim()||!t.functionName.trim())return`${Xe} has a JavaScript action without a web resource or function — set them in the Command Editor, or turn the override off`}return null}const Iy=["Mscrm.HideOnModern","Mscrm.ShowOnlyOnModern"];function Wn(e,t){const n=new Set;for(const o of[t,e.baseline])for(const s of Object.values(o??{}))for(const i of s.tabs){n.add(i.id);for(const l of i.groups){n.add(l.id);for(const r of Te(l))n.add(r.id)}}for(const o of Object.values(e.layers??{})){for(const s of o?.containerIds??[])n.add(s);for(const s of o?.controlIds??[])n.add(s)}return n}function Rn(e,t){return po(e,t)?.containerIds}function po(e,t){return e.layers[t==="Application"?"application":"entity"]}function at(e){return JSON.parse(JSON.stringify(e))}function wt(e){return{ribbons:e.ribbons,commands:e.commands,enableRules:e.enableRules,displayRules:e.displayRules,locLabels:e.locLabels,pendingUnhides:e.pendingUnhides,pendingOrphanDeletes:e.pendingOrphanDeletes,customisedCommandIds:e.customisedCommandIds,uncustomisedCommandIds:e.uncustomisedCommandIds}}function Ae(e,t,n,o,s="info"){return{ts:new Date().toISOString(),userId:"",userName:"You",op:e,target:t,detail:n,icon:o,color:s}}let lt=null;const jy=1e3;let ts=null,Ry=0;function Rd(e,t,n,o){const s=ts??o,i=e.past[e.past.length-1];return s&&i?.coalesceKey===s&&e.future.length===0&&(ts!==null||Date.parse(t.ts)-Date.parse(i.ts)<jy)?{past:[...e.past.slice(0,-1),{...i,...t}],future:[],mutationsSincePublish:e.mutationsSincePublish+1}:{past:[...e.past,{...t,coalesceKey:s,snapshot:n()}].slice(-80),future:[],mutationsSincePublish:e.mutationsSincePublish+1}}function Fe(e,t,n,o){return lt?(lt.meta||(lt.meta=n),t):{...t,...Rd(e,n,()=>wt(e),o)}}function Ne(e,t,n,o){const s=at(e.ribbons);return t(s),Fe(e,{ribbons:s},n,o)}function so(e){const t=(n,o)=>JSON.stringify(n)===JSON.stringify(o);return e.pendingUnhides.entity.length+e.pendingUnhides.application.length>0||e.pendingOrphanDeletes.entity.length+e.pendingOrphanDeletes.application.length>0||e.customisedCommandIds.length>0||e.uncustomisedCommandIds.entity.length+e.uncustomisedCommandIds.application.length>0||!t(e.ribbons,e.baseline)||!t(e.commands,e.baselineCommands)||!t(e.enableRules,e.baselineEnableRules)||!t(e.displayRules,e.baselineDisplayRules)||!t(e.locLabels,e.baselineLocLabels)}function Hn(e,t){const n=e.findIndex(o=>o.id===t.id);return n<0?[...e,t]:JSON.stringify(e[n])===JSON.stringify(t)?null:e.map((o,s)=>s===n?t:o)}const _r={entity:null,application:null},Gs={entity:[],application:[]},qr=["HomepageGrid","SubGrid","Form"];function $d(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 Wr(e,t){for(let n=1;n<e.length;n++)e[n].sequence>e[n-1].sequence||(t(e[n])?ns(e,n,t):t(e[n-1])&&ns(e,n-1,t));for(const n of e.filter(t)){const o=e.indexOf(n);if((e[o-1]?.sequence??-1/0)<n.sequence&&n.sequence<(e[o+1]?.sequence??1/0))continue;e.splice(o,1);const i=e.findIndex(l=>l.sequence>n.sequence);e.splice(i<0?e.length:i,0,n)}}function ft(e){return[...e].sort((t,n)=>t.sequence-n.sequence)}function Td(e,t){const n=new Set(e.baseline[t]?.tabs.flatMap(s=>s.groups.map(i=>i.id))??[]),o=new Set(Rn(e,t)??[]);return s=>!n.has(s.id)||o.has(s.id)}function Nd(e,t,n,o,s){const i=ft(e.ribbons[t].tabs.find(d=>d.id===n)?.groups??[]),l=i.findIndex(d=>d.id===o),r=i[l+s];if(l<0||!r)return!1;const c=Td(e,t);return c(i[l])||c(r)}function ns(e,t,n){let o=t;for(;o>0&&n(e[o-1]);)o--;let s=t;for(;s<e.length-1&&n(e[s+1]);)s++;const i=o>0?e[o-1].sequence:0,l=s<e.length-1?e[s+1].sequence:1/0;if(l-i-1>=s-o+1){let d=i;for(let u=o;u<=s;u++){const p=s-u,m=e[u];m.sequence>d&&m.sequence<=l-1-p||(m.sequence=l===1/0?d+10:d+Math.max(1,Math.min(10,Math.floor((l-d)/(p+2))))),d=m.sequence}return}const r=new Set(e.filter((d,u)=>u!==t).map(d=>d.sequence));let c=(t>0?e[t-1].sequence:0)+1;for(;r.has(c);)c++;e[t].sequence=c}function Hr(e,t,n){const o=e[t],s=$d(o.sequence,e[t-1]?.sequence,e[t+1]?.sequence);if(s!==void 0){o.sequence=s;return}if(ns(e,t,n),!((e[t-1]?.sequence??-1/0)<o.sequence&&o.sequence<(e[t+1]?.sequence??1/0))){e.splice(t,1);const l=e.findIndex(r=>r.sequence>o.sequence);e.splice(l<0?e.length:l,0,o)}}function Us(){const{activeSolution:e,publisherPrefix:t}=ae.getState();return e?.publisherPrefix?.trim()||t?.trim()||"new"}function Vs(e,t){const n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(`${o}.`)||n.startsWith(`${o}_`)?e:`${t}.${e}`}const Xs={HomepageGrid:{location:"HomepageGrid",entityLogicalName:"",tabs:[]},SubGrid:{location:"SubGrid",entityLogicalName:"",tabs:[]},Form:{location:"Form",entityLogicalName:"",tabs:[]},Application:{location:"Application",entityLogicalName:"",tabs:[]}};function gt(e,t,n,o,s){const i=e[t].tabs.find(r=>r.id===n)?.groups.find(r=>r.id===o),l=Ss(i,s);return i&&l?{group:i,button:l}:void 0}function kd(e,t,n){return(e.baseline[t]?.tabs??[]).some(o=>o.groups.some(s=>Te(s).some(i=>i.id===n)))}function rt(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob===!0&&n.custom!==!0}function Wa(e,t,n){return n.origin!=="unmanaged"&&!n.hidden&&n.kind!=="flyout"&&n.kind!=="splitButton"&&!dt(n.kind)&&!rt(e,t,n)}function $y(e,t,n){for(const o of e.baseline[t].tabs)for(const s of o.groups){const i=s.buttons.find(l=>l.id===n);if(i)return i}}function Ty(e,t,n){if(t.location!==n.location||t.tabId!==n.tabId||t.groupId!==n.groupId)return!1;const o=ft(e.buttons),s=o.findIndex(l=>l.id===t.buttonId),i=o[s+1]?.id;return n.beforeButtonId?n.beforeButtonId===t.buttonId||n.beforeButtonId===i:i===void 0}const os=/^\$LocLabels:/,io=e=>e.labelsUnknown?void 0:new Set(e.locLabels.map(t=>t.id));function Ny(e,t){if(!e)return;const n=s=>s&&(!os.test(s)||no(s,t))?s:void 0,o={};for(const[s,i]of Object.entries(e.attributes))s!=="Id"&&!os.test(i)&&(o[s]=i);return{...e,labelToken:n(e.labelToken),tooltipTitleToken:n(e.tooltipTitleToken),tooltipBodyToken:n(e.tooltipBodyToken),attributes:o}}const Ks=(e,t)=>({entity:e.entity.filter(n=>n!==t),application:e.application.filter(n=>n!==t)});function Gr(e,t){const n=e.baselineCommands.find(s=>s.id===t),o=e.commands.find(s=>s.id===t);return!n||!o||JSON.stringify(n)===JSON.stringify(o)?e.commands:e.commands.map(s=>s.id===t?JSON.parse(JSON.stringify(n)):s)}const M=Kt()(Vg((e,t)=>({ribbons:at(Xs),baseline:at(Xs),baselineCommands:[],baselineEnableRules:[],baselineDisplayRules:[],baselineLocLabels:[],layers:{..._r},pendingUnhides:{entity:[],application:[]},orphans:{entity:[],application:[]},pendingOrphanDeletes:{entity:[],application:[]},baseLanguageCode:1033,baseLanguageUnknown:!1,labelsUnknown:!1,customisedCommandIds:[],uncustomisedCommandIds:{entity:[],application:[]},reloadRequiredCommandIds:[],commands:[],displayRules:[],enableRules:[],locLabels:[],templates:[],conflicts:[],mutationsSincePublish:0,past:[],future:[],loadRibbons(n){e({ribbons:at(n),baseline:at(n),mutationsSincePublish:0,past:[],future:[]}),lt&&(lt={snapshot:wt(t()),meta:null})},setConflicts(n){e({conflicts:n})},applyImport(n,o){e(s=>Fe(s,{ribbons:{...s.ribbons,...at(n.ribbons)},commands:[...n.commands],enableRules:[...n.enableRules],displayRules:[...n.displayRules],locLabels:[...n.locLabels]},Ae("imported","RibbonDiffXml",o,"arrow_upload","success")))},loadWorkspace(n){const o=at(n.ribbons);e({ribbons:o,baseline:at(o),commands:[...n.commands],displayRules:[...n.displayRules],enableRules:[...n.enableRules],baselineCommands:JSON.parse(JSON.stringify(n.commands)),baselineDisplayRules:JSON.parse(JSON.stringify(n.displayRules)),baselineEnableRules:JSON.parse(JSON.stringify(n.enableRules)),locLabels:[...n.locLabels],baselineLocLabels:JSON.parse(JSON.stringify(n.locLabels)),layers:{..._r,...n.layers??{}},pendingUnhides:{...Gs},orphans:{entity:[],application:[],...n.orphans??{}},pendingOrphanDeletes:{...Gs},baseLanguageCode:n.baseLanguageCode??1033,baseLanguageUnknown:n.baseLanguageUnknown??!1,labelsUnknown:n.labelsUnknown??!1,customisedCommandIds:[],uncustomisedCommandIds:{entity:[],application:[]},reloadRequiredCommandIds:[],templates:[...n.templates??[]],conflicts:[...n.conflicts??[]],mutationsSincePublish:0,past:[],future:[]}),lt&&(lt={snapshot:wt(t()),meta:null})},restoreWorkspace(n,o){const s=JSON.parse(JSON.stringify(n));e(i=>{const l=c=>{const d=i.layers[c];return d?s.pendingUnhides[c].filter(u=>d.hides.some(p=>p.location===u)):s.pendingUnhides[c]},r={...s,pendingUnhides:{entity:l("entity"),application:l("application")}};return JSON.stringify(wt({...i,...r}))===JSON.stringify(wt(i))?i:Fe(i,r,Ae("restored","unsaved changes",o,"history"))})},resetWorkspace(){t().loadWorkspace({ribbons:Xs,commands:[],displayRules:[],enableRules:[],locLabels:[]})},undo(){t().restore(t().past.length-1)},redo(){const n=t();if(n.future.length===0||lt)return;const[o,...s]=n.future;e({...o.snapshot,past:[...n.past,{...o,snapshot:wt(n)}],future:s,mutationsSincePublish:so({...n,...o.snapshot})?n.mutationsSincePublish+1:0})},restore(n){const o=t(),{past:s}=o;if(n<0||n>=s.length||lt)return;let i=wt(o),l=o.future;for(let c=s.length-1;c>=n;c--)l=[{...s[c],coalesceKey:void 0,snapshot:i},...l],i=s[c].snapshot;const r=s.length-n;e({...i,past:s.slice(0,n),future:l,mutationsSincePublish:so({...o,...i})?Math.max(1,o.mutationsSincePublish-r):0})},batch(n){if(lt){n();return}lt={snapshot:wt(t()),meta:null};try{n()}finally{const{snapshot:o,meta:s}=lt;lt=null,s&&e(i=>Rd(i,s,()=>o))}},beginEditSession(){ts=`session:${++Ry}`},endEditSession(){ts=null},moveButton(n,o){const s=t(),l=s.ribbons[n.location].tabs.find(p=>p.id===n.tabId)?.groups.find(p=>p.id===n.groupId),r=l?.buttons.find(p=>p.id===n.buttonId),c=s.ribbons[o.location].tabs.find(p=>p.id===o.tabId)?.groups.find(p=>p.id===o.groupId);if(!r||!l||!c)return null;const d=$y(s,n.location,r.id)?.origin;if(d!==void 0&&d!=="unmanaged"&&!r.menu&&!Cn(r.kind)&&!rt(n.location,n.tabId,r)){if(Ty(l,n,o))return null;const p=f=>(ce.getState().logWarn("ribbon",`Can't move ${r.id}: ${f}`),null);if(r.hidden)return p("it's hidden — move your copy of it instead.");if(n.location==="Application"!=(o.location==="Application"))return p("it isn't yours, and a copy can't move between the table's ribbon and the application ribbon.");const m=Us();let g=null,b=!1;return t().batch(()=>{const f=t().customiseButton(n.location,n.tabId,n.groupId,n.buttonId,m);f&&(b=!0,g=t().moveButton({...n,buttonId:f},o),ce.getState().logInfo("ribbon",`${r.id} isn't yours, so it can't be moved: moved your copy ${f} instead and hid the original.`))}),b&&!g&&t().undo(),b?g:p("it isn't yours and can't be copied (e.g. it has an override of its command); undo the override, then move it.")}return rt(n.location,n.tabId,r)?null:(e(p=>Ne(p,m=>{const g=m[n.location].tabs.find(j=>j.id===n.tabId);if(!g)return;const b=g.groups.find(j=>j.id===n.groupId);if(!b)return;const f=b.buttons.findIndex(j=>j.id===n.buttonId);if(f===-1||rt(n.location,n.tabId,b.buttons[f]))return;const x=(n.tabId===o.tabId&&n.location===o.location?g:m[o.location].tabs.find(j=>j.id===o.tabId))?.groups.find(j=>j.id===o.groupId);if(!x)return;const[v]=b.buttons.splice(f,1);x.buttons.sort((j,T)=>j.sequence-T.sequence);const C=o.beforeButtonId?x.buttons.findIndex(j=>j.id===o.beforeButtonId):x.buttons.length,$=C<0?x.buttons.length:C;x.buttons.splice($,0,v);const A=$d(v.sequence,x.buttons[$-1]?.sequence,x.buttons[$+1]?.sequence);if(A!==void 0)v.sequence=A;else{const j=new Set(p.layers[o.location==="Application"?"application":"entity"]?.controlIds??[]),T=new Set(p.baseline[o.location].tabs.flatMap(R=>R.groups.flatMap(I=>I.buttons.map(N=>N.id))));ns(x.buttons,$,R=>R===v||j.has(R.id)||!T.has(R.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"moved",target:n.buttonId,detail:`to ${o.groupId}`,icon:"arrow_move",color:"info"})),n.buttonId)},setButtonProp(n,o,s,i,l){const c=Object.values(l).every(d=>typeof d=="string")?`button:${n}:${i}:${Object.keys(l).sort().join(",")}`:void 0;e(d=>{const u=p=>{const m=gt(p,n,o,s,i);return!m||l.kind===void 0||l.kind===m.button.kind||!kd(d,n,i)&&(m.group.buttons.includes(m.button)||ka.includes(l.kind))};return Object.keys(l).length===1&&!u(d.ribbons)?{}:Ne(d,p=>{const m=gt(p,n,o,s,i)?.button;if(!m||rt(n,o,m))return;const g=m.kind,b=u(p);Object.assign(m,l),b||(m.kind=g),Cn(m.kind)&&!m.menu&&(m.menu=_s(m.id))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l.label??i,detail:Object.keys(l).join(", "),icon:"edit",color:"info"},c)})},deleteButton(n,o,s,i){const l=t(),r=gt(l.ribbons,n,o,s,i)?.button;if(r&&!Is(r,l.baseline[n])){ce.getState().logWarn("ribbon",`"${r.label}" (${i}) was not deleted: only your own buttons can be deleted — hide it instead.`);return}e(c=>Ne(c,d=>{const u=gt(d,n,o,s,i);if(!u)return;const{group:p,button:m}=u;rt(n,o,m)||sd(p,i)||(p.buttons=p.buttons.filter(g=>g.id!==i))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:i,detail:s,icon:"delete",color:"danger"}))},addMenuItem({location:n,tabId:o,groupId:s,parentId:i,sectionId:l,item:r}){e(c=>Ne(c,d=>{const u=gt(d,n,o,s,i)?.button;if(!u||rt(n,o,u))return;u.menu=u.menu??_s(u.id),u.menu.sections.length===0&&u.menu.sections.push(Ai(u.id,[]));const p=u.menu.sections.find(g=>g.id===l)??u.menu.sections[0],m=p.controls[p.controls.length-1]?.sequence??0;p.controls.push({...r,kind:r.kind??"button",sequence:r.sequence??m+10,templateAlias:r.templateAlias??"",hidden:!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:r.label,detail:`menu of ${i}`,icon:"add",color:"success"}))},addMenuSection(n,o,s,i,l){e(r=>Ne(r,c=>{const d=gt(c,n,o,s,i)?.button;!d||rt(n,o,d)||(d.menu=d.menu??{id:`${d.id}.Menu`,sections:[]},d.menu.sections.push(Ai(d.id,d.menu.sections,l)))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:l??"Menu section",detail:`menu of ${i}`,icon:"add",color:"success"}))},setMenuSectionProp(n,o,s,i,l,r){e(c=>Ne(c,d=>{const u=gt(d,n,o,s,i)?.button,p=u?.menu?.sections.find(m=>m.id===l);!u||!p||rt(n,o,u)||Object.assign(p,r)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l,detail:Object.keys(r).join(", "),icon:"edit",color:"info"}))},deleteMenuSection(n,o,s,i,l){e(r=>Ne(r,c=>{const d=gt(c,n,o,s,i)?.button;!d?.menu||rt(n,o,d)||(d.menu.sections=d.menu.sections.filter(u=>u.id!==l))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:l,detail:`menu of ${i}`,icon:"delete",color:"danger"}))},duplicateButton(n,o,s,i){e(l=>Ne(l,r=>{const c=gt(r,n,o,s,i);if(c){const{group:d,button:u}=c;if(rt(n,o,u))return;const p=io(l),m=to(u.source?.labelToken)||no(u.source?.labelToken,p),g={...Jo(u,`${Vs(u.id,Us())}_copy_${Date.now()}`,p),label:dt(u.kind)||m?u.label:`${u.label} (copy)`,sequence:u.sequence},b=Yo(d,i),f=b?b.section.controls:d.buttons,y=f.findIndex(C=>C.id===i);f.splice(y+1,0,g);const x=new Set(po(l,n)?.controlIds??[]),v=new Set((l.baseline[n]?.tabs??[]).flatMap(C=>C.groups.flatMap(Te)).map(C=>C.id));Hr(f,y+1,C=>C===g||x.has(C.id)||!v.has(C.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:i,detail:s,icon:"copy",color:"info"}))},createButton({tabId:n,groupId:o,location:s,button:i}){e(l=>Ne(l,r=>{const d=r[s].tabs.find(u=>u.id===n)?.groups.find(u=>u.id===o);if(d){const u=new Set(d.buttons.map(b=>b.sequence)),p=Math.max(0,...d.buttons.map(b=>b.sequence))+10,m=i.sequence!==void 0&&!u.has(i.sequence)?i.sequence:p,g={...i,id:i.id??`new_${Date.now()}`,label:i.label??"New Button",kind:i.kind??"button",sequence:m,templateAlias:i.templateAlias??"o1",commandId:i.commandId??"",hidden:i.hidden??!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"};Cn(g.kind)&&!g.menu&&(g.menu=_s(g.id)),d.buttons.push(g)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:i.label??"New Button",detail:o,icon:"add",color:"success"}))},createGroup({tabId:n,location:o,group:s}){e(i=>Ne(i,l=>{const r=l[o].tabs.find(c=>c.id===n);if(r){const c=l[o],d=o==="Application"?"global":c.entityLogicalName,u={id:s.id??Pr(d,`${o}.${s.label??"New Group"}`,"Group",Wn(i,l)),label:s.label??"New Group",sequence:s.sequence!==void 0&&!r.groups.some(p=>p.sequence===s.sequence)?s.sequence:Math.max(0,...r.groups.map(p=>p.sequence))+10,template:s.template??"Flexible2",buttons:s.buttons??[]};r.groups.push(u)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:s.label??"New Group",detail:n,icon:"add",color:"success"}))},renameGroup(n,o,s,i){e(l=>Ne(l,r=>{const d=r[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===s);d&&(d.label=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:s,detail:i,icon:"edit",color:"info"}))},duplicateGroup(n,o,s){let i=null;if(e(l=>Ne(l,r=>{const c=r[n].tabs.find($=>$.id===o);if(!c)return;const d=c.groups.find($=>$.id===s);if(!d)return;const u=`_copy_${Date.now()}`,p=Us(),m=io(l),g=l.baseLanguageCode,b=d.source?.titleToken,f=b!==void 0&&Ge(b,l.locLabels,g)===d.label?b:d.label,y=to(f)||no(f,m),x={...JSON.parse(JSON.stringify(d)),id:`${Vs(d.id,p)}${u}`,label:y?Ge(f,l.locLabels,g):`${Ge(d.label,l.locLabels,g)} (copy)`,source:y?{titleToken:f,attributes:{}}:void 0,description:void 0,sequence:d.sequence,buttons:d.buttons.map($=>Jo($,`${Vs($.id,p)}${u}`,m))},v=c.groups.findIndex($=>$.id===s);c.groups.splice(v+1,0,x);const C=new Set((l.baseline[n]?.tabs??[]).flatMap($=>$.groups.map(A=>A.id)));Hr(c.groups,v+1,$=>$===x||!C.has($.id)),y&&(i={copyId:x.id,title:f})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:s,detail:o,icon:"copy",color:"info"})),i){const{copyId:l,title:r}=i;ce.getState().logInfo("ribbon",`Duplicate group ${s}: the copy ${l} keeps its title ${r}, which comes from ${to(r)?"the platform":"another solution"} and can't take " (copy)". Rename the copy before you publish if it should read differently: once published, only titles of your own can be renamed.`)}},setGroupTemplate(n,o,s,i){e(l=>Ne(l,r=>{const d=r[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===s);d&&(d.template=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:s,detail:`template → ${i}`,icon:"edit",color:"info"}))},deleteGroup(n,o,s){const i=t(),l=i.ribbons[n].tabs.find(r=>r.id===o)?.groups.find(r=>r.id===s);if(l&&!La(l,i.baseline[n],Rn(i,n))){ce.getState().logWarn("ribbon",`Group "${l.label}" (${s}) was not deleted: only your own groups, with only your own buttons in them, can be deleted — hide its buttons instead.`);return}e(r=>Ne(r,c=>{const d=c[n].tabs.find(u=>u.id===o);d&&(d.groups=d.groups.filter(u=>u.id!==s))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:s,detail:o,icon:"delete",color:"danger"}))},createTab(n,o){e(s=>o.id&&Wn(s,s.ribbons).has(o.id)?{}:Ne(s,i=>{const l=i[n],r=n==="Application"?"global":l.entityLogicalName,c=o.id??Pr(r,`${n}.${o.label??"New Tab"}`,"Tab",Wn(s,i)),d=id({...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:ad(n,l.entityLogicalName,d),groups:[]};l.tabs.push(u)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:o.label??"New Tab",detail:n,icon:"add",color:"success"}))},renameTab(n,o,s){e(i=>Ne(i,l=>{const r=l[n].tabs.find(c=>c.id===o);r&&(r.label=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:o,detail:s,icon:"edit",color:"info"}))},deleteTab(n,o){const s=t(),i=s.ribbons[n].tabs.find(l=>l.id===o);if(i&&!bd(i,s.baseline[n],Rn(s,n))){ce.getState().logWarn("ribbon",`Tab "${i.label}" (${o}) was not deleted: only your own tabs, with only your own groups and buttons in them, can be deleted.`);return}e(l=>Ne(l,r=>{r[n].tabs=r[n].tabs.filter(c=>c.id!==o)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:o,detail:n,icon:"delete",color:"danger"}))},reorderTabs(n,o){e(s=>Ne(s,i=>{const l=i[n].tabs,r=o.map(u=>l.find(p=>p.id===u)).filter(u=>u!==void 0);i[n].tabs=r;const c=new Set(s.baseline[n]?.tabs.map(u=>u.id)??[]),d=new Set(Rn(s,n)??[]);Wr(r,u=>!c.has(u.id)||d.has(u.id))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:"Tabs",detail:n,icon:"arrow_sort",color:"info"}))},moveGroup(n,o,s,i){const l=t();if(!Nd(l,n,o,s,i))return;const r=l.ribbons[n].tabs.find(c=>c.id===o)?.groups.find(c=>c.id===s)?.label??s;e(c=>Ne(c,d=>{const u=d[n].tabs.find(b=>b.id===o);if(!u)return;u.groups.sort((b,f)=>b.sequence-f.sequence);const p=u.groups.findIndex(b=>b.id===s),[m]=u.groups.splice(p,1);u.groups.splice(p+i,0,m);const g=Td(c,n);Wr(u.groups,g)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:r,detail:i<0?"Moved left":"Moved right",icon:"arrow_sort",color:"info"}))},setTabDisplayRules(n,o,s){e(i=>Ne(i,l=>{const r=l[n].tabs.find(c=>c.id===o);r&&(r.tabDisplayRules=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} display rules`,detail:`${s.length} rule(s)`,icon:"eye",color:"info"}))},setScaling(n,o,s){e(i=>Ne(i,l=>{const r=l[n];r.scalingByTab=r.scalingByTab??{},r.scalingByTab[o]={tabId:o,maxSizes:[...s.maxSizes],scales:[...s.scales]}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} scaling`,detail:`${s.maxSizes.length} MaxSize, ${s.scales.length} Scale`,icon:"resize",color:"info"}))},hideOobButton(n,o,s,i){e(l=>Ne(l,r=>{const c=gt(r,n,o,s,i)?.button;c&&(rt(n,o,c)||(c.hidden=!0))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"hid",target:i,detail:s,icon:"eye_off",color:"warn"}))},customizeOobButton(n,o,s,i){e(l=>Ne(l,r=>{const c=gt(r,n,o,s,i)?.button;if(c){if(rt(n,o,c))return;c.oob=!1,c.custom=!0,c.managed=!1,c.origin="unmanaged"}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"customized",target:i,detail:"OOB override",icon:"edit",color:"info"}))},customiseButton(n,o,s,i,l){const r=t(),c=r.ribbons[n].tabs.find(x=>x.id===o)?.groups.find(x=>x.id===s)?.buttons.find(x=>x.id===i);if(!c||!Wa(n,o,c))return null;const d=Wn(r,r.ribbons),u=`${(l||"new").trim()}.${c.id}`;let p=u;for(let x=2;d.has(p);x++)p=`${u}.${x}`;const m=[],g=[],b=io(r),f=[[c.source?.labelToken,bs(p)],[c.source?.tooltipTitleToken,ys(p)],[c.source?.tooltipBodyToken,xs(p)]];for(const[x,v]of f){if(!x||!os.test(x))continue;const C=r.locLabels.find($=>$.id===x.replace(os,""));C?m.push({id:v,titles:C.titles.map($=>({...$}))}):no(x,b)&&g.push(x)}g.length>0&&ce.getState().logInfo("ribbon",`Customise button ${c.id}: ${g.join(", ")} ${g.length===1?"is":"are"} defined by another solution, so the copy ${p} uses ${g.length===1?"it":"them"} too. Edit the copy's text to give it a label of its own.`);const y=new Set(m.map(x=>x.id));return e(x=>{const v=at(x.ribbons),C=v[n].tabs.find(R=>R.id===o)?.groups.find(R=>R.id===s),$=C?.buttons.findIndex(R=>R.id===i)??-1;if(!C||$<0)return{};const A=C.buttons[$],j={...A,id:p,source:Ny(A.source,b),hidden:!1,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0},T=C.buttons[$+1]?.sequence;return(T===void 0||A.sequence+1<T)&&(j.sequence=A.sequence+1),A.hidden=!0,C.buttons.splice($+1,0,j),Fe(x,{ribbons:v,...m.length>0?{locLabels:[...x.locLabels.filter(R=>!y.has(R.id)),...m]}:{}},Ae("customised",i,`copied to ${p}, original hidden`+(g.length>0?" (keeps another solution's labels)":""),"copy"))}),p},customiseCommand(n){const o=t();return!o.commands.some(s=>s.id===n)||o.reloadRequiredCommandIds.includes(n)?!1:(e(s=>Fe(s,{customisedCommandIds:[...s.customisedCommandIds.filter(i=>i!==n),n],uncustomisedCommandIds:Ks(s.uncustomisedCommandIds,n)},Ae("customised",n,"command copied to your layer on publish","code"))),!0)},uncustomiseCommand(n,o){e(s=>Fe(s,{commands:Gr(s,n),customisedCommandIds:s.customisedCommandIds.filter(i=>i!==n),uncustomisedCommandIds:{...Ks(s.uncustomisedCommandIds,n),[o]:[...s.uncustomisedCommandIds[o].filter(i=>i!==n),n]}},Ae("uncustomised",n,`command removed from the ${o==="entity"?"table's":"application ribbon's"} layer on publish`,"arrow_undo")))},discardCommandChanges(n){const o=t(),s=Gr(o,n);(s!==o.commands||o.customisedCommandIds.includes(n)||o.uncustomisedCommandIds.entity.includes(n)||o.uncustomisedCommandIds.application.includes(n))&&e(l=>Fe(l,{commands:s,customisedCommandIds:l.customisedCommandIds.filter(r=>r!==n),uncustomisedCommandIds:Ks(l.uncustomisedCommandIds,n)},Ae("discarded",n,"command changes","arrow_undo")))},setOpenRecordOverride(n,o,s){if(!Sd.includes(n))return!1;const i=t(),l=i.ribbons[n],r=Cd(l);if(o){if(r.length>0)return!0;const c=jd(l);if(!c)return!1;const d=Wn(i,i.ribbons);for(const p of i.commands)d.add(p.id);const{id:u}=vd(s,l.entityLogicalName,n,"OpenRecordItem",d);return t().batch(()=>{t().createButton({location:n,tabId:c.tabId,groupId:c.groupId,button:{id:u,label:"Open record",tooltipTitle:"Open record",tooltipBody:`Runs the table's ${Xe} action for the selected row, as opening a row does.`,kind:"button",templateAlias:"o1",commandId:Xe,hidden:!1,oob:!1,custom:!0,managed:!1}}),t().commands.some(p=>p.id===Xe)||t().upsertCommand(wy())}),!0}return r.length===0?!0:r.some(c=>Id(c)!=="yours")?!1:(t().batch(()=>{for(const u of r)t().deleteButton(n,u.tabId,u.groupId,u.button.id);const c=t();!Object.values(c.ribbons).some(u=>qa(u).length>0)&&!c.baselineCommands.some(u=>u.id===Xe)&&e(u=>Fe(u,{commands:u.commands.filter(p=>p.id!==Xe)},Ae("removed",Xe,"grid open override","delete","danger")))}),!0)},hideWithDisplayRules(n){const o=n?t().commands.find(i=>i.id===n):void 0;if(!o)return!1;const s=[...o.displayRules];for(const i of Iy)s.includes(i)||s.push(i);return e(i=>{const l=Hn(i.commands,{...o,displayRules:s});return l?Fe(i,{commands:l},Ae("hid",o.id,"with display rules","eye_off","warn")):i}),!0},upsertCommand(n){e(o=>{const s=Hn(o.commands,n);if(!s)return o;const i=s.length>o.commands.length;return Fe(o,{commands:s},i?Ae("added",n.id,"command","add","success"):Ae("edited",n.id,"command","edit"),i?void 0:`command:${n.id}`)})},renameCommandId(n,o){const s=t();return!n||!o||n===o?!0:s.commands.some(i=>i.id===o)?!1:(e(i=>{const l=at(i.ribbons);for(const c of Object.keys(l))for(const d of l[c].tabs)for(const u of d.groups)for(const p of Te(u))p.commandId===n&&(p.commandId=o),p.source?.xml&&(p.source.xml=ib(p.source.xml,n,o));const r=i.commands.map(c=>c.id===n?{...c,id:o}:c);return Fe(i,{ribbons:l,commands:r},Ae("renamed",n,`command -> ${o}`,"edit"))}),!0)},upsertDisplayRule(n){e(o=>{const s=Hn(o.displayRules,n);if(!s)return o;const i=s.length>o.displayRules.length;return Fe(o,{displayRules:s},i?Ae("added",n.id,"display rule","add","success"):Ae("edited",n.id,"display rule","edit"),i?void 0:`displayRule:${n.id}`)})},renameDisplayRuleId(n,o){const s=t();return!n||!o||n===o?!0:s.displayRules.some(i=>i.id===o)?!1:(e(i=>{const l=i.displayRules.map(c=>c.id===n?{...c,id:o}:c),r=i.commands.map(c=>({...c,displayRules:c.displayRules.map(d=>d===n?o:d)}));return Fe(i,{displayRules:l,commands:r},Ae("renamed",n,`display rule -> ${o}`,"edit"))}),!0)},upsertEnableRule(n){e(o=>{const s=Hn(o.enableRules,n);if(!s)return o;const i=s.length>o.enableRules.length;return Fe(o,{enableRules:s},i?Ae("added",n.id,"enable rule","add","success"):Ae("edited",n.id,"enable rule","edit"),i?void 0:`enableRule:${n.id}`)})},renameEnableRuleId(n,o){const s=t();return!n||!o||n===o?!0:s.enableRules.some(i=>i.id===o)?!1:(e(i=>{const l=i.enableRules.map(c=>c.id===n?{...c,id:o}:c),r=i.commands.map(c=>({...c,enableRules:c.enableRules.map(d=>d===n?o:d)}));return Fe(i,{enableRules:l,commands:r},Ae("renamed",n,`enable rule -> ${o}`,"edit"))}),!0)},upsertLocLabel(n){e(o=>{const s=Hn(o.locLabels,n);return s?Fe(o,{locLabels:s},Ae("edited",n.id,"label","translate"),`locLabel:${n.id}`):o})},setLayerHideUnhidden(n,o,s){e(i=>{if(i.pendingUnhides[n].includes(o)===s)return i;const l=i.pendingUnhides[n].filter(r=>r!==o);return s&&l.push(o),Fe(i,{pendingUnhides:{...i.pendingUnhides,[n]:l}},s?Ae("un-hid",o,"on publish","eye"):Ae("kept hidden",o,"by customizations","eye_off"))})},setOrphanDeleted(n,o,s){e(i=>{const l=i.orphans[n].find(c=>c.id===o);if(!l||s&&l.recentPublish?.published||i.pendingOrphanDeletes[n].includes(o)===s)return i;const r=i.pendingOrphanDeletes[n].filter(c=>c!==o);return s&&r.push(o),Fe(i,{pendingOrphanDeletes:{...i.pendingOrphanDeletes,[n]:r}},s?Ae("deleted",o,"not on the canvas — removed on publish","delete","danger"):Ae("kept",o,"not on the canvas","arrow_undo"))})},setLayerSnapshot(n,o){e(s=>({layers:{...s.layers,[n]:o}}))},markPublished(n,o){e(s=>{const i=Object.keys(s.ribbons),l=n??i,r=at(s.baseline),c=at(s.ribbons);let d=s.locLabels,u=s.baselineLocLabels;const p=(S,k)=>[...S.filter(w=>!k.some(D=>D.id===w.id)),...k];for(const[S,k]of Object.entries(o??{})){const w=S==="entity"?qr:["Application"];for(const F of w)l.includes(F)&&bb(c[F],k);const D=_i(k);d=p(d,D),u=p(u,JSON.parse(JSON.stringify(D)))}for(const S of l)r[S]=at(c)[S];const m=i.every(S=>l.includes(S)),g={...s.layers},b={...s.pendingUnhides},f={entity:[],application:[]},y=[["entity",qr.every(S=>l.includes(S))],["application",l.includes("Application")]];for(const[S,k]of y){const w=o?.[S];if(!k||!w)continue;const D=g[S],F=(X,ne)=>[...new Set([...X,...ne])];g[S]=D?{...D,containerIds:F(D.containerIds,Jc(w)),controlIds:F(D.controlIds,Ko(w)),locLabelIds:F(D.locLabelIds,new Set(w.locLabels.keys()))}:es(w)}for(const[S,k]of y){if(!k||b[S].length===0)continue;const w=g[S];w&&(g[S]={...w,hides:w.hides.filter(D=>!b[S].includes(D.location))}),f[S]=b[S],b[S]=[]}const x={...s.orphans},v={...s.pendingOrphanDeletes},C={entity:[],application:[]};for(const[S,k]of y)!k||v[S].length===0||(x[S]=x[S].filter(w=>!v[S].includes(w.id)),C[S]=v[S],v[S]=[]);const $={...s.uncustomisedCommandIds},A=[...s.reloadRequiredCommandIds],j={entity:[],application:[]};for(const[S,k]of y)if(k){for(const w of $[S])A.includes(w)||A.push(w);j[S]=$[S],$[S]=[]}const T=(S,k)=>({entity:S.entity.filter(w=>!k.entity.includes(w)),application:S.application.filter(w=>!k.application.includes(w))}),R=S=>({...S,snapshot:{...S.snapshot,pendingUnhides:T(S.snapshot.pendingUnhides,f),pendingOrphanDeletes:T(S.snapshot.pendingOrphanDeletes??Gs,C),uncustomisedCommandIds:T(S.snapshot.uncustomisedCommandIds,j)}}),I=[f,j,C].reduce((S,k)=>S+k.entity.length+k.application.length,0)>0,N=s.past.map((S,k)=>{const w=I?R(S):S;return k===s.past.length-1&&w.coalesceKey?{...w,coalesceKey:void 0}:w}),B={ribbons:c,locLabels:d,baselineLocLabels:u,baseline:r,layers:g,pendingUnhides:b,uncustomisedCommandIds:$,orphans:x,pendingOrphanDeletes:v,...m?{baselineCommands:JSON.parse(JSON.stringify(s.commands)),baselineEnableRules:JSON.parse(JSON.stringify(s.enableRules)),baselineDisplayRules:JSON.parse(JSON.stringify(s.displayRules)),baselineLocLabels:JSON.parse(JSON.stringify(d)),customisedCommandIds:[]}:{}},O=so({...s,...B});return{...B,past:N,future:I?s.future.map(R):s.future,reloadRequiredCommandIds:A,mutationsSincePublish:O?Math.max(1,s.mutationsSincePublish):0}})}})));Gg(()=>{M.getState().resetWorkspace(),Y.getState().clearSelection()});var Oe=Uint8Array,ct=Uint16Array,Ha=Int32Array,Rs=new Oe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),$s=new Oe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),qi=new Oe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ad=function(e,t){for(var n=new ct(31),o=0;o<31;++o)n[o]=t+=1<<e[o-1];for(var s=new Ha(n[30]),o=1;o<30;++o)for(var i=n[o];i<n[o+1];++i)s[i]=i-n[o]<<5|o;return{b:n,r:s}},Od=Ad(Rs,2),Md=Od.b,Wi=Od.r;Md[28]=258,Wi[258]=28;var Dd=Ad($s,0),ky=Dd.b,Ur=Dd.r,Hi=new ct(32768);for(var Re=0;Re<32768;++Re){var Lt=(Re&43690)>>1|(Re&21845)<<1;Lt=(Lt&52428)>>2|(Lt&13107)<<2,Lt=(Lt&61680)>>4|(Lt&3855)<<4,Hi[Re]=((Lt&65280)>>8|(Lt&255)<<8)>>1}var Rt=(function(e,t,n){for(var o=e.length,s=0,i=new ct(t);s<o;++s)e[s]&&++i[e[s]-1];var l=new ct(t);for(s=1;s<t;++s)l[s]=l[s-1]+i[s-1]<<1;var r;if(n){r=new ct(1<<t);var c=15-t;for(s=0;s<o;++s)if(e[s])for(var d=s<<4|e[s],u=t-e[s],p=l[e[s]-1]++<<u,m=p|(1<<u)-1;p<=m;++p)r[Hi[p]>>c]=d}else for(r=new ct(o),s=0;s<o;++s)e[s]&&(r[s]=Hi[l[e[s]-1]++]>>15-e[s]);return r}),Xt=new Oe(288);for(var Re=0;Re<144;++Re)Xt[Re]=8;for(var Re=144;Re<256;++Re)Xt[Re]=9;for(var Re=256;Re<280;++Re)Xt[Re]=7;for(var Re=280;Re<288;++Re)Xt[Re]=8;var fo=new Oe(32);for(var Re=0;Re<32;++Re)fo[Re]=5;var Ay=Rt(Xt,9,0),Oy=Rt(Xt,9,1),My=Rt(fo,5,0),Dy=Rt(fo,5,1),Ys=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},bt=function(e,t,n){var o=t/8|0;return(e[o]|e[o+1]<<8)>>(t&7)&n},Js=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Ga=function(e){return(e+7)/8|0},vo=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Oe(e.subarray(t,n))},Ey=["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"],Ve=function(e,t,n){var o=new Error(t||Ey[e]);if(o.code=e,Error.captureStackTrace&&Error.captureStackTrace(o,Ve),!n)throw o;return o},By=function(e,t,n,o){var s=e.length,i=o?o.length:0;if(!s||t.f&&!t.l)return n||new Oe(0);var l=!n,r=l||t.i!=2,c=t.i;l&&(n=new Oe(s*3));var d=function(We){var Be=n.length;if(We>Be){var Le=new Oe(Math.max(Be*2,We));Le.set(n),n=Le}},u=t.f||0,p=t.p||0,m=t.b||0,g=t.l,b=t.d,f=t.m,y=t.n,x=s*8;do{if(!g){u=bt(e,p,1);var v=bt(e,p+1,3);if(p+=3,v)if(v==1)g=Oy,b=Dy,f=9,y=5;else if(v==2){var j=bt(e,p,31)+257,T=bt(e,p+10,15)+4,R=j+bt(e,p+5,31)+1;p+=14;for(var I=new Oe(R),N=new Oe(19),B=0;B<T;++B)N[qi[B]]=bt(e,p+B*3,7);p+=T*3;for(var O=Ys(N),S=(1<<O)-1,k=Rt(N,O,1),B=0;B<R;){var w=k[bt(e,p,S)];p+=w&15;var C=w>>4;if(C<16)I[B++]=C;else{var D=0,F=0;for(C==16?(F=3+bt(e,p,3),p+=2,D=I[B-1]):C==17?(F=3+bt(e,p,7),p+=3):C==18&&(F=11+bt(e,p,127),p+=7);F--;)I[B++]=D}}var X=I.subarray(0,j),ne=I.subarray(j);f=Ys(X),y=Ys(ne),g=Rt(X,f,1),b=Rt(ne,y,1)}else Ve(1);else{var C=Ga(p)+4,$=e[C-4]|e[C-3]<<8,A=C+$;if(A>s){c&&Ve(0);break}r&&d(m+$),n.set(e.subarray(C,A),m),t.b=m+=$,t.p=p=A*8,t.f=u;continue}if(p>x){c&&Ve(0);break}}r&&d(m+131072);for(var re=(1<<f)-1,le=(1<<y)-1,_=p;;_=p){var D=g[Js(e,p)&re],L=D>>4;if(p+=D&15,p>x){c&&Ve(0);break}if(D||Ve(2),L<256)n[m++]=L;else if(L==256){_=p,g=null;break}else{var U=L-254;if(L>264){var B=L-257,W=Rs[B];U=bt(e,p,(1<<W)-1)+Md[B],p+=W}var te=b[Js(e,p)&le],P=te>>4;te||Ve(3),p+=te&15;var ne=ky[P];if(P>3){var W=$s[P];ne+=Js(e,p)&(1<<W)-1,p+=W}if(p>x){c&&Ve(0);break}r&&d(m+131072);var Q=m+U;if(m<ne){var be=i-ne,Ee=Math.min(ne,Q);for(be+m<0&&Ve(3);m<Ee;++m)n[m]=o[be+m]}for(;m<Q;++m)n[m]=n[m-ne]}}t.l=g,t.p=_,t.b=m,t.f=u,g&&(u=1,t.m=f,t.d=b,t.n=y)}while(!u);return m!=n.length&&l?vo(n,0,m):n.subarray(0,m)},Nt=function(e,t,n){n<<=t&7;var o=t/8|0;e[o]|=n,e[o+1]|=n>>8},Gn=function(e,t,n){n<<=t&7;var o=t/8|0;e[o]|=n,e[o+1]|=n>>8,e[o+2]|=n>>16},Zs=function(e,t){for(var n=[],o=0;o<e.length;++o)e[o]&&n.push({s:o,f:e[o]});var s=n.length,i=n.slice();if(!s)return{t:Bd,l:0};if(s==1){var l=new Oe(n[0].s+1);return l[n[0].s]=1,{t:l,l:1}}n.sort(function(A,j){return A.f-j.f}),n.push({s:-1,f:25001});var r=n[0],c=n[1],d=0,u=1,p=2;for(n[0]={s:-1,f:r.f+c.f,l:r,r:c};u!=s-1;)r=n[n[d].f<n[p].f?d++:p++],c=n[d!=u&&n[d].f<n[p].f?d++:p++],n[u++]={s:-1,f:r.f+c.f,l:r,r:c};for(var m=i[0].s,o=1;o<s;++o)i[o].s>m&&(m=i[o].s);var g=new ct(m+1),b=Gi(n[u-1],g,0);if(b>t){var o=0,f=0,y=b-t,x=1<<y;for(i.sort(function(j,T){return g[T.s]-g[j.s]||j.f-T.f});o<s;++o){var v=i[o].s;if(g[v]>t)f+=x-(1<<b-g[v]),g[v]=t;else break}for(f>>=y;f>0;){var C=i[o].s;g[C]<t?f-=1<<t-g[C]++-1:++o}for(;o>=0&&f;--o){var $=i[o].s;g[$]==t&&(--g[$],++f)}b=t}return{t:new Oe(g),l:b}},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},Vr=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new ct(++t),o=0,s=e[0],i=1,l=function(c){n[o++]=c},r=1;r<=t;++r)if(e[r]==s&&r!=t)++i;else{if(!s&&i>2){for(;i>138;i-=138)l(32754);i>2&&(l(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(l(s),--i;i>6;i-=6)l(8304);i>2&&(l(i-3<<5|8208),i=0)}for(;i--;)l(s);i=1,s=e[r]}return{c:n.subarray(0,o),n:t}},Un=function(e,t){for(var n=0,o=0;o<t.length;++o)n+=e[o]*t[o];return n},Ed=function(e,t,n){var o=n.length,s=Ga(t+2);e[s]=o&255,e[s+1]=o>>8,e[s+2]=e[s]^255,e[s+3]=e[s+1]^255;for(var i=0;i<o;++i)e[s+i+4]=n[i];return(s+4+o)*8},Xr=function(e,t,n,o,s,i,l,r,c,d,u){Nt(t,u++,n),++s[256];for(var p=Zs(s,15),m=p.t,g=p.l,b=Zs(i,15),f=b.t,y=b.l,x=Vr(m),v=x.c,C=x.n,$=Vr(f),A=$.c,j=$.n,T=new ct(19),R=0;R<v.length;++R)++T[v[R]&31];for(var R=0;R<A.length;++R)++T[A[R]&31];for(var I=Zs(T,7),N=I.t,B=I.l,O=19;O>4&&!N[qi[O-1]];--O);var S=d+5<<3,k=Un(s,Xt)+Un(i,fo)+l,w=Un(s,m)+Un(i,f)+l+14+3*O+Un(T,N)+2*T[16]+3*T[17]+7*T[18];if(c>=0&&S<=k&&S<=w)return Ed(t,u,e.subarray(c,c+d));var D,F,X,ne;if(Nt(t,u,1+(w<k)),u+=2,w<k){D=Rt(m,g,0),F=m,X=Rt(f,y,0),ne=f;var re=Rt(N,B,0);Nt(t,u,C-257),Nt(t,u+5,j-1),Nt(t,u+10,O-4),u+=14;for(var R=0;R<O;++R)Nt(t,u+3*R,N[qi[R]]);u+=3*O;for(var le=[v,A],_=0;_<2;++_)for(var L=le[_],R=0;R<L.length;++R){var U=L[R]&31;Nt(t,u,re[U]),u+=N[U],U>15&&(Nt(t,u,L[R]>>5&127),u+=L[R]>>12)}}else D=Ay,F=Xt,X=My,ne=fo;for(var R=0;R<r;++R){var W=o[R];if(W>255){var U=W>>18&31;Gn(t,u,D[U+257]),u+=F[U+257],U>7&&(Nt(t,u,W>>23&31),u+=Rs[U]);var te=W&31;Gn(t,u,X[te]),u+=ne[te],te>3&&(Gn(t,u,W>>5&8191),u+=$s[te])}else Gn(t,u,D[W]),u+=F[W]}return Gn(t,u,D[256]),u+F[256]},Ly=new Ha([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Bd=new Oe(0),zy=function(e,t,n,o,s,i){var l=i.z||e.length,r=new Oe(o+l+5*(1+Math.ceil(l/7e3))+s),c=r.subarray(o,r.length-s),d=i.l,u=(i.r||0)&7;if(t){u&&(c[0]=i.r>>3);for(var p=Ly[t-1],m=p>>13,g=p&8191,b=(1<<n)-1,f=i.p||new ct(32768),y=i.h||new ct(b+1),x=Math.ceil(n/3),v=2*x,C=function(et){return(e[et]^e[et+1]<<x^e[et+2]<<v)&b},$=new Ha(25e3),A=new ct(288),j=new ct(32),T=0,R=0,I=i.i||0,N=0,B=i.w||0,O=0;I+2<l;++I){var S=C(I),k=I&32767,w=y[S];if(f[k]=w,y[S]=k,B<=I){var D=l-I;if((T>7e3||N>24576)&&(D>423||!d)){u=Xr(e,c,0,$,A,j,R,N,O,I-O,u),N=T=R=0,O=I;for(var F=0;F<286;++F)A[F]=0;for(var F=0;F<30;++F)j[F]=0}var X=2,ne=0,re=g,le=k-w&32767;if(D>2&&S==C(I-le))for(var _=Math.min(m,D)-1,L=Math.min(32767,I),U=Math.min(258,D);le<=L&&--re&&k!=w;){if(e[I+X]==e[I+X-le]){for(var W=0;W<U&&e[I+W]==e[I+W-le];++W);if(W>X){if(X=W,ne=le,W>_)break;for(var te=Math.min(le,W-2),P=0,F=0;F<te;++F){var Q=I-le+F&32767,be=f[Q],Ee=Q-be&32767;Ee>P&&(P=Ee,w=Q)}}}k=w,w=f[k],le+=k-w&32767}if(ne){$[N++]=268435456|Wi[X]<<18|Ur[ne];var We=Wi[X]&31,Be=Ur[ne]&31;R+=Rs[We]+$s[Be],++A[257+We],++j[Be],B=I+X,++T}else $[N++]=e[I],++A[e[I]]}}for(I=Math.max(I,B);I<l;++I)$[N++]=e[I],++A[e[I]];u=Xr(e,c,d,$,A,j,R,N,O,I-O,u),d||(i.r=u&7|c[u/8|0]<<3,u-=7,i.h=y,i.p=f,i.i=I,i.w=B)}else{for(var I=i.w||0;I<l+d;I+=65535){var Le=I+65535;Le>=l&&(c[u/8|0]=d,Le=l),u=Ed(c,u+1,e.subarray(I,Le))}i.i=l}return vo(r,0,o+Ga(u)+s)},Py=(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})(),Fy=function(){var e=-1;return{p:function(t){for(var n=e,o=0;o<t.length;++o)n=Py[n&255^t[o]]^n>>>8;e=n},d:function(){return~e}}},_y=function(e,t,n,o,s){if(!s&&(s={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new Oe(i.length+e.length);l.set(i),l.set(e,i.length),e=l,s.w=i.length}return zy(e,t.level==null?6:t.level,t.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,o,s)},Ld=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},Ct=function(e,t){return e[t]|e[t+1]<<8},pt=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Qs=function(e,t){return pt(e,t)+pt(e,t+4)*4294967296},He=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function zd(e,t){return _y(e,t||{},0,0)}function Pd(e,t){return By(e,{i:2},t&&t.out,t&&t.dictionary)}var Fd=function(e,t,n,o){for(var s in e){var i=e[s],l=t+s,r=o;Array.isArray(i)&&(r=Ld(o,i[1]),i=i[0]),ArrayBuffer.isView(i)?n[l]=[i,r]:(n[l+="/"]=[new Oe(0),r],Fd(i,l,n,o))}},Kr=typeof TextEncoder<"u"&&new TextEncoder,Ui=typeof TextDecoder<"u"&&new TextDecoder,qy=0;try{Ui.decode(Bd,{stream:!0}),qy=1}catch{}var Wy=function(e){for(var t="",n=0;;){var o=e[n++],s=(o>127)+(o>223)+(o>239);if(n+s>e.length)return{s:t,r:vo(e,n-1)};s?s==3?(o=((o&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|o>>10,56320|o&1023)):s&1?t+=String.fromCharCode((o&31)<<6|e[n++]&63):t+=String.fromCharCode((o&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(o)}};function ss(e,t){if(t){for(var n=new Oe(e.length),o=0;o<e.length;++o)n[o]=e.charCodeAt(o);return n}if(Kr)return Kr.encode(e);for(var s=e.length,i=new Oe(e.length+(e.length>>1)),l=0,r=function(u){i[l++]=u},o=0;o<s;++o){if(l+5>i.length){var c=new Oe(l+8+(s-o<<1));c.set(i),i=c}var d=e.charCodeAt(o);d<128||t?r(d):d<2048?(r(192|d>>6),r(128|d&63)):d>55295&&d<57344?(d=65536+(d&1047552)|e.charCodeAt(++o)&1023,r(240|d>>18),r(128|d>>12&63),r(128|d>>6&63),r(128|d&63)):(r(224|d>>12),r(128|d>>6&63),r(128|d&63))}return vo(i,0,l)}function Ts(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(Ui)return Ui.decode(e);var s=Wy(e),i=s.s,n=s.r;return n.length&&Ve(8),i}}var Hy=function(e,t){return t+30+Ct(e,t+26)+Ct(e,t+28)},Gy=function(e,t,n){var o=Ct(e,t+28),s=Ct(e,t+30),i=Ts(e.subarray(t+46,t+46+o),!(Ct(e,t+8)&2048)),l=t+46+o,r=Uy(e,l,s,n,pt(e,t+20),pt(e,t+24),pt(e,t+42)),c=r[0],d=r[1],u=r[2];return[Ct(e,t+10),c,d,i,l+s+Ct(e,t+32),u]},Uy=function(e,t,n,o,s,i,l){var r=s==4294967295,c=i==4294967295,d=l==4294967295,u=t+n,p=r+c+d;if(o&&p){for(;t+4<u;t+=4+Ct(e,t+2))if(Ct(e,t)==1)return[r?Qs(e,t+4+8*c):s,c?Qs(e,t+4):i,d?Qs(e,t+4+8*(c+r)):l,1];o<2&&Ve(13)}return[s,i,l,0]},Vi=function(e){var t=0;if(e)for(var n in e){var o=e[n].length;o>65535&&Ve(9),t+=o+4}return t},Yr=function(e,t,n,o,s,i,l,r){var c=o.length,d=n.extra,u=r&&r.length,p=Vi(d);He(e,t,l!=null?33639248:67324752),t+=4,l!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(i<0&&8),e[t++]=s&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var m=new Date(n.mtime==null?Date.now():n.mtime),g=m.getFullYear()-1980;if((g<0||g>119)&&Ve(10),He(e,t,g<<25|m.getMonth()+1<<21|m.getDate()<<16|m.getHours()<<11|m.getMinutes()<<5|m.getSeconds()>>1),t+=4,i!=-1&&(He(e,t,n.crc),He(e,t+4,i<0?-i-2:i),He(e,t+8,n.size)),He(e,t+12,c),He(e,t+14,p),t+=16,l!=null&&(He(e,t,u),He(e,t+6,n.attrs),He(e,t+10,l),t+=14),e.set(o,t),t+=c,p)for(var b in d){var f=d[b],y=f.length;He(e,t,+b),He(e,t+2,y),e.set(f,t+4),t+=4+y}return u&&(e.set(r,t),t+=u),t},Vy=function(e,t,n,o,s){He(e,t,101010256),He(e,t+8,n),He(e,t+10,n),He(e,t+12,o),He(e,t+16,s)};function dI(e,t){t||(t={});var n={},o=[];Fd(e,"",n,t);var s=0,i=0;for(var l in n){var r=n[l],c=r[0],d=r[1],u=d.level==0?0:8,p=ss(l),m=p.length,g=d.comment,b=g&&ss(g),f=b&&b.length,y=Vi(d.extra);m>65535&&Ve(11);var x=u?zd(c,d):c,v=x.length,C=Fy();C.p(c),o.push(Ld(d,{size:c.length,crc:C.d(),c:x,f:p,m:b,u:m!=l.length||b&&g.length!=f,o:s,compression:u})),s+=30+m+y+v,i+=76+2*(m+y)+(f||0)+v}for(var $=new Oe(i+22),A=s,j=i-s,T=0;T<o.length;++T){var p=o[T];Yr($,p.o,p,p.f,p.u,p.c.length);var R=30+p.f.length+Vi(p.extra);$.set(p.c,p.o+R),Yr($,s,p,p.f,p.u,p.c.length,p.o,p.m),s+=16+R+(p.m?p.m.length:0)}return Vy($,s,o.length,j,A),$}function Xy(e,t){for(var n={},o=e.length-22;pt(e,o)!=101010256;--o)(!o||e.length-o>65558)&&Ve(13);var s=Ct(e,o+8);if(!s)return{};var i=pt(e,o+16),l=pt(e,o-20)==117853008;if(l){var r=pt(e,o-12);l=pt(e,r)==101075792,l&&(s=pt(e,r+32),i=pt(e,r+48))}for(var c=0;c<s;++c){var d=Gy(e,i,l),u=d[0],p=d[1],m=d[2],g=d[3],b=d[4],f=d[5],y=Hy(e,f);i=b,u?u==8?n[g]=Pd(e.subarray(y,y+p),{out:new Oe(m)}):Ve(14,"unknown compression type "+u):n[g]=vo(e,y,y+p)}return n}const Ns=4,_d=30,qd=`cbs:draft:v${Ns}:`,Ky=["cbs:ribbon:","cbs:draft:"],$n={commands:"baselineCommands",enableRules:"baselineEnableRules",displayRules:"baselineDisplayRules",locLabels:"baselineLocLabels"},Ua=["HomepageGrid","SubGrid","Form","Application"];function Wd(e){return{orgUrl:e.orgUrl.trim().replace(/\/+$/,"").toLowerCase(),solutionId:e.solutionId.trim().toLowerCase(),entityLogicalName:e.entityLogicalName.trim().toLowerCase()}}function On(e){const t=Wd(e);return`${qd}${encodeURIComponent(t.orgUrl)}:${encodeURIComponent(t.solutionId)}:${encodeURIComponent(t.entityLogicalName)}`}function is(e,t){return!e||!t?!1:On(e)===On(t)}function Yy(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 To=null;function Hd(e){const t=[e.baseline,e.baselineCommands,e.baselineEnableRules,e.baselineDisplayRules,e.baselineLocLabels,e.layers,e.baseLanguageCode];if(To&&To.of.every((o,s)=>o===t[s]))return To.value;const n=Yy(JSON.stringify(t));return To={of:t,value:n},n}const Jr=new WeakMap;function No(e){let t=Jr.get(e);return t===void 0&&(t=JSON.stringify(e),Jr.set(e,t)),t}const vn=e=>JSON.parse(JSON.stringify(e)),So={},Gd={list:"groups",child:{list:"buttons",child:So}};function Ud(e){const t=new Map;for(const n of e)t.set(n.id,t.has(n.id)?null:n);return t}function ei(e,t,n){if(!n.list||!Array.isArray(e[n.list]))return e;const o=t?.[n.list]??[];return{...e,[n.list]:Xi(e[n.list],o,n.child??So)}}function ko(e,t,n){if(!n.list||e[n.list]===void 0)return e;const o=t?.[n.list]??[];return{...e,[n.list]:Ki(e[n.list],o,n.child??So)}}function Xi(e,t,n){const o=Ud(t),s=new Set(e.map(i=>i.id));if(s.size===e.length&&o.size===t.length){const i=t.filter(r=>s.has(r.id)),l=e.slice(i.length);if(i.every((r,c)=>e[c].id===r.id)&&l.every(r=>!o.has(r.id)))return{set:e.slice(0,i.length).filter(r=>No(o.get(r.id))!==No(r)).map(r=>ei(r,o.get(r.id),n)),drop:t.filter(r=>!s.has(r.id)).map(r=>r.id),add:l.map(r=>ei(r,void 0,n))}}return e.map(i=>{const l=o.get(i.id)??void 0;return l&&No(l)===No(i)?i.id:ei(i,l,n)})}function Ki(e,t,n){const o=Ud(t);if(Array.isArray(e)){const c=[];for(const d of e)if(typeof d!="string")c.push(ko(d,o.get(d.id)??void 0,n));else{const u=o.get(d);u&&c.push(vn(u))}return c}const s=new Set(e.drop),i=new Map(e.set.map(c=>[c.id,c])),l=[];for(const c of e.add)o.has(c.id)?i.set(c.id,c):l.push(c);const r=new Set(t.map(c=>c.id));return[...t.filter(c=>!s.has(c.id)).map(c=>i.has(c.id)?ko(i.get(c.id),c,n):vn(c)),...[...i.values()].filter(c=>!r.has(c.id)).map(c=>ko(c,void 0,n)),...l.map(c=>ko(c,void 0,n))]}const Jy=e=>!Array.isArray(e)&&e.set.length+e.drop.length+e.add.length===0,as=e=>e;function Zy(e){const t=wt(e),n={};for(const i of Ua){const l=t.ribbons[i],r=e.baseline[i];if(!l)continue;const c=Xi(l.tabs,r?.tabs??[],Gd),d={};for(const[p,m]of Object.entries(l))p!=="tabs"&&JSON.stringify(m)!==JSON.stringify(r?.[p])&&(d[p]=m);const u=Object.keys(r??{}).filter(p=>p!=="tabs"&&!(p in l));(!Jy(c)||Object.keys(d).length+u.length>0)&&(n[i]={props:d,unset:u,tabs:c})}const o={};for(const i of Object.keys($n))o[i]=Xi(as(t[i]),as(e[$n[i]]),So);const s={...t};delete s.ribbons;for(const i of Object.keys($n))delete s[i];return{ribbons:n,lists:o,other:s}}function Qy(e,t){const{delta:n}=e,o={};for(const i of Ua){const l=n.ribbons[i],r=t.baseline[i];if(!l){o[i]=vn(r);continue}const c={...vn(r),...vn(l.props)};for(const d of l.unset)delete c[d];c.tabs=Ki(l.tabs,as(r?.tabs??[]),Gd),o[i]=c}const s={...wt(t),...vn(n.other),ribbons:o};for(const i of Object.keys($n))s[i]=Ki(n.lists[i],as(t[$n[i]]),So);return s}function ex(e){return btoa(Ts(zd(ss(JSON.stringify(e)),{level:9}),!0))}function tx(e){return JSON.parse(Ts(Pd(ss(atob(e),!0))))}const Ut=e=>Array.isArray(e),ti=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Zr=e=>{if(Ut(e))return!0;const t=e;return!!t&&typeof t=="object"&&Ut(t.set)&&Ut(t.drop)&&Ut(t.add)},nx=e=>!!e&&typeof e=="object"&&Ut(e.entity)&&Ut(e.application);function ox(e){if(!e||typeof e!="object")return!1;const t=e,n=t.ribbons,o=t.other??{};return!!n&&typeof n=="object"&&Object.entries(n).every(([s,i])=>Ua.includes(s)&&Zr(i?.tabs)&&ti(i?.props)&&Ut(i?.unset))&&ti(t.lists)&&Object.keys($n).every(s=>Zr(t.lists[s]))&&ti(t.other)&&["pendingUnhides","uncustomisedCommandIds"].every(s=>!(s in o)||nx(o[s]))&&(!("customisedCommandIds"in o)||Ut(o.customisedCommandIds))}function sx(e,t){try{const n={format:Ns,key:Wd(e),savedAt:new Date().toISOString(),baselineFingerprint:Hd(t),data:ex(Zy(t))};return localStorage.setItem(On(e),JSON.stringify(n)),n.savedAt}catch{return null}}function ix(e){const t=On(e);let n;try{n=localStorage.getItem(t)}catch{return null}if(!n)return null;try{const o=JSON.parse(n);if(o.format===Ns&&is(o.key,e)&&typeof o.data=="string"){const s=tx(o.data);if(ox(s)){const i=o;return{format:i.format,key:i.key,savedAt:i.savedAt,baselineFingerprint:i.baselineFingerprint,delta:s}}}}catch{}return rs(e),null}function ax(e){try{const t=localStorage.getItem(On(e));if(!t)return!1;const n=JSON.parse(t);return n.format===Ns&&is(n.key,e)&&typeof n.data=="string"}catch{return!1}}function rs(e){try{localStorage.removeItem(On(e))}catch{}}function rx(e,t){try{const n=Date.parse(JSON.parse(e??"").savedAt??"");return!(t-n<=_d*864e5)}catch{return!0}}function lx(e=Date.now()){const t=[];try{for(let n=0;n<localStorage.length;n++){const o=localStorage.key(n);o&&(o.startsWith(qd)?rx(localStorage.getItem(o),e):Ky.some(s=>o.startsWith(s)))&&t.push(o)}for(const n of t)localStorage.removeItem(n)}catch{return 0}return t.length}function Vd(e){return e.mutationsSincePublish>0||so(e)}function _o(){return je.getState().target!==null&&Vd(M.getState())}let ln=null;function tn(e){const{target:t,pending:n}=je.getState();if(!t||n)return!0;const o=e.ribbons.HomepageGrid.entityLogicalName;if(o&&o.toLowerCase()!==t.entityLogicalName.toLowerCase())return!0;let s=!0;if(!Vd(e))ln!==null&&e.future.some(r=>r.op==="restored"&&r.ts===ln)||(rs(t),je.setState({lastSavedAt:null}));else{const l=sx(t,e);s=l!==null,l&&je.setState({lastSavedAt:l})}const{saveFailed:i}=je.getState();return!s&&!i&&ce.getState().logWarn("ribbon","Unsaved changes could not be saved as a draft (browser storage is full or unavailable): publish them, or they are lost when Command Bar Studio closes."),s===i&&je.setState({saveFailed:!s}),s}const cx=["mutationsSincePublish","ribbons","commands","enableRules","displayRules","locLabels","pendingUnhides","customisedCommandIds","uncustomisedCommandIds","baseline","baselineCommands","baselineEnableRules","baselineDisplayRules","baselineLocLabels","layers"];function dx(){return M.subscribe((e,t)=>{e.baseline!==t.baseline&&(ln=null),!cx.every(n=>e[n]===t[n])&&tn(e)})}function Xd(e){const t=ae.getState();return{orgUrl:t.connectionUrl,solutionId:t.activeSolution?.id??"",entityLogicalName:e}}function ux(){const e=M.getState();e.loadWorkspace({ribbons:e.baseline,commands:e.baselineCommands,enableRules:e.baselineEnableRules,displayRules:e.baselineDisplayRules,locLabels:e.baselineLocLabels,templates:e.templates,conflicts:e.conflicts,layers:e.layers,baseLanguageCode:e.baseLanguageCode})}function ni(e){je.setState({target:null,pending:null,pendingBaselineChanged:!1});const t=ae.getState();e.kind==="entity"?t.setActiveEntity(e.entity):t.setActiveSolution(e.solution)}const je=Kt()((e,t)=>({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null,beginLoad(){ln=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,saveFailed:!1,lastSavedAt:null})},workspaceLoaded(n){const o=ix(n);ln=null,e({target:n,pending:o,restoreError:null,lastSavedAt:o?.savedAt??null,pendingBaselineChanged:!!o&&o.baselineFingerprint!==Hd(M.getState())})},restoreDraft(){const{target:n,pending:o}=t();if(!n||!o||!is(n,o.key))return!1;const s=M.getState();try{s.restoreWorkspace(Qy(o,s),`saved ${new Date(o.savedAt).toLocaleString()}`)}catch(r){const c=r instanceof Error?r.message:String(r);return ce.getState().logError("ribbon",`The unsaved changes saved ${o.savedAt} couldn't be restored: ${c}`),e({restoreError:c}),!1}const i=M.getState(),l=i.past[i.past.length-1];return i.past.length>s.past.length&&l?.op==="restored"&&(ln=l.ts),e({pending:null,pendingBaselineChanged:!1,restoreError:null}),tn(i),!0},discardDraft(){const{target:n,pending:o}=t();o&&(rs(o.key),e({pending:null,pendingBaselineChanged:!1,restoreError:null,lastSavedAt:null}),n&&is(n,o.key)&&tn(M.getState()))},requestEntitySwitch(n){ae.getState().activeEntity?.logicalName!==n.logicalName&&(_o()?(tn(M.getState()),e({pendingSwitch:{kind:"entity",entity:n}})):ni({kind:"entity",entity:n}))},requestSolutionSwitch(n){ae.getState().activeSolution?.id!==n.id&&(_o()?(tn(M.getState()),e({pendingSwitch:{kind:"solution",solution:n}})):ni({kind:"solution",solution:n}))},resolveSwitch(n){const{pendingSwitch:o,target:s,pending:i}=t();if(o){if(n==="cancel"){e({pendingSwitch:null});return}n==="keep"&&!tn(M.getState())||(n==="discard"&&s&&!i&&rs(s),e({pendingSwitch:null,target:null,pending:null,pendingBaselineChanged:!1,saveFailed:!1}),ux(),ni(o))}},releaseForConnectionChange(){const n=_o(),o=n?tn(M.getState()):!1;return ln=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null}),{hadChanges:n,kept:o}}})),Kd=e=>e?.trim().toLowerCase()==="production",uI=e=>Kd(e),mI=(e,t)=>t.trim()!==""&&e.trim().toLowerCase()===t.trim().toLowerCase(),mx=me({root:{display:"inline-flex",alignItems:"center",gap:h.spacingHorizontalXS,minWidth:0,borderRadius:h.borderRadiusMedium,":focus-visible":{outline:`2px solid ${h.colorStrokeFocus2}`,outlineOffset:"2px"}},prefix:{color:h.colorNeutralForeground3},name:{maxWidth:"180px"},nameBelow1200:{display:"inline-flex",minWidth:0,"@media (max-width: 1200px)":{display:"none"}}});function px({prefix:e,compactBelow:t}){const n=mx(),o=ae(r=>r.connectionName),s=ae(r=>r.connectionUrl),i=ae(r=>r.environment);if(!o&&!s)return null;const l=Kd(i);return a.jsx(pe,{content:s||o,relationship:"description",children:a.jsxs("span",{"data-testid":"environment-badge",className:n.root,tabIndex:0,children:[e&&a.jsx(V,{size:200,wrap:!1,className:n.prefix,children:e}),a.jsx("span",{className:t?n.nameBelow1200:void 0,children:a.jsx(V,{size:200,weight:"semibold",truncate:!0,wrap:!1,className:n.name,children:o||s})}),i&&a.jsx(xe,{size:"medium",appearance:l?"filled":"tint",color:l?"warning":"informative",children:i})]})})}const Yi=Kt()(e=>({managed:{},setManaged:t=>e({managed:Object.fromEntries(t.map(n=>[n.id,n]))})})),fx=new Set(["label","labeltext","tabname","tabheading","title","tooltip","tooltiptitle","tooltipdescription","alt","button","tab","group","flyout","menu","name","text","caption"]),hx=/^([A-Za-z_$][\w$]*(\.[\w$!{}-]+){2,}|[A-Z][\w$]*\.[\w$!{}-]+)$/,gx=/^(Mscrm|Ribbon)(_[A-Za-z0-9]+){2,}$/,bx=/^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)+$/;function yx(e,t=!1){const n=hx.test(e)?".":gx.test(e)||t&&bx.test(e)?"_":void 0;if(!n)return;const s=e.split(n).filter(i=>i&&!fx.has(i.toLowerCase())).at(-1);if(!(!s||/^(Mscrm|Ribbon|\{!EntityLogicalName\})$/i.test(s)))return s.replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").trim()}function xx(e,t){return e.titles.find(n=>n.languageCode===t)?.description??e.titles.find(n=>n.languageCode===1033)?.description??e.titles[0]?.description}const Qr=/^\$(Resources(\([^)]*\))?|LocLabels):/,vx=[[/\{!EntityPluralDisplayName\}/g,"‹table name, plural›"],[/\{!EntityDisplayName\}/g,"‹table name›"]];function Sx(e){return vx.reduce((t,[n,o])=>t.replace(n,o),e)}function wx(e,t,n,o,s){const i=Cx(e,t,n,o,s);return i&&Sx(i)}function Cx(e,t,n,o,s){const i=Ge(e,t,n);if(!i)return i;const r=s!==void 0&&Ge(s,t,n)===(e??"")?s:e??"";if(!Qr.test(r))return i;const c=o[i];if(c)return xx(c,n)??i;const d=i===r.replace(Qr,"");return yx(i,d)??i}function De(){const e=Yi(n=>n.managed),t=M(n=>n.baseLanguageCode);return E.useCallback((n,o,s,i)=>wx(n,o,s??t??1033,e,i),[e,t])}const Yd="Unified Interface has no visible tabs: this tab's buttons appear in the table's command bar (or its overflow menu) wherever the tab's display rule applies.",Vn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ix=e=>[e.icon,e.image16,e.image32].some(t=>!!t&&t.startsWith("$webresource:")),jx=e=>!!e.source&&Da(e)===e.source.modernImage&&(e.source.modernImage!==void 0||!e.icon),Rx=/^\$LocLabels:(.+)$/,Pt=e=>e?Rx.exec(e)?.[1]??null:null,$x=/^\s*<(EnableRule|DisplayRule)\b[^>]*?\sId="([^"]+)"/,Xn=e=>new Set(e??[]);function Tx(e){const t=[];for(const n of Object.values(e.source?.attributes??{})){const o=Pt(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 el(e){return(e.menu?.sections??[]).map(t=>({id:t.id,title:t.title??"",sequence:t.sequence,displayMode:t.displayMode??"",controlsId:t.controlsId}))}function Nx(e){const t=[],n=[],o=[],s=[],i=[],l=[],r=[],c=[],d=[],u=[],p=new Map,m=(_,L)=>{const U=Pt(_);U&&p.set(U,new Set([...p.get(U)??[],L]))};for(const{baseline:_}of e.locations)for(const L of _.tabs){m(L.label,L.id);for(const U of L.groups){m(U.label,U.id);for(const W of Te(U))for(const te of Object.values(W.source?.attributes??{}))m(te,W.id)}}const g=new Set([...(e.locLabels??[]).map(_=>_.id),...Xn(e.layer?.locLabelIds)]);let b=!1;const f=new Set,y=Xn(e.layer?.containerIds),x=Xn(e.layer?.locLabelIds),v=new Set,C=new Set,$=new Map,A=new Map,j=[],T=new Set(e.locations.flatMap(({current:_})=>Array.from(It(_).values(),L=>L.button.id))),R=(_,L,U,W)=>{const te=Pt(U);if(y.has(L)&&te&&x.has(te)&&!Pt(W)&&W.trim())if([...p.get(te)??[]].some(P=>P!==L)){let P=`${L}.Title`;for(let Q=2;P===te||g.has(P);Q++)P=`${L}.Title${Q}`;g.add(P),u.push({id:P,text:W,containerId:L,newLabel:!0})}else u.push({id:te,text:W,containerId:L});else t.push(`Renaming ${_} ${L} — only tabs and groups your unmanaged customizations add (with a translatable title) can be renamed`)};for(const{current:_,baseline:L}of e.locations){const U=Ob(_,L);U.newButtons+U.overriddenButtons+U.hiddenButtons+U.newTabs+U.newGroups>0&&(b=!0),U.scalingChanges>0&&t.push(`Scaling changes on ${_.location} (not supported yet)`);const W=ld(_,L);t.push(...W.problems);const te=Xn(e.layer?.scalingStepIds);for(const[G,H]of Object.entries(L.scalingByTab??{})){const oe=_.tabs.find(ue=>ue.id===G),se=[...H.maxSizes.filter(ue=>te.has(ue.id)).map(ue=>({...ue,kind:"MaxSize"})),...H.scales.filter(ue=>te.has(ue.id)).map(ue=>({...ue,kind:"Scale"})),...(oe?.groups??[]).map(ue=>W.steps.get(ue.id)).filter(ue=>!!ue).map(ue=>({...ue,kind:"MaxSize"}))];if(se.length===0)continue;const $e=Hc(G,{maxSizes:H.maxSizes.filter(ue=>!te.has(ue.id)).map(ue=>ue.sequence),scales:H.scales.filter(ue=>!te.has(ue.id)).map(ue=>ue.sequence)},se);n.push(...$e.changes.map(ab)),t.push(...$e.problems)}const P=It(_),Q=It(L);for(const{button:G}of P.values())for(const H of _c(G))f.add(H);for(const[G,{button:H,menu:oe}]of P){const se=Tx(H);se.forEach(ze=>v.add(ze));const $e=Q.get(G)?.button,ue=!$e||Oi($e,H);ue&&oe&&!ka.includes(H.kind??"button")&&t.push(`Menu item "${H.label}" (${H.id}) is a ${wn[H.kind]??H.kind} — a menu can hold buttons and flyouts only; change its Kind`);for(const ze of[bs(H.id),ys(H.id),xs(H.id)])ue?C.add(ze):se.includes(ze)||$.set(ze,H);ue&&se.forEach(ze=>C.add(ze))}for(const[G,H]of Q){const oe=H.button.id,se=P.get(G);if(!se){if(H.menu&&T.has(oe)&&T.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(dt(H.button.kind)&&T.has(oe)&&/<Menu[\s>/]/.test(H.button.source?.xml??"")){t.push(`Moving the <${wn[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}rn(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&&!se.button.hidden&&s.push(oe),(se.button.kind??"button")!==(H.button.kind??"button")&&t.push(`Changing the kind of "${se.button.label}" (${oe}) — not supported yet`);const $e=Oi(H.button,se.button);$e&&dt(se.button.kind)&&t.push(`Editing the <${wn[se.button.kind]}> "${se.button.label}" (${oe}) — CBS shows it read-only; it can be hidden, or moved and deleted when it's your own`),$e&&(Cn(se.button.kind)||se.button.menu)&&H.button.origin!=="unmanaged"&&t.push(`Editing the flyout / split button "${se.button.label}" (${oe}) itself — only your own can be edited; its menu items can be edited, hidden or added to`),Vn(el(H.button),el(se.button))||t.push(`Adding, removing or changing menu sections of "${se.button.label}" (${oe}) — not supported yet for an existing menu; add, edit or remove its items instead`),(se.button.icon??"")!==(H.button.icon??"")&&!Ix(se.button)&&!jx(se.button)&&t.push(`Changing the icon of "${se.button.label}" (${oe}) to a built-in icon — not supported yet; choose an SVG web resource`),((se.menu||H.menu?se.menu?.controlsId!==H.menu?.controlsId:se.groupId!==H.groupId)||se.button.sequence!==H.button.sequence)&&(H.button.origin==="unmanaged"?l.push({id:oe,groupId:se.groupId,sequence:se.button.sequence,...se.menu?{controlsId:se.menu.controlsId}:{}}):t.push(`Moving or re-ordering "${se.button.label}" (${oe}) — only your own unmanaged buttons, and copies made with "Customise button", can be moved; undo the move, then hide it and add a new button instead`))}for(const[G,H]of P){if(Q.has(G))continue;A.has(H.button.id)||A.set(H.button.id,{groupId:H.groupId,sequence:H.button.sequence,...H.menu?{controlsId:H.menu.controlsId}:{}});const oe=td(H.button.source?.attributes.PopulateDynamically);Cn(H.button.kind)&&!oe&&!dn(H.button).some(se=>!se.hidden)&&j.push({id:H.button.id,label:H.button.label})}const be=new Map(L.tabs.flatMap(G=>G.groups.map(H=>[H.id,H]))),Ee=new Map(L.tabs.map(G=>[G.id,G])),We=L.tabs.map(G=>G.id).filter(G=>_.tabs.some(H=>H.id===G)),Be=_.tabs.map(G=>G.id).filter(G=>Ee.has(G)),Le=G=>!y.has(G),et=We.filter(Le),Pe=Be.filter(Le).find((G,H)=>G!==et[H]);if(Pe){const G=_.tabs.find(H=>H.id===Pe);t.push(e.layer?`Reordering tab "${G.label}" (${G.id}) — only tabs your customizations add can be reordered; drag it back`:`Reordering tab "${G.label}" (${G.id}) — your unmanaged customizations couldn't be read, so it isn't known whether the tab is yours; use Retry, or drag it back`)}for(const G of _.tabs){const H=Ee.get(G.id);H&&y.has(G.id)&&H.sequence!==G.sequence&&c.push({id:G.id,sequence:G.sequence})}for(const G of _.tabs){const H=Ee.get(G.id);if(H)for(const oe of G.groups){const se=H.groups.find($e=>$e.id===oe.id);se&&y.has(oe.id)&&se.sequence!==oe.sequence&&d.push({id:oe.id,sequence:oe.sequence})}}const ut=new Set(_.tabs.map(G=>G.id)),Jt=new Set(_.tabs.flatMap(G=>G.groups.map(H=>H.id)));for(const G of _.tabs){const H=Pt(G.label);H&&v.add(H);const oe=Ee.get(G.id);if(!oe){C.add(`${G.id}.Title`);const se=Pt(G.source?.titleToken);se&&C.add(se),G.commandId&&f.add(G.commandId),_.location==="Application"&&(G.tabDisplayRules??[]).length===0&&t.push(`New tab ${G.id} has no tab display rule, so it would never be shown — add one in Tab rules`),n.push(`New tab "${G.label}" (${G.id}): ${Yd}`)}oe&&oe.label!==G.label&&R("tab",G.id,oe.label,G.label),oe&&!Vn(oe.tabDisplayRules??[],G.tabDisplayRules??[])&&(y.has(G.id)?G.commandId?r.push(G.id):t.push(`Changing the display rules of tab ${G.id} — the tab has no Command to attach them to`):t.push(`Changing the display rules of tab ${G.id} — only tabs your unmanaged customizations add can be changed`));for(const se of G.groups){const $e=Pt(se.label);$e&&v.add($e);const ue=be.get(se.id);if(!ue){C.add(`${se.id}.Title`);const ze=se.source?.attributes.Command;ze&&f.add(ze);const Zt=Pt(se.source?.titleToken);Zt&&C.add(Zt)}ue&&ue.template!==se.template&&t.push(`Re-templating group ${se.id} — not supported yet`),ue&&ue.label!==se.label&&R("group",se.id,ue.label,se.label)}}const z=(G,H)=>t.push(`Removing ${G} ${H} — only tabs and groups your unmanaged customizations add can be deleted; hide it instead`);for(const G of L.tabs){if(!ut.has(G.id)){y.has(G.id)?i.push(G.id):z("tab",G.id);continue}for(const H of G.groups)Jt.has(H.id)||(y.has(H.id)?i.push(H.id):z("group",H.id))}}for(let _=o.length-1;_>=0;_--){const L=A.get(o[_]);L&&(l.push({id:o[_],...L}),o.splice(_,1))}for(const _ of e.deletedOrphans??[]){for(const L of _.deleteControlIds)o.includes(L)||o.push(L);for(const L of _.deleteContainerIds)i.includes(L)||i.push(L)}for(const _ of j)l.some(L=>L.id===_.id)||t.push(`New flyout / split button "${_.label}" has no menu items — add at least one item to its menu`);const I=e.layer?.commandIds?Xn(e.layer.commandIds):null,N=new Set(e.uncustomisedCommandIds??[]),B=[...N].filter(_=>I?I.has(_):f.has(_)&&!e.excludeCommandIds?.has(_));for(const _ of B)e.layer?.commandRefIds&&!Ta(_,e.layer.commandRefIds)&&t.push(`Uncustomising ${_} — it is your own command (your customizations' buttons use it and no other solution defines it); undo the uncustomise`);B.includes(Xe)&&f.has(Xe)&&t.push(`Uncustomising ${Xe} — its "Open record" buttons still use it; undo the uncustomise and turn the record open override off in the Advanced section instead`);for(const _ of e.excludeCommandIds??[])f.delete(_);const O=new Set(e.customisedCommandIds??[]),S=new Map(e.baselineCommands.map(_=>[_.id,_])),k=e.commands.filter(_=>f.has(_.id)&&!N.has(_.id)&&(!S.has(_.id)||!Vn(S.get(_.id),_)||O.has(_.id)&&!I?.has(_.id))).map(_=>_.id);for(const _ of e.commands){if(!k.includes(_.id))continue;_.actions.some(U=>U.kind==="powerFx"||U.kind==="customApi")&&t.push(`Power Fx / Custom API action in command ${_.id} — classic ribbon commands can't run these; remove the action (#28)`);const L=_.id===Xe?Cy(_):null;L&&t.push(L)}const w=new Set,D=new Set;for(const _ of e.commands)if(!(!f.has(_.id)||N.has(_.id))){_.enableRules.forEach(L=>w.add(L)),_.displayRules.forEach(L=>D.add(L));for(const L of _.rawRuleRefs??[]){const U=$x.exec(L.xml);U&&(U[1]==="EnableRule"?w:D).add(U[2])}}const F=(_,L,U)=>{const W=new Map(L.map(te=>[te.id,te]));return _.filter(te=>U.has(te.id)&&(!W.has(te.id)||!Vn(W.get(te.id),te))).map(te=>te.id)},X=F(e.enableRules,e.baselineEnableRules,w),ne=F(e.displayRules,e.baselineDisplayRules,D),re=[];if(e.locLabels&&e.baselineLocLabels){const _=new Map(e.baselineLocLabels.map(L=>[L.id,L]));for(const L of e.locLabels){const U=_.get(L.id);if(U&&Vn(U,L)||C.has(L.id))continue;if(v.has(L.id)){x.has(L.id)?re.push(L.id):t.push(`Translations of label ${L.id} — it is defined by another solution; change the text in the properties pane instead`);continue}const W=$.get(L.id);W&&t.push(`Translations for "${W.label}" (${W.id}) — its text isn't a translatable label yet; change the text in the properties pane first, then add translations`)}}const le=(e.unhiddenLayerHideIds??[]).filter(_=>!s.includes(_));return{hasChanges:b||k.length>0||B.length>0||X.length>0||ne.length>0||o.length>0||s.length>0||le.length>0||i.length>0||l.length>0||re.length>0||r.length>0||c.length>0||d.length>0||u.length>0,editedCommandIds:k,uncustomisedCommandIds:B,editedEnableRuleIds:X,editedDisplayRuleIds:ne,deletedButtonIds:o,unhiddenButtonIds:[...s,...le],deletedContainerIds:i,movedButtons:l,editedLocLabelIds:re,editedTabIds:r,resequencedTabs:c,resequencedGroups:d,renamedLabels:u,unsupported:[...new Set(t)],warnings:[...new Set(n)]}}const tl=["HomepageGrid","Form","SubGrid","Application"];function kx(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function Ax(e){if(e.includes("Application"))return"the application ribbon";const t=[...e].sort((n,o)=>tl.indexOf(n)-tl.indexOf(o));return`the ${kx(t.map(n=>Vt[n].label.toLowerCase()))}`}function Ox(e){const{plan:t,buttonName:n,titleOf:o}=e,s=new Map,i=(y,x,v,C={})=>{const $=`${y}|${x}|${v}|${C.detail??""}`,A=s.get($)??{change:{kind:y,action:x,name:v,...C.detail?{detail:C.detail}:{}},locations:[],preposition:C.preposition};C.location&&!A.locations.includes(C.location)&&A.locations.push(C.location),s.set($,A)},l=new Map,r=new Map,c=new Map,d=new Map;for(const{current:y,baseline:x}of e.locations){for(const{button:v}of It(y).values())l.has(v.id)||l.set(v.id,{button:v,location:y.location});for(const{button:v}of It(x).values())r.has(v.id)||r.set(v.id,{button:v,location:x.location});for(const v of x.tabs){c.set(v.id,{kind:"tab",label:v.label,location:x.location});for(const C of v.groups)c.set(C.id,{kind:"group",label:C.label,location:x.location})}for(const v of y.tabs)d.set(v.id,{label:v.label,location:y.location})}const u=new Set(t.movedButtons.map(y=>y.id)),p=new Set,m=new Set;for(const{current:y,baseline:x}of e.locations){const v=y.location,C=new Map(x.tabs.map(j=>[j.id,j]));for(const j of y.tabs){const T=C.get(j.id);if(!T){i("new","Add tab",o(j.label),{location:v,preposition:"to"});continue}const R=new Set(T.groups.map(I=>I.id));for(const I of j.groups)R.has(I.id)||i("new","Add group",o(I.label),{detail:`to tab “${o(j.label)}”`})}const $=Aa(y,x),A=new Set($.map(j=>j.entry.button.id));for(const{entry:j,change:T}of $){const{button:R}=j;if(u.has(R.id))continue;const I=n(R);T==="new"?(i("new","Add",I,{location:v,preposition:"to"}),R.commandId&&p.add(R.commandId)):T==="hide"?i("hide","Hide",I,{location:v,preposition:"on"}):i("change","Change",I,{location:v,preposition:"on"})}for(const{button:j}of It(y).values())j.commandId&&!A.has(j.id)&&m.add(j.commandId)}for(const y of t.unhiddenButtonIds){const x=l.get(y)??r.get(y);i("show","Show",x?n(x.button):y,{location:x?.location,preposition:"again on"})}for(const y of t.movedButtons){const x=l.get(y.id),v=r.get(y.id),C=x&&v&&x.location!==v.location;i("move","Move",x?n(x.button):y.id,{location:C?x.location:void 0,preposition:"to"})}for(const y of t.deletedButtonIds){const x=r.get(y);i("delete","Delete",x?n(x.button):y,{location:x?.location,preposition:"from"})}for(const y of t.deletedContainerIds){const x=c.get(y);i("delete",x?.kind==="group"?"Delete group":"Delete tab",x?o(x.label):y,{location:x?.location,preposition:"from"})}for(const y of t.renamedLabels){const x=c.get(y.containerId);i("change",x?.kind==="group"?"Rename group":"Rename tab",x?o(x.label):y.containerId,{detail:`to “${y.text}”`})}for(const y of t.resequencedTabs){const x=d.get(y.id);i("move","Move tab",x?o(x.label):y.id,{location:x?.location,preposition:"on"})}for(const y of t.resequencedGroups??[]){const x=c.get(y.id);i("move","Move group",x?o(x.label):y.id,{location:x?.location,preposition:"on"})}for(const y of t.editedTabIds){const x=d.get(y);i("change","Change the display rules of tab",x?o(x.label):y)}const g=new Set(e.baselineCommands.map(y=>y.id));for(const y of t.editedCommandIds)g.has(y)?i("change","Change command",y):(!p.has(y)||m.has(y))&&i("new","Add command",y);for(const y of t.uncustomisedCommandIds)i("change","Remove your copy of command",y,{detail:"(the original applies again)"});const b=new Set(e.baselineEnableRuleIds),f=new Set(e.baselineDisplayRuleIds);for(const y of t.editedEnableRuleIds)b.has(y)?i("change","Change enable rule",y):i("new","Add enable rule",y);for(const y of t.editedDisplayRuleIds)f.has(y)?i("change","Change display rule",y):i("new","Add display rule",y);for(const y of t.editedLocLabelIds)i("change","Change the translations of",y);return[...s.values()].map(({change:y,locations:x,preposition:v})=>x.length>0&&v?{...y,detail:`${v} ${Ax(x)}`}:y)}const oi=["HomepageGrid","SubGrid","Form"];function Mx(){const e=M(I=>I.ribbons),t=M(I=>I.baseline),n=M(I=>I.commands),o=M(I=>I.displayRules),s=M(I=>I.enableRules),i=M(I=>I.baselineCommands),l=M(I=>I.baselineEnableRules),r=M(I=>I.baselineDisplayRules),c=M(I=>I.locLabels),d=M(I=>I.baselineLocLabels),u=M(I=>I.layers),p=M(I=>I.pendingUnhides),m=M(I=>I.orphans),g=M(I=>I.pendingOrphanDeletes),b=M(I=>I.customisedCommandIds),f=M(I=>I.uncustomisedCommandIds),y=ae(I=>I.activeEntity),x=ae(I=>I.solutionRibbonComponentIds),v=De(),C=Array.isArray(x)&&x.length>0,$=E.useCallback((I,N,B)=>Nx({locations:I.map(O=>({current:e[O],baseline:t[O]})),excludeCommandIds:B,locLabels:c,baselineLocLabels:d,layer:u[N]??void 0,unhiddenLayerHideIds:p[N],deletedOrphans:m[N].filter(O=>g[N].includes(O.id)),customisedCommandIds:b,uncustomisedCommandIds:f[N],commands:n,baselineCommands:i,enableRules:s,baselineEnableRules:l,displayRules:o,baselineDisplayRules:r}),[e,t,n,i,s,l,o,r,c,d,u,p,m,g,b,f]),A=E.useMemo(()=>y?$(oi,"entity"):null,[y,$]),j=E.useMemo(()=>{const I=new Set;if(y)for(const N of oi)for(const B of e[N].tabs)for(const O of B.groups)for(const S of Te(O))S.commandId&&I.add(S.commandId);return $(["Application"],"application",I)},[$,y,e]),T=j.hasChanges&&C,R=E.useMemo(()=>{const I=(N,B)=>Ox({locations:N.map(O=>({current:e[O],baseline:t[O]})),plan:B,baselineCommands:i,baselineEnableRuleIds:l.map(O=>O.id),baselineDisplayRuleIds:r.map(O=>O.id),buttonName:O=>v(O.label,c,void 0,O.source?.labelToken)||O.id,titleOf:O=>v(O,c)||O});return[...A?.hasChanges?I(oi,A):[],...T?I(["Application"],j):[]]},[A,j,T,e,t,i,l,r,c,v]);return{entityPlan:A,appPlan:j,solutionSupportsAppRibbon:C,includeApplicationRibbon:T,scopes:[...y&&A?.hasChanges?[y.logicalName]:[],...T?["Application ribbon"]:[]],unsupported:[...A?.unsupported??[],...j.unsupported],warnings:[...A?.warnings??[],...j.warnings],changes:R}}function Jd(){const e=je(i=>i.target!==null),{changes:t,unsupported:n}=Mx(),o=M(i=>i.mutationsSincePublish>0),s=M(i=>i.mutationsSincePublish===0&&so(i));return{count:t.length,canPublish:e&&(t.length>0||n.length>0||o||s)}}const Dx=me({combobox:{minWidth:"140px",width:"220px",flexShrink:1,"@media (max-width: 1200px)":{width:"180px"}},input:{minWidth:0,width:"100%"},listbox:{maxHeight:"min(480px, 70vh)"},option:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,minWidth:0,width:"100%"},names:{display:"flex",flexDirection:"column",minWidth:0,flex:1},ellipsis:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},logical:{fontFamily:h.fontFamilyMonospace,color:h.colorNeutralForeground3},muted:{color:h.colorNeutralForeground3,flexShrink:0},empty:{whiteSpace:"normal"}}),Ex="__none";function Bx(e,t){const n=t.trim().toLowerCase();return!n||e.displayName.toLowerCase().includes(n)||e.logicalName.toLowerCase().includes(n)}function Lx(){const e=Dx(),t=ae(T=>T.entities),n=ae(T=>T.activeEntity),o=ae(T=>T.activeSolution),s=ae(T=>T.solutionEntityIds),i=je(T=>T.requestEntitySwitch),l=Z(T=>T.tablePickerOpen),r=Z(T=>T.setTablePickerOpen),{count:c}=Jd(),[d,u]=E.useState(null),p=E.useRef(null),m=!!o&&s===null,g=!o||m,b=l&&!g;E.useEffect(()=>{b&&document.activeElement!==p.current&&p.current?.focus()},[b]);const f=E.useMemo(()=>{const T=new Set;if(!l)return T;for(const R of t)ax(Xd(R.logicalName))&&T.add(R.logicalName);return T},[l,t]),y=t.filter(T=>Bx(T,d??"")),x=y.filter(T=>T.isCustomEntity),v=y.filter(T=>!T.isCustomEntity),C=T=>{const R=T.logicalName===n?.logicalName,I=R?c:0;return a.jsx(xi,{value:T.logicalName,text:T.displayName,children:a.jsxs("div",{className:e.option,children:[a.jsxs("div",{className:e.names,children:[a.jsx(V,{size:200,weight:R?"semibold":"regular",className:e.ellipsis,children:T.displayName}),a.jsx(V,{size:200,className:Ie(e.logical,e.ellipsis),children:T.logicalName})]}),I>0?a.jsxs(xe,{appearance:"tint",color:"brand",size:"medium",children:[I," change",I===1?"":"s"]}):!R&&f.has(T.logicalName)&&a.jsx(xe,{appearance:"tint",color:"brand",size:"medium",children:"Draft"}),T.isManaged&&a.jsx(un,{fontSize:12,className:e.muted,"aria-label":"Managed table"})]})},T.logicalName)},$=t.length===0&&o?`No tables in ${o.friendlyName}. Add one in the maker portal (Solutions › ${o.friendlyName} › Add existing › Table) and reload.`:"No tables match.",A=(T,R)=>{if(R.optionValue===void 0||T.type==="keydown"&&T.key==="Tab")return;u(null);const I=t.find(N=>N.logicalName===R.optionValue);I&&I.logicalName!==n?.logicalName&&i(I)},j=o?m?"Loading tables…":"Choose table":"Choose a solution first";return a.jsxs(la,{ref:p,"aria-label":"Table",className:e.combobox,input:{className:e.input},listbox:{className:e.listbox},placeholder:j,disabled:g,freeform:!0,value:d??n?.displayName??"",selectedOptions:n?[n.logicalName]:[],open:b,onOpenChange:(T,R)=>{r(R.open),R.open||u(null)},onChange:T=>{u(T.target.value),l||r(!0)},onOptionSelect:A,onFocus:T=>T.currentTarget.select(),children:[x.length>0&&a.jsx(cr,{label:`Custom (${x.length})`,children:x.map(C)}),v.length>0&&a.jsx(cr,{label:`Standard (${v.length})`,children:v.map(C)}),y.length===0&&a.jsx(xi,{value:Ex,text:"",disabled:!0,children:a.jsx("span",{className:e.empty,children:$})})]})}const si={small:440,medium:600,large:960},Zd=me({surface:{width:"calc(100vw - 32px)",maxHeight:"calc(100vh - 48px)",display:"flex",flexDirection:"column"},small:{maxWidth:`${si.small}px`},medium:{maxWidth:`${si.medium}px`},large:{maxWidth:`${si.large}px`},body:{maxHeight:"calc(100vh - 96px)",minHeight:0},content:{minHeight:0,overflowY:"auto"},wholeRow:{gridColumnStart:1},danger:{backgroundColor:h.colorStatusDangerBackground3,color:h.colorNeutralForegroundOnBrand,":hover":{backgroundColor:h.colorStatusDangerBackground3Hover,color:h.colorNeutralForegroundOnBrand},":hover:active":{backgroundColor:h.colorStatusDangerBackground3Pressed,color:h.colorNeutralForegroundOnBrand}}}),mn=({open:e,onOpenChange:t,title:n,size:o="medium",modalType:s="modal",actions:i,startActions:l,children:r,contentClassName:c})=>{const d=Zd(),u=s!=="alert",p=E.useRef(null);return E.useEffect(()=>{if(!e)return;const m=p.current?.querySelector("[data-autofocus]");m?.focus(),(m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement)&&m.select()},[e]),a.jsx($m,{modalType:s,open:e,onOpenChange:(m,g)=>t(g.open),children:a.jsx(Tm,{ref:p,className:Ie(d.surface,d[o]),children:a.jsxs(Nm,{className:d.body,children:[a.jsx(km,{action:u?a.jsx(Am,{action:"close",children:a.jsx(K,{appearance:"subtle","aria-label":"Close",icon:a.jsx(cn,{})})}):void 0,children:n}),a.jsx(Om,{className:Ie(d.content,c),children:r}),(i||l)&&a.jsxs(a.Fragment,{children:[l&&a.jsx(dr,{position:"start",children:l}),a.jsx(dr,{position:"end",className:l?void 0:d.wholeRow,children:i})]})]})})})},Va=({className:e,children:t,...n})=>{const o=Zd();return a.jsx(K,{...n,appearance:"primary",className:Ie(o.danger,e),children:t})},ls=e=>e instanceof Error?e.message:String(e),zx=3e3;function Px(e,t){let n;const o=new Promise((s,i)=>{n=setTimeout(()=>i(new Error(`no answer in ${t/1e3} s`)),t)});return Promise.race([e,o]).finally(()=>clearTimeout(n))}async function ks(e){const t=[],n=window.toolboxAPI?.utils?.copyToClipboard;if(n)try{return await Px(n(e),zx),{ok:!0}}catch(o){t.push(`host: ${ls(o)}`)}if(navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0}}catch(o){t.push(`browser: ${ls(o)}`)}return{ok:!1,error:t.join("; ")||"no clipboard is available here"}}async function pI(e,t,n){const o=window.toolboxAPI?.fileSystem?.saveFile;if(o)try{const s=await o(e,t,n);return s?{ok:!0,path:s}:{ok:!1,canceled:!0}}catch(s){return{ok:!1,error:ls(s)}}try{const s=URL.createObjectURL(new Blob([t],{type:"application/xml"})),i=document.createElement("a");return i.href=s,i.download=e,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4),{ok:!0}}catch(s){return{ok:!1,error:ls(s)}}}const Ji=48,As=me({root:{height:`${Ji}px`,display:"flex",alignItems:"center",gap:h.spacingHorizontalS,padding:`0 ${h.spacingHorizontalM}`,backgroundColor:h.colorNeutralBackground3,borderBottom:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0,minWidth:0},brand:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,flexShrink:0},brandMark:{width:"24px",height:"24px",borderRadius:h.borderRadiusMedium,backgroundColor:h.colorBrandBackground,color:h.colorNeutralForegroundOnBrand,display:"flex",alignItems:"center",justifyContent:"center"},brandTitle:{whiteSpace:"nowrap","@media (max-width: 1100px)":{display:"none"}},divider:{width:"1px",alignSelf:"stretch",margin:`${h.spacingVerticalM} 0`,backgroundColor:h.colorNeutralStroke2,flexShrink:0},solutionTrigger:{minWidth:"120px",maxWidth:"260px",flexShrink:1,justifyContent:"flex-start","@media (max-width: 1200px)":{maxWidth:"200px"}},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3,flexShrink:0},solutionPickerSurface:{padding:h.spacingHorizontalM,width:"380px",maxWidth:"calc(100vw - 32px)",display:"flex",flexDirection:"column",gap:h.spacingVerticalS},optionText:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},search:{flexShrink:0,color:h.colorNeutralForeground3,fontWeight:h.fontWeightRegular},searchText:{"@media (max-width: 1180px)":{display:"none"}},kbd:{marginLeft:h.spacingHorizontalS,padding:"0 4px",border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusSmall,fontSize:h.fontSizeBase200,"@media (max-width: 1180px)":{display:"none"}},toolsOverflow:{flex:"1 1 0",minWidth:"40px",overflow:"hidden",display:"flex",justifyContent:"flex-end"},toolbar:{flexWrap:"nowrap",minWidth:0},overflowSlot:{display:"inline-flex"},publish:{flexShrink:0},helpBody:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,maxWidth:"320px"},shortcuts:{display:"grid",gridTemplateColumns:"auto 1fr",columnGap:h.spacingHorizontalM,rowGap:h.spacingVerticalXXS,margin:0,fontSize:h.fontSizeBase200,lineHeight:h.lineHeightBase200,"& dt":{fontWeight:h.fontWeightSemibold,whiteSpace:"nowrap"},"& dd":{margin:0}}}),Fx=[["Ctrl+K","Search"],["Ctrl+S","Publish"],["Ctrl+Z / Ctrl+Y","Undo / redo"],["Ctrl+D","Duplicate"],["Ctrl+X / Ctrl+V","Move a button"]];function _x(){const e=As(),t=Z(d=>d.openBulkPublish),n=Z(d=>d.setCommandPaletteOpen),{count:o,canPublish:s}=Jd(),[i,l]=E.useState(!1),r=o>0?`Publish ${o} change${o===1?"":"s"}`:"Publish",c=a.jsx(K,{appearance:"primary",icon:a.jsx(Mm,{}),className:e.publish,disabledFocusable:!s,onClick:s?t:void 0,children:s&&o===0?"Publish changes":r});return a.jsxs("header",{className:e.root,children:[a.jsxs("div",{className:e.brand,children:[a.jsx("div",{className:e.brandMark,"aria-hidden":"true",children:a.jsx(V,{size:100,weight:"bold",children:"CBS"})}),a.jsx(V,{weight:"semibold",size:300,className:e.brandTitle,children:"Command Bar Studio"})]}),a.jsx("div",{className:e.divider}),a.jsx(px,{compactBelow:1200}),a.jsx("div",{className:e.divider}),a.jsx(Wx,{}),a.jsx(Lx,{}),a.jsx(Ux,{onHelp:()=>l(!0)}),a.jsx(pe,{content:"Search buttons, commands, rules (Ctrl+K)",relationship:"label",children:a.jsxs(K,{appearance:"outline",icon:a.jsx(Hl,{}),className:e.search,onClick:()=>n(!0),children:[a.jsx("span",{className:e.searchText,children:"Search"}),a.jsx("span",{className:e.kbd,"aria-hidden":"true",children:"Ctrl K"})]})}),s?c:a.jsx(pe,{content:"No unpublished changes on this table. Make a change and it shows here as Publish 1 change.",relationship:"description",children:c}),a.jsx(mn,{open:i,onOpenChange:l,title:"Command Bar Studio",size:"small",children:a.jsx(tu,{})})]})}function qx(e){return(e.publisherPrefix||"new")==="new"||/^defaultpublisher/i.test(e.publisherUniqueName??"")}function Wx(){const e=As(),t=ae(f=>f.solutions),n=ae(f=>f.activeSolution),o=je(f=>f.requestSolutionSwitch),s=Z(f=>f.solutionPickerOpen),i=Z(f=>f.setSolutionPickerOpen),[l,r]=E.useState(""),c=E.useRef(null),d=E.useMemo(()=>t.filter(f=>!f.isManaged).map(f=>({value:f.id,children:f.friendlyName||f.uniqueName,searchText:`${f.friendlyName??""} ${f.uniqueName??""}`.toLowerCase(),solution:f})),[t]),u=Gl(l,d,{optionToText:f=>f.searchText,filter:(f,y)=>f.includes(y.toLowerCase()),optionToReactKey:f=>f.value,renderOption:f=>a.jsx(xi,{value:f.value,text:f.solution.friendlyName??f.solution.uniqueName,children:a.jsxs("div",{className:e.optionText,children:[a.jsx(V,{size:200,weight:"semibold",children:f.solution.friendlyName||f.solution.uniqueName}),a.jsxs(V,{size:200,className:e.muted,children:[f.solution.uniqueName," · v",f.solution.version,f.solution.publisherName?` · ${f.solution.publisherName}`:""]})]})},f.value),noOptionsMessage:t.length===0?"Loading solutions…":"No solutions match the filter."}),p=(f,y)=>{const x=t.find(v=>v.id===y.optionValue);x&&(o(x),i(!1),r(""),requestAnimationFrame(()=>{const v=document.activeElement;(!v||v===document.body)&&c.current?.focus()}))},m=n?n.friendlyName||n.uniqueName:"",g=n?qx(n):!1,b=n?.publisherPrefix||"new";return a.jsxs(ca,{open:s,onOpenChange:(f,y)=>i(y.open),positioning:"below-start",trapFocus:!0,children:[a.jsx(da,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:n?m:"Choose the solution your changes are saved to",relationship:"description",children:a.jsxs(K,{ref:c,appearance:n?"subtle":"primary",icon:a.jsx(Vl,{}),"aria-label":n?`Solution: ${m}`:"Select solution",className:e.solutionTrigger,children:[n?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:e.ellipsis,children:m}),g&&a.jsx(Ul,{"aria-label":"Default publisher",style:{color:h.colorPaletteDarkOrangeForeground1,flexShrink:0}})]}):"Choose solution",a.jsx(it,{fontSize:12,className:e.muted})]})})}),a.jsxs(ua,{className:e.solutionPickerSurface,children:[a.jsx(_e,{label:"Solution your changes are saved to",children:a.jsx(la,{placeholder:t.length===0?"Loading solutions…":"Search by display name or unique name",value:l,onChange:f=>r(f.target.value),onOptionSelect:p,freeform:!0,clearable:!0,children:u})}),a.jsxs(V,{size:200,className:e.muted,children:[d.length," unmanaged solution",d.length!==1?"s":""," available"]}),n&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsx(Et,{size:"small",info:g?`New ids are prefixed "${b}_", the org's default publisher. To use your own prefix, create a solution in make.powerapps.com bound to your publisher.`:`New ids are prefixed "${b}_" (publisher ${n.publisherName||n.publisherUniqueName||b}).`,children:"Publisher prefix"}),a.jsxs(xe,{appearance:"tint",color:g?"warning":"informative",size:"medium",children:[b,"_"]})]})]})]})}async function Hx(e,t){const n=`${e.replace(/\/$/,"")}/main.aspx?pagetype=entitylist&etn=${encodeURIComponent(t)}`;await window.toolboxAPI?.utils.openInConnectionBrowser(n,"primary")}function Gx(){const e=M(g=>g.past),t=M(g=>g.future),n=M(g=>g.undo),o=M(g=>g.redo),s=Z(g=>g.openXmlDrawer),i=Z(g=>g.openImportXml),l=Z(g=>g.openDiffViewer),r=Z(g=>g.rightPaneMode),c=Z(g=>g.setRightPaneMode),d=Z(g=>g.bottomCollapsed),u=Z(g=>g.setBottomCollapsed),p=ae(g=>g.connectionUrl),m=ae(g=>g.activeEntity?.logicalName);return{canUndo:e.length>0,canRedo:t.length>0,undo:n,redo:o,viewXml:()=>s(Y.getState().location),importXml:()=>i(),compare:()=>l("compare"),canOpenInApp:!!(p&&m),openInApp:()=>p&&m?void Hx(p,m):void 0,rightPaneMode:r,setRightPaneMode:c,bottomCollapsed:d,setBottomCollapsed:u}}const Qd=e=>a.jsxs(a.Fragment,{children:[a.jsx(fe,{onClick:e.viewXml,children:"View XML"}),a.jsx(fe,{onClick:e.importXml,children:"Import XML…"}),a.jsx(fe,{onClick:e.compare,children:"Compare with published"})]});function Zi(e){return{checkedValues:{properties:[e.rightPaneMode],bottom:e.bottomCollapsed?[]:["show"]},onCheckedValueChange:(t,n)=>{n.name==="properties"&&e.setRightPaneMode(n.checkedItems[0]),n.name==="bottom"&&e.setBottomCollapsed(!n.checkedItems.includes("show"))}}}const eu=a.jsxs(a.Fragment,{children:[a.jsxs(Bm,{children:[a.jsx(ao,{children:"Properties pane"}),a.jsx(Sn,{name:"properties",value:"docked",children:"Docked"}),a.jsx(Sn,{name:"properties",value:"floating",children:"Floating"}),a.jsx(Sn,{name:"properties",value:"hidden",children:"Hidden"})]}),a.jsx(Dt,{}),a.jsx(Kl,{name:"bottom",value:"show",children:"Show the bottom panel"})]});function Ux({onHelp:e}){const t=As(),n=Gx();return a.jsx(ma,{padding:40,children:a.jsx("div",{className:t.toolsOverflow,children:a.jsxs(Dm,{"aria-label":"Tools",size:"small",className:t.toolbar,children:[a.jsx(Ft,{id:"undo",groupId:"history",children:a.jsx(pe,{content:"Undo (Ctrl+Z)",relationship:"label",children:a.jsx(on,{icon:a.jsx(pa,{}),disabledFocusable:!n.canUndo,onClick:n.undo})})}),a.jsx(Ft,{id:"redo",groupId:"history",children:a.jsx(pe,{content:"Redo (Ctrl+Y)",relationship:"label",children:a.jsx(on,{icon:a.jsx(fa,{}),disabledFocusable:!n.canRedo,onClick:n.redo})})}),a.jsx(Em,{}),a.jsx(Ft,{id:"xml",children:a.jsx("span",{className:t.overflowSlot,children:a.jsxs(Ke,{children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsxs(on,{icon:a.jsx(Mn,{}),children:["XML ",a.jsx(it,{fontSize:12})]})}),a.jsx(Je,{children:a.jsx(Ze,{children:Qd(n)})})]})})}),a.jsx(Ft,{id:"open",children:a.jsx(pe,{content:"Open this table in Dynamics 365",relationship:"label",children:a.jsx(on,{icon:a.jsx(ha,{}),disabledFocusable:!n.canOpenInApp,onClick:n.openInApp})})}),a.jsx(Ft,{id:"view",children:a.jsx("span",{className:t.overflowSlot,children:a.jsxs(Ke,{...Zi(n),children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:"View",relationship:"label",children:a.jsx(on,{icon:a.jsx(Xl,{})})})}),a.jsx(Je,{children:a.jsx(Ze,{children:eu})})]})})}),a.jsx(Ft,{id:"help",children:a.jsx("span",{className:t.overflowSlot,children:a.jsx(Xx,{})})}),a.jsx(Vx,{tools:n,onHelp:e})]})})})}function Vx({tools:e,onHelp:t}){const{ref:n,isOverflowing:o,overflowCount:s}=ba();return o?a.jsxs(Ke,{...Zi(e),children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:`More tools (${s})`,relationship:"label",children:a.jsx(on,{ref:n,icon:a.jsx(us,{})})})}),a.jsx(Je,{children:a.jsxs(Ze,{children:[a.jsx(hn,{id:"undo",children:a.jsx(fe,{icon:a.jsx(pa,{}),disabled:!e.canUndo,onClick:e.undo,secondaryContent:"Ctrl+Z",children:"Undo"})}),a.jsx(hn,{id:"redo",children:a.jsx(fe,{icon:a.jsx(fa,{}),disabled:!e.canRedo,onClick:e.redo,secondaryContent:"Ctrl+Y",children:"Redo"})}),a.jsx(hn,{id:"xml",children:a.jsxs(Ke,{children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(Mn,{}),children:"XML"})}),a.jsx(Je,{children:a.jsx(Ze,{children:Qd(e)})})]})}),a.jsx(hn,{id:"open",children:a.jsx(fe,{icon:a.jsx(ha,{}),disabled:!e.canOpenInApp,onClick:e.openInApp,children:"Open in Dynamics 365"})}),a.jsx(hn,{id:"view",children:a.jsxs(Ke,{...Zi(e),children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(Xl,{}),children:"View"})}),a.jsx(Je,{children:a.jsx(Ze,{children:eu})})]})}),a.jsx(hn,{id:"help",children:a.jsx(fe,{icon:a.jsx(ga,{}),onClick:t,children:"Help"})})]})})]}):null}function hn({id:e,children:t}){return ya(e)?null:t}const nl="https://github.com/mohsinonxrm/pptb-mxrm-commandbar-studio#readme";function tu(){const e=As(),[t,n]=E.useState("");return a.jsxs("div",{className:e.helpBody,children:[a.jsx(V,{size:200,children:"Your changes are kept as a draft for each table automatically, until you publish or discard them."}),a.jsx("dl",{className:e.shortcuts,children:Fx.map(([o,s])=>a.jsxs(E.Fragment,{children:[a.jsx("dt",{children:o}),a.jsx("dd",{children:s})]},o))}),a.jsx(K,{size:"small",onClick:async()=>n((await ks(nl)).ok?"yes":"no"),children:"Copy documentation link"}),t==="yes"&&a.jsx(V,{size:200,children:"Copied: paste it into your browser."}),t==="no"&&a.jsxs(V,{size:200,children:["Couldn't copy. The link is ",nl]})]})}function Xx(){return a.jsxs(ca,{withArrow:!0,children:[a.jsx(da,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:"Help",relationship:"label",children:a.jsx(on,{icon:a.jsx(ga,{})})})}),a.jsxs(ua,{"aria-label":"Help",children:[a.jsx(V,{weight:"semibold",children:"Command Bar Studio"}),a.jsx(tu,{})]})]})}const nu="cbs.ui.";function ou(e,t){try{const n=window.localStorage.getItem(nu+e);return n===null?t:JSON.parse(n)}catch{return t}}function su(e,t){try{window.localStorage.setItem(nu+e,JSON.stringify(t))}catch{}}const Kx=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,flexShrink:0},more:{alignSelf:"flex-start",fontSize:h.fontSizeBase200}}),ol={error:0,warning:1,info:2,success:3};function sl(e){const t=ou(e,{});return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(n=>typeof n[1]=="string"))}const Xa=({scope:e,messages:t,className:n})=>{const o=Kx(),s=`dismissed.${e}`,[i,l]=E.useState(()=>sl(s)),[r,c]=E.useState(!1),[d,u]=E.useState(e);d!==e&&(u(e),l(sl(s)),c(!1));const p=t.filter(b=>i[b.id]!==(b.signature??"")).sort((b,f)=>ol[b.intent]-ol[f.intent]);if(p.length===0)return null;const m=r?p:p.slice(0,1),g=b=>{if(b.onDismiss){b.onDismiss();return}const f={...i,[b.id]:b.signature??""};l(f),su(s,f)};return a.jsxs("div",{className:n?`${o.root} ${n}`:o.root,children:[a.jsx(Lm,{animate:"both",children:m.map(b=>a.jsxs($t,{intent:b.intent,layout:"multiline",children:[a.jsxs(Tt,{children:[a.jsx(Yl,{children:b.title}),b.body]}),(b.actions||b.dismissible!==!1)&&a.jsx(ms,{containerAction:b.dismissible===!1?void 0:a.jsx(K,{appearance:"transparent","aria-label":`Dismiss: ${b.title}`,icon:a.jsx(cn,{}),onClick:()=>g(b)}),children:b.actions})]},b.id))}),p.length>1&&a.jsx(Tn,{as:"button",className:o.more,"aria-expanded":r,onClick:()=>c(b=>!b),children:r?"Show fewer":`+${p.length-1} more`})]})};function Yx(){const e=je(n=>n.saveFailed),t=je(n=>n.lastSavedAt);return e?{id:"draft-save-failed",intent:"error",title:"Your latest changes can't be saved as a draft",body:t?a.jsxs(a.Fragment,{children:["The browser storage is full. The last saved draft is from"," ",new Date(t).toLocaleString(),"; publish your changes, or the ones made since are lost when Command Bar Studio closes."]}):a.jsx(a.Fragment,{children:"The browser storage is full. Publish your changes, or they are lost when Command Bar Studio closes."}),dismissible:!1}:null}function Jx(){const e=ae(s=>s.connectionNotice),t=ae(s=>s.dismissConnectionNotice);if(!e)return null;const n=`${e.from.name||e.from.url} (${e.from.environment})`,o=`${e.to.name||e.to.url} (${e.to.environment})`;return{id:"connection-changed",intent:e.draftLost?"error":e.to.environment==="Production"?"warning":"info",title:`Connection changed to ${o}`,body:a.jsxs(a.Fragment,{children:["The solution and table loaded from ",n," were closed; pick a solution to continue in ",o,"."," ",e.draftKept&&a.jsxs(a.Fragment,{children:["Your unpublished changes were kept as a draft: switch the tool back to"," ",n," and open the table to restore them."]}),e.draftLost&&a.jsx(a.Fragment,{children:"Your unpublished changes couldn't be saved as a draft (the browser storage is full) and are lost."})]}),onDismiss:t}}function Zx(){const e=Yx();return[Jx(),e].filter(n=>n!==null)}const Qx=me({slot:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`}});function ev(){const e=Qx(),t=Zx();return t.length===0?null:a.jsx(Xa,{scope:"shell",messages:t,className:e.slot})}const iu=E.createContext({}),we=Kt()((e,t)=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],appFilter:"all",selectedCommandId:null,loadToken:0,beginLoad(n){const o=t().loadToken+1;return e({tableLogicalName:n,status:"loading",error:null,commands:[],apps:[],selectedCommandId:null,loadToken:o}),o},finishLoad(n,o){if(n!==t().loadToken)return;const{appFilter:s}=t(),i=s==="all"||o.apps.some(l=>l.id===s);e({status:o.error?"unavailable":"loaded",error:o.error??null,commands:o.commands,apps:o.apps,appFilter:i?s:"all"})},reset(){e(n=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],selectedCommandId:null,appFilter:"all",loadToken:n.loadToken+1}))},setAppFilter(n){e({appFilter:n?n.toLowerCase():"all"})},selectCommand(n){n&&Y.getState().clearSelection(),e({selectedCommandId:n})}}));Y.subscribe((e,t)=>{if(!we.getState().selectedCommandId)return;(e.selectedButtonId&&e.selectedButtonId!==t.selectedButtonId||e.location!==t.location||e.tabId!==t.tabId)&&we.setState({selectedCommandId:null})});function tv(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 nv='[role="dialog"], [role="alertdialog"], [role="menu"], [role="menubar"], [role="listbox"], .fui-PopoverSurface, .fui-MenuPopover',au=".fui-OverlayDrawer, .fui-InlineDrawer",il=e=>!!e.closest(au)&&!e.matches('[role="alertdialog"]');function ov(e){const t=e instanceof Element?e.closest(nv):null;return t&&!il(t)?!0:Array.from(document.querySelectorAll('[aria-modal="true"], [role="alertdialog"]')).some(n=>!il(n))}function sv(e){return e instanceof Element&&!!e.closest(au)}function iv(){const e=Z($=>$.setCommandPaletteOpen),t=Z($=>$.openBulkPublish),n=Z($=>$.announce),o=Z($=>$.openHideInsteadOfDelete),s=M($=>$.undo),i=M($=>$.redo),l=M($=>$.past),r=M($=>$.future),c=Y($=>$.selectedButtonId),d=Y($=>$.selectedGroupId),u=Y($=>$.tabId),p=Y($=>$.location),m=M($=>$.duplicateButton),g=M($=>$.deleteButton),b=M($=>$.moveButton),f=M($=>$.ribbons),y=M($=>$.baseline),x=Y($=>$.selectButtonInContext),v=Y($=>$.selectGroup),C=E.useRef(null);E.useEffect(()=>{const $=A=>{const T=navigator.platform.toUpperCase().includes("MAC")?A.metaKey:A.ctrlKey,R=A.target,I=A.key??"",N=A.altKey||A.getModifierState?.("AltGraph"),B=!N&&/^Key[A-Z]$/.test(A.code??"")&&!/^[a-z]$/i.test(I)?A.code.slice(3).toLowerCase():I.length===1?I.toLowerCase():I,O=T&&!A.shiftKey&&!N;if(A.key==="Escape"){e(!1);return}if(ov(R)){O&&B==="s"&&A.preventDefault();return}if(O&&B==="k"){A.preventDefault(),e(!0),n("Command palette opened");return}if(O&&B==="s"){A.preventDefault(),t(),n("Bulk publish dialog opened");return}const S=tv(R);if(O&&B==="z"&&l.length>0&&!S){A.preventDefault(),s(),n("Undo");return}if(T&&!N&&(B==="y"||A.shiftKey&&B==="z")&&!S){A.preventDefault(),r.length>0&&(i(),n("Redo"));return}if(!sv(R)){if(O&&B==="d"){!S&&c&&d&&u&&p&&(A.preventDefault(),m(p,u,d,c),n("Button duplicated"));return}if(T&&!N&&B==="x"){if(!S&&c&&d&&u&&p){A.preventDefault();const k=f[p].tabs.find(w=>w.id===u)?.groups.find(w=>w.id===d);if(k&&Yo(k,c)){n("Menu items can't be cut. Delete the item and add a new one to the other menu.");return}C.current={location:p,tabId:u,groupId:d,buttonId:c},n("Button cut. Focus a destination group, then press paste.")}return}if(T&&!N&&B==="v"){const k=C.current;if(!S&&k&&d&&u&&p){A.preventDefault();const w=b({groupId:k.groupId,buttonId:k.buttonId,tabId:k.tabId,location:k.location},{groupId:d,tabId:u,location:p});if(C.current=null,!w){n("The button couldn't be moved there.");return}requestAnimationFrame(()=>{x(p,u,d,w),document.querySelector(`[data-ribbon-btn-id="${w}"]`)?.focus()}),n(w===k.buttonId?"Button pasted to destination group.":"Pasted your copy of the button to the destination group; the original is hidden.")}return}if((A.key==="Delete"||A.key==="Backspace")&&c&&d&&u&&p&&!S){const k=f[p].tabs.find(_=>_.id===u),w=k?.groups.find(_=>_.id===d),D=Ss(w,c);if(!D)return;if(A.preventDefault(),!Is(D,y[p])){p==="Application"&&u==="Mscrm.GlobalTab"&&D.oob&&!D.custom?n(`"${D.label}" is read-only and can't be deleted.`):D.hidden?n(`"${D.label}" can't be deleted — only your own buttons can. It is already hidden.`):o({location:p,tabId:u,groupId:d,buttonId:c});return}const F=w?Yo(w,c):void 0,X=F?F.section.controls.map(_=>({groupId:d,buttonId:_.id})):k?.groups.flatMap(_=>_.buttons.map(L=>({groupId:_.id,buttonId:L.id})))??[],ne=X.findIndex(_=>_.buttonId===c),re=X[ne+1]??X[ne-1]??(F?{groupId:d,buttonId:F.parent.id}:null),le=d;g(p,u,d,c),requestAnimationFrame(()=>{if(re){x(p,u,re.groupId,re.buttonId),document.querySelector(`[data-ribbon-btn-id="${re.buttonId}"]`)?.focus();return}le&&(v(le),document.querySelector(`[data-add-btn-group-id="${le}"]`)?.focus())}),n("Button deleted")}}};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[e,t,n,o,s,i,l.length,r.length,c,d,u,p,m,g,b,f,y,x,v])}const av=me({handleV:{width:"4px",cursor:"col-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:h.colorNeutralStroke2},":active":{backgroundColor:h.colorBrandStroke1},":focus-visible":{backgroundColor:h.colorBrandStroke1,outline:"none"},userSelect:"none"},handleH:{height:"4px",cursor:"row-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:h.colorNeutralStroke2},":active":{backgroundColor:h.colorBrandStroke1},":focus-visible":{backgroundColor:h.colorBrandStroke1,outline:"none"},userSelect:"none"}}),rv=16,lv=64;function ii({direction:e,onResize:t,value:n,min:o,max:s,target:i,"aria-label":l=`Resize ${e} pane`}){const r=av(),c=E.useRef(0),d=E.useCallback(m=>{m.currentTarget.setPointerCapture(m.pointerId),c.current=e==="vertical"?m.clientX:m.clientY},[e]),u=E.useCallback(m=>{if(!m.currentTarget.hasPointerCapture(m.pointerId))return;const g=e==="vertical"?m.clientX:m.clientY,b=g-c.current;c.current=g,t(b)},[e,t]),p=E.useCallback(m=>{const g=e==="vertical"?["ArrowLeft","ArrowRight"]:["ArrowUp","ArrowDown"],b=m.key===g[0]?-1:m.key===g[1]?1:0;b!==0&&(m.preventDefault(),t(b*(m.shiftKey?lv:rv)))},[e,t]);return a.jsx("div",{className:e==="vertical"?r.handleV:r.handleH,role:"separator","aria-orientation":e==="vertical"?"vertical":"horizontal","aria-label":l,"aria-valuenow":Math.round(n),"aria-valuemin":o,"aria-valuemax":s,"aria-valuetext":`${i}, ${Math.round(n)} pixels ${e==="vertical"?"wide":"high"}`,tabIndex:0,onKeyDown:p,onPointerDown:d,onPointerMove:u})}class zt extends tt.Component{state={hasError:!1,error:null};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[CBS ErrorBoundary]",this.props.label??"panel",t,n)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:a.jsxs($t,{intent:"error",style:{margin:8},children:[a.jsxs(Tt,{children:[a.jsx("strong",{children:this.props.label??"Panel"})," encountered an error:"," ",this.state.error?.message??"Unknown error"]}),a.jsx(ms,{children:a.jsx(K,{size:"small",onClick:this.handleRetry,children:"Retry"})})]}):this.props.children}}const cv=.4,Ka=160,Ya=200,ru=500,lu=600;function qo(e,t,n){const o=t+n-e*(1-cv);if(o<=0||t+n===0)return{left:t,right:n};const s=(i,l)=>Math.max(Math.min(i,l),Math.round(i-o*i/(t+n)));return{left:s(t,Ka),right:n===0?0:s(n,Ya)}}function dv(e,t,n,o,s){const i=qo(e,t,n),l=(c,d,u)=>Math.max(d,Math.min(u,c));if(o==="left"){const c=l(i.left+s,Ka,ru);return n>0&&i.right!==n?{left:c,right:i.right}:{left:c}}const r=l(i.right-s,Ya,lu);return i.left!==t?{left:i.left,right:r}:{right:r}}const uv=E.lazy(()=>ht(()=>import("./EditorDrawer-BtFb9OzQ.js"),__vite__mapDeps([0,1,2,3]),import.meta.url)),mv=E.lazy(()=>ht(()=>import("./BulkPublishModal-BWRed6Fv.js"),__vite__mapDeps([4,2,5,1,6,7,8,3]),import.meta.url)),pv=E.lazy(()=>ht(()=>import("./NewButtonModal-5nQ-f2by.js"),__vite__mapDeps([9,2,1,3]),import.meta.url)),fv=E.lazy(()=>ht(()=>import("./NewGroupModal-vEuxSpnD.js"),__vite__mapDeps([10,2,1,3]),import.meta.url)),hv=E.lazy(()=>ht(()=>import("./NewTabModal-DNzMru8E.js"),__vite__mapDeps([11,2,1,3]),import.meta.url)),gv=E.lazy(()=>ht(()=>import("./ImportXmlModal-BZq0Iglk.js"),__vite__mapDeps([12,2,6,7,8,5,1,3]),import.meta.url)),bv=E.lazy(()=>ht(()=>import("./CommandPalette-Fc4MPKvd.js"),__vite__mapDeps([13,2,1,3]),import.meta.url)),yv=E.lazy(()=>ht(()=>import("./IconPickerModal-FyQ9ud3R.js"),__vite__mapDeps([14,2,15,1,3]),import.meta.url)),xv=E.lazy(()=>ht(()=>import("./WebResourceBrowser-L3R7UTNR.js"),__vite__mapDeps([16,2,15,1,3]),import.meta.url)),vv=E.lazy(()=>ht(()=>import("./HideInsteadOfDeleteModal-fdtkLfSG.js"),__vite__mapDeps([17,2,1,3]),import.meta.url)),Sv=me({root:{display:"flex",flexDirection:"column",height:"100vh",overflow:"hidden",backgroundColor:h.colorNeutralBackground1,color:h.colorNeutralForeground1,fontFamily:h.fontFamilyBase},body:{display:"flex",flex:1,overflow:"hidden",position:"relative"},leftPane:{flexShrink:0,overflow:"hidden",borderRight:`1px solid ${h.colorNeutralStroke2}`},rightPane:{flexShrink:0,overflow:"hidden",borderLeft:`1px solid ${h.colorNeutralStroke2}`},bottomPanel:{flexShrink:0},rail:{width:"48px",flexShrink:0,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:h.spacingVerticalS,borderRight:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground2},drawerBody:{position:"relative",width:"100%",height:"100%",overflow:"hidden"},belowTopBar:{top:`${Ji+1}px`,height:`calc(100vh - ${Ji+1}px)`}}),wv=[{value:"structure",label:"Structure",icon:a.jsx(Jl,{})},{value:"solution",label:"Solution",icon:a.jsx(Zl,{})}],Cv=1200,al=120,rl=520;function Iv(){const[e,t]=E.useState(()=>window.innerWidth);return E.useEffect(()=>{const n=()=>t(window.innerWidth);return window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),e}function jv({children:e,leftPane:t,rightPane:n,bottomPanel:o}){const s=Sv(),i=Z(J=>J.leftPaneWidth),l=Z(J=>J.rightPaneWidth),r=Z(J=>J.rightPaneMode),c=Z(J=>J.setLeftPaneWidth),d=Z(J=>J.setRightPaneWidth),u=Z(J=>J.bottomPanelHeight),p=Z(J=>J.bottomCollapsed),m=Z(J=>J.setBottomPanelHeight),g=Z(J=>J.announcement),b=Iv(),f=b<Cv,y=Y(J=>J.selectedButtonId),x=Y(J=>J.selectedGroupId),v=ae(J=>J.activeEntity?.logicalName??null),[C,$]=E.useState(!1),A=Z(J=>J.leftPaneTab),j=Z(J=>J.setLeftPaneTab),T=we(J=>J.selectedCommandId),[R,I]=E.useState(!1),N=Z(J=>J.propertiesRequested),B=Z(J=>J.setPropertiesRequested),O=R||f&&N,S=()=>{I(!1),B(!1)},k=!!(y||x||T),w=`${x??""}|${y??""}|${T??""}`,[D,F]=E.useState(w);D!==w&&(F(w),f&&!C&&k&&I(!0));const[X,ne]=E.useState(f);X!==f&&(ne(f),$(!1),I(!1));const re=Z(J=>J.structureChoice),[le,_]=E.useState(re);le!==re&&(_(re),$(!1),f&&k&&I(!0));const[L,U]=E.useState(v);L!==v&&(U(v),$(!1));const W=qo(b,i,r==="docked"?l:0),te={left:Math.max(W.left,qo(b,ru,W.right).left),right:Math.max(W.right,qo(b,W.left,lu).right)},P=Z(J=>J.editorStack.length>0||J.bulkPublishOpen||J.newButtonGroupId!==null||J.newGroupOpen||J.newTabOpen||J.importXmlOpen||J.commandPaletteOpen||J.iconPickerOpen||J.webResourceBrowserOpen||J.hideInsteadOfDelete!==null),Q=E.useRef(null),be=E.useRef(!1);iv(),E.useEffect(()=>{N&&!f&&B(!1)},[N,f,B]),E.useEffect(()=>{if(P&&!be.current){const J=document.activeElement;Q.current=J instanceof HTMLElement?J:null}if(!P&&be.current){const J=Q.current;requestAnimationFrame(()=>{!J||!J.isConnected||J.focus()})}be.current=P},[P]);const Ee=r==="docked"?l:0,We=E.useCallback((J,Pe)=>{const ut=dv(b,i,Ee,J,Pe);ut.left!==void 0&&c(ut.left),ut.right!==void 0&&d(ut.right)},[b,i,Ee,c,d]),Be=E.useCallback(J=>We("left",J),[We]),Le=E.useCallback(J=>We("right",J),[We]),et=E.useCallback(J=>{const Pe=u-J;m(Math.max(al,Math.min(rl,Pe)))},[u,m]);return a.jsxs("div",{className:s.root,children:[a.jsx(_x,{}),a.jsx(ev,{}),a.jsxs("div",{className:s.body,children:[f?a.jsxs("nav",{className:s.rail,"aria-label":"Side panes",children:[wv.map(({value:J,label:Pe,icon:ut})=>a.jsx(pe,{content:Pe,relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:ut,"aria-pressed":C&&A===J,onClick:()=>{j(J),$(!0)}})},J)),r!=="hidden"&&a.jsx(pe,{content:"Properties",relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:a.jsx(zm,{}),"aria-pressed":O,onClick:()=>O?S():I(!0)})})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:s.leftPane,style:{width:W.left},children:a.jsx(zt,{label:"Left pane",children:t})}),a.jsx(ii,{direction:"vertical",onResize:Be,value:W.left,min:Math.min(Ka,W.left),max:te.left,target:"Left pane","aria-label":"Resize left pane"})]}),a.jsx(zt,{label:"Ribbon canvas",children:e}),f&&a.jsxs(a.Fragment,{children:[a.jsx(ur,{position:"start",size:"small",open:C,onOpenChange:(J,Pe)=>$(Pe.open),"aria-label":A==="structure"?"Structure":"Solution",children:a.jsx("div",{className:s.drawerBody,children:a.jsx(zt,{label:"Left pane",children:t})})}),r!=="hidden"&&a.jsx(ur,{position:"end",size:"small",modalType:"non-modal",className:s.belowTopBar,open:O,onOpenChange:(J,Pe)=>Pe.open?I(!0):S(),"aria-label":"Properties",children:a.jsx("div",{className:s.drawerBody,children:a.jsx(iu.Provider,{value:{onClose:S},children:a.jsx(zt,{label:"Properties pane",children:n})})})})]}),!f&&r==="docked"&&a.jsxs(a.Fragment,{children:[a.jsx(ii,{direction:"vertical",onResize:Le,value:W.right,min:Math.min(Ya,W.right),max:te.right,target:"Properties pane","aria-label":"Resize right pane"}),a.jsx("div",{className:s.rightPane,style:{width:W.right},children:a.jsx(zt,{label:"Properties pane",children:n})})]}),!f&&r==="floating"&&a.jsx("div",{style:{position:"absolute",right:8,top:8,bottom:8,width:l,maxWidth:"90vw",border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground1,boxShadow:h.shadow16,borderRadius:h.borderRadiusMedium,overflow:"hidden",zIndex:10},children:a.jsx(zt,{label:"Properties pane",children:n})})]}),!p&&a.jsx(ii,{direction:"horizontal",onResize:et,value:u,min:al,max:rl,target:"Bottom panel","aria-label":"Resize bottom panel"}),a.jsx("div",{className:s.bottomPanel,children:a.jsx(zt,{label:"Bottom panel",children:o})}),a.jsx(zt,{label:"Panels",children:a.jsxs(E.Suspense,{fallback:null,children:[a.jsx(uv,{}),a.jsx(mv,{}),a.jsx(pv,{}),a.jsx(fv,{}),a.jsx(hv,{}),a.jsx(gv,{}),a.jsx(bv,{}),a.jsx(yv,{}),a.jsx(xv,{}),a.jsx(vv,{})]})}),a.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",left:-9999,top:"auto"},children:g})]})}const Rv=["HomepageGrid","SubGrid","Form"];function $v(e,t){const n=new Map;for(const b of Object.values(t.baseline))for(const f of b.tabs)for(const y of f.groups)for(const x of y.buttons)n.set(x.id,x.origin);let o=!1,s=!1,i=Bi(e);for(const[b,f]of Object.entries(t.ribbons))for(const y of f.tabs)for(const x of y.groups)for(const v of x.buttons)v.commandId===e&&(Rv.includes(b)?o=!0:s=!0,n.has(v.id)&&n.get(v.id)!=="unmanaged"&&(i=!0));const l=o||!s?"entity":"application",r=o&&s,c=t.layers[l],d=c?.commandIds?c.commandIds.includes(e):void 0,u=t.baselineCommands.find(b=>b.id===e),p=(b,f=l)=>({provenance:b,scope:f,sharedWithApplication:r});if(t.reloadRequiredCommandIds.includes(e))return p("reloadRequired");for(const b of["entity","application"])if(t.uncustomisedCommandIds[b].includes(e))return p("uncustomising",b);if(!u||!i&&d!==!1)return p("custom");if(d){const b=c?.commandRefIds?Ta(e,c.commandRefIds):Bi(e);return p(b?"customised":"custom")}const m=t.commands.find(b=>b.id===e),g=!!m&&JSON.stringify(m)!==JSON.stringify(u);return t.customisedCommandIds.includes(e)||g?p("customising"):p("oob")}const Tv={oob:"Out of the box",customising:"Customised (unpublished)",customised:"Customised in your layer",uncustomising:"Uncustomised (unpublished)",custom:"Custom",reloadRequired:"Uncustomised — reload the table"};function Os(e){const t=M(d=>d.commands),n=M(d=>d.baselineCommands),o=M(d=>d.ribbons),s=M(d=>d.baseline),i=M(d=>d.layers),l=M(d=>d.customisedCommandIds),r=M(d=>d.uncustomisedCommandIds),c=M(d=>d.reloadRequiredCommandIds);return tt.useMemo(()=>e&&t.some(d=>d.id===e)?$v(e,{commands:t,baselineCommands:n,ribbons:o,baseline:s,layers:i,customisedCommandIds:l,uncustomisedCommandIds:r,reloadRequiredCommandIds:c}):null,[e,t,n,o,s,i,l,r,c])}function Nv(e){return e?.provenance==="oob"||e?.provenance==="uncustomising"||e?.provenance==="reloadRequired"}function kv({location:e,tabId:t,groupId:n,button:o,onDone:s}){const i=M(m=>m.customiseButton),l=M(m=>m.customiseCommand),r=ae(m=>m.activeSolution),c=ae(m=>m.publisherPrefix),d=Y(m=>m.selectButtonInContext),u=Z(m=>m.openCommandEditor),p=Os(o.commandId||void 0);return a.jsxs(a.Fragment,{children:[o.origin!=="unmanaged"&&a.jsx(fe,{icon:a.jsx(Pm,{}),disabled:!Wa(e,t,o),onClick:()=>{const m=r?.publisherPrefix?.trim()||c?.trim()||"new",g=i(e,t,n,o.id,m);g&&d(e,t,n,g),s()},children:"Customise button (copy, hide original)"}),p?.provenance==="oob"&&a.jsx(fe,{icon:a.jsx(Mn,{}),onClick:()=>{l(o.commandId)&&u(o.commandId),s()},children:"Customise command"})]})}const Ln=({open:e,title:t,children:n,confirmLabel:o,cancelLabel:s="Cancel",destructive:i=!1,onConfirm:l,onCancel:r})=>a.jsx(mn,{open:e,onOpenChange:c=>!c&&r(),title:t,size:"small",modalType:"alert",actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:r,children:s}),i?a.jsx(Va,{onClick:l,children:o}):a.jsx(K,{appearance:"primary",onClick:l,children:o})]}),children:n}),Av=me({body:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM},options:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS},description:{display:"block",color:h.colorNeutralForeground2,paddingLeft:"32px",marginTop:`-${h.spacingVerticalXS}`}}),cu=({open:e,buttonLabel:t,buttonId:n,commandId:o,deleteBlockedReason:s,onConfirmHide:i,onConfirmDisplayRule:l,onCancel:r})=>{const c=Av(),d=De(),u=M(x=>x.locLabels),p=M(x=>x.ribbons),m=Y(x=>x.location),g=o?od(p,o,n??"",x=>d(x.label,u,void 0,x.source?.labelToken),m):[],[b,f]=E.useState(o&&g.length===0?"rules":"button"),y=g.length===0?"No other button uses its command.":`Also hides ${g.length===1?"1 other button":`${g.length} other buttons`} that use${g.length===1?"s":""} its command: ${g.slice(0,4).join(", ")}${g.length>4?", …":""}.`;return a.jsx(mn,{open:e,onOpenChange:x=>!x&&r(),size:"medium",title:s?`Can't delete "${t}"`:`Hide "${t}"?`,actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:r,children:"Cancel"}),a.jsx(K,{appearance:"primary",onClick:b==="rules"?l:i,children:"Hide button"})]}),children:a.jsxs("div",{className:c.body,children:[s&&a.jsxs(V,{children:[s," Only buttons your solution adds can be deleted; you can hide this one instead."]}),a.jsxs(vi,{className:c.options,value:b,onChange:(x,v)=>f(v.value),"aria-label":"How to hide it",children:[a.jsxs("div",{children:[a.jsx(sn,{value:"button",label:"Hide this button only"}),a.jsx(V,{size:200,className:c.description,children:"Removes it from this table's ribbon. Show it again under “Hidden by customizations” in Properties. Once a managed solution ships the hide, only a new version of that solution can bring it back."})]}),a.jsxs("div",{children:[a.jsx(sn,{value:"rules",disabled:!o,label:"Hide it with display rules on its command"}),a.jsx(V,{size:200,className:c.description,children:o?`Adds two display rules to the command so it never shows. Easy to undo: remove the rules. ${y}`:"Not available: this button has no command."})]})]}),a.jsx(Et,{size:"small",info:a.jsx(a.Fragment,{children:"“Hide this button only” adds a HideCustomAction to your customizations. The display rules are Mscrm.HideOnModern and Mscrm.ShowOnlyOnModern, which are never both true."}),children:"What each one writes"})]})})};function Ov(e,t,n,o,s,i=Ge){const l=e.groups.filter(c=>c.id!==t&&!(n&&c.buttons.some(d=>d.id===n))).map(c=>({groupId:c.id,text:i(c.label,o,s,c.source?.titleToken).trim()||c.id})),r=new Map;for(const c of l)r.set(c.text,(r.get(c.text)??0)+1);return l.map(c=>(r.get(c.text)??0)>1&&c.text!==c.groupId?{...c,text:`${c.text} (${c.groupId})`}:c)}const Mv=me({danger:{color:h.colorPaletteRedForeground1},note:{maxWidth:"280px",whiteSpace:"normal"}});function wo({location:e,tab:t,target:n,onClose:o}){const s=Mv(),i=De(),l=M(R=>R.locLabels),r=M(R=>R.baseLanguageCode),c=M(R=>R.baseline),d=M(R=>R.setButtonProp),u=M(R=>R.customizeOobButton),p=M(R=>R.duplicateButton),m=M(R=>R.moveButton),g=M(R=>R.deleteButton),b=M(R=>R.hideOobButton),f=Y(R=>R.selectButtonInContext),y=Z(R=>R.openIconPicker),x=Z(R=>R.openLocalizationEditor),[v,C]=E.useState(null),[$,A]=E.useState(null),j=R=>i(R.label,l,void 0,R.source?.labelToken),T=n&&(()=>{const{button:R,groupId:I}=n,N=Ba(e,t.id,R),B=dt(R.kind),O=Ov(t,I,R.id,l,r,i),S=k=>()=>{k(),o()};return a.jsxs(Ke,{open:!0,onOpenChange:(k,w)=>!w.open&&o(),positioning:{target:n.anchor,position:"below",align:"start"},children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Je,{children:a.jsxs(Ze,{"aria-label":`Actions for ${j(R)}`,children:[N&&a.jsx(ao,{className:s.note,children:"Microsoft's global command bar buttons can't be changed."}),!N&&B&&a.jsxs(ao,{className:s.note,children:[xt[R.kind],": shown read-only. You can hide, move or delete it."]}),a.jsx(fe,{icon:a.jsx(Ql,{}),onClick:S(()=>f(e,t.id,I,R.id)),children:"Edit properties"}),a.jsx(fe,{icon:a.jsx(Si,{}),disabled:N||B,onClick:S(()=>{f(e,t.id,I,R.id),y()}),children:"Change icon…"}),a.jsx(fe,{icon:a.jsx(Fm,{}),disabled:N||B,onClick:S(()=>x(R.id)),children:"Edit labels…"}),a.jsx(Dt,{}),R.hidden?a.jsx(fe,{icon:a.jsx(Dn,{}),disabled:N,onClick:S(()=>d(e,t.id,I,R.id,{hidden:!1})),children:"Show button"}):a.jsx(fe,{icon:a.jsx(Bt,{}),disabled:N,onClick:S(()=>R.oob?C(n):d(e,t.id,I,R.id,{hidden:!0})),children:R.oob?"Hide button…":"Hide button"}),(R.origin==="oob"||R.origin==="managed")&&a.jsx(fe,{icon:a.jsx(ro,{}),disabled:N||B,onClick:S(()=>u(e,t.id,I,R.id)),children:"Create override…"}),a.jsx(kv,{location:e,tabId:t.id,groupId:I,button:R,onDone:o}),a.jsx(Dt,{}),a.jsx(fe,{icon:a.jsx(yo,{}),disabled:N,onClick:S(()=>p(e,t.id,I,R.id)),children:"Duplicate"}),O.length===0||N?a.jsx(fe,{icon:a.jsx(mr,{}),disabled:!0,secondaryContent:N?void 0:"No other groups",children:"Move to"}):a.jsxs(Ke,{children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(mr,{}),children:"Move to"})}),a.jsx(Je,{children:a.jsx(Ze,{"aria-label":"Move to group",children:O.map(k=>a.jsx(fe,{onClick:S(()=>{const w=m({groupId:I,buttonId:R.id,tabId:t.id,location:e},{groupId:k.groupId,tabId:t.id,location:e});w&&f(e,t.id,k.groupId,w)}),children:k.text},k.groupId))})})]}),Is(R,c[e])&&a.jsxs(a.Fragment,{children:[a.jsx(Dt,{}),a.jsx(fe,{icon:a.jsx(En,{className:s.danger}),className:s.danger,disabled:N,onClick:S(()=>A(n)),children:"Delete…"})]})]})})]})})();return a.jsxs(a.Fragment,{children:[T,$&&a.jsxs(Ln,{open:!0,title:"Delete button",confirmLabel:"Delete button",destructive:!0,onConfirm:()=>{g(e,t.id,$.groupId,$.button.id),A(null)},onCancel:()=>A(null),children:["Delete “",j($.button),"”? You can undo this until you publish."]}),v&&a.jsx(cu,{open:!0,buttonLabel:j(v.button),buttonId:v.button.id,commandId:v.button.commandId,onConfirmHide:()=>{b(e,t.id,v.groupId,v.button.id),C(null)},onConfirmDisplayRule:()=>{M.getState().hideWithDisplayRules(v.button.commandId),C(null)},onCancel:()=>C(null)})]})}const du=({open:e,initialLabel:t,onRename:n,onCancel:o,noun:s="group"})=>{const[i,l]=E.useState(t),r=i.trim(),c=()=>{r&&(r===t.trim()?o():n(r))};return a.jsx(mn,{open:e,onOpenChange:d=>!d&&o(),size:"small",title:`Rename ${s}`,actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:o,children:"Cancel"}),a.jsx(K,{appearance:"primary",onClick:c,disabled:!r,children:"Rename"})]}),children:a.jsx(_e,{label:s==="tab"?"Tab title":"Group title",required:!0,validationState:r?"none":"error",validationMessage:r?void 0:`Enter a title for the ${s}.`,children:a.jsx(_t,{value:i,onChange:(d,u)=>l(u.value),onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),c())},"data-autofocus":!0})})})},Dv=e=>e.replace(/^Mscrm\.Templates\./,""),Ev=({open:e,currentTemplate:t,customTemplateIds:n=[],loadedGroup:o=!1,onChange:s,onCancel:i})=>{const l=Oa(t),[r,c]=E.useState(l),d=[...new Set([...Db,...n,l])],u=()=>{r===l?i():s(r)};return a.jsxs(mn,{open:e,onOpenChange:p=>!p&&i(),size:"small",title:"Change group template",actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:i,children:"Cancel"}),a.jsx(K,{appearance:"primary",onClick:u,disabled:r===l,children:"Change template"})]}),children:[a.jsx(_e,{label:"Group template",hint:"How the group's buttons shrink when the classic ribbon is narrow. Unified Interface ignores it.",children:a.jsx(xa,{value:r,onChange:(p,m)=>c(m.value),children:d.map(p=>a.jsxs("option",{value:p,children:[Dv(p),p===l?" (current)":""]},p))})}),o&&a.jsx($t,{intent:"warning",style:{marginTop:"12px"},children:a.jsx(Tt,{children:"This group was loaded from the environment. Publishing can't change an existing group's template yet (it's reported as not supported); groups you add publish theirs."})})]})};function Bv(e){if(e instanceof HTMLElement)return e;const{x:t,y:n}=e;return{getBoundingClientRect:()=>({x:t,y:n,top:n,left:t,right:t,bottom:n,width:0,height:0,toJSON:()=>({})})}}function Ja({location:e,tab:t,target:n,onClose:o,moveLabels:s=["Move left","Move right"]}){const i=De(),l=M(N=>N.locLabels),r=M(N=>N.baseLanguageCode),c=M(N=>N.baseline),d=M(N=>N.layers),u=M(N=>N.templates),p=M(N=>N.duplicateGroup),m=M(N=>N.setGroupTemplate),g=M(N=>N.renameGroup),b=M(N=>N.deleteGroup),f=M(N=>N.moveGroup),y=M(N=>N.ribbons),x=Z(N=>N.openNewButton),[v,C]=E.useState(null),[$,A]=E.useState(null),[j,T]=E.useState(null);E.useEffect(()=>{n?.action==="rename"&&(C(n.group),o())},[n,o]);const R=N=>i(N.label,l,r,N.source?.titleToken)||N.id,I=n&&!n.action&&(()=>{const{group:N}=n,B=O=>()=>{O(),o()};return a.jsxs(Ke,{open:!0,onOpenChange:(O,S)=>!S.open&&o(),positioning:{position:"below",align:"start",target:Bv(n.anchor)},children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Je,{children:a.jsxs(Ze,{"aria-label":`Actions for ${R(N)}`,children:[a.jsx(fe,{icon:a.jsx(ke,{}),onClick:B(()=>x(N.id)),children:"Add button…"}),Li("group",N.id,c[e],po({layers:d},e))?a.jsx(fe,{icon:a.jsx(pr,{}),onClick:B(()=>C(N)),children:"Rename…"}):a.jsx(fe,{icon:a.jsx(pr,{}),disabled:!0,title:Fo,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),a.jsx(fe,{icon:a.jsx(yo,{}),onClick:B(()=>p(e,t.id,N.id)),children:"Duplicate group"}),a.jsx(fe,{icon:a.jsx(ro,{}),onClick:B(()=>A(N)),children:"Change template…"}),a.jsx(Dt,{}),[-1,1].map((O,S)=>{const k=Nd({ribbons:y,baseline:c,layers:d},e,t.id,N.id,O),w=t.groups,D=w.findIndex(X=>X.id===N.id),F=!w[D+O];return a.jsx(fe,{icon:O<0?a.jsx(_m,{}):a.jsx(qm,{}),disabled:!k,subText:k||F?void 0:"Only groups your customizations add can change places",onClick:B(()=>f(e,t.id,N.id,O)),children:s[S]},O)}),La(N,c[e],Rn({layers:d},e))&&a.jsxs(a.Fragment,{children:[a.jsx(Dt,{}),a.jsx(fe,{icon:a.jsx(En,{}),onClick:B(()=>T(N)),children:"Delete group"})]})]})})]})})();return a.jsxs(a.Fragment,{children:[I,v&&a.jsx(du,{open:!0,initialLabel:Ge(v.label,l,r),onRename:N=>{g(e,t.id,v.id,N),C(null)},onCancel:()=>C(null)}),$&&a.jsx(Ev,{open:!0,currentTemplate:$.template,customTemplateIds:u.map(N=>N.id),loadedGroup:c[e].tabs.some(N=>N.id===t.id&&N.groups.some(B=>B.id===$.id)),onChange:N=>{m(e,t.id,$.id,N),A(null)},onCancel:()=>A(null)}),j&&a.jsxs(Ln,{open:!0,title:"Delete group",confirmLabel:"Delete group",destructive:!0,onConfirm:()=>{b(e,t.id,j.id),T(null)},onCancel:()=>T(null),children:["Delete the group “",R(j),"” and its"," ",j.buttons.length," button",j.buttons.length===1?"":"s","?"]})]})}function uu(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 Lv={new:ke,plus:ke,addexisting:ke,exporttoexcel:gc,tablegroup:sc,flows:vr,process:vr,emaillink:qh,sendbyemail:nc,failedmail:ji,letter:ji,remove:cn,close:cn,abandon:cn,cancel:xr,cleardefault:xr,assign:_h,activate:jo,saveascomplete:jo,finishstage:jo,setdefault:jo,deactivate:Fh,reactivate:oc,connection:Io,connect:Io,connectiontoother:Io,connectiontome:Io,addtoqueue:yr,bulletlistadd:yr,queueitemdetail:Ph,ratingempty:Bo,ratingfull:Bo,ratingfullgrey:Bo,report:wi,openinpowerbi:wi,wordtemplates:Ls,documenttemplates:Ls,applytemplate:Ls,dynamics365:zh,formdesign:Lh,msteamsicon:Bh,convert:br,switchprocess:br,viewhierarchy:Eh,linkarticle:ac,saveandclose:Dh,saveandedit:hc,runroutingrule:gr,saveandrunroutingrule:gr,createquickcampaign:Mh,pdficonfile:Oh,mergerecords:Ah,yammericon:hr,post:hr,opportunity:Ci,opportunitieslist:Ci,case:cc,deletebulk:En,foldertrack:lc,sadsmiley:kh,kbrecords:fr,insertkbarticle:fr,salesliterature:Nh,follow:Dn,history:Th,contactcard:$h,flash:Rh,pin:jh,multiselect:Ih,browsecards:ic,addmembers:Ch,distributionlist:dc,health:wh,tools:Sh,relationshipassistant:tc,task:vh,appointment:xh},mu={add:{regular:ke,filled:yh},delete:{regular:En,filled:bh},edit:{regular:Ql,filled:gh},save:{regular:hc,filled:hh},copy:{regular:yo,filled:fh},cut:{regular:ph,filled:mh},clipboardpaste:{regular:uh,filled:dh},share:{regular:ch,filled:lh},mail:{regular:ji,filled:rh},chat:{regular:ah,filled:ih},phone:{regular:sh,filled:oh},search:{regular:Hl,filled:nh},filter:{regular:fc,filled:th},arrowleft:{regular:eh,filled:Qf},arrowright:{regular:Zf,filled:Jf},arrowup:{regular:Yf,filled:Kf},arrowdown:{regular:Xf,filled:Vf},chevrondown:{regular:it,filled:Uf},chevronup:{regular:pc,filled:Gf},navigation:{regular:Hf,filled:Wf},home:{regular:qf,filled:_f},settings:{regular:Ff,filled:Pf},info:{regular:Ii,filled:zf},warning:{regular:Ul,filled:Lf},checkmark:{regular:mc,filled:Bf},dismiss:{regular:cn,filled:Ef},questioncircle:{regular:ga,filled:Df},lockclosed:{regular:un,filled:Mf},lockopen:{regular:Of,filled:Af},shield:{regular:kf,filled:Nf},person:{regular:uc,filled:Tf},people:{regular:dc,filled:$f},personadd:{regular:Rf,filled:jf},building:{regular:If,filled:Cf},briefcase:{regular:cc,filled:wf},money:{regular:Ci,filled:Sf},creditcard:{regular:vf,filled:xf},cart:{regular:yf,filled:bf},tag:{regular:gf,filled:hf},document:{regular:ps,filled:ff},documentbulletlist:{regular:pf,filled:mf},folder:{regular:lc,filled:uf},folderopen:{regular:df,filled:cf},attach:{regular:lf,filled:rf},arrowdownload:{regular:af,filled:sf},arrowupload:{regular:of,filled:nf},globe:{regular:rc,filled:tf},link:{regular:ac,filled:ef},open:{regular:ha,filled:Qp},calendar:{regular:Zp,filled:Jp},clock:{regular:Yp,filled:Kp},timer:{regular:Xp,filled:Vp},star:{regular:Bo,filled:Up},heart:{regular:Gp,filled:Hp},thumblike:{regular:Wp,filled:qp},thumbdislike:{regular:_p,filled:Fp},eye:{regular:Dn,filled:Pp},eyeoff:{regular:Bt,filled:zp},zoomin:{regular:Lp,filled:Bp},zoomout:{regular:Ep,filled:Dp},maximize:{regular:Mp,filled:Op},minimize:{regular:Ap,filled:kp},grid:{regular:ic,filled:Np},list:{regular:Tp,filled:$p},table:{regular:va,filled:Rp},tablesimple:{regular:sc,filled:jp},code:{regular:Mn,filled:Ip},bug:{regular:Cp,filled:wp},play:{regular:Sp,filled:vp},pause:{regular:xp,filled:yp},stop:{regular:bp,filled:gp},refresh:{regular:oc,filled:hp},arrowsync:{regular:fp,filled:pp},arrowundo:{regular:pa,filled:mp},arrowredo:{regular:fa,filled:up},printer:{regular:dp,filled:cp},send:{regular:nc,filled:lp},rocket:{regular:rp,filled:ap},sparkle:{regular:ip,filled:sp},trophy:{regular:op,filled:np},lightbulb:{regular:tc,filled:tp},bot:{regular:ep,filled:Qm},databar:{regular:wi,filled:Zm},chartmultiple:{regular:Jm,filled:Ym},poll:{regular:Km,filled:Xm},layoutcolumntwo:{regular:Vm,filled:Um},codeblock:{regular:Gm,filled:Hm},clockarrowcounterclockwise:{regular:ec,filled:Wm}},Za=({name:e,size:t=20,variant:n="regular",style:o,className:s,"aria-hidden":i=!0})=>{const l=uu(e).replace(/_/g,""),r=mu[l],c=(n==="filled"?r?.filled??r?.regular:r?.regular)??Lv[l]??ro;return a.jsx(c,{fontSize:t,"aria-hidden":i,className:s,style:{display:"inline-block",verticalAlign:"middle",flexShrink:0,color:h.colorNeutralForeground1,...o}})};async function fI(e,t=32,n="regular"){const o=uu(e).replace(/_/g,""),s=mu[o],i=n==="filled"?s?.filled??s?.regular:s?.regular;if(!i)return null;const{renderToStaticMarkup:l}=await ht(async()=>{const{renderToStaticMarkup:c}=await import("./server.browser-DTeSoizu.js").then(d=>d.s);return{renderToStaticMarkup:c}},__vite__mapDeps([18,2]),import.meta.url);let r=l(tt.createElement(i,{fontSize:t}));return r.includes("<svg")?(r.includes("xmlns")||(r=r.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),r=r.replace(/width="1em"/,`width="${t}"`).replace(/height="1em"/,`height="${t}"`),r=r.replace(/\s(?:class|aria-hidden|focusable|data-fui-icon|font-size)="[^"]*"/g,""),r):null}function pu(){return window.dataverseAPI}async function zv(){let e="the organization record has no languagecode";for(let t=0;t<2;t++)try{const o=(await pu().queryData("organizations?$select=languagecode")).value?.[0]?.languagecode;if(typeof o=="number")return o}catch(n){e=n instanceof Error?n.message:String(n)}throw new Error(`Couldn't read the organization's base language (${e}).`)}const Pv=[/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 Fv(e){const t=e instanceof Error?`${e.message} ${String(e.code??"")}`:typeof e=="string"?e:JSON.stringify(e??"");return Pv.some(n=>n.test(t))}const _v={0:"Import",1:"Uninstall",2:"Export",3:"Publish",4:"PublishAll",5:"LanguageProvision",6:"ImportTranslation",7:"RibbonMetadataGeneration",8:"WorkflowSetState",10:"ExportLite",11:"UpdatingMissingPackages"},fu=30;async function qv(e=fu,t=Date.now()){const n=t-e*6e4;try{return((await pu().queryData("msdyn_solutionhistories?$select=msdyn_name,msdyn_operation,msdyn_status,msdyn_starttime&$orderby=msdyn_starttime desc&$top=25")).value??[]).filter(s=>typeof s.msdyn_operation=="number"&&(s.msdyn_status===0||s.msdyn_status===2)&&s.msdyn_operation!==2&&s.msdyn_operation!==10&&(!s.msdyn_starttime||Date.parse(s.msdyn_starttime)>=n)).map(s=>({operation:_v[s.msdyn_operation??-1]??`operation ${s.msdyn_operation}`,name:s.msdyn_name??"",startedOn:s.msdyn_starttime??""}))}catch{return[]}}const hu=e=>new Promise(t=>setTimeout(t,e)),ll=e=>e.map(t=>t.name&&t.name!==t.operation?`${t.operation} (${t.name})`:t.operation).join(", ");async function hI(e={}){const t=e.sleep??hu,n=e.now??Date.now,o=n()+(e.timeoutMs??10*6e4);for(;;){const s=await qv(fu,n());if(s.length===0)return;if(n()>=o)throw new Error(`The environment is still busy (${ll(s)} running). Try again when it has finished — Solutions › History shows its progress.`);e.onProgress?.(`Waiting for another operation to finish: ${ll(s)}…`),await t(15e3)}}async function gu(e,t,n={}){const o=n.sleep??hu,s=n.now??Date.now,i=s()+(n.timeoutMs??10*6e4);for(let l=0;;l++)try{return await t()}catch(r){if(!Fv(r))throw r;const c=Math.min(6e4,15e3*2**l);if(s()+c>i)throw new Error(`${e} kept failing because another solution operation is running in the environment (${r instanceof Error?r.message:String(r)}). Try again when it has finished.`);n.onProgress?.(`${e}: another solution operation is running in the environment — retrying in ${Math.round(c/1e3)} s…`),await o(c)}}function Yt(){const e=window.dataverseAPI;if(!e)throw new Error("dataverseAPI is not available in the current runtime");return e}const bu={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 yu(e){return bu[e]??"xml"}async function Wv(e,t){let n="webresourceset?$select=webresourceid,name,displayname,description,webresourcetype,modifiedon,ismanaged&$orderby=name asc";if(t!==void 0){const s=Object.entries(bu).find(([,i])=>i===t)?.[0];s&&(n+=`&$filter=webresourcetype eq ${s}`)}return(await e.queryData(n)).value.map(s=>{const i=s;return{id:String(i.webresourceid??""),name:String(i.name??""),displayName:i.displayname?String(i.displayname):void 0,description:i.description?String(i.description):void 0,webResourceType:yu(Number(i.webresourcetype??3)),modifiedOn:i.modifiedon?String(i.modifiedon):void 0,isCustom:i.ismanaged===!1}})}async function Hv(e,t){const n=await e.retrieve("webresource",t,["content"]);return n.content?String(n.content):""}const xu=61;async function vu(e,t,n,o=fs){await o("Adding the web resource to the solution"),await e.execute({operationName:"AddSolutionComponent",operationType:"action",parameters:{ComponentId:t,ComponentType:xu,SolutionUniqueName:n,AddRequiredComponents:!1}})}class Gv extends Error{constructor(t){super(`Web resource ${t} already exists; it was left as it is.`),this.name="WebResourceSaveCancelled"}}async function Uv(e,t,n,o,s={}){const i=s.guard??Ec(),{displayName:l,solutionUniqueName:r,onExisting:c}=s;let d=s.keepExisting??!1;const u=await e.queryData(`webresourceset?$select=webresourceid,ismanaged&$filter=name eq '${t.replace(/'/g,"''")}'&$top=1`),p={name:t,content:n,webresourcetype:o,...l?{displayname:l}:{}};let m;if(u.value.length>0){const g=u.value[0],b=String(g.webresourceid??"");if(!d&&c){const f=g.ismanaged===!0,y=await c({id:b,name:t,managed:f});if(y==="cancel")throw new Gv(t);if(y==="replace"&&f)throw new Error(`A managed web resource named ${t} already exists, so it can't be replaced. Keep it, or rename the file and upload it again.`);d=y==="keep"}d||(await i("Saving the web resource"),await e.update("webresource",b,p)),m={id:b,created:!1,updated:!d}}else{await i("Saving the web resource");const g=await e.create("webresource",p);m={id:String(g.id??""),created:!0,updated:!1}}if(r&&m.id){try{await vu(e,m.id,r,i)}catch(g){throw new Error(`Web resource ${t} was saved but could not be added to solution ${r}: ${g instanceof Error?g.message:String(g)}`)}m.solutionUniqueName=r}return m}const cl=40,dl=(e,t)=>Array.from({length:Math.ceil(e.length/t)},(n,o)=>e.slice(o*t,(o+1)*t)),Vv=e=>`'${e.replace(/'/g,"''").replace(/[^A-Za-z0-9/._\-'~]/gu,t=>encodeURIComponent(t))}'`,ul=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Xv(e,t,n){const o=t.map(c=>c.split(/[?#]/)[0].trim()).filter(Boolean),s=o.filter((c,d)=>o.findIndex(u=>u.toLowerCase()===c.toLowerCase())===d),i={};for(const c of s)i[c.toLowerCase()]={exists:!1,inSolution:!1};if(s.length===0)return i;const l=new Map;for(const c of dl(s,cl)){const d=c.map(p=>`name eq ${Vv(p)}`).join(" or "),u=await e.queryData(`webresourceset?$select=webresourceid,name,ismanaged&$filter=${d}`);for(const p of u.value??[]){const m=p,g=String(m.name??"").toLowerCase();if(!(g in i))continue;i[g]={exists:!0,inSolution:!1,managed:m.ismanaged===!0};const b=String(m.webresourceid??"").toLowerCase();ul.test(b)&&l.set(b,g)}}const r=n?.replace(/[{}]/g,"");if(r&&ul.test(r)&&l.size>0)for(const c of dl([...l.keys()],cl)){const d=c.map(p=>`objectid eq ${p}`).join(" or "),u=await e.queryData(`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${r} and componenttype eq ${xu} and (${d})`);for(const p of u.value??[]){const m=l.get(String(p.objectid??"").toLowerCase());m&&(i[m].inSolution=!0)}}return i}async function gI(e,t){return Xv(Yt(),e,t)}async function bI(e){return Wv(Yt(),e)}async function yI(e){return Hv(Yt(),e)}async function Kv(e){const t=Yt(),n=e.replace(/'/g,"''"),o=await t.queryData(`webresourceset?$select=webresourceid,name,displayname,webresourcetype,ismanaged&$filter=name eq '${n}'&$top=1`);if(!o.value?.length)return null;const s=o.value[0];return{id:String(s.webresourceid??""),name:String(s.name??""),displayName:s.displayname?String(s.displayname):void 0,webResourceType:yu(Number(s.webresourcetype??3)),isCustom:s.ismanaged===!1}}async function Yv(e,t,n,o={}){const s=ae.getState().activeSolution,i=o.solutionUniqueName??(s&&!s.isManaged?s.uniqueName:void 0),l=o.guard??Ec(),r=await Uv(Yt(),e,t,n,{...o,solutionUniqueName:i,guard:l});if((r.created||r.updated)&&o.publish!==!1)try{await gu(`Publishing web resource ${e}`,()=>Su(r.id,l),{timeoutMs:2*6e4,onProgress:c=>ce.getState().logInfo("webresource",c)}),r.published=!0}catch(c){r.publishWarning=`Web resource ${e} was saved but not published (${c instanceof Error?c.message:String(c)}). Users get the previous version until it's published: save it again, or run Publish All.`,ce.getState().logWarn("webresource",r.publishWarning)}if(!i){const c=s?`the active solution ${s.uniqueName} is managed`:"no solution is selected";r.solutionWarning=`Web resource ${e} was saved but not added to any solution because ${c}. It is only in the Default solution — select an unmanaged solution and save it again so it travels with your customizations.`,ce.getState().logWarn("webresource",r.solutionWarning)}return r}async function xI(e,t,n=fs){const o=t??await Kv(e);if(!o?.id)throw new Error(`No web resource named ${e} exists in this environment.`);const s=o.id;if(o.isCustom===!1){const l=`Web resource ${e} is managed, so it isn't added to your solution. The solution that provides it must be installed wherever you import your customizations.`;return ce.getState().logWarn("webresource",l),{solutionWarning:l}}const i=ae.getState().activeSolution;if(!i||i.isManaged){const l=i?`the active solution ${i.uniqueName} is managed`:"no solution is selected",r=`Web resource ${e} was not added to any solution because ${l}. Select an unmanaged solution and pick the icon again so it travels with your customizations.`;return ce.getState().logWarn("webresource",r),{solutionWarning:r}}return await vu(Yt(),s,i.uniqueName,n),{solutionUniqueName:i.uniqueName}}async function Su(e,t=fs){const n=Yt(),o=`<importexportxml><webresources><webresource>${e}</webresource></webresources></importexportxml>`;await t("Publishing the web resource"),await n.execute({operationName:"PublishXml",operationType:"action",parameters:{ParameterXml:o}})}const Jv={5:"image/png",6:"image/jpeg",7:"image/gif",10:"image/x-icon",11:"image/svg+xml"};async function Zv(e){const o=(await Yt().queryData(`webresourceset?$select=content,webresourcetype&$filter=name eq '${e.replace(/'/g,"''")}'&$top=1`)).value?.[0],s=Jv[Number(o?.webresourcetype)],i=o?.content;return s&&typeof i=="string"&&i?`data:${s};base64,${i}`:null}const Qv=.35,gn=24,ml=new Map;function eS(e){return new Promise(t=>{const n=new Image;n.onload=()=>{try{const o=document.createElement("canvas");o.width=gn,o.height=gn;const s=o.getContext("2d");if(!s)return t("light");s.drawImage(n,0,0,gn,gn);const{data:i}=s.getImageData(0,0,gn,gn);let l=0,r=0;for(let c=0;c<i.length;c+=4){const d=i[c+3]/255;d<.5||(l+=d*(.2126*i[c]+.7152*i[c+1]+.0722*i[c+2]),r+=d*255)}t(r>0&&l/r<Qv?"dark":"light")}catch{t("light")}},n.onerror=()=>t("light"),n.src=e})}function tS(e){let t=ml.get(e);return t||(t=eS(e),ml.set(e,t)),t}const pl="$webresource:",nS="invert(1) hue-rotate(180deg)",ai=new Map,oS=6;let ri=0;const fl=[];async function sS(e){ri>=oS&&await new Promise(t=>fl.push(t)),ri++;try{return await e()}finally{ri--,fl.shift()?.()}}function iS(e,t){let n=ai.get(e);return n||(n=sS(()=>Zv(t)).catch(()=>(ai.delete(e),null)),ai.set(e,n)),n}function aS(e){return[e.image32,e.image16,e.source?.modernImage].find(n=>n?.startsWith(pl))?.slice(pl.length).trim()||void 0}function vt({button:e,size:t,style:n}){const o=ae(m=>m.connectionUrl),s=Z(m=>m.themeMode==="dark"),i=aS(e),l=i?`${o}|${i}`:"",[r,c]=E.useState({key:"",src:null}),[d,u]=E.useState(null);E.useEffect(()=>{if(!l||!i)return;let m=!0;return iS(l,i).then(g=>{m&&c({key:l,src:g})}),()=>{m=!1}},[l,i]);const p=l&&r.key===l?r.src:null;if(E.useEffect(()=>{if(!s||!p)return;let m=!0;return tS(p).then(g=>{m&&u({src:p,tone:g})}),()=>{m=!1}},[s,p]),p){const g=[s&&d?.src===p&&d.tone==="dark"&&nS,n?.filter!=="none"&&n?.filter].filter(Boolean).join(" ")||void 0;return a.jsx("img",{src:p,width:t,height:t,alt:"","aria-hidden":!0,style:{objectFit:"contain",...n,filter:g}})}return a.jsx(Za,{name:e.icon||"apps_add_in",size:t,style:n})}const wu="__end__";function rS(e,t){return`slot::${e}::${t??wu}`}function lS(e){return`group::${e}`}function hl(e){if(e.startsWith("slot::")){const[,t,n]=e.split("::");return{kind:"slot",groupId:t,beforeButtonId:n===wu?null:n}}return e.startsWith("group::")?{kind:"group",groupId:e.slice(7)}:null}const bn={root:{display:"flex",gap:h.spacingHorizontalM,flexWrap:"wrap",alignItems:"flex-start",minHeight:"120px",padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`},groupButtons:{display:"flex",gap:h.spacingHorizontalXS,flexWrap:"wrap",minHeight:"72px",alignItems:"flex-start",padding:h.spacingHorizontalXS},groupLabel:{textAlign:"center",fontSize:h.fontSizeBase100,color:h.colorNeutralForeground3,borderTop:`1px solid ${h.colorNeutralStroke2}`,paddingTop:h.spacingVerticalXS,paddingBottom:h.spacingVerticalXS,marginTop:"auto"},emptyTab:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:h.spacingVerticalM,minHeight:"160px",color:h.colorNeutralForeground3,flex:1,padding:"48px",textAlign:"center"},addGroupBtn:{minHeight:"96px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",border:`1px dashed ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,cursor:"pointer",color:h.colorNeutralForeground3,backgroundColor:"transparent"},addButtonGhost:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",width:"60px",minHeight:"72px",borderRadius:h.borderRadiusMedium,border:`1px dashed ${h.colorNeutralStroke2}`,backgroundColor:"transparent",cursor:"pointer",color:h.colorNeutralForeground3}};function cS({button:e}){const t=M(s=>s.locLabels),o=De()(e.label,t,void 0,e.source?.labelToken);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:h.borderRadiusMedium,border:`1px solid ${h.colorBrandStroke1}`,backgroundColor:h.colorNeutralBackground1,boxShadow:h.shadow16,opacity:.9,cursor:"grabbing",pointerEvents:"none",color:e.custom?h.colorBrandForeground1:h.colorNeutralForeground1},children:[a.jsx(vt,{button:e,size:24}),a.jsx("span",{style:{fontSize:h.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.colorNeutralForeground1},children:o})]})}function dS({group:e,isDropTarget:t,children:n,...o}){const{setNodeRef:s,isOver:i}=ja({id:lS(e.id),data:{type:"group",groupId:e.id}});return a.jsx("div",{ref:s,style:{display:"flex",flexDirection:"column",minWidth:"80px",border:`1px solid ${i||t?h.colorBrandStroke1:h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,backgroundColor:i||t?h.colorBrandBackground2:h.colorNeutralBackground2,padding:`${h.spacingVerticalXS} ${h.spacingHorizontalXS}`,transition:"border-color 0.1s, background-color 0.1s"},...o,children:n})}function gl({groupId:e,beforeButtonId:t}){const n=rS(e,t),{setNodeRef:o,isOver:s}=ja({id:n,data:{type:"slot",groupId:e,beforeButtonId:t}});return a.jsx("div",{ref:o,style:{width:s?"2px":"0px",minHeight:"72px",backgroundColor:h.colorBrandStroke1,borderRadius:"2px",flexShrink:0,transition:"width 0.1s"},"aria-hidden":!0})}function uS({tab:e,location:t}){const n=M(N=>N.locLabels),o=De(),s=M(N=>N.baseLanguageCode),i=N=>o(N.label,n,s,N.source?.titleToken)||N.id,l=M(N=>N.moveButton),r=M(N=>N.createGroup),c=Z(N=>N.openNewButton),d=Z(N=>N.openNewGroup),u=Y(N=>N.selectButtonInContext),p=Y(N=>N.selectGroup),[m,g]=E.useState(null),[b,f]=E.useState(null),[y,x]=E.useState(null),[v,C]=E.useState(null),$=E.useMemo(()=>{if(!y)return null;for(const N of e.groups){const B=N.buttons.find(O=>O.id===y);if(B)return{button:B,groupId:N.id}}return null},[y,e.groups]),A=Tc(Uo(Mc,{activationConstraint:{distance:5}}),Uo(Oc));function j(N){x(String(N.active.id))}function T(N){const B=N.over;if(!B){C(null);return}const O=hl(String(B.id));C(O?O.groupId:null)}function R(){x(null),C(null)}function I(N){const{active:B,over:O}=N;if(x(null),C(null),!O||!B)return;let S=null;for(const D of e.groups)if(D.buttons.some(F=>F.id===B.id)){S=D.id;break}if(!S)return;const k=hl(String(O.id));if(!k)return;let w=null;k.kind==="slot"?w=l({groupId:S,buttonId:String(B.id),tabId:e.id,location:t},{groupId:k.groupId,beforeButtonId:k.beforeButtonId??void 0,tabId:e.id,location:t}):k.kind==="group"&&k.groupId!==S&&(w=l({groupId:S,buttonId:String(B.id),tabId:e.id,location:t},{groupId:k.groupId,tabId:e.id,location:t})),w&&w!==String(B.id)&&u(t,e.id,k.groupId,w)}return e.groups.length===0?a.jsxs("div",{style:bn.emptyTab,children:[a.jsx(ps,{fontSize:36,"aria-hidden":!0}),a.jsx(V,{children:"This tab has no groups yet"}),a.jsxs("button",{type:"button",style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 16px",background:h.colorBrandBackground,color:h.colorNeutralForegroundInverted,border:"none",borderRadius:h.borderRadiusMedium,cursor:"pointer",fontSize:h.fontSizeBase300},onClick:()=>d(),children:[a.jsx(ke,{fontSize:12})," Add first group"]})]}):a.jsxs(a.Fragment,{children:[t==="SubGrid"&&a.jsx($t,{intent:"info",style:{margin:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`},children:a.jsxs(Tt,{children:["Subgrid ribbons support only 3 native controls: ",a.jsx("strong",{children:"Add"}),","," ",a.jsx("strong",{children:"Show List"}),", and ",a.jsx("strong",{children:"Delete"}),". Their icons cannot be changed."]})}),a.jsxs(Nc,{sensors:A,collisionDetection:kc,onDragStart:j,onDragOver:T,onDragEnd:I,onDragCancel:R,children:[a.jsxs("div",{style:bn.root,role:"group","aria-label":"Groups","data-ribbon-canvas-root":"1",children:[e.groups.map(N=>a.jsxs(dS,{group:N,isDropTarget:v===N.id,role:"group","aria-label":i(N),tabIndex:0,"data-ribbon-group-id":N.id,onContextMenu:B=>{B.target.closest("[data-btn]")||(B.preventDefault(),f({group:N,anchor:{x:B.clientX,y:B.clientY}}))},onFocus:B=>{B.target===B.currentTarget&&p(N.id)},onKeyDown:B=>{if(B.target===B.currentTarget&&(B.key==="Enter"||B.key===" ")&&N.buttons.length>0){B.preventDefault();const O=N.buttons[0];if(!O)return;u(t,e.id,N.id,O.id),document.querySelector(`[data-ribbon-btn-id="${O.id}"]`)?.focus()}},children:[a.jsxs("div",{style:bn.groupButtons,children:[N.buttons.map(B=>a.jsxs(tt.Fragment,{children:[y&&a.jsx(gl,{groupId:N.id,beforeButtonId:B.id}),a.jsx(mS,{button:B,groupId:N.id,tabId:e.id,location:t,activeId:y,onContextMenu:O=>g({groupId:N.id,button:B,anchor:O.currentTarget})})]},B.id)),y&&a.jsx(gl,{groupId:N.id,beforeButtonId:null}),a.jsxs("button",{type:"button",style:bn.addButtonGhost,"data-add-btn-group-id":N.id,onClick:()=>c(N.id),title:`Add button to ${i(N)}`,"aria-label":`Add button to ${i(N)}`,children:[a.jsx(ke,{fontSize:16}),a.jsx(V,{size:100,style:{color:"inherit"},children:"Add"})]})]}),a.jsx(pe,{content:`Template: ${N.template||"Flexible2"}`,relationship:"description",children:a.jsx("div",{style:bn.groupLabel,children:i(N)})})]},N.id)),a.jsx("button",{type:"button",style:bn.addGroupBtn,onClick:()=>r({tabId:e.id,location:t,group:{label:"New Group",sequence:(e.groups.length+1)*10,template:"Flexible2",buttons:[]}}),title:"Add group","aria-label":"Add group",children:a.jsx(ke,{fontSize:16})})]}),a.jsx(Ac,{dropAnimation:null,children:$?a.jsx(cS,{button:$.button}):null})]}),a.jsx(wo,{location:t,tab:e,target:m,onClose:()=>g(null)}),a.jsx(Ja,{location:t,tab:e,target:b,onClose:()=>f(null)})]})}const mS=tt.memo(function({button:t,groupId:n,tabId:o,location:s,activeId:i,onContextMenu:l}){const r=Y(I=>I.selectedButtonId),c=Y(I=>I.selectButtonInContext),d=M(I=>I.locLabels),u=De(),p=r===t.id,m=s==="Application"&&o==="Mscrm.GlobalTab"&&t.oob&&!t.custom,g=u(t.label,d,void 0,t.source?.labelToken),b=dt(t.kind)?xt[t.kind]:void 0,f=b?` (${b}, read-only)`:"",{attributes:y,listeners:x,setNodeRef:v,isDragging:C}=Ag({id:t.id,data:{type:"button",button:t,groupId:n},disabled:t.managed||m}),$=C||i===t.id,{onKeyDown:A,...j}=x??{},T={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:h.borderRadiusMedium,cursor:"grab",border:p?`1px solid ${h.colorBrandStroke1}`:t.custom?`1px solid ${h.colorBrandStroke2}`:"1px solid transparent",backgroundColor:p?h.colorBrandBackground2:t.managed?h.colorNeutralBackground3:"transparent",opacity:$?.3:t.hidden?.4:1,position:"relative",userSelect:"none",color:t.custom?h.colorBrandForeground1:h.colorNeutralForeground1,transition:"opacity 0.15s, border-color 0.1s, background-color 0.1s"},R=I=>{if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(I.key))return;I.preventDefault();const N=I.currentTarget.closest("[data-ribbon-canvas-root='1']");if(!N)return;const B=Array.from(N.querySelectorAll(`[data-ribbon-tab-id="${o}"][data-btn="1"]`)),O=B.findIndex(X=>X.dataset.ribbonBtnId===t.id);if(O<0||B.length===0)return;const S=I.key==="ArrowLeft"||I.key==="ArrowUp"?-1:1,k=Math.max(0,Math.min(B.length-1,O+S)),w=B[k],D=w?.dataset.ribbonGroupId,F=w?.dataset.ribbonBtnId;!w||!D||!F||(c(s,o,D,F),w.focus())};return a.jsx(pe,{content:m?"OOB global command bar buttons cannot be customized.":`${g}${f}${t.hidden?" — hidden":""}`,relationship:"label",children:a.jsxs("button",{ref:v,type:"button","data-btn":"1","data-ribbon-tab-id":o,"data-ribbon-group-id":n,"data-ribbon-btn-id":t.id,style:T,"aria-current":p?"true":void 0,"aria-label":`${g}${f}${t.hidden?" — hidden":""}${t.custom?" (custom)":""}${t.managed?" (read-only)":""}`,onClick:()=>c(s,o,n,t.id),onFocus:()=>c(s,o,n,t.id),onKeyDown:I=>{if(!i){if(I.key==="Enter"||I.key===" "){c(s,o,n,t.id),A?A(I):I.preventDefault();return}R(I)}},onContextMenu:I=>{I.preventDefault(),I.stopPropagation(),c(s,o,n,t.id),l(I)},...y,...j,children:[a.jsx(vt,{button:t,size:24,style:{filter:t.custom?"none":"grayscale(40%) opacity(0.85)"}}),a.jsx("span",{style:{fontSize:h.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.colorNeutralForeground1},children:g}),b&&a.jsx("span",{style:{fontSize:h.fontSizeBase100,lineHeight:"1",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.colorNeutralForeground3},children:b}),t.menu&&a.jsx(it,{fontSize:10,"aria-label":"Has a menu"}),t.hidden&&a.jsx("span",{style:{position:"absolute",top:2,right:2},"aria-hidden":!0,children:a.jsx(Bt,{fontSize:10,style:{color:h.colorNeutralForeground3}})}),t.custom&&!t.managed&&a.jsx(pe,{content:"Yours: added by your customizations",relationship:"label",children:a.jsx(xe,{size:"extra-small",color:"brand",style:{position:"absolute",bottom:4,right:4}})}),(t.managed||m)&&a.jsx("span",{style:{position:"absolute",top:2,left:2},title:m?"OOB global command bar buttons cannot be customized.":"Read-only (managed)",children:a.jsx(un,{fontSize:10,style:{color:h.colorNeutralForeground3}})})]})})});function pS(e,t,n){if(!t.buttonId||n.groupId===t.groupId&&n.buttonId===t.buttonId)return null;const o=e.find(r=>r.id===n.groupId);if(!o)return null;const s=ft(o.buttons);if(!n.buttonId)return o.id===t.groupId&&s.at(-1)?.id===t.buttonId?null:{groupId:o.id};const i=s.findIndex(r=>r.id===n.buttonId);if(i<0)return null;const l=o.id===t.groupId?s.findIndex(r=>r.id===t.buttonId):-1;if(l>=0&&l<i){const r=s[i+1]?.id;return r?{groupId:o.id,before:r}:{groupId:o.id}}return{groupId:o.id,before:n.buttonId}}const Qa=me({root:{display:"flex",flexWrap:"wrap",alignItems:"flex-start",gap:h.spacingHorizontalM},card:{flex:"1 1 240px",minWidth:"220px",maxWidth:"320px",display:"flex",flexDirection:"column",backgroundColor:h.colorNeutralBackground1,border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusLarge,boxShadow:h.shadow2,minHeight:0},cardSelected:{border:`1px solid ${h.colorBrandStroke1}`},cardOver:{backgroundColor:h.colorBrandBackground2},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalXS} ${h.spacingVerticalXS} ${h.spacingHorizontalM}`,borderBottom:`1px solid ${h.colorNeutralStroke3}`},titleButton:{flex:1,minWidth:0,display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",padding:0,fontWeight:"inherit",textAlign:"left"},ellipsis:{display:"block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3},rows:{display:"flex",flexDirection:"column",padding:h.spacingVerticalXS,gap:"2px",minHeight:"8px"},row:{display:"flex",alignItems:"center",justifyContent:"flex-start",gap:h.spacingHorizontalS,width:"100%",maxWidth:"100%",minWidth:0,minHeight:"32px",padding:`0 ${h.spacingHorizontalS}`,fontWeight:h.fontWeightRegular,textAlign:"left"},rowSelected:{backgroundColor:h.colorSubtleBackgroundSelected,border:`1px solid ${h.colorBrandStroke1}`},rowHidden:{color:h.colorNeutralForeground3},handle:{color:h.colorNeutralForeground3,flexShrink:0},handleOff:{visibility:"hidden"},label:{flex:1,minWidth:0},footer:{padding:`0 ${h.spacingHorizontalXS} ${h.spacingVerticalXS}`},overlay:{boxShadow:h.shadow16,backgroundColor:h.colorNeutralBackground1,borderRadius:h.borderRadiusMedium}}),fS=e=>{const t=e.droppableContainers.filter(i=>String(i.id).startsWith("row:")),n=e.droppableContainers.filter(i=>String(i.id).startsWith("card:"));if(e.pointerCoordinates){const i=Ir({...e,droppableContainers:t});if(i.length)return i;const l=Ir({...e,droppableContainers:n});if(l.length)return l}const o=new Set(t.map(i=>i.data.current?.groupId)),s=n.filter(i=>!o.has(i.data.current?.groupId));return kc({...e,droppableContainers:[...t,...s]})},er=(e,t)=>`row:${e}:${t}`,Cu=e=>`card:${e}`;function hS({tab:e,location:t}){const n=Qa(),o=De(),s=M(S=>S.locLabels),i=M(S=>S.baseLanguageCode),l=M(S=>S.moveButton),r=Y(S=>S.selectedGroupId),c=Y(S=>S.selectedButtonId),d=Y(S=>S.selectGroup),u=Y(S=>S.selectButtonInContext),p=Z(S=>S.openNewButton),[m,g]=E.useState(null),[b,f]=E.useState(null),[y,x]=E.useState(null),[v,C]=E.useState(null),$=E.useRef(null),A=S=>o(S.label,s,i,S.source?.titleToken)||S.id,j=S=>o(S.label,s,void 0,S.source?.labelToken)||S.id,T=Tc(Uo(Mc,{activationConstraint:{distance:5}}),Uo(Oc,{coordinateGetter:Og,keyboardCodes:{start:["Space"],cancel:["Escape"],end:["Space","Enter"]}})),R=S=>setTimeout(()=>{if(document.activeElement?.closest('[role="dialog"], [role="alertdialog"]'))return;const k=Y.getState().selectedButtonId;(S instanceof HTMLElement&&S.isConnected?S:[...$.current?.querySelectorAll("[data-card-button]")??[]].find(D=>D.dataset.cardButton===k))?.focus()}),I=S=>{const k=String(S??"");for(const w of e.groups){if(k===Cu(w.id))return`the end of ${A(w)}`;const D=w.buttons.find(F=>k===er(w.id,F.id));if(D)return`${j(D)} in ${A(w)}`}return""},N=S=>S&&typeof S=="object"&&"groupId"in S?S:null,B=S=>{const k=N(S.active.data.current),w=e.groups.find(F=>F.id===k?.groupId),D=w?.buttons.find(F=>F.id===k?.buttonId);w&&D&&x({button:D,groupId:w.id})},O=S=>{x(null),C(null);const k=N(S.active.data.current),w=N(S.over?.data.current);if(!k?.buttonId||!w)return;const D=pS(e.groups,k,w);if(!D)return;const F=l({location:t,tabId:e.id,groupId:k.groupId,buttonId:k.buttonId},{location:t,tabId:e.id,groupId:D.groupId,beforeButtonId:D.before});F&&(u(t,e.id,D.groupId,F),setTimeout(()=>[...$.current?.querySelectorAll("[data-card-button]")??[]].find(X=>X.dataset.cardButton===F)?.focus()))};return a.jsxs(a.Fragment,{children:[a.jsxs(Nc,{sensors:T,collisionDetection:fS,onDragStart:B,onDragOver:S=>C(N(S.over?.data.current)?.groupId??null),onDragEnd:O,onDragCancel:()=>{x(null),C(null)},accessibility:{screenReaderInstructions:{draggable:"To move a button, press Space. Use the arrow keys to move it, Space or Enter to drop it, Escape to cancel."},announcements:{onDragStart:({active:S})=>`Picked up ${I(S.id)}.`,onDragOver:({active:S,over:k})=>k?`${I(S.id)} is over ${I(k.id)}.`:void 0,onDragEnd:({active:S,over:k})=>k?`${I(S.id)} was dropped on ${I(k.id)}.`:`${I(S.id)} was dropped.`,onDragCancel:({active:S})=>`Moving ${I(S.id)} was cancelled.`}},children:[a.jsx("div",{ref:$,className:n.root,"aria-label":`Groups of ${e.id}`,role:"list",children:ft(e.groups).map(S=>a.jsx(gS,{group:S,tab:e,location:t,title:A(S),buttonText:j,selected:r===S.id&&!c,selectedButtonId:r===S.id?c:null,dropping:v===S.id&&!!y,onSelectGroup:()=>d(S.id),onSelectButton:k=>u(t,e.id,S.id,k.id),onGroupMenu:k=>g({group:S,anchor:k}),onButtonMenu:(k,w)=>f({button:k,groupId:S.id,anchor:w}),onAddButton:()=>p(S.id)},S.id))}),a.jsx(Ac,{dropAnimation:null,children:y&&a.jsxs("div",{className:Ie(n.row,n.overlay),children:[a.jsx(bc,{className:n.handle}),a.jsx(vt,{button:y.button,size:16}),a.jsx("span",{className:Ie(n.label,n.ellipsis),children:j(y.button)})]})})]}),a.jsx(Ja,{location:t,tab:e,target:m,onClose:()=>{R(m?.anchor),g(null)}}),a.jsx(wo,{location:t,tab:e,target:b,onClose:()=>{R(b?.anchor),f(null)}})]})}function gS({group:e,tab:t,location:n,title:o,buttonText:s,selected:i,selectedButtonId:l,dropping:r,onSelectGroup:c,onSelectButton:d,onGroupMenu:u,onButtonMenu:p,onAddButton:m}){const g=Qa(),{setNodeRef:b}=ja({id:Cu(e.id),data:{groupId:e.id}}),f=ft(e.buttons);return a.jsxs("section",{ref:b,role:"listitem","aria-label":o,"data-group-card":e.id,className:Ie(g.card,i&&g.cardSelected,r&&g.cardOver),children:[a.jsxs("div",{className:g.header,children:[a.jsx(pe,{content:`${o} (${e.id})`,relationship:"description",children:a.jsxs(K,{appearance:"transparent",className:g.titleButton,"aria-pressed":i,onClick:c,onContextMenu:y=>{y.preventDefault(),u(y.currentTarget)},onKeyDown:y=>{(y.key==="ContextMenu"||y.shiftKey&&y.key==="F10")&&(y.preventDefault(),u(y.currentTarget))},children:[a.jsx(V,{weight:"semibold",size:300,className:g.ellipsis,children:o}),a.jsx(V,{size:200,className:Ie(g.ellipsis,g.muted),children:e.template||"Flexible2"})]})}),a.jsx(pe,{content:"Group options",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(yc,{}),"aria-label":`Group options: ${o}`,onClick:y=>u(y.currentTarget)})})]}),a.jsx(Mg,{items:f.map(y=>er(e.id,y.id)),strategy:Dg,children:a.jsx("div",{className:g.rows,role:"list","aria-label":`Buttons in ${o}`,children:f.map(y=>a.jsx(bS,{button:y,groupId:e.id,text:s(y),locked:y.managed||Ba(n,t.id,y),selected:l===y.id,onSelect:()=>d(y),onMenu:x=>p(y,x)},y.id))})}),a.jsx("div",{className:g.footer,children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:m,"aria-label":`Add button to ${o}`,children:"Add button"})})]})}function bS({button:e,groupId:t,text:n,locked:o,selected:s,onSelect:i,onMenu:l}){const r=Qa(),{attributes:c,listeners:d,setNodeRef:u,transform:p,transition:m,isDragging:g}=Eg({id:er(t,e.id),data:{groupId:t,buttonId:e.id},disabled:{draggable:o,droppable:!1}}),b=e.custom&&!e.managed,f=dt(e.kind)?xt[e.kind]:void 0,y=`${n}${f?` (${f}, read-only)`:""}${e.hidden?", hidden":""}${b?", yours":""}, Sequence ${e.sequence}`;return a.jsx("div",{role:"listitem",style:{opacity:g?.4:1},children:a.jsx(pe,{content:`${n} (${e.id})`,relationship:"description",children:a.jsxs(K,{ref:u,appearance:"subtle",...c,...d,"aria-roledescription":o?void 0:"draggable button","aria-label":y,"aria-pressed":s,"data-card-button":e.id,className:Ie(r.row,s&&r.rowSelected,e.hidden&&r.rowHidden),style:{transform:Bg.Transform.toString(p),transition:m},onClick:i,onContextMenu:x=>{x.preventDefault(),l(x.currentTarget)},onKeyDown:x=>{if(x.key==="ContextMenu"||x.shiftKey&&x.key==="F10"){x.preventDefault(),l(x.currentTarget);return}d?.onKeyDown?.(x)},children:[a.jsx(bc,{"aria-hidden":!0,className:Ie(r.handle,o&&r.handleOff)}),a.jsx(vt,{button:e,size:16}),a.jsx("span",{className:Ie(r.label,r.ellipsis),children:n}),e.hidden?a.jsx(xe,{size:"medium",appearance:"outline",color:"subtle",children:"Hidden"}):b?a.jsx(xe,{size:"medium",appearance:"tint",color:"brand",children:"Yours"}):null,a.jsx(V,{size:200,className:r.muted,children:e.sequence})]})})})}const Kn={Form:0,MainGrid:1,SubGrid:2,AssociatedGrid:3,GlobalHeader:5},yS={0:"Form",1:"Main grid",2:"Subgrid",3:"Associated grid",4:"Quick form",5:"Global header",6:"Dashboard"},Iu="appaction_appactionrule_classicrules",xS=["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"],li="@OData.Community.Display.V1.FormattedValue",Me=e=>typeof e=="string"&&e.trim()!==""?e:typeof e=="number"?String(e):void 0,Mt=e=>{if(e==null||e==="")return;const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0},Ao=e=>e===!0||e===1||e==="true"||e==="1",nn=e=>{const t=Me(e);return t?t.toLowerCase():null};function vS(e){switch(Mt(e)){case 1:return"dropdown";case 2:return"split";case 3:return"group";default:return"button"}}function SS(e){const t=Mt(e);return t===1?"formula":t===2?"javascript":"none"}function wS(e){const t=Mt(e);return t===1?"formula":t===2?"classicRules":"none"}function CS(e){const t=Mt(e);return t===1?"migrated":t===2?"enhancedMigrated":"default"}function bl(e,t){const n={componentLibrary:Me(e[`${t}componentlibrary`]),componentName:Me(e[`${t}componentname`]),functionName:Me(e[`${t}functionname`])};return n.componentLibrary||n.componentName||n.functionName?n:void 0}function IS(e){return Array.isArray(e)?e.map(t=>{const n=nn(t.appactionruleid);return n?{id:n,name:Me(t.name)??Me(t.uniquename)??n,uniqueName:Me(t.uniquename),kind:Mt(t.type)===0?"enable":"display"}:null}).filter(t=>t!==null):[]}function jS(e){const t=nn(e.appactionid);if(!t)return null;const n=Mt(e.location);if(n===void 0)return null;const o=Me(e.name)??"",s=Me(e.uniquename)??o;return{id:t,name:o,uniqueName:s,label:Me(e.buttonlabeltext)??(o||s||t),tooltipTitle:Me(e.buttontooltiptitle),tooltipDescription:Me(e.buttontooltipdescription),accessibilityText:Me(e.buttonaccessibilitytext),appModuleId:nn(e._appmoduleid_value),appName:Me(e[`_appmoduleid_value${li}`]),scope:Mt(e.context)===0?"all":"entity",contextValue:Me(e.contextvalue),contextEntityId:nn(e._contextentity_value)??void 0,location:n,type:vS(e.type),sequence:Mt(e.sequence)??Mt(e.buttonsequencepriority)??0,hidden:Ao(e.hidden),disabled:Ao(e.isdisabled),origin:CS(e.origin),managed:Ao(e.ismanaged),fontIcon:Me(e.fonticon),iconWebResourceId:nn(e._iconwebresourceid_value)??void 0,iconWebResourceName:Me(e[`_iconwebresourceid_value${li}`]),parentId:nn(e._parentappactionid_value),groupTitle:Me(e.grouptitle),groupTitleHidden:Ao(e.isgrouptitlehidden),action:SS(e.onclickeventtype),jsFunctionName:Me(e.onclickeventjavascriptfunctionname),jsParameters:Me(e.onclickeventjavascriptparameters),jsWebResourceId:nn(e._onclickeventjavascriptwebresourceid_value)??void 0,jsWebResourceName:Me(e[`_onclickeventjavascriptwebresourceid_value${li}`]),onSelectFormula:bl(e,"onclickeventformula"),visibility:wS(e.visibilitytype),visibilityFormula:bl(e,"visibilityformula"),classicRules:IS(e[Iu])}}function RS(e){const t=new Map;for(const n of e){const o=jS(n);o&&!t.has(o.id)&&t.set(o.id,o)}return[...t.values()]}function $S(e){switch(e){case"HomepageGrid":return[Kn.MainGrid];case"SubGrid":return[Kn.SubGrid,Kn.AssociatedGrid];case"Form":return[Kn.Form];case"Application":return[Kn.GlobalHeader]}}function TS(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 NS(e,t){return t==="all"||e.appModuleId===null||e.appModuleId===t.toLowerCase()}function kS(e,t){const n=new Set($S(t.location));return e.filter(o=>n.has(o.location)&&NS(o,t.appFilter)&&TS(o,t.table))}const Qi=(e,t)=>e.sequence-t.sequence||e.label.localeCompare(t.label)||e.id.localeCompare(t.id);function ju(e){const t=new Set(e.map(l=>l.id)),n=new Map,o=[];for(const l of e)if(l.parentId&&l.parentId!==l.id&&t.has(l.parentId)){const r=n.get(l.parentId)??[];r.push(l),n.set(l.parentId,r)}else o.push(l);const s=new Set,i=l=>{s.add(l.id);const r=(n.get(l.id)??[]).filter(c=>!s.has(c.id)).sort(Qi);return{command:l,children:r.map(i)}};return o.sort(Qi).map(i)}function Ru(e){return e.flatMap(t=>[t.command,...Ru(t.children)])}const $u=/\{!EntityLogicalName\}/gi,AS=/(?:![A-Za-z0-9_]+)*!\d+$/;function OS(e,t){if(e.origin==="default")return[];const n=[],o=s=>{s.includes(".")&&!n.includes(s)&&n.push(s)};for(const s of[e.uniqueName,e.name]){if(!s)continue;const i=s.trim().replace($u,t).replace(AS,""),l=i.indexOf("_"),r=i.indexOf(".");l>0&&(r===-1||l<r)&&o(i.slice(l+1)),o(i)}return n}function ea(e,t){return e.replace($u,t).toLowerCase()}function yl(e,t){const n=ea(e,t).split(".");return n.length<4||n[0]!=="mscrm"?null:[n[0],n[1],"*",...n.slice(3)].join(".")}function xl(e,t,n,o={}){const s=new Map,i=new Map;for(const r of t){const c=ea(r,n);s.has(c)||s.set(c,r);const d=yl(r,n);d&&!i.has(d)&&i.set(d,r)}const l=new Map;for(const r of e){if(r.disabled&&!o.includeDisabled)continue;const c=OS(r,n),d=c.map(p=>s.get(ea(p,n))).find(Boolean)??c.map(p=>yl(p,n)).map(p=>p?i.get(p):void 0).find(Boolean);if(!d)continue;const u=l.get(d)??[];u.push({buttonId:d,command:r,effect:r.hidden?"hidden":"replaced"}),l.set(d,u)}return l}function MS(e,t,n){const o=l=>l.toLowerCase(),s=`mscrm.${o(t)}.${o(n)}.maintab`,i=e.find(l=>l.id==="Mscrm.GlobalTab")?.id;return t==="Application"&&i?i:e.find(l=>o(l.id)===s)?.id??e.find(l=>/maintab$/i.test(l.id)&&!/\.allentities\./i.test(l.id))?.id??i??e[0]?.id}function Tu(e){return(e.menu?.sections??[]).flatMap(t=>t.controls.flatMap(n=>[n,...Tu(n)]))}function DS(e){const{commands:t,tabs:n,location:o,entityLogicalName:s}=e,i=n.flatMap(x=>x.groups.flatMap(v=>v.buttons)),l=[...i,...i.flatMap(Tu)].map(x=>x.id),r=new Map(t.map(x=>[x.id,x])),c=new Set([...xl(t,l,s,{includeDisabled:!0}).values()].flat().map(x=>x.command.id)),d=new Map,u=(x,v=new Set)=>{const C=d.get(x.id);if(C!==void 0)return C;let $=x.parentId?r.get(x.parentId):void 0;for(const j=new Set;$?.type==="group"&&!c.has($.id)&&!j.has($.id);)j.add($.id),$=$.parentId?r.get($.parentId):void 0;const A=c.has(x.id)&&(!$||!v.has($.id)&&u($,v.add(x.id)));return d.set(x.id,A),A},m=(x=>{for(const[v,C]of x){const $=C.filter(A=>u(A.command));$.length>0?x.set(v,$):x.delete(v)}return x})(xl(t,l,s)),g=new Set([...m.values()].flat().map(x=>x.command.id)),b=x=>{const v=new Set;for(let C=x.parentId;C&&!v.has(C);C=r.get(C)?.parentId??null){v.add(C);const $=r.get(C);if($&&u($))return C}},f=new Map,y=[];for(const x of t){const v=b(x);if(!v){u(x)||y.push(x);continue}if(g.has(x.id))continue;const C=f.get(v)??[];C.push(x),f.set(v,C)}for(const x of m.values())for(const v of x){const C=f.get(v.command.id);C&&(v.items=[...C].sort(Qi))}return{commandBarTabId:MS(n,o,s),nodes:ju(y),overrides:m,unmatchedMigrated:y.filter(x=>x.origin!=="default")}}function Nu(e,t){const n=new Map,o=[];for(const s of t){const i=e.find(r=>r.sequence>s.command.sequence);if(!i){o.push(s);continue}const l=n.get(i.id)??[];l.push(s),n.set(i.id,l)}return{before:n,trailing:o}}function vl(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 ES(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 BS(e,t,n){const o=new Map(t.map(i=>[i.id.toLowerCase(),i])),s=new Map;for(const i of n??[]){const l=o.get(i.toLowerCase());l&&s.set(l.id.toLowerCase(),l)}if(n)return[...s.values()].sort((i,l)=>i.name.localeCompare(l.name)||i.id.localeCompare(l.id));for(const i of e)!i.appModuleId||s.has(i.appModuleId)||s.set(i.appModuleId,o.get(i.appModuleId)??{id:i.appModuleId,name:i.appName??i.appModuleId});return[...s.values()].sort((i,l)=>i.name.localeCompare(l.name)||i.id.localeCompare(l.id))}function ho(e,t){return e.appModuleId===null?"All apps":t?.get(e.appModuleId)??e.appName??e.appModuleId}function tr(e,t){const n=ho(e.command,t),o=e.command.appModuleId===null?"in all apps":`in ${n}`,s=e.effect==="hidden"?`Hidden by modern command ${e.command.label} ${o}`:`Rendered as modern command ${e.command.label} ${o} (migrated)`;return e.items?.length?`${s}; its menu also has ${e.items.map(i=>i.label).join(", ")}`:s}function ku(e,t){if(!e?.length)return"";const n=e.find(o=>o.effect==="hidden");return n?` — ${tr(n,t).replace(/^Hidden/,"hidden")}`:" — modern (migrated)"}const LS={button:"Command",dropdown:"Dropdown",split:"Split button",group:"Group"},zS={default:"Command designer",migrated:"Migrated from classic",enhancedMigrated:"Enhanced migrated from classic"};function Au(e,t){const n=[{label:"App",value:ho(e,t)},{label:"Location",value:`${yS[e.location]??`Location ${e.location}`}${e.scope==="all"?" (all tables)":""}`},{label:"Type",value:LS[e.type]},{label:"Order",value:String(e.sequence)},{label:"Origin",value:zS[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:vl(e.visibilityFormula)??"Power Fx formula"});else if(e.visibility==="classicRules"){const o=e.classicRules.filter(s=>s.kind==="display").map(s=>s.name);n.push({label:"Visibility",value:o.length?`Classic rules: ${o.join(", ")}`:"Classic rules"})}if(e.action==="formula")n.push({label:"OnSelect (Power Fx)",value:vl(e.onSelectFormula)??"Power Fx formula"});else if(e.action==="javascript"){const o=e.jsWebResourceName??e.jsWebResourceId,s=e.jsFunctionName??"(no function)";n.push({label:"Action (JavaScript)",value:o?`${s} in ${o}`:s}),e.jsParameters&&n.push({label:"Parameters",value:e.jsParameters})}return n}function PS(){return window.dataverseAPI}const go=e=>e instanceof Error?e.message:String(e);async function cs(e){const t=[],n=new Set;let o=e;for(;o&&!n.has(o);){n.add(o);const s=await PS().queryData(o);t.push(...s.value??[]);const i=s["@odata.nextLink"];o=i?i.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}function Ou(e){return/\b40[13]\b|0x80040220|prvRead|privilege|unauthori[sz]ed|forbidden|not have permission/i.test(go(e))}const Mu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sl(e,t){const n=[`contextvalue eq '${e.logicalName.replace(/'/g,"''")}'`];e.metadataId&&Mu.test(e.metadataId)&&n.push(`_contextentity_value eq ${e.metadataId}`);const o=`statecode eq 0 and (context eq 0 or ${n.join(" or ")}) and (location eq 0 or location eq 1 or location eq 2 or location eq 3 or location eq 5)`,s=t?`&$expand=${Iu}($select=appactionruleid,name,uniquename,type)`:"";return`appactions?$select=${xS.join(",")}&$filter=${o}${s}`}async function FS(e){const t=ce.getState();let n;try{n=await cs(Sl(e,!0))}catch(o){if(Ou(o))throw o;t.logInfo("dataverse",`Modern commands: classic rules couldn't be expanded (${go(o)}); retrying without them.`),n=await cs(Sl(e,!1))}return RS(n)}async function _S(e){const t=ce.getState(),n="appmodules?$select=appmoduleid,appmoduleidunique,name,uniquename",o=e.metadataId&&Mu.test(e.metadataId)?`appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 1 and objectid eq ${e.metadataId}`:null,[s,i]=await Promise.all([cs(n),o?cs(o).catch(d=>(t.logInfo("dataverse",`Modern commands: couldn't resolve which apps contain ${e.logicalName} (${go(d)}).`),null)):Promise.resolve(null)]),l=s,r=l.filter(d=>!!d.appmoduleid).map(d=>({id:String(d.appmoduleid).toLowerCase(),name:d.name?.trim()||d.uniquename||String(d.appmoduleid),uniqueName:d.uniquename}));let c=null;if(i){const d=new Set(i.map(u=>u._appmoduleidunique_value).filter(u=>typeof u=="string").map(u=>u.toLowerCase()));c=new Set(l.filter(u=>u.appmoduleid&&u.appmoduleidunique&&d.has(u.appmoduleidunique.toLowerCase())).map(u=>String(u.appmoduleid).toLowerCase()))}return{apps:r,containingAppIds:c}}async function qS(e){const t=ce.getState(),[n,o]=await Promise.allSettled([FS(e),_S(e)]);if(n.status==="rejected"){const r=go(n.reason);return t.logWarn("dataverse",Ou(n.reason)?`No permission to read modern commands (appaction) for ${e.logicalName}; the canvas shows classic commands only. (${r})`:`Modern commands unavailable for ${e.logicalName}: ${r}`),{commands:[],apps:[],error:r}}o.status==="rejected"&&t.logInfo("dataverse",`Modern commands: app list unavailable (${go(o.reason)}); showing app ids from the commands.`);const{apps:s,containingAppIds:i}=o.status==="fulfilled"?o.value:{apps:[],containingAppIds:null},l=ES(n.value,i);return t.logInfo("dataverse",`Loaded ${l.length} modern command${l.length===1?"":"s"} for ${e.logicalName}.`),{commands:l,apps:BS(l,s,i)}}function WS(){const e=ae(n=>n.activeEntity?.logicalName),t=ae(n=>n.activeEntity?.metadataId);E.useEffect(()=>{const n=we.getState();if(!e||typeof window.dataverseAPI>"u"){n.reset();return}const o=n.beginLoad(e);qS({logicalName:e,metadataId:t}).then(s=>we.getState().finishLoad(o,s))},[e,t])}function zn(){const e=we(n=>n.apps),t=we(n=>n.commands);return E.useMemo(()=>{const n=new Map;for(const o of t)o.appModuleId&&o.appName&&n.set(o.appModuleId,o.appName);for(const o of e)n.set(o.id,o.name);return n},[e,t])}function Du(e){const t=we(i=>i.commands),n=we(i=>i.appFilter),o=ae(i=>i.activeEntity?.logicalName),s=ae(i=>i.activeEntity?.metadataId);return E.useMemo(()=>o?kS(t,{location:e,appFilter:n,table:{logicalName:o,metadataId:s}}):[],[t,n,e,o,s])}const ta=new Set;function HS(){ta.clear()}function nr(e){const t=Du(e),n=ae(u=>u.activeEntity?.logicalName)??"",o=M(u=>u.ribbons[e]?.tabs),s=M(u=>u.ribbons[e]?.entityLogicalName??""),i=we(u=>u.status==="loaded"?u.tableLogicalName:null),l=(o?.length??0)>0&&(e==="Application"||s.toLowerCase()===n.toLowerCase()),r=E.useMemo(()=>DS({commands:t,tabs:l?o??[]:[],location:e,entityLogicalName:n}),[t,o,l,e,n]),d=!!n&&i===n&&l?r.unmatchedMigrated.map(u=>u.uniqueName).join(", "):"";return E.useEffect(()=>{const u=`${n}|${e}|${d}`;!d||ta.has(u)||(ta.add(u),ce.getState().logInfo("ribbon",`Migrated modern commands without a classic control in ${n} ${e}: ${d}`))},[d,n,e]),r}function Ms(e,t){const n=nr(e);return E.useMemo(()=>{const o=t.groups.flatMap(i=>i.buttons.map(l=>({id:l.id,sequence:l.sequence}))),s=t.id===n.commandBarTabId?n.nodes:[];return{nodes:s,placement:Nu(o,s),overrides:n.overrides}},[n,t])}function GS(e,t){const{overrides:n}=nr(e);return t&&n.get(t)||US}const US=[];function VS(){const e=we(s=>s.selectedCommandId),t=Y(s=>s.selectedButtonId),n=Y(s=>s.location),o=Du(n);return E.useMemo(()=>{if(!e||t)return null;const s=o.find(l=>l.id===e);if(!s)return null;let i;for(const l of ju(o))if(i=Eu(l,e),i)break;return{command:s,children:i?Ru(i.children):[]}},[e,t,o])}function Eu(e,t){if(e.command.id===t)return e;for(const n of e.children){const o=Eu(n,t);if(o)return o}}function XS(e,t,n){const o=ft(e.groups).flatMap(r=>ft(r.buttons).map(c=>{const d=n.get(c.id)??[],u=c.hidden||d.length>0&&d.every(g=>g.effect==="hidden"),p=d.find(g=>g.effect==="replaced")?.command;return{item:{kind:"classic",id:c.id,button:c,groupId:r.id,replacedBy:p},hidden:u}})),s=t.filter(r=>!r.command.hidden&&!r.command.disabled),i=Nu(o.map(r=>({id:r.item.id,sequence:r.item.button.sequence})),s),l=r=>({kind:"modern",id:`modern:${r.command.id}`,command:r.command});return[...o.flatMap(({item:r,hidden:c})=>[...(i.before.get(r.id)??[]).map(l),...c?[]:[r]]),...i.trailing.map(l)]}const Bu=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,marginBottom:h.spacingVerticalM},header:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:h.spacingHorizontalS,minWidth:0},muted:{color:h.colorNeutralForeground3},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},bar:{display:"flex",alignItems:"center",gap:"2px",minWidth:0,height:"40px",padding:`0 ${h.spacingHorizontalXS}`,overflow:"hidden",backgroundColor:h.colorNeutralBackground1,border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,boxShadow:h.shadow2},command:{flexShrink:0,fontWeight:h.fontWeightRegular,maxWidth:"220px"},selected:{backgroundColor:h.colorSubtleBackgroundSelected,outline:`1px solid ${h.colorBrandStroke1}`},empty:{padding:`0 ${h.spacingHorizontalS}`}});function KS({tab:e,location:t}){const n=Bu(),o=De(),s=M(v=>v.locLabels),i=M(v=>v.baseLanguageCode),l=Y(v=>v.selectedButtonId),r=Y(v=>v.selectButtonInContext),c=we(v=>v.selectedCommandId),d=we(v=>v.selectCommand),u=Ms(t,e),p=Wh({axis:"horizontal",memorizeCurrent:!0}),m=XS(e,u.nodes,u.overrides),g=o(e.label,s,i,e.source?.titleToken)||e.id,b=v=>v.kind==="modern"?v.command.label||v.command.uniqueName:v.replacedBy?v.replacedBy.label||v.replacedBy.uniqueName:o(v.button.label,s,void 0,v.button.source?.labelToken)||v.button.id,f=v=>v.kind==="classic"?v.id===l||!l&&!!v.replacedBy&&v.replacedBy.id===c:!l&&v.command.id===c,y=v=>v.kind==="classic"?r(t,e.id,v.groupId,v.button.id):d(v.command.id),x=xo(e.id);return a.jsxs("section",{className:n.root,"aria-label":"How users see it",children:[a.jsxs("div",{className:n.header,children:[a.jsx(V,{weight:"semibold",size:300,children:"How users see it"}),a.jsxs(V,{size:200,className:Ie(n.muted,n.ellipsis),children:[g," · ",m.length," command",m.length===1?"":"s"]}),a.jsx(xe,{appearance:"outline",color:"informative",size:"medium",children:"Preview: rules not applied"}),a.jsx(Et,{size:"small",info:"The tab's commands in the order Unified Interface lists them, without the ones hidden by your customizations or replaced by a modern command. Display and enable rules aren't evaluated, so some of these may not show, or be disabled, for users. What doesn't fit goes into the ⋮ menu.",infoButton:{"aria-label":"About this preview"}})]}),x?a.jsx(V,{size:200,className:Ie(n.bar,n.empty,n.muted),children:"Unified Interface doesn't show this tab's commands."}):m.length===0?a.jsx(V,{size:200,className:Ie(n.bar,n.empty,n.muted),children:"No commands on this tab are shown."}):a.jsx(ma,{padding:40,children:a.jsxs("div",{className:n.bar,role:"toolbar",...p,"aria-label":`Command bar preview: ${g}`,children:[m.map(v=>a.jsx(Ft,{id:v.id,priority:f(v)?2:1,children:a.jsx(YS,{item:v,text:b(v),selected:f(v),onChoose:()=>y(v)})},v.id)),a.jsx(JS,{items:m,textOf:b,isSelected:f,onChoose:y})]})})]})}const YS=E.forwardRef(function({item:t,text:n,selected:o,onChoose:s},i){const l=Bu(),r=t.kind==="classic"&&!!t.button.menu;return a.jsxs(K,{ref:i,appearance:"subtle",size:"small",className:Ie(l.command,o&&l.selected),"aria-current":o||void 0,"data-users-bar":t.id,"aria-description":t.kind==="modern"?"Modern command":t.replacedBy?"Modern command, migrated from this button":t.id,icon:t.kind==="classic"?a.jsx(vt,{button:t.button,size:16}):void 0,onClick:s,children:[a.jsx("span",{className:l.ellipsis,children:n}),r&&a.jsx(it,{fontSize:12,"aria-label":"Has a menu"})]})});function JS({items:e,textOf:t,isSelected:n,onChoose:o}){const{ref:s,isOverflowing:i,overflowCount:l}=ba();return i?a.jsxs(Ke,{children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(K,{ref:s,appearance:"subtle",size:"small",icon:a.jsx(yc,{}),"aria-label":`${l} more commands`,children:l})}),a.jsx(Je,{children:a.jsx(Ze,{children:e.map(r=>a.jsx(ZS,{item:r,text:t(r),selected:n(r),onChoose:()=>o(r)},r.id))})})]}):null}function ZS({item:e,text:t,selected:n,onChoose:o}){return ya(e.id)?null:a.jsx(fe,{icon:e.kind==="classic"?a.jsx(vt,{button:e.button,size:16}):void 0,secondaryContent:n?"Selected":e.kind==="modern"?"Modern":void 0,onClick:o,children:t})}function Lu(e,t,n=`_copy_${Date.now()}`){return{...Jo(e,`${e.id}${n}`,t),label:e.label??"New Button",kind:e.kind??"button",sequence:void 0,templateAlias:e.templateAlias??"o1",commandId:e.commandId??"",hidden:!1,oob:!1,custom:!0,managed:!1}}const zu=me({chip:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,height:"32px",padding:`0 ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:`1px dashed ${h.colorPaletteBerryBorderActive}`,backgroundColor:h.colorPaletteBerryBackground1,color:h.colorNeutralForeground1,cursor:"default",whiteSpace:"nowrap",flexShrink:0,userSelect:"none",":hover":{backgroundColor:h.colorPaletteBerryBackground2},":focus-visible":{outline:`2px solid ${h.colorBrandStroke1}`,outlineOffset:"2px"}},selected:{border:`1px solid ${h.colorPaletteBerryForeground2}`,backgroundColor:h.colorPaletteBerryBackground2},muted:{opacity:.5},hidden:{textDecoration:"line-through"},tooltip:{display:"flex",flexDirection:"column",gap:"2px",maxWidth:"360px"},tooltipRow:{fontSize:h.fontSizeBase200,overflowWrap:"anywhere"}});function Pu({node:e,appNames:t}){const n=zu(),o=e.command;return a.jsxs("div",{className:n.tooltip,children:[a.jsx(V,{weight:"semibold",children:o.label}),a.jsx(V,{className:n.tooltipRow,children:"Modern command — read-only in CBS; edit it in the command designer."}),Au(o,t).map(s=>a.jsxs(V,{className:n.tooltipRow,children:[a.jsxs("b",{children:[s.label,":"]})," ",s.value]},s.label)),e.children.length>0&&a.jsxs(V,{className:n.tooltipRow,children:[a.jsx("b",{children:"Items:"})," ",e.children.map(s=>s.command.label).join(", ")]})]})}function QS({node:e,appNames:t,showApp:n,onDragRejected:o}){const s=zu(),i=e.command,l=we(b=>b.selectedCommandId),r=we(b=>b.selectCommand),c=Y(b=>b.selectedButtonId),d=l===i.id&&!c,u=i.type==="dropdown"||i.type==="split"||e.children.length>0,p=i.fontIcon&&!i.fontIcon.startsWith("$")?i.fontIcon:"apps_add_in",m=`${i.hidden?" — hidden":""}${i.disabled?" — disabled":""}`,g=b=>{b.preventDefault(),b.stopPropagation(),b.dataTransfer.dropEffect="none",o?.()};return a.jsx(pe,{content:a.jsx(Pu,{node:e,appNames:t}),relationship:"description",children:a.jsxs("button",{type:"button",draggable:!1,className:Ie(s.chip,d&&s.selected,(i.hidden||i.disabled)&&s.muted,i.hidden&&s.hidden),"aria-pressed":d,"aria-label":`${i.label} — modern command (read-only), ${ho(i,t)}${m}`,onClick:()=>r(i.id),onDragStart:b=>b.preventDefault(),onDragOver:g,onDrop:g,onContextMenu:b=>{b.preventDefault(),r(i.id)},children:[a.jsx(Za,{name:p,size:16}),a.jsx(V,{size:200,children:i.label}),u&&a.jsx(it,{fontSize:12,"aria-hidden":!0}),i.hidden&&a.jsx(Bt,{fontSize:12,"aria-hidden":!0}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",icon:a.jsx(un,{}),children:"Modern"}),n&&a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",color:"informative",children:ho(i,t)})]})})}function or({overrides:e,appNames:t}){if(!e?.length)return null;const n=e.some(s=>s.effect==="hidden"),o=e.map(s=>tr(s,t)).join(`
|
|
132
|
+
`);return a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:n?"warning":"important",title:o,"aria-label":o,children:n?"Hidden by modern":"Modern (migrated)"})}const Oo="application/x-rw-btn",wl="application/x-rw-se",ew=me({root:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingHorizontalS} 0`,minHeight:"48px"},scrollRow:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,flex:1,minWidth:0,overflowX:"auto",overflowY:"hidden",paddingBottom:h.spacingHorizontalXS},button:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,height:"32px",padding:`0 ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:"1px solid transparent",cursor:"pointer",backgroundColor:"transparent",color:h.colorNeutralForeground1,whiteSpace:"nowrap",flexShrink:0,position:"relative",userSelect:"none",":hover":{backgroundColor:h.colorNeutralBackground3,border:`1px solid ${h.colorNeutralStroke1}`},":focus-visible":{outline:`2px solid ${h.colorBrandStroke1}`,outlineOffset:"2px"}},buttonSelected:{backgroundColor:h.colorBrandBackground2,border:`1px solid ${h.colorBrandStroke1}`},buttonHidden:{opacity:.4,textDecoration:"line-through"},buttonCustom:{border:`1px solid ${h.colorBrandStroke2}`},lockIcon:{position:"absolute",top:"4px",left:"4px",color:h.colorNeutralForeground3,pointerEvents:"none"},dropLine:{width:"2px",height:"24px",backgroundColor:h.colorBrandStroke1,borderRadius:"2px",flexShrink:0},overflowBtn:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,height:"32px",padding:`0 ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground2,cursor:"pointer",color:h.colorNeutralForeground3,flexShrink:0},trailingControls:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,flexShrink:0,paddingLeft:h.spacingHorizontalS,borderLeft:`1px solid ${h.colorNeutralStroke2}`,marginLeft:h.spacingHorizontalXS}});function tw({tab:e,location:t}){const n=ew(),o=Y(w=>w.selectedButtonId),s=Y(w=>w.selectButtonInContext),i=M(w=>w.moveButton),l=M(w=>w.locLabels),r=De(),c=M(w=>w.baseLanguageCode),d=(w,D,F)=>r(w,l,c,F)||D,u=Z(w=>w.openNewButton),[p,m]=E.useState(null),[g,b]=E.useState(null),[f,y]=E.useState(null),x=Ms(t,e),v=zn(),C=we(w=>w.appFilter==="all"),$=w=>a.jsx(QS,{node:w,appNames:v,showApp:C,onDragRejected:()=>m(null)},w.command.id),A=w=>ku(x.overrides.get(w.id),v),j=w=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&w.oob&&!w.custom,T=w=>dt(w.kind),R=w=>T(w)?` (${xt[w.kind]}, read-only)`:"",I=e.groups.flatMap(w=>w.buttons.map(D=>({button:D,groupId:w.id})));function N(w,D,F){w.dataTransfer.setData(Oo,JSON.stringify({groupId:D,buttonId:F})),w.dataTransfer.effectAllowed="move",b(F)}function B(){b(null),m(null)}function O(w,D){const F=Array.from(w.dataTransfer.types??[]);!F.includes(Oo)&&!F.includes(wl)||(w.preventDefault(),w.dataTransfer.dropEffect=F.includes(Oo)?"move":"copy",m({beforeButtonId:D}))}const S=M(w=>w.createButton);function k(w,D,F){w.preventDefault(),w.stopPropagation();const X=w.dataTransfer.getData(Oo);if(X){try{const re=JSON.parse(X);if(re?.buttonId){const le=i({groupId:re.groupId,buttonId:re.buttonId,tabId:e.id,location:t},{groupId:D,beforeButtonId:F??void 0,tabId:e.id,location:t});le&&le!==re.buttonId&&s(t,e.id,D,le)}}catch{}m(null),b(null);return}const ne=w.dataTransfer.getData(wl);if(ne){try{const le=JSON.parse(ne)?.button;le&&S({location:t,tabId:e.id,groupId:D,button:Lu(le,io(M.getState()))})}catch{}m(null),b(null);return}m(null),b(null)}return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:n.root,children:[a.jsxs("div",{className:n.scrollRow,onDragOver:w=>{w.preventDefault()},onDrop:w=>k(w,e.groups[0]?.id??"",null),children:[I.map(({button:w,groupId:D})=>a.jsxs(tt.Fragment,{children:[x.placement.before.get(w.id)?.map($),p?.beforeButtonId===w.id&&a.jsx("div",{className:n.dropLine,"aria-hidden":!0}),a.jsx(pe,{content:j(w)?"OOB global command bar buttons cannot be customized.":`${r(w.label,l,void 0,w.source?.labelToken)}${R(w)}${w.hidden?" — hidden":""}${A(w)}`,relationship:"label",children:a.jsxs("button",{type:"button",className:[n.button,o===w.id?n.buttonSelected:"",w.hidden?n.buttonHidden:"",w.custom?n.buttonCustom:""].filter(Boolean).join(" "),"aria-current":o===w.id?"true":void 0,"aria-label":`${r(w.label,l,void 0,w.source?.labelToken)}${R(w)}${w.hidden?" — hidden":""}${A(w)}`,onClick:()=>s(t,e.id,D,w.id),onContextMenu:F=>{F.preventDefault(),s(t,e.id,D,w.id),y({button:w,groupId:D,anchor:F.currentTarget})},draggable:!w.managed&&!j(w),onDragStart:F=>N(F,D,w.id),onDragEnd:B,onDragOver:F=>O(F,w.id),onDrop:F=>k(F,D,w.id),style:{opacity:g===w.id?.3:void 0},children:[a.jsx(vt,{button:w,size:16}),a.jsx(V,{size:200,children:r(w.label,l,void 0,w.source?.labelToken)}),T(w)&&a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",color:"informative",children:xt[w.kind]}),w.menu&&a.jsx(it,{fontSize:12,"aria-label":"Has a menu"}),w.hidden&&a.jsx(Bt,{fontSize:12,"aria-hidden":!0}),w.custom&&a.jsx(xe,{style:{flexShrink:0},size:"medium",color:"brand",appearance:"tint","aria-label":"Custom",children:"NEW"}),a.jsx(or,{overrides:x.overrides.get(w.id),appNames:v}),j(w)&&a.jsx("span",{className:n.lockIcon,title:"OOB global command bar buttons cannot be customized.",children:a.jsx(un,{fontSize:12})})]})})]},w.id)),x.placement.trailing.map($)]}),a.jsx("div",{className:n.trailingControls,children:(()=>{const w=e.groups[0];return w?a.jsx(pe,{content:`Add a new button to "${d(w.label,w.id,w.source?.titleToken)}"`,relationship:"label",children:a.jsxs("button",{type:"button",className:n.overflowBtn,onClick:()=>u(w.id),"aria-label":"Add a new button",children:[a.jsx(ke,{fontSize:14})," Add"]})}):a.jsx(pe,{content:'No groups in this tab yet. Switch to "Classic ribbon" view to add a group first.',relationship:"label",children:a.jsxs("button",{type:"button",className:n.overflowBtn,disabled:!0,children:[a.jsx(ke,{fontSize:14})," Add"]})})})()})]}),a.jsx(wo,{location:t,tab:e,target:f,onClose:()=>y(null)})]})}const nw=me({root:{marginTop:h.spacingVerticalM,display:"flex",flexDirection:"column",gap:h.spacingVerticalXS},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS},row:{cursor:"pointer",backgroundColor:h.colorPaletteBerryBackground1,":hover":{backgroundColor:h.colorPaletteBerryBackground2}},rowSelected:{backgroundColor:h.colorPaletteBerryBackground2,outline:`1px solid ${h.colorPaletteBerryBorderActive}`},hidden:{opacity:.55,textDecoration:"line-through"},mono:{fontFamily:h.fontFamilyMonospace,color:h.colorNeutralForeground3},table:{tableLayout:"fixed",width:"100%"},note:{color:h.colorNeutralForeground3,minWidth:0}}),ow={button:"command",dropdown:"dropdown",split:"split",group:"group"};function sw({tab:e,location:t}){const n=nw(),{nodes:o}=Ms(t,e),s=zn(),i=we(m=>m.selectedCommandId),l=we(m=>m.selectCommand),r=Y(m=>m.selectedButtonId),[c,d]=E.useState(!0);if(o.length===0)return null;const u=[],p=(m,g)=>{for(const b of m)u.push({node:b,depth:g}),p(b.children,g+1)};return p(o,0),a.jsxs("section",{className:n.root,"aria-label":"Modern commands",children:[a.jsxs("div",{className:n.header,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:c?a.jsx(it,{}):a.jsx(Hh,{}),"aria-expanded":c,onClick:()=>d(!c),children:a.jsxs(V,{weight:"semibold",size:200,children:["Modern commands (",u.length,")"]})}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",children:"read-only"}),a.jsx(V,{size:200,truncate:!0,wrap:!1,className:n.note,children:"Built with the command designer (appaction). Edit them there."})]}),c&&a.jsxs(Gh,{size:"small",className:n.table,"aria-label":"Modern commands (read-only)",children:[a.jsx(Uh,{children:a.jsxs(Sr,{children:[a.jsx(Fn,{style:{width:52},children:"#"}),a.jsx(Fn,{style:{width:"36%"},children:"Label"}),a.jsx(Fn,{style:{width:"20%"},children:"App"}),a.jsx(Fn,{style:{width:96},children:"Type"}),a.jsx(Fn,{children:"Unique name"})]})}),a.jsx(Vh,{children:u.map(({node:m,depth:g})=>{const b=m.command,f=i===b.id&&!r;return a.jsxs(Sr,{className:Ie(n.row,f&&n.rowSelected),"aria-selected":f,tabIndex:0,onClick:()=>l(b.id),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),l(b.id))},children:[a.jsx(_n,{children:b.sequence}),a.jsx(_n,{children:a.jsx(pe,{content:a.jsx(Pu,{node:m,appNames:s}),relationship:"description",children:a.jsxs("span",{className:b.hidden||b.disabled?n.hidden:void 0,style:{paddingLeft:g*16,display:"flex",gap:4,alignItems:"center",minWidth:0,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:[a.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:b.label}),b.hidden&&a.jsx(Bt,{fontSize:12,"aria-label":"hidden"}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",children:"Modern"})]})})}),a.jsx(_n,{children:a.jsx(lo,{truncate:!0,children:ho(b,s)})}),a.jsx(_n,{children:a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",children:ow[b.type]})}),a.jsx(_n,{children:a.jsx(lo,{truncate:!0,className:n.mono,children:a.jsx("span",{title:b.uniqueName,children:b.uniqueName})})})]},b.id)})})]})]})}const iw=me({root:{width:"100%",minWidth:0},toolbar:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,padding:`${h.spacingVerticalXS} 0`},search:{flex:1,minWidth:0,maxWidth:"480px"},muted:{color:h.colorNeutralForeground3},grid:{width:"100%",minWidth:0},header:{position:"sticky",top:`calc(-1 * ${h.spacingHorizontalM})`,zIndex:1,backgroundColor:h.colorNeutralBackground1},row:{cursor:"pointer"},rowSelected:{backgroundColor:h.colorSubtleBackgroundSelected,":hover":{backgroundColor:h.colorSubtleBackgroundSelected}},hidden:{color:h.colorNeutralForeground3},mono:{fontFamily:h.fontFamilyMonospace,color:h.colorNeutralForeground3},badge:{marginLeft:h.spacingHorizontalXS,flexShrink:0},labelMain:{display:"flex",alignItems:"center",minWidth:0,overflow:"hidden"},shrink:{minWidth:0},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}),Cl={id:"ID",command:"Command"},Il=e=>!!e.target.closest('button, input, [role="switch"], [role="menuitem"]');function aw({tab:e,location:t}){const n=iw(),o=Y(S=>S.selectedButtonId),s=Y(S=>S.selectButtonInContext),i=M(S=>S.setButtonProp),l=M(S=>S.locLabels),r=M(S=>S.baseLanguageCode),c=De(),{overrides:d}=Ms(t,e),u=zn(),[p,m]=E.useState(""),[g,b]=E.useState([]),[f,y]=E.useState(null),[x,v]=E.useState(void 0),C=xc({tabBehavior:"unlimited",ignoreDefaultKeydown:{Enter:!0}}),$=E.useMemo(()=>{let S=0;return ft(e.groups).flatMap(k=>ft(k.buttons).map(w=>({button:w,label:c(w.label,l,void 0,w.source?.labelToken)||w.id,groupId:k.id,groupLabel:c(k.label,l,r,k.source?.titleToken)||k.id,order:S++})))},[e,c,l,r]),A=p.toLowerCase().trim(),j=A?$.filter(({button:S,label:k,groupLabel:w})=>S.id.toLowerCase().includes(A)||k.toLowerCase().includes(A)||S.label.toLowerCase().includes(A)||(S.commandId??"").toLowerCase().includes(A)||w.toLowerCase().includes(A)):$,T=S=>s(t,e.id,S.groupId,S.button.id),R=(S,k)=>y({button:S.button,groupId:S.groupId,anchor:k}),I={seq:{defaultWidth:52,minWidth:44,idealWidth:52},label:{defaultWidth:220,minWidth:140,idealWidth:220},kind:{defaultWidth:110,minWidth:80,idealWidth:110},group:{defaultWidth:150,minWidth:90,idealWidth:150},visible:{defaultWidth:72,minWidth:64,idealWidth:72},id:{defaultWidth:240,minWidth:140,idealWidth:240},command:{defaultWidth:220,minWidth:140,idealWidth:220},actions:{defaultWidth:44,minWidth:44,idealWidth:44}},N=S=>a.jsx(V,{size:200,weight:"semibold",children:S}),B=(S,k)=>a.jsx(lo,{truncate:!0,className:k,title:S,children:S}),O=[qe({columnId:"seq",compare:(S,k)=>S.button.sequence-k.button.sequence||S.order-k.order,renderHeaderCell:()=>N("#"),renderCell:({button:S})=>a.jsx(V,{size:200,children:S.sequence})}),qe({columnId:"label",compare:(S,k)=>S.label.localeCompare(k.label)||S.order-k.order,renderHeaderCell:()=>N("Label"),renderCell:({button:S,label:k})=>a.jsx(pe,{content:`${k} (${S.id})`,relationship:"description",children:a.jsxs(lo,{media:a.jsx(vt,{button:S,size:16}),className:Ie(n.shrink,S.hidden&&n.hidden),content:{className:n.shrink},main:{className:n.labelMain},children:[a.jsx("span",{className:n.ellipsis,children:k}),a.jsx("span",{className:n.badge,children:a.jsx(or,{overrides:d.get(S.id),appNames:u})})]})})}),qe({columnId:"kind",compare:(S,k)=>xt[S.button.kind].localeCompare(xt[k.button.kind])||S.order-k.order,renderHeaderCell:()=>N("Kind"),renderCell:({button:S})=>B(xt[S.kind]??S.kind)}),qe({columnId:"group",compare:(S,k)=>S.groupLabel.localeCompare(k.groupLabel)||S.order-k.order,renderHeaderCell:()=>N("Group"),renderCell:({groupLabel:S})=>B(S)}),...g.includes("id")?[qe({columnId:"id",compare:(S,k)=>S.button.id.localeCompare(k.button.id),renderHeaderCell:()=>N("ID"),renderCell:({button:S})=>B(S.id,n.mono)})]:[],...g.includes("command")?[qe({columnId:"command",compare:(S,k)=>(S.button.commandId??"").localeCompare(k.button.commandId??"")||S.order-k.order,renderHeaderCell:()=>N("Command"),renderCell:({button:S})=>B(S.commandId||"—",n.mono)})]:[],qe({columnId:"visible",compare:(S,k)=>Number(S.button.hidden)-Number(k.button.hidden)||S.order-k.order,renderHeaderCell:()=>N("Visible"),renderCell:({button:S,label:k,groupId:w})=>{const D=Ba(t,e.id,S);return a.jsx(pe,{content:D?"Microsoft's global command bar buttons can't be changed.":S.hidden?"Hidden":"Shown",relationship:"description",children:a.jsx(Sa,{checked:!S.hidden,disabled:D,"aria-label":`Toggle visibility of ${k}`,onChange:(F,X)=>i(t,e.id,w,S.id,{hidden:!X.checked})})})}}),qe({columnId:"actions",renderHeaderCell:()=>a.jsx("span",{className:n.muted}),renderCell:S=>a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(us,{}),"aria-label":`Actions for ${S.label}`,onClick:k=>R(S,k.currentTarget)})})];return a.jsxs("div",{className:n.root,children:[a.jsxs("div",{className:n.toolbar,children:[a.jsx(an,{size:"small",className:n.search,placeholder:`Filter ${$.length} button${$.length!==1?"s":""}`,"aria-label":"Filter the buttons",value:p,onChange:(S,k)=>m(k.value)}),A&&a.jsxs(V,{size:200,className:n.muted,children:[j.length," match",j.length!==1?"es":""]}),a.jsxs(Ke,{checkedValues:{columns:g},onCheckedValueChange:(S,k)=>b(k.checkedItems),children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Xh,{}),children:"Columns"})}),a.jsx(Je,{children:a.jsx(Ze,{children:Object.keys(Cl).map(S=>a.jsx(Kl,{name:"columns",value:S,children:Cl[S]},S))})})]})]}),a.jsx("div",{...C,children:a.jsxs(Kh,{className:n.grid,items:j,columns:O,columnSizingOptions:I,resizableColumns:!0,sortable:!0,sortState:x,onSortChange:(S,k)=>v(k),getRowId:S=>S.button.id,focusMode:"composite",size:"small","aria-label":`Buttons of ${e.id}`,children:[a.jsx(Yh,{className:n.header,children:a.jsx(wr,{children:({renderHeaderCell:S})=>a.jsx(vc,{children:S()})})}),a.jsx(Jh,{children:({item:S,rowId:k})=>{const w=o===S.button.id;return a.jsx(wr,{"aria-selected":w,"data-list-button":S.button.id,className:Ie(n.row,w&&n.rowSelected),onClick:D=>{Il(D)||T(S)},onKeyDown:D=>{Il(D)||(D.key==="Enter"||D.key===" "?(D.preventDefault(),T(S)):(D.key==="ContextMenu"||D.shiftKey&&D.key==="F10")&&(D.preventDefault(),R(S,D.currentTarget)))},onContextMenu:D=>{D.preventDefault(),R(S,D.currentTarget)},children:({renderCell:D})=>a.jsx(Sc,{children:D(S)})},k)}})]},g.join("|"))}),j.length===0&&a.jsx(V,{size:200,className:n.muted,as:"p",children:A?"No buttons match.":"This tab has no buttons."}),a.jsx(wo,{location:t,tab:e,target:f,onClose:()=>{const S=f?.anchor;setTimeout(()=>{document.activeElement?.closest('[role="dialog"], [role="alertdialog"]')||S?.isConnected&&S.focus()}),y(null)}}),a.jsx(sw,{tab:e,location:t})]})}const Fu=me({root:{marginTop:h.spacingVerticalM,border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,backgroundColor:h.colorNeutralBackground1,maxWidth:"520px"},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,borderBottom:`1px solid ${h.colorNeutralStroke2}`},spacer:{flex:1},body:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:h.spacingHorizontalS},section:{display:"flex",flexDirection:"column",gap:"2px"},sectionHeader:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`2px ${h.spacingHorizontalXS}`,color:h.colorNeutralForeground3},item:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,width:"100%",minHeight:"28px",padding:`0 ${h.spacingHorizontalS}`,border:"1px solid transparent",borderRadius:h.borderRadiusMedium,backgroundColor:"transparent",color:h.colorNeutralForeground1,cursor:"pointer",textAlign:"left",":hover":{backgroundColor:h.colorNeutralBackground3},":focus-visible":{outline:`2px solid ${h.colorBrandStroke1}`}},itemSelected:{backgroundColor:h.colorBrandBackground2,border:`1px solid ${h.colorBrandStroke1}`},itemHidden:{opacity:.45,textDecoration:"line-through"},itemRow:{display:"flex",alignItems:"center",gap:"2px"},nested:{marginLeft:h.spacingHorizontalL,paddingLeft:h.spacingHorizontalS,borderLeft:`1px dashed ${h.colorNeutralStroke2}`},empty:{padding:`2px ${h.spacingHorizontalS}`,color:h.colorNeutralForeground3}});function rw({tab:e,location:t}){const n=Fu(),o=Y(j=>j.selectedButtonId),s=Y(j=>j.selectedGroupId),i=Y(j=>j.selectButtonInContext),l=M(j=>j.baseline),r=M(j=>j.locLabels),c=De(),d=M(j=>j.addMenuSection),u=M(j=>j.setMenuSectionProp),p=M(j=>j.deleteMenuSection),{overrides:m}=nr(t),g=zn(),b=e.groups.find(j=>j.id===s),f=jb(b,o),y=E.useMemo(()=>{const j=new Set;for(const T of l[t]?.tabs??[])for(const R of T.groups)for(const I of Te(R))j.add(I.id);return j},[l,t]);if(!b||!f||!f.menu&&!Cn(f.kind))return null;const x=b.id,v=j=>c(j.label,r,void 0,j.source?.labelToken),C=j=>td(j.source?.attributes.PopulateDynamically)?j.source?.attributes.PopulateQueryCommand??"a command":null,$=j=>{const T=[...j.menu?.sections??[]].sort((N,B)=>N.sequence-B.sequence),R=!y.has(j.id),I=C(j);return a.jsxs(a.Fragment,{children:[I&&a.jsxs(Qe,{className:n.empty,children:["Populated when the menu opens, by ",I,". Static items below are kept as they are."]}),T.map(N=>a.jsx(lw,{section:N,parent:j,editable:R,onTitle:B=>u(t,e.id,x,j.id,N.id,{title:B}),onDisplayMode:B=>u(t,e.id,x,j.id,N.id,{displayMode:B}),onDelete:()=>p(t,e.id,x,j.id,N.id),renderItem:A},N.id)),T.length===0&&!I&&a.jsx(Qe,{className:n.empty,children:"No menu sections yet."}),R&&a.jsx("div",{children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),onClick:()=>d(t,e.id,x,j.id,""),children:"Add section"})})]})},A=j=>{const T=j.id===o,R=m.get(j.id);return a.jsxs("div",{children:[a.jsxs("div",{className:n.itemRow,children:[a.jsxs("button",{type:"button",className:[n.item,T?n.itemSelected:"",j.hidden?n.itemHidden:""].filter(Boolean).join(" "),"aria-pressed":T,"aria-label":`Menu item ${v(j)}${j.hidden?" — hidden":""}${ku(R,g)}`,onClick:()=>i(t,e.id,x,j.id),children:[a.jsx(vt,{button:j,size:16}),a.jsx(V,{size:200,children:v(j)}),j.menu&&a.jsx(it,{fontSize:12,"aria-hidden":!0}),a.jsx(or,{overrides:R,appNames:g}),j.custom&&!y.has(j.id)&&a.jsx(xe,{style:{flexShrink:0},size:"medium",color:"brand",appearance:"tint",children:"NEW"})]}),T&&a.jsx(dw,{item:j,location:t,tabId:e.id,groupId:x,onDeleted:()=>i(t,e.id,x,f.id)})]}),j.menu&&a.jsx("div",{className:n.nested,children:$(j)})]},j.id)};return a.jsxs("section",{className:n.root,"aria-label":`Menu of ${v(f)}`,children:[a.jsxs("div",{className:n.header,children:[a.jsx(it,{"aria-hidden":!0}),a.jsx(V,{weight:"semibold",size:300,children:v(f)}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",children:f.kind==="splitButton"?"Split button menu":"Flyout menu"}),a.jsx("span",{className:n.spacer}),a.jsxs(Qe,{children:[dn(f).length," item(s)"]})]}),a.jsx("div",{className:n.body,children:$(f)})]})}function lw({section:e,parent:t,editable:n,onTitle:o,onDisplayMode:s,onDelete:i,renderItem:l}){const r=Fu(),c=M(p=>p.locLabels),d=De(),u=[...e.controls].sort((p,m)=>p.sequence-m.sequence);return a.jsxs("div",{className:r.section,children:[a.jsx("div",{className:r.sectionHeader,children:n?a.jsxs(a.Fragment,{children:[a.jsx(_t,{size:"small",placeholder:"Section title (optional)",value:e.title??"","aria-label":"Menu section title",onChange:(p,m)=>o(m.value)}),a.jsxs(xa,{size:"small","aria-label":"Menu section display mode",value:e.displayMode??"Menu16",onChange:(p,m)=>s(m.value),children:[a.jsx("option",{value:"Menu16",children:"16 px icons"}),a.jsx("option",{value:"Menu32",children:"32 px icons"}),a.jsx("option",{value:"Menu",children:"Text only"})]}),a.jsx(pe,{content:"Delete section and its items",relationship:"label",children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(En,{}),onClick:i})})]}):a.jsx(Qe,{children:d(e.title,c,void 0,e.attributes?.Title)||e.id})}),u.map(p=>l(p)),e.rawContent!==void 0&&a.jsx(Qe,{className:r.empty,children:"Gallery / dynamic content (kept as is)"}),(e.rawControls?.length??0)>0&&a.jsxs(Qe,{className:r.empty,children:[e.rawControls.length," other control(s) CBS doesn't edit (kept as they are)"]}),e.rawContent===void 0&&a.jsx(cw,{parent:t,section:e})]})}function cw({parent:e,section:t}){const n=Y(m=>m.location),o=Y(m=>m.tabId),s=Y(m=>m.selectedGroupId),i=Y(m=>m.selectButtonInContext),l=M(m=>m.addMenuItem),r=M(m=>m.upsertCommand),c=ae(m=>m.activeSolution),d=ae(m=>m.publisherPrefix),u=ae(m=>m.activeEntity),p=()=>{if(!s)return;const{ribbons:m,commands:g}=M.getState(),b=new Set(g.map(v=>v.id));for(const v of Object.values(m))for(const C of v.tabs)for(const $ of C.groups)for(const A of Te($))b.add(A.id);const f=c?.publisherPrefix?.trim()||d?.trim()||"new",{id:y,commandId:x}=vd(f,u?.logicalName??"global",n,"MenuItem",b);l({location:n,tabId:o,groupId:s,parentId:e.id,sectionId:t.id,item:{id:y,label:"Menu item",commandId:x}}),r({id:x,enableRules:[],displayRules:[],actions:[]}),i(n,o,s,y)};return a.jsx("div",{children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),onClick:p,children:"Add item"})})}function dw({item:e,location:t,tabId:n,groupId:o,onDeleted:s}){const i=M(c=>c.setButtonProp),l=M(c=>c.deleteButton),r=M(c=>c.baseline[t]);return a.jsxs(a.Fragment,{children:[a.jsx(pe,{content:e.hidden?"Show item":"Hide item",relationship:"label",children:a.jsx(K,{size:"small",appearance:"subtle",icon:e.hidden?a.jsx(Dn,{}):a.jsx(Bt,{}),onClick:()=>i(t,n,o,e.id,{hidden:!e.hidden})})}),Is(e,r)&&a.jsx(pe,{content:"Delete item",relationship:"label",children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(En,{}),onClick:()=>{l(t,n,o,e.id),s()}})})]})}const uw=me({surface:{maxWidth:"380px",display:"flex",flexDirection:"column",gap:h.spacingVerticalS},ribbonId:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,color:h.colorNeutralForeground3,overflowWrap:"anywhere"}}),mw=({location:e,table:t,compact:n})=>{const o=uw(),s=Vt[e],i=n?a.jsx(pe,{content:"About this location",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Ii,{})})}):a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Ii,{}),children:"About this location"});return a.jsxs(ca,{withArrow:!0,positioning:"below-start",children:[a.jsx(da,{disableButtonEnhancement:!0,children:i}),a.jsxs(ua,{className:o.surface,"aria-label":`About ${s.title}`,children:[a.jsx(V,{weight:"semibold",children:s.title}),a.jsx(V,{children:s.body}),a.jsx("span",{className:o.ribbonId,children:wb(e,t)})]})]})},pw=me({popover:{overflowY:"auto"},trigger:{maxWidth:"200px",minWidth:0},label:{color:h.colorNeutralForeground3,flexShrink:0},value:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function fw(){const e=pw(),t=we(c=>c.status),n=we(c=>c.apps),o=we(c=>c.appFilter),s=we(c=>c.setAppFilter),i=we(c=>c.commands.length),l=we(c=>c.error);if(t==="idle")return null;if(t==="loading")return a.jsx(Zh,{size:"extra-tiny","aria-label":"Loading modern commands"});if(t==="unavailable")return a.jsx(Et,{size:"small",info:`Modern commands couldn't be read: ${l??"unknown error"}`,children:"Modern commands unavailable"});const r=o==="all"?"All apps":n.find(c=>c.id===o)?.name??"All apps";return a.jsxs(Ke,{positioning:{autoSize:"height"},checkedValues:{app:[o]},onCheckedValueChange:(c,d)=>s(d.checkedItems[0]??"all"),children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:`${i} modern command${i===1?"":"s"} for this table (read-only). Pick an app to see its command bar.`,relationship:"description",children:a.jsxs(K,{appearance:"subtle",size:"small",className:e.trigger,"aria-label":`App for modern commands: ${r}`,icon:a.jsx(it,{}),iconPosition:"after",children:[a.jsx("span",{className:e.label,children:"App: "}),a.jsx("span",{className:e.value,children:r})]})})}),a.jsx(Je,{className:e.popover,children:a.jsxs(Ze,{children:[a.jsx(Sn,{name:"app",value:"all",children:"All apps"}),n.map(c=>a.jsx(Sn,{name:"app",value:c.id,children:c.name},c.id))]})})]})}const hw=me({row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`0 ${h.spacingHorizontalS}`,minHeight:"40px",borderBottom:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0,minWidth:0},locationRow:{backgroundColor:h.colorNeutralBackground2},locationTabs:{flex:"1 1 0",minWidth:0,overflow:"hidden",display:"flex",alignItems:"center"},spacer:{flex:"1 1 0",minWidth:0},viewValue:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3,flexShrink:0},tableName:{flex:"0 1 auto",maxWidth:"200px",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",paddingRight:h.spacingHorizontalS,borderRight:`1px solid ${h.colorNeutralStroke2}`,fontWeight:h.fontWeightSemibold},pinned:{flexShrink:0}}),_u=["HomepageGrid","Form","SubGrid","Application"],qu={HomepageGrid:a.jsx(va,{}),Form:a.jsx(ps,{}),SubGrid:a.jsx(Qh,{}),Application:a.jsx(rc,{})},Mo={groups:"Group cards",classic:"Classic ribbon",modern:"Modern command bar",list:"List"};function gw(){const e=hw(),t=Y(m=>m.location),n=Y(m=>m.setLocation),o=Y(m=>m.setTabId),s=Y(m=>m.tabId),i=M(m=>m.ribbons),l=!/^(Mscrm|Microsoft)\./.test(s)&&i[t].tabs.some(m=>m.id===s),r=ae(m=>m.activeEntity?.logicalName),c=ae(m=>m.activeEntity?.displayName),d=Z(m=>m.ribbonViewStyle),u=Z(m=>m.setRibbonViewStyle),p=m=>{n(m);const g=mo(i[m].tabs);g&&o(g)};return a.jsxs("div",{className:`${e.row} ${e.locationRow}`,children:[r&&a.jsx(pe,{content:`Table: ${c||r} (${r})`,relationship:"description",children:a.jsx("span",{className:e.tableName,tabIndex:0,children:c||r})}),a.jsx(ma,{minimumVisible:1,padding:48,children:a.jsxs("div",{className:e.locationTabs,children:[a.jsxs(wa,{size:"small","aria-label":"Where the command bar appears",selectedValue:t,onTabSelect:(m,g)=>p(g.value),children:[_u.map(m=>a.jsx(Ft,{id:m,priority:m===t?2:1,children:a.jsx(qt,{value:m,icon:qu[m],children:Vt[m].label})},m)),a.jsx(bw,{onSelect:p})]}),a.jsx(mw,{location:t,table:r,compact:!0}),l&&a.jsx(Et,{size:"small",info:Yd,infoButton:{"aria-label":"How Unified Interface shows this tab"}})]})}),a.jsx(fw,{}),a.jsxs(Ke,{checkedValues:{view:[d]},onCheckedValueChange:(m,g)=>u(g.checkedItems[0]),children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsxs(K,{appearance:"subtle",size:"small",icon:a.jsx(it,{}),iconPosition:"after","aria-label":`View as: ${Mo[d]}`,className:e.pinned,children:[a.jsx("span",{className:e.muted,children:"View: "}),a.jsx("span",{className:e.viewValue,children:Mo[d]})]})}),a.jsx(Je,{children:a.jsx(Ze,{children:Object.keys(Mo).map(m=>a.jsx(Sn,{name:"view",value:m,children:Mo[m]},m))})})]})]})}function bw({onSelect:e}){const{ref:t,isOverflowing:n,overflowCount:o}=ba();return n?a.jsxs(Ke,{children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(K,{ref:t,appearance:"transparent",size:"small",icon:a.jsx(it,{}),iconPosition:"after","aria-label":`${o} more locations`,children:"More"})}),a.jsx(Je,{children:a.jsx(Ze,{children:_u.map(s=>a.jsx(yw,{location:s,onSelect:e},s))})})]}):null}function yw({location:e,onSelect:t}){return ya(e)?null:a.jsx(fe,{icon:qu[e],onClick:()=>t(e),children:Vt[e].label})}const sr=me({empty:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:h.spacingVerticalM,padding:h.spacingHorizontalXXL,textAlign:"center",color:h.colorNeutralForeground3},icon:{fontSize:"40px",color:h.colorNeutralForeground4},body:{maxWidth:"420px"},loading:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,padding:h.spacingHorizontalM},skeletonRow:{display:"flex",gap:h.spacingHorizontalS},skeletonCards:{display:"flex",gap:h.spacingHorizontalM,flexWrap:"wrap"},card:{flex:"1 1 200px",height:"140px"},status:{color:h.colorNeutralForeground2},error:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:h.spacingHorizontalM,maxWidth:"720px"},details:{margin:0,fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:h.colorNeutralForeground2}});function xw({kind:e}){const t=sr(),n=Z(s=>s.setSolutionPickerOpen),o=Z(s=>s.setTablePickerOpen);return e==="noSolution"?a.jsxs("div",{className:t.empty,children:[a.jsx(Vl,{className:t.icon,"aria-hidden":"true"}),a.jsx(V,{size:500,weight:"semibold",children:"Choose a solution to start"}),a.jsx(V,{className:t.body,children:"Your changes are saved to the solution you pick. Only unmanaged solutions are listed."}),a.jsx(K,{appearance:"primary",onClick:()=>n(!0),children:"Choose solution"})]}):a.jsxs("div",{className:t.empty,children:[a.jsx(va,{className:t.icon,"aria-hidden":"true"}),a.jsx(V,{size:500,weight:"semibold",children:"Pick a table"}),a.jsx(V,{className:t.body,children:"Choose a table from this solution to see and change its command bars."}),a.jsx(K,{appearance:"primary",onClick:()=>o(!0),children:"Choose table"})]})}function vw({table:e,step:t}){const n=sr();return a.jsxs("div",{className:n.loading,children:[a.jsx(eg,{thickness:"medium","aria-label":"Loading"}),a.jsxs(V,{role:"status","aria-live":"polite",className:n.status,children:[e?`Loading ${e}`:"Loading the ribbon",t?` · ${t}`:""]}),a.jsxs(tg,{"aria-hidden":"true",className:n.loading,children:[a.jsx("div",{className:n.skeletonRow,children:[70,80,90,60,75].map(o=>a.jsx(Cr,{style:{width:o,height:32}},o))}),a.jsx("div",{className:n.skeletonCards,children:[0,1,2].map(o=>a.jsx(Cr,{className:n.card},o))})]})]})}function Sw(e){return/\b401\b|unauthori[sz]ed/i.test(e)?"Your connection may have expired.":/\b403\b|forbidden|privilege/i.test(e)?"Your account may not have permission to read this table's ribbon.":/\b(429|503|504)\b|timeout|timed out/i.test(e)?"Dataverse was busy or didn't answer in time. Try again in a moment.":/\b5\d\d\b/.test(e)?"Dataverse returned an error.":/failed to fetch|network/i.test(e)?"The connection to Dataverse failed.":"Something went wrong while reading it."}function ww({table:e,error:t,onRetry:n}){const o=sr(),[s,i]=E.useState("");return a.jsxs("div",{className:o.error,children:[a.jsxs($t,{intent:"error",layout:"multiline",children:[a.jsxs(Tt,{children:[a.jsxs(Yl,{children:["Couldn't load ",e?`${e}'s`:"the"," ribbon"]}),Sw(t)]}),n&&a.jsx(ms,{children:a.jsx(K,{size:"small",appearance:"primary",onClick:n,children:"Retry"})})]}),a.jsx(wc,{collapsible:!0,children:a.jsxs(Cc,{value:"details",children:[a.jsx(Ic,{size:"small",children:"Details"}),a.jsxs(jc,{children:[a.jsx("pre",{className:o.details,children:t}),a.jsx(K,{size:"small",onClick:async()=>i((await ks(t)).ok?"yes":"no"),children:s==="yes"?"Copied":s==="no"?"Couldn't copy":"Copy details"})]})]})})]})}const Cw=me({root:{display:"flex",flexDirection:"column",flex:1,minWidth:0,overflow:"hidden",backgroundColor:h.colorNeutralBackground1},messages:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`},canvas:{flex:1,overflow:"auto",padding:h.spacingHorizontalM}}),Iw=me({root:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"80px",gap:h.spacingHorizontalM,color:h.colorNeutralForeground3}});function jw({isLoadingRibbon:e=!1,loadingTable:t,loadingStep:n=null,ribbonLoadError:o=null,layerReadError:s=null,onRetryRibbonLoad:i,emptyState:l}){const r=Cw(),c=Y(R=>R.location),d=Y(R=>R.tabId),u=Y(R=>R.setTabId),p=M(R=>R.ribbons),m=M(R=>R.orphans.entity.filter(I=>!R.pendingOrphanDeletes.entity.includes(I.id)&&!I.recentPublish?.published).map(I=>I.id).sort().join("|")),g=m?m.split("|").length:0,b=ae(R=>R.connectionUrl),f=Y(R=>R.clearSelection),y=Z(R=>R.ribbonViewStyle),x=Z(R=>R.openNewGroup),v=Z(R=>R.setPropertiesRequested),[C,$]=E.useState(!1),A=p[c],j=A.tabs.find(R=>R.id===d)??A.tabs.find(R=>R.id===mo(A.tabs));E.useEffect(()=>{if(!A.tabs.length)return;if(!A.tabs.some(I=>I.id===d)){const I=mo(A.tabs);I&&u(I)}},[A.tabs,d,u]);const T=[];return s&&!e&&!o&&T.push({id:"layer-read",intent:"warning",title:"Couldn't read your unmanaged ribbon customizations",body:`Labels may show as ids, and what you can edit or delete is unknown. Reload before editing. Details: ${s}`,dismissible:!1,actions:i&&a.jsx(K,{size:"small",onClick:()=>_o()?$(!0):i(),children:"Retry"})}),j&&xo(j.id)&&T.push({id:`hidden-tab:${j.id}`,intent:"warning",title:"Unified Interface doesn't show this tab's buttons",body:"They don't come back when the table is reloaded either. Add buttons to the table's main tab instead."}),c!=="Application"&&g>0&&T.push({id:"orphans",intent:"warning",signature:m,title:`${g} of your customizations ${g!==1?"aren't":"isn't"} on the canvas`,body:a.jsxs(a.Fragment,{children:["The ribbon doesn't return ",g!==1?"them":"it",". See"," ",a.jsx("strong",{children:"Orphaned customizations"})," in the Properties pane to delete"," ",g!==1?"them":"it","."]}),actions:a.jsx(K,{size:"small",onClick:()=>{f(),v(!0)},children:"Show"})}),l?a.jsx("main",{className:r.root,"aria-label":"Ribbon canvas",children:a.jsx(xw,{kind:l})}):a.jsxs("main",{className:r.root,"aria-label":"Ribbon canvas",children:[a.jsx(gw,{}),a.jsx(Xa,{messages:T,scope:`canvas:${b}:${A.entityLogicalName}:${c}`,className:r.messages}),a.jsx("div",{className:r.canvas,children:e?a.jsx(vw,{table:t,step:n}):o?a.jsx(ww,{table:t,error:o,onRetry:i}):j?a.jsxs(a.Fragment,{children:[y==="groups"?a.jsxs(a.Fragment,{children:[a.jsx(KS,{tab:j,location:c}),a.jsx(hS,{tab:j,location:c})]}):y==="classic"?a.jsx(uS,{tab:j,location:c}):y==="modern"?a.jsx(tw,{tab:j,location:c}):a.jsx(aw,{tab:j,location:c}),a.jsx(rw,{tab:j,location:c})]}):a.jsx(Rw,{onAddGroup:x})}),C&&i&&a.jsx(Ln,{open:!0,title:"Reload the ribbon",confirmLabel:"Reload",onConfirm:()=>{$(!1),i()},onCancel:()=>$(!1),children:"You have unpublished changes. Reloading replaces the canvas; your changes are kept in a draft that is offered after the reload. They were made while your labels weren't loaded, so check their texts before you publish: a text can read a label's id."})]})}function Rw({onAddGroup:e}){const t=Iw();return a.jsxs("div",{className:t.root,children:[a.jsx(ps,{fontSize:32,style:{opacity:.4}}),a.jsx(V,{size:300,children:"This tab has no groups yet"}),a.jsx(K,{appearance:"primary",size:"small",icon:a.jsx(ke,{}),onClick:e,children:"Add first group"})]})}let Yn=null;const na={set(e){Yn=e},invoke(e){const t=Yn;Yn=null,t?.(e)},clear(){Yn=null},hasPending(){return Yn!==null}},$w=me({field:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS,minWidth:0},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,minWidth:0},input:{flex:1,minWidth:0,backgroundColor:h.colorNeutralBackground3},srOnly:{position:"absolute",width:"1px",height:"1px",overflow:"hidden",clipPath:"inset(50%)",whiteSpace:"nowrap"},value:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,textOverflow:"ellipsis"}}),Wu=({label:e,value:t,action:n,hideLabel:o})=>{const s=$w(),i=E.useId(),[l,r]=E.useState("idle"),c=E.useRef(void 0);E.useEffect(()=>()=>clearTimeout(c.current),[]);const d=async()=>{const m=await ks(t);r(m.ok?"copied":"failed"),clearTimeout(c.current),c.current=setTimeout(()=>r("idle"),2e3)},u=l==="copied"?`${e} copied`:l==="failed"?`Couldn't copy the ${e.toLowerCase()}`:`Copy ${e.toLowerCase()}`,p=a.jsxs("div",{className:s.row,children:[a.jsx(pe,{content:t,relationship:"description",withArrow:!0,children:a.jsx(_t,{id:i,className:s.input,input:{className:s.value},value:t,readOnly:!0,appearance:"filled-darker","aria-label":o?e:void 0})}),a.jsx(pe,{content:u,relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:l==="copied"?a.jsx(mc,{}):a.jsx(yo,{}),onClick:()=>{d()}})}),n,a.jsx("span",{"aria-live":"polite",className:s.srOnly,children:l==="idle"?"":u})]});return o?p:a.jsxs("div",{className:s.field,children:[a.jsx(ng,{htmlFor:i,size:"small",weight:"semibold",children:e}),p]})},Tw=["button","flyout","splitButton","textBox","comboBox","checkBox"],Nw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,minWidth:0},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS},localeChips:{display:"flex",flexWrap:"wrap",gap:h.spacingHorizontalXS,alignItems:"center"},iconPreview:{width:"32px",height:"32px",borderRadius:"6px",backgroundColor:h.colorNeutralBackground4,color:h.colorNeutralForeground1,display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0},keyHint:{overflowWrap:"anywhere"},lockedNote:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,color:h.colorNeutralForeground2},webResLink:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,cursor:"pointer",color:h.colorBrandForeground1,textDecoration:"underline",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1,border:"none",background:"transparent",textAlign:"left"}});function ci({button:e,location:t,tabId:n,groupId:o,part:s}){const i=Nw(),l=M(j=>j.setButtonProp),r=M(j=>j.locLabels),c=M(j=>j.baseLanguageCode),d=Z(j=>j.openIconPicker),u=Z(j=>j.openLocalizationEditor),p=Z(j=>j.openWebResourceBrowser),m=M(j=>!j.ribbons[t].tabs.find(T=>T.id===n)?.groups.find(T=>T.id===o)?.buttons.some(T=>T.id===e.id)),g=M(j=>kd(j,t,e.id)),b=M(j=>j.ribbons[t].tabs.find(T=>T.id===n)?.groups.find(T=>T.id===o)),f=De(),y=[...new Set([...m?ka:Tw,e.kind])];function x(j){l(t,n,o,e.id,j)}const v=e.origin!=="unmanaged",C={label:f(e.label,r,void 0,e.source?.labelToken),tooltipTitle:f(e.tooltipTitle,r,void 0,e.source?.tooltipTitleToken),tooltipBody:f(e.tooltipBody,r,void 0,e.source?.tooltipBodyToken)},$=(j,T)=>j&&j!==T?{children:`From ${j}`,className:i.keyHint}:void 0,A=Sb(e,r,c);return s==="position"?a.jsxs("div",{className:i.root,children:[a.jsx(_e,{label:"Group",hint:"Use Move to in the button's menu to move it.",children:a.jsx(_t,{readOnly:!0,appearance:"filled-darker",value:b?f(b.label,r,c,b.source?.titleToken)||b.id:o})}),a.jsx(_e,{label:"Order",hint:"Lower numbers show first within the group. Unified Interface merges the groups into one bar.",children:a.jsx(og,{value:e.sequence,disabled:v,step:10,min:0,onChange:(j,T)=>x({sequence:Number(T.value??e.sequence)})})})]}):s==="advanced"?a.jsxs("div",{className:i.root,children:[a.jsx(_e,{label:"Kind",hint:g?"A loaded control's kind can't be changed: add a new control instead.":m?"A menu holds buttons and flyouts.":void 0,children:a.jsx(xa,{value:e.kind,disabled:g,onChange:(j,T)=>x({kind:T.value}),children:y.map(j=>a.jsx("option",{value:j,children:xt[j]},j))})}),a.jsx(_e,{label:"Template alias",hint:"Which slot of the group's layout the button uses on the classic ribbon, for example o1.",children:a.jsx(_t,{value:e.templateAlias,readOnly:v,onChange:(j,T)=>x({templateAlias:T.value})})})]}):a.jsxs("div",{className:i.root,children:[v&&a.jsxs(V,{size:200,className:i.lockedNote,children:[a.jsx(un,{"aria-hidden":!0})," Customise this button, or create an override, to edit these fields."]}),a.jsx(_e,{label:"Label",hint:v?$(e.label,C.label):void 0,children:a.jsx(_t,{value:v?C.label:e.label,readOnly:v,appearance:v?"filled-darker":void 0,onChange:(j,T)=>x({label:T.value})})}),a.jsx(_e,{label:"Translations",children:a.jsxs("div",{className:i.localeChips,children:[a.jsx(Rc,{"aria-label":"Languages of this button's text",size:"small",children:(A.length?A:[1033]).map(j=>a.jsx(Ca,{value:String(j),appearance:"brand",children:a.jsxs(Ia,{disabled:v,onClick:()=>u(e.id),children:[j===1033?"en-US":String(j),A.length===0?" (default)":""]})},j))}),a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),disabled:v,onClick:()=>u(e.id),children:"Add language…"})]})}),a.jsx(_e,{label:"Tooltip title",hint:v?$(e.tooltipTitle,C.tooltipTitle):void 0,children:a.jsx(_t,{value:v?C.tooltipTitle:e.tooltipTitle??"",readOnly:v,appearance:v?"filled-darker":void 0,onChange:(j,T)=>x({tooltipTitle:T.value})})}),a.jsx(_e,{label:"Tooltip body",hint:v?$(e.tooltipBody,C.tooltipBody):void 0,children:a.jsx(sg,{value:v?C.tooltipBody:e.tooltipBody??"",readOnly:v,appearance:v?"filled-darker":void 0,onChange:(j,T)=>x({tooltipBody:T.value}),resize:"vertical"})}),a.jsx(Lo,{}),a.jsx(_e,{label:"Icon",children:a.jsxs("div",{className:i.row,children:[a.jsx("div",{className:i.iconPreview,children:e.icon?a.jsx(Za,{name:e.icon,size:20}):a.jsx(Si,{style:{color:h.colorNeutralForeground3}})}),a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Si,{}),disabled:v,onClick:d,children:"Change…"})]})}),e.icon&&a.jsx(_e,{label:"Modern image",hint:"What Unified Interface shows. Set from the icon you pick.",children:a.jsx(_t,{value:Da(e)??"(none)",readOnly:!0})}),e.image16&&a.jsx(_e,{label:"Image16",children:a.jsx("div",{className:i.row,children:a.jsx(pe,{content:e.image16,relationship:"description",children:a.jsx(Tn,{as:"button",className:i.webResLink,disabled:v,onClick:()=>{na.set(j=>{x({image16:`$webresource:${j.name}`,icon:j.name.split("/").pop()?.replace(/\..*$/,"")})}),p()},children:e.image16})})})}),e.image32&&a.jsx(_e,{label:"Image32",children:a.jsx("div",{className:i.row,children:a.jsx(pe,{content:e.image32,relationship:"description",children:a.jsx(Tn,{as:"button",className:i.webResLink,disabled:v,onClick:()=>{na.set(j=>{x({image32:`$webresource:${j.name}`})}),p()},children:e.image32})})})}),a.jsx(Sa,{label:"Visible",checked:!e.hidden,onChange:(j,T)=>x({hidden:!T.checked})}),a.jsx(Wu,{label:"Button ID",value:e.id})]})}const kw=me({row:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:h.spacingHorizontalS}}),Aw={oob:"informative",customising:"warning",customised:"brand",uncustomising:"danger",custom:"success",reloadRequired:"danger"};function Do(e){return e.scope==="application"?"the application ribbon's layer (every table)":e.sharedWithApplication?"this table's layer only (the application ribbon keeps the original)":"this table's layer"}function Ow({commandId:e,compact:t=!1,hideBadge:n=!1}){const o=kw(),s=Os(e),i=M(x=>x.customiseCommand),l=M(x=>x.uncustomiseCommand),r=M(x=>x.discardCommandChanges),c=M(x=>{const v=x.commands.find($=>$.id===e),C=x.baselineCommands.find($=>$.id===e);return!!v&&!!C&&JSON.stringify(v)!==JSON.stringify(C)}),[d,u]=E.useState(null);if(!s)return null;const p=(x,v,C)=>{c?u({what:x,confirmLabel:v,run:C}):C()},m=d&&a.jsxs(Ln,{open:!0,title:"Discard unpublished changes?",confirmLabel:d.confirmLabel,destructive:!0,onConfirm:()=>{d.run(),u(null)},onCancel:()=>u(null),children:[d.what," discards your unpublished changes to ",a.jsx("code",{children:e}),"."]}),{provenance:g}=s,b=g==="oob"?a.jsx(K,{size:"small",appearance:"outline",onClick:()=>i(e),children:"Customise command"}):g==="customising"?a.jsx(K,{size:"small",appearance:"subtle",onClick:()=>p("Discarding the customisation","Discard customisation",()=>r(e)),children:"Discard customisation"}):g==="customised"?a.jsx(K,{size:"small",appearance:"subtle",onClick:()=>p("Uncustomising","Uncustomise",()=>l(e,s.scope)),children:"Uncustomise"}):g==="uncustomising"?a.jsx(K,{size:"small",appearance:"subtle",onClick:()=>r(e),children:"Undo uncustomise"}):null,f=a.jsx(xe,{appearance:g==="oob"?"outline":"filled",color:Aw[g],size:"medium",children:Tv[g]});if(t)return a.jsxs("div",{className:o.row,children:[f,b,m]});const y={oob:`Out of the box or from another solution, so it's read-only. Customise it to copy it — actions, parameters and rules — into ${Do(s)} and change it there; its buttons keep using it.`,customising:`On publish, this command is copied into ${Do(s)} and replaces the original there. Rules keep their ids; a rule you edit is written to the layer as well.`,customised:`${Do(s).replace(/^./,x=>x.toUpperCase())} has a copy of this command that replaces the original. Uncustomise to remove the copy so the original applies again.`,uncustomising:`On publish, the copy of this command in ${Do(s)} is removed (with rules only it used) and the original applies again. Reload the table after publishing to see the original definition.`,custom:"Your own command.",reloadRequired:"Your layer's copy of this command was removed, so the original applies. What is shown here is the removed copy: reload the table to load the original before changing or customising it again."};return g==="custom"?n?null:a.jsx("div",{className:o.row,children:f}):a.jsxs(a.Fragment,{children:[a.jsxs($t,{layout:"multiline",intent:g==="uncustomising"||g==="reloadRequired"?"warning":"info",children:[a.jsx(Tt,{children:a.jsxs("div",{className:o.row,children:[!n&&f,a.jsx(V,{size:200,children:y[g]})]})}),b&&a.jsx(ms,{children:b})]}),m]})}const Mw=me({field:{minWidth:0},combobox:{minWidth:0,width:"100%"},listbox:{maxHeight:"280px",maxWidth:"min(480px, 90vw)",overflowWrap:"anywhere"}});function Hu({label:e,options:t,selected:n,onSelect:o,placeholder:s="Type to filter",noOptionsMessage:i="Nothing matches.",hint:l}){const r=Mw(),[c,d]=E.useState(n),[u,p]=E.useState(n);u!==n&&(p(n),d(n));const m=Gl(c,t.map(b=>({value:b,children:b})),{noOptionsMessage:i,optionToReactKey:b=>b.value,optionToText:b=>b.value}),g=(b,f)=>{d(f.optionText??""),o(f.optionValue??"")};return a.jsx(_e,{label:e,hint:l,className:r.field,children:a.jsx(la,{size:"small",freeform:!0,clearable:!0,className:r.combobox,listbox:{className:r.listbox},placeholder:s,value:c,selectedOptions:n?[n]:[],onChange:b=>{d(b.target.value),n&&o("")},onOptionSelect:g,children:m})})}const Dw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,minWidth:0},commandRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:h.spacingHorizontalS,padding:`${h.spacingHorizontalXS} ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground3},commandId:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,color:h.colorNeutralForeground1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function Ew({button:e,groupId:t,tabId:n,location:o}){const s=Dw(),i=M(f=>f.commands),l=M(f=>f.upsertCommand),r=M(f=>f.setButtonProp),c=M(f=>f.batch),d=Z(f=>f.openCommandEditor),[u,p]=tt.useState(""),m=i.find(f=>f.id===e.commandId),g=()=>{const f=new Set(i.map(x=>x.id)),y=Pa("New","Command",f);c(()=>{l({id:y,enableRules:[],displayRules:[],actions:[]}),r(o,n,t,e.id,{commandId:y})}),d(y)},b=()=>{u&&(r(o,n,t,e.id,{commandId:u}),p(""))};return a.jsx("div",{className:s.root,children:m?a.jsxs(a.Fragment,{children:[a.jsx(Wu,{label:"Command ID",value:m.id,action:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Mn,{}),onClick:()=>d(m.id),children:"Edit command"})}),a.jsx(Ow,{commandId:m.id,compact:!0}),m.actions.length>0&&a.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:m.actions.map((f,y)=>a.jsx(zs,{size:"extra-small",appearance:"outline",children:f.kind==="javascript"?`JS: ${f.functionName}`:f.kind==="url"?`URL: ${f.address}`:f.kind==="powerFx"?`Fx: ${f.expression}`:f.kind==="customApi"?`API: ${f.actionName}`:f.kind==="outlookCommand"?`Outlook: ${f.actionType}`:`XML: ${f.tagName}`},y))}),m.enableRules.length>0&&a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"Enable rules:"}),m.enableRules.map(f=>a.jsx(zs,{size:"extra-small",appearance:"outline",color:"success",children:f},f))]}),m.displayRules.length>0&&a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"Display rules:"}),m.displayRules.map(f=>a.jsx(zs,{size:"extra-small",appearance:"outline",color:"informative",children:f},f))]})]}):e.commandId?a.jsx("div",{className:s.commandRow,children:a.jsxs(V,{className:s.commandId,style:{color:h.colorStatusWarningForeground3},children:[e.commandId," (not found)"]})}):a.jsxs(a.Fragment,{children:[a.jsx(Hu,{label:"Use an existing command",options:i.map(f=>f.id),selected:u,onSelect:p,noOptionsMessage:"No command matches."}),a.jsxs("div",{style:{display:"flex",gap:h.spacingHorizontalXS},children:[a.jsx(K,{appearance:"outline",size:"small",disabled:!u,onClick:b,children:"Bind"}),a.jsx(K,{appearance:"outline",size:"small",icon:a.jsx(ke,{}),onClick:g,children:"Create and bind"})]})]})})}const Bw=new Set(["enablerule","displayrule","rule","enable","display","tabdisplayrule","mscrm"]);function Lw(e){const t=e.split(".").filter(Boolean);for(let n=t.length-1;n>=0;n--)if(!Bw.has(t[n].toLowerCase()))return t[n];return e}const zw=({ruleId:e,kind:t,onOpen:n,onRemove:o})=>{const s=Lw(e),i=t==="enable"?"enable rule":"display rule";return a.jsxs(Ca,{value:e,size:"small",appearance:"outline",children:[a.jsx(pe,{content:e,relationship:"description",children:a.jsx(Ia,{hasSecondaryAction:!!o,onClick:n,children:s})}),o&&a.jsx(ig,{"aria-label":`Unbind ${i} ${s}`,onClick:o})]})},Pw=me({section:{display:"flex",flexDirection:"column",gap:h.spacingHorizontalXS},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS},pillList:{display:"flex",flexWrap:"wrap",gap:h.spacingHorizontalXS,maxWidth:"100%",minWidth:0},addBtn:{alignSelf:"flex-start"},note:{fontSize:h.fontSizeBase200,color:h.colorNeutralForeground3,fontStyle:"italic"}}),Gu=({kind:e})=>{const t=Pw(),n=Y(w=>w.location),o=Y(w=>w.tabId),s=Y(w=>w.selectedGroupId),i=Y(w=>w.selectedButtonId),l=M(w=>w.commands),r=M(w=>w.displayRules),c=M(w=>w.enableRules),d=M(w=>w.upsertCommand),u=M(w=>w.upsertDisplayRule),p=M(w=>w.upsertEnableRule),m=M(w=>w.batch),g=Z(w=>w.openRuleEditor),x=M(w=>w.ribbons)[n].tabs.find(w=>w.id===o)?.groups.find(w=>w.id===s),v=Ss(x,i),C=l.find(w=>w.id===v?.commandId),$=Os(C?.id),A=Nv($),j=$?.provenance==="uncustomising"?"Undo the uncustomise to change its rules.":$?.provenance==="reloadRequired"?"Reload the table to change its rules.":"Customise the command to change its rules.",T=e==="display"?C?.displayRules??[]:C?.enableRules??[],R=e==="display"?r:c,[I,N]=tt.useState(""),B=R.filter(w=>!T.includes(w.id)),O=w=>{if(!C)return;const D=T.filter(F=>F!==w);d(e==="display"?{...C,displayRules:D}:{...C,enableRules:D})},S=()=>{if(!C)return;if(e==="display"){const F=new Set(r.map(ne=>ne.id)),X=uo(Fr(C.id),"Display",F);m(()=>{u({id:X,steps:[]}),d({...C,displayRules:[...C.displayRules,X]})}),g(X,"display");return}const w=new Set(c.map(F=>F.id)),D=uo(Fr(C.id),"Enable",w);m(()=>{p({id:D,steps:[]}),d({...C,enableRules:[...C.enableRules,D]})}),g(D,"enable")},k=()=>{!C||!I||(d(e==="display"?{...C,displayRules:[...C.displayRules,I]}:{...C,enableRules:[...C.enableRules,I]}),N(""))};return a.jsxs("div",{className:t.section,children:[!C&&a.jsx(V,{className:t.note,children:"Bind a command first to manage rules."}),T.length>0&&a.jsx(Rc,{className:t.pillList,"aria-label":e==="display"?"Bound display rules":"Bound enable rules",children:T.map(w=>a.jsx(zw,{ruleId:w,kind:e,onOpen:()=>g(w,e),onRemove:A?void 0:()=>O(w)},w))}),C&&A&&a.jsx(V,{className:t.note,children:j}),C&&!A&&a.jsxs(a.Fragment,{children:[a.jsx(Hu,{label:`Bind an existing ${e} rule`,options:B.map(w=>w.id),selected:I,onSelect:N,noOptionsMessage:"No rule matches."}),a.jsxs("div",{style:{display:"flex",gap:h.spacingHorizontalXS},children:[a.jsx(K,{className:t.addBtn,appearance:"subtle",size:"small",onClick:k,disabled:!I,children:"Bind"}),a.jsxs(K,{className:t.addBtn,appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:S,children:["Create new ",e," rule"]})]})]}),e==="enable"&&a.jsx(Et,{size:"small",info:"Disabled buttons are hidden in the modern command bar (Unified Interface). In the classic ribbon, they stay visible but do nothing when clicked.",children:"What a failing enable rule does"})]})},Fw=()=>a.jsx(Gu,{kind:"display"}),_w=()=>a.jsx(Gu,{kind:"enable"}),qw=me({section:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS},note:{color:h.colorNeutralForeground2}}),Ww=()=>{const e=qw(),t=Y(p=>p.location),n=Y(p=>p.tabId),o=M(p=>p.ribbons[t]),s=M(p=>p.locLabels),i=M(p=>p.baseLanguageCode),l=De(),r=o.tabs.find(p=>p.id===n),c=o.scalingByTab?.[n],d=(c?.maxSizes.length??0)+(c?.scales.length??0),u=r?.groups.length??0;return a.jsxs("div",{className:e.section,children:[r?a.jsxs(V,{size:200,className:e.note,children:["“",l(r.label,s,i,r.source?.titleToken)||r.id,"” has ",u," group",u===1?"":"s"," and ",d," scaling step",d===1?"":"s","."]}):a.jsx(V,{size:200,className:e.note,children:"Select a tab to see its scaling."}),a.jsx(V,{size:200,className:e.note,children:"Scaling decides how groups shrink as the classic ribbon narrows; Unified Interface ignores it. Command Bar Studio can't change it yet."})]})},Hw=me({section:{display:"flex",flexDirection:"column",gap:h.spacingHorizontalXS},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS},note:{fontSize:h.fontSizeBase200,color:h.colorNeutralForeground3}}),Gw=()=>{const e=Hw(),t=Y(C=>C.location),n=Y(C=>C.selectedButtonId),o=M(C=>C.ribbons),s=Z(C=>C.openCommandEditor),i=M(C=>C.setOpenRecordOverride),l=Y(C=>C.clearSelection),r=ae(C=>C.activeSolution),c=ae(C=>C.publisherPrefix),d=o[t],u=Sd.includes(t),p=Cd(d),m=p.length>0,g=p.map(C=>Id(C)),b=g.includes("theirs"),f=!b&&g.includes("unknown"),y=!m&&!jd(d),x=qa(d).filter(C=>!wd(C.button)),v=C=>{const $=r?.publisherPrefix?.trim()||c?.trim()||"new";!C&&p.some(A=>A.button.id===n)&&l(),!(!i(t,C,$)||!C)&&s(Xe)};return a.jsxs("div",{className:e.section,children:[u&&a.jsxs("div",{children:[a.jsx(Sa,{label:a.jsx(Et,{info:a.jsxs(a.Fragment,{children:["When on, double-clicking a row of this table's"," ",t==="SubGrid"?"sub-grids (on any form)":"home grid",", selecting its primary column link or pressing Enter runs your command instead of opening the record. Unified Interface only. As Microsoft's recipe requires, an “Open record” button using the command is added here: don't hide it. The Command Editor opens so you can set the script; Publish waits until you do. Turning it off removes that button."]}),children:`Override opening a record from the ${t==="SubGrid"?"sub-grid":"home grid"}`}),checked:m,disabled:b||f||y,onChange:(C,$)=>v($.checked)}),b&&a.jsx(V,{size:200,className:e.note,children:`The "Open record" button here comes from another solution, so the override can't be turned off from your customizations.`}),f&&a.jsx(V,{size:200,className:e.note,children:`CBS doesn't know yet which solution the "Open record" button here comes from (its solution layers haven't loaded), so it isn't removed — reload the table if this doesn't clear.`}),x.length>0&&a.jsxs(V,{size:200,className:e.note,children:["Also using Mscrm.OpenRecordItem here:"," ",x.map(C=>C.button.id).join(", "),". Turning the override off keeps ",x.length===1?"it":"them"," ","and the command."]}),y&&a.jsx(V,{size:200,className:e.note,children:"This location has no group to put the button in."})]}),t==="Form"&&a.jsxs(V,{size:200,className:e.note,children:["Changes apply to every main form of this table."," ",a.jsx(Et,{size:"small",info:"Unified Interface doesn't support a ribbon for one form only, so Command Bar Studio changes the table's form ribbon, which all its main forms use.",infoButton:{"aria-label":"Why every form"}})]})]})},Uw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,minWidth:0},id:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200},pending:{textDecoration:"line-through",color:h.colorNeutralForeground3}});function Vw(){const e=Uw(),t=M(i=>i.layers),n=M(i=>i.pendingUnhides),o=M(i=>i.setLayerHideUnhidden),s=["entity","application"].flatMap(i=>(t[i]?.hides??[]).map(l=>({scope:i,...l})));return s.length===0?null:a.jsxs("section",{className:e.root,"aria-label":"Hidden by customizations",children:[a.jsx(V,{as:"h3",size:300,weight:"semibold",children:"Hidden by customizations"}),a.jsx(Qe,{children:"Hidden by a HideCustomAction in your unmanaged customizations, so they aren't on the canvas. Un-hiding takes effect when you publish; reload afterwards to see them."}),s.map(i=>{const l=n[i.scope].includes(i.location);return a.jsxs("div",{className:e.row,children:[a.jsx(Bt,{}),a.jsx(pe,{content:`${i.location} (${i.scope==="entity"?"this table":"application ribbon"})`,relationship:"description",children:a.jsx(V,{className:`${e.id} ${l?e.pending:""}`,children:i.location})}),a.jsx(K,{size:"small",appearance:l?"subtle":"secondary",onClick:()=>o(i.scope,i.location,!l),children:l?"Keep hidden":"Unhide"})]},`${i.scope}:${i.location}`)})]})}const Xw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"flex-start",gap:h.spacingHorizontalS,minWidth:0},icon:{flexShrink:0,marginTop:"2px",color:h.colorPaletteMarigoldForeground1},text:{display:"flex",flexDirection:"column",flex:1,minWidth:0},mono:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200},why:{color:h.colorNeutralForeground3},pending:{textDecoration:"line-through",color:h.colorNeutralForeground3}});function Kw(){const e=Xw(),t=M(r=>r.orphans),n=M(r=>r.pendingOrphanDeletes),o=M(r=>r.setOrphanDeleted),[s,i]=E.useState(null),l=["entity","application"].flatMap(r=>t[r].map(c=>({scope:r,...c})));return l.length===0?null:a.jsxs("section",{className:e.root,"aria-label":"Orphaned customizations",children:[a.jsx(V,{as:"h3",size:300,weight:"semibold",children:"Orphaned customizations"}),a.jsx(Qe,{children:"In your unmanaged customizations, but the ribbon doesn't return them, so they aren't on the canvas (and, except for tabs, Unified Interface doesn't show them either). Publishing keeps them unless you delete them. For a while after a publish the ribbon can still be the one from before it (10 minutes or more), so what you just published can show up here: don't delete it, reload later."}),l.map(r=>{const c=n[r.scope].includes(r.id),d=r.label&&r.label!==r.id?`“${r.label}” `:"",u=`${r.scope}:${r.id}`,p=!!r.recentPublish?.published,m=c?a.jsx(K,{size:"small",appearance:"subtle","aria-label":`Keep ${r.id}`,onClick:()=>o(r.scope,r.id,!1),children:"Keep"}):p?a.jsx(pe,{content:"Published from here moments ago: reload later — it most likely isn't loaded yet",relationship:"description",children:a.jsx(K,{size:"small",disabledFocusable:!0,"aria-label":`Delete ${r.id}`,children:"Delete"})}):r.recentPublish?a.jsx(K,{size:"small",appearance:"secondary","aria-label":`Delete ${r.id}`,onClick:()=>i({scope:r.scope,id:r.id,minutesAgo:r.recentPublish?.minutesAgo}),children:"Delete…"}):a.jsx(K,{size:"small",appearance:"secondary","aria-label":`Delete ${r.id}`,onClick:()=>o(r.scope,r.id,!0),children:"Delete"});return a.jsxs("div",{className:e.row,children:[a.jsx(ag,{className:e.icon}),a.jsxs("div",{className:e.text,children:[a.jsx(pe,{content:`${r.element} ${r.id} — CustomAction ${r.customActionId} at ${r.location}`,relationship:"description",children:a.jsxs(V,{className:Ie(e.mono,c&&e.pending),children:[d,r.id]})}),a.jsx(Qe,{className:Ie(e.mono,e.why),children:r.location}),a.jsx(Qe,{className:e.why,children:r.why})]}),m]},u)}),s&&a.jsxs(Ln,{open:!0,title:"Delete a recent customization?",confirmLabel:"Delete anyway",destructive:!0,onConfirm:()=>{o(s.scope,s.id,!0),i(null)},onCancel:()=>i(null),children:[s.id," was published",s.minutesAgo!==void 0?` about ${s.minutesAgo} minute${s.minutesAgo===1?"":"s"} ago`:" recently",". The ribbon may not show it yet, so it may not be orphaned at all. Reload the table later to check before deleting it."]})]})}const Yw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS},field:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},mono:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,overflowWrap:"anywhere"},xml:{margin:0,maxHeight:"240px",overflow:"auto",padding:h.spacingHorizontalS,borderRadius:h.borderRadiusMedium,backgroundColor:h.colorNeutralBackground3,fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,whiteSpace:"pre-wrap",overflowWrap:"anywhere"}});function Jw({button:e,location:t,tabId:n,groupId:o}){const s=Yw(),i=M(f=>f.locLabels),l=De(),r=M(f=>f.setButtonProp),c=M(f=>f.hideOobButton),d=M(f=>f.hideWithDisplayRules),[u,p]=E.useState(!1),m=t==="Application"&&n==="Mscrm.GlobalTab"&&e.oob&&!e.custom,g=xt[e.kind],b=(f,y)=>y?a.jsxs("div",{className:s.field,children:[a.jsx(Qe,{children:f}),a.jsx(V,{className:s.mono,children:y})]}):null;return a.jsxs("section",{className:s.root,"aria-label":`${g} (read-only)`,children:[a.jsxs("div",{className:s.title,children:[a.jsx(un,{"aria-hidden":!0}),a.jsx(V,{as:"h3",size:300,weight:"semibold",children:"Shown read-only"})]}),a.jsxs(Qe,{children:["Command Bar Studio shows this <",wn[e.kind],"> but doesn't edit it. You can hide it, and move or delete it when your customizations add it; its XML is published as it was loaded."]}),b("Label",l(e.label,i,void 0,e.source?.labelToken)),b("Id",e.id),b("Command",e.commandId||void 0),a.jsx("div",{children:a.jsx(K,{size:"small",disabled:m,icon:e.hidden?a.jsx(Dn,{}):a.jsx(Bt,{}),onClick:()=>!e.hidden&&e.oob?p(!0):r(t,n,o,e.id,{hidden:!e.hidden}),children:e.hidden?"Unhide":"Hide"})}),u&&a.jsx(cu,{open:!0,buttonLabel:l(e.label,i,void 0,e.source?.labelToken),buttonId:e.id,commandId:e.commandId,onConfirmHide:()=>{c(t,n,o,e.id),p(!1)},onConfirmDisplayRule:()=>{d(e.commandId),p(!1)},onCancel:()=>p(!1)}),e.source?.xml&&a.jsxs("div",{className:s.field,children:[a.jsx(Qe,{children:"XML"}),a.jsx("pre",{className:s.xml,children:e.source.xml})]})]})}const Uu=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,flexWrap:"wrap"},grid:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:h.spacingHorizontalM,rowGap:h.spacingVerticalXS,alignItems:"baseline"},key:{color:h.colorNeutralForeground3,fontSize:h.fontSizeBase200},value:{fontSize:h.fontSizeBase200,overflowWrap:"anywhere",minWidth:0},mono:{fontFamily:h.fontFamilyMonospace},list:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS}});function kt({label:e,value:t,mono:n}){const o=Uu();return t?a.jsxs(a.Fragment,{children:[a.jsx(V,{className:o.key,children:e}),a.jsx(V,{className:`${o.value} ${n?o.mono:""}`,children:t})]}):null}function Zw({command:e,items:t}){const n=Uu(),o=zn(),s=we(r=>r.selectCommand),i=we(r=>e.parentId?r.commands.find(c=>c.id===e.parentId):void 0),l=e.visibility==="formula"||e.action==="formula";return a.jsxs("section",{className:n.root,"aria-label":"Modern command properties",children:[a.jsxs("div",{className:n.title,children:[a.jsx(rg,{children:e.label}),a.jsx(xe,{appearance:"tint",color:"important",children:"Modern"}),e.managed&&a.jsx(xe,{appearance:"outline",color:"informative",children:"Managed"})]}),a.jsx($t,{intent:"info",children:a.jsx(Tt,{children:"Modern commands are read-only in Command Bar Studio and are never published from here. Edit them in the command designer."})}),a.jsxs("div",{className:n.grid,children:[Au(e,o).map(r=>a.jsx(kt,{label:r.label,value:r.value},r.label)),a.jsx(kt,{label:"Tooltip title",value:e.tooltipTitle}),a.jsx(kt,{label:"Tooltip text",value:e.tooltipDescription}),a.jsx(kt,{label:"Accessibility text",value:e.accessibilityText}),a.jsx(kt,{label:"Icon",value:e.fontIcon??e.iconWebResourceName??e.iconWebResourceId}),a.jsx(kt,{label:"Group title",value:e.groupTitle}),a.jsx(kt,{label:"Name",value:e.name}),a.jsx(kt,{label:"Unique name",value:e.uniqueName,mono:!0}),a.jsx(kt,{label:"Id",value:e.id,mono:!0})]}),l&&a.jsx(Qe,{children:"Power Fx formulas are stored in the app's command component library, not on the command, so only the function reference is shown here."}),i&&a.jsxs(a.Fragment,{children:[a.jsx(Lo,{}),a.jsx(V,{className:n.key,children:"Inside"}),a.jsx(Tn,{onClick:()=>s(i.id),children:i.label})]}),t.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Lo,{}),a.jsxs(V,{className:n.key,children:["Items (",t.length,")"]}),a.jsx("div",{className:n.list,children:t.map(r=>a.jsxs(Tn,{onClick:()=>s(r.id),children:[r.label,r.hidden?" (hidden)":""]},r.id))})]}),e.classicRules.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Lo,{}),a.jsxs(V,{className:n.key,children:["Classic rules (",e.classicRules.length,")"]}),a.jsx("div",{className:n.list,children:e.classicRules.map(r=>a.jsxs(V,{className:`${n.value} ${n.mono}`,children:[r.kind==="enable"?"Enable":"Display",":"," ",r.uniqueName??r.name]},r.id))})]})]})}const Qw=me({slot:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`},list:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS}});function eC({button:e,location:t,tabId:n,groupId:o,overrides:s}){const i=Qw(),l=M(x=>x.customizeOobButton),r=M(x=>x.customiseButton),c=M(x=>x.conflicts),d=ae(x=>x.activeSolution),u=ae(x=>x.publisherPrefix),p=Y(x=>x.selectButtonInContext),m=zn(),g=we(x=>x.selectCommand),b=Wa(t,n,e),f=[],y=dt(e.kind);if(e.origin==="managed"||e.origin==="oob"&&!y){const x=c.find(T=>T.elementId===e.id),v=e.solutionName??x?.solutions[0]?.solutionName,C=e.publisherName??x?.solutions[0]?.publisher,$=e.origin==="oob"?"Out-of-the-box button":`From the managed solution${v?` ${v}`:""}${C?` by ${C}`:""}`,A=y?void 0:"You can't edit it directly: customise a copy, or create an override, to change it.",j=a.jsxs(a.Fragment,{children:[!y&&b&&a.jsx(K,{size:"small",onClick:()=>{const T=d?.publisherPrefix?.trim()||u?.trim()||"new",R=r(t,n,o,e.id,T);R&&p(t,n,o,R)},children:"Customise button"}),!y&&a.jsx(K,{size:"small",onClick:()=>l(t,n,o,e.id),children:"Create override"})]});f.push({id:"provenance",intent:"info",title:$,body:A,dismissible:!1,actions:j})}if(s.length>0){const x=s.some(v=>v.effect==="hidden");f.push({id:"modern-override",intent:x?"warning":"info",title:x?"Hidden by a modern command":"Shown as a modern command",dismissible:!1,body:a.jsxs("div",{className:i.list,children:[s.map(v=>a.jsxs("span",{children:[tr(v,m),"."," ",a.jsx(Tn,{inline:!0,onClick:()=>g(v.command.id),children:"View"})]},v.command.id)),a.jsx(Qe,{children:"Matched by the migrated command's unique name. Unified Interface may show the modern command instead of this button."})]})})}return f.length===0?null:a.jsx(Xa,{scope:"properties",messages:f,className:i.slot})}const tC=me({header:{position:"sticky",top:0,zIndex:1,display:"flex",alignItems:"center",gap:h.spacingHorizontalS,minHeight:"52px",padding:`${h.spacingVerticalS} ${h.spacingHorizontalS} ${h.spacingVerticalS} ${h.spacingHorizontalM}`,backgroundColor:h.colorNeutralBackground2,borderBottom:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0},tile:{width:"36px",height:"36px",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:h.borderRadiusMedium,backgroundColor:h.colorNeutralBackground1,border:`1px solid ${h.colorNeutralStroke2}`},text:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS},label:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},badges:{display:"flex",flexWrap:"wrap",gap:h.spacingHorizontalXS},badge:{flexShrink:0,maxWidth:"100%"},badgeText:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function nC(e){return e.origin==="unmanaged"?{text:"Yours",color:"brand"}:e.origin==="managed"?{text:e.solutionName?`Managed · ${e.solutionName}`:"Managed",color:"informative"}:{text:"Out of the box",color:"informative"}}function oC({button:e}){const t=tC(),{onClose:n}=E.useContext(iu),o=Y(u=>u.clearSelection),s=M(u=>u.locLabels),i=De(),l=n?{label:"Close properties",run:n}:e?{label:"Clear selection",run:o}:void 0,r=l&&a.jsx(pe,{content:l.label,relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:a.jsx(cn,{}),onClick:l.run})});if(!e)return a.jsxs("div",{className:t.header,children:[a.jsx(V,{size:400,weight:"semibold",className:t.text,children:"Properties"}),r]});const c=i(e.label,s,void 0,e.source?.labelToken)||e.id,d=nC(e);return a.jsxs("div",{className:t.header,children:[a.jsx("div",{className:t.tile,"aria-hidden":!0,children:a.jsx(vt,{button:e,size:20})}),a.jsxs("div",{className:t.text,children:[a.jsx(pe,{content:c,relationship:"description",children:a.jsx(V,{as:"h2",size:400,weight:"semibold",className:t.label,tabIndex:0,children:c})}),a.jsxs("div",{className:t.badges,children:[a.jsx(xe,{size:"medium",appearance:"tint",color:d.color,className:t.badge,children:a.jsx("span",{className:t.badgeText,children:d.text})}),a.jsx(xe,{size:"medium",appearance:"outline",color:"informative",className:t.badge,children:xt[e.kind]})]})]}),r]})}const sC="Mscrm.HideOnModern",iC="Mscrm.ShowOnlyOnModern";function Vu(e,t){if(e===sC)return"classic";if(e===iC)return"uci";const n=t?.steps.length===1?t.steps[0]:void 0;if(!(n?.kind!=="CommandClientTypeRule"||n.default!==void 0))return n.type==="Modern"?n.invertResult?"classic":"uci":n.type==="Refresh"&&!n.invertResult?"classic":"other"}function aC(e,t){const n=e.displayRules.map(o=>Vu(o,t.find(s=>s.id===o))).filter(o=>o!==void 0);return n.length===0?"all":n.length===1&&n[0]!=="other"?n[0]:"custom"}const rC=me({group:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS}});function lC({button:e}){const t=rC(),n=De(),o=M(v=>v.commands),s=M(v=>v.displayRules),i=M(v=>v.ribbons),l=Y(v=>v.location),r=M(v=>v.locLabels),c=M(v=>v.upsertCommand),d=M(v=>v.upsertDisplayRule),u=M(v=>v.batch),p=Os(e.commandId||void 0),m=o.find(v=>v.id===e.commandId);if(!m)return a.jsx(_e,{label:"Show on",hint:"Bind a command first: where a button shows is set on its command.",children:a.jsx(vi,{disabled:!0,value:"all",children:a.jsx(sn,{value:"all",label:"All clients"})})});const g=aC(m,s),b=p?.provenance==="custom"||p?.provenance==="customising"||p?.provenance==="customised",f=od(i,m.id,e.id,v=>n(v.label,r,void 0,v.source?.labelToken),l),y=v=>{const C=m.displayRules.filter(R=>Vu(R,s.find(I=>I.id===R))===void 0);if(v==="all"){c({...m,displayRules:C});return}const $=v==="uci"?"Modern":"Refresh",A=s.find(R=>R.steps.length===1&&R.steps[0].kind==="CommandClientTypeRule"&&R.steps[0].type===$&&!R.steps[0].invertResult&&R.steps[0].default===void 0);let j=A?.id??`${m.id}.${$}.DisplayRule`;for(let R=1;!A&&s.some(I=>I.id===j);R++)j=`${m.id}.${$}.DisplayRule.${R}`;const T={kind:"CommandClientTypeRule",type:$};u(()=>{A||d({id:j,steps:[T]}),c({...m,displayRules:[...C,j]})})},x=b?f.length>0?`Also changes ${f.length===1?"1 other button":`${f.length} other buttons`} that use${f.length===1?"s":""} this command: ${f.slice(0,3).join(", ")}${f.length>3?", …":""}.`:"Set by display rules on the button's command.":"Customise the command to change where it shows.";return a.jsx(_e,{label:"Show on",hint:x,children:a.jsxs(vi,{className:t.group,value:g,disabled:!b,onChange:(v,C)=>C.value!=="custom"&&y(C.value),children:[a.jsx(sn,{value:"all",label:"All clients"}),a.jsx(sn,{value:"uci",label:"Unified Interface only"}),a.jsx(sn,{value:"classic",label:"Classic web client only (not shown in Unified Interface)"}),g==="custom"&&a.jsx(sn,{value:"custom",label:"Custom: see Display rules",disabled:!0})]})})}const cC=me({item:{borderBottom:`1px solid ${h.colorNeutralStroke3}`},headerRow:{display:"flex",alignItems:"center",paddingRight:h.spacingHorizontalS},header:{flex:1,minWidth:0,fontWeight:h.fontWeightSemibold},count:{marginLeft:h.spacingHorizontalXS},panel:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,margin:0,padding:`0 ${h.spacingHorizontalL} ${h.spacingVerticalM}`,minWidth:0}}),dC=({storageKey:e,defaultOpen:t,children:n})=>{const[o,s]=E.useState(()=>ou(`sections.${e}`,t)),i=(l,r)=>{const c=r.openItems.map(String);s(c),su(`sections.${e}`,c)};return a.jsx(wc,{multiple:!0,collapsible:!0,openItems:o,onToggle:i,children:n})},en=({value:e,title:t,info:n,count:o,children:s})=>{const i=cC();return a.jsxs(Cc,{value:e,className:i.item,children:[a.jsxs("div",{className:i.headerRow,children:[a.jsxs(Ic,{size:"small",className:i.header,children:[t,!!o&&a.jsx(xn,{count:o,size:"medium",appearance:"ghost",color:"informative",className:i.count})]}),n&&a.jsx(Et,{info:n,infoButton:{"aria-label":`About ${t}`}})]}),a.jsx(jc,{className:i.panel,children:s})]})},uC=me({root:{display:"flex",flexDirection:"column",height:"100%",overflowY:"auto",overflowX:"hidden",backgroundColor:h.colorNeutralBackground2},empty:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:h.spacingHorizontalM,color:h.colorNeutralForeground3,padding:h.spacingHorizontalXL,textAlign:"center"},place:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`,color:h.colorNeutralForeground2}});function mC(){const e=uC(),t=Y(y=>y.selectedButtonId),n=Y(y=>y.selectedGroupId),o=Y(y=>y.location),s=Y(y=>y.tabId),c=M(y=>y.ribbons)[o].tabs.find(y=>y.id===s)?.groups.find(y=>y.id===n),d=Ss(c,t),u=c&&d?Yo(c,d.id):void 0,p=M(y=>y.locLabels),m=De(),g=VS(),b=GS(o,d?.id),f=M(y=>d?.commandId?y.commands.find(x=>x.id===d.commandId):void 0);return a.jsxs("aside",{className:e.root,"aria-label":"Properties",children:[a.jsx(oC,{button:d}),!d&&g?a.jsx(Zw,{command:g.command,items:g.children}):d?a.jsxs(a.Fragment,{children:[a.jsx(eC,{button:d,location:o,tabId:s,groupId:n,overrides:b}),u&&a.jsxs(Qe,{className:e.place,children:["Menu item of “",m(u.parent.label,p,void 0,u.parent.source?.labelToken),"”",u.section.title?` — section “${u.section.title}”`:""]}),dt(d.kind)?a.jsx(Jw,{button:d,location:o,tabId:s,groupId:n}):a.jsxs(dC,{storageKey:"properties.button",defaultOpen:["appearance","position","command","display","enable"],children:[a.jsxs(en,{value:"appearance",title:"Appearance",children:[a.jsx(ci,{part:"appearance",button:d,location:o,tabId:s,groupId:n}),a.jsx(lC,{button:d})]}),a.jsx(en,{value:"position",title:"Position",children:a.jsx(ci,{part:"position",button:d,location:o,tabId:s,groupId:n})}),a.jsx(en,{value:"command",title:"Command",children:a.jsx(Ew,{button:d,groupId:n,tabId:s,location:o})}),a.jsx(en,{value:"display",title:"Display rules",count:f?.displayRules.length,info:"All of them must pass for the button to show.",children:a.jsx(Fw,{})}),a.jsx(en,{value:"enable",title:"Enable rules",count:f?.enableRules.length,info:"All of them must pass for the button to be enabled. Unified Interface hides a button that isn't enabled.",children:a.jsx(_w,{})}),a.jsx(en,{value:"scaling",title:"Scaling",info:"Scaling only applies to the classic ribbon. Unified Interface ignores it.",children:a.jsx(Ww,{})}),a.jsxs(en,{value:"advanced",title:"Advanced",children:[a.jsx(ci,{part:"advanced",button:d,location:o,tabId:s,groupId:n}),a.jsx(Gw,{})]})]},`${n}|${d.id}`)]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.empty,children:[a.jsx(lg,{fontSize:32,style:{opacity:.4}}),a.jsx(V,{size:300,children:"Select a button to view its properties"})]}),a.jsx(Vw,{}),a.jsx(Kw,{})]})]})}function Xu(e,t){const n=new Map,o=l=>{l&&n.set(l,(n.get(l)??0)+1)};for(const l of Object.keys(e))for(const r of e[l].tabs){o(r.commandId);for(const c of r.groups){o(c.source?.attributes.Command);for(const d of Te(c))o(d.commandId),o(d.source?.attributes.PopulateQueryCommand)}}const s=new Map,i=new Map;for(const l of t){for(const r of new Set(l.enableRules))s.set(r,(s.get(r)??0)+1);for(const r of new Set(l.displayRules))i.set(r,(i.get(r)??0)+1)}return{byCommand:n,byEnable:s,byDisplay:i}}const pC=e=>(cg({...e,renderRow:()=>null}),e),Ku=E.createContext(void 0),fC=void 0,hC=()=>{var e;return(e=E.useContext(Ku))!=null?e:fC},gC=Ku.Provider,Yu=E.createContext({current:null}),bC={current:null},Ju=()=>{var e;return(e=E.useContext(Yu))!=null?e:bC},yC=Yu.Provider,Zu=E.createContext({current:null}),xC={current:null},Qu=()=>{var e;return(e=E.useContext(Zu))!=null?e:xC},vC=Zu.Provider,SC=(e,t)=>{const{height:n,itemSize:o,width:s="100%",ariaRowIndexStart:i=2,children:l,listProps:r}=e,c=Ju(),d=Qu(),p=dg({...e,children:l},t),m=E.useCallback(({data:f,index:y,style:x,isScrolling:v})=>{const C=f[y];return E.createElement(gC,{value:i+y},E.createElement(ug,{value:C.rowId},l(C,x,y,v)))},[i,l]),g=E.useCallback(()=>{c.current&&d.current&&d.current.scroll({left:c.current.scrollLeft,behavior:"instant"})},[]),b=E.useCallback(f=>{var y;(y=c.current)==null||y.removeEventListener("scroll",g),c.current=f,f&&f.addEventListener("scroll",g)},[]);return{...p,itemSize:o,height:n,virtualizedRow:m,width:s,ariaRowIndexStart:i,listProps:r,outerRef:b}};function oa(){return oa=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},oa.apply(null,arguments)}function jl(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function sa(e,t){return sa=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,o){return n.__proto__=o,n},sa(e,t)}function wC(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,sa(e,t)}var Rl=Number.isNaN||function(t){return typeof t=="number"&&t!==t};function CC(e,t){return!!(e===t||Rl(e)&&Rl(t))}function IC(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!CC(e[n],t[n]))return!1;return!0}function di(e,t){t===void 0&&(t=IC);var n,o=[],s,i=!1;function l(){for(var r=[],c=0;c<arguments.length;c++)r[c]=arguments[c];return i&&n===this&&t(r,o)||(s=e.apply(this,r),i=!0,n=this,o=r),s}return l}var jC=typeof performance=="object"&&typeof performance.now=="function",$l=jC?function(){return performance.now()}:function(){return Date.now()};function Tl(e){cancelAnimationFrame(e.id)}function RC(e,t){var n=$l();function o(){$l()-n>=t?e.call(null):s.id=requestAnimationFrame(o)}var s={id:requestAnimationFrame(o)};return s}var ui=-1;function Nl(e){if(e===void 0&&(e=!1),ui===-1||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",document.body.appendChild(t),ui=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return ui}var yn=null;function kl(e){if(e===void 0&&(e=!1),yn===null||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",n.direction="rtl";var o=document.createElement("div"),s=o.style;return s.width="100px",s.height="100px",t.appendChild(o),document.body.appendChild(t),t.scrollLeft>0?yn="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?yn="negative":yn="positive-ascending"),document.body.removeChild(t),yn}return yn}var $C=150,TC=function(t,n){return t};function NC(e){var t,n=e.getItemOffset,o=e.getEstimatedTotalSize,s=e.getItemSize,i=e.getOffsetForIndexAndAlignment,l=e.getStartIndexForOffset,r=e.getStopIndexForStartIndex,c=e.initInstanceProps,d=e.shouldResetStyleCacheOnItemSizeChange,u=e.validateProps;return t=(function(p){wC(m,p);function m(b){var f;return f=p.call(this,b)||this,f._instanceProps=c(f.props,jl(f)),f._outerRef=void 0,f._resetIsScrollingTimeoutId=null,f.state={instance:jl(f),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof f.props.initialScrollOffset=="number"?f.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},f._callOnItemsRendered=void 0,f._callOnItemsRendered=di(function(y,x,v,C){return f.props.onItemsRendered({overscanStartIndex:y,overscanStopIndex:x,visibleStartIndex:v,visibleStopIndex:C})}),f._callOnScroll=void 0,f._callOnScroll=di(function(y,x,v){return f.props.onScroll({scrollDirection:y,scrollOffset:x,scrollUpdateWasRequested:v})}),f._getItemStyle=void 0,f._getItemStyle=function(y){var x=f.props,v=x.direction,C=x.itemSize,$=x.layout,A=f._getItemStyleCache(d&&C,d&&$,d&&v),j;if(A.hasOwnProperty(y))j=A[y];else{var T=n(f.props,y,f._instanceProps),R=s(f.props,y,f._instanceProps),I=v==="horizontal"||$==="horizontal",N=v==="rtl",B=I?T:0;A[y]=j={position:"absolute",left:N?void 0:B,right:N?B:void 0,top:I?0:T,height:I?"100%":R,width:I?R:"100%"}}return j},f._getItemStyleCache=void 0,f._getItemStyleCache=di(function(y,x,v){return{}}),f._onScrollHorizontal=function(y){var x=y.currentTarget,v=x.clientWidth,C=x.scrollLeft,$=x.scrollWidth;f.setState(function(A){if(A.scrollOffset===C)return null;var j=f.props.direction,T=C;if(j==="rtl")switch(kl()){case"negative":T=-C;break;case"positive-descending":T=$-v-C;break}return T=Math.max(0,Math.min(T,$-v)),{isScrolling:!0,scrollDirection:A.scrollOffset<T?"forward":"backward",scrollOffset:T,scrollUpdateWasRequested:!1}},f._resetIsScrollingDebounced)},f._onScrollVertical=function(y){var x=y.currentTarget,v=x.clientHeight,C=x.scrollHeight,$=x.scrollTop;f.setState(function(A){if(A.scrollOffset===$)return null;var j=Math.max(0,Math.min($,C-v));return{isScrolling:!0,scrollDirection:A.scrollOffset<j?"forward":"backward",scrollOffset:j,scrollUpdateWasRequested:!1}},f._resetIsScrollingDebounced)},f._outerRefSetter=function(y){var x=f.props.outerRef;f._outerRef=y,typeof x=="function"?x(y):x!=null&&typeof x=="object"&&x.hasOwnProperty("current")&&(x.current=y)},f._resetIsScrollingDebounced=function(){f._resetIsScrollingTimeoutId!==null&&Tl(f._resetIsScrollingTimeoutId),f._resetIsScrollingTimeoutId=RC(f._resetIsScrolling,$C)},f._resetIsScrolling=function(){f._resetIsScrollingTimeoutId=null,f.setState({isScrolling:!1},function(){f._getItemStyleCache(-1,null)})},f}m.getDerivedStateFromProps=function(f,y){return kC(f,y),u(f),null};var g=m.prototype;return g.scrollTo=function(f){f=Math.max(0,f),this.setState(function(y){return y.scrollOffset===f?null:{scrollDirection:y.scrollOffset<f?"forward":"backward",scrollOffset:f,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},g.scrollToItem=function(f,y){y===void 0&&(y="auto");var x=this.props,v=x.itemCount,C=x.layout,$=this.state.scrollOffset;f=Math.max(0,Math.min(f,v-1));var A=0;if(this._outerRef){var j=this._outerRef;C==="vertical"?A=j.scrollWidth>j.clientWidth?Nl():0:A=j.scrollHeight>j.clientHeight?Nl():0}this.scrollTo(i(this.props,f,y,$,this._instanceProps,A))},g.componentDidMount=function(){var f=this.props,y=f.direction,x=f.initialScrollOffset,v=f.layout;if(typeof x=="number"&&this._outerRef!=null){var C=this._outerRef;y==="horizontal"||v==="horizontal"?C.scrollLeft=x:C.scrollTop=x}this._callPropsCallbacks()},g.componentDidUpdate=function(){var f=this.props,y=f.direction,x=f.layout,v=this.state,C=v.scrollOffset,$=v.scrollUpdateWasRequested;if($&&this._outerRef!=null){var A=this._outerRef;if(y==="horizontal"||x==="horizontal")if(y==="rtl")switch(kl()){case"negative":A.scrollLeft=-C;break;case"positive-ascending":A.scrollLeft=C;break;default:var j=A.clientWidth,T=A.scrollWidth;A.scrollLeft=T-j-C;break}else A.scrollLeft=C;else A.scrollTop=C}this._callPropsCallbacks()},g.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&Tl(this._resetIsScrollingTimeoutId)},g.render=function(){var f=this.props,y=f.children,x=f.className,v=f.direction,C=f.height,$=f.innerRef,A=f.innerElementType,j=f.innerTagName,T=f.itemCount,R=f.itemData,I=f.itemKey,N=I===void 0?TC:I,B=f.layout,O=f.outerElementType,S=f.outerTagName,k=f.style,w=f.useIsScrolling,D=f.width,F=this.state.isScrolling,X=v==="horizontal"||B==="horizontal",ne=X?this._onScrollHorizontal:this._onScrollVertical,re=this._getRangeToRender(),le=re[0],_=re[1],L=[];if(T>0)for(var U=le;U<=_;U++)L.push(E.createElement(y,{data:R,key:N(U,R),index:U,isScrolling:w?F:void 0,style:this._getItemStyle(U)}));var W=o(this.props,this._instanceProps);return E.createElement(O||S||"div",{className:x,onScroll:ne,ref:this._outerRefSetter,style:oa({position:"relative",height:C,width:D,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:v},k)},E.createElement(A||j||"div",{children:L,ref:$,style:{height:X?"100%":W,pointerEvents:F?"none":void 0,width:X?W:"100%"}}))},g._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var f=this.props.itemCount;if(f>0){var y=this._getRangeToRender(),x=y[0],v=y[1],C=y[2],$=y[3];this._callOnItemsRendered(x,v,C,$)}}if(typeof this.props.onScroll=="function"){var A=this.state,j=A.scrollDirection,T=A.scrollOffset,R=A.scrollUpdateWasRequested;this._callOnScroll(j,T,R)}},g._getRangeToRender=function(){var f=this.props,y=f.itemCount,x=f.overscanCount,v=this.state,C=v.isScrolling,$=v.scrollDirection,A=v.scrollOffset;if(y===0)return[0,0,0,0];var j=l(this.props,A,this._instanceProps),T=r(this.props,j,A,this._instanceProps),R=!C||$==="backward"?Math.max(1,x):1,I=!C||$==="forward"?Math.max(1,x):1;return[Math.max(0,j-R),Math.max(0,Math.min(y-1,T+I)),j,T]},m})(E.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var kC=function(t,n){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,n.instance},AC=NC({getItemOffset:function(t,n){var o=t.itemSize;return n*o},getItemSize:function(t,n){var o=t.itemSize;return o},getEstimatedTotalSize:function(t){var n=t.itemCount,o=t.itemSize;return o*n},getOffsetForIndexAndAlignment:function(t,n,o,s,i,l){var r=t.direction,c=t.height,d=t.itemCount,u=t.itemSize,p=t.layout,m=t.width,g=r==="horizontal"||p==="horizontal",b=g?m:c,f=Math.max(0,d*u-b),y=Math.min(f,n*u),x=Math.max(0,n*u-b+u+l);switch(o==="smart"&&(s>=x-b&&s<=y+b?o="auto":o="center"),o){case"start":return y;case"end":return x;case"center":{var v=Math.round(x+(y-x)/2);return v<Math.ceil(b/2)?0:v>f+Math.floor(b/2)?f:v}default:return s>=x&&s<=y?s:s<x?x:y}},getStartIndexForOffset:function(t,n){var o=t.itemCount,s=t.itemSize;return Math.max(0,Math.min(o-1,Math.floor(n/s)))},getStopIndexForStartIndex:function(t,n,o){var s=t.direction,i=t.height,l=t.itemCount,r=t.itemSize,c=t.layout,d=t.width,u=s==="horizontal"||c==="horizontal",p=n*r,m=u?d:i,g=Math.ceil((m+o-p)/r);return Math.max(0,Math.min(l-1,n+g-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.itemSize}});const OC=e=>{const{slots:t,slotProps:n}=mg(e),{dir:o}=$c();return E.createElement(t.root,n.root,E.createElement(AC,{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))},em=E.forwardRef((e,t)=>{const n=SC(e,t);return pC(n),OC(n)});em.displayName="DataGridBody";const MC=(e,t)=>{var n;const{targetDocument:o}=$c(),s=pg({targetDocument:o}),i=E.useRef(null),l=E.useRef(null);let r=e.containerWidthOffset;r===void 0&&(r=e.selectionMode?-44:0,r-=s||0);const c=fg({...e,"aria-rowcount":e.items.length,containerWidthOffset:r},t);return e.resizableColumns&&((n=e.resizableColumnsOptions)==null?void 0:n.autoFitColumns)===!1&&c.root.style&&(c.root.style.minWidth="auto"),{...c,headerRef:i,bodyRef:l}},DC=(e,t)=>E.createElement(vC,{value:e.headerRef},E.createElement(yC,{value:e.bodyRef},hg(e,t))),tm=E.forwardRef((e,t)=>{const n=MC(e,t);return gg(n),DC(n,bg(n))});tm.displayName="DataGrid";const EC=(e,t)=>{const n=hC();return yg({...e,"aria-rowindex":n},t)},BC=me({root:{minWidth:"fit-content"}}),LC=e=>{const t=BC();return e.root.className=Ie(t.root,e.root.className),xg(e),e},ir=E.forwardRef((e,t)=>{const n=EC(e,t);return LC(n),vg(n)});ir.displayName="DataGridRow";const zC=(e,t)=>{const n=Ju(),o=Qu(),s=E.useCallback(()=>{n.current&&o.current&&n.current.scroll({left:o.current.scrollLeft,behavior:"instant"})},[]),i=E.useCallback(r=>{var c;(c=o.current)==null||c.removeEventListener("scroll",s),o.current=r,r&&r.addEventListener("scroll",s)},[]),l=Sg(e,t);return l.root.ref=wg(l.root.ref,i),l},PC=me({root:{overflowX:"auto",scrollbarWidth:"none","::-webkit-scrollbar":{width:0,height:0}}}),FC=e=>{const t=PC();return e.root.className=Ie(t.root,e.root.className),Cg(e),e},nm=E.forwardRef((e,t)=>{const n=zC(e,t);return FC(n),Ig(n)});nm.displayName="DataGridHeader";const _C=new Set(["mscrm","command","commands","enablerule","enablerules","displayrule","displayrules","rule","button","customaction","template","templates"]);function Wo(e){const t=e.split(".").filter(Boolean);for(let n=t.length-1;n>=0;n--)if(!_C.has(t[n].toLowerCase()))return t[n];return e}const mi=36,Co=me({row:{cursor:"pointer"},selected:{backgroundColor:h.colorSubtleBackgroundSelected,":hover":{backgroundColor:h.colorSubtleBackgroundSelected}},mono:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200},tags:{display:"flex",gap:h.spacingHorizontalXXS,minWidth:0,overflow:"hidden",whiteSpace:"nowrap"},chip:{display:"inline-flex",padding:"0 6px",borderRadius:h.borderRadiusMedium,fontSize:h.fontSizeBase200,border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground3,flexShrink:0},muted:{color:h.colorNeutralForeground3},empty:{padding:h.spacingVerticalS,color:h.colorNeutralForeground3},box:{flex:1,minHeight:0,minWidth:0,overflowX:"auto",overflowY:"auto"}}),qC={javascript:"JS",url:"URL",powerFx:"Fx",customApi:"API",outlookCommand:"Outlook",raw:"XML"},Gt=e=>a.jsx(V,{size:200,weight:"semibold",children:e}),om=(e,t)=>a.jsxs(xe,{size:"medium",appearance:"tint",color:e?"brand":"informative",children:[e??0," ",t,e===1?"":"s"]});function sm({id:e}){const t=Co();return a.jsx(pe,{content:e,relationship:"description",children:a.jsx(lo,{truncate:!0,className:t.mono,children:e})})}const im=tt.createContext(null),pi=e=>!!e.target.closest("button");function WC({item:e,rowId:t,style:n}){const o=Co(),s=tt.useContext(im),i=s.idOf(e),l=s.selected===i;return a.jsx(ir,{style:n,"aria-current":l||void 0,"data-element-row":i,className:Ie(o.row,l&&o.selected),onClick:r=>{pi(r)||s.select(i)},onDoubleClick:r=>{pi(r)||s.open(e)},onKeyDown:r=>{pi(r)||(r.key===" "?(r.preventDefault(),s.select(i)):r.key==="Enter"&&(r.preventDefault(),s.open(e)))},children:({renderCell:r})=>a.jsx(Sc,{children:r(e)})},t)}const HC=({item:e,rowId:t},n)=>a.jsx(WC,{item:e,rowId:t,style:n}),Al=34;function am({items:e,columns:t,sizing:n,idOf:o,label:s,height:i,onOpen:l,emptyText:r}){const c=Co(),[d,u]=E.useState(null),p=E.useRef(null),[m,g]=E.useState(0);E.useLayoutEffect(()=>{const x=Math.floor(p.current?.getBoundingClientRect().height??0);x!==m&&g(x)},[i,m]),E.useEffect(()=>{const x=p.current;if(!x||typeof ResizeObserver>"u")return;const v=new ResizeObserver(([C])=>g(Math.floor(C.contentRect.height)));return v.observe(x),()=>v.disconnect()},[]);const b=xc({tabBehavior:"unlimited",ignoreDefaultKeydown:{Enter:!0}}),f=E.useMemo(()=>({selected:d,select:u,open:l,idOf:o}),[d,l,o]),y=Math.max(mi,(m||i+Al)-Al);return a.jsx("div",{ref:p,className:c.box,...b,children:e.length===0?a.jsx(V,{as:"p",size:200,className:c.empty,children:r}):a.jsx(im.Provider,{value:f,children:a.jsxs(tm,{items:e,columns:t,columnSizingOptions:n,resizableColumns:!0,getRowId:o,focusMode:"composite",size:"small","aria-label":s,children:[a.jsx(nm,{children:a.jsx(ir,{children:({renderHeaderCell:x})=>a.jsx(vc,{children:x()})})}),a.jsx(em,{itemSize:mi,height:Math.min(y,e.length*mi),listProps:{width:"100%",style:{overflowX:"hidden"}},children:HC})]})})})}function Ol({id:e,onOpen:t}){return a.jsx(pe,{content:e,relationship:"description",children:a.jsx(Ca,{size:"extra-small",appearance:"outline",shape:"rounded",children:a.jsx(Ia,{onClick:t,children:Wo(e)})})})}function GC({commands:e,usage:t,height:n,onOpen:o,onOpenRule:s,emptyText:i}){const l=Co(),r=[qe({columnId:"id",renderHeaderCell:()=>Gt("Command"),renderCell:c=>a.jsx(sm,{id:c.id})}),qe({columnId:"actions",renderHeaderCell:()=>Gt("Actions"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.actions.length===0?a.jsx("span",{className:l.muted,children:"—"}):c.actions.map((d,u)=>a.jsx("span",{className:l.chip,children:qC[d.kind]??"XML"},u))})}),qe({columnId:"enable",renderHeaderCell:()=>Gt("Enable rules"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.enableRules.map(d=>a.jsx(Ol,{id:d,onOpen:()=>s(d,"enable")},d))})}),qe({columnId:"display",renderHeaderCell:()=>Gt("Display rules"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.displayRules.map(d=>a.jsx(Ol,{id:d,onOpen:()=>s(d,"display")},d))})}),qe({columnId:"used",renderHeaderCell:()=>Gt("Used by"),renderCell:c=>om(t.get(c.id),"control")}),qe({columnId:"edit",renderHeaderCell:()=>null,renderCell:c=>a.jsx(K,{appearance:"subtle",size:"small","aria-label":`Edit ${c.id}`,onClick:()=>o(c.id),children:"Edit"})})];return a.jsx(am,{items:e,columns:r,sizing:{id:{defaultWidth:260,minWidth:120},actions:{defaultWidth:84,minWidth:48},enable:{defaultWidth:180,minWidth:80},display:{defaultWidth:180,minWidth:80},used:{defaultWidth:100,minWidth:72},edit:{defaultWidth:60,minWidth:52}},idOf:c=>c.id,label:"Commands",height:n,onOpen:c=>o(c.id),emptyText:i})}function Ml({rules:e,kind:t,usage:n,height:o,onOpen:s,emptyText:i}){const l=Co(),r=[qe({columnId:"id",renderHeaderCell:()=>Gt("Rule"),renderCell:c=>a.jsx(sm,{id:c.id})}),qe({columnId:"steps",renderHeaderCell:()=>Gt("Steps"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.steps.length===0?a.jsx("span",{className:l.muted,children:"—"}):a.jsxs(a.Fragment,{children:[c.steps.slice(0,3).map((d,u)=>a.jsx("span",{className:l.chip,children:d.kind.replace(/Rule$/,"")},u)),c.steps.length>3&&a.jsxs("span",{className:Ie(l.chip,l.muted),children:["+",c.steps.length-3]})]})})}),qe({columnId:"used",renderHeaderCell:()=>Gt("Used by"),renderCell:c=>om(n.get(c.id),"command")}),qe({columnId:"edit",renderHeaderCell:()=>null,renderCell:c=>a.jsx(K,{appearance:"subtle",size:"small","aria-label":`Edit ${c.id}`,onClick:()=>s(c.id),children:"Edit"})})];return a.jsx(am,{items:e,columns:r,sizing:{id:{defaultWidth:360,minWidth:140},steps:{defaultWidth:260,minWidth:100},used:{defaultWidth:110,minWidth:80},edit:{defaultWidth:60,minWidth:52}},idOf:c=>c.id,label:t==="enable"?"Enable rules":"Display rules",height:o,onOpen:c=>s(c.id),emptyText:i})}const rm=me({root:{display:"flex",flexDirection:"column",borderTop:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground2,flexShrink:0},tabRow:{display:"flex",alignItems:"center",borderBottom:`1px solid ${h.colorNeutralStroke2}`,gap:0,paddingRight:h.spacingHorizontalS,flexShrink:0},content:{flex:1,minHeight:0,overflowY:"auto",padding:`${h.spacingHorizontalXS} ${h.spacingHorizontalM}`},gridContent:{overflow:"hidden",display:"flex",flexDirection:"column"},tabCount:{marginLeft:h.spacingHorizontalXS},toolbar:{flexShrink:0,display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,paddingBottom:h.spacingHorizontalXS,borderBottom:`1px solid ${h.colorNeutralStroke3}`,marginBottom:h.spacingHorizontalXS},historyRow:{display:"flex",alignItems:"flex-start",gap:h.spacingHorizontalS,padding:`${h.spacingHorizontalXS} 0`,borderBottom:`1px solid ${h.colorNeutralStroke3}`},historyAvatar:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:h.colorBrandBackground2,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:"2px"},historyContent:{flex:1,minWidth:0},consoleRow:{padding:"2px 0",fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,display:"flex",gap:h.spacingHorizontalS},consoleTs:{color:h.colorNeutralForeground4,flexShrink:0,fontSize:h.fontSizeBase200}}),fi="Shown once the table's ribbon is loaded.";function UC(){const e=rm(),t=je(P=>P.target!==null),n=Z(P=>P.activeBottomTab),o=Z(P=>P.setActiveBottomTab),s=Z(P=>P.bottomPanelHeight),i=Z(P=>P.bottomCollapsed),l=Z(P=>P.setBottomCollapsed),r=M(P=>P.commands),c=M(P=>P.displayRules),d=M(P=>P.enableRules),u=M(P=>P.past),p=M(P=>P.ribbons),m=M(P=>P.restore),g=ae(P=>P.currentUserName),b=ce(P=>P.entries),f=ce(P=>P.clear),y=ce(P=>P.logWarn),x=Z(P=>P.openCommandEditor),v=Z(P=>P.openRuleEditor),C=Z(P=>P.openDiffViewer),$=M(P=>P.upsertCommand),A=M(P=>P.upsertEnableRule),j=M(P=>P.upsertDisplayRule),[T,R]=E.useState(""),[I,N]=E.useState(""),[B,O]=E.useState(""),[S,k]=E.useState(""),w=E.useMemo(()=>{const P=T.toLowerCase().trim();return P?r.filter(Q=>Q.id.toLowerCase().includes(P)||Q.enableRules.some(be=>be.toLowerCase().includes(P))||Q.displayRules.some(be=>be.toLowerCase().includes(P))):r},[r,T]),D=E.useMemo(()=>{const P=I.toLowerCase().trim();return P?c.filter(Q=>Q.id.toLowerCase().includes(P)||Q.steps.some(be=>be.kind.toLowerCase().includes(P))):c},[c,I]),F=E.useMemo(()=>{const P=B.toLowerCase().trim();return P?d.filter(Q=>Q.id.toLowerCase().includes(P)||Q.steps.some(be=>be.kind.toLowerCase().includes(P))):d},[d,B]),X=E.useMemo(()=>{const P=S.toLowerCase().trim();return P?u.filter(Q=>Q.op.toLowerCase().includes(P)||Q.target.toLowerCase().includes(P)||Q.detail.toLowerCase().includes(P)||Q.userName.toLowerCase().includes(P)):u},[u,S]),ne=()=>{const P=new Set(r.map(be=>be.id)),Q=Pa("New","Command",P);$({id:Q,enableRules:[],displayRules:[],actions:[]}),x(Q)},re=()=>{const P=new Set(d.map(be=>be.id)),Q=uo("New","Enable",P);A({id:Q,steps:[]}),v(Q,"enable")},le=()=>{const P=new Set(c.map(be=>be.id)),Q=uo("New","Display",P);j({id:Q,steps:[]}),v(Q,"display")},_=E.useMemo(()=>Xu(p,r),[p,r]),L=i?32:s,U=Math.max(36,s-116),W=n==="commands"||n==="displayRules"||n==="enableRules";function te(P){return P.userName&&P.userName!=="You"?P.userName:g||"You"}return a.jsxs("div",{className:e.root,style:{height:L},children:[a.jsxs("div",{className:e.tabRow,children:[a.jsxs(wa,{selectedValue:n,onTabSelect:(P,Q)=>{o(Q.value),i&&l(!1)},size:"small",style:{flex:1},children:[a.jsxs(qt,{value:"commands",children:["Commands",a.jsx(xn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:r.length,showZero:!0,overflowCount:9999})]}),a.jsxs(qt,{value:"displayRules",children:["Display rules",a.jsx(xn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:c.length,showZero:!0,overflowCount:9999})]}),a.jsxs(qt,{value:"enableRules",children:["Enable rules",a.jsx(xn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:d.length,showZero:!0,overflowCount:9999})]}),a.jsxs(qt,{value:"history",children:["History",a.jsx(xn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:u.length,showZero:!0,overflowCount:9999})]}),a.jsx(qt,{value:"console",children:"Console"})]}),a.jsx(K,{appearance:"subtle",size:"small",icon:i?a.jsx(pc,{}):a.jsx(it,{}),onClick:()=>l(!i),"aria-label":i?"Expand panel":"Collapse panel"})]}),!i&&a.jsxs("div",{className:Ie(e.content,W&&e.gridContent),children:[n==="commands"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:ne,children:"New command"}),a.jsx(an,{size:"small",placeholder:`Filter ${r.length} command${r.length!==1?"s":""}…`,value:T,"aria-label":"Filter the commands",onChange:(P,Q)=>R(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),T&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[w.length," match",w.length!==1?"es":""]})]}),a.jsx(GC,{commands:w,usage:_.byCommand,height:U,onOpen:x,onOpenRule:v,emptyText:t?T?"No commands match.":"No commands.":fi})]}),n==="displayRules"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:le,children:"New display rule"}),a.jsx(an,{size:"small",placeholder:`Filter ${c.length} display rule${c.length!==1?"s":""}…`,value:I,"aria-label":"Filter the display rules",onChange:(P,Q)=>N(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),I&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[D.length," match",D.length!==1?"es":""]})]}),a.jsx(Ml,{rules:D,kind:"display",usage:_.byDisplay,height:U,onOpen:P=>v(P,"display"),emptyText:t?I?"No display rules match.":"No display rules.":fi})]}),n==="enableRules"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:re,children:"New enable rule"}),a.jsx(an,{size:"small",placeholder:`Filter ${d.length} enable rule${d.length!==1?"s":""}…`,value:B,"aria-label":"Filter the enable rules",onChange:(P,Q)=>O(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),B&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[F.length," match",F.length!==1?"es":""]})]}),a.jsx(Ml,{rules:F,kind:"enable",usage:_.byEnable,height:U,onOpen:P=>v(P,"enable"),emptyText:t?B?"No enable rules match.":"No enable rules.":fi})]}),n==="history"&&a.jsxs(a.Fragment,{children:[u.length>0&&a.jsxs("div",{className:e.toolbar,children:[a.jsx(an,{size:"small",placeholder:`Filter ${u.length} entr${u.length!==1?"ies":"y"}…`,value:S,"aria-label":"Filter the history",onChange:(P,Q)=>k(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),S&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[X.length," match",X.length!==1?"es":""]})]}),u.length===0?a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"No history yet — make a change to see it here."}):X.slice().reverse().map((P,Q)=>{const be=u.indexOf(P);return a.jsxs("div",{className:e.historyRow,children:[a.jsx("div",{className:e.historyAvatar,"aria-hidden":!0,children:a.jsx(uc,{fontSize:12,style:{color:h.colorBrandForeground1}})}),a.jsxs("div",{className:e.historyContent,children:[a.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[a.jsx(V,{size:200,weight:"semibold",children:P.op}),a.jsxs(V,{size:200,children:["— ",a.jsx("strong",{children:P.target})]}),P.detail&&a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:P.detail})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2},children:[a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[te(P)," ·"," ",new Date(P.ts).toLocaleTimeString()]}),a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(jg,{}),onClick:()=>C("history",be),children:"View diff"}),a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ec,{}),title:"Undo this change and every later one (redo brings them back)",onClick:()=>m(be),children:"Undo from here"})]})]})]},Q)})]}),n==="console"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(yo,{}),disabled:b.length===0,onClick:()=>{const P=b.slice().reverse().map(Q=>{const be=new Date(Q.ts).toLocaleTimeString();return`${Q.scope} ${be}
|
|
133
|
+
[${Q.level.toUpperCase()}]
|
|
134
|
+
${Q.message}`}).join(`
|
|
135
|
+
|
|
136
|
+
`);ks(P).then(Q=>{Q.ok||y("ui",`Couldn't copy the log: ${Q.error}.`)})},title:"Copy all log entries to clipboard",children:"Copy log"}),a.jsx(K,{appearance:"subtle",size:"small",onClick:f,children:"Clear log"})]}),a.jsx("div",{children:b.length===0?a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"No runtime diagnostics yet."}):b.slice().reverse().map(P=>a.jsx(VC,{ts:`${P.scope} ${new Date(P.ts).toLocaleTimeString()}`,level:P.level,message:P.message},P.id))})]})]})]})}function VC({ts:e,level:t,message:n}){const o=rm(),s=t==="error"?h.colorStatusDangerForeground1:t==="warn"?h.colorStatusWarningForeground1:h.colorNeutralForeground3;return a.jsxs("div",{className:o.consoleRow,children:[a.jsx("span",{className:o.consoleTs,children:e}),a.jsxs("span",{style:{color:s},children:["[",t.toUpperCase(),"]"]}),a.jsx("span",{style:{color:h.colorNeutralForeground1},children:n})]})}const XC=me({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalS}`,flexShrink:0},search:{flex:1,minWidth:0},body:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"},selected:{backgroundColor:h.colorSubtleBackgroundSelected,":hover":{backgroundColor:h.colorSubtleBackgroundSelected}},label:{display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},hidden:{color:h.colorNeutralForeground3},muted:{color:h.colorNeutralForeground3},yours:{flexShrink:0,marginLeft:h.spacingHorizontalXS},empty:{padding:`${h.spacingVerticalM} ${h.spacingHorizontalM}`,color:h.colorNeutralForeground3}}),Jn=e=>`tab:${e}`,Ho=(e,t)=>`group:${e}:${t}`,ia=(e,t,n)=>`btn:${e}:${t}:${n}`,Dl=(e,t,n)=>n?t&&ia(e,t,n):t?Ho(e,t):Jn(e),KC=e=>e.target===e.currentTarget,YC=e=>e.key==="ContextMenu"||e.shiftKey&&e.key==="F10";function JC(){const e=XC(),t=De(),n=Y(q=>q.location),o=Y(q=>q.tabId),s=Y(q=>q.selectedGroupId),i=Y(q=>q.selectedButtonId),l=Y(q=>q.setTabId),r=Y(q=>q.selectGroup),c=Y(q=>q.selectButtonInContext),d=M(q=>q.ribbons[n].tabs),u=M(q=>q.locLabels),p=M(q=>q.baseLanguageCode),m=M(q=>q.baseline),g=M(q=>q.layers),b=M(q=>q.renameTab),f=M(q=>q.deleteTab),y=M(q=>q.reorderTabs),x=ae(q=>!!q.activeEntity),v=je(q=>q.target!==null),C=Z(q=>q.openNewTab),$=Z(q=>q.openNewGroup),A=Z(q=>q.openTabDisplayRules),j=Z(q=>q.announce),T=Z(q=>q.noteStructureChoice),[R,I]=E.useState(""),[N,B]=E.useState(()=>new Set),[O,S]=E.useState(null),[k,w]=E.useState(null),[D,F]=E.useState(null),[X,ne]=E.useState(null),[re,le]=E.useState(null),[_,L]=E.useState(null),[U,W]=E.useState(null),te=E.useRef(null),P=E.useRef(null),Q=q=>t(q.label,u,p,q.source?.titleToken)||q.id,be=q=>t(q.label,u,p,q.source?.titleToken)||q.id,Ee=q=>t(q.label,u,void 0,q.source?.labelToken)||q.id,We=d.find(q=>q.id===o);E.useEffect(()=>{const q=[Jn(o)];s&&q.push(Ho(o,s)),B(ie=>q.every(de=>ie.has(de))?ie:new Set([...ie,...q]))},[n,o,s]);const Be=Dl(o,s,i);E.useEffect(()=>{if(!Be)return;[...P.current?.querySelectorAll("[data-structure-key]")??[]].find(ie=>ie.dataset.structureKey===Be)?.scrollIntoView?.({block:"nearest"})},[Be]);const Le=R.trim().toLowerCase(),et=E.useMemo(()=>{const q=(ye,ge)=>ye.toLowerCase().includes(Le)||ge.toLowerCase().includes(Le),ie=new Set,de=new Set;if(!Le)return{shown:null,opened:de};for(const ye of d){const ge=Jn(ye.id),Ue=q(Q(ye),ye.id);for(const nt of ye.groups){const St=Ho(ye.id,nt.id),pn=q(be(nt),nt.id);for(const Pn of nt.buttons){const lr=q(Ee(Pn),Pn.id);(lr||pn||Ue)&&ie.add(ia(ye.id,nt.id,Pn.id)),lr&&(de.add(ge),de.add(St),ie.add(St),ie.add(ge))}(pn||Ue)&&ie.add(St),pn&&(de.add(ge),ie.add(ge))}Ue&&ie.add(ge)}return{shown:ie,opened:de}},[Le,d,u,p,t]),J=q=>!et.shown||et.shown.has(q),Pe=Le?O??et.opened:N,ut=(q,ie)=>{const de=String(ie.value),ye=te.current===de&&ie.type==="Click"?!0:ie.open;te.current=null;const ge=new Set(Pe);ye?ge.add(de):ge.delete(de),Le?S(ge):B(ge)},Jt=q=>{(q.id!==o||s||i)&&l(q.id)},z=(q,ie)=>{q.id!==o&&l(q.id),r(ie.id)},G=(q,ie,de)=>c(n,q.id,ie.id,de.id),H=q=>Li("tab",q.id,m[n],po({layers:g},n)),oe=q=>Li("group",q.id,m[n],po({layers:g},n)),se=q=>bd(q,m[n],Rn({layers:g},n)),$e=(q,ie,de)=>{j(`${de} can't be renamed: ${Fo}.`),ce.getState().logInfo("structure",`${q} ${ie} can't be renamed: ${Fo}.`)},ue=(q,ie)=>{const de=d.map(Ue=>Ue.id),ye=de.indexOf(q.id),ge=ye+ie;ye<0||ge<0||ge>=de.length||y(n,Lg(de,ye,ge))},ze=q=>setTimeout(()=>{const ie=document.activeElement?.closest('[role="dialog"], [role="alertdialog"]');if(ie&&!ie.contains(P.current))return;const de=Y.getState(),ye=Dl(de.tabId,de.selectedGroupId,de.selectedButtonId),ge=[...P.current?.querySelectorAll("[data-structure-key]")??[]].find(Ue=>Ue.dataset.structureKey===ye)??q?.closest('[role="treeitem"]');ge?.isConnected&&ge.focus()}),Zt=d.find(q=>q.id===re)??We,Ds=(q,ie,de,ye)=>({"data-structure-key":q,onClick:()=>{Be!==q&&(te.current=q),ie(),q.startsWith("tab:")||T()},onKeyDown:ge=>{KC(ge)&&(YC(ge)?(ge.preventDefault(),ie(),de(ge.currentTarget)):ge.key==="F2"&&ye&&(ge.preventDefault(),ye()))},onContextMenu:ge=>{ge.target.closest('[role="treeitem"]')===ge.currentTarget&&(ge.preventDefault(),ie(),de(ge.currentTarget))}}),Es=(q,ie,de)=>a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(us,{}),"aria-label":`Actions for ${q}`,onClick:ye=>{ie(),de(ye.currentTarget)}}),wm=(q,ie,de)=>{const ye=ia(q.id,ie.id,de.id);if(!J(ye))return null;const ge=Ee(de),Ue=Be===ye,nt=de.custom&&!de.managed,St=()=>G(q,ie,de),pn=Pn=>{le(q.id),ne({button:de,groupId:ie.id,anchor:Pn})};return a.jsx(Wt,{itemType:"leaf",value:ye,"aria-selected":Ue,"aria-description":de.id,...Ds(ye,St,pn),children:a.jsx(Ht,{className:Ue?e.selected:void 0,iconBefore:a.jsx(vt,{button:de,size:16}),aside:de.hidden?a.jsx(xe,{size:"medium",appearance:"outline",color:"subtle",children:"Hidden"}):a.jsx(V,{size:200,className:e.muted,"aria-label":`Sequence ${de.sequence}`,children:de.sequence}),actions:Es(ge,St,pn),children:a.jsxs("span",{style:{display:"flex",alignItems:"center",minWidth:0},children:[a.jsx("span",{className:Ie(e.label,de.hidden&&e.hidden),children:ge}),nt&&a.jsx(pe,{content:"Yours: added by your customizations",relationship:"label",children:a.jsx(xe,{size:"extra-small",color:"brand",className:e.yours})})]})})},ye)},Cm=(q,ie)=>{const de=Ho(q.id,ie.id);if(!J(de))return null;const ye=be(ie),ge=Be===de,Ue=()=>z(q,ie),nt=St=>{le(q.id),F({group:ie,anchor:St})};return a.jsxs(Wt,{itemType:"branch",value:de,"aria-selected":ge,"aria-description":ie.id,...Ds(de,Ue,nt,()=>{if(!oe(ie))return $e("Group",ie.id,ye);Ue(),le(q.id),F({group:ie,anchor:document.body,action:"rename"})}),children:[a.jsx(Ht,{className:ge?e.selected:void 0,iconBefore:a.jsx($g,{}),aside:a.jsx(V,{size:200,className:e.muted,"aria-label":`${ie.buttons.length} controls`,children:ie.buttons.length}),actions:Es(ye,Ue,nt),children:a.jsx("span",{className:e.label,children:ye})}),a.jsx(Zn,{children:ft(ie.buttons).map(St=>wm(q,ie,St))})]},de)},Im=q=>{const ie=Jn(q.id);if(!J(ie))return null;const de=Q(q),ye=Be===ie,ge=nt=>w({tab:q,anchor:nt}),Ue=()=>{H(q)?L(q):$e("Tab",q.id,de)};return a.jsxs(Wt,{itemType:"branch",value:ie,"aria-selected":ye,"aria-description":q.id,...Ds(ie,()=>Jt(q),ge,Ue),children:[a.jsx(Ht,{className:ye?e.selected:void 0,iconBefore:a.jsx(Rg,{}),aside:a.jsx(V,{size:200,className:e.muted,"aria-label":`${q.groups.length} groups`,children:q.groups.length}),actions:Es(de,()=>Jt(q),ge),children:a.jsx("span",{className:e.label,children:de})}),a.jsx(Zn,{children:ft(q.groups).map(nt=>Cm(q,nt))})]},ie)},Bs=k?d.findIndex(q=>q.id===k.tab.id):-1,rr=k?k.tab.tabDisplayRules.reduce((q,ie)=>q+ie.rules.length,0):0,jm=d.filter(q=>J(Jn(q.id)));return a.jsxs("div",{className:e.root,children:[a.jsxs("div",{className:e.header,children:[a.jsx(an,{size:"small",className:e.search,placeholder:"Filter tabs, groups, buttons","aria-label":"Filter the structure",value:R,disabled:!x||!v,onChange:(q,ie)=>{I(ie.value),S(null)}}),a.jsx(pe,{content:"Add tab",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),disabled:!x||!v,onClick:C})})]}),a.jsx("div",{className:e.body,children:x?v?d.length===0?a.jsx(V,{as:"p",block:!0,size:200,className:e.empty,children:"This location has no tabs."}):jm.length===0?a.jsxs(V,{as:"p",block:!0,size:200,className:e.empty,children:["Nothing matches “",R.trim(),"”."]}):a.jsx(Zn,{ref:P,size:"small","aria-label":"Ribbon structure",openItems:Pe,onOpenChange:ut,children:d.map(Im)}):a.jsx(V,{as:"p",block:!0,size:200,className:e.empty,children:"Shown once the table's ribbon is loaded."}):a.jsx(V,{as:"p",block:!0,size:200,className:e.empty,children:"Choose a table to see its tabs, groups and buttons."})}),k&&a.jsxs(Ke,{open:!0,onOpenChange:(q,ie)=>{ie.open||(w(null),ze(k.anchor))},positioning:{target:k.anchor,position:"below",align:"start"},children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Je,{children:a.jsxs(Ze,{"aria-label":`Actions for ${Q(k.tab)}`,children:[H(k.tab)?a.jsx(fe,{secondaryContent:"F2",onClick:()=>L(k.tab),children:"Rename…"}):a.jsx(fe,{disabled:!0,title:Fo,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),a.jsx(fe,{icon:a.jsx(Dn,{}),secondaryContent:rr>0?String(rr):void 0,onClick:()=>A(n,k.tab.id),children:"Tab display rules…"}),a.jsx(fe,{icon:a.jsx(ke,{}),onClick:()=>{Jt(k.tab),$()},children:"Add group…"}),a.jsx(Dt,{}),a.jsx(fe,{disabled:Bs<=0,onClick:()=>ue(k.tab,-1),children:"Move up"}),a.jsx(fe,{disabled:Bs<0||Bs>=d.length-1,onClick:()=>ue(k.tab,1),children:"Move down"}),a.jsx(Dt,{}),a.jsx(fe,{disabled:!se(k.tab),onClick:()=>W(k.tab),children:"Delete tab…"})]})})]}),Zt&&a.jsx(Ja,{location:n,tab:Zt,moveLabels:["Move up","Move down"],target:D,onClose:()=>{ze(D?.anchor instanceof HTMLElement?D.anchor:void 0),F(null)}}),Zt&&a.jsx(wo,{location:n,tab:Zt,target:X,onClose:()=>{ze(X?.anchor),ne(null)}}),_&&a.jsx(du,{open:!0,noun:"tab",initialLabel:Ge(_.label,u,p),onRename:q=>{b(n,_.id,q),L(null)},onCancel:()=>L(null)}),U&&a.jsxs(Ln,{open:!0,title:"Delete tab",confirmLabel:"Delete tab",destructive:!0,onConfirm:()=>{f(n,U.id),W(null)},onCancel:()=>W(null),children:["Delete the tab “",Q(U),"” and its groups and buttons?"]})]})}const ZC="application/x-rw-se",QC=me({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalS}`,flexShrink:0},search:{flex:1,minWidth:0},body:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"},name:{display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3,whiteSpace:"nowrap"},meta:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS},empty:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,color:h.colorNeutralForeground3}}),hi=100,e0=e=>e.key==="ContextMenu"||e.shiftKey&&e.key==="F10";function t0(){const e=QC(),t=De(),n=M(z=>z.commands),o=M(z=>z.displayRules),s=M(z=>z.enableRules),i=M(z=>z.templates),l=M(z=>z.ribbons),r=M(z=>z.baseline),c=M(z=>z.locLabels),d=M(z=>z.baseLanguageCode),u=M(z=>z.upsertCommand),p=M(z=>z.upsertEnableRule),m=M(z=>z.upsertDisplayRule),g=M(z=>z.createButton),b=Y(z=>z.location),f=Y(z=>z.tabId),y=Y(z=>z.selectButtonInContext),x=Z(z=>z.openCommandEditor),v=Z(z=>z.openRuleEditor),C=Z(z=>z.announce),$=Z(z=>z.noteStructureChoice),[A,j]=E.useState(""),[T,R]=E.useState(()=>new Set(["buttons"])),[I,N]=E.useState(null),[B,O]=E.useState({}),S=E.useMemo(()=>{const z=[];for(const G of Object.keys(l)){const H=new Set(r[G].tabs.flatMap(oe=>oe.groups.flatMap(se=>Te(se))).map(oe=>oe.id));for(const oe of l[G].tabs)for(const se of oe.groups)for(const $e of Te(se))$e.custom&&z.push({button:$e,location:G,tabId:oe.id,groupId:se.id,isNew:!H.has($e.id)})}return z},[l,r]),k=E.useMemo(()=>Xu(l,n),[l,n]),w=z=>t(z.label,c,void 0,z.source?.labelToken)||z.id,D=A.trim().toLowerCase(),F=(...z)=>!D||z.some(G=>G.toLowerCase().includes(D)),X=S.filter(z=>F(w(z.button),z.button.id)),ne=n.filter(z=>F(z.id)),le=[...s.map(z=>({id:z.id,kind:"enable"})),...o.map(z=>({id:z.id,kind:"display"}))].filter(z=>F(z.id)),_=i.filter(z=>F(z.id)),L=D?new Set([["buttons",X],["commands",ne],["rules",le],["templates",_]].filter(([,z])=>z.length>0).map(([z])=>z)):null,[U,W]=E.useState(null),te=L?U?.q===D?U.open:L:T,P=()=>{const z=Pa("New","Command",new Set(n.map(G=>G.id)));u({id:z,enableRules:[],displayRules:[],actions:[]}),x(z)},Q=z=>{const G=uo("New",z==="enable"?"Enable":"Display",new Set([...s.map(H=>H.id),...o.map(H=>H.id)]));z==="enable"?p({id:G,steps:[]}):m({id:G,steps:[]}),v(G,z)},be=z=>{y(z.location,z.tabId,z.groupId,z.button.id),$()},Ee=l[b].tabs.find(z=>z.id===f),We=Ee?ft(Ee.groups):[],Be=!!I&&I.row.location==="Application"!=(b==="Application"),Le=(z,G,H)=>{Ee&&(g({location:b,tabId:Ee.id,groupId:G,button:Lu(z.button,io(M.getState()))}),C(`A copy of ${w(z.button)} was added to ${H}.`))},et=(z,G,H,oe,se,$e={},ue)=>a.jsx(Wt,{itemType:"leaf",value:z,"aria-description":oe,onClick:se,...$e,children:a.jsx(Ht,{aside:H,actions:ue,children:a.jsx("span",{className:e.name,title:oe,children:G})})},z),J=(z,G,H,oe,se)=>{const $e=te.has(z),ue=B[z]??hi;return a.jsxs(Wt,{itemType:"branch",value:z,children:[a.jsx(Ht,{aside:a.jsx(xn,{size:"medium",appearance:"ghost",color:"informative",count:H.length,showZero:!0}),children:G}),a.jsx(Zn,{children:$e&&(H.length===0?ut(se):[...H.slice(0,ue).map(ze=>tt.cloneElement(oe(ze),{"data-branch-row":z})),...H.length>ue?[a.jsx(Wt,{itemType:"leaf",value:`more:${z}`,onClick:()=>{setTimeout(()=>{document.querySelectorAll(`[data-branch-row="${z}"]`)[ue]?.focus()}),O(ze=>({...ze,[z]:ue+hi}))},children:a.jsx(Ht,{children:a.jsxs("span",{className:e.muted,children:["Show"," ",Math.min(hi,H.length-ue)," ","more of ",H.length-ue]})})},`more:${z}`)]:[]])})]},z)},Pe=z=>z?`used ${z}×`:"not used",ut=z=>a.jsx(Wt,{itemType:"leaf",value:`none:${z}`,"aria-disabled":!0,children:a.jsx(Ht,{children:a.jsx("span",{className:e.muted,children:z})})}),Jt=z=>{const G=`button:${z.location}:${z.button.id}`,H=oe=>N({row:z,anchor:oe});return et(G,w(z.button),a.jsxs("span",{className:e.meta,children:[a.jsx(xe,{size:"medium",appearance:"outline",children:Vt[z.location].label}),z.isNew&&a.jsx(xe,{size:"medium",color:"brand",appearance:"tint",children:"New"})]}),`${z.button.id} · ${Vt[z.location].label}`,()=>be(z),{draggable:!0,onDragStart:oe=>{oe.dataTransfer.setData(ZC,JSON.stringify({button:z.button})),oe.dataTransfer.effectAllowed="copy"},onContextMenu:oe=>{oe.preventDefault(),H(oe.currentTarget)},onKeyDown:oe=>{oe.target===oe.currentTarget&&e0(oe)&&(oe.preventDefault(),H(oe.currentTarget))}},a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(us,{}),"aria-label":`Actions for ${w(z.button)}`,onClick:oe=>H(oe.currentTarget)}))};return a.jsxs("div",{className:e.root,children:[a.jsxs("div",{className:e.header,children:[a.jsx(an,{size:"small",className:e.search,placeholder:"Search buttons, commands, rules","aria-label":"Search the solution's elements",contentBefore:a.jsx(fc,{}),value:A,onChange:(z,G)=>j(G.value)}),a.jsxs(Ke,{children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:"New command or rule",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{})})})}),a.jsx(Je,{children:a.jsxs(Ze,{children:[a.jsx(fe,{icon:a.jsx(Mn,{}),onClick:P,children:"New command"}),a.jsx(fe,{icon:a.jsx(ro,{}),onClick:()=>Q("enable"),children:"New enable rule"}),a.jsx(fe,{icon:a.jsx(ro,{}),onClick:()=>Q("display"),children:"New display rule"})]})})]})]}),a.jsx("div",{className:e.body,children:a.jsxs(Zn,{size:"small","aria-label":"Solution elements",openItems:te,onOpenChange:(z,G)=>{const H=new Set(te);G.open?H.add(String(G.value)):H.delete(String(G.value)),D?W({q:D,open:H}):R(H)},children:[J("buttons","Buttons",X,Jt,D?"No buttons match.":"None of your buttons yet."),J("commands","Commands",ne,z=>et(`command:${z.id}`,Wo(z.id),a.jsx(V,{size:200,className:e.muted,children:Pe(k.byCommand.get(z.id))}),z.id,()=>x(z.id)),D?"No commands match.":"No commands."),J("rules","Rules",le,z=>et(`rule:${z.kind}:${z.id}`,Wo(z.id),a.jsxs("span",{className:e.meta,children:[a.jsx(V,{size:200,className:e.muted,children:Pe((z.kind==="enable"?k.byEnable:k.byDisplay).get(z.id))}),a.jsx(xe,{size:"medium",appearance:"tint",color:z.kind==="enable"?"success":"informative",children:z.kind==="enable"?"Enable":"Display"})]}),z.id,()=>v(z.id,z.kind)),D?"No rules match.":"No rules."),J("templates","Templates",_,z=>a.jsx(Wt,{itemType:"leaf",value:`template:${z.id}`,"aria-description":z.id,children:a.jsx(Ht,{iconBefore:a.jsx(gc,{}),children:a.jsx("span",{className:e.name,title:z.id,children:Wo(z.id)})})},`template:${z.id}`),D?"No templates match.":"No templates.")]})}),I&&a.jsxs(Ke,{open:!0,onOpenChange:(z,G)=>!G.open&&N(null),positioning:{target:I.anchor,position:"below",align:"start"},children:[a.jsx(Ye,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Je,{children:a.jsxs(Ze,{"aria-label":`Actions for ${w(I.row.button)}`,children:[a.jsx(fe,{onClick:()=>be(I.row),children:"Go to button"}),a.jsx(Dt,{}),a.jsx(ao,{children:"Add a copy to a group of this tab"}),Be&&a.jsx(ao,{children:b==="Application"?"A table's button can't go on the application ribbon.":"An application ribbon button can't go on a table's ribbon."}),We.length===0?a.jsx(fe,{disabled:!0,children:"No groups on this tab"}):We.map(z=>{const G=t(z.label,c,d,z.source?.titleToken)||z.id;return a.jsxs(fe,{disabled:Be,onClick:()=>Le(I.row,z.id,G),children:["Add to ",G]},z.id)})]})})]},`${I.row.location}:${I.row.button.id}`)]})}const n0=me({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},tabs:{flexShrink:0,padding:`0 ${h.spacingHorizontalXS}`,borderBottom:`1px solid ${h.colorNeutralStroke2}`},body:{flex:1,minHeight:0,overflow:"hidden"}});function o0(){const e=n0(),t=Z(o=>o.leftPaneTab),n=Z(o=>o.setLeftPaneTab);return a.jsxs("div",{className:e.root,children:[a.jsxs(wa,{size:"small",className:e.tabs,"aria-label":"Left pane",selectedValue:t,onTabSelect:(o,s)=>n(s.value),children:[a.jsx(qt,{value:"structure",icon:a.jsx(Jl,{}),children:"Structure"}),a.jsx(qt,{value:"solution",icon:a.jsx(Zl,{}),children:"Solution"})]}),a.jsx("div",{className:e.body,role:"tabpanel","aria-label":t==="structure"?"Structure":"Solution",children:t==="structure"?a.jsx(JC,{}):a.jsx(t0,{})})]})}function ar(){return window.dataverseAPI}async function s0(){const e=ar();ce.getState().logInfo("dataverse","Loading solutions...");const s=((await e.queryData("solutions?$select=solutionid,uniquename,friendlyname,version,ismanaged,versionnumber,isvisible&$expand=publisherid($select=publisherid,uniquename,friendlyname,customizationprefix,customizationoptionvalueprefix)&$filter=isvisible eq true and uniquename ne 'Active' and uniquename ne 'Default'&$orderby=friendlyname asc")).value??[]).map(l=>{const r=l.publisherid??{};return{id:String(l.solutionid??""),uniqueName:String(l.uniquename??""),friendlyName:String(l.friendlyname??""),version:String(l.version??""),isManaged:!!l.ismanaged,publisherId:r.publisherid??"",publisherUniqueName:r.uniquename??"",publisherName:r.friendlyname??"",publisherPrefix:r.customizationprefix??"",publisherOptionValuePrefix:typeof r.customizationoptionvalueprefix=="number"?r.customizationoptionvalueprefix:void 0,versionNumber:l.versionnumber}});ce.getState().logInfo("dataverse",`Loaded ${s.length} solution(s).`);const i=s.filter(l=>!l.isManaged).slice(0,5);for(const l of i)ce.getState().logInfo("dataverse",` • "${l.friendlyName||l.uniqueName}" → prefix="${l.publisherPrefix||"(empty)"}" (publisher: ${l.publisherName||l.publisherUniqueName||"(empty)"})`);return s}async function i0(e){if(!e)return[];const t=ar();ce.getState().logInfo("dataverse",`Loading solution entity components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 1`,i=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return ce.getState().logInfo("dataverse",`Solution contains ${i.length} table component(s).`),i}async function a0(e){if(!e)return[];const t=ar();ce.getState().logInfo("dataverse",`Loading solution ribbon components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 50`,i=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return ce.getState().logInfo("dataverse",`Solution contains ${i.length} ribbon-customization component(s).`),i}function r0(){return window.dataverseAPI}async function l0(e){if(e.length===0)return[];const t=r0(),n=ce.getState();n.logInfo("dataverse",`Loading metadata for ${e.length} solution entit${e.length===1?"y":"ies"}...`);const o="MetadataId,LogicalName,SchemaName,DisplayName,IsCustomEntity,IsIntersect",s=d=>({metadataId:String(d.MetadataId??""),logicalName:String(d.LogicalName??""),schemaName:d.SchemaName?String(d.SchemaName):void 0,displayName:d.DisplayName?.UserLocalizedLabel?.Label??String(d.LogicalName??""),isCustomEntity:!!d.IsCustomEntity,isManaged:!1,isIntersect:!!d.IsIntersect}),i=async d=>{try{return s(await t.queryData(`EntityDefinitions(${d})?$select=${o}`))}catch(u){return n.logWarn("dataverse",`Could not resolve entity for component ${d}: ${u instanceof Error?u.message:String(u)}`),null}},l=[];for(let d=0;d<e.length;d+=40)l.push(e.slice(d,d+40));const c=(await Promise.all(l.map(async d=>{try{const p=((await t.queryData(`EntityDefinitions?$select=${o}&$filter=${d.map(g=>`MetadataId eq ${g}`).join(" or ")}`)).value??[]).map(s),m=new Set(p.map(g=>g.metadataId.toLowerCase()));for(const g of d)m.has(g.toLowerCase())||n.logWarn("dataverse",`Could not resolve entity for component ${g}: not found.`);return p}catch(u){n.logWarn("dataverse",`Couldn't read ${d.length} tables in one request (${u instanceof Error?u.message:String(u)}); reading them one at a time.`);const p=[];for(const m of d)p.push(await i(m));return p}}))).flat().filter(d=>d!==null&&!d.isIntersect).sort((d,u)=>d.displayName.localeCompare(u.displayName));return n.logInfo("dataverse",`Loaded metadata for ${c.length} table(s).`),c}async function lm(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const o=Xy(n),s=Object.entries(o).find(([i])=>i.toLowerCase().endsWith("ribbonxml.xml"));if(!s){const i=Object.keys(o);throw new Error(`Dataverse returned a ribbon package without RibbonXml.xml (it has ${i.length>0?i.join(", "):"no files"}).`)}return Ts(s[1])}const cm=30,c0=cm*6e4,dm=(e,t)=>`cbs:lastPublish:${e.replace(/\/+$/,"")}:${t}`;function um(e,t){try{const n=sessionStorage.getItem(e);if(!n)return null;const o=JSON.parse(n);if(typeof o.at!="number"||!o.publishedAt||typeof o.publishedAt!="object")return null;const s=Object.fromEntries(Object.entries(o.publishedAt).filter(i=>typeof i[1]=="number"&&t-i[1]<c0));return{at:o.at,publishedAt:s}}catch{return null}}function vI(e,t,n,o=Date.now()){const s=dm(e,t),i={...um(s,o)?.publishedAt??{}};for(const l of n){const r=/^customActions:ca:(.+)$/.exec(l)?.[1];r&&(i[r]=o)}try{sessionStorage.setItem(s,JSON.stringify({at:o,publishedAt:i}))}catch{}}function d0(e,t,n=Date.now()){return um(dm(e,t),n)}const El=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]),gi=new Set(["Tab","Group"]),Bl=/^(.+)\._children$/;function Ll(e){return e?Array.from(e.children):[]}function bo(e,t){return t?e.split("{!EntityLogicalName}").join(t):e}function u0(e,t){const n=new Map,o=(s,i)=>n.set(bo(s,t),i);for(const s of e)for(const i of s.tabs){o(`${i.id}.Groups`,i.id);for(const l of i.groups){o(`${l.id}.Controls`,i.id);for(const r of Te(l))for(const c of r.menu?.sections??[])o(c.controlsId,i.id)}}return n}function m0(e,t){const n=new Set,o=s=>n.add(bo(s,t));for(const s of e)for(const i of s.tabs){o(i.id);for(const l of i.groups){o(l.id);for(const r of Te(l))o(r.id)}}return n}function zl(e){return[e,...Array.from(e.getElementsByTagName("*"))].flatMap(t=>t.getAttribute("Id")??[])}function p0(e,t,n,o={}){const{locLabels:s=[],languageCode:i=1033}=o,l=[...t],r=T=>bo(T,n),c=m0(l,n),d=u0(l,n),u=[...hs(e).map(T=>T.location),...o.otherHides??[]].map(r),p=new Set(u),m=new Set,g=[...e.customActions.values()].map(T=>new DOMParser().parseFromString(T,"application/xml").documentElement);for(const T of g)if(T.tagName==="CustomAction")for(const R of Array.from(T.getElementsByTagName("*")))p.has(r(R.getAttribute("Id")??""))&&zl(R).forEach(I=>m.add(r(I)));const b=T=>m.has(T)||u.some(R=>T===R||T.startsWith(`${R}.`)),f=new Set(["Mscrm.Tabs",`Mscrm.SubGrid.${n}.ContextualTabs`]),y=(T,R)=>{const I=d.get(R);return I&&xo(I)?{reason:"hidden-tab",why:`It is on the tab ${I}, which Unified Interface doesn't show; the ribbon doesn't return what is added there.`}:I||f.has(R)?{reason:"not-returned",why:T==="Tab"?`The ribbon doesn't return this tab at ${R}, so Command Bar Studio can't place it (it may still show in Unified Interface).`:`${R} is on the canvas, but the ribbon doesn't return this ${T.toLowerCase()} there (for example a control added to a new group in a separate CustomAction).`}:{reason:"missing-location",why:/^(Mscrm|Microsoft)\./.test(R)?`${R} isn't in this table's ribbon as loaded: it is not shown — possibly hidden by another solution — or it was removed.`:`${R} isn't in this table's ribbon as loaded: the group, tab or menu was removed or renamed, the Location is misspelled, or it is hidden by another solution.`}},x=T=>{const R=T.getAttribute("LabelText")??T.getAttribute("Title")??T.getAttribute("Alt")??"";return Ge(R,s,i)||(T.getAttribute("Id")??"")},v=[],C=(T,R,I)=>{const N=T.getAttribute("Id")??"",B=Bl.exec(R)?.[1]??R;if(!N||c.has(r(N))||b(r(N))||b(r(B)))return;const O=gi.has(T.tagName);v.push({orphan:{id:N,element:T.tagName,label:x(T),location:R,customActionId:I,...y(T.tagName,r(B)),deleteControlIds:O?[]:[N],deleteContainerIds:O?[N]:[]},parent:B,inside:new Set(zl(T))})};for(const T of g){if(T.tagName!=="CustomAction")continue;const R=T.getAttribute("Location")??"";if(!Bl.test(R)||/\.Scaling\._children$/.test(R))continue;const I=Ll(Ll(T).find(O=>O.tagName==="CommandUIDefinition"))[0],N=I?.getAttribute("Id");if(!I||!N||!(gi.has(I.tagName)||El.has(I.tagName)))continue;const B=T.getAttribute("Id")??"";if(!c.has(r(N))){C(I,R,B);continue}for(const O of Array.from(I.getElementsByTagName("*"))){const S=O.parentElement;S?.tagName!=="Controls"&&S?.tagName!=="Groups"||!gi.has(O.tagName)&&!El.has(O.tagName)||C(O,`${S.getAttribute("Id")??""}._children`,B)}}const $=T=>v.find(R=>R!==T&&R.inside.has(T.parent)&&!T.inside.has(R.parent)),A=T=>{const R=new Set([T]);let I=T;for(let N=$(I);N&&!R.has(N);N=$(I))R.add(N),I=N;return I},j=v.filter(T=>!$(T));for(const T of v){const R=A(T);if(R===T||!j.includes(R))continue;const I=(N,B)=>B.forEach(O=>N.includes(O)||N.push(O));I(R.orphan.deleteControlIds,T.orphan.deleteControlIds),I(R.orphan.deleteContainerIds,T.orphan.deleteContainerIds)}return j.map(T=>T.orphan)}function f0(e,t,n=Date.now()){if(!t)return e;const o=cm*6e4,s=i=>Math.max(0,Math.floor((n-i)/6e4));return e.map(i=>{const l=t.publishedAt[i.customActionId];if(l!==void 0&&n-l<o){const c=s(l);return{...i,recentPublish:{minutesAgo:c,published:!0},why:`Published from here ${c} min before this table was loaded: the ribbon may not have caught up yet (it can lag 10 minutes or more). Reload the table later before deleting it. ${i.why}`}}if(n-t.at>=o)return i;const r=s(t.at);return{...i,recentPublish:{minutesAgo:r,published:!1},why:`The table was published from here ${r} min before this table was loaded, and the ribbon may not have caught up yet. ${i.why}`}})}const mm=window.dataverseAPI;function Eo(e){const t=new Set,n=[];for(const o of e)t.has(o.id)||(t.add(o.id),n.push(o));return n}function pm(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 fm(e){return pm(e)[0]}function h0(e,t,n={}){const o={HomepageGrid:[],SubGrid:[],Form:[]};for(const i of e)i.id.startsWith("Mscrm.Form.")?o.Form.push(i):i.id.startsWith("Mscrm.SubGrid.")?o.SubGrid.push(i):i.id.startsWith("Mscrm.HomepageGrid.")?o.HomepageGrid.push(i):o[fm(i)??"HomepageGrid"].push(i);const s=i=>{const l=Object.fromEntries(o[i].filter(r=>n[r.id]).map(r=>[r.id,n[r.id]]));return{location:i,entityLogicalName:t,tabs:o[i],...Object.keys(l).length>0?{scalingByTab:l}:{}}};return{HomepageGrid:s("HomepageGrid"),SubGrid:s("SubGrid"),Form:s("Form")}}const g0="Microsoft.Dynamics.CRM.RibbonLocationFilters'All'";function b0(e){return`RetrieveEntityRibbon(EntityName=@e,RibbonLocationFilter=@f)?@e='${encodeURIComponent(e.replace(/'/g,"''"))}'&@f=${g0}`}async function y0(e,t=[]){ce.getState().logInfo("dataverse",`RetrieveEntityRibbon(${e}, All)`);const n=await mm.queryData(b0(e));if(typeof n?.CompressedEntityXml!="string"||!n.CompressedEntityXml)throw new Error(`Dataverse returned no ribbon for ${e} (RetrieveEntityRibbon had no CompressedEntityXml).`);const o=await lm(n.CompressedEntityXml),s=js(o,"HomepageGrid",e,t),i=h0(s.ribbon.tabs,e,s.ribbon.scalingByTab);if(s.ribbon.templateLayouts)for(const l of Object.values(i))l.templateLayouts=s.ribbon.templateLayouts;return ce.getState().logInfo("dataverse",`RetrieveEntityRibbon succeeded for ${e} (Form=${i.Form.tabs.length}, HomepageGrid=${i.HomepageGrid.tabs.length}, SubGrid=${i.SubGrid.tabs.length})`),{ribbons:i,commands:s.commands,displayRules:s.displayRules,enableRules:s.enableRules,locLabels:s.locLabels}}const hm=5*6e4;let aa=null,ra=0,gm=0;function x0(e={}){aa=null,ra++,e.afterPublish&&(gm=Date.now()+hm)}async function v0(e=[]){const t=ce.getState(),n=ae.getState().connectionUrl,o=aa;let s;if(o&&o.environment===n&&Date.now()-o.at<hm)s=o.xml,t.logInfo("dataverse","RetrieveApplicationRibbon (reused from this session)");else{const i=ra;t.logInfo("dataverse","RetrieveApplicationRibbon()");const r=(await mm.execute({operationName:"RetrieveApplicationRibbon",operationType:"function"}))?.CompressedApplicationRibbonXml;if(typeof r!="string"||!r)throw new Error("Dataverse returned no application ribbon (RetrieveApplicationRibbon had no CompressedApplicationRibbonXml).");s=await lm(r),i===ra&&Date.now()>=gm&&(aa={environment:n,at:Date.now(),xml:s}),t.logInfo("dataverse","RetrieveApplicationRibbon succeeded")}return js(s,"Application","{!EntityLogicalName}",e)}function bi(e,t,n,o=[]){const s={added:[],replaced:[]};if(n.commandDefinitions.size+n.enableRules.size+n.displayRules.size===0)return s;const i=xy(n),l=(g,b)=>JSON.stringify(g,Pl)===JSON.stringify(b,Pl),r=(g,b)=>{const f=new Map(b.map(y=>[y.id,y]));for(let y=0;y<g.length;y++){const x=f.get(g[y].id);x&&!l(x,g[y])&&(g[y]=x,s.replaced.push(x.id))}};r(t.commands,i.commands),r(t.enableRules,i.enableRules),r(t.displayRules,i.displayRules);const c=new Set(t.commands.map(g=>g.id)),d=new Set(o.filter(g=>!c.has(g)&&n.commandDefinitions.has(g)));for(const g of e)for(const b of g.tabs)for(const f of b.groups)for(const y of Te(f))y.commandId&&!c.has(y.commandId)&&n.commandDefinitions.has(y.commandId)&&d.add(y.commandId);const u=i.commands.filter(g=>d.has(g.id));t.commands.push(...u),s.added.push(...u.map(g=>g.id));const p=new Set(t.enableRules.map(g=>g.id)),m=new Set(t.displayRules.map(g=>g.id));for(const g of t.commands){for(const b of g.enableRules){const f=i.enableRules.find(y=>y.id===b);f&&!p.has(b)&&(t.enableRules.push(f),p.add(b),s.added.push(b))}for(const b of g.displayRules){const f=i.displayRules.find(y=>y.id===b);f&&!m.has(b)&&(t.displayRules.push(f),m.add(b),s.added.push(b))}}return s}function Pl(e,t){if(typeof t!="string"||!t.trimStart().startsWith("<"))return t;try{return Nn(t)}catch{return t}}function S0(e,t){const n=(o,s)=>new Map([...o].filter(([i])=>!s?.has(i)));return{...e,commandDefinitions:n(e.commandDefinitions,t?.commandDefinitions),enableRules:n(e.enableRules,t?.enableRules),displayRules:n(e.displayRules,t?.displayRules)}}function w0(e,t,n){if(n!==1033)for(const o of e)for(const s of o.tabs)for(const i of s.groups)for(const l of Te(i)){for(const d of l.menu?.sections??[]){const u=d.attributes?.Title;u?.startsWith("$LocLabels:")&&(d.title=Ge(u,t,n))}const r=l.source;if(!r)continue;const c=[[r.labelToken,"label"],[r.tooltipTitleToken,"tooltipTitle"],[r.tooltipBodyToken,"tooltipBody"]];for(const[d,u]of c)d?.startsWith("$LocLabels:")&&(l[u]=Ge(d,t,n))}}function Fl(e,t,n,o){const s=new Set(Object.values(e).flatMap(m=>m?.tabs.map(g=>g.id)??[])),i=new Set(hs(t).map(m=>m.location)),l=n?`Mscrm.SubGrid.${n}.ContextualTabs._children`:null,r=[];for(const m of Yc(t.customActions).values()){const g=new DOMParser().parseFromString(m,"application/xml").documentElement;if(g.tagName!=="CustomAction")continue;const b=bo(g.getAttribute("Location")??"",n??void 0);if(b!=="Mscrm.Tabs._children"&&b!==l)continue;const f=Array.from(g.getElementsByTagName("CommandUIDefinition")[0]?.children??[])[0],y=f?.tagName==="Tab"?f.getAttribute("Id"):null;!y||s.has(bo(y,n??void 0))||r.push({xml:new XMLSerializer().serializeToString(f),subGrid:b===l})}if(r.length===0)return[];const c=`<RibbonDefinitions><RibbonDefinition><UI><Ribbon><Tabs>${r.map(m=>m.xml).join("")}</Tabs></Ribbon></UI><RuleDefinitions><TabDisplayRules>${[...t.tabDisplayRules.values()].join("")}</TabDisplayRules></RuleDefinitions></RibbonDefinition></RibbonDefinitions>`,d=js(c,n?"HomepageGrid":"Application",n??"{!EntityLogicalName}",o);d.ribbon.tabs=d.ribbon.tabs.filter(m=>!i.has(m.id));for(const m of d.ribbon.tabs){m.groups=m.groups.filter(g=>!i.has(g.id));for(const g of m.groups){g.buttons=g.buttons.filter(b=>!i.has(b.id));for(const b of Te(g))i.has(b.id)&&sd(g,b.id)}}const u=new Set(r.filter(m=>m.subGrid).map(m=>new DOMParser().parseFromString(m.xml,"application/xml").documentElement.getAttribute("Id"))),p=m=>n?u.has(m.id)?"SubGrid":fm(m)??"HomepageGrid":"Application";for(const m of d.ribbon.tabs){const g=n&&!u.has(m.id)?pm(m).slice(1):[];g.length>0&&ce.getState().logWarn("ribbon",`Tab ${m.id} shows on the ${p(m)} and on the ${g.join(" and ")} (its display rules); Command Bar Studio lists it under ${p(m)} only.`);const b=e[p(m)];if(!b)continue;b.tabs.push(m),b.tabs.sort((y,x)=>y.sequence-x.sequence);const f=d.ribbon.scalingByTab?.[m.id];f&&(b.scalingByTab={...b.scalingByTab??{},[m.id]:f})}return d.ribbon.tabs.map(m=>m.id)}function yi(e,t){if(t.added.length+t.replaced.length===0)return;const n=[t.added.length>0?`${t.added.length} missing (${t.added.join(", ")})`:"",t.replaced.length>0?`${t.replaced.length} out of date (${t.replaced.join(", ")})`:""].filter(Boolean);ce.getState().logWarn("ribbon",`${e} returned command / rule definitions that don't match your unmanaged customizations — ${n.join("; ")}. It can lag behind for a few minutes after a publish; loaded them from the unmanaged layer.`)}async function C0(e,t){const n=ce.getState();t?.("Reading your customizations…");const o=[],s=f=>y=>(o.push(`${f}: ${y instanceof Error?y.message:String(y)}`),null),[i,l,r]=await Promise.all([Fi(e).catch(s(`the ${e} table's customizations`)),Fi(null).catch(s("the application ribbon's customizations")),zv().catch(f=>{n.logWarn("dataverse",`${f instanceof Error?f.message:String(f)} Labels are shown in English; publishing reads it again and stops if it still can't.`)})]),c=i?_i(i):[],d=l?_i(l):[];t?.("Reading the table's ribbon and the application ribbon…");const[u,p]=await Promise.all([y0(e,[...c,...d]),v0(d)]);if(i){const f=Fl(u.ribbons,i,e,[...c,...d]);f.length>0&&n.logInfo("ribbon",`Loaded tab(s) ${f.join(", ")} from the table's unmanaged layer.`);const y=Ko(i);for(const x of Object.values(u.ribbons))Er(x,y);yi("RetrieveEntityRibbon",bi(Object.values(u.ribbons),u,i,[Xe]))}l&&(Fl({Application:p.ribbon},l,null,d),Er(p.ribbon,Ko(l)),yi("RetrieveApplicationRibbon",bi([p.ribbon],p,l)),yi("RetrieveEntityRibbon",bi(Object.values(u.ribbons),u,S0(l,i))));const m=Eo([...u.locLabels,...p.locLabels]),g=r??1033;t?.("Matching labels and ownership…"),w0([...Object.values(u.ribbons),p.ribbon],m,g);const b=i?p0(i,Object.values(u.ribbons),e,{locLabels:m,languageCode:g,otherHides:l?hs(l).map(f=>f.location):[]}):[];return b.length>0&&n.logWarn("ribbon",`${b.length} element(s) of the table's unmanaged customizations aren't on the canvas — the ribbon doesn't return them (see "Orphaned customizations"): ${b.map(f=>`${f.id} at ${f.location}`).join(", ")}.`),{ribbons:{HomepageGrid:u.ribbons.HomepageGrid,SubGrid:u.ribbons.SubGrid,Form:u.ribbons.Form,Application:p.ribbon},commands:Eo([...u.commands,...p.commands]),displayRules:Eo([...u.displayRules,...p.displayRules]),enableRules:Eo([...u.enableRules,...p.enableRules]),locLabels:m,layers:{entity:i?es(i):null,application:l?es(l):null},baseLanguageCode:r,orphans:b,...o.length>0?{layerReadError:o.join("; ")}:{}}}const I0="System",ds="{!EntityLogicalName}",Go=new Map;function j0(e){if(!e||!e.includes("<"))return[];try{const t=new DOMParser().parseFromString(e,"application/xml");if(t.querySelector("parsererror"))return[];const n=t.getElementsByTagName("CommandUIDefinition")[0];if(!n)return[];const o=[];for(const s of Array.from(n.getElementsByTagName("*"))){const i=s.getAttribute("Id");i&&o.push(i)}return o}catch{return[]}}async function R0(e){const t=e.filter(n=>!Go.has(n));for(let n=0;n<t.length;n+=40){const o=t.slice(n,n+40),s=await In(`solutions?$select=solutionid,uniquename&$expand=publisherid($select=friendlyname)&$filter=${o.map(i=>`solutionid eq ${i}`).join(" or ")}`);for(const i of o)Go.set(i,null);for(const i of s){const l=i.publisherid;Go.set(String(i.solutionid),{uniqueName:String(i.uniquename??""),publisherName:l?.friendlyname})}}}async function $0(e){const t=ce.getState(),n=new Map;if(!e||e===ds)return n;try{const o=e.replace(/'/g,"''"),s=await In(`ribbondiffs?$select=rdx,solutionid&$filter=(entity eq '${o}' or entity eq null) and ismanaged eq true and difftype le 1&$orderby=solutionid`),i=new Map;for(const l of s){const r=String(l.solutionid??"");if(r)for(const c of j0(String(l.rdx??""))){const d=c.split(ds).join(e);for(const u of d===c?[c]:[c,d])i.has(u)||i.set(u,new Set),i.get(u).add(r)}}await R0([...new Set([...i.values()].flatMap(l=>[...l]))]);for(const[l,r]of i){const c=[...r].map(d=>Go.get(d)).find(d=>d&&d.uniqueName!==I0);c&&n.set(l,{origin:"managed",solutionName:c.uniqueName,publisherName:c.publisherName})}t.logInfo("provenance",`${s.length} managed CustomAction(s) for ${e}: ${n.size} control(s) from managed solutions.`)}catch(o){t.logWarn("provenance",`Couldn't read which managed solutions add ${e}'s controls (${o instanceof Error?o.message:String(o)}); their owners aren't shown. This is non-fatal.`)}return n}async function T0(e){if(!e||e===ds)return[];try{const t=e.replace(/'/g,"''"),n=await In(`ribbondiffs?$select=rdx&$filter=(entity eq '${t}' or entity eq null) and ismanaged eq true and difftype eq 3&$orderby=solutionid`),o=[],s=new DOMParser;for(const i of n){const l=s.parseFromString(String(i.rdx??""),"application/xml");if(!l.querySelector("parsererror"))for(const r of Array.from(l.getElementsByTagName("LocLabel"))){const c=r.getAttribute("Id");if(!c)continue;const d=Array.from(r.getElementsByTagName("Title")).map(p=>({languageCode:Number(p.getAttribute("languagecode")),description:p.getAttribute("description")??""})).filter(p=>Number.isFinite(p.languageCode)&&p.description);if(d.length===0)continue;o.push({id:c,titles:d});const u=c.split(ds).join(e);u!==c&&o.push({id:u,titles:d})}}return ce.getState().logInfo("provenance",`${o.length} label text(s) from managed solutions for ${e}.`),o}catch(t){return ce.getState().logWarn("provenance",`Couldn't read the managed solutions' label texts for ${e} (${t instanceof Error?t.message:String(t)}); their ids are shown. This is non-fatal.`),[]}}function N0(){return window.dataverseAPI}async function k0(){const e=N0();ce.getState().logInfo("dataverse","Resolving current user via WhoAmI...");const t=await e.execute({operationName:"WhoAmI",operationType:"function"}),n=typeof t.UserId=="string"?t.UserId:"";if(!n)return ce.getState().logWarn("dataverse","WhoAmI returned no user id."),{id:"",name:""};const s=(await e.retrieve("systemuser",n,["fullname"])).fullname?.trim(),i={id:n,name:s&&s.length>0?s:"Current User"};return ce.getState().logInfo("dataverse",`Current user resolved: ${i.name}.`),i}function A0(){E.useEffect(()=>{const e=lx();return e>0&&ce.getState().logInfo("ribbon",`Discarded ${e} unsaved-changes draft(s) older than ${_d} days, or saved by an earlier version of Command Bar Studio (they can't be restored correctly).`),dx()},[])}function O0(){const e=je(i=>i.pending),t=je(i=>i.pendingBaselineChanged),n=je(i=>i.restoreError),o=je(i=>i.restoreDraft),s=je(i=>i.discardDraft);return e?a.jsxs(mn,{open:!0,onOpenChange:()=>{},modalType:"alert",size:"small",title:"Unpublished changes",actions:a.jsxs(a.Fragment,{children:[a.jsx(Va,{onClick:s,children:"Discard changes"}),a.jsx(K,{appearance:"primary",disabled:!!n,onClick:()=>o(),"data-autofocus":!0,children:"Restore changes"})]}),children:[a.jsxs(V,{block:!0,children:["You have unpublished changes to this table from a previous session (saved"," ",new Date(e.savedAt).toLocaleString(),"). Restore them on top of the ribbon as it is now, or discard them?"]}),t&&a.jsx($t,{intent:"warning",layout:"multiline",style:{marginTop:"12px"},children:a.jsx(Tt,{children:"The table's ribbon has changed since then (published from another session, or by someone else): review the publish plan before publishing."})}),n&&a.jsx($t,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:a.jsxs(Tt,{children:["These changes couldn't be restored (",n,"). Discard them to continue; the details are in the runtime log."]})})]}):null}function M0(){const e=je(d=>d.pendingSwitch),t=je(d=>d.pending!==null),n=je(d=>d.saveFailed),o=je(d=>d.resolveSwitch),s=ae(d=>d.activeEntity),i=ae(d=>d.activeSolution);if(!e)return null;const l=s?.displayName||s?.logicalName||"this table",r=e.kind==="entity"?`table ${e.entity.displayName||e.entity.logicalName}`:`solution ${e.solution.friendlyName||e.solution.uniqueName}`,c=i?.friendlyName||i?.uniqueName||"this solution";return a.jsxs(mn,{open:!0,onOpenChange:d=>!d&&o("cancel"),modalType:"alert",size:"small",title:"Unpublished changes",actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:()=>o("cancel"),children:"Cancel"}),a.jsxs(Va,{onClick:()=>o("discard"),children:["Discard",t?" and switch":" changes"]}),!t&&a.jsx(K,{appearance:"primary",disabled:n,onClick:()=>o("keep"),children:"Keep as draft"})]}),children:[a.jsxs(V,{block:!0,children:[l," has changes that aren't published. Switch to ",r,"?"]}),a.jsx(V,{block:!0,style:{marginTop:"8px"},children:t?a.jsxs(a.Fragment,{children:["Changes made since opening ",l," aren't saved: the unsaved changes of your previous session are kept until you restore or discard them."]}):a.jsxs(a.Fragment,{children:[a.jsx("strong",{children:"Keep as draft"})," saves them on this computer: they are offered again when you open ",l," in ",c,". ",a.jsx("strong",{children:"Discard changes"})," ","deletes them."]})}),n&&!t&&a.jsx($t,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:a.jsx(Tt,{children:"The changes can't be saved as a draft: the browser storage is full. Publish them first, or discard them to switch."})})]})}function D0(){const e=ae(I=>I.setSolutions),t=ae(I=>I.setEntities),n=ae(I=>I.setCurrentUser),o=ae(I=>I.setSolutionEntityIds),s=ae(I=>I.setSolutionRibbonComponentIds),i=ae(I=>I.activeSolution),l=ae(I=>I.activeEntity),r=ae(I=>I.connectionVersion),c=M(I=>I.loadWorkspace),d=Y(I=>I.setTabId),u=Z(I=>I.themeMode),p=ce(I=>I.logInfo),m=ce(I=>I.logWarn),g=ce(I=>I.logError);A0(),WS();const[b,f]=E.useState("idle"),[y,x]=E.useState(null),[v,C]=E.useState(null),[$,A]=E.useState(null),[j,T]=E.useState(0);E.useEffect(()=>{p("runtime","Loading solutions and current user...");let I=!1;return s0().then(N=>{I||(e(N),p("runtime",`Loaded ${N.length} solution(s). Pick one to load its tables.`))}).catch(N=>{I||g("runtime",`Failed to load solutions: ${N instanceof Error?N.message:String(N)}`)}),k0().then(N=>{I||!N.id||(n(N.id,N.name),p("runtime",`Current user: ${N.name}.`))}).catch(N=>{m("runtime",`Failed to resolve current user: ${N instanceof Error?N.message:String(N)}`)}),()=>{I=!0}},[e,n,p,m,g,r]),E.useEffect(()=>{if(!i){o(null),s(null),t([]);return}let I=!1;return(async()=>{try{const[N,B]=await Promise.all([i0(i.id),a0(i.id)]);if(I)return;if(o(N),s(B),N.length===0){t([]);return}const O=await l0(N);if(I)return;t(O)}catch(N){if(I)return;g("runtime",`Failed to load solution tables: ${N instanceof Error?N.message:String(N)}`),o([]),s([]),t([])}})(),()=>{I=!0}},[i,t,o,s,g]),E.useEffect(()=>{if(je.getState().beginLoad(),!l?.logicalName){f("idle"),x(null),A(null);return}let I=!1;const N=Xd(l.logicalName);return f("loading"),x(null),A(null),C(null),p("ribbon",`Loading ribbon workspace for ${l.logicalName}...`),Yi.getState().setManaged([]),T0(l.logicalName).then(B=>{I||Yi.getState().setManaged(B)}),Promise.all([C0(l.logicalName,B=>{I||C(B)}),$0(l.logicalName).catch(()=>new Map)]).then(([B,O])=>{if(I)return;const S=new Set([...B.layers?.entity?.controlIds??[],...B.layers?.application?.controlIds??[]]);oy(B.ribbons,O,S);const k=[],w=new Set;for(const re of Object.values(B.ribbons))for(const le of re.tabs)for(const _ of le.groups)for(const L of Te(_))L.origin==="managed"&&!w.has(L.id)&&(w.add(L.id),k.push({elementId:L.id,elementKind:"button",solutions:[{solutionId:"",solutionName:L.solutionName??"Managed Solution",publisher:L.publisherName??"",managed:!0,wins:!0,importedOn:void 0}]}));M.getState().setConflicts(k),c({ribbons:B.ribbons,commands:B.commands,displayRules:B.displayRules,enableRules:B.enableRules,locLabels:B.locLabels,layers:B.layers,baseLanguageCode:B.baseLanguageCode,baseLanguageUnknown:B.baseLanguageCode===void 0,labelsUnknown:B.layerReadError!==void 0,orphans:{entity:f0(B.orphans??[],d0(ae.getState().connectionUrl,l.logicalName))}});const{location:D,tabId:F}=Y.getState(),X=B.ribbons[D]?.tabs??[];if(!(X.some(re=>re.id===F)&&!xo(F))){const re=mo(X);re&&d(re)}je.getState().workspaceLoaded(N),A(B.layerReadError??null),B.layerReadError&&m("ribbon",`Unmanaged layer not read: ${B.layerReadError}`),f("idle"),p("ribbon",`Ribbon workspace loaded for ${l.logicalName}.`)}).catch(B=>{if(I)return;const O=B instanceof Error?B.message:"Failed to load ribbon";f("error"),x(O),g("ribbon",`Ribbon load failed for ${l.logicalName}: ${O}`)}),()=>{I=!0}},[l?.logicalName,c,j,d,p,m,g]);function R(){x0(),T(I=>I+1)}return a.jsxs(Tg,{theme:u==="dark"?Ng:kg,children:[a.jsx(jv,{leftPane:a.jsx(o0,{}),rightPane:a.jsx(mC,{}),bottomPanel:a.jsx(UC,{}),children:a.jsx(jw,{isLoadingRibbon:b==="loading",loadingTable:l?.displayName??l?.logicalName,loadingStep:v,ribbonLoadError:y,layerReadError:$,onRetryRibbonLoad:R,emptyState:i?l?void 0:"noTable":"noSolution"})}),a.jsx(O0,{}),a.jsx(M0,{})]})}const E0=5e3,_l=3e4,bm="1.2.7";function ql(e,t,n){let o;return Promise.race([e,new Promise((s,i)=>{o=setTimeout(()=>i(new Error(n)),t)})]).finally(()=>clearTimeout(o))}async function B0(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 ${bm} or later.`);const s=[];let i="light";try{const r=t.utils?.getCurrentTheme;if(typeof r!="function")throw new Error("the host has no theme API");i=await ql(r(),E0,"the host didn't answer")==="dark"?"dark":"light"}catch(r){s.push(`Couldn't read the host theme (${xm(r)}); using the light theme.`)}const l=await ql(o(),_l,`Power Platform ToolBox didn't return the active connection within ${_l/1e3} seconds. Make sure a connection is active and signed in, then open Command Bar Studio again.`);if(!l)throw new Error("No active connection: connect to an environment in Power Platform ToolBox, then open Command Bar Studio again.");return{connection:l,theme:i,warnings:s}}function ym(e,t,n="Command Bar Studio couldn't start"){const o=e.ownerDocument,s=(c,d)=>{const u=o.createElement(c);return d&&(u.textContent=d),u},i=s("div");i.setAttribute("role","alert"),i.style.cssText="font-family: 'Segoe UI', system-ui, sans-serif; padding: 24px; max-width: 720px; line-height: 1.5;",i.append(s("h1",n));const l=s("p",xm(t));l.style.fontWeight="600",i.append(l);const r=s("ul");for(const c of["Close the Command Bar Studio tab and open the tool again.",`Use Power Platform ToolBox ${bm} or later (desktop app or VS Code extension).`,"Make sure a connection is active and signed in.","If it keeps happening, report it at https://github.com/mohsinonxrm/pptb-mxrm-commandbar-studio/issues with this message."])r.append(s("li",c));i.append(r),e.replaceChildren(i)}function xm(e){return e instanceof Error?e.message:String(e)}class L0 extends E.Component{state={error:void 0};box=E.createRef();static getDerivedStateFromError(t){return{error:t??new Error("Unknown error")}}componentDidCatch(t,n){console.error("[CBS RootErrorBoundary]",t,n),ce.getState().logError("app",t instanceof Error?t.message:String(t))}componentDidMount(){this.componentDidUpdate()}componentDidUpdate(){this.state.error!==void 0&&this.box.current&&ym(this.box.current,this.state.error,"Command Bar Studio stopped working")}render(){return this.state.error===void 0?this.props.children:a.jsx("div",{ref:this.box})}}function z0(e){return e.replace(/([A-Z])/g,(t,n,o)=>(o>0?"_":"")+t.toLowerCase())}function P0(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 vm(e,t="regular"){return`${z0(e)}${t==="filled"?".filled":""}.svg`}function F0(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/${vm(t,n)}`}const _0=11,q0=2*6e4,Wl={save:Yv,publish:Su},Sm=new Set;function W0(){Sm.clear()}async function SI(e,t,n,o,s={}){const i=s.save??Wl.save,l=s.publish??Wl.publish,r=s.published??Sm,c=F0(n,e,t),d=await o(e,20,t);if(!d)throw new Error(`Could not convert the Fluent icon "${e}" to SVG`);const u=await i(c,P0(d),_0,{displayName:`${vm(e,t)} (CBS icon)`,keepExisting:!0,guard:s.guard,publish:!1}),p={name:c,id:u.id,created:u.created};if(!r.has(u.id))try{await gu(`Publishing icon web resource ${c}`,()=>l(u.id,s.guard),{timeoutMs:q0,...s.busy}),r.add(u.id)}catch(m){p.publishError=m instanceof Error?m.message:String(m)}return p}const H0=["commandEditorOpen","ruleEditorOpen","iconPickerOpen","newGroupOpen","importXmlOpen","webResourceBrowserOpen","newTabOpen"];function G0(e){if(!e)return"none";const t=ae.getState(),n=ce.getState();if(Vo(e)===Vo({id:t.connectionId,url:t.connectionUrl}))return e.name===t.connectionName&&e.environment===t.environment?"none":(t.setConnection(e.url,e.name,e.environment,e.id),n.logInfo("startup",`Connection details updated: ${e.name} (${e.environment}).`),"details");const s=`${t.connectionName||t.connectionUrl} (${t.environment})`,i=`${e.name} (${e.environment})`,{hadChanges:l,kept:r}=je.getState().releaseForConnectionChange();M.getState().resetWorkspace(),Y.getState().clearSelection(),we.getState().reset(),W0(),HS(),na.clear(),t.switchConnection(e,{draftKept:l&&r,draftLost:l&&!r});try{Z.setState({...Object.fromEntries(H0.map(c=>[c,!1])),editorStack:[]})}catch(c){n.logWarn("startup",`Couldn't close the open panels after the connection change: ${c instanceof Error?c.message:String(c)}`)}return n.logWarn("startup",`The tool's connection changed from ${s} to ${i}. The loaded solution and table were closed.`),l&&r&&n.logInfo("startup",`The unpublished changes were kept as a draft for ${s}.`),l&&!r&&n.logError("startup",`The unpublished changes on ${s} couldn't be saved as a draft (browser storage full) and are lost.`),"switched"}async function U0(){const e=ce.getState().logInfo,t=window,n=t.toolboxAPI,{connection:o,theme:s,warnings:i}=await B0({toolboxAPI:n,dataverseAPI:t.dataverseAPI});e("startup","Connected to PPTB host runtime.");for(const m of i)ce.getState().logWarn("startup",m);e("startup",`Host theme loaded: ${s}.`);const{setConnection:l}=ae.getState(),{setThemeMode:r}=Z.getState(),c=await Ra().catch(()=>null)??o;l(c.url,c.name,c.environment,c.id),r(s),e("startup",`Connected to ${c.name} (${c.environment}).`),Hg(m=>G0(m));const d=()=>{n.utils.getCurrentTheme().then(m=>{Z.getState().setThemeMode(m==="dark"?"dark":"light")}).catch(m=>{ce.getState().logWarn("startup",`Theme refresh failed: ${m instanceof Error?m.message:String(m)}`)})};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&d()}),n.events?.on((m,g)=>{g?.event==="settings:updated"&&d()});const u=document.getElementById("root");if(!u)throw new Error("No #root element found");Pg.createRoot(u).render(a.jsx(E.StrictMode,{children:a.jsx(L0,{children:a.jsx(D0,{})})}))}U0().catch(e=>{ce.getState().logError("startup",e instanceof Error?e.message:String(e)),console.error(e);const t=document.getElementById("root")??document.body;ym(t,e)});export{gI as $,Z0 as A,eI as B,J0 as C,u0 as D,x0 as E,Ec as F,ce as G,zv as H,Wu as I,hI as J,aI as K,dI as L,ss as M,ab as N,gu as O,he as P,Fv as Q,Q0 as R,ae as S,Ra as T,Kd as U,uI as V,mI as W,Mx as X,oi as Y,mn as Z,ks as _,M as a,vI as a0,lI as a1,Y as a2,vd as a3,Db as a4,Wn as a5,Pr as a6,cI as a7,Yd as a8,js as a9,nm as aA,ir as aB,em as aC,na as aD,cu as aE,rI as aF,Nv as aG,Ow as aH,zw as aI,uo as aJ,Kv as aK,yI as aL,Rn as aM,pI as aN,wt as aO,so as aP,sI as aQ,xs as aR,ys as aS,bs as aT,dt as aa,zc as ab,Oi as ac,Zo as ad,Ge as ae,Xe as af,wd as ag,td as ah,Dr as ai,xo as aj,De as ak,je as al,Ss as am,Vt as an,bI as ao,Za as ap,z0 as aq,F0 as ar,Ea as as,px as at,SI as au,fI as av,xI as aw,Yv as ax,Gv as ay,tm as az,Z as b,Ib as c,iI as d,Bn as e,ty as f,ey as g,Jb as h,Bi as i,Qb as j,Zb as k,Fi as l,$a as m,id as n,Ko as o,Y0 as p,Jc as q,Zc as r,Ta as s,Te as t,Os as u,_c as v,tI as w,nI as x,Na as y,oI as z};
|