| 1 |
var desktopMode=function(Ts){"use strict";var Ns=typeof document<"u"?document.currentScript:null;function $f(){const e=window;e.wp=e.wp??{};const t=e.wp;t.desktop||(t.desktop={});const n=t.desktop;if(n.myWordpress)return;const o=[],s={registerEntityKind:(i,r)=>{const a={unregister:null},d={kind:i,renderer:r,slot:a};return o.push(d),()=>{if(a.unregister){a.unregister(),a.unregister=null;return}const c=o.indexOf(d);c!==-1&&o.splice(c,1)}},__pendingKinds:o};n.myWordpress=s}$f();function pt(){const e=window.wp?.hooks;if(!e)throw new Error("[desktop-mode] `window.wp.hooks` is not available. The plugin declares `wp-hooks` as a script dependency; if you are seeing this error, verify the enqueue order.");return e}function Ds(e,t,n,o){pt().addFilter(e,t,n,o)}function G(e,t,n,o){pt().addAction(e,t,n,o)}function ha(e,t){return pt().removeAction(e,t)}function j(e,t,...n){return pt().applyFilters(e,t,...n)}function A(e,...t){pt().doAction(e,...t)}function wa(e){return pt().didAction(e)}function Uf(){return pt()}const v={INIT:"desktop-mode.init",WALLPAPERS:"desktop-mode.wallpapers",UNFOCUS_EFFECTS:"desktop-mode.unfocus-effects",WALLPAPER_MOUNTING:"desktop-mode.wallpaper.mounting",WALLPAPER_MOUNTED:"desktop-mode.wallpaper.mounted",WALLPAPER_UNMOUNTING:"desktop-mode.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"desktop-mode.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"desktop-mode.wallpaper.visibility",WALLPAPER_PREVIEW_PARAMS:"desktop-mode.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"desktop-mode.wallpaper.settings-changed",IFRAME_READY:"desktop-mode.iframe.ready",IFRAME_ERROR:"desktop-mode.iframe.error",IFRAME_NETWORK_COMPLETED:"desktop-mode.iframe.network-completed",SHELL_ERROR:"desktop-mode.shell.error",BROADCAST:"desktop-mode.broadcast",MONITOR_ENTRY:"desktop-mode.monitor.entry",WALLPAPER_SURFACES:"desktop-mode.wallpaper.surfaces",WINDOW_GEOMETRY:"desktop-mode.window.geometry",WINDOW_OPENED:"desktop-mode.window.opened",WINDOW_CONTENT_LOADING:"desktop-mode.window.content-loading",WINDOW_CONTENT_LOADED:"desktop-mode.window.content-loaded",WINDOW_LOADING_OVERLAY:"desktop-mode.window.loading-overlay",WINDOW_REOPENED:"desktop-mode.window.reopened",WINDOW_CLOSING:"desktop-mode.window.closing",WINDOW_CLOSED:"desktop-mode.window.closed",WINDOW_FOCUSED:"desktop-mode.window.focused",WINDOW_BLURRED:"desktop-mode.window.blurred",WINDOW_MINIMIZED:"desktop-mode.window.minimized",WINDOW_RESTORED:"desktop-mode.window.restored",WINDOW_MAXIMIZED:"desktop-mode.window.maximized",WINDOW_UNMAXIMIZED:"desktop-mode.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"desktop-mode.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"desktop-mode.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"desktop-mode.window.auto-exit-fullscreen",WINDOW_FOCUS_ON_DRAG_HOVER:"desktop-mode.window.focus-on-drag-hover",WINDOW_BOUNDS_CHANGED:"desktop-mode.window.bounds-changed",WINDOW_MOVED:"desktop-mode.window.moved",WINDOW_RESIZED:"desktop-mode.window.resized",WINDOW_DRAG_START:"desktop-mode.window.drag-start",WINDOW_DRAG_END:"desktop-mode.window.drag-end",WINDOW_RESIZE_START:"desktop-mode.window.resize-start",WINDOW_RESIZE_END:"desktop-mode.window.resize-end",WINDOW_DETACHED:"desktop-mode.window.detached",WINDOW_RELOADED:"desktop-mode.window.reloaded",WINDOW_TITLE_CHANGED:"desktop-mode.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"desktop-mode.window.highlight-changed",WINDOW_BODY_RESIZED:"desktop-mode.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"desktop-mode.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"desktop-mode.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"desktop-mode.native-window.before-close",WINDOW_CHROME_THEME:"desktop-mode.window.chrome.theme",WINDOW_CHROME_CONTROLS:"desktop-mode.window.chrome.controls",WINDOW_CHROME_SLOT:"desktop-mode.window.chrome.slot",WINDOW_CHROME_RENDER:"desktop-mode.window.chrome.render",WINDOW_CHROME_APPLIED:"desktop-mode.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"desktop-mode.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"desktop-mode.desktop-icon.clicked",DESKTOP_ICONS_RENDERED:"desktop-mode.desktop-icons.rendered",ICON_BADGE_CHANGED:"desktop-mode.icon.badge-changed",COMPONENTS_REGISTERED:"desktop-mode.components.registered",DOCK_ITEM_APPENDED:"desktop-mode.dock.item-appended",DOCK_ITEM_REMOVED:"desktop-mode.dock.item-removed",DOCK_BEFORE_RENDER:"desktop-mode.dock.before-render",DOCK_AFTER_RENDER:"desktop-mode.dock.after-render",DOCK_TILE_CLASS:"desktop-mode.dock.tile-class",DOCK_TILE_ELEMENT:"desktop-mode.dock.tile-element",DOCK_TILE_RENDERED:"desktop-mode.dock.tile-rendered",DOCK_TILE_TOOLTIP:"desktop-mode.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"desktop-mode.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"desktop-mode.dock.peek-card-element",OVERVIEW_ENTERING:"desktop-mode.overview.entering",OVERVIEW_ENTERED:"desktop-mode.overview.entered",OVERVIEW_EXITING:"desktop-mode.overview.exiting",OVERVIEW_EXITED:"desktop-mode.overview.exited",OVERVIEW_WINDOW_HOVER:"desktop-mode.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"desktop-mode.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"desktop-mode.overview.window-click",ARRANGE_CASCADE_STARTING:"desktop-mode.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"desktop-mode.arrange.cascade.applied",ARRANGE_TILE_STARTING:"desktop-mode.arrange.tile.starting",ARRANGE_TILE_APPLIED:"desktop-mode.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"desktop-mode.arrange.tile.dimensions",ARRANGE_SNAP_CHANGED:"desktop-mode.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"desktop-mode.arrange.snap.cell-size",ARRANGE_CUSTOM_ACTION:"desktop-mode.arrange.custom-action",SNAP_ZONE_PENDING:"desktop-mode.snap.zone-pending",SNAP_ZONE_CANCELED:"desktop-mode.snap.zone-canceled",SNAP_ZONE_COMMITTED:"desktop-mode.snap.zone-committed",SNAP_SPLIT_FILLED:"desktop-mode.snap.split-filled",WIDGETS:"desktop-mode.widgets",WIDGET_MOUNTING:"desktop-mode.widget.mounting",WIDGET_MOUNTED:"desktop-mode.widget.mounted",WIDGET_UNMOUNTING:"desktop-mode.widget.unmounting",WIDGET_MOUNT_FAILED:"desktop-mode.widget.mount-failed",WIDGET_ADDED:"desktop-mode.widget.added",WIDGET_REMOVED:"desktop-mode.widget.removed",DESKTOP_CREATED:"desktop-mode.desktop.created",DESKTOP_CLOSED:"desktop-mode.desktop.closed",DESKTOP_SWITCHED:"desktop-mode.desktop.switched",PRIMARY_DESKTOP_ID:"desktop-mode.primary-desktop-id",WINDOWS_BEFORE_CLOSE_ALL:"desktop-mode.windows.before-close-all",WINDOWS_CLOSE_ALL:"desktop-mode.windows.close-all",WINDOWS_AFTER_CLOSE_ALL:"desktop-mode.windows.after-close-all",COMMAND_BEFORE_RUN:"desktop-mode.command.before-run",COMMAND_AFTER_RUN:"desktop-mode.command.after-run",COMMAND_ERROR:"desktop-mode.command.error",SHELL_RESIZED:"desktop-mode.shell.resized",SHELL_VISIBILITY:"desktop-mode.shell.visibility",CONNECTION_OPENED:"desktop-mode.connection.opened",CONNECTION_CLOSED:"desktop-mode.connection.closed",CONNECTION_MESSAGE:"desktop-mode.connection.message",IFRAME_CONNECTION_REQUEST:"desktop-mode.iframe.connection-request",WINDOW_CONTENT_CHANGED:"desktop-mode.window-links.content-changed",WINDOW_LINK_GROUPS_CHANGED:"desktop-mode.window-links.groups-changed",WINDOW_LINKS_CONTENT:"desktop-mode.window-links.content",WINDOW_LINK_GROUPS:"desktop-mode.window-links.groups",WINDOW_LINK_EDGES:"desktop-mode.window-links.edges",WINDOW_LINK_RENDERERS:"desktop-mode.window-links.renderers",WINDOW_LINK_RENDERER:"desktop-mode.window-links.renderer",FILE_DROP_FILES_DETECTED:"desktop-mode.drop.files-detected",FILE_DROP_FILES_REJECTED:"desktop-mode.drop.files-rejected",FILE_DROP_DIALOG_FIELDS:"desktop-mode.drop.dialog-fields",FILE_DROP_BEFORE_UPLOAD:"desktop-mode.drop.before-upload",FILE_DROP_UPLOAD_STARTED:"desktop-mode.drop.upload-started",FILE_DROP_UPLOAD_PROGRESS:"desktop-mode.drop.upload-progress",FILE_DROP_AFTER_UPLOAD:"desktop-mode.drop.after-upload",FILE_DROP_UPLOAD_FAILED:"desktop-mode.drop.upload-failed"};let Hf=0;function ga(e){if(wa(v.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++Hf}`;G(v.INIT,t,e)}function Bf(){return wa(v.INIT)>0}const Ff=["post_type","page","taxonomy","path","post","c","p"];function ya(e){return e.replace(/\.php/g,"-php").replace(/[?&=]/g,"-").replace(/[^a-zA-Z0-9_-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")||"index"}function ne(e,t){let n=null;try{n=new URL(e,t)}catch{n=null}if(n){const s=new URL(t).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams;for(const d of Ff){const c=n.searchParams.get(d);c&&r.set(d,c)}const a=r.toString();return ya(a?`${i}?${a}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),ya(o)}function zf(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function Gf(e){e.style.setProperty("--desktop-mode-file-tile-enter-delay",`${(Math.random()*.25).toFixed(3)}s`),e.style.setProperty("--desktop-mode-file-tile-enter-duration",`${(.3+Math.random()*.25).toFixed(3)}s`)}function ba(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("desktop_mode_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function xo(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("desktop_mode_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.searchParams.delete("_wp_http_referer"),t.searchParams.sort(),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function va(e){if(typeof e!="string"||e===""||typeof DOMParser>"u")return"";let t;try{t=new DOMParser().parseFromString(e,"image/svg+xml")}catch{return""}const n=t.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||t.getElementsByTagName("parsererror").length>0)return"";const o=new Set(["script","style","foreignobject","iframe","object","embed"]),s=i=>{const r=Array.from(i.children);for(const a of r){if(o.has(a.nodeName.toLowerCase())){a.remove();continue}for(const d of Array.from(a.attributes)){const c=d.name.toLowerCase(),l=d.value.trim().toLowerCase();if(c.startsWith("on")){a.removeAttribute(d.name);continue}l.startsWith("javascript:")&&a.removeAttribute(d.name)}s(a)}};s(n);for(const i of Array.from(n.attributes)){const r=i.name.toLowerCase(),a=i.value.trim().toLowerCase();(r.startsWith("on")||a.startsWith("javascript:"))&&n.removeAttribute(i.name)}return n.outerHTML}let Nt=null;function Co(){return!!window.desktopModeWindowSystem}function ka(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-window-system="1"]'),s=()=>{if(Co()){t();return}n(new Error("[desktop-mode] window-system bundle loaded but did not register `window.desktopModeWindowSystem`."))};if(o){Co()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeWindowSystem="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))),document.head.appendChild(i)})}function jf(){return window.desktopModeConfig?.windowSystemBundleUrl??""}function qf(e){!e||Co()||Nt||(Nt=ka(e).catch(t=>{Nt=null,typeof console<"u"&&console.warn("[desktop-mode] window-system preload failed; will retry on first open():",t)}))}async function Vf(e){if(Co())return window.desktopModeWindowSystem;if(!e){const t=window.desktopModeWindowSystem;if(t)return t;throw new Error("[desktop-mode] ensureWindowSystemLoaded(): no bundle URL configured and `window.desktopModeWindowSystem` is not pre-registered.")}return Nt||(Nt=ka(e)),await Nt,window.desktopModeWindowSystem}const Kf="wpd-confirm-dialog";let Dt=null;function on(){return typeof window.customElements<"u"&&!!window.customElements.get(Kf)}function _a(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-shell-overlays="1"]'),s=()=>{if(on()){t();return}n(new Error("[desktop-mode] shell-overlays bundle loaded but did not register the overlay components."))};if(o){on()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeShellOverlays="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(i)})}function Yf(e){!e||on()||Dt||(Dt=_a(e).catch(t=>{Dt=null,typeof console<"u"&&console.warn("[desktop-mode] shell-overlays preload failed; will retry on first overlay use:",t)}))}function Os(e){return on()||!e?Promise.resolve():(Dt||(Dt=_a(e)),Dt)}function Rs(){return window.desktopModeConfig?.shellOverlaysBundleUrl??""}function sn(e,t){const n=Rs();if(on()||!n){t();return}Os(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[desktop-mode] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Ea="desktop-mode";function Ms(){return window.wp?.i18n}function O(e,t=Ea){return Ms()?.__(e,t)??e}function rn(e,t,n,o=Ea){return Ms()?._n(e,t,n,o)??(n===1?e:t)}function oe(e,...t){const n=Ms()?.sprintf;if(n)return n(e,...t);let o=0;return e.replace(/%(?:(\d+)\$)?[sd]/g,(s,i)=>{const r=i?Number.parseInt(i,10)-1:o++;return String(t[r]??"")})}function Xf(e,t){if(!e||typeof e!="object")return!1;const n=e.cols,o=e.rows;return typeof n!="number"||typeof o!="number"||!Number.isFinite(n)||!Number.isFinite(o)||n<1||o<1?!1:Math.floor(n)*Math.floor(o)>=t}function Zf(e){if(!e||typeof e!="object")return!1;const t=e.cellWidth,n=e.cellHeight;return typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)?!1:t>0&&n>0}function Jf(e,t,n){if(e<=1)return{cols:1,rows:1};const o=t/Math.max(1,n),s=6;let i={cols:e,rows:1,score:1/0};for(let r=1;r<=Math.min(s,e);r++){const a=Math.min(s,Math.ceil(e/r));if(r*a<e)continue;const d=t/r/Math.max(1,n/a),c=Math.abs(d-o),l=r*a-e,u=c+l*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function Ws(e,t,n=0){const o=e.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,d=34,c=(t.width-r*2-a*(s-1))/s,l=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,l-d);return e.map((p,f)=>{const h=f%s,m=Math.floor(f/s),w=t.left+r+h*(c+a),g=t.top+n+r+m*(l+a)+d,x=p.element.offsetWidth,T=p.element.offsetHeight,y=Math.min(c/x,u/T),k=x*y,N=T*y;return{win:p,x:w+(c-k)/2,y:g+(u-N)/2,scale:y}})}const Sa=120,Ia=["adminmenumain","adminmenuback","desktop-mode-dock","desktop-mode-side-dock","desktop-mode-widgets"];function xa(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function Qf(e){if(e._overviewActive)return;const t=e._stack.filter(l=>l.config.desktopId===e._activeDesktopId);if(t.length>0&&t.every(l=>l.state==="minimized"))for(const l of t)try{l.restore()}catch(u){typeof console<"u"&&console.error("[desktop-mode] enterOverview: window.restore() threw for",l.id,u)}const n=e._stack.filter(l=>l.state!=="minimized"&&l.config.desktopId===e._activeDesktopId);e._overviewActive=!0,A(v.OVERVIEW_ENTERING,{});for(const l of Ia){const u=document.getElementById(l);u&&(u.inert=!0)}xa(!0);for(const l of e._stack)l.element.inert=!0;e._overviewSnapshot.clear();for(const l of n)e._overviewSnapshot.set(l.id,{transform:l.element.style.transform||"",transition:l.element.style.transition||""});for(const l of n)l.state==="fullscreen"&&l.toggleFullscreen();const o=e._desktop.getBoundingClientRect(),s=Array.from(document.querySelectorAll(".desktop-mode-dock"));let i=0;for(const l of s){const u=l.getBoundingClientRect(),p=u.bottom>o.top&&u.top<o.bottom,f=u.height>u.width;p&&f&&(i+=u.width)}const r=new DOMRect(0,0,o.width+i,o.height);e._desktop.classList.add("desktop-mode-area--overview"),document.getElementById("desktop-mode-shell")?.classList.add("desktop-mode-shell--overview"),e._overviewTopBar=Ca(e),e._desktop.appendChild(e._overviewTopBar);const d=Ws(n,r,Sa);e._overviewLabels.clear();for(const l of d){const u=l.win.element;u.classList.add("desktop-mode-window--overview");const p=l.x-u.offsetLeft,f=l.y-u.offsetTop;u.style.transform=`translate(${p}px, ${f}px) scale(${l.scale})`;const h=$s(l);u.insertAdjacentElement("afterend",h),e._overviewLabels.set(l.win.id,h)}const c=l=>{const u=l.target,p=u?.closest(".desktop-mode-window--overview");return p?{id:p.id.replace(/^wp-window-/,""),element:p}:u===e._desktop?{id:"backdrop",element:e._desktop}:null};e._overviewPointerDownHandler=l=>{if(l.button!==0){e._overviewPressTarget=null;return}e._overviewPressTarget=c(l),e._overviewPressTarget&&(l.preventDefault(),l.stopPropagation())},e._overviewPointerUpHandler=l=>{if(l.button!==0)return;const u=e._overviewPressTarget;if(e._overviewPressTarget=null,!u)return;const p=u.element.getBoundingClientRect();if(!(l.clientX>=p.left&&l.clientX<=p.right&&l.clientY>=p.top&&l.clientY<=p.bottom))return;if(l.preventDefault(),l.stopPropagation(),u.id==="backdrop"){ft(e);return}const h=e.getById(u.id);A(v.OVERVIEW_WINDOW_CLICK,{windowId:u.id}),ft(e,h,!0)},e._overviewKeyHandler=l=>{if(l.key==="Escape"){ft(e);return}if(l.key==="Enter"){const p=l.target?.ownerDocument||document;if(p.activeElement&&p.activeElement.tagName==="BUTTON")return;if(l.preventDefault(),e._overviewAddTileFocused){Aa(e);return}ft(e)}},e._desktop.addEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._desktop.addEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewClickBlocker=l=>{l.target?.closest(".desktop-mode-overview-top-bar")||(l.stopPropagation(),l.preventDefault())},e._desktop.addEventListener("click",e._overviewClickBlocker,!0),document.addEventListener("keydown",e._overviewKeyHandler),e._lastOverviewHoverId=null,e._overviewMouseHandler=l=>{const p=l.target?.closest(".desktop-mode-window--overview"),f=p?p.id.replace(/^wp-window-/,""):null;f!==e._lastOverviewHoverId&&(e._lastOverviewHoverId&&A(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&A(v.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&A(v.OVERVIEW_ENTERED,{})},300)}function em(e){e._overviewEnterTimeoutId!==null&&(window.clearTimeout(e._overviewEnterTimeoutId),e._overviewEnterTimeoutId=null),e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null)}function Ca(e){const t=document.createElement("div");t.className="desktop-mode-overview-top-bar";const n=document.createElement("div");n.className="desktop-mode-overview-top-bar__list",t.appendChild(n);for(const s of e._desktops)n.appendChild(tm(e,s));const o=document.createElement("button");return o.type="button",o.className="desktop-mode-overview-top-bar__tile desktop-mode-overview-top-bar__tile--add",e._overviewAddTileFocused&&o.classList.add("desktop-mode-overview-top-bar__tile--cursor"),o.setAttribute("aria-label",O("Add new desktop")),o.innerHTML='<span class="desktop-mode-overview-top-bar__tile-plus" aria-hidden="true">+</span>',o.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Aa(e)}),n.appendChild(o),t}function Aa(e){const t=Da(e);e._overviewAddTileFocused=!1,La(e,t.id)}function tm(e,t){const n=document.createElement("div");n.className="desktop-mode-overview-top-bar__tile-wrapper";const o=document.createElement("button");o.type="button",o.className="desktop-mode-overview-top-bar__tile",o.dataset.desktopId=t.id,t.id===e._activeDesktopId&&!e._overviewAddTileFocused&&o.classList.add("desktop-mode-overview-top-bar__tile--active"),o.setAttribute("aria-label",oe(O("Switch to %s"),t.label));const s=document.createElement("span");s.className="desktop-mode-overview-top-bar__tile-preview";const i=e._stack.filter(d=>d.config.desktopId===t.id).length;if(i>0){const d=document.createElement("span");d.className="desktop-mode-overview-top-bar__tile-count",d.textContent=String(i),s.appendChild(d)}o.appendChild(s);const r=document.createElement("span");r.className="desktop-mode-overview-top-bar__tile-label",r.textContent=t.label,o.appendChild(r),o.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),La(e,t.id)});const a=document.createElement("button");return a.type="button",a.className="desktop-mode-overview-top-bar__tile-close",a.setAttribute("aria-label",oe(O("Close %s"),t.label)),a.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2.5 2.5l7 7M9.5 2.5l-7 7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),Ra(e,t.id),Ps(e)}),n.appendChild(o),n.appendChild(a),n}function Ps(e){if(!e._overviewTopBar)return;const t=Ca(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function La(e,t){Oa(e,t),ft(e)}function $s(e){const t=document.createElement("div");t.className="desktop-mode-overview-label",t.dataset.windowId=e.win.id;const n=e.win.element.offsetWidth*e.scale;t.style.left=`${e.x}px`,t.style.top=`${e.y-34}px`,t.style.width=`${n}px`;const o=e.win.config.icon||"dashicons-admin-generic",s=document.createElement("span");s.className=`desktop-mode-overview-label__icon dashicons ${o}`,s.setAttribute("aria-hidden","true"),t.appendChild(s);const i=document.createElement("span");i.className="desktop-mode-overview-label__title",i.textContent=e.win.config.title,t.appendChild(i);const r=e.win.getExternalTabCount();if(r>0){const a=document.createElement("span");a.className="desktop-mode-overview-label__meta",a.textContent=oe(rn("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function ft(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,A(v.OVERVIEW_EXITING,{windowId:t&&n?t.id:void 0,reason:t&&n?"select":"cancel"}),e._desktop.classList.remove("desktop-mode-area--overview"),document.getElementById("desktop-mode-shell")?.classList.remove("desktop-mode-shell--overview");for(const i of Ia){const r=document.getElementById(i);r&&(r.inert=!1)}xa(!1);for(const i of e._stack)i.element.inert=!1;for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform)}t&&n&&(e.focus(t),t.maximize());for(const i of e._overviewLabels.values())i.classList.add("desktop-mode-overview-label--out");e._overviewTopBar&&e._overviewTopBar.classList.add("desktop-mode-overview-top-bar--out");const s=280;e._overviewExitTimeoutId=window.setTimeout(()=>{e._overviewExitTimeoutId=null;for(const i of e._stack)i.element.classList.remove("desktop-mode-window--overview");for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),e._overviewTopBar&&(e._overviewTopBar.remove(),e._overviewTopBar=null),e._overviewClickBlocker&&(e._desktop.removeEventListener("click",e._overviewClickBlocker,!0),e._overviewClickBlocker=null),A(v.OVERVIEW_EXITED,{windowId:t&&n?t.id:void 0,reason:t&&n?"select":"cancel"})},s),e._overviewPointerDownHandler&&(e._desktop.removeEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._overviewPointerDownHandler=null),e._overviewPointerUpHandler&&(e._desktop.removeEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewPointerUpHandler=null),e._overviewPressTarget=null,e._overviewKeyHandler&&(document.removeEventListener("keydown",e._overviewKeyHandler),e._overviewKeyHandler=null),e._overviewMouseHandler&&(e._desktop.removeEventListener("mouseover",e._overviewMouseHandler),e._overviewMouseHandler=null),e._lastOverviewHoverId&&(A(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function nm(e){return[...e._desktops]}function Ta(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function om(e){return Ta(e).id}function Na(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none"}function Us(e){for(const t of e._stack)Na(e,t)}function Da(e){e._desktopSeq++;const t={id:`desktop-${e._desktopSeq}`,label:oe(O("Desktop %d"),e._desktopSeq)};return e._desktops.push(t),A(v.DESKTOP_CREATED,{desktopId:t.id}),t}function Oa(e,t,n){if(t===e._activeDesktopId||!e._desktops.some(s=>s.id===t))return;const o=e._activeDesktopId;if(e._activeDesktopId=t,e._overviewActive)Ma(e),Ps(e);else{Us(e),n?.direction&&sm(e,n.direction);const s=[...e._stack].reverse().find(i=>i.config.desktopId===t&&i.state!=="minimized");s&&e.focus(s)}A(v.DESKTOP_SWITCHED,{from:o,to:t})}function sm(e,t){const n=e._desktop,o=t==="next"?"desktop-mode-area--sliding-from-right":"desktop-mode-area--sliding-from-left";n.classList.remove("desktop-mode-area--sliding-from-right","desktop-mode-area--sliding-from-left"),n.offsetWidth,n.classList.add(o);const s=i=>{i.animationName.startsWith("desktop-mode-area-slide-from-")&&(n.classList.remove(o),n.removeEventListener("animationend",s))};n.addEventListener("animationend",s)}function Ra(e,t){if(e._desktops.length<=1)return;const n=e._desktops.findIndex(r=>r.id===t);if(n===-1)return;const o=n>0?n-1:1,s=e._desktops[o];for(const r of e._stack)r.config.desktopId===t&&(r.config.desktopId=s.id);e._desktops.splice(n,1),e._activeDesktopId===t&&(e._activeDesktopId=s.id),e._overviewActive?Ma(e):Us(e),A(v.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function Ma(e){for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform,a.element.style.transition=r.transition,a.element.classList.remove("desktop-mode-window--overview"))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),Us(e);const t=e._stack.filter(i=>i.state!=="minimized"&&i.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const i of t)e._overviewSnapshot.set(i.id,{transform:i.element.style.transform||"",transition:i.element.style.transition||""});const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=Ws(t,o,Sa);for(const i of s){const r=i.win.element;r.classList.add("desktop-mode-window--overview");const a=i.x-r.offsetLeft,d=i.y-r.offsetTop;r.style.transform=`translate(${a}px, ${d}px) scale(${i.scale})`;const c=$s(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function im(e,t,n){if(t.length===0)return;e._desktops=t.map(s=>({...s})),e._activeDesktopId=t.some(s=>s.id===n)?n:t[0].id;let o=0;for(const s of t){const i=s.id.match(/^desktop-(\d+)$/);if(i){const r=parseInt(i[1],10);Number.isFinite(r)&&r>o&&(o=r)}}e._desktopSeq=Math.max(e._desktopSeq,o)}function rm(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;A(v.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=e._desktop.getBoundingClientRect(),o=30,s=30,i=Math.min(Math.round(n.width*.7),1100),r=Math.min(Math.round(n.height*.75),750),a=Math.max(1,Math.floor((n.width-i-o)/s)),d=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(a,d);t.forEach((u,p)=>{const f=p%Math.max(1,c);u.element.style.left=`${o+f*s}px`,u.element.style.top=`${o+f*s}px`,u.element.style.width=`${i}px`,u.element.style.height=`${r}px`});const l=e.getFocused();l&&e.focus(l),document.dispatchEvent(new CustomEvent("desktop-mode-window-changed",{detail:{reason:"cascade"}})),A(v.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function am(e){const t=e._stack.filter(p=>p.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const p of t)p.state==="minimized"&&p.restore(),p.state==="fullscreen"&&p.toggleFullscreen(),p.state==="maximized"&&p.toggleMaximize();const n=e._desktop.getBoundingClientRect(),o=Jf(t.length,n.width,n.height),s=j(v.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=Xf(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;A(v.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,d=12,c=Math.floor((n.width-a*2-d*(i-1))/i),l=Math.floor((n.height-a*2-d*(r-1))/r);t.forEach((p,f)=>{const h=f%i,m=Math.floor(f/i);p.element.style.left=`${a+h*(c+d)}px`,p.element.style.top=`${a+m*(l+d)}px`,p.element.style.width=`${c}px`,p.element.style.height=`${l}px`});const u=e.getFocused();u&&e.focus(u),document.dispatchEvent(new CustomEvent("desktop-mode-window-changed",{detail:{reason:"tile"}})),A(v.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}const Wa="desktop-mode-snap-to-grid";function dm(){try{return window.localStorage.getItem(Wa)==="1"}catch{return!1}}function cm(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(Wa,t?"1":"0")}catch{}A(v.ARRANGE_SNAP_CHANGED,{enabled:t})}}function lm(e){if(!e._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const t=e._desktop.getBoundingClientRect(),n=t.width>=t.height?12:8,o={cellWidth:Math.max(40,Math.round(t.width/n)),cellHeight:Math.max(40,Math.round(t.height/Math.round(n*.66)))},s=j(v.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=Zf(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function um(e,t,n){if(e._splitOverviewActive)return;e._splitOverviewActive=!0,e._splitOverviewAnchor=t,e._splitOverviewZone=n;const o=e._stack.filter(a=>a!==t&&a.state!=="minimized"&&a.config.desktopId===e._activeDesktopId);if(o.length===0){Pa(e);return}e._splitOverviewSnapshot.clear();for(const a of o)e._splitOverviewSnapshot.set(a.id,{transform:a.element.style.transform||"",transition:a.element.style.transition||""});e._desktop.classList.add("desktop-mode-area--split-overview");const s=wm(e,n),i=Ws(o,s,0);e._splitOverviewLabels.clear();for(const a of i){const d=a.win.element;d.classList.add("desktop-mode-window--overview");const c=a.x-d.offsetLeft,l=a.y-d.offsetTop;d.style.transform=`translate(${c}px, ${l}px) scale(${a.scale})`;const u=$s(a);d.insertAdjacentElement("afterend",u),e._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const d=a.target,c=d?.closest(".desktop-mode-window--overview");return c?{id:c.id.replace(/^wp-window-/,""),element:c}:d?{id:"dismiss",element:e._desktop}:null};e._splitOverviewPointerDown=a=>{if(a.button!==0){e._splitOverviewPressTarget=null;return}e._splitOverviewPressTarget=r(a),e._splitOverviewPressTarget&&(a.preventDefault(),a.stopPropagation())},e._splitOverviewPointerUp=a=>{if(a.button!==0)return;const d=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!d)return;const c=d.element.getBoundingClientRect();if(!(a.clientX>=c.left&&a.clientX<=c.right&&a.clientY>=c.top&&a.clientY<=c.bottom))return;if(a.preventDefault(),a.stopPropagation(),d.id==="dismiss"){an(e);return}const u=e.getById(d.id);if(!u){an(e);return}pm(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&an(e)},e._splitOverviewClickBlocker=a=>{a.stopPropagation(),a.preventDefault()},e._desktop.addEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._desktop.addEventListener("pointerup",e._splitOverviewPointerUp,!0),e._desktop.addEventListener("click",e._splitOverviewClickBlocker,!0),document.addEventListener("keydown",e._splitOverviewKey)}function pm(e,t){const n=e._splitOverviewZone;if(!n){an(e);return}const o=n==="left"?"right":"left";t.element.style.transform="",t.element.classList.remove("desktop-mode-window--overview"),t.applySnap(o),e._splitOverviewSnapshot.delete(t.id),e.focus(t),A(v.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),an(e)}function an(e){if(!e._splitOverviewActive)return;e._splitOverviewActive=!1;for(const[n,o]of e._splitOverviewSnapshot){const s=e.getById(n);s&&(s.element.style.transform=o.transform)}for(const n of e._splitOverviewLabels.values())n.classList.add("desktop-mode-overview-label--out");e._desktop.classList.remove("desktop-mode-area--split-overview"),window.setTimeout(()=>{for(const n of e._stack)e._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("desktop-mode-window--overview");for(const n of e._splitOverviewLabels.values())n.remove();Pa(e)},260),e._splitOverviewPointerDown&&(e._desktop.removeEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._splitOverviewPointerDown=null),e._splitOverviewPointerUp&&(e._desktop.removeEventListener("pointerup",e._splitOverviewPointerUp,!0),e._splitOverviewPointerUp=null),e._splitOverviewClickBlocker&&(e._desktop.removeEventListener("click",e._splitOverviewClickBlocker,!0),e._splitOverviewClickBlocker=null),e._splitOverviewKey&&(document.removeEventListener("keydown",e._splitOverviewKey),e._splitOverviewKey=null),e._splitOverviewPressTarget=null}function Pa(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const $a=30,fm=260;function mm(e,t){return e<=t.left+$a?"left":e>=t.right-$a?"right":null}function hm(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?0:n.width-o,y:0,width:o,height:s}}function wm(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return t==="left"?new DOMRect(o,0,o,s):new DOMRect(0,0,o,s)}function gm(e,t){if(e._snapPendingZone===t&&e._snapPreviewEl)return;if(e._snapPendingZone=t,!e._snapPreviewEl){const o=document.createElement("div");o.className="desktop-mode-snap-preview",o.setAttribute("aria-hidden","true"),e._desktop.appendChild(o),e._snapPreviewEl=o,Promise.resolve().then(()=>{o.classList.add("desktop-mode-snap-preview--visible")})}const n=hm(e,t);e._snapPreviewEl.style.left=`${n.x}px`,e._snapPreviewEl.style.top=`${n.y}px`,e._snapPreviewEl.style.width=`${n.width}px`,e._snapPreviewEl.style.height=`${n.height}px`,e._snapPreviewEl.dataset.zone=t}function Hs(e){if(!e._snapPreviewEl){e._snapPendingZone=null;return}const t=e._snapPreviewEl;e._snapPreviewEl=null,e._snapPendingZone=null,t.classList.remove("desktop-mode-snap-preview--visible"),window.setTimeout(()=>{t.remove()},fm)}function ym(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=mm(n,o),i=e._snapPendingZone;s?(gm(e,s),i!==s&&A(v.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(Hs(e),A(v.SNAP_ZONE_CANCELED,{windowId:t.id}))}function bm(e,t){const n=e._snapPendingZone;return n?(Hs(e),t.state==="normal"&&(t._savedGeometry={x:t.element.offsetLeft,y:t.element.offsetTop,width:t.element.offsetWidth,height:t.element.offsetHeight}),t.applySnap(n),A(v.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{um(e,t,n)}),!0):!1}function vm(e){e._snapPendingZone&&Hs(e)}const Ua="desktop-mode-native-window-geometry",Ha=64,Fe=8192;function Ao(){try{const e=window.localStorage.getItem(Ua);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function Ba(e){try{window.localStorage.setItem(Ua,JSON.stringify(e))}catch{}}function Fa(e){if(!e)return null;const n=Ao()[e];if(!n)return null;const o=Number(n.width),s=Number(n.height);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0||s<=0||o>Fe||s>Fe)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),a=Number(n.y),d=Number.isFinite(r)&&Number.isFinite(a)&&r>=0&&a>=0&&r<=Fe&&a<=Fe;return{width:Math.round(o),height:Math.round(s),...d?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function za(e,t){if(!e)return;const n=Math.round(Number(t.width)),o=Math.round(Number(t.height));if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0||n>Fe||o>Fe)return;const s=Ao(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,d=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===d||(dn(s,e,{width:n,height:o,...typeof a=="number"&&typeof d=="number"?{x:a,y:d}:{},...r?{state:r}:{}}),cn(s))}function Ga(e,t){if(!e)return;const n=Math.round(Number(t.x)),o=Math.round(Number(t.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>Fe||o>Fe)return;const s=Ao(),i=s[e];i&&(i.x===n&&i.y===o||(dn(s,e,{...i,x:n,y:o}),cn(s)))}function ja(e,t,n){if(!e)return;const o=Ao(),s=o[e];if(!s){if(t===null||!n)return;const i=Math.round(Number(n.width)),r=Math.round(Number(n.height));if(!Number.isFinite(i)||!Number.isFinite(r)||i<=0||r<=0||i>Fe||r>Fe)return;dn(o,e,{width:i,height:r,state:t}),cn(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;dn(o,e,r),cn(o);return}s.state!==t&&(dn(o,e,{...s,state:t}),cn(o))}function dn(e,t,n){delete e[t],e[t]=n}function cn(e){const t=Object.keys(e);if(t.length>Ha){const n={};for(const o of t.slice(-Ha))n[o]=e[o];Ba(n);return}Ba(e)}const qa=100,Lo=30;class km{constructor(t){this._stack=[],this.cascadeIndex=0,this._desktops=[{id:"desktop-1",label:"Desktop 1"}],this._activeDesktopId="desktop-1",this._desktopSeq=1,this.onToggleStartupRequested=null,this.desktopResizeObserver=null,this._reflowRestoreTimer=null,this._snapEnabled=dm(),this._overviewActive=!1,this._overviewSnapshot=new Map,this._overviewLabels=new Map,this._overviewPointerDownHandler=null,this._overviewPointerUpHandler=null,this._overviewKeyHandler=null,this._overviewPressTarget=null,this._overviewClickBlocker=null,this._overviewTopBar=null,this._overviewMouseHandler=null,this._lastOverviewHoverId=null,this._overviewAddTileFocused=!1,this._overviewEnterTimeoutId=null,this._overviewExitTimeoutId=null,this._snapPendingZone=null,this._snapPreviewEl=null,this._splitOverviewActive=!1,this._splitOverviewAnchor=null,this._splitOverviewZone=null,this._splitOverviewSnapshot=new Map,this._splitOverviewLabels=new Map,this._splitOverviewPointerDown=null,this._splitOverviewPointerUp=null,this._splitOverviewPressTarget=null,this._splitOverviewClickBlocker=null,this._splitOverviewKey=null,this._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const t=this._desktop.ownerDocument?.activeElement??null;if(!t||t.tagName!=="IFRAME")return;const n=t.closest(".desktop-mode-window");if(!n)return;const o=n.id.replace(/^wp-window-/,""),s=this.getById(o);s&&(this._overviewActive||this.getFocused()!==s&&this.focus(s))},0)})}reflowStatefulWindows(){if(!this._overviewActive){for(const t of this._stack){const n=t.element.parentElement;if(n){if(t.state==="maximized")t.element.classList.add("desktop-mode-window--reflowing"),t.element.style.width=`${n.clientWidth}px`,t.element.style.height=`${n.clientHeight}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("desktop-mode-window--reflowing");const o=Math.floor(n.clientWidth/2),s=n.clientHeight,i=t.state==="snapped-left"?0:o;t.element.style.left=`${i}px`,t.element.style.top="0px",t.element.style.width=`${o}px`,t.element.style.height=`${s}px`}}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const t of this._stack)t.element.classList.remove("desktop-mode-window--reflowing")},140)}}async open(t){if(!t||typeof t!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(t===null?"null":typeof t));if(typeof t.id!="string"||t.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof t.url!="string"||t.url==="")throw new TypeError('windowManager.open(): config.url must be a non-empty string. Pass an admin URL (e.g. "/wp-admin/edit.php") or a hash fragment (e.g. "#my-window") for native windows.');if(typeof t.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=t.baseId||t.id,o=this.getByBaseIdOnActiveDesktop(n);if(o){const i=o.state==="minimized";this.focus(o),i&&o.restore();let r=!1;if(!o.config.native){const d=xo(t.url);d===xo(o.getCurrentUrl())||d===xo(o.config.url||"")||d===xo(o.config.parentUrl??o.config.url??"")||(r=o.navigateTo(t.url))}const a={windowId:o.id,baseId:n,wasMinimized:i,navigated:r};return document.dispatchEvent(new CustomEvent("desktop-mode-window-reopened",{detail:a})),A(v.WINDOW_REOPENED,a),o}const s=this.getByBaseId(n)?this.nextInstanceId(n):t.id;return this.createWindow({...t,id:s,baseId:n})}async openNew(t){const n=t.baseId||t.id,o=this.nextInstanceId(n),s=40+this.cascadeIndex%8*Lo,i=40+this.cascadeIndex%8*Lo;return this.createWindow({initialState:"normal",x:s,y:i,...t,id:o,baseId:n})}async createWindow(t){const n=this._desktop.getBoundingClientRect(),o=Math.min(Math.round(n.width*.8),1200),s=Math.min(Math.round(n.height*.8),800),i=40+this.cascadeIndex%8*Lo,r=40+this.cascadeIndex%8*Lo,a=t.baseId||t.id,d=t.minWidth??320,c=t.minHeight??200,l=typeof t.width=="number",u=typeof t.height=="number",p=typeof t.x=="number",f=typeof t.y=="number",h=typeof t.initialState=="string",m=!l||!u||!h||!p||!f?Fa(a):null,w=t.width??(m?Math.max(m.width,d):o),g=t.height??(m?Math.max(m.height,c):s),x=t.initialState??(m?.state==="maximized"?"maximized":void 0);let T,y;if(m&&typeof m.x=="number"&&typeof m.y=="number"){const $=Math.max(0,n.width-w-12),Z=Math.max(0,n.height-g-12);T=Math.max(12,Math.min(m.x,$)),y=Math.max(12,Math.min(m.y,Z))}const k=t.x??T??i,N=t.y??y??r,b=l||u||p||f||h,L=!!m,D={x:k,y:N,width:w,height:g,state:x};let C;try{C=j(v.WINDOW_GEOMETRY,D,{windowId:t.id,baseId:a,hasSavedGeometry:L,callerPinned:b,desktopRect:{width:n.width,height:n.height}})}catch(M){A(v.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:M}),typeof console<"u"&&console.error(`[desktop-mode] WINDOW_GEOMETRY filter threw for "${t.id}":`,M),C=D}const S=(M,$)=>typeof M=="number"&&Number.isFinite(M)?M:$,I=C&&typeof C=="object"?C:D,R=Math.max(S(I.width,w),d),F=Math.max(S(I.height,g),c),K=S(I.x,k),X=S(I.y,N),E=I.state??x,P={icon:t.icon||"dashicons-admin-generic",...t,x:K,y:X,width:R,height:F,minWidth:d,minHeight:c,...E?{initialState:E}:{},baseId:a,desktopId:t.desktopId||this._activeDesktopId};this.cascadeIndex++;const[H]=await Promise.all([Vf(jf()),Os(Rs())]),W=H.createWindow(P);W.onFocusRequest=M=>this.focus(M),W.onClose=M=>this.remove(M),W.onMinimize=()=>{const M=this._stack.filter($=>$.state!=="minimized");M.length>0&&this.focus(M[M.length-1])},W.onOpenAnother=M=>{const $=M.config.baseId||M.id;M.config.native&&window.wp?.desktop?.openNewWindow?.($,{source:"open-another"})||this.openNew({id:$,baseId:$,url:M.config.url||"",title:M.config.title,icon:M.config.icon,submenu:M.config.submenu,multi:!0})},W.onOpenInNewWindow=M=>{const $=M.config.baseId||M.id;if(M.config.native&&window.wp?.desktop?.openNewWindow?.($,{source:"open-in-new-window"}))return;const Z=M.getCurrentUrl();this.openNew({id:$,baseId:$,url:Z||M.config.url||"",title:M.config.title,icon:M.config.icon,submenu:M.config.submenu,multi:!0})},W.onToggleStartup=M=>{this.onToggleStartupRequested?.(M)},W.snapConfigProvider=()=>this.getSnapConfig(),W.onDragMove=(M,$)=>{ym(this,M,$)},W.onDragEnd=M=>this._snapPendingZone?bm(this,M):(vm(this),!1),this._stack.push(W),this._desktop.appendChild(W.element),Na(this,W),W.hydrateNative(),this.focus(W);const V={windowId:W.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("desktop-mode-window-opened",{detail:V})),A(v.WINDOW_OPENED,V),W}nextInstanceId(t){const n=new Set(this._stack.map(s=>s.id));if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=this._stack.length>0?this._stack[this._stack.length-1]:null,o=this._stack.find(r=>r!==t&&r.isFocused()&&r.isFullscreen());o&&j(v.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:o.id,focusedTo:t.id})&&o.toggleFullscreen();const s=this._stack.indexOf(t);if(s>-1&&this._stack.splice(s,1),this._stack.push(t),this._stack.forEach((r,a)=>{r.setZIndex(qa+a),r.setFocused(a===this._stack.length-1)}),n&&n!==t&&n.id!==t.id){const r={windowId:n.id,focusedTo:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-blurred",{detail:r})),A(v.WINDOW_BLURRED,r)}const i={windowId:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-focused",{detail:i})),A(v.WINDOW_FOCUSED,i)}raise(t){const n=this.getById(t);if(!n||this._stack.length<2)return;const o=this._stack.indexOf(n);o===-1||o===this._stack.length-1||(this._stack.splice(o,1),this._stack.splice(this._stack.length-1,0,n),this._stack.forEach((s,i)=>{s.setZIndex(qa+i)}))}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);for(let i=this._stack.length-1;i>=0;i--){const r=this._stack[i];if(!(r.state==="minimized"||(r.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(r);break}}const o={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("desktop-mode-window-closing",{detail:o})),A(v.WINDOW_CLOSING,o);const s={windowId:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-closed",{detail:s})),A(v.WINDOW_CLOSED,s)}getById(t){return this._stack.find(n=>n.id===t)}getByBaseId(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===t)return o}}getByBaseIdOnActiveDesktop(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==t)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(t){const n=o=>{if(o===t)return 1;const s=`${t}-`;if(o.startsWith(s)){const i=parseInt(o.slice(s.length),10);return Number.isFinite(i)?i:999}return 999};return this._stack.filter(o=>(o.config.baseId||o.id)===t).sort((o,s)=>n(o.id)-n(s.id))}getAllByBaseIdOnActiveDesktop(t){return this.getAllByBaseId(t).filter(n=>(n.config.desktopId||this._activeDesktopId)===this._activeDesktopId)}getAll(){return[...this._stack]}findByIframeSource(t){if(t)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===t)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(t){const n=this.getById(t);if(!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)return!1;const s=this.getFocused();return!!s&&s.id===t}isActiveByBaseId(t){const n=this.getFocused();return!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId?!1:(n.config.baseId||n.id)===t}getDesktops(){return nm(this)}getActiveDesktop(){return Ta(this)}getActiveDesktopId(){return om(this)}createDesktop(){return Da(this)}switchDesktop(t,n){Oa(this,t,n)}closeDesktop(t){Ra(this,t)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=j(v.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(d=>!n.has(d.id));A(v.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=j(v.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(d=>!i.includes(d));let a=0;for(const d of i.slice())try{d.close(),a++}catch(c){typeof console<"u"&&console.error("[desktop-mode] closeAll: window.close() threw for",d.id,c)}return A(v.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r}),a}minimizeAll(){const t=[];for(const n of this._stack.slice())if((n.config.desktopId||this._activeDesktopId)===this._activeDesktopId&&n.state!=="minimized")try{n.minimize(),t.push(n)}catch(s){typeof console<"u"&&console.error("[desktop-mode] minimizeAll: window.minimize() threw for",n.id,s)}return t}restoreFrom(t){if(!Array.isArray(t))return;const n=new Set(this._stack);for(const o of t)if(!(!n.has(o)||(o.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)&&o.state==="minimized")try{o.restore()}catch(i){typeof console<"u"&&console.error("[desktop-mode] restoreFrom: window.restore() threw for",o.id,i)}}toggleShowDesktop(){const t=this._stack.filter(o=>(o.config.desktopId||this._activeDesktopId)===this._activeDesktopId);if(t.length===0)return!1;if(t.every(o=>o.state==="minimized")){for(const o of t)try{o.restore()}catch{}return!1}return this.minimizeAll(),!0}cascade(){rm(this)}tile(){am(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){cm(this,t)}getSnapConfig(){return lm(this)}enterOverview(){Qf(this)}exitOverview(t,n=!1){ft(this,t,n)}destroy(){this._overviewActive&&ft(this),em(this)}getVisibleRects(){return this._stack.map(t=>{const n=t.getSnapshot();return{windowId:t.id,rect:{x:n.x,y:n.y,width:n.width,height:n.height},state:n.state,element:t.element}})}snapshot(){const t=this.getFocused(),o=this._stack.filter(i=>!i.config.native).map(i=>{const r=i.getSnapshot(),a=i.getExternalTabsSnapshot();return{id:i.id,baseId:i.config.baseId||i.id,desktopId:i.config.desktopId||this._activeDesktopId,url:i.getCurrentUrl(),title:i.config.title,icon:i.config.icon,state:r.state,x:r.x,y:r.y,width:r.width,height:r.height,...a.length>0?{externalTabs:a}:{}}}),s=t&&!t.config.native?t.id:"";return{windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Math.floor(Date.now()/1e3)}}seedDesktops(t,n){im(this,t,n)}}function _m(e){const t=e.getActiveDesktopId(),n=Array.from(e._desktop.children);return e.getAll().filter(o=>(o.config.desktopId||t)===t).sort((o,s)=>n.indexOf(o.element)-n.indexOf(s.element))}function Va(e,t){if(e._overviewActive)return;const n=_m(e);if(n.length<2)return;const o=e.getFocused(),r=((o?n.indexOf(o):-1)+(t==="next"?1:-1)+n.length)%n.length,a=n[r];a.state==="minimized"?a.restore():e.focus(a)}let Ka=!1;function Ya(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;if(!t)return!1;if(t instanceof HTMLIFrameElement||t instanceof HTMLTextAreaElement)return!0;if(t instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(t.type);if(t instanceof HTMLElement&&t.isContentEditable===!0)return!0;const n=t.getAttribute("contenteditable");return n!==null&&n!=="false"}function Em(e){if(Ka)return;Ka=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(Ya(document)||(n.preventDefault(),Va(e,n.shiftKey?"prev":"next")))},!0);const t=window.location.origin;window.addEventListener("message",n=>{if(n.origin!==t)return;const o=n.data;!o||o.type!=="desktop-mode-window-switch"||Va(e,o.direction==="prev"?"prev":"next")})}function Xa(e,t){const n=e.getDesktops();if(n.length<2)return!1;const o=e.getActiveDesktopId(),s=n.findIndex(a=>a.id===o);if(s===-1)return!1;const r=(s+(t==="next"?1:-1)+n.length)%n.length;return r===s?!1:(e.switchDesktop(n[r].id,{direction:t}),!0)}function Za(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(d=>d.id===e.getActiveDesktopId());if(i===-1)return!1;const a=(i+(t==="next"?1:-1)+o)%o;return a===i?!1:a===s?(e._overviewAddTileFocused=!0,Ps(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function Sm(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function Im(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Ja(e){return e._overviewActive?(e.exitOverview(),!0):!1}function xm(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function Cm(e){return xm(e)?(e.toggleShowDesktop(),!0):!1}let Qa=!1;function Am(e){Qa||(Qa=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||Ya(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Za(e,"prev"):Xa(e,"prev");break;case"ArrowRight":n=e._overviewActive?Za(e,"next"):Xa(e,"next");break;case"ArrowUp":n=Ja(e)||Cm(e)||Sm(e);break;case"ArrowDown":n=Ja(e)||Im(e);break}n&&t.preventDefault()},!0))}const ed=new Map,Lm=new Map;function Bs(e,t,n,o){let s=e.get(t);if(!s){if(!o)return;s=new Map,e.set(t,s)}let i=s.get(n);if(!i){if(!o)return;i=new Set,s.set(n,i)}return i}function td(e,t,n,o){const s={channel:n,windowId:t},i=Bs(e,t,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(d){typeof console<"u"&&console.error(`[desktop-mode] window-channel subscriber for "${n}" threw:`,d)}const r=Bs(e,t,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(d){typeof console<"u"&&console.error(`[desktop-mode] window-channel wildcard subscriber for "${t}" threw:`,d)}}function Tm(e,t,n){const o=Bs(ed,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function Nm(e,t,n){td(ed,e,t,n)}function Dm(e,t,n){td(Lm,e,t,n)}const nd=new Set,Om=new Set,od=new Map;function Rm(e){if(!nd.has(e)){nd.add(e);const t=od.get(e);if(t){od.delete(e);for(const n of t)try{n.flush()}catch(o){typeof console<"u"&&console.error(`[desktop-mode] flushing queued window-send for "${n.channel}" threw:`,o)}}}Om.delete(e)&&(A(v.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("desktop-mode-window-content-loaded",{detail:{windowId:e}})))}const Mm=Symbol.for("desktop-mode/window-config");function Wm(e){return e[Mm]}function sd(){const e=document.createElement("div");e.className="desktop-mode-window__loading",e.setAttribute("aria-hidden","true");const t=document.createElement("wpd-spinner");return t.setAttribute("preset","classic"),t.setAttribute("size","clamp(96px, 14vw, 192px)"),t.setAttribute("label",O("Loading window content")),e.appendChild(t),e}function Pm(e){let t=sd();const n={windowId:e.id,config:e};if(typeof e.loading?.render=="function")try{e.loading.render(t,n)}catch(o){typeof console<"u"&&console.error(`[desktop-mode] loading.render threw for "${e.id}":`,o)}try{const o=j(v.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[desktop-mode] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains("desktop-mode-window__loading")&&t.classList.add("desktop-mode-window__loading"),t}function $m(e){e.querySelector(":scope .desktop-mode-window__loading")?.remove()}function id(e){const t=e.querySelector(":scope .desktop-mode-window__body");if(!t||t.querySelector(":scope .desktop-mode-window__loading"))return;const o=Wm(e);t.appendChild(o?Pm(o):sd())}const Um=250;let rd=!1;function ad(e){return e?document.getElementById(`wp-window-${e}`):null}function Hm(){rd||(rd=!0,Bm())}function Bm(){G(v.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=ad(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .desktop-mode-window__body");n&&(n.classList.add("desktop-mode-window__body--loading"),id(t))}),G(v.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=ad(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .desktop-mode-window__body");n&&(n.classList.remove("desktop-mode-window__body--loading"),window.setTimeout(()=>{n.classList.contains("desktop-mode-window__body--loading")||$m(t)},Um))}),G(v.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>dd())})}function dd(){document.querySelectorAll(".desktop-mode-window__body--loading").forEach(t=>{const n=t.closest(".desktop-mode-window");n&&(t.querySelector(":scope .desktop-mode-window__loading")?.remove(),id(n))})}const cd="__desktopModeSharedStores";function Fm(){const e=window;let t=e[cd];return t||(t=new Map,e[cd]=t),t}function re(e,t){const n=Fm();let o=n.get(e);o||(o={state:t(),listeners:new Set,rebuild:t},n.set(e,o));const s={get state(){return o.state},set state(i){o.state=i},getState(){return o.state},notify(){for(const i of Array.from(o.listeners))try{i(o.state)}catch(r){console.error(`[desktop-mode/shared-store:${e}] subscriber threw:`,r)}},subscribe(i){return o.listeners.add(i),()=>{o.listeners.delete(i)}},setState(i){const r=o.state;if(typeof r!="object"||r===null){console.warn(`[desktop-mode/shared-store:${e}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(r,i),s.notify()},reset(){const i=o.rebuild(),r=o.state;if(typeof r=="object"&&r!==null&&typeof i=="object"&&i!==null){const a=r;for(const d of Object.keys(a))delete a[d];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}const ln=re("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function zm(e){ln.state.deps=e}function Ot(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.nativeWindowId!="string"||e.nativeWindowId==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=ln.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Gm(e.id)}function Gm(e){const t=ln.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function ld(e){const{deps:t,remaps:n}=ln.state;if(!t||!e)return null;let o;try{o=new URL(e,t.adminUrl)}catch{return null}const s=t.getSnapshot();for(const i of n)if(i.matches(e,o)&&!(i.enabled&&!i.enabled(s)))return i.nativeWindowId;return null}function mt(e){const{deps:t,remaps:n}=ln.state;if(!t||!e)return!1;let o;try{o=new URL(e,t.adminUrl)}catch{return!1}const s=t.getSnapshot();for(const i of n)if(i.matches(e,o)&&!(i.enabled&&!i.enabled(s))){if(i.onMatch)try{i.onMatch(e,o)}catch(r){console.warn(`[desktop-mode] URL remap onMatch hook threw for "${i.id}":`,r)}if(t.openById(i.nativeWindowId))return!0}return!1}const jm="desktop-mode.activity.";function Fs(e){return`${jm}${String(e)}`}let qm=0;const ye={publish(e,t){A(Fs(e),t)},subscribe(e,t){const n=`desktop-mode/activity-sub/${++qm}`,o=Fs(e);G(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,ha(o,n))}},filter(e,t,...n){return j(Fs(e),t,...n)}},Vm=4e3,Km=200;function ee(e){const t=ye.filter("desktop-mode/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return sn(()=>!n,()=>{o=Ym(t)}),()=>{n=!0,o&&o()}}function Ym(e){const t=Xm(),n=document.createElement("wpd-toast");n.textContent=e.message,e.action&&(n.setAttribute("action",e.action.label),n.addEventListener("wpd-toast-action",()=>{e.action?.onClick(),i()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("wpd-toast-dismiss",()=>{e.onDismiss?.(),i()})),t.appendChild(n);let o=!1,s=null;const i=()=>{o||(o=!0,s!==null&&(window.clearTimeout(s),s=null),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove()},Km))};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),e.persistent||(s=window.setTimeout(i,e.duration??Vm)),ye.publish("desktop-mode/toast-shown",{...e}),i}function Xm(){const e=document.querySelector("wpd-toast-container");if(e)return e;const t=document.createElement("wpd-toast-container");return document.body.appendChild(t),t}const zs=re("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function Zm(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=zs.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>ud(e.id)}function ud(e){const t=zs.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function Jm(){return zs.state.entries.slice()}function un(e,t){if(!e||typeof e!="object")return["def (not an object)"];const n=e,o=[];for(const s of t)s.valid(n)||o.push(`${s.field} (${s.message})`);return o}class Qm extends Error{constructor(t,n,o){super(`[desktop-mode] ${t} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=t,this.errors=n,this.def=o}}function Oe(e,t,n){if(t.length!==0)throw new Qm(e,t,n)}function pd(e,t,n){typeof console>"u"||console.warn(`[desktop-mode] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const eh=32,th=/^[a-z0-9_/-]+$/,ie=re("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function ht(e){return`${e.type}:${e.id}`}function fd(e){return e.root?ht(e.root):ht(e)}function md(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&th.test(o.trim().toLowerCase());return un(e,[{field:"type",valid:o=>n(o.type),message:"must match /^[a-z0-9_/-]+$/ — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-type"},{field:"id",valid:o=>t(o.id),message:"must be a finite number or non-empty string"},{field:"root",valid:o=>o.root===void 0||!!o.root&&typeof o.root=="object"&&n(o.root.type)&&t(o.root.id),message:"when present, must be { type, id } with the same shapes as the ref itself"},{field:"links",valid:o=>o.links===void 0||Array.isArray(o.links)&&o.links.every(s=>!!s&&typeof s=="object"&&n(s.type)&&t(s.id)&&(s.rel===void 0||s.rel==="references"||s.rel==="child")),message:"when present, must be an array of { type, id, rel?: 'references'|'child' } entries"}])}function nh(e,t){const n={type:e.type.trim().toLowerCase(),id:e.id,source:t};return e.root&&(n.root={type:e.root.type.trim().toLowerCase(),id:e.root.id}),Array.isArray(e.links)&&e.links.length>0&&(n.links=e.links.slice(0,eh).map(o=>{const s={type:o.type.trim().toLowerCase(),id:o.id};return o.rel==="child"&&(s.rel="child"),s})),typeof e.label=="string"&&e.label!==""&&(n.label=e.label),n}function Gs(e){return e?[ht(e),fd(e),...(e.links??[]).map(t=>ht(t)+(t.rel==="child"?"!child":""))].join("|"):""}function To(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Oe("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=md(t);if(a.length>0){o==="api"&&Oe("WindowContentRef",a,t),pd("WindowContentRef",a,t);return}s=nh(t,o)}if(s=j(v.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||md(s).length>0)){pd("WindowContentRef",["filter (desktop-mode.window-links.content returned an invalid ref)"],s);return}const i=ie.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&Gs(s)===Gs(i)&&s.label===i.label)return;s===null?ie.state.contentByWindow.delete(e):ie.state.contentByWindow.set(e,s);const r={windowId:e,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("desktop-mode-window-content-changed",{detail:r})),A(v.WINDOW_CONTENT_CHANGED,r),rh(),sh()}function hd(e){return ie.state.contentByWindow.get(e)}function No(){const e=new Map;for(const[s,i]of ie.state.contentByWindow){const r=fd(i);let a=e.get(r);a||(a={key:r,root:i.root?{...i.root}:{type:i.type,id:i.id},rootWindowIds:[],children:[]},e.set(r,a)),i.root?a.children.push({windowId:s,content:i}):a.rootWindowIds.push(s)}const t=ie.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=j(v.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function wd(e){return No().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function gd(e){const t=new Set,n=wd(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of pn())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function oh(e){const t=new Set;for(const n of pn())n.fromWindowId===e?t.add(n.toWindowId):n.toWindowId===e&&t.add(n.fromWindowId);return t.delete(e),Array.from(t)}function pn(){const e=ie.state.focusSeq,t=new Map;for(const[a,d]of ie.state.contentByWindow){const c=ht(d),l=t.get(c);(!l||(e.get(a)??0)>(e.get(l)??0))&&t.set(c,a)}const n=new Map,o=(a,d)=>`${a}→${d}`;for(const[a,d]of ie.state.contentByWindow){if(d.root){const c=t.get(ht(d.root));c&&c!==a&&n.set(o(a,c),{fromWindowId:a,toWindowId:c,kind:"child-root",bidirectional:!1})}for(const c of d.links??[]){const l=t.get(ht(c));if(!l||l===a)continue;if(c.rel==="child"){const p=o(l,a),f=n.get(p);(!f||f.kind!=="child-root")&&n.set(p,{fromWindowId:l,toWindowId:a,kind:"child-root",bidirectional:!1});continue}const u=o(a,l);n.has(u)||n.set(u,{fromWindowId:a,toWindowId:l,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[a,d]of n){if(i.has(a))continue;const c=o(d.toWindowId,d.fromWindowId),l=n.get(c);if(l&&d.kind==="reference"){if(l.kind==="reference"){i.add(c),s.push({...d,bidirectional:!0});continue}continue}s.push(d)}const r=j(v.WINDOW_LINK_EDGES,s);return Array.isArray(r)?r:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.window-links.edges` filter returned a non-array; falling back to derived edges."),s)}function yd(e){return ie.state.listeners.add(e),()=>{ie.state.listeners.delete(e)}}function sh(){for(const e of Array.from(ie.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[desktop-mode] window-links listener threw:",t)}}function ih(){return Array.from(ie.state.contentByWindow).map(([e,t])=>`${e}=${Gs(t)}`).sort().join(";")}function rh(){const e=ih();if(e===ie.state.lastGroupsSignature)return;ie.state.lastGroupsSignature=e;const n={groups:No()};document.dispatchEvent(new CustomEvent("desktop-mode-window-link-groups-changed",{detail:n})),A(v.WINDOW_LINK_GROUPS_CHANGED,n)}const ah={get:hd,set:(e,t)=>To(e,t,{source:"api"}),groups:No,edges:pn,groupOf:wd,related:gd,subscribe:yd};function dh({manager:e}){ie.state.manager=e,!ie.state.started&&(ie.state.started=!0,G(v.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=ie.state.manager?.getById(t.windowId)?.config?.content;o&&To(t.windowId,o,{source:"config"})}),G(v.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(ie.state.focusSeq.delete(t.windowId),To(t.windowId,null,{source:"config"}))}),G(v.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(ie.state.seq+=1,ie.state.focusSeq.set(t.windowId,ie.state.seq))}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t.data;if(!n||n.type!=="desktop-mode-content-identity")return;const o=ie.state.manager?.findByIframeSource?.(t.source);o&&To(o.id,n.identity??null,{source:"bridge"})}))}const ch=re("desktop-mode/admin-link-deps",()=>({deps:null}));function lh(e){ch.state.deps=e}const bd=re("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),Rt=bd.state.seed,uh=bd.state.listeners;function fn(e){Oe("Wallpaper",un(e,Ed),e);const t=Rt.findIndex(n=>n.id===e.id);t>=0?Rt[t]=e:Rt.push(e),kd()}function vd(e){const t=Rt.findIndex(n=>n.id===e);t>=0&&(Rt.splice(t,1),kd())}function kd(){const e=Array.from(uh);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] wallpaper registry listener threw:",n)}}function _d(){const e=Rt.slice(),t=j(v.WALLPAPERS,e);return Array.isArray(t)?t.filter(ph):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.wallpapers` filter returned a non-array; falling back to seed list."),e)}function js(e){return _d().find(t=>t.id===e)}const Ed=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"preview",message:"missing or not a non-empty string",valid:e=>typeof e.preview=="string"&&e.preview!==""},{field:"type",message:'must be "css" or "canvas"',valid:e=>e.type==="css"||e.type==="canvas"},{field:"value/resolveValue/mount",message:"css types need `value` or `resolveValue`; canvas types need `mount`",valid:e=>e.type==="css"?typeof e.value=="string"||typeof e.resolveValue=="function":e.type==="canvas"?typeof e.mount=="function":!0}];function ph(e){return un(e,Ed).length===0}const Sd=re("desktop-mode/wallpaper-settings",()=>({values:{}}));function fh(e){return{...Sd.state.values[e]??{}}}function mh(e){const t=Sd.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const Id="desktop-mode-os-settings",hh="custom-gradient",xd="custom-image",qs="dark",Cd=[{id:"wp-blue",label:"WordPress Blue",value:"#2271b1"},{id:"indigo",label:"Indigo",value:"#3858e9"},{id:"teal",label:"Teal",value:"#04a4cc"},{id:"emerald",label:"Emerald",value:"#059669"},{id:"amber",label:"Amber",value:"#d97706"},{id:"rose",label:"Rose",value:"#e11d48"}];function Ad(){const t=window.wp?.desktop?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return Cd;const n=[];for(const o of t)o&&typeof o=="object"&&typeof o.id=="string"&&typeof o.label=="string"&&typeof o.value=="string"&&o.id!==""&&o.label!==""&&/^#[0-9a-f]{3,8}$/i.test(o.value)&&n.push({id:o.id,label:o.label,value:o.value});return n.length>0?n:Cd}function Ld(){const t=window.wp?.desktop?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:qs}const Vs=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],wh=[{id:"classic",label:"Classic"},{id:"unified",label:"Unified"},{id:"spatial",label:"Spatial"}],Q={wallpaper:qs,accent:"wp-blue",dockSize:"default",desktopLayout:"classic",dockRailRenderer:"default",unfocusEffect:"darken",windowLinkRenderer:"svg-splines",windowLinkVisibility:"always",windowLinksEnabled:!0,windowLinkRaiseOnFocus:!0,windowLinkHighlight:!0,customGradient:{from:"#2271b1",to:"#7c3aed",angle:135},customImage:null,wallpaperSettings:{},libraryHdOnly:!0,ai:{enabled:!1},heartbeatRate:60,nativePostsEnabled:!1,nativePostsHiddenColumns:[],nativePagesEnabled:!1,nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,showDesktopOnWallpaperClick:!1,showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,itemVisibility:{},dockOrder:[],dockPromotedPositions:{}};function Td(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const Nd="X-WP-Nonce";function Dd(e,t){const n=gh();if(!n)return t;const o=yh(e);if(!o||!bh(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Nd)?t:(i.set(Nd,n),{...t??{},headers:i})}function gh(){if(typeof window>"u")return;const t=window.desktopModeConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function yh(e){try{const t=typeof window<"u"&&window.location?window.location.href:void 0;return typeof e=="string"?new URL(e,t):e instanceof URL?e:typeof Request<"u"&&e instanceof Request?new URL(e.url,t):null}catch{return null}}function bh(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function ze(e,t,n={}){const o=window.wp?.desktop?.fetch;if(typeof o=="function")return o(e,t,n);const s=Dd(e,t);return fetch(e,s)}function vh(){const e=kh();if(e){const t=Od(e);return Ys(t),t}try{const t=window.localStorage.getItem(Id);if(t)return Od(JSON.parse(t))}catch{}return Nh()}function kh(){const t=window.desktopModeConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}function Od(e){const t=Ad();return{wallpaper:typeof e.wallpaper=="string"&&e.wallpaper!==""?e.wallpaper:Ld(),accent:t.some(n=>n.id===e.accent)?e.accent:Q.accent,dockSize:Vs.some(n=>n.id===e.dockSize)?e.dockSize:Q.dockSize,desktopLayout:wh.some(n=>n.id===e.desktopLayout)?e.desktopLayout:Q.desktopLayout,dockRailRenderer:typeof e.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(e.dockRailRenderer)?e.dockRailRenderer:Q.dockRailRenderer,unfocusEffect:typeof e.unfocusEffect=="string"&&/^[a-z0-9_/-]+$/.test(e.unfocusEffect)?e.unfocusEffect:Q.unfocusEffect,windowLinkRenderer:typeof e.windowLinkRenderer=="string"&&/^[a-z0-9_/-]+$/.test(e.windowLinkRenderer)?e.windowLinkRenderer:Q.windowLinkRenderer,windowLinkVisibility:e.windowLinkVisibility==="focus"||e.windowLinkVisibility==="always"||e.windowLinkVisibility==="off"?e.windowLinkVisibility:Q.windowLinkVisibility,windowLinksEnabled:typeof e.windowLinksEnabled=="boolean"?e.windowLinksEnabled:Q.windowLinksEnabled,windowLinkRaiseOnFocus:typeof e.windowLinkRaiseOnFocus=="boolean"?e.windowLinkRaiseOnFocus:Q.windowLinkRaiseOnFocus,windowLinkHighlight:typeof e.windowLinkHighlight=="boolean"?e.windowLinkHighlight:Q.windowLinkHighlight,customGradient:Oh(e.customGradient),customImage:Rh(e.customImage),wallpaperSettings:_h(e.wallpaperSettings),libraryHdOnly:typeof e.libraryHdOnly=="boolean"?e.libraryHdOnly:Q.libraryHdOnly,ai:Dh(e.ai),heartbeatRate:e.heartbeatRate===15||e.heartbeatRate===30||e.heartbeatRate===45||e.heartbeatRate===60?e.heartbeatRate:Q.heartbeatRate,nativePostsEnabled:typeof e.nativePostsEnabled=="boolean"?e.nativePostsEnabled:Q.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(e.nativePostsHiddenColumns)?e.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):Q.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof e.nativePagesEnabled=="boolean"?e.nativePagesEnabled:Q.nativePagesEnabled,nativeUsersEnabled:typeof e.nativeUsersEnabled=="boolean"?e.nativeUsersEnabled:Q.nativeUsersEnabled,nativePluginsEnabled:typeof e.nativePluginsEnabled=="boolean"?e.nativePluginsEnabled:Q.nativePluginsEnabled,nativeCommentsEnabled:typeof e.nativeCommentsEnabled=="boolean"?e.nativeCommentsEnabled:Q.nativeCommentsEnabled,showDesktopOnWallpaperClick:typeof e.showDesktopOnWallpaperClick=="boolean"?e.showDesktopOnWallpaperClick:Q.showDesktopOnWallpaperClick,showPostStatusRibbons:typeof e.showPostStatusRibbons=="boolean"?e.showPostStatusRibbons:Q.showPostStatusRibbons,developerModeEnabled:typeof e.developerModeEnabled=="boolean"?e.developerModeEnabled:Q.developerModeEnabled,foldersSharingEnabled:typeof e.foldersSharingEnabled=="boolean"?e.foldersSharingEnabled:Q.foldersSharingEnabled,itemVisibility:Eh(e.itemVisibility),dockOrder:Sh(e.dockOrder),dockPromotedPositions:Ih(e.dockPromotedPositions)}}function _h(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(typeof o!="string"||o===""||!/^[a-z0-9_/-]+$/.test(o)||!s||typeof s!="object"||Array.isArray(s))continue;const i={};let r=0;for(const[a,d]of Object.entries(s)){if(r>=32)break;if(!(typeof a!="string"||a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof d=="boolean")i[a]=d;else if(typeof d=="number"&&Number.isFinite(d))i[a]=d;else if(typeof d=="string")i[a]=d.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function Eh(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=["both","dock","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(e)){if(o>=256)break;if(typeof s!="string"||s===""||typeof i!="string")continue;const r=i;t.includes(r)&&(n[s]=r,o++)}return n}function Sh(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const o of e)if(!(typeof o!="string"||o===""||n.has(o))&&(n.add(o),t.push(o),t.length>=256))break;return t}function Ih(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(typeof s!="string"||s===""||!i||typeof i!="object"||Array.isArray(i))continue;const r=i;typeof r.x!="number"||typeof r.y!="number"||!Number.isFinite(r.x)||!Number.isFinite(r.y)||Math.abs(r.x)>o||Math.abs(r.y)>o||(t[s]={x:r.x,y:r.y},n++)}return t}let Do=null;const xh=250;let mn=null;function Ch(e){mn=Ks(e)}function Ks(e){return{...e,customGradient:{...e.customGradient},customImage:e.customImage?{...e.customImage}:null,wallpaperSettings:Object.fromEntries(Object.entries(e.wallpaperSettings).map(([t,n])=>[t,{...n}])),ai:{...e.ai},nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),itemVisibility:{...e.itemVisibility},dockOrder:e.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function Ah(e,t={}){Ys(e),Lh(e,t.windowId)}function Ys(e){try{window.localStorage.setItem(Id,JSON.stringify(e))}catch{}}function Lh(e,t){Do!==null&&clearTimeout(Do),t&&(Xs=t),Mt("pending"),Do=setTimeout(()=>{Do=null;const n=Xs;Xs=null,Th(e,n)},xh)}let Xs=null;function Th(e,t){const n=window.desktopModeConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Mt("saved");return}Mt("saving");const i=t||"desktop-mode-os-settings";ze(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:e})},{windowId:i}).then(r=>{if(!r.ok)throw new Error(`${r.status} ${r.statusText}`);mn=Ks(e),Mt("saved")}).catch(r=>{mn?(Ys(mn),Mt("failed",r instanceof Error?r.message:String(r),Ks(mn))):Mt("failed",r instanceof Error?r.message:String(r))})}function Mt(e,t,n){const o={phase:e};t&&(o.error=t),n&&(o.rolledBackTo=n),document.dispatchEvent(new CustomEvent("desktop-mode-os-settings-save-lifecycle",{detail:o}))}function Nh(){return{...Q,customGradient:{...Q.customGradient},customImage:null,wallpaperSettings:{...Q.wallpaperSettings},ai:{...Q.ai},itemVisibility:{...Q.itemVisibility},dockOrder:[...Q.dockOrder],dockPromotedPositions:{...Q.dockPromotedPositions}}}function Dh(e){if(!e||typeof e!="object")return{...Q.ai};const{enabled:t}=e;return{enabled:typeof t=="boolean"?t:Q.ai.enabled}}function Oh(e){if(!e||typeof e!="object")return{...Q.customGradient};const{from:t,to:n,angle:o}=e;return{from:Td(t)?t:Q.customGradient.from,to:Td(n)?n:Q.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:Q.customGradient.angle}}function Rh(e){if(!e||typeof e!="object")return null;const{id:t,url:n}=e;return typeof t!="number"||!Number.isFinite(t)||t<=0||typeof n!="string"||!/^https?:\/\//i.test(n)?null:{id:t,url:n}}const hn=re("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),rt=hn.state.registry,Zs=hn.state.listeners,Mh=/^[a-z0-9_-]+$/;function Rd(e){if(!e||typeof e!="object")throw new TypeError("[desktop-mode] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!Mh.test(e.id))throw new TypeError(`[desktop-mode] registerDockRailRenderer: id must match /^[a-z0-9_-]+$/, got: ${String(e.id)}`);if(typeof e.label!="string"||e.label==="")throw new TypeError("[desktop-mode] registerDockRailRenderer: label must be a non-empty string.");if(typeof e.mount!="function")throw new TypeError("[desktop-mode] registerDockRailRenderer: mount must be a function.");if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new TypeError(`[desktop-mode] registerDockRailRenderer: unsupported apiVersion ${e.apiVersion} (this shell speaks v1).`);rt.set(e.id,e),Oo()}function Wh(e){rt.delete(e)&&Oo()}function Ph(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(rt.entries()))o.owner===e&&(rt.delete(n),t++);return t>0&&Oo(),t}function $h(){return Array.from(rt.values())}function Uh(e){return Zs.add(e),()=>{Zs.delete(e)}}function Hh(e){hn.state.activeId!==e&&(hn.state.activeId=e,Oo())}function Js(){return rt.get(hn.state.activeId)??rt.get("default")??rt.values().next().value}function Oo(){const e=Array.from(Zs);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] dock-rail-renderer listener threw:",n)}}function Qs(e){if(!e)return 214;let t=5381;for(let n=0;n<e.length;n++)t=Math.imul(t,33)+e.charCodeAt(n);return(t%360+360)%360}const Bh=180,Fh=220,Md=32;function Wd(e){const{tile:t}=e;let n=null,o=null,s=null,i=!1;const r=()=>{o!==null&&(window.clearTimeout(o),o=null)},a=()=>{s!==null&&(window.clearTimeout(s),s=null)},d=()=>{r(),a(),n&&(n.remove(),n=null),e.suppressTooltip(!1)},c=f=>{f.pointerType==="mouse"&&zh(e)&&(i=!0,a(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},Bh)))},l=f=>{n&&f.relatedTarget instanceof Node&&n.contains(f.relatedTarget)||(i=!1,r(),u())},u=()=>{a(),s=window.setTimeout(()=>{s=null,!i&&d()},Fh)},p=()=>{e.suppressTooltip(!0),n=Gh(e,()=>d()),document.body.appendChild(n),Zh(n),Jh(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("desktop-mode-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,a()}),n.addEventListener("pointerleave",f=>{f.relatedTarget instanceof Node&&t.contains(f.relatedTarget)||(i=!1,u())})};return t.addEventListener("pointerenter",c),t.addEventListener("pointerleave",l),()=>{t.removeEventListener("pointerenter",c),t.removeEventListener("pointerleave",l),d()}}function zh(e){return e.getInstances().length>=1}function Gh(e,t){const n=document.createElement("div");n.className="desktop-mode-dock-peek",n.setAttribute("role","menu"),n.setAttribute("aria-label",oe(O("%s — open windows"),e.item.title));const o=document.createElement("div");o.className="desktop-mode-dock-peek__cards",n.appendChild(o);const s=e.getInstances();let i=0;for(const r of s){const a=jh(r,e,i++,t);o.appendChild(a)}if(e.enableGhost!==!1){const r=Vh(e,i,t);o.appendChild(r)}return n}function jh(e,t,n,o){const s=document.createElement("button");s.type="button",s.setAttribute("role","menuitem"),s.className="desktop-mode-dock-peek__card desktop-mode-dock-peek__card--instance",s.style.setProperty("--peek-card-index",String(n)),s.style.setProperty("--peek-card-delay",`${n*Md}ms`);const i=e.config.title||t.item.title;s.style.setProperty("--peek-card-hue",`${Qs(e.id||i)}`),s.style.setProperty("--peek-card-vt-name",`desktop-mode-peek-card-${e.id}`);const r=document.createElement("span");r.className="desktop-mode-dock-peek__card-titlebar";const a=document.createElement("span");a.className="desktop-mode-dock-peek__card-dots",a.setAttribute("aria-hidden","true");for(let m=0;m<3;m++)a.appendChild(document.createElement("i"));r.appendChild(a);const d=document.createElement("span");d.className="desktop-mode-dock-peek__card-icon",d.setAttribute("aria-hidden","true");const c=e.config.icon||t.item.icon;c.startsWith("dashicons-")?d.classList.add("dashicons",zf(c)):d.classList.add("dashicons","dashicons-admin-generic"),r.appendChild(d);const l=document.createElement("span");l.className="desktop-mode-dock-peek__card-label",l.textContent=i,r.appendChild(l),s.appendChild(r);const u=document.createElement("span");u.className="desktop-mode-dock-peek__card-body",u.setAttribute("aria-hidden","true");for(let m=0;m<3;m++){const w=document.createElement("span");w.className="desktop-mode-dock-peek__card-line",u.appendChild(w)}const p={window:e,item:t.item},f=j(v.DOCK_PEEK_CARD_CONTENT,u,p);return f!==u&&f.classList.add("desktop-mode-dock-peek__card-body--custom"),s.appendChild(f),s.addEventListener("click",()=>{qh(t,e,s,o)}),s.addEventListener("pointerenter",()=>{t.windowManager.getFocused()!==e&&t.windowManager.focus(e)}),j(v.DOCK_PEEK_CARD_ELEMENT,s,p)}function qh(e,t,n,o){const s=document,i=`desktop-mode-peek-card-${t.id}`,r=()=>{o(),e.windowManager.focus(t)};if(typeof s.startViewTransition!="function"){r();return}const a=t.element;n.style.setProperty("view-transition-name",i),a.style.setProperty("view-transition-name",i);const d=s.startViewTransition(r),c=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},l=d;l.finished&&typeof l.finished.then=="function"?l.finished.then(c,c):Promise.resolve().then(c)}function Vh(e,t,n){const o=document.createElement("button");o.type="button",o.setAttribute("role","menuitem"),o.className="desktop-mode-dock-peek__card desktop-mode-dock-peek__card--ghost",o.style.setProperty("--peek-card-index",String(t)),o.style.setProperty("--peek-card-delay",`${t*Md}ms`);const s=document.createElement("span");s.className="desktop-mode-dock-peek__card-plus",s.setAttribute("aria-hidden","true"),s.textContent="+",o.appendChild(s);const i=document.createElement("span");return i.className="desktop-mode-dock-peek__card-label",i.textContent=oe(O("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{Kh(e,n)}),o}function Kh(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const Yh=12,Xh=["--wp-admin-theme-color","--desktop-mode-titlebar-bg","--desktop-mode-titlebar-bg-focused","--desktop-mode-titlebar-color","--desktop-mode-titlebar-color-focused"];function Zh(e){const t=document.querySelector(".desktop-mode-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of Xh){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function Jh(e,t,n){const o=t.getBoundingClientRect();e.dataset.orientation=n,n==="bottom"?(e.style.left=`${o.left+o.width/2}px`,e.style.top=`${o.top-12}px`):n==="right"?(e.style.top=`${o.top+o.height/2}px`,e.style.left=`${o.left-12}px`):(e.style.top=`${o.top+o.height/2}px`,e.style.left=`${o.right+12}px`),requestAnimationFrame(()=>Qh(e))}function Qh(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=Yh;let r=0,a=0;n.top<i?r=i-n.top:n.bottom>o-i&&(r=o-i-n.bottom),n.left<i?a=i-n.left:n.right>s-i&&(a=s-i-n.right),!(a===0&&r===0)&&(e.style.setProperty("--peek-clamp-x",`${a}px`),e.style.setProperty("--peek-clamp-y",`${r}px`),e.classList.add("desktop-mode-dock-peek--clamped"))}function Ro(e){try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin?!1:(window.open(t.toString(),"_blank","noopener,noreferrer"),!0)}catch{return!1}}function ew(e){return`desktop:${e}`}function tw(e){return`dock:${e}`}function nw(e){return e.startsWith("dock:")?e.slice(5):e.startsWith("desktop:")?e.slice(8):e}function wt(e,t,n){const o=n[e];return o||t}function Pd(e){return e==="dock"||e==="both"}function $d(e){return e==="desktop"||e==="both"}function ow(e,t,n,o){const s=n.itemVisibility,i=n.dockOrder,r=[];for(const a of e){const d=wt(a.id,"dock",s);Pd(d)&&r.push(a)}for(const a of t){const d=wt(a.id,"desktop",s);Pd(d)&&(a.window&&o&&o.has(a.window)||r.push({id:tw(a.id),title:a.title,icon:a.icon,url:a.url||"",windowId:a.window||void 0,badge:0,submenu:[],isCore:!1}))}return iw(r,i)}function sw(e,t,n){const o=[];for(const i of e){const r=wt(i.id,"desktop",n);$d(r)&&o.push(i)}let s=0;for(const i of t){const r=wt(i.id,"dock",n);$d(r)&&o.push({id:ew(i.id),title:i.title,icon:i.icon,window:"",url:i.url||"",position:2e3+s++})}return o}function iw(e,t){if(t.length===0||e.length<=1)return e;const n=new Map;for(const i of e)n.set(i.id,i);const o=[],s=new Set;for(const i of t){const r=n.get(i);r&&(o.push(r),s.add(i))}for(const i of e)s.has(i.id)||o.push(i);return o}function z(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function rw(e){return!!e&&e.__wpdHtml===!0}const aw="$$wpd$$",_e=/\$\$wpd\$\$(\d+)\$\$/g;function dw(e){let t=e[0];for(let n=1;n<e.length;n++)t+=`${aw}${n-1}$$`+e[n];return t}const Ud=new WeakMap;function Hd(e){const t=Ud.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=dw(e);const o=[],s=(a,d)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const p of Array.from(u.attributes)){const f=p.name,h=p.value,m=f[0];if(_e.test(h))if(_e.lastIndex=0,m==="@"){const w=_e.exec(h);_e.lastIndex=0,o.push({path:d,kind:"event",name:f.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(f)}else if(m==="."){const w=_e.exec(h);_e.lastIndex=0,o.push({path:d,kind:"prop",name:f.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(f)}else if(m==="?"){const w=_e.exec(h);_e.lastIndex=0,o.push({path:d,kind:"bool",name:f.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(f)}else{const w=[],g=[];let x=0,T;for(_e.lastIndex=0;(T=_e.exec(h))!==null;)w.push(h.slice(x,T.index)),g.push(Number(T[1])),x=T.index+T[0].length;w.push(h.slice(x)),o.push({path:d,kind:"attr",name:f,template:w,valueIndices:g}),u.setAttribute(f,"")}}}const c=Array.from(a.childNodes);let l=0;for(let u=0;u<c.length;u++){const p=c[u],f=u+l;if(p.nodeType===Node.TEXT_NODE){const h=p.textContent||"";if(!_e.test(h)){_e.lastIndex=0;continue}_e.lastIndex=0;const m=p.parentNode;let w=0,g;const x=[],T=[];for(_e.lastIndex=0;(g=_e.exec(h))!==null;){g.index>w&&x.push(document.createTextNode(h.slice(w,g.index)));const y=document.createTextNode("");x.push(y),T.push({path:[...d,f+x.length-1],kind:"node",valueIndex:Number(g[1])}),w=g.index+g[0].length}w<h.length&&x.push(document.createTextNode(h.slice(w)));for(const y of x)m.insertBefore(y,p);m.removeChild(p),l+=x.length-1,o.push(...T)}else s(p,[...d,f])}};s(n.content,[]);const r={template:n,buildParts:a=>{const d=[];for(const c of o){let l=a;for(const u of c.path)l=l.childNodes[u];c.kind==="node"?d.push({kind:"node",valueIndex:c.valueIndex,child:{anchor:l,state:null}}):c.kind==="attr"?d.push({kind:"attr",element:l,name:c.name,template:c.template,valueIndices:c.valueIndices}):c.kind==="event"?d.push({kind:"event",valueIndex:c.valueIndex,element:l,name:c.name}):c.kind==="prop"?d.push({kind:"prop",valueIndex:c.valueIndex,element:l,name:c.name}):c.kind==="bool"&&d.push({kind:"bool",valueIndex:c.valueIndex,element:l,name:c.name})}return d}};return Ud.set(e,r),r}const Bd=new WeakMap;function cw(e,t){const n=Bd.get(t);if(n&&n.strings===e.strings){Mo(n.parts,e.values);return}const o=Hd(e.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s);for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s),Mo(i,e.values),Bd.set(t,{strings:e.strings,parts:i})}function Mo(e,t){for(const n of e)if(n.kind==="node")ei(n.child,t[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;s<n.valueIndices.length;s++)o+=Fd(t[n.valueIndices[s]]),o+=n.template[s+1];o!==n.last&&(n.last=o,o===""?n.element.removeAttribute(n.name):n.element.setAttribute(n.name,o))}else if(n.kind==="event"){const o=t[n.valueIndex];o!==n.current&&(n.current&&n.element.removeEventListener(n.name,n.current),o&&n.element.addEventListener(n.name,o),n.current=o)}else if(n.kind==="prop"){const o=t[n.valueIndex];o!==n.last&&(n.last=o,n.element[n.name]=o)}else if(n.kind==="bool"){const o=!!t[n.valueIndex];o!==n.last&&(n.last=o,o?n.element.setAttribute(n.name,""):n.element.removeAttribute(n.name))}}function ei(e,t){if(t==null||t===!1){e.state&&(Wt(e.state),e.state=null);return}if(Array.isArray(t)){fw(e,t);return}if(rw(t)){pw(e,t);return}if(t instanceof Node){lw(e,t);return}uw(e,Fd(t))}function lw(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Wt(n),Wo(e,[t]),e.state={shape:"node",node:t})}function uw(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Wt(n);const o=document.createTextNode(t);Wo(e,[o]),e.state={shape:"text",node:o,text:t}}function pw(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){Mo(n.parts,t.values);return}n&&Wt(n);const o=Hd(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);Wo(e,[s]),Mo(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function fw(e,t){const n=e.state;if(n?.shape==="array"&&n.entries.length===t.length){for(let s=0;s<t.length;s++)ei(n.entries[s],t[s]);return}n&&Wt(n);const o=[];for(const s of t){const i=document.createTextNode("");Wo(e,[i]);const r={anchor:i,state:null};ei(r,s),o.push(r)}e.state={shape:"array",entries:o}}function Wo(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Wt(e){if(e.shape==="text"){e.node.remove();return}if(e.shape==="template"){for(const t of e.nodes)t.parentNode&&t.parentNode.removeChild(t);return}if(e.shape==="node"){e.node.parentNode&&e.node.parentNode.removeChild(e.node);return}for(const t of e.entries)t.state&&Wt(t.state),t.anchor.remove()}function Fd(e){return e==null||e===!1?"":String(e)}const ut=class ut extends HTMLElement{constructor(){super(),this._renderScheduled=!1,this._propValues={},this.constructor.shadow?(this.attachShadow({mode:"open"}),this._renderRoot=this.shadowRoot):this._renderRoot=this,this._installPropAccessors()}static get observedAttributes(){return this.props.map(zd)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=mw(t);this._propValues[s]=o,this.requestUpdate()}get classNames(){return Array.from(this.classList)}set classNames(t){if(t==null){this.removeAttribute("class");return}const o=(Array.isArray(t)?t:String(t).split(/\s+/)).map(s=>String(s).trim()).filter(s=>s!=="");this.className=o.join(" ")}requestUpdate(){this._scheduleRender()}emit(t,n){return this.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,composed:!0}))}_installPropAccessors(){const t=this.constructor;for(const n of t.props){if(Object.getOwnPropertyDescriptor(this,n))continue;const o=zd(n);Object.defineProperty(this,n,{get:()=>n in this._propValues?this._propValues[n]:this.getAttribute(o),set:s=>{let i;s==null||s===!1?i=null:s===!0?i="":i=String(s),this._propValues[n]=i,i===null?this.removeAttribute(o):this.setAttribute(o,i),this.requestUpdate()},enumerable:!0,configurable:!0})}}_scheduleRender(){this._renderScheduled||!this.isConnected||(this._renderScheduled=!0,queueMicrotask(()=>{this._renderScheduled=!1,this.isConnected&&cw(this.render(),this._renderRoot)}))}_adoptStyles(){const t=this.constructor;if(t.styles.length!==0)if(t.shadow&&this.shadowRoot){const n=t.styles.map(o=>o.sheet).filter(o=>o!==null);if(this.shadowRoot.adoptedStyleSheets=n,n.length!==t.styles.length){for(const o of t.styles)if(!o.sheet){const s=document.createElement("style");s.textContent=o.cssText,this.shadowRoot.appendChild(s)}}}else this._adoptLightStyles(t)}_adoptLightStyles(t){if(!ut._lightStylesAdopted.has(t)){ut._lightStylesAdopted.add(t);for(const n of t.styles){const o=document.createElement("style");o.dataset.wpdUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};ut.props=[],ut.styles=[],ut.shadow=!0,ut._lightStylesAdopted=new WeakSet;let pe=ut;function me(e,t){customElements.get(e)||customElements.define(e,t)}function zd(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function mw(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const hw=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function he(e,...t){let n=e[0];for(let o=1;o<e.length;o++){const s=t[o-1];if(typeof s=="string"||typeof s=="number")n+=String(s);else if(s&&s.__wpdCss)n+=s.cssText;else throw new TypeError("[wpd-ui] css`` interpolations must be strings, numbers, or other css`` results. Got: "+typeof s);n+=e[o]}if(hw){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function ww(e){const t=[],n=[];let o=null,s=e.parentElement;for(;s&&!(s===document.body||s===document.documentElement);){const r=s.id||"";if(r.startsWith("wp-window-")){o=r.slice(10);break}if(s.tagName.toLowerCase()==="wpd-tabpanel"){const a=s.getAttribute("for");a&&n.unshift(a)}s=s.parentElement}o&&t.push(ti(o));for(const r of n)t.push("tab-"+ti(r));const i=e.getAttribute("label");return i&&t.push(ti(i)),t.length===0?"wpd-unnamed":"wpd-"+t.filter(r=>r!=="").join("-")}function ti(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Gd(e){if(e.id)return e.id;const t=ww(e);return e.id=t,t}const gw=he`:host{display:none;position:fixed;inset:0;align-items:center;justify-content:center;background:rgba( 0,0,0,0.45 );backdrop-filter:blur( 2px );z-index:10000}:host( [ open ] ){display:flex}.dialog{width:min( 420px,92vw );background:var( --wpd-confirm-dialog-bg,var( --desktop-mode-bg,#1d2327 ) );color:var( --wpd-confirm-dialog-fg,var( --desktop-mode-fg,#fff ) );border:1px solid rgba( 255,255,255,0.08 );border-radius:10px;box-shadow:0 20px 50px rgba( 0,0,0,0.6 );padding:20px 22px 18px;display:flex;flex-direction:column;gap:10px;position:relative}.close{position:absolute;top:8px;right:10px;width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;background:transparent;border:0;border-radius:6px;color:var( --wpd-confirm-dialog-fg-muted,rgba( 255,255,255,0.7 ) );cursor:pointer;font-size:22px;line-height:1;padding:0}.close:hover{background:rgba( 255,255,255,0.08 );color:inherit}.title{margin:0 0 4px;font-size:16px;font-weight:600}.message{margin:0;color:var( --wpd-confirm-dialog-fg-muted,rgba( 255,255,255,0.7 ) );line-height:1.45;white-space:pre-line}.actions{display:flex;justify-content:flex-end;gap:8px;margin-top:6px}.btn{border:0;border-radius:6px;padding:8px 14px;font-size:13px;cursor:pointer;font-weight:500}.btn--secondary{background:rgba( 255,255,255,0.08 );color:inherit}.btn--secondary:hover{background:rgba( 255,255,255,0.14 )}.btn--primary{background:var( --wp-admin-theme-color,#2271b1 );color:#fff}.btn--primary:hover{filter:brightness( 1.08 )}.btn--danger{background:#d63638;color:#fff}.btn--danger:hover{filter:brightness( 1.08 )}`,co=class co extends pe{constructor(){super(...arguments),this._onKey=t=>{t.key==="Escape"&&(t.preventDefault(),this._cancel()),t.key==="Enter"&&!t.isComposing&&(t.preventDefault(),this._confirm())},this._onBackdrop=t=>{const n=t.composedPath();(n.length>0?n[0]:t.target)===this&&this._cancel()},this._confirm=()=>{this.emit("wpd-confirm",{confirmed:!0}),this.removeAttribute("open")},this._cancel=()=>{this.emit("wpd-cancel",{confirmed:!1}),this.removeAttribute("open")}}connectedCallback(){super.connectedCallback(),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","true"),this.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop)}render(){const t=this.title??"",n=this.message??"",o=this["confirm-label"]||"Confirm",s=this["cancel-label"]||"Cancel",i=this.hasAttribute("danger"),r=this.hasAttribute("hide-cancel"),a=this.hasAttribute("dismissable");return z` |
| 2 |
<div class="dialog" tabindex="-1"> |
| 3 |
${a?z`<button |
| 4 |
type="button" |
| 5 |
class="close" |
| 6 |
aria-label="Close" |
| 7 |
@click=${()=>this._cancel()} |
| 8 |
>×</button>`:z``} |
| 9 |
${t?z`<h2 class="title">${t}</h2>`:z``} |
| 10 |
${n?z`<p class="message">${n}</p>`:z``} |
| 11 |
<div class="actions"> |
| 12 |
${r?z``:z`<button |
| 13 |
type="button" |
| 14 |
class="btn btn--secondary" |
| 15 |
@click=${()=>this._cancel()} |
| 16 |
> |
| 17 |
${s} |
| 18 |
</button>`} |
| 19 |
<button |
| 20 |
type="button" |
| 21 |
class="btn ${i?"btn--danger":"btn--primary"}" |
| 22 |
@click=${()=>this._confirm()} |
| 23 |
> |
| 24 |
${o} |
| 25 |
</button> |
| 26 |
</div> |
| 27 |
</div> |
| 28 |
`}};co.props=["open","title","message","confirm-label","cancel-label","danger","hide-cancel","dismissable"],co.styles=[gw],co.help=void 0;let ni=co;me("wpd-confirm-dialog",ni);function jd(e){return new Promise(t=>{const n=document.createElement("wpd-confirm-dialog");n.setAttribute("open",""),e.title&&n.setAttribute("title",e.title),n.setAttribute("message",e.message),e.confirmLabel&&n.setAttribute("confirm-label",e.confirmLabel),e.cancelLabel&&n.setAttribute("cancel-label",e.cancelLabel),e.danger&&n.setAttribute("danger",""),e.hideCancel&&n.setAttribute("hide-cancel",""),e.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),t(i)};n.addEventListener("wpd-confirm",()=>o(!0)),n.addEventListener("wpd-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}const yw="http://localhost/";function wn(e,t){const n=typeof window<"u"&&window.location?window.location.href:yw,o=new URL(e,n),s=t.replace(/^\/+/,""),i=s.indexOf("?"),r=i===-1?s:s.slice(0,i),a=i===-1?"":s.slice(i+1);if(o.searchParams.has("rest_route")){const d=o.searchParams.get("rest_route")??"/",c=d.endsWith("/")?d:d+"/";o.searchParams.set("rest_route",c+r)}else{const d=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=d+r}return a&&new URLSearchParams(a).forEach((c,l)=>{o.searchParams.append(l,c)}),o.toString()}function gn(){return window.wp?.desktop??null}let gt=null;function yn(){gt&&(gt.remove(),gt=null)}function bn(e,t){const n=gn();if(!n?.getOsSettings||!n?.updateOsSettings)return;const s={...n.getOsSettings().itemVisibility};s[e]=t,n.updateOsSettings({itemVisibility:s})}function bw(e,t){return e.startsWith("dock:")?"dock":e.startsWith("desktop:")?"desktop":t}function qd(e,t,n,o){return wt(e,t,o)==="both"?n==="dock"?"desktop":"dock":"hidden"}let Vd=0;function Kd(e){yn();const t=++Vd;sn(()=>t===Vd,()=>vw(e))}function vw(e){yn();const t=nw(e.id),n=bw(e.id,e.surface),o=wt(t,n,gn()?.getOsSettings?.().itemVisibility??{}),s=[];if(e.surface==="dock"?(s.push({id:"hide-from-dock",label:O("Hide from dock"),icon:"dashicons-hidden",onPick:()=>bn(t,qd(t,n,"dock",gn()?.getOsSettings?.().itemVisibility??{}))}),o!=="both"&&s.push({id:"show-on-desktop-too",label:O("Also show on desktop"),icon:"dashicons-desktop",onPick:()=>bn(t,"both")})):(s.push({id:"hide-from-desktop",label:O("Hide from desktop"),icon:"dashicons-hidden",onPick:()=>bn(t,qd(t,n,"desktop",gn()?.getOsSettings?.().itemVisibility??{}))}),o!=="both"&&s.push({id:"show-on-dock-too",label:O("Also show on dock"),icon:"dashicons-menu",onPick:()=>bn(t,"both")})),s.push({id:"hide-everywhere",label:O("Hide everywhere"),icon:"dashicons-no",danger:!0,onPick:()=>bn(t,"hidden")}),s.push({id:"open-settings",label:O("Apps & Icons settings…"),icon:"dashicons-admin-generic",onPick:()=>{gn()?.openOsSettings?.({tabId:"apps-icons"})}}),e.pluginFile){const l=e.pluginFile,u=e.pluginName||e.title;s.push({kind:"separator"}),s.push({id:"deactivate-plugin",label:oe(O("Deactivate %s…"),u),icon:"dashicons-trash",danger:!0,onPick:()=>{kw(l,u)}})}const i=document.createElement("wpd-context-menu");i.setAttribute("open",""),i.classList.add("desktop-mode-item-visibility-menu"),i.dataset.itemId=e.id,i.style.position="fixed",i.style.left="-9999px",i.style.top="-9999px",i.style.visibility="hidden",i.style.zIndex="1000000";const r=new Map;for(const l of s){if(l.kind==="separator"){const p=document.createElement("hr");p.style.cssText="border: 0; border-top: 1px solid var( --wpd-context-menu-separator-color, rgba(255,255,255,0.12) ); margin: 4px 6px;",i.appendChild(p);continue}r.set(l.id,l);const u=document.createElement("wpd-context-menu-option");u.dataset.menuItemId=l.id,u.setAttribute("value",l.id),l.icon&&u.setAttribute("icon",l.icon),l.danger&&u.setAttribute("danger",""),u.textContent=l.label,i.appendChild(u)}i.addEventListener("wpd-context-menu-pick",l=>{const u=l.detail,p=u?.id||u?.value||"",f=r.get(p);yn();try{f?.onPick()}catch{}}),document.body.appendChild(i),gt=i,requestAnimationFrame(()=>{if(i!==gt)return;const l=i.getBoundingClientRect(),u=8;let p=e.x,f;e.surface==="dock"?f=Math.max(u,e.y-l.height-u):(f=e.y,f+l.height+u>window.innerHeight&&(f=Math.max(u,e.y-l.height))),p+l.width+u>window.innerWidth&&(p=Math.max(u,e.x-l.width)),i.style.left=`${p}px`,i.style.top=`${f}px`,i.style.visibility=""});const d=l=>{gt&&(gt.contains(l.target)||(yn(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",c,!0)))},c=l=>{l.key==="Escape"&&(yn(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",c,!0))};document.addEventListener("mousedown",d,!0),document.addEventListener("keydown",c,!0)}async function kw(e,t){if(!await jd({title:oe(O("Deactivate %s?"),t),message:O("This plugin will stop running on the site. You can re-activate it later from the Plugins screen."),confirmLabel:O("Deactivate"),cancelLabel:O("Cancel"),danger:!0}))return;const o=window.desktopModeConfig??{},s=typeof o.restRoot=="string"&&o.restRoot?o.restRoot:`${window.location.origin}/wp-json/`,i=typeof o.restNonce=="string"&&o.restNonce?o.restNonce:"",a=(e.endsWith(".php")?e.slice(0,-4):e).split("/").map(encodeURIComponent).join("/"),d=wn(s,`wp/v2/plugins/${a}`);try{const p=await ze(d,{method:"PUT",headers:{"Content-Type":"application/json","X-WP-Nonce":i},body:JSON.stringify({status:"inactive"}),credentials:"same-origin"},{source:"desktop-mode/dock-deactivate-plugin"});if(!p.ok)throw new Error(`HTTP ${p.status}`)}catch(p){ee({message:oe(O("Could not deactivate %s."),t),duration:4e3}),console.error("[desktop-mode] deactivate plugin failed",p);return}const c=_w(e),l=c.length>0?oe(O("%1$s deactivated. Closed %2$d window(s)."),t,c.length):oe(O("%s deactivated."),t);ee({message:l,duration:3e3}),window.wp?.desktop?.refreshMenu?.()}function _w(e){const t=window.wp?.desktop;if(!t?.windowManager?.getAll)return[];const o=(t.getMenuItems?.()??[]).filter(c=>c.pluginFile===e);if(o.length===0)return[];const s=new Set;for(const c of o)s.add(c.id),t.deriveWindowId&&s.add(t.deriveWindowId(c.url));const i=new Map,r=t.windowManager.getAll()??[],a=t.deriveWindowId;for(const c of r){if(s.has(c.id)){i.set(c.id,c);continue}if(c.config?.baseId&&s.has(c.config.baseId)){i.set(c.id,c);continue}if(a&&c.config?.url){const l=a(c.config.url);if(s.has(l)){i.set(c.id,c);continue}}if(a&&c.iframe){let l="";try{l=c.iframe.src||""}catch{}if(l){const u=a(l);s.has(u)&&i.set(c.id,c)}}}const d=[];for(const c of i.values()){d.push(c.config?.title??c.id);try{c.close()}catch{}}return d}const Ae=class Ae{constructor(t,n,o,s,i="left"){this.itemElements=new Map,this.systemItems=[],this.systemItemElements=new Map,this.systemSeparator=null,this.badgeOverrides=new Map,this.attentionTimers=new Map,this.peekTeardowns=new Map,this.boundRefresh=()=>{},this.container=t,this.windowManager=n,this.items=o,this.adminUrl=s,this.orientation=i,this.rail=i==="bottom"?"taskbar":"dock",this.hooksNamespace=`desktop-mode/dock/${++Ae.instanceCounter}`,this.container.setAttribute("data-desktop-mode-dock-placement",i);const r=document.createElement("div");r.className="desktop-mode-dock__scroll";const a=document.createElement("div");a.className="desktop-mode-dock__pinned",t.appendChild(r),t.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="desktop-mode-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("desktop-mode-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("desktop-mode-dock__tooltip--before"):this.tooltip.classList.add("desktop-mode-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.render(),this.bindWindowEvents()}buildHookContextBase(){return{rail:this.rail,orientation:this.orientation,dockId:this.container.id,container:this.container}}setOrientation(t){this.orientation!==t&&(this.orientation=t,this.container.setAttribute("data-desktop-mode-dock-placement",t),this.tooltip.classList.remove("desktop-mode-dock__tooltip--above","desktop-mode-dock__tooltip--before","desktop-mode-dock__tooltip--after"),t==="bottom"?this.tooltip.classList.add("desktop-mode-dock__tooltip--above"):t==="right"?this.tooltip.classList.add("desktop-mode-dock__tooltip--before"):this.tooltip.classList.add("desktop-mode-dock__tooltip--after"))}replaceItems(t){for(const i of this.itemElements.keys()){const r=this.peekTeardowns.get(i);r&&(r(),this.peekTeardowns.delete(i))}for(const i of this.itemElements.values())i.remove();this.itemHost.querySelectorAll(".desktop-mode-dock__separator--group").forEach(i=>i.remove()),this.itemElements.clear(),this.items=t;const n=this.buildHookContextBase();A(v.DOCK_BEFORE_RENDER,{...n,items:t,tileElements:this.itemElements});let o=!1,s=0;for(const i of t){if(!o&&i.isCore===!1){if(s>0){const d=document.createElement("div");d.className="desktop-mode-dock__separator desktop-mode-dock__separator--group",d.setAttribute("aria-hidden","true"),this.itemHost.appendChild(d)}o=!0}const r=this.createItemButton(i);this.itemElements.set(i.id,r),this.itemHost.appendChild(r),s++;const a=this.badgeOverrides.get(i.id);if(a!==void 0){const d=r.querySelector(".desktop-mode-dock__item-primary");Yd(d??r,a)}A(v.DOCK_TILE_RENDERED,{...n,item:i,isSystem:!1,el:r})}this.updateActiveStates(),A(v.DOCK_AFTER_RENDER,{...n,items:t,tileElements:this.itemElements})}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(t){const n=this.systemItemElements.get(t);n&&(n.remove(),this.systemItemElements.delete(t),this.systemItems=this.systemItems.filter(o=>o.id!==t),this.badgeOverrides.delete(t),this.systemItemElements.size===0&&this.systemSeparator&&(this.systemSeparator.remove(),this.systemSeparator=null),A(v.DOCK_ITEM_REMOVED,{id:t,placement:this.rail}))}setBadge(t,n){const o=this._resolveTileElement(t);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(t):this.badgeOverrides.set(t,s);const i=o.querySelector(".desktop-mode-dock__item-primary");Yd(i??o,s),ye.publish("desktop-mode/badge-changed",{itemId:t,count:s,rail:this.rail})}clearBadge(t){this.setBadge(t,0)}setAttention(t,n,o={}){const s=this._resolveTileElement(t);if(!s)return;const i=this.attentionTimers.get(t);if(i!==void 0&&(window.clearTimeout(i),this.attentionTimers.delete(t)),s.classList.remove("desktop-mode-dock__item--attention-pulse","desktop-mode-dock__item--attention-shake","desktop-mode-dock__item--attention-bounce","desktop-mode-dock__item--intensity-subtle","desktop-mode-dock__item--intensity-normal","desktop-mode-dock__item--intensity-strong"),n===null)return;s.classList.add(`desktop-mode-dock__item--attention-${n}`);const r=o.intensity??"normal";s.classList.add(`desktop-mode-dock__item--intensity-${r}`);const a=o.durationMs??4e3;if(a>0){const d=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},a);this.attentionTimers.set(t,d)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}appendSystemItem(t){this.systemItems.push(t),this.systemSeparator||(this.systemSeparator=document.createElement("div"),this.systemSeparator.className="desktop-mode-dock__separator",this.systemSeparator.setAttribute("aria-hidden","true"),this.systemHost.appendChild(this.systemSeparator));const n=this.createSystemItemButton(t);this.systemItemElements.set(t.id,n),this.systemHost.appendChild(n),this.updateActiveStates(),A(v.DOCK_TILE_RENDERED,{...this.buildHookContextBase(),item:t,isSystem:!0,el:n})}render(){if(Ae.activeDragReset){const o=Ae.activeDragReset;Ae.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="";const t=this.buildHookContextBase();A(v.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of this.items){if(!n&&o.isCore===!1){if(this.itemHost.childElementCount>0){const i=document.createElement("div");i.className="desktop-mode-dock__separator desktop-mode-dock__separator--group",i.setAttribute("aria-hidden","true"),this.itemHost.appendChild(i)}n=!0}const s=this.createItemButton(o);this.itemElements.set(o.id,s),this.itemHost.appendChild(s),A(v.DOCK_TILE_RENDERED,{...t,item:o,isSystem:!1,el:s})}A(v.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["desktop-mode-dock__item","desktop-mode-dock__item--system"],i=j(v.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id;const r=document.createElement("button");r.className="desktop-mode-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title)),r.addEventListener("click",()=>t.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=Wd({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:""},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(t.id),enableGhost:!!t.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(t.onOpenNew??t.onOpen)()},suppressTooltip:d=>{d&&this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),j(v.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["desktop-mode-dock__item"];t.multi&&s.push("desktop-mode-dock__item--multi");const i=j(v.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="desktop-mode-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const a=this.resolveIcon(t.icon,t.title,t.url);if(r.appendChild(a),t.badge>0){const l=t.badge>99?"99+":String(t.badge),u=document.createElement("span");u.className="desktop-mode-dock__badge",u.textContent=l,u.setAttribute("aria-label",oe(rn("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.addEventListener("contextmenu",l=>{l.preventDefault(),Kd({x:l.clientX,y:l.clientY,id:t.id,title:t.title,surface:"dock",pluginFile:t.pluginFile??null,pluginName:t.pluginName??null})}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const d=this.resolveItemBaseId(t),c=Wd({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(d),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(t),suppressTooltip:l=>{l&&this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}});return this.peekTeardowns.set(t.id,c),this.attachDragReorder(o,t.id),j(v.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n){let i=!1,r=0,a=0,d=[],c=null,l=-1,u=null,p=!1;const f=()=>{i=!1,t.classList.remove("desktop-mode-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",N),document.removeEventListener("pointercancel",b),document.removeEventListener("keydown",L,!0),window.removeEventListener("blur",D),document.removeEventListener("visibilitychange",C),l=-1,u=null},h=S=>!!S&&S instanceof HTMLElement&&S.classList.contains("desktop-mode-dock__item")&&!S.classList.contains("desktop-mode-dock__item--system")&&!!S.dataset.menuSlug,m=S=>{for(const I of Array.from(this.itemHost.children))I instanceof HTMLElement&&I!==t&&h(I)&&S(I)},w=()=>{const S=[];for(const I of Array.from(this.itemHost.children))h(I)&&S.push(I.dataset.menuSlug);return S},g=S=>{m(I=>{const R=S.get(I);if(!R)return;const F=I.getBoundingClientRect(),K=R.left-F.left,X=R.top-F.top;if(Math.abs(K)<.5&&Math.abs(X)<.5)return;I.style.transition="none",I.style.transform=`translate(${K}px, ${X}px)`,I.offsetHeight,I.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",I.style.transform="";const E=()=>{I.style.transition="",I.style.transform="",I.removeEventListener("transitionend",E)};I.addEventListener("transitionend",E)})},x=S=>{if(l!==-1&&S.pointerId!==l)return;if(!i){const W=S.clientX-r,V=S.clientY-a;if(W*W+V*V<5*5)return;i=!0,d=w(),c=t.nextSibling,u=t.getBoundingClientRect(),t.classList.add("desktop-mode-dock__item--dragging"),this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}if(!u)return;const I=S.clientX-r,R=S.clientY-a;t.style.transform=`translate(${I}px, ${R}px)`;const K=document.elementFromPoint(S.clientX,S.clientY)?.closest(".desktop-mode-dock__item");if(!K||K===t||!h(K))return;const X=K.getBoundingClientRect();let E;this.orientation==="bottom"?E=S.clientX<X.left+X.width/2:E=S.clientY<X.top+X.height/2;const P=new Map;m(W=>{P.set(W,W.getBoundingClientRect())});let H=!1;if(E?K!==t.nextSibling&&(this.itemHost.insertBefore(t,K),H=!0):K.nextSibling!==t&&(this.itemHost.insertBefore(t,K.nextSibling),H=!0),H){t.style.transform="";const W=t.getBoundingClientRect();r=W.left+W.width/2,a=W.top+W.height/2,t.style.transform=`translate(${S.clientX-r}px, ${S.clientY-a}px)`,g(P)}},T=()=>{t.classList.remove("desktop-mode-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",N),document.removeEventListener("pointercancel",b),document.removeEventListener("keydown",L,!0),window.removeEventListener("blur",D),document.removeEventListener("visibilitychange",C),l=-1,u=null,i=!1,Ae.activeDragReset===f&&(Ae.activeDragReset=null)},y=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const S=()=>{t.style.transition="",t.removeEventListener("transitionend",S)};t.addEventListener("transitionend",S)},k=S=>{const I=window.wp?.desktop;if(!I?.getOsSettings||!I?.updateOsSettings)return;const R=I.getOsSettings().dockOrder,F=new Set(S),K=[];let X=!1;for(const E of R){if(F.has(E)){X||(K.push(...S),X=!0);continue}K.push(E)}X||K.push(...S),I.updateOsSettings({dockOrder:K})},N=S=>{if(l!==-1&&S.pointerId!==l)return;if(!i){T();return}p=!0;const I=w();y(),T(),I.length===d.length&&I.every((F,K)=>F===d[K])||k(I),setTimeout(()=>{p=!1},200)},b=S=>{if(!(S&&l!==-1&&S.pointerId!==l)){if(i&&c!==void 0){const I=new Map;m(R=>{I.set(R,R.getBoundingClientRect())}),this.itemHost.insertBefore(t,c),g(I)}y(),T()}},L=S=>{S.key==="Escape"&&b()},D=()=>b(),C=()=>{document.visibilityState!=="visible"&&b()};t.addEventListener("pointerdown",S=>{if(S.button===0){if(Ae.activeDragReset){const I=Ae.activeDragReset;Ae.activeDragReset=null,I()}(i||l!==-1)&&f(),r=S.clientX,a=S.clientY,l=S.pointerId,i=!1,Ae.activeDragReset=f,document.addEventListener("pointermove",x),document.addEventListener("pointerup",N),document.addEventListener("pointercancel",b),document.addEventListener("keydown",L,!0),window.addEventListener("blur",D),document.addEventListener("visibilitychange",C)}}),t.addEventListener("click",S=>{p&&(S.preventDefault(),S.stopImmediatePropagation())},!0)}resolveIcon(t,n,o){if(t.startsWith("dashicons-")&&t!=="dashicons-admin-generic"){const s=document.createElement("span");return s.className=`dashicons ${t}`,s.setAttribute("aria-hidden","true"),s}if(t.startsWith("data:image/svg+xml;base64,")){const s=t.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(s))return this._makeSvgIcon(t)}if(t.startsWith("url("))return this._makeSvgIcon(t);if(t.startsWith("http://")||t.startsWith("https://")){const s=document.createElement("img");return s.className="desktop-mode-dock__item-img",s.src=t,s.alt="",s.setAttribute("aria-hidden","true"),s}if(o){const s=this._extractNativeMenuIcon(o);if(s)return s}if(t==="dashicons-admin-generic"){const s=document.createElement("span");return s.className="dashicons dashicons-admin-generic",s.setAttribute("aria-hidden","true"),s}return this.createLetterBadge(n)}_makeSvgIcon(t){const n=document.createElement("span");return n.className="desktop-mode-dock__item-svg",n.style.backgroundImage=t.startsWith("url(")?t:`url("${t}")`,n.style.backgroundSize="contain",n.style.backgroundRepeat="no-repeat",n.style.backgroundPosition="center",n.setAttribute("aria-hidden","true"),n}_extractNativeMenuIcon(t){const n=document.getElementById("adminmenu");if(!n)return null;let o;try{const p=new URL(t,window.location.href);o=(p.pathname.split("/").pop()||"")+p.search}catch{return null}if(!o)return null;const s=n.querySelectorAll("li.menu-top > a");let i=null;for(const p of Array.from(s))if(p.href.endsWith(o)){i=p.closest("li.menu-top");break}if(!i)return null;const r=i.querySelector(".wp-menu-image");if(!r)return null;const a=r.querySelector("img");if(a&&a.src){const p=document.createElement("img");return p.className="desktop-mode-dock__item-img",p.src=a.src,p.alt="",p.setAttribute("aria-hidden","true"),p}const d=r.className.match(/\bdashicons-[\w-]+\b/);if(d&&d[0]!=="dashicons-before"){const p=document.createElement("span");return p.className=`dashicons ${d[0]}`,p.setAttribute("aria-hidden","true"),p}const l=window.getComputedStyle(r,"::before").backgroundImage;if(l&&l!=="none"&&!l.includes('url("")'))return this._makeSvgIcon(l);const u=window.getComputedStyle(r).backgroundImage;return u&&u!=="none"&&!u.includes('url("")')?this._makeSvgIcon(u):null}createLetterBadge(t){const n=document.createElement("span");n.className="desktop-mode-dock__item-letter",n.setAttribute("aria-hidden","true");const o=t.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=Qs(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(t,n,o){const s=j(v.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("desktop-mode-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}))}positionTooltip(t,n){const o=t.getBoundingClientRect();this.tooltip.textContent=n,this.orientation==="bottom"?(this.tooltip.style.left=`${o.left+o.width/2}px`,this.tooltip.style.top=`${o.top-14}px`):this.orientation==="right"?(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.left}px`):(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.right+8}px`)}openPage(t){if(t.id.startsWith("dock:")){const o=t.id.slice(5),i=window.desktopModeConfig?.desktopIcons?.find(r=>r.id===o);if(i?.window){window.wp?.desktop?.openWindow?.(i.window);return}if(i?.url){if(Ro(i.url))return;const r=this.deriveWindowId(i.url);this.windowManager.open({id:r,baseId:r,url:i.url,parentUrl:i.url,title:i.title,icon:i.icon.startsWith("dashicons-")?i.icon:"dashicons-admin-generic",submenu:[],multi:!1});return}return}if(Ro(t.url)||mt(t.url))return;const n=this.deriveWindowId(t.url);this.windowManager.open({id:n,baseId:n,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,multi:!!t.multi})}openNewInstance(t){if(Ro(t.url))return;const n=window.wp?.desktop?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=ld(t.url);if(o&&n?.(o,{source:"dock-peek"}))return;const s=this.deriveWindowId(t.url);this.windowManager.openNew({id:s,baseId:s,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,multi:!0})}deriveWindowId(t){return ne(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:ld(t.url)??this.deriveWindowId(t.url)}bindWindowEvents(){const t=()=>this.updateActiveStates();this.boundRefresh=t,document.addEventListener("desktop-mode-window-opened",t),document.addEventListener("desktop-mode-window-closed",t),document.addEventListener("desktop-mode-window-focused",t),window.wp?.hooks?.addAction?.("desktop-mode.desktop.switched",this.hooksNamespace,t),window.wp?.hooks?.addAction?.("desktop-mode.desktop.closed",this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.WINDOW_RESTORED,this.hooksNamespace,t)}destroy(){document.removeEventListener("desktop-mode-window-opened",this.boundRefresh),document.removeEventListener("desktop-mode-window-closed",this.boundRefresh),document.removeEventListener("desktop-mode-window-focused",this.boundRefresh),window.wp?.hooks?.removeAction?.("desktop-mode.desktop.switched",this.hooksNamespace),window.wp?.hooks?.removeAction?.("desktop-mode.desktop.closed",this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.WINDOW_RESTORED,this.hooksNamespace);for(const t of this.attentionTimers.values())window.clearTimeout(t);this.attentionTimers.clear();for(const t of this.peekTeardowns.values())t();for(this.peekTeardowns.clear(),this.tooltip.remove();this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.itemElements.clear(),this.systemItemElements.clear(),this.systemItems=[],this.systemSeparator=null,this.container.removeAttribute("data-desktop-mode-dock-placement")}updateActiveStates(){const t=this.windowManager.getFocused(),n=t?t.config.baseId||t.id:null,o=this.windowManager.getActiveDesktopId(),s=r=>(r.config.desktopId||o)===o,i=r=>r.state==="minimized";for(const r of this.items){const a=this.itemElements.get(r.id);if(!a)continue;const d=this.resolveItemBaseId(r),c=this.windowManager.getAllByBaseId(d).filter(s),l=c.length>0,u=l&&c.every(i),p=n===d&&!!t&&s(t)&&!i(t);a.classList.toggle("desktop-mode-dock__item--active",l),a.classList.toggle("desktop-mode-dock__item--focused",p),a.classList.toggle("desktop-mode-dock__item--all-minimized",u)}for(const r of this.systemItems){const a=this.systemItemElements.get(r.id);if(!a)continue;const d=this.windowManager.getById(r.id),c=r.isOpen?r.isOpen():!!d,l=!!d&&i(d),u=!!t&&t.id===r.id&&!i(t);a.classList.toggle("desktop-mode-dock__item--active",c),a.classList.toggle("desktop-mode-dock__item--focused",u),a.classList.toggle("desktop-mode-dock__item--all-minimized",l)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("desktop-mode-show-desktop-active",o)}};Ae.instanceCounter=0,Ae.activeDragReset=null;let Po=Ae;function Yd(e,t){const n=e.querySelector(":scope > .desktop-mode-dock__badge");if(t<=0){n?.remove();return}const o=t>99?"99+":String(t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",oe(rn("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="desktop-mode-dock__badge",s.textContent=o,s.setAttribute("aria-label",oe(rn("%d notification","%d notifications",t),t)),e.appendChild(s)}const Xd=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),oi={id:"default",label:"Icon strip",description:"The shipped baseline — icon tiles with badges, tooltips, multi-instance chips, and attention animations.",icon:"dashicons-menu-alt",apiVersion:1,mount(e){const t=new Po(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[Xd]:t,replaceItems:o=>t.replaceItems(o),appendSystemItem:o=>t.appendSystemItem(o),removeSystemItem:o=>t.removeSystemItem(o),setBadge:(o,s)=>t.setBadge(o,s),setAttention:(o,s,i)=>t.setAttention(o,s,i),setOrientation:o=>t.setOrientation(o),destroy:()=>t.destroy()}}};function $o(e){if(!e)return null;const n=e[Xd];return n instanceof Po?n:null}function Ew(){Rd(oi)}const Sw=he`:host{display:none;position:fixed;inset:0;align-items:center;justify-content:center;background:rgba( 0,0,0,0.45 );backdrop-filter:blur( 2px );z-index:10000;--desktop-mode-text:#f0f0f1;--desktop-mode-text-muted:#bbc1c7;--desktop-mode-muted:#a7aaad;--desktop-mode-muted-fg:#a7aaad;--desktop-mode-border:rgba( 255,255,255,0.25 );--wpd-button-bg-hover:rgba( 255,255,255,0.08 )}:host( [ open ] ){display:flex}.dialog{max-width:92vw;max-height:90vh;background:var( --wpd-modal-bg,var( --desktop-mode-bg,#1d2327 ) );color:var( --wpd-modal-fg,var( --desktop-mode-fg,#fff ) );border:1px solid rgba( 255,255,255,0.08 );border-radius:10px;box-shadow:0 20px 50px rgba( 0,0,0,0.6 );display:flex;flex-direction:column;overflow:hidden}:host( [ size='sm' ] ) .dialog{width:min( 360px,92vw )}:host(:not( [ size ] ) ) .dialog,:host( [ size='md' ] ) .dialog{width:min( 540px,92vw )}:host( [ size='lg' ] ) .dialog{width:min( 760px,94vw )}.header{display:flex;align-items:center;gap:10px;padding:16px 20px 12px;border-bottom:1px solid rgba( 255,255,255,0.06 )}.title{margin:0;flex:1;font-size:15px;font-weight:600}.header-actions{display:flex;gap:6px}.header-actions::slotted( * ){margin-inline-start:6px}.close{background:transparent;border:0;color:inherit;font-size:18px;line-height:1;padding:4px 8px;border-radius:4px;cursor:pointer;opacity:0.7}.close:hover{opacity:1;background:rgba( 255,255,255,0.08 )}.body{padding:16px 20px;overflow:auto;flex:1 1 auto;font-size:13px;line-height:1.5}.footer{padding:12px 20px 16px;border-top:1px solid rgba( 255,255,255,0.06 )}.footer slot{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap}:host( [ mandatory ] ) .close{display:none}`,Zd='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',lo=class lo extends pe{constructor(){super(...arguments),this._prevFocus=null,this._onKey=t=>{if(t.key==="Escape"&&!this.hasAttribute("mandatory")){t.preventDefault(),this._cancel();return}if(t.key==="Tab"){const n=this._focusables();if(n.length===0)return;const o=n[0],s=n[n.length-1],i=this.ownerDocument,r=i?i.activeElement:null,a=t.composedPath()[0]||r;t.shiftKey&&a===o?(t.preventDefault(),s.focus()):!t.shiftKey&&a===s&&(t.preventDefault(),o.focus())}},this._onBackdrop=t=>{if(this.hasAttribute("mandatory"))return;const n=t.composedPath();(n.length>0?n[0]:t.target)===this&&this._cancel()}}connectedCallback(){super.connectedCallback(),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","true"),this.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback?.(t,n,o),t==="open"){if(o!==null){const s=this.ownerDocument;this._prevFocus=s?s.activeElement:null,queueMicrotask(()=>this._focusFirst())}else if(this._prevFocus){try{this._prevFocus.focus()}catch{}this._prevFocus=null}}}showModal(){this.setAttribute("open","")}hideModal(){this.removeAttribute("open")}_focusables(){const t=this.shadowRoot;if(!t)return[];const n=Array.from(this.querySelectorAll(Zd)),o=Array.from(t.querySelectorAll(Zd));return[...n,...o].filter(s=>s.offsetParent!==null||s.tagName==="BUTTON")}_focusFirst(){const t=this._focusables();t.length>0?t[0].focus():this.shadowRoot?.querySelector(".dialog")?.focus?.()}_cancel(){const t=new CustomEvent("wpd-modal-cancel",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(t)&&this.hideModal()}render(){const t=this.getAttribute("title")??"",n=this.hasAttribute("mandatory");return z` |
| 29 |
<div class="dialog" tabindex="-1"> |
| 30 |
${t?z` |
| 31 |
<div class="header"> |
| 32 |
<h2 class="title">${t}</h2> |
| 33 |
<div class="header-actions"> |
| 34 |
<slot name="header-actions"></slot> |
| 35 |
${n?z``:z`<button |
| 36 |
type="button" |
| 37 |
class="close" |
| 38 |
aria-label="Close" |
| 39 |
@click=${()=>this._cancel()} |
| 40 |
>×</button>`} |
| 41 |
</div> |
| 42 |
</div> |
| 43 |
`:z``} |
| 44 |
<div class="body"> |
| 45 |
<slot></slot> |
| 46 |
</div> |
| 47 |
<div class="footer"> |
| 48 |
<slot name="footer"></slot> |
| 49 |
</div> |
| 50 |
</div> |
| 51 |
`}};lo.props=["open","title","size","mandatory"],lo.styles=[Sw],lo.help=void 0;let si=lo;me("wpd-modal",si);const Iw=he`:host{display:inline-flex}:host( [ fill-cell ] ){display:flex;width:100%}button{appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:var( --wpd-button-padding,6px 12px );border-radius:var( --wpd-button-border-radius,6px );font:inherit;font-weight:500;cursor:pointer;transition:background-color 0.12s ease,color 0.12s ease,border-color 0.12s ease;background:var( --wpd-button-bg,transparent );color:var( --wpd-button-fg,var( --desktop-mode-text,#1d2327 ) );border:var( --wpd-button-border,1px solid var( --desktop-mode-border,#c3c4c7 ) )}:host( [ fill-cell ] ) button{width:100%;min-height:var( --wpd-button-min-height,44px )}button:disabled{opacity:0.5;cursor:not-allowed}button:hover:not(:disabled ){background:var( --wpd-button-bg-hover,rgba( 0,0,0,0.04 ) )}:host( [ variant='primary' ] ) button{background:var( --wpd-button-bg,var( --wp-admin-theme-color,#2271b1 ) );color:var( --wpd-button-fg,#fff );border:var( --wpd-button-border,1px solid transparent )}:host( [ variant='primary' ] ) button:hover:not(:disabled ){filter:brightness( 1.06 );background:var( --wpd-button-bg,var( --wp-admin-theme-color,#2271b1 ) )}:host( [ variant='secondary' ] ) button{background:var( --wpd-button-bg,rgba( 0,0,0,0.06 ) );color:var( --wpd-button-fg,var( --desktop-mode-text,#1d2327 ) );border:var( --wpd-button-border,1px solid transparent )}:host( [ variant='secondary' ] ) button:hover:not(:disabled ){background:var( --wpd-button-bg-hover,rgba( 0,0,0,0.1 ) )}:host( [ variant='danger' ] ) button{background:var( --wpd-button-bg,transparent );color:var( --wpd-button-fg,#d63638 );border:var( --wpd-button-border,1px solid currentColor )}:host( [ variant='danger' ] ) button:hover:not(:disabled ){background:#d63638;color:#fff}:host( [ variant='link' ] ) button{background:transparent;color:var( --wpd-button-fg,var( --wp-admin-theme-color,#2271b1 ) );border:0;padding:0;text-decoration:underline}:host( [ busy ] ) button{pointer-events:none;opacity:0.75}`,uo=class uo extends pe{render(){const t=this.disabled!==null,n=this.type||"button";return z` |
| 52 |
<button part="button" type=${n} ?disabled=${t}> |
| 53 |
<slot></slot> |
| 54 |
</button> |
| 55 |
`}};uo.props=["variant","disabled","type","busy","fill-cell"],uo.styles=[Iw],uo.help=void 0;let ii=uo;me("wpd-button",ii);function Jd(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}const xw=()=>O("Mix your own two-colour gradient and set the angle — your desk, your palette.");function Cw(e){fn({id:hh,label:O("Custom gradient"),type:"css",preview:Jd(e.state),description:xw(),resolveValue:()=>Jd(e.state)})}function Aw(e){if(!e.customImage){vd(xd);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`;fn({id:xd,label:O("Custom image"),type:"css",value:n,preview:n,description:O("Any image from your media library or an upload, sized to cover the whole desk.")})}let Uo=null;function Lw(e){return window.desktopModeRenderOsSettingsPanel?Promise.resolve(window.desktopModeRenderOsSettingsPanel):Uo||(Uo=new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-os-settings-panel="1"]'),s=()=>{const r=window.desktopModeRenderOsSettingsPanel;if(!r){n(new Error("[desktop-mode] os-settings-panel bundle loaded but did not register desktopModeRenderOsSettingsPanel"));return}t(r)};if(o){window.desktopModeRenderOsSettingsPanel?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeOsSettingsPanel="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))),document.head.appendChild(i)}),Uo)}class Tw{constructor(t,n){this.activeEditorTeardown=null,this.tabRegistryUnsubscribe=null,this.activeTabId=null,this.osSettingsListeners=new Set,this._lastRenderedBody=null,this.config=t,this.layer=n,this.state=vh(),Ch(this.state),document.addEventListener("desktop-mode-os-settings-save-lifecycle",o=>{const s=o.detail;!s||s.phase!=="failed"||!s.rolledBackTo||(this.state=s.rolledBackTo,this.apply(),this._lastRenderedBody?.isConnected&&this.renderPanel(this._lastRenderedBody))}),Cw(this),Aw(this.state)}getOsSettingsSnapshot(){return{wallpaper:this.state.wallpaper,accent:this.state.accent,dockSize:this.state.dockSize,desktopLayout:this.state.desktopLayout,dockRailRenderer:this.state.dockRailRenderer,unfocusEffect:this.state.unfocusEffect,windowLinkRenderer:this.state.windowLinkRenderer,windowLinkVisibility:this.state.windowLinkVisibility,windowLinksEnabled:this.state.windowLinksEnabled,windowLinkRaiseOnFocus:this.state.windowLinkRaiseOnFocus,windowLinkHighlight:this.state.windowLinkHighlight,ai:{...this.state.ai},nativePostsEnabled:this.state.nativePostsEnabled,nativePostsHiddenColumns:this.state.nativePostsHiddenColumns.slice(),nativePagesEnabled:this.state.nativePagesEnabled,nativeUsersEnabled:this.state.nativeUsersEnabled,nativePluginsEnabled:this.state.nativePluginsEnabled,nativeCommentsEnabled:this.state.nativeCommentsEnabled,developerModeEnabled:this.state.developerModeEnabled,foldersSharingEnabled:this.state.foldersSharingEnabled,itemVisibility:{...this.state.itemVisibility},dockOrder:this.state.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(this.state.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}subscribeOsSettings(t){return this.osSettingsListeners.add(t),()=>{this.osSettingsListeners.delete(t)}}apply(){const t=document.getElementById("desktop-mode-shell");if(!t)return;mh(this.state.wallpaperSettings);const n=js(this.state.wallpaper)||js(Ld())||js(qs)||_d()[0];n&&this.layer.apply(n);const o=Ad(),s=o.find(a=>a.id===this.state.accent)??o[0],i=Vs.find(a=>a.id===this.state.dockSize)??Vs[1],r=document.documentElement;r.style.setProperty("--wp-admin-theme-color",s.value),r.style.setProperty("--desktop-mode-dock-width",`${i.width}px`),r.style.setProperty("--desktop-mode-dock-icon-size",`${i.icon}px`),t.setAttribute("data-desktop-mode-layout",this.state.desktopLayout),Hh(this.state.dockRailRenderer)}save(t={}){if(Ah(this.state,t),this.osSettingsListeners.size>0){const n=this.getOsSettingsSnapshot(),o=Array.from(this.osSettingsListeners);for(const s of o)try{s(n)}catch(i){typeof console<"u"&&console.error("[desktop-mode] os-settings listener threw:",i)}}}focusTab(t){this.activeTabId=t;const n=this._lastRenderedBody;if(!n?.isConnected)return;const o=n.querySelector("wpd-tabs");o&&(o.value=t)}renderPanel(t){this._lastRenderedBody=t;const n=window.desktopModeRenderOsSettingsPanel;if(n){n(this,t);return}Lw(this.config.osSettingsPanelBundleUrl??"").then(o=>{t.isConnected&&o(this,t)}).catch(o=>{typeof console<"u"&&console.error("[desktop-mode] OS Settings panel failed to load:",o)})}}const Nw="desktop-mode-exit";function Dw(){return{id:Nw,title:O("Exit Desktop Mode"),icon:"dashicons-exit",onOpen:()=>{Ow()}}}async function Ow(){const e=window.desktopModeAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Qd(t);return}const n=new URLSearchParams;n.set("action","save-desktop-mode"),n.set("nonce",e.nonce),n.set("enabled","");let o=t;try{const s=await fetch(e.ajaxUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),credentials:"same-origin"});if(s.ok){const i=await s.json();i?.success&&i.data?.redirect&&(o=i.data.redirect)}}catch{}Qd(o)}function Qd(e){try{window.top.location.href=e}catch{window.location.href=e}}const Rw={userId:null,requestedAt:0,tabRequested:!1};let Ho=null;function Mw(){if(Ho)return Ho;const t=window.wp?.desktop?.createSharedStore;return typeof t!="function"?null:(Ho=t("desktop-mode/user-edit/target",()=>({...Rw})),Ho)}function Ww(e){const t=Mw();if(t){t.state.userId=e,t.state.requestedAt=Date.now(),t.state.tabRequested=!0,t.notify();return}const n=window;n._wpdUserEditTarget={userId:e,requestedAt:Date.now(),tabRequested:!0}}const ri=new Map;function Ee(e,t){const n=ri.get(e);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-desktop-mode-vendor="${Pw(e)}"]`,a=document.querySelector(r);if(a){if(a.dataset.loaded==="1"){s();return}a.addEventListener("load",()=>s(),{once:!0}),a.addEventListener("error",()=>i(new Error(`Failed to load ${e}`)),{once:!0});return}t?.translations&&Bo(t.translations);for(const c of t?.l10n??[])Bo(c);for(const c of t?.before??[])Bo(c);const d=document.createElement("script");d.src=e,d.async=!0,d.dataset.desktopModeVendor=e,d.addEventListener("load",()=>{d.dataset.loaded="1";for(const c of t?.after??[])Bo(c);s()},{once:!0}),d.addEventListener("error",()=>{ri.delete(e),d.remove(),i(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(d)});return ri.set(e,o),o}function Bo(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.desktopModeVendorInline="1",document.head.appendChild(t)}function Pw(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}const Fo=new Map;function ec(e){if(!e||typeof e.id!="string"||e.id===""){typeof console<"u"&&console.warn("[desktop-mode] Ignored invalid module registration:",e);return}if(typeof e.url!="string"||e.url===""){typeof console<"u"&&console.warn(`[desktop-mode] Module "${e.id}" has no url; ignored.`);return}Fo.set(e.id,e)}function $w(){return Array.from(Fo.keys())}async function tc(e){if(!e||e.length===0)return;const t=e.filter(n=>!Fo.has(n));if(t.length>0)throw new Error(`[desktop-mode] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${$w().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=Fo.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():Ee(o.url)}))}function nc(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:Uw(),visible:!document.hidden,settings:fh(e)}}function Uw(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class oc{constructor(t,n){this.generation=0,this.active=null,this.boundVisibilityChange=()=>{this.active&&A(v.WALLPAPER_VISIBILITY,{id:this.active.id,state:document.hidden?"hidden":"visible"})},this.element=t,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(t){const n=++this.generation;if(this.teardownActive(),t.type==="css"){this.applyCss(t);return}this.applyCanvas(t,n)}teardownActive(){if(!this.active)return;const{id:t,teardown:n}=this.active;this.active=null,A(v.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){A(v.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[desktop-mode] Wallpaper "${t}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(t){const n=t.resolveValue?t.resolveValue(nc(t.id,this.pluginUrl)):t.value;typeof n=="string"&&(this.element.style.setProperty("--desktop-mode-bg",n),document.getElementById("desktop-mode-shell")?.style.setProperty("--desktop-mode-bg",n))}applyCanvas(t,n){const o=nc(t.id,this.pluginUrl);A(v.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?tc(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},A(v.WALLPAPER_MOUNTED,{id:t.id,container:this.element,ctx:o})};s.then(()=>{if(n!==this.generation)return;let r;try{r=t.mount(this.element,o)}catch(a){this.handleMountFailure(t.id,a);return}if(Hw(r)){r.then(i,a=>{n===this.generation&&this.handleMountFailure(t.id,a)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(t.id,r)})}handleMountFailure(t,n){this.element.innerHTML="",A(v.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),A(v.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[desktop-mode] Wallpaper "${t}" failed to mount:`,n)}}function Hw(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}function Bw(e){const{osSettings:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await Ee(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter})}catch(l){A(v.SHELL_ERROR,{scope:"wallpaper-script-load",id:c.id,error:l});return}o.add(c.scriptUrl)}},i=c=>(window.desktopModeWallpapers||{})[c]??null,r=c=>c.type!=="css"||c.value===""?null:{id:c.id,label:c.label,type:"css",value:c.value,preview:c.preview!==""?c.preview:c.value,description:c.description||void 0},a=async c=>{if(n.has(c.id))return;const l=r(c);if(l){fn(l),n.add(c.id),t.apply();return}await s(c);let u=i(c.id);if(u&&!u.description&&c.description&&(u={...u,description:c.description}),!u){A(v.SHELL_ERROR,{scope:"wallpaper-missing-def",id:c.id,error:new Error(`[desktop-mode] No wallpaper def on window.desktopModeWallpapers["${c.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)});return}try{fn(u)}catch(p){A(v.SHELL_ERROR,{scope:"wallpaper-register",id:c.id,error:p});return}n.add(c.id),t.apply()},d=c=>{n.has(c)&&(vd(c),n.delete(c),t.apply())};return async c=>{const l=new Set;for(const u of c)l.add(u.id);for(const u of Array.from(n))l.has(u)||d(u);for(const u of c)n.has(u.id)||await a(u)}}const sc=/^[a-z0-9_/-]+$/,ic=re("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),yt=ic.state.registry,Fw=ic.state.listeners;function zo(e){const t=[],n=typeof e?.slug=="string"?e.slug.trim().toLowerCase():"";!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.slug!="string"||e.slug.trim()===""?t.push("slug (missing)"):sc.test(n)||t.push(`slug (must match ${sc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.run!="function"&&t.push("run (must be a function)")),Oe("Command",t,e),yt.set(n,{...e,slug:n}),ai()}function rc(e){yt.delete(e.toLowerCase())&&ai()}function Go(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(yt.entries()))o.owner===e&&(yt.delete(n),t++);return t>0&&ai(),t}function ac(){return Array.from(yt.values())}function zw(){const e=[];for(const t of yt.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function Gw(e){return yt.get(e.toLowerCase())??null}function ai(){const e=Array.from(Fw);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] command-registry listener threw:",n)}}function jw(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ee(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.slug)continue;let c=a.get(d.scriptHandle);c||(c=new Set,a.set(d.scriptHandle,c)),c.add(d.slug)}return a},i=r=>{const a=new Set;for(const c of ac())c.owner===r&&a.add(c.slug);const d=n.get(r);if(d)for(const c of d)a.add(c);return a};return async(r,a)=>{const d=new Set;for(const c of r)c.handle&&d.add(c.handle);for(const c of Array.from(e))if(!d.has(c)){for(const l of i(c))rc(l);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const dc=re("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),vn=dc.state.registry,qw=dc.state.listeners;function cc(e){if(!e||typeof e.id!="string"||e.id.trim()===""||typeof e.label!="string"||e.label.trim()===""||typeof e.render!="function")return;const t=e.id.trim().toLowerCase();if(!/^[a-z0-9_\-]+$/.test(t)){typeof console<"u"&&console.warn("[desktop-mode] registerSettingsTab: id must be [a-z0-9_-]+, got",e.id);return}vn.set(t,{...e,id:t}),di()}function lc(e){vn.delete(e.toLowerCase())&&di()}function Vw(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(vn.entries()))o.owner===e&&(vn.delete(n),t++);return t>0&&di(),t}function uc(){return Array.from(vn.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function di(){const e=Array.from(qw);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] settings-tab-registry listener threw:",n)}}function Kw(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ee(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let c=a.get(d.scriptHandle);c||(c=new Set,a.set(d.scriptHandle,c)),c.add(d.id)}return a},i=r=>{Vw(r);const a=n.get(r);if(a){const d=new Set(uc().map(c=>c.id));for(const c of a)d.has(c)&&lc(c)}};return async(r,a)=>{const d=new Set;for(const c of r)c.handle&&d.add(c.handle);for(const c of Array.from(e))d.has(c)||(i(c),e.delete(c));for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const pc=re("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),kn=pc.state.registry,Yw=pc.state.listeners,fc=/^[a-z0-9_/-]+$/;function mc(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):fc.test(e.id.trim().toLowerCase())||t.push(`id (must match ${fc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (missing)"),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)")),Oe("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();kn.set(n,{...e,id:n}),ci()}function Xw(e){kn.delete(e.toLowerCase())&&ci()}function Zw(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(kn.entries()))o.owner===e&&(kn.delete(n),t++);return t>0&&ci(),t}function Jw(){return Array.from(kn.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function ci(){const e=Array.from(Yw);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] title-bar-button registry listener threw:",n)}}function Qw(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ee(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(Zw(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Pt="none",li="svg-splines",hc=re("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),_n=hc.state.registry,ui=hc.state.listeners,wc=/^[a-z0-9_/-]+$/;function gc(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):wc.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Pt&&t.push('id ("none" is reserved)'):t.push(`id (must match ${wc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.mount!="function"&&t.push("mount (not a function)")),Oe("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();_n.set(n,{...e,id:n}),fi()}function eg(e){_n.delete(e.toLowerCase())&&fi()}function tg(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(_n.entries()))o.owner===e&&(_n.delete(n),t++);return t>0&&fi(),t}function yc(){const e=Array.from(_n.values()),t=j(v.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function pi(e){return yc().find(t=>t.id===e)}function ng(e){return ui.add(e),()=>{ui.delete(e)}}function fi(){const e=Array.from(ui);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-link-renderer registry listener threw:",n)}}const og=16;function sg(e,t){const n=t.map(i=>({start:Math.max(e.start,i.start),end:Math.min(e.end,i.end)})).filter(i=>i.end>i.start).sort((i,r)=>i.start-r.start),o=[];let s=e.start;for(const i of n)i.start>s&&o.push({start:s,end:i.start}),s=Math.max(s,i.end);return s<e.end&&o.push({start:s,end:e.end}),o}function ig(e,t){const n=e.x+e.width/2,o=e.y+e.height/2,s=t.x-n,i=t.y-o;if(s===0&&i===0)return{x:n,y:o,side:"right"};const r=s!==0?e.width/2/Math.abs(s):1/0,a=i!==0?e.height/2/Math.abs(i):1/0,d=Math.min(r,a),c=n+s*d,l=o+i*d;let u;return r<=a?u=s>0?"right":"left":u=i>0?"bottom":"top",{x:c,y:l,side:u}}function bc(e,t,n,o){for(const s of n)if(!(s.windowId===o||s.zIndex<=t)&&e.x>=s.rect.x&&e.x<=s.rect.x+s.rect.width&&e.y>=s.rect.y&&e.y<=s.rect.y+s.rect.height)return!1;return!0}function rg(e,t,n,o,s){const i=n.filter(c=>c.windowId!==o&&c.zIndex>t),r=[{side:"top",base:{start:e.x,end:e.x+e.width},at:e.y,horizontal:!0},{side:"bottom",base:{start:e.x,end:e.x+e.width},at:e.y+e.height,horizontal:!0},{side:"left",base:{start:e.y,end:e.y+e.height},at:e.x,horizontal:!1},{side:"right",base:{start:e.y,end:e.y+e.height},at:e.x+e.width,horizontal:!1}];let a=null,d=1/0;for(const{side:c,base:l,at:u,horizontal:p}of r){const f=[];for(const{rect:h}of i)(p?h.y<=u&&u<=h.y+h.height:h.x<=u&&u<=h.x+h.width)&&f.push(p?{start:h.x,end:h.x+h.width}:{start:h.y,end:h.y+h.height});for(const h of sg(l,f)){if(h.end-h.start<og)continue;const m=(h.start+h.end)/2,w=p?m:u,g=p?u:m,x=Math.hypot(s.x-w,s.y-g);x<d&&(d=x,a={x:w,y:g,side:c})}}return a}function ag(e,t){const n=Math.max(t.x-(e.x+e.width),e.x-(t.x+t.width)),o=Math.max(t.y-(e.y+e.height),e.y-(t.y+t.height));if(n<0&&o<0)return null;const s=Math.max(e.x,t.x),i=Math.min(e.x+e.width,t.x+t.width),r=Math.max(e.y,t.y),a=Math.min(e.y+e.height,t.y+t.height);let d,c;i>=s?d=c=(s+i)/2:t.x>e.x?(d=e.x+e.width,c=t.x):(d=e.x,c=t.x+t.width);let l,u;a>=r?l=u=(r+a)/2:t.y>e.y?(l=e.y+e.height,u=t.y):(l=e.y,u=t.y+t.height);const p=n>=o,f=(h,m,w)=>p?m<=h.x?"left":"right":w<=h.y?"top":"bottom";return{from:{x:d,y:l,side:f(e,d,l)},to:{x:c,y:u,side:f(t,c,u)}}}function vc(e,t){const n=Math.min(160,Math.max(24,.4*t));switch(e.side){case"left":return{x:e.x-n,y:e.y};case"right":return{x:e.x+n,y:e.y};case"top":return{x:e.x,y:e.y-n};default:return{x:e.x,y:e.y+n}}}function dg(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}const $t="http://www.w3.org/2000/svg";let cg=0;function kc(e,t,n,o,s){const i=ig(e,s);return t===null||bc(i,t,o,n)?i:rg(e,t,o,n,s)??i}function lg(e,t){const n=document.createElementNS($t,"defs"),o=(a,d,c)=>{const l=`${t}-${a}`,u=document.createElementNS($t,"marker");u.setAttribute("id",l),u.setAttribute("viewBox","0 0 10 10"),u.setAttribute("refX","5"),u.setAttribute("refY","5"),u.setAttribute("markerWidth",c),u.setAttribute("markerHeight",c),u.setAttribute("markerUnits","strokeWidth");const p=document.createElementNS($t,"circle");return p.setAttribute("cx","5"),p.setAttribute("cy","5"),p.setAttribute("r","4"),p.classList.add(d),u.appendChild(p),n.appendChild(u),l},s="desktop-mode-window-link__endpoint",i=`${s}--active`,r={dot:{normal:o("dot",s,"7"),active:o("dot-active",i,"7")},port:{normal:o("port",s,"4.5"),active:o("port-active",i,"4.5")}};return e.appendChild(n),r}gc({id:"svg-splines",label:O("Splines"),description:O("Curved connectors between related windows, ending in circular dots — the larger dot sits on the window the content belongs to; windows that reference each other get large dots on both ends."),mount:e=>{const t=++cg,n=(a,d)=>{const c=document.createElementNS($t,"svg");return c.classList.add("desktop-mode-window-links__svg"),a.appendChild(c),{svg:c,markers:lg(c,`desktop-mode-window-link-${t}${d}`)}},o={base:n(e.container,""),elevated:n(e.elevatedContainer,"-elevated")},s=new Map,i=a=>{for(const{svg:c}of[o.base,o.elevated])c.setAttribute("width",String(a.container.width)),c.setAttribute("height",String(a.container.height)),c.setAttribute("viewBox",`0 0 ${a.container.width} ${a.container.height}`);const d=new Set;for(const c of a.edges){if(!c.from||!c.to)continue;const l=`${c.fromWindowId}→${c.toWindowId}:${c.kind}`;d.add(l);const u=c.elevated?"elevated":"base";let p=s.get(l);if(p&&p.surface!==u&&(p.group.remove(),s.delete(l),p=void 0),!p){const b=document.createElementNS($t,"g");b.classList.add("desktop-mode-window-link");const L=document.createElementNS($t,"path");L.classList.add("desktop-mode-window-link__path"),b.appendChild(L),o[u].svg.appendChild(b),p={group:b,path:L,surface:u},s.set(l,p)}const f=a.obstacles??[],h=ag(c.from,c.to),m=(b,L,D)=>L===null||bc(b,L,f,D);let w=null;h&&m(h.from,c.fromZIndex,c.fromWindowId)&&(w=h.from),w||(w=kc(c.from,c.fromZIndex,c.fromWindowId,f,h?{x:h.to.x,y:h.to.y}:dg(c.to)));let g=null;h&&m(h.to,c.toZIndex,c.toWindowId)&&(g=h.to),g||(g=kc(c.to,c.toZIndex,c.toWindowId,f,{x:w.x,y:w.y}));const x=Math.hypot(g.x-w.x,g.y-w.y),T=vc(w,x),y=vc(g,x);p.path.setAttribute("d",`M ${w.x} ${w.y} C ${T.x} ${T.y}, ${y.x} ${y.y}, ${g.x} ${g.y}`);const k=o[p.surface].markers,N=c.focused?"active":"normal";p.path.setAttribute("marker-end",`url(#${k.dot[N]})`),p.path.setAttribute("marker-start",`url(#${c.bidirectional?k.dot[N]:k.port[N]})`),p.group.classList.toggle("desktop-mode-window-link--active",c.focused)}for(const[c,l]of Array.from(s))d.has(c)||(l.group.remove(),s.delete(c))},r=e.onFrame(i);return i(e.getFrame()),()=>{r(),s.clear(),o.base.svg.remove(),o.elevated.svg.remove()}}});const _c="desktop-mode-window-links",Ec="desktop-mode-window--linked",Sc="desktop-mode-window-links--visible";let Ic=!1;function ug({manager:e,osSettings:t}){if(Ic)return;Ic=!0;let n=t.getOsSettingsSnapshot(),o=null,s=null,i=null,r=null,a=0;const d=new Set;let c=!1;const l=new Set;let u=!1;const p=I=>{const R=I.element;return!R||!R.isConnected||I.state==="minimized"||R.offsetParent===null?null:{x:R.offsetLeft,y:R.offsetTop,width:R.offsetWidth,height:R.offsetHeight}},f=I=>I.state==="snapped-left"||I.state==="snapped-right"?null:p(I),h=()=>{const I=[];for(const E of No()){if(E.rootWindowIds.length===0||E.children.length===0)continue;const P=[],H=(W,V,M)=>{const $=e.getById(W);!$||!M||P.push({windowId:W,role:V,content:M,rect:f($),focused:$.isFocused(),state:$.state})};for(const W of E.rootWindowIds)H(W,"root",hd(W));for(const W of E.children)H(W.windowId,"child",W.content);P.length>0&&I.push({key:E.key,root:E.root,members:P})}const R=E=>{const P=Number.parseInt(E.element?.style.zIndex||"",10);return Number.isFinite(P)?P:null},F=e.getFocused()?.id??null,K=[];for(const E of pn()){const P=e.getById(E.fromWindowId),H=e.getById(E.toWindowId);if(!P||!H)continue;const W=P.isFocused()||H.isFocused();K.push({fromWindowId:E.fromWindowId,toWindowId:E.toWindowId,kind:E.kind,bidirectional:E.bidirectional,focused:W,from:f(P),to:f(H),fromZIndex:R(P),toZIndex:R(H),elevated:F!==null&&(E.fromWindowId===F||E.toWindowId===F)})}const X=[];for(const E of e.getAll()){const P=p(E);P&&X.push({windowId:E.id,rect:P,zIndex:R(E)??0})}return{groups:I,edges:K,obstacles:X,container:{width:o?.offsetWidth??0,height:o?.offsetHeight??0}}},m=()=>{c||d.size===0||(c=!0,requestAnimationFrame(()=>{if(c=!1,!i)return;const I=h();for(const R of Array.from(d))try{R(I)}catch(F){typeof console<"u"&&console.error("[desktop-mode] window-link frame subscriber threw:",F)}}))},w=()=>{if(o&&o.isConnected&&s?.isConnected)return o;const I=document.getElementById("desktop-mode-area");if(!I)return null;o=document.createElement("div"),o.id=_c,o.className="desktop-mode-window-links",o.setAttribute("aria-hidden","true"),s=document.createElement("div"),s.id=`${_c}-elevated`,s.className="desktop-mode-window-links desktop-mode-window-links--elevated",s.setAttribute("aria-hidden","true");const R=document.getElementById("desktop-mode-widgets");return R&&R.parentElement===I?(R.insertAdjacentElement("afterend",s),R.insertAdjacentElement("afterend",o)):I.prepend(o,s),o},g=()=>pn().length>0,x=()=>{let I=n.windowLinkRenderer||li;return I=j(v.WINDOW_LINK_RENDERER,I),I===Pt?Pt:pi(I)?I:pi(li)?li:Pt},T=()=>{if(a++,d.clear(),c=!1,r){try{r()}catch(I){A(v.SHELL_ERROR,{scope:"window-link-renderer-teardown",error:I})}r=null}i=null,o?.replaceChildren(),s?.replaceChildren()},y=I=>{const R=pi(I),F=w();if(!R||!F||!s)return;i=I;const K=++a,X={container:F,elevatedContainer:s,getFrame:h,onFrame:E=>(d.add(E),()=>{d.delete(E)})};try{const E=R.mount(X);E instanceof Promise?E.then(P=>{if(K!==a){typeof P=="function"&&P();return}typeof P=="function"&&(r=P)}).catch(P=>{A(v.SHELL_ERROR,{scope:"window-link-renderer-mount",error:P}),K===a&&(i=null)}):typeof E=="function"&&(r=E)}catch(E){A(v.SHELL_ERROR,{scope:"window-link-renderer-mount",error:E}),i=null}m()},k=()=>{const I=e.getFocused();return I?new Set(gd(I.id)):new Set},N=()=>n.windowLinksEnabled!==!1,b=()=>{if(!o)return;const I=!u&&N()&&(n.windowLinkVisibility==="always"||n.windowLinkVisibility==="focus"&&k().size>0);o.classList.toggle(Sc,I),s?.classList.toggle(Sc,I)},L=()=>{if(!N()||n.windowLinkRaiseOnFocus===!1||n.windowLinkVisibility==="off")return;const I=e.getFocused();if(I)for(const R of oh(I.id)){const F=e.getById(R);F&&F.state!=="minimized"&&e.raise(R)}},D=()=>{if(!s)return;const I=e.getFocused(),R=k();if(!I||R.size===0||!N()||n.windowLinkVisibility==="off"){s.style.zIndex="";return}let F=-1/0;for(const K of[I.id,...R]){const X=e.getById(K),E=X?.element;if(!E||X.state==="minimized")continue;const P=Number.parseInt(E.style.zIndex||"",10);Number.isFinite(P)&&(F=Math.max(F,P))}s.style.zIndex=Number.isFinite(F)?String(F):""},C=()=>{const I=N()&&n.windowLinkHighlight!==!1&&n.windowLinkVisibility!=="off"?k():new Set;for(const R of l)I.has(R)||e.getById(R)?.element?.classList.remove(Ec);for(const R of I)e.getById(R)?.element?.classList.add(Ec);l.clear();for(const R of I)l.add(R)},S=()=>{const I=N()&&n.windowLinkVisibility!=="off"&&g()?x():Pt;I===Pt?i&&T():I!==i&&(T(),y(I)),b(),C(),D(),m()};G(v.WINDOW_BOUNDS_CHANGED,"desktop-mode/window-links-frame",()=>m());for(const I of[v.WINDOW_MOVED,v.WINDOW_RESIZED,v.WINDOW_MINIMIZED,v.WINDOW_RESTORED,v.WINDOW_MAXIMIZED,v.WINDOW_UNMAXIMIZED,v.WINDOW_FULLSCREEN_ENTERED,v.WINDOW_FULLSCREEN_EXITED,v.SNAP_ZONE_COMMITTED,v.SNAP_SPLIT_FILLED,v.DESKTOP_SWITCHED,v.SHELL_RESIZED])G(I,"desktop-mode/window-links-frame",()=>m());G(v.WINDOW_FOCUSED,"desktop-mode/window-links-focus",()=>{L(),b(),C(),D(),m()}),G(v.WINDOW_BLURRED,"desktop-mode/window-links-blur",()=>{b(),C(),D(),m()}),G(v.OVERVIEW_ENTERING,"desktop-mode/window-links-overview",()=>{u=!0,b()}),G(v.OVERVIEW_EXITED,"desktop-mode/window-links-overview",()=>{u=!1,b(),m()}),yd(S),ng(S),t.subscribeOsSettings(I=>{const R=I.windowLinkRenderer!==n.windowLinkRenderer,F=R||I.windowLinkVisibility!==n.windowLinkVisibility||I.windowLinksEnabled!==n.windowLinksEnabled||I.windowLinkRaiseOnFocus!==n.windowLinkRaiseOnFocus||I.windowLinkHighlight!==n.windowLinkHighlight;n=I,F&&(R&&i&&T(),S())}),S()}const xc="none",Cc=re("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),En=Cc.state.registry,mi=Cc.state.listeners,Ac=/^[a-z0-9_/-]+$/;function jo(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Ac.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===xc&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Ac} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.className!="string"&&typeof e.apply!="function"&&t.push("className|apply (at least one must be provided — a CSS class to toggle or an apply callback)")),Oe("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();En.set(n,{...e,id:n}),wi()}function pg(e){En.delete(e.toLowerCase())&&wi()}function fg(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(En.entries()))o.owner===e&&(En.delete(n),t++);return t>0&&wi(),t}function hi(){const e=Array.from(En.values()),t=j(v.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function Lc(e){return hi().find(t=>t.id===e)}function mg(e){return mi.add(e),()=>{mi.delete(e)}}function wi(){const e=Array.from(mi);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] unfocus-effect registry listener threw:",n)}}jo({id:"darken",label:O("Darken"),description:O("Dim unfocused windows so the focused one stands out."),className:"desktop-mode-window--fx-darken"}),jo({id:"frost",label:O("Frost"),description:O("Throw unfocused windows out of focus — a soft, frosted-glass blur, as if you were looking at them through an iced-over pane."),className:"desktop-mode-window--fx-frost"}),jo({id:"grayscale",label:O("Grayscale"),description:O("Drain the colour from unfocused windows so the focused one is the only thing still in colour — your eye snaps right to it."),className:"desktop-mode-window--fx-grayscale"});function hg(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ee(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"unfocus-effect-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(fg(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function wg(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ee(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"window-link-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(tg(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const gi="data-desktop-unfocus-effect",yi="data-desktop-unfocus-effect-class";let Tc=!1;function gg(e){return e.querySelector("canvas")!==null}function yg({manager:e,osSettings:t}){if(Tc)return;Tc=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const d=r.getAttribute(yi);d&&(r.classList.remove(d),r.removeAttribute(yi));const c=r.getAttribute(gi);c&&Lc(c)?.clear?.(r);for(const l of a)l.className&&r.classList.remove(l.className);r.removeAttribute(gi)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(yi,a.className)),r.setAttribute(gi,a.id),a.apply?.(r)},i=()=>{const r=n===xc?void 0:Lc(n),a=hi();for(const d of e.getAll()){const c=d.element;c&&(o(c,a),!(!r||d.isFocused()||d.state==="minimized")&&(gg(c)||s(c,r)))}};for(const r of["desktop-mode-window-opened","desktop-mode-window-reopened","desktop-mode-window-closed","desktop-mode-window-focused","desktop-mode-window-blurred"])document.addEventListener(r,()=>i());t.subscribeOsSettings(r=>{n=r.unfocusEffect,i()}),mg(()=>i()),i()}function bg(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ee(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(Ph(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Nc=re("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),Sn=Nc.state.registry,vg=Nc.state.listeners,Dc=/^[a-z0-9_/-]+$/;function Oc(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{if(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Dc.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Dc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!e.tokens||typeof e.tokens!="object")t.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(e.tokens))if(!o.startsWith("--")){t.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof e.match!="function"&&t.push("match (must be a function)")}Oe("WindowTheme",t,e);const n=e.id.trim().toLowerCase();Sn.set(n,{...e,id:n}),bi()}function Rc(e){Sn.delete(e.toLowerCase())&&bi()}function kg(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Sn.entries()))o.owner===e&&(Sn.delete(n),t++);return t>0&&bi(),t}function Mc(){return Array.from(Sn.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function bi(){const e=Array.from(vg);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-theme registry listener threw:",n)}}function _g(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async d=>{if(!d.scriptUrl||t.has(d.scriptUrl)){e.add(d.handle);return}try{await Ee(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(c){A(v.SHELL_ERROR,{scope:"window-theme-script-load",handle:d.handle,url:d.scriptUrl,error:c});return}t.add(d.scriptUrl),e.add(d.handle)},i=d=>{const c=new Map;if(!d)return c;for(const l of d){if(!l.scriptHandle||!l.id)continue;let u=c.get(l.scriptHandle);u||(u=new Set,c.set(l.scriptHandle,u)),u.add(l.id)}return c},r=d=>{const c=new Set;for(const u of Mc())u.owner===d&&c.add(u.id);const l=n.get(d);if(l)for(const u of l)c.add(u);return c},a=d=>{if(d){for(const c of d)if(!(!c.id||!c.tokens))try{Oc({id:c.id,label:c.label,tokens:c.tokens,priority:c.priority,match:()=>!0,owner:c.scriptHandle||void 0}),o.add(c.id)}catch(l){A(v.SHELL_ERROR,{scope:"window-theme-shell-register",id:c.id,error:l})}}};return async(d,c)=>{const l=new Set;for(const u of d)u.handle&&l.add(u.handle);for(const u of Array.from(e)){if(l.has(u))continue;const p=r(u);for(const f of p)Rc(f),o.delete(f);kg(u),e.delete(u)}a(c);for(const u of d)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const Wc=re("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),In=Wc.state.registry,Eg=Wc.state.listeners,Pc=/^[a-z0-9_/-]+$/;function xn(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Pc.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Pc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)"),typeof e.render!="function"&&(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (required when render is omitted)"),typeof e.match!="function"&&t.push("match (must be a function)"),e.placement!==void 0&&e.placement!=="left"&&e.placement!=="right"&&e.placement!=="controls"&&t.push('placement (must be "left", "right", or "controls")')),Oe("WindowControl",t,e);const n=e.id.trim().toLowerCase();In.set(n,{...e,id:n}),vi()}function $c(e){In.delete(e.toLowerCase())&&vi()}function Sg(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(In.entries()))o.owner===e&&(In.delete(n),t++);return t>0&&vi(),t}function Uc(){return Array.from(In.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function vi(){const e=Array.from(Eg);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-control registry listener threw:",n)}}function Ig(){xn({id:"core/minimize",label:O("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),xn({id:"core/maximize",label:O("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),xn({id:"core/focus-tab",label:O("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),xn({id:"core/close",label:O("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function xg(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ee(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let c=a.get(d.scriptHandle);c||(c=new Set,a.set(d.scriptHandle,c)),c.add(d.id)}return a},i=r=>{const a=new Set;for(const c of Uc())c.owner===r&&a.add(c.id);const d=n.get(r);if(d)for(const c of d)a.add(c);return a};return async(r,a)=>{const d=new Set;for(const c of r)c.handle&&d.add(c.handle);for(const c of Array.from(e))if(!d.has(c)){for(const l of i(c))$c(l);Sg(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Hc=re("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),Cn=Hc.state.registry,Cg=Hc.state.listeners,Bc=/^[a-z0-9_/-]+$/,Fc=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function zc(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Bc.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Bc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):Fc.has(e.slot)||t.push(`slot (must be one of ${Array.from(Fc).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Oe("WindowSlot",t,e);const n=e.id.trim().toLowerCase();Cn.set(n,{...e,id:n}),_i()}function ki(e){Cn.delete(e.toLowerCase())&&_i()}function Ag(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Cn.entries()))o.owner===e&&(Cn.delete(n),t++);return t>0&&_i(),t}function Gc(){return Array.from(Cn.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function _i(){const e=Array.from(Cg);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-slot registry listener threw:",n)}}function Lg(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ee(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let c=a.get(d.scriptHandle);c||(c=new Set,a.set(d.scriptHandle,c)),c.add(d.id)}return a},i=r=>{const a=new Set;for(const c of Gc())c.owner===r&&a.add(c.id);const d=n.get(r);if(d)for(const c of d)a.add(c);return a};return async(r,a)=>{const d=new Set;for(const c of r)c.handle&&d.add(c.handle);for(const c of Array.from(e))if(!d.has(c)){for(const l of i(c))ki(l);Ag(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Tg="desktop-mode-notice-dismissed";function Ng(){const t=window.wp?.desktop?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function jc(){return`${Tg}:${Ng()}`}function Ei(){try{const e=window.localStorage.getItem(jc());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function qc(e){try{window.localStorage.setItem(jc(),JSON.stringify(e))}catch{}}function Vc(e){return e?Ei()[e]===!0:!1}function qo(e){if(!e)return;const t=Ei();t[e]=!0,qc(t)}function Kc(e){if(!e)return;const t=Ei();t[e]&&(delete t[e],qc(t))}const Dg=he`:host{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:10px 14px;font:var( --wpd-notice-font,13px/1.5 var( --desktop-mode-font,system-ui ) );color:var( --wpd-notice-color,var( --desktop-mode-text,#1d2327 ) );background:var( --wpd-notice-bg,rgba( 0,0,0,0.04 ) );border-block-end:1px solid var( --wpd-notice-border,rgba( 0,0,0,0.08 ) );border-inline-start:4px solid var( --wpd-notice-accent,#646970 )}:host( [ hidden ] ){display:none}.wpd-notice__icon{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:var( --wpd-notice-accent,#646970 )}.wpd-notice__icon[ hidden ]{display:none}.wpd-notice__label{flex:1;min-width:0;word-wrap:break-word}::slotted( a ){color:var( --wpd-notice-link,var( --wp-admin-theme-color,#2271b1 ) )}::slotted( p:first-child ){margin-block-start:0}::slotted( p:last-child ){margin-block-end:0}.wpd-notice__close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;background:transparent;color:inherit;opacity:0.6;cursor:pointer;border-radius:4px;transition:opacity 0.12s ease,background-color 0.12s ease}.wpd-notice__close:hover{opacity:1;background:rgba( 0,0,0,0.06 )}.wpd-notice__close:focus-visible{opacity:1;outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:1px}.wpd-notice__close[ hidden ]{display:none}.wpd-notice__close svg{width:14px;height:14px}:host( [ tone='info' ] ){--wpd-notice-accent:var( --wpd-notice-info,#0969da );--wpd-notice-bg:var( --wpd-notice-info-bg,rgba( 9,105,218,0.08 ) );--wpd-notice-border:var( --wpd-notice-info-border,rgba( 9,105,218,0.16 ) )}:host( [ tone='success' ] ){--wpd-notice-accent:var( --wpd-notice-success,#1a7f37 );--wpd-notice-bg:var( --wpd-notice-success-bg,rgba( 26,127,55,0.08 ) );--wpd-notice-border:var( --wpd-notice-success-border,rgba( 26,127,55,0.16 ) )}:host( [ tone='warning' ] ){--wpd-notice-accent:var( --wpd-notice-warning,#9a6700 );--wpd-notice-bg:var( --wpd-notice-warning-bg,rgba( 154,103,0,0.08 ) );--wpd-notice-border:var( --wpd-notice-warning-border,rgba( 154,103,0,0.16 ) )}:host( [ tone='error' ] ),:host( [ tone='danger' ] ){--wpd-notice-accent:var( --wpd-notice-error,#cf222e );--wpd-notice-bg:var( --wpd-notice-error-bg,rgba( 207,34,46,0.08 ) );--wpd-notice-border:var( --wpd-notice-error-border,rgba( 207,34,46,0.16 ) )}:host( [ tone='neutral' ] ){--wpd-notice-accent:var( --wpd-notice-neutral,#57606a );--wpd-notice-bg:var( --wpd-notice-neutral-bg,rgba( 87,96,106,0.08 ) );--wpd-notice-border:var( --wpd-notice-neutral-border,rgba( 87,96,106,0.16 ) )}`,po=class po extends pe{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&Vc(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&qo(t),this.emit("wpd-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&Kc(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return z` |
| 56 |
<span |
| 57 |
class="wpd-notice__icon dashicons ${t??""}" |
| 58 |
?hidden=${!t} |
| 59 |
aria-hidden="true" |
| 60 |
></span> |
| 61 |
<span class="wpd-notice__label"><slot></slot></span> |
| 62 |
<button |
| 63 |
type="button" |
| 64 |
class="wpd-notice__close" |
| 65 |
?hidden=${!n} |
| 66 |
aria-label=${O("Dismiss notice")} |
| 67 |
@click=${o=>this._onDismiss(o)} |
| 68 |
> |
| 69 |
<svg viewBox="0 0 14 14" aria-hidden="true"> |
| 70 |
<path |
| 71 |
d="M3 3 L11 11 M11 3 L3 11" |
| 72 |
stroke="currentColor" |
| 73 |
stroke-width="1.6" |
| 74 |
stroke-linecap="round" |
| 75 |
fill="none" |
| 76 |
></path> |
| 77 |
</svg> |
| 78 |
</button> |
| 79 |
`}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};po.props=["tone","notDismissible","icon","noticeId"],po.styles=[Dg],po.help=void 0;let Si=po;me("wpd-notice",Si);const An=re("desktop-mode/window-notices",()=>({entries:new Map})),Og=/^[a-z0-9_/-]+$/;function Yc(e){return`desktop-mode-notice/${e.toLowerCase()}`}function Rg(e){const t=document.createElement("wpd-notice");return t.setAttribute("tone",e.tone??"info"),t.setAttribute("notice-id",e.id),e.dismissible===!1&&t.setAttribute("not-dismissible",""),e.icon&&t.setAttribute("icon",e.icon),t.innerHTML=e.message,t}function Xc(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!Og.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};An.state.entries.set(t,n);const o=Yc(t);return zc({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=An.state.entries.get(t);if(!i)return!1;if(typeof i.match!="function")return!0;try{return i.match(s)===!0}catch{return!1}},render:s=>{const i=An.state.entries.get(t);i&&s.appendChild(Rg(i))}}),()=>Ii(t)}function Ii(e){const t=String(e??"").trim().toLowerCase();t&&An.state.entries.delete(t)&&ki(Yc(t))}function Zc(){return Array.from(An.state.entries.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Mg(e){const t=String(e??"").trim().toLowerCase();t&&qo(t)}function Wg(e){const t=String(e??"").trim().toLowerCase();t&&Kc(t)}function Pg(e){if(!e)return;const t=new Set;if(typeof e.window=="string"&&e.window!==""&&t.add(e.window),Array.isArray(e.windows))for(const o of e.windows)typeof o=="string"&&o!==""&&t.add(o);const n=typeof e.urlContains=="string"&&e.urlContains!==""?e.urlContains.toLowerCase():null;if(!(t.size===0&&n===null))return o=>!(t.size>0&&!t.has(o.id)||n!==null&&!(typeof o.config.url=="string"?o.config.url.toLowerCase():"").includes(n))}function Jc(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),Xc({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:Pg(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of Zc())n.owner==="__server__"&&(t.has(n.id)||Ii(n.id))}const Qc=re("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),Ln=Qc.state.registry,$g=Qc.state.listeners,el=/^[a-z0-9_/-]+$/;function Ug(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):el.test(e.id.trim().toLowerCase())||t.push(`id (must match ${el} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Oe("WindowChrome",t,e);const n=e.id.trim().toLowerCase();Ln.set(n,{...e,id:n}),xi()}function tl(e){Ln.delete(e.toLowerCase())&&xi()}function Hg(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Ln.entries()))o.owner===e&&(Ln.delete(n),t++);return t>0&&xi(),t}function nl(){return Array.from(Ln.values()).sort((e,t)=>e.id.localeCompare(t.id))}function xi(){const e=Array.from($g);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-chrome registry listener threw:",n)}}function Bg(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ee(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let c=a.get(d.scriptHandle);c||(c=new Set,a.set(d.scriptHandle,c)),c.add(d.id)}return a},i=r=>{const a=new Set;for(const c of nl())c.owner===r&&a.add(c.id);const d=n.get(r);if(d)for(const c of d)a.add(c);return a};return async(r,a)=>{const d=new Set;for(const c of r)c.handle&&d.add(c.handle);for(const c of Array.from(e))if(!d.has(c)){for(const l of i(c))tl(l);Hg(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Ci=window.location.origin;let Fg=0;const Ut=new Map,Ht=new Map,Tn=new Map;function zg(e,t){return Tn.set(e,t),()=>{Tn.get(e)===t&&Tn.delete(e)}}function Gg(){return`desktop-mode-conn-${++Fg}`}function jg(e){const t=(d,c)=>{try{d.contentWindow?.postMessage(c,Ci)}catch(l){typeof console<"u"&&console.error("[desktop-mode] connection: postMessage failed",l)}},n=(d,c={})=>{const l=Gg(),u=Array.isArray(c.topics)?[...c.topics]:[],p=new Map,f=[];let h=!1,m=!1;const w=()=>{const b=Tn.get(d);return b||(e.getById(d)?.iframe??null)},g=()=>{if(w())return!1;const b=e.getById(d);return!!b&&b.config?.native===!0},x=[],T=()=>{const b=w();if(b)for(;f.length;){const L=f.shift();t(b,{type:"desktop-mode-bridge-publish",connectionId:l,topic:L.topic,payload:L.payload})}},y={id:l,target:d,isOpen:()=>h,subscribe(b,L){const D=L;if(g()){const S=Tm(d,b,(I,R)=>{A(v.CONNECTION_MESSAGE,{connectionId:l,topic:R.channel,direction:"in"});try{D(I,{topic:R.channel})}catch(F){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",F)}});return x.push(S),S}let C=p.get(b);return C||(C=new Set,p.set(b,C)),C.add(D),()=>{C?.delete(D)}},send(b,L){if(m)return;if(A(v.CONNECTION_MESSAGE,{connectionId:l,topic:b,direction:"out"}),g()){Dm(d,b,L);return}if(!h){f.push({topic:b,payload:L});return}const D=w();D&&t(D,{type:"desktop-mode-bridge-publish",connectionId:l,topic:b,payload:L})},disconnect(){y._destroy("disconnect")},_targetWindow:w,_handleIframeMessage(b){if(!b||typeof b!="object")return;const L=b;if(L.type==="desktop-mode-bridge-handshake-ack"){if(h)return;h=!0,A(v.CONNECTION_OPENED,{connectionId:l,targetWindowId:d,topics:u,connection:y});try{c.onOpen?.()}catch(D){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",D)}T();return}if(L.type==="desktop-mode-bridge-publish"){const D=b,C=typeof D.topic=="string"?D.topic:"";if(!C)return;A(v.CONNECTION_MESSAGE,{connectionId:l,topic:C,direction:"in"});const S=p.get(C);if(S)for(const R of Array.from(S))try{R(D.payload,{topic:C})}catch(F){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",F)}const I=p.get("*");if(I)for(const R of Array.from(I))try{R(D.payload,{topic:C})}catch(F){typeof console<"u"&&console.error("[desktop-mode] connection wildcard subscriber threw:",F)}return}L.type==="desktop-mode-bridge-disconnect"&&y._destroy("disconnect")},_destroy(b){if(m)return;m=!0;const L=h;h=!1,Ut.delete(l);const D=Ht.get(d);D&&(D.delete(l),D.size===0&&Ht.delete(d));for(const C of x.splice(0))try{C()}catch{}if(L){const C=w();C&&t(C,{type:"desktop-mode-bridge-disconnect",connectionId:l})}A(v.CONNECTION_CLOSED,{connectionId:l,reason:b});try{c.onClose?.(b)}catch(C){typeof console<"u"&&console.error("[desktop-mode] connection.onClose threw:",C)}}};Ut.set(l,y);let k=Ht.get(d);if(k||(k=new Set,Ht.set(d,k)),k.add(l),g())return Promise.resolve().then(()=>{if(!(m||h)){h=!0,A(v.CONNECTION_OPENED,{connectionId:l,targetWindowId:d,topics:u});try{c.onOpen?.()}catch(b){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",b)}}}),y;const N=w();return N&&t(N,{type:"desktop-mode-bridge-handshake",connectionId:l,targetWindowId:d,topics:u}),y},o=(d,c)=>{if(!d||typeof d!="object")return;const l=d;if(typeof l.type!="string"||!l.type.startsWith("desktop-mode-bridge-"))return;if(l.type==="desktop-mode-bridge-connection-request"&&typeof l.requestId=="string"&&typeof c=="string"&&c!==""){s(c,l.requestId,Array.isArray(l.topics)?l.topics:[]);return}if(typeof l.connectionId!="string")return;Ut.get(l.connectionId)?._handleIframeMessage(d)},s=(d,c,l)=>{const p=Tn.get(d)??e.getById(d)?.iframe??null;if(!p)return;const f=j(v.IFRAME_CONNECTION_REQUEST,!0,{windowId:d,requestId:c,topics:l.slice()});if(f===!1){try{p.contentWindow?.postMessage({type:"desktop-mode-bridge-connection-ack",requestId:c,accepted:!1,reason:"rejected"},Ci)}catch{}return}const h=f&&typeof f=="object"&&Array.isArray(f.topics)?f.topics:l,m=n(d,{topics:h});try{p.contentWindow?.postMessage({type:"desktop-mode-bridge-connection-ack",requestId:c,accepted:!0,connectionId:m.id},Ci)}catch{}};return{connect:n,getConnection:d=>Ut.get(d)??null,routeIncomingFromIframe:o,onIframeReady:d=>{const c=Ht.get(d);if(c)for(const l of Array.from(c)){const u=Ut.get(l);if(!u||u.isOpen())continue;const p=u._targetWindow();p&&t(p,{type:"desktop-mode-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:d=>{const c=Ht.get(d);if(c)for(const l of Array.from(c))Ut.get(l)?._destroy("window-closed")}}}const qg={};function Vg(...e){(typeof{url:Ns&&Ns.tagName.toUpperCase()==="SCRIPT"&&Ns.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&qg?"production":void 0)!=="production"&&console.log(...e)}const Kg="iframe:";function Ai(e){return Kg+e}function ol(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function Yg(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}class Xg{constructor(t){this.subscribedWindowId=null,this.manager=t.manager,this.adminUrl=t.adminUrl}install(){document.addEventListener("desktop-mode-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&this.onFocused(o.windowId)}),document.addEventListener("desktop-mode-window-closed",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&(Go(Ai(o.windowId)),this.subscribedWindowId===o.windowId&&(this.subscribedWindowId=null))}),document.addEventListener("desktop-mode-window-changed",n=>{const o=n.detail;!o||typeof o.windowId!="string"||o.reason==="state"&&o.state==="minimized"&&this.subscribedWindowId===o.windowId&&(this.subscribedWindowId=null)}),window.addEventListener("message",n=>{if(n.origin!==window.location.origin)return;const o=n.data;if(!o||typeof o.type!="string")return;if(o.type==="desktop-mode-bridge-ready"){const i=this.manager.findByIframeSource(n.source);i&&i.id===this.subscribedWindowId&&this.sendSubscribe(i.id);return}if(o.type!=="desktop-mode-commands-list"||!Array.isArray(o.commands))return;const s=this.manager.findByIframeSource(n.source);s&&s.id===this.subscribedWindowId&&this.applyList(s.id,o.commands)});const t=this.manager.getFocused();t&&this.onFocused(t.id)}onFocused(t){if(this.subscribedWindowId!==t){if(this.subscribedWindowId){const n=this.manager.getById(this.subscribedWindowId);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"desktop-mode-commands-unsubscribe"},window.location.origin)}catch{}Go(Ai(this.subscribedWindowId))}this.subscribedWindowId=t,this.sendSubscribe(t)}}sendSubscribe(t){const n=this.manager.getById(t);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"desktop-mode-commands-subscribe"},window.location.origin)}catch(o){Vg("[wpd-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=Ai(t);Go(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=Yg(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?va(s.iconSvg):"",a={slug:i,label:s.label,icon:ol(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,ol(s)):this.runProxy(t,s.name)};try{zo(a)}catch(d){console.error("[desktop-mode] iframe-bridge: dropping bad command",a,d)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),mt(t))return;const r=ne(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runProxy(t,n){return(o,s)=>{s.close();const i=this.manager.getById(t);if(!(!i||!i.iframe||!i.iframe.contentWindow)){try{i.iframe.contentWindow.postMessage({type:"desktop-mode-commands-invoke",name:n},window.location.origin)}catch{}this.manager.focus(i)}}}}const sl="global",Zg=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,Jg=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,Qg=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,ey=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,ty=/getSiteEditorPage\s*\(|site-editor\.php/,ny=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function oy(e){const t=window.__desktopModeMenuCommands;if(!Array.isArray(t))return null;for(const n of t)if(n&&typeof n=="object"&&n.name===e&&typeof n.url=="string"&&n.url!=="")return{label:typeof n.label=="string"?n.label:"",url:n.url};return null}class sy{constructor(t){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=t.manager,this.adminUrl=t.adminUrl}install(){this.tryMount(0)}tryMount(t){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){t<40&&window.setTimeout(()=>this.tryMount(t+1),150);return}this.mount()}mount(){const t=window.wp,n=t.element,o=t.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,d=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof d!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const c=document.createElement("div");c.setAttribute("aria-hidden","true"),c.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(c),this.host=c;const l={perLoader:{},statics:[],loadersList:[]},u=m=>{if(!Array.isArray(m)||m.length===0)return"";const w=new Array(m.length);for(let g=0;g<m.length;g++){const x=m[g];w[g]=x&&x.name?x.name:""}return w.join("|")},p=()=>{let m=[];for(const w of l.loadersList){const g=l.perLoader[w];Array.isArray(g)&&(m=m.concat(g))}Array.isArray(l.statics)&&(m=m.concat(l.statics)),this.callbackCache=Object.create(null);for(const w of m)w&&w.name&&typeof w.callback=="function"&&(this.callbackCache[w.name]=w.callback);this.publish(m)},f=m=>{const w=m.loader;let g=null;try{g=w.hook({search:""})}catch{}const x=g&&Array.isArray(g.commands)?g.commands:[],T=a(()=>u(x),[x]);return i(()=>{l.perLoader[w.name]=x,p()},[T]),i(()=>()=>{delete l.perLoader[w.name],p()},[]),null},h=()=>{const m=d(k=>{const N=k("core/commands");return!N||typeof N.getCommandLoaders!="function"?[]:[...N.getCommandLoaders(!1)||[],...N.getCommandLoaders(!0)||[]]},[]),w=d(k=>{const N=k("core/commands");return!N||typeof N.getCommands!="function"?[]:[...N.getCommands(!1)||[],...N.getCommands(!0)||[]]},[]),g=a(()=>Array.isArray(m)?m.map(k=>k&&k.name||""):[],[m]),x=g.join("|");i(()=>{l.loadersList=g,p()},[x]);const T=a(()=>u(Array.isArray(w)?w:[]),[w]);if(i(()=>{l.statics=Array.isArray(w)?w:[],p()},[T]),!Array.isArray(m)||m.length===0)return null;const y=[];for(const k of m)!k||typeof k.hook!="function"||y.push(s(f,{key:k.name,loader:k}));return s(n.Fragment||"div",null,y)};try{this.root=n.createRoot(c),this.root.render(s(h))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(t){const n=Object.create(null),o=[];for(const i of t)!i||!i.name||!i.label||i.disabled||n[i.name]||(n[i.name]=!0,o.push(this.classify(i)));let s="";for(const i of o)s+=`${i.name}|${i.kind}|${i.url||""} |
| 80 |
`;if(s!==this.lastFingerprint){this.lastFingerprint=s,Go(sl);for(const i of o){if(i.kind==="skip")continue;const r=`global-${i.name.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}`,a=this.iconFor(i),d={slug:r,label:i.label,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?va(i.iconSvg):void 0,owner:sl,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{zo(d)}catch(c){console.error("[desktop-mode] shell-harvester: dropping bad command",d,c)}}}}classify(t){const n={name:String(t.name),label:String(t.label),icon:typeof t.icon=="string"?t.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof t.callback=="function"?t.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=oy(n.name);if(s){try{n.url=new URL(s.url,this.adminUrl).toString(),n.kind="navigate",s.label!==""&&(n.windowTitle=s.label)}catch{n.kind="skip"}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}if(typeof t.callback=="function"){let i="";try{i=Function.prototype.toString.call(t.callback)}catch{i=""}const r=i.match(Zg)||i.match(Jg)||i.match(Qg);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(ey.test(i)){const d=ty.test(i)?n.name.match(ny):null;if(d){const c=d[1],l=d[2],u=`/${c}/${l}`;try{const p=new URL("site-editor.php",this.adminUrl);p.searchParams.set("p",u),p.searchParams.set("canvas","edit"),n.url=p.toString(),n.kind="navigate"}catch{n.kind="skip"}}else n.kind="skip"}}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}renderIcon(t){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(t);if(typeof o=="string"&&o.toLowerCase().startsWith("<svg"))return o}catch{}return""}iconFor(t){return t.icon&&t.icon.startsWith("dashicons-")?t.icon:t.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}runNavigate(t,n,o){return(s,i)=>{if(i.close(),mt(t))return;const r=ne(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runInvoke(t,n,o){return(s,i)=>{i.close();const r=this.callbackCache[t];if(typeof r!="function")return;const a=this.runWithNavCapture(r);if(a){const d=ne(a,this.adminUrl);this.manager.open({id:d,baseId:d,url:a,title:n,icon:o})}}}runWithNavCapture(t){let n=null;const o=d=>{n===null&&typeof d=="string"&&d!==""&&(n=d)},s=window.location,i=new Proxy(s,{get(d,c){const l=d[c];return c==="assign"||c==="replace"?u=>o(u):typeof l=="function"?l.bind(d):l},set(d,c,l){return c==="href"&&o(l),!0}}),r=[],a=d=>{try{Object.defineProperty(d,"location",{configurable:!0,get:()=>i,set:c=>o(c)}),r.push({obj:d,key:"location"})}catch{}};a(document),a(window);try{t({close:()=>{}})}catch{}finally{for(const d of r)try{delete d.obj[d.key]}catch{}}return n}}const Bt=[];function Li(e){Oe("Widget",un(e,rl),e);const t=Bt.findIndex(n=>n.id===e.id);t>=0?Bt[t]=e:Bt.push(e)}function iy(e){const t=Bt.findIndex(n=>n.id===e);t>=0&&Bt.splice(t,1)}function il(){const e=Bt.slice(),t=j(v.WIDGETS,e);return Array.isArray(t)?t.filter(ry):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.widgets` filter returned a non-array; falling back to seed list."),e)}function Nn(e){return il().find(t=>t.id===e)}const rl=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"description",message:"not a string",valid:e=>typeof e.description=="string"},{field:"icon",message:"missing or not a non-empty string",valid:e=>typeof e.icon=="string"&&e.icon!==""},{field:"mount",message:"not a function",valid:e=>typeof e.mount=="function"}];function ry(e){return un(e,rl).length===0}let Ge=null;function ay(e){if(Ge)return;const t=document.createElement("div");t.className="desktop-mode-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",O("Add widget"));const n=document.createElement("div");n.className="desktop-mode-widget-picker__title",n.textContent=O("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="desktop-mode-widget-picker__list",t.appendChild(o),dl(o,e),document.body.appendChild(t),dy(t,e.anchor);const s=a=>{const d=a.target;d&&(t.contains(d)||e.anchor.contains(d)||al())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&al()};document.addEventListener("keydown",i),Ge={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function Dn(){if(!Ge)return;const e=Ge.panel.querySelector(".desktop-mode-widget-picker__list");e&&dl(e,Ge.options)}function al(){Ge&&(document.removeEventListener("pointerdown",Ge.onOutsidePointerDown,!0),document.removeEventListener("keydown",Ge.onKeyDown),Ge.panel.remove(),Ge=null)}function dl(e,t){e.innerHTML="";const n=new Set(t.enabledIds()),o=t.registry();if(o.length===0){const s=document.createElement("div");s.className="desktop-mode-widget-picker__empty",s.textContent=O("No widgets available. Activate a plugin that registers one, or see the docs for the registerWidget API."),e.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="desktop-mode-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("desktop-mode-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=oe(O("%s (already added)"),s.label):a=oe(O("Add %s"),s.label),i.setAttribute("aria-label",a);const d=document.createElement("span");d.className=`desktop-mode-widget-picker__entry-icon dashicons ${s.icon}`,d.setAttribute("aria-hidden","true"),i.appendChild(d);const c=document.createElement("span");c.className="desktop-mode-widget-picker__entry-text";const l=document.createElement("span");if(l.className="desktop-mode-widget-picker__entry-label",l.textContent=s.label,c.appendChild(l),s.description){const u=document.createElement("span");u.className="desktop-mode-widget-picker__entry-description",u.textContent=s.description,c.appendChild(u)}if(i.appendChild(c),r){const u=document.createElement("span");u.className="desktop-mode-widget-picker__entry-status",u.textContent=O("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function dy(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.style.visibility="hidden";const o=e.getBoundingClientRect(),s=o.width||320,i=o.height||200,r=6;let a=n.right-s,d=n.top-i-r;a<8&&(a=8),d<8&&(d=n.bottom+r),e.style.left=`${Math.round(a)}px`,e.style.top=`${Math.round(d)}px`,e.style.visibility=""}const Vo="desktop-mode-widgets__card--floating",cy="desktop-mode-widgets__card--movable",ly="desktop-mode-widgets__card--resizable",cl="desktop-mode-widgets__card--dragging",ll="desktop-mode-widgets__card--resizing",uy=160,ul=80,py=280,fy=180,Ko=20,pl=5,my=pl*pl,hy='input, textarea, select, button, a, [contenteditable="true"]';function wy(e,t,n){const o=document.createElement("div");o.className="desktop-mode-widgets__card",o.dataset.widgetId=e.id;const s=e.movable===!0,i=e.resizable===!0;s&&o.classList.add(cy),i&&o.classList.add(ly),s?o.appendChild(gy(e,n.onRemove,n.onRedock)):o.appendChild(by(e,n.onRemove));const r=document.createElement("div");r.className="desktop-mode-widgets__card-body",o.appendChild(r),t.geometry?(Ti(o,Iy(t.geometry,t.floatingParent)),o.classList.add(Vo)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${Sy(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(Vo),d=[];if(i)for(const l of _y()){const u=document.createElement("div");u.className=`desktop-mode-widgets__resize desktop-mode-widgets__resize--${l}`,u.setAttribute("aria-hidden","true"),u.dataset.dir=l,o.appendChild(u),d.push(ky(o,u,l,e,t,n,a))}let c=null;if(s){const l=o.querySelector(".desktop-mode-widgets__chrome");l&&(c=vy(o,l,e,t,n))}return{card:o,body:r,dispose:()=>{for(const l of d)try{l()}catch{}if(c)try{c()}catch{}o.remove()}}}function gy(e,t,n){const o=document.createElement("header");o.className="desktop-mode-widgets__chrome";const s=document.createElement("span");s.className="desktop-mode-widgets__grip",s.setAttribute("aria-hidden","true"),o.appendChild(s);const i=document.createElement("span");i.className="desktop-mode-widgets__title",i.textContent=e.label,o.appendChild(i),o.appendChild(yy(e,n));const r=fl(e,t);return o.appendChild(r),o}function yy(e,t){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-redock",n.setAttribute("aria-label",oe(O("Dock %s back to widget column"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2 6h6M5.5 3.5L8 6l-2.5 2.5M10 2.5v7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n.dataset.noDrag="true",n}function by(e,t){const n=fl(e,t);return n.classList.add("desktop-mode-widgets__card-close--corner"),n}function fl(e,t){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-close",n.setAttribute("aria-label",oe(O("Remove %s"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2.5 2.5l7 7M9.5 2.5l-7 7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function vy(e,t,n,o,s){let i=null,r=0,a=0,d=0,c=0,l=!1;const u=m=>{if(m.button!==0)return;const w=m.target;w&&w.closest(hy)||(m.preventDefault(),i=m.pointerId,r=m.clientX,a=m.clientY,l=!1,d=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0,t.setPointerCapture(i))},p=()=>{if(!e.classList.contains(Vo)){const m=o.floatingParent.getBoundingClientRect(),w=e.getBoundingClientRect(),g={x:w.left-m.left,y:w.top-m.top,width:w.width||n.defaultWidth||py,height:w.height||n.defaultHeight||fy};Ti(e,g),e.classList.add(Vo),s.onLiberate(g),d=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(cl)},f=m=>{if(i===null||m.pointerId!==i)return;const w=m.clientX-r,g=m.clientY-a;if(!l){if(w*w+g*g<my)return;l=!0,p()}const x=hl(d+w,c+g,e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${x.x}px`,e.style.top=`${x.y}px`},h=m=>{if(!(i===null||m.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,l&&(l=!1,e.classList.remove(cl),s.onGeometryChanged(ml(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",f),t.addEventListener("pointerup",h),t.addEventListener("pointercancel",h),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",f),t.removeEventListener("pointerup",h),t.removeEventListener("pointercancel",h)}}function ky(e,t,n,o,s,i,r){let a=null,d=0,c=0,l=0,u=0,p=0,f=0;const h=g=>{if(g.button!==0||!r()&&!Ey(n))return;g.preventDefault(),g.stopPropagation(),a=g.pointerId,d=g.clientX,c=g.clientY;const x=e.getBoundingClientRect(),T=s.floatingParent.getBoundingClientRect();l=x.left-T.left,u=x.top-T.top,p=x.width,f=x.height,t.setPointerCapture(a),e.classList.add(ll)},m=g=>{if(a===null||g.pointerId!==a)return;const x=g.clientX-d,T=g.clientY-c,y=xy(n,x,T,l,u,p,f,o,s.floatingParent,r());r()&&(e.style.left=`${y.x}px`,e.style.top=`${y.y}px`,e.style.width=`${y.width}px`),e.style.height=`${y.height}px`},w=g=>{if(!(a===null||g.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(ll),r()?i.onGeometryChanged(ml(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",h),t.addEventListener("pointermove",m),t.addEventListener("pointerup",w),t.addEventListener("pointercancel",w),()=>{t.removeEventListener("pointerdown",h),t.removeEventListener("pointermove",m),t.removeEventListener("pointerup",w),t.removeEventListener("pointercancel",w)}}function _y(){return["n","e","s","w","ne","nw","se","sw"]}function Ey(e){return e==="s"}function Ti(e,t){e.style.left=`${t.x}px`,e.style.top=`${t.y}px`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`}function ml(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function Sy(e,t){return On(e,t.minHeight??ul,t.maxHeight??1/0)}function Iy(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=hl(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function hl(e,t,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,a=Math.max(0,i-n-Ko),d=Math.max(0,r-o-Ko);return{x:Math.min(Math.max(Ko,e),a),y:Math.min(Math.max(Ko,t),d)}}function xy(e,t,n,o,s,i,r,a,d,c){const l=a.minWidth??uy,u=a.minHeight??ul,p=a.maxWidth??1/0,f=a.maxHeight??1/0,h=d.clientWidth||d.getBoundingClientRect().width,m=d.clientHeight||d.getBoundingClientRect().height;let w=o,g=s,x=i,T=r;if((e==="e"||e==="ne"||e==="se")&&(x=On(i+t,l,Math.min(p,h-o))),e==="w"||e==="nw"||e==="sw"){const y=On(i-t,l,Math.min(p,o+i));w=o+(i-y),x=y}if((e==="s"||e==="se"||e==="sw")&&(T=On(r+n,u,Math.min(f,m-s))),e==="n"||e==="ne"||e==="nw"){const y=On(r-n,u,Math.min(f,s+r));g=s+(r-y),T=y}return c||(x=i,w=o),{x:w,y:g,width:x,height:T}}function On(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const wl="desktop-mode-widgets",gl="desktop-mode-widgets-geometry",yl="desktop-mode-widgets-docked-heights";function bl(){try{return window.localStorage.getItem(wl)}catch{return null}}function Cy(){const e=bl();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Ni(e){try{window.localStorage.setItem(wl,JSON.stringify(e))}catch{}}function Ay(){try{const e=window.localStorage.getItem(gl);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t)){const i=Ty(s);i&&(n[o]=i)}return n}catch{return{}}}function Di(e){try{window.localStorage.setItem(gl,JSON.stringify(e))}catch{}}function Ly(){try{const e=window.localStorage.getItem(yl);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t))typeof s=="number"&&Number.isFinite(s)&&s>0&&(n[o]=s);return n}catch{return{}}}function vl(e){try{window.localStorage.setItem(yl,JSON.stringify(e))}catch{}}function Ty(e){if(!e||typeof e!="object")return null;const{x:t,y:n,width:o,height:s}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)||typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||s<=0?null:{x:t,y:n,width:o,height:s}}function Ny(e){const t=`desktop-mode.widget.${e}.`,n=o=>{try{return localStorage.getItem(t+o)}catch{return null}};return{get(o){const s=n(o);if(s===null)return null;try{return JSON.parse(s)}catch{return null}},set(o,s){try{localStorage.setItem(t+o,JSON.stringify(s))}catch{}},remove(o){try{localStorage.removeItem(t+o)}catch{}},clear(){try{for(let o=localStorage.length-1;o>=0;o--){const s=localStorage.key(o);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}}}}const Dy=["clock"];class Oy{constructor(t,n,o){this.mounted=new Map,this.generation=0,this.root=t,this.pluginUrl=n,this.enabledIds=Cy(),this.geometry=Ay(),this.dockedHeights=Ly(),this.floatingHost=o??t.parentElement??t,this.listEl=document.createElement("div"),this.listEl.className="desktop-mode-widgets__list",this.root.appendChild(this.listEl),this.addTile=this.buildAddTile(),this.root.appendChild(this.addTile),this.paintEmptyState()}hydrate(){bl()===null&&(this.enabledIds=Dy.filter(t=>!!Nn(t)),Ni(this.enabledIds));for(const t of this.enabledIds)this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){this.enabledIds.includes(t)||Nn(t)&&(this.enabledIds.push(t),Ni(this.enabledIds),this.mountById(t),this.paintEmptyState(),A(v.WIDGET_ADDED,{id:t}),Dn())}remove(t){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(Ni(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],Di(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],vl(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),A(v.WIDGET_REMOVED,{id:t}),Dn())}getEnabledIds(){return[...this.enabledIds]}mountIfEnabled(t){Nn(t)&&this.enabledIds.includes(t)&&(this.mounted.has(t)||(this.mountById(t),this.paintEmptyState()))}unmount(t){this.mounted.has(t)&&(this.unmountById(t),this.paintEmptyState())}ensureMounted(t){return Nn(t)?(this.enabledIds.includes(t)||this.add(t),!0):!1}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t)}mountById(t){const n=Nn(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=wy(n,{floatingParent:this.floatingHost,geometry:s,dockedHeight:this.dockedHeights[t]},{onRemove:()=>this.remove(t),onGeometryChanged:u=>this.persistGeometry(t,u),onDockedHeightChanged:u=>this.persistDockedHeight(t,u),onLiberate:u=>this.liberate(t,u),onRedock:()=>this.redock(t)}),r=!!s,a={id:t,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(t,a),this.placeCard(i.card,r);const d={id:t,pluginUrl:this.pluginUrl,storage:Ny(t)};A(v.WIDGET_MOUNTING,{id:t,container:i.body,ctx:d});const c=u=>{const p=this.mounted.get(t);if(!p||p.generation!==o){try{u()}catch{}return}p.teardown=u,A(v.WIDGET_MOUNTED,{id:t,container:i.body,ctx:d})};let l;try{l=n.mount(i.body,d)}catch(u){this.handleMountFailure(t,u);return}if(Ry(l)){l.then(c,u=>{this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,u)});return}c(l)}unmountById(t){const n=this.mounted.get(t);if(n){A(v.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){A(v.SHELL_ERROR,{scope:"widget-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[desktop-mode] Widget "${t}" teardown threw:`,o)}this.generation++,n.frame.dispose(),this.mounted.delete(t)}}handleMountFailure(t,n){const o=this.mounted.get(t);o&&(o.frame.dispose(),this.mounted.delete(t)),A(v.WIDGET_MOUNT_FAILED,{id:t,error:n}),A(v.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[desktop-mode] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="desktop-mode-widgets__add",t.setAttribute("aria-label",O("Add widget"));const n=document.createElement("span");n.className="desktop-mode-widgets__add-plus",n.setAttribute("aria-hidden","true"),n.textContent="+";const o=document.createElement("span");return o.className="desktop-mode-widgets__add-label",o.textContent=O("Add widget"),t.appendChild(n),t.appendChild(o),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),ay({anchor:t,registry:()=>il(),enabledIds:()=>[...this.enabledIds],onAdd:i=>this.add(i)})}),t}placeCard(t,n){n?this.floatingHost.appendChild(t):this.listEl.appendChild(t)}liberate(t,n){const o=this.mounted.get(t);!o||o.floating||(o.floating=!0,this.floatingHost.appendChild(o.frame.card),Ti(o.frame.card,n),this.persistGeometry(t,n),this.paintEmptyState())}redock(t){const n=this.mounted.get(t);if(!n||!n.floating)return;n.floating=!1,this.geometry[t]&&(delete this.geometry[t],Di(this.geometry));const o=n.frame.card;o.classList.remove("desktop-mode-widgets__card--floating"),o.style.left="",o.style.top="",o.style.width="";const s=this.dockedHeights[t];o.style.height=s!==void 0?`${s}px`:"",this.listEl.appendChild(o),this.paintEmptyState()}persistGeometry(t,n){this.geometry[t]=n,Di(this.geometry)}persistDockedHeight(t,n){!Number.isFinite(n)||n<=0||(this.dockedHeights[t]=n,vl(this.dockedHeights))}paintEmptyState(){let t=0;for(const n of this.mounted.values())n.floating||t++;this.root.classList.toggle("desktop-mode-widgets--has-widgets",t>0)}}function Ry(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const My=280,Wy=220,Py=520,$y=400;function Uy(e,t,n){return o=>{const s=document.createElement("iframe");s.style.width="100%",s.style.height="100%",s.style.border="0",s.setAttribute("src",e.url),typeof e.sandbox=="string"&&e.sandbox!==""&&s.setAttribute("sandbox",e.sandbox),o.style.padding="0",o.appendChild(s);const i=zg(n,s);t.push(i);let r;try{r=new URL(e.url,window.location.origin).origin}catch{r=window.location.origin}let a=null;const d=new Promise(u=>{a=u}),c=()=>{if(e.bridge)try{const u=s.contentDocument;if(u&&!u.querySelector("script[data-desktop-mode-iframe-bridge]")){const p=window.desktopModeConfig?.iframeBridgeUrl;if(p){const f=u.createElement("script");f.src=p,f.setAttribute("data-desktop-mode-iframe-bridge","1"),u.head?.appendChild(f)}}}catch{}Rm(n),a?.()};s.addEventListener("load",c);const l=u=>{if(!s.contentWindow||u.source!==s.contentWindow||u.origin!==r&&u.origin!==window.location.origin)return;const p=u.data;p&&typeof p=="object"&&typeof p.type=="string"&&p.type.startsWith("desktop-mode-bridge-")&&window.__desktopModeConnectionBridge?.routeIncomingFromIframe(p,n),p&&typeof p=="object"&&p.type==="desktop-mode-window-publish"&&typeof p.channel=="string"&&p.channel!==""&&Nm(n,p.channel,p.payload);try{e.onMessage?.(u.data)}catch(f){typeof console<"u"&&console.error("[desktop-mode] iframeContent.onMessage threw:",f)}};return window.addEventListener("message",l),t.push(()=>{window.removeEventListener("message",l),s.removeEventListener("load",c)}),d}}function Hy(e){return async t=>{const n=t.render;let o=n;const s=[];t.iframeContent&&(n&&typeof console<"u"&&console.warn("[desktop-mode] registerWindow: both `render` and `iframeContent` provided — ignoring `render` and using the iframe shorthand. Drop one."),o=Uy(t.iframeContent,s,t.id));const i=t.onClose,r=s.length?()=>{for(const d of s)try{d()}catch{}i?.()}:i;return await e.open({id:t.id,baseId:t.baseId||t.id,native:!0,url:t.url||`#${t.id}`,title:t.title,icon:t.icon,x:t.x??0,y:t.y??0,width:t.width??Py,height:t.height??$y,minWidth:t.minWidth??My,minHeight:t.minHeight??Wy,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let By=0;function Fy(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++By}`,s=n.persistent===!0,i=[["opened",v.WINDOW_OPENED],["reopened",v.WINDOW_REOPENED],["focused",v.WINDOW_FOCUSED],["blurred",v.WINDOW_BLURRED],["closing",v.WINDOW_CLOSING],["closed",v.WINDOW_CLOSED],["minimized",v.WINDOW_MINIMIZED],["restored",v.WINDOW_RESTORED],["maximized",v.WINDOW_MAXIMIZED],["unmaximized",v.WINDOW_UNMAXIMIZED],["fullscreenEntered",v.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",v.WINDOW_FULLSCREEN_EXITED],["resized",v.WINDOW_RESIZED],["bodyResized",v.WINDOW_BODY_RESIZED],["boundsChanged",v.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const d=()=>{if(!a){a=!0;for(const c of r)ha(c,o)}};for(const[c,l]of i){const u=t[c];u&&(r.push(l),G(l,o,p=>{const f=p;if(f.windowId!==e)return;const{windowId:h,...m}=f;u(m),c==="closed"&&!s&&d()}))}return d}function kl(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.desktopModeNativeWindows||{}}}function zy(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,a=new Set,d=new Map,c=y=>{const k=Fa(y.id);return k?{width:Math.max(k.width,y.minWidth),height:Math.max(k.height,y.minHeight)}:{width:y.width,height:y.height}},l=y=>{if(i.has(y.templateId))return;if(document.getElementById(y.templateId)){i.add(y.templateId);return}if(!y.templateHtml)return;const k=document.createElement("template");k.id=y.templateId,k.innerHTML=y.templateHtml,document.body.appendChild(k),i.add(y.templateId)},u=y=>{const k=y.styleUrl;if(!k||a.has(k))return;const N=k.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${N}"]`)){const L=document.createElement("link");L.rel="stylesheet",L.href=k,y.styleHandle&&(L.dataset.desktopModeStyleHandle=y.styleHandle),document.head.appendChild(L)}if(Array.isArray(y.styleInline))for(const L of y.styleInline){if(typeof L!="string"||L==="")continue;const D=document.createElement("style");y.styleHandle&&(D.dataset.desktopModeStyleHandle=y.styleHandle),D.textContent=L,document.head.appendChild(D)}a.add(k)},p=async y=>{if(!(!y.scriptUrl||r.has(y.scriptUrl))){try{await Ee(y.scriptUrl,{translations:y.scriptTranslations,l10n:y.scriptL10n,before:y.scriptBefore,after:y.scriptAfter})}catch(k){A(v.SHELL_ERROR,{scope:"native-window-script-load",id:y.id,error:k})}r.add(y.scriptUrl)}},f=y=>{const k=kl()[y.id],N=(L,D)=>(L.appendChild(Oi(y.templateId)),k?.(L,D)),b=c(y);t.open({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:b.width,height:b.height,minWidth:y.minWidth,minHeight:y.minHeight,render:N,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle})},h=y=>{const k=kl()[y.id],N=(L,D)=>(L.appendChild(Oi(y.templateId)),k?.(L,D)),b=c(y);t.openNew({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:b.width,height:b.height,minWidth:y.minWidth,minHeight:y.minHeight,initialState:"normal",render:N,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle})},m=async y=>{if(!s.has(y.id)){if(y.placement==="none"){l(y),u(y),await p(y),s.add(y.id);return}l(y),u(y),await p(y),n({id:y.id,title:y.title,icon:y.icon,isOpen:()=>!!t.getById(y.id),onOpen:()=>f(y)}),A(v.DOCK_ITEM_APPENDED,{id:y.id}),s.add(y.id)}},w=y=>{s.has(y)&&(o(y),s.delete(y),d.delete(y))},g=async y=>{const k=new Set;for(const N of y)k.add(N.id),d.set(N.id,N);for(const N of Array.from(s))k.has(N)||w(N);for(const N of y)s.has(N.id)||await m(N)},x=(y,k={})=>{const N=d.get(y);return N?(ye.publish("desktop-mode/open-requested",{windowId:y,source:k.source??"api"}),f(N),!0):!1},T=(y,k={})=>{const N=d.get(y);return N?(ye.publish("desktop-mode/open-requested",{windowId:y,source:k.source??"api"}),h(N),!0):!1};return G(v.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",y=>{const k=y,N=k?.windowId,b=k?.width,L=k?.height;if(!N||typeof b!="number"||typeof L!="number")return;const D=t.getById(N);if(!D||D.state!=="normal")return;const C=D.config.baseId||D.id;za(C,{width:b,height:L}),D.element&&Ga(C,{x:D.element.offsetLeft,y:D.element.offsetTop})}),G(v.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",y=>{const k=y?.windowId;if(!k)return;const N=t.getById(k);if(!N||N.state!=="normal"||!N.element)return;const b=N.config.baseId||N.id;za(b,{width:N.element.offsetWidth,height:N.element.offsetHeight}),Ga(b,{x:N.element.offsetLeft,y:N.element.offsetTop})}),G(v.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",y=>{const k=y?.windowId;if(!k)return;const N=t.getById(k);if(!N)return;const b=N.config.baseId||N.id,L=d.get(b),D=L?{width:L.width,height:L.height}:{width:N.config.width,height:N.config.height};ja(b,"maximized",D)}),G(v.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",y=>{const k=y?.windowId;if(!k)return;const N=t.getById(k);if(!N)return;const b=N.config.baseId||N.id;ja(b,null)}),{sync:g,openById:x,openNewById:T}}function Oi(e){let t=null;if(typeof e=="string"){const n=document.getElementById(e);n instanceof HTMLTemplateElement&&(t=n)}else t=e;if(!t)throw new Error(`[desktop-mode] cloneTemplate: no <template> found for ${typeof e=="string"?`#${e}`:"<reference>"}`);return t.content.cloneNode(!0)}function _l(e){const t=window.wp?.desktop,n=window.desktopModeConfig,o=t?.config?.adminUrl??n?.adminUrl;if(!o)return null;const s=t?.getMenuItems?.()??n?.dockItems??[],i=ne(e,o);return s.find(r=>ne(r.url,o)===i||(r.submenu??[]).some(a=>ne(a.url,o)===i))??null}function Ri(e,t){const n=t.className??"",o=t.title??"";if(typeof e=="string"&&e.startsWith("dashicons-")){const a=document.createElement("span");return a.className=`dashicons ${e} ${n}`.trim(),a.setAttribute("aria-hidden","true"),a}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const a=e.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(a)){const d=document.createElement("span");return d.className=n,d.setAttribute("aria-hidden","true"),d.style.backgroundImage=`url("${e}")`,d.style.backgroundRepeat="no-repeat",d.style.backgroundPosition="center",d.style.backgroundSize="contain",d.style.display="inline-block",d}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const a=e.indexOf(","),d=a>=0?e.slice(a+1):"";if(/^[A-Za-z0-9+/=]+$/.test(d))return El(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return El(e,n);const s=document.createElement("span");s.className=`${n} desktop-mode-icon-letter`.trim(),s.setAttribute("aria-hidden","true");const i=Gy(o);s.textContent=i;const r=Qs(o);return s.style.backgroundColor=`hsl( ${r}, 60%, 45% )`,s.style.color="#fff",s.style.display="inline-flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.fontWeight="600",s.style.borderRadius="4px",s}function El(e,t){const n=document.createElement("img");return n.className=t,n.src=e,n.alt="",n.setAttribute("aria-hidden","true"),n.draggable=!1,n}function Gy(e){const t=(e??"").trim();if(t==="")return"?";const n=t.split(/\s+/);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();const o=n[0];return o.length>=2?o.slice(0,2).toUpperCase():o.toUpperCase()}const Sl="desktop-mode-icon__badge",Rn=new Map;function jy(e){return Math.max(0,Math.floor(Number(e)||0))}function Il(e,t){if(!e)return;const n=Xy(e);if(!n)return;const o=jy(t),s=Rn.get(e)??0;o!==s&&(o===0?Rn.delete(e):Rn.set(e,o),Al(n,o),ye.publish("desktop-mode/badge-changed",{itemId:e,count:o,rail:"icon"}),A(v.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function qy(e){Il(e,0)}function Vy(e){return Rn.get(e)??0}const Ky={setBadge:Il,clearBadge:qy,getBadge:Vy};function Yy(e){return!e||e.length===0?"":e.map(t=>`${t.id}|${t.title}|${t.icon}|${t.window??""}|${t.url??""}|${t.position??0}|${t.pinned?1:0}`).join(";")}let xl="";function Cl(e,t,n){const o=Yy(t);if(o===xl&&e.querySelector(":scope > .desktop-mode-icons"))return;xl=o;const s=e.querySelector(":scope > .desktop-mode-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="desktop-mode-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",O("Desktop icons"));const r=[...t].sort((d,c)=>{const l=d.pinned?0:1,u=c.pinned?0:1;return l-u}),a=new Map;for(const d of r){const c=Jy(d,n),l=Rn.get(d.id)??0;l>0&&Al(c,l),i.appendChild(c),a.set(d.id,c)}e.appendChild(i),A(v.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(d=>d.id),container:i,tiles:a})}function Xy(e){if(!e)return null;const t=document.querySelector(".desktop-mode-icons");return t?t.querySelector(`[data-icon-id="${Zy(e)}"]`):null}function Al(e,t){const n=e.querySelector(`:scope > .${Sl}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=oe(rn("%d notification","%d notifications",t),t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",s);return}const i=document.createElement("span");i.className=Sl,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function Zy(e){const t=window.CSS;return t?.escape?t.escape(e):e}function Jy(e,t){const n=document.createElement("button");n.type="button",n.className=e.pinned?"desktop-mode-icon desktop-mode-icon--pinned":"desktop-mode-icon",n.dataset.iconId=e.id,e.pinned&&(n.dataset.pinned="1"),n.setAttribute("role","listitem"),n.setAttribute("aria-label",e.title);const o=Ri(e.icon,{title:e.title,className:"desktop-mode-icon__image"});n.appendChild(o);const s=document.createElement("span");return s.className="desktop-mode-icon__label",s.textContent=e.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),A(v.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),Qy(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),Kd({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function Qy(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(Ro(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=_l(n.toString());t.manager.open({id:o,baseId:o,url:n.toString(),parentUrl:s?.url??n.toString(),title:e.title,icon:e.icon,submenu:s?.submenu,multi:!!s?.multi})}catch{}}}const Ll="desktop-mode-side-dock";function eb(e,t){return{id:`dock-core:${e.id}`,title:e.title,icon:e.icon,window:"",url:e.url,position:1e3+t}}function tb(e,t,n,o){let s=t,i=n,r=o??[],a=null,d=null,c=null,l=null,u=null;const p=new Map,f=C=>C==="core"&&d?d:a,h=()=>{const C=document.getElementById(Ll);if(C)return C;const S=document.createElement("nav");return S.id=Ll,S.className="desktop-mode-dock",S.setAttribute("role","toolbar"),S.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(S,e.shellBody.firstChild),S},m=()=>{u&&u.parentNode&&u.parentNode.removeChild(u),u=null},w=()=>e.getSettings?.()??{itemVisibility:{},dockOrder:[]},g=()=>{const C=new Set;for(const S of p.values())C.add(S.item.id);return ow(i,r,w(),C)},x=()=>{const C=g(),S=[],I=[];for(const R of C)R.isCore?S.push(R):I.push(R);return{core:S,plugin:I}},T=()=>{const C=w();if(s!=="spatial"){e.renderIcons(sw(r,i,C.itemVisibility));return}const{core:S}=x(),I=S.map(eb),R=r.filter(X=>{const E=C.itemVisibility[X.id];return E?E==="desktop"||E==="both":!!X.pinned}),F=[];let K=0;for(const X of i){const E=C.itemVisibility[X.id];(E==="desktop"||E==="both")&&F.push({id:`dock:${X.id}`,title:X.title,icon:X.icon,window:"",url:X.url||"",position:2e3+K++})}e.renderIcons([...I,...R,...F])},y=()=>{if(a){try{a.destroy()}catch(C){A(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:C})}a=null,c=null}if(d){try{d.destroy()}catch(C){A(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:C})}d=null,l=null}},k=C=>{const S=Js();if(!S)return A(v.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return S.mount(C)}catch(I){if(A(v.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:S.id,error:I}),S===oi)return null;try{return oi.mount(C)}catch{return null}}},N=(C,S,I)=>({container:C,items:S,fullMenu:i.slice(),fullSystemTiles:Array.from(p.values()).map(R=>R.item),orientation:I,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:R=>{const F=ne(R.url,e.adminUrl);e.windowManager.open({id:F,baseId:F,url:R.url,parentUrl:R.url,title:R.title,icon:R.icon.startsWith("dashicons-")?R.icon:"dashicons-admin-generic",submenu:R.submenu,multi:!!R.multi})},openSubmenuPick:(R,F)=>{e.windowManager.open({id:ne(F.url,e.adminUrl),baseId:ne(R.url,e.adminUrl),url:F.url,parentUrl:R.url,title:R.title,icon:R.icon.startsWith("dashicons-")?R.icon:"dashicons-admin-generic",submenu:R.submenu,multi:!!R.multi})},openSystemItem:R=>R.onOpen()}),b=()=>{y();const{core:C,plugin:S}=x();s==="classic"?(u=h(),d=k(N(u,C,"left")),l=$o(d),a=k(N(e.bottomDockEl,S,"bottom")),c=$o(a)):s==="unified"?(m(),a=k(N(e.bottomDockEl,g(),"bottom")),c=$o(a)):(m(),a=k(N(e.bottomDockEl,S,"bottom")),c=$o(a));for(const I of p.values())f(I.affinity)?.appendSystemItem(I.item)},L={getLayout:()=>s,getPrimary:()=>c,getSide:()=>l,setLayout:C=>{C!==s&&(s=C,e.shellRoot.setAttribute("data-desktop-mode-layout",C),b(),T(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:C,primary:c,side:l}})))},applyDockItems:C=>{i=C;const{core:S,plugin:I}=x();s==="classic"?(d?.replaceItems(S),a?.replaceItems(I)):s==="unified"?a?.replaceItems(g()):a?.replaceItems(I),T()},applyDesktopIcons:C=>{r=C??[],T()},appendSystemTile:(C,S="plugin")=>{p.set(C.id,{item:C,affinity:S}),f(S)?.appendSystemItem(C)},removeSystemTile:C=>{const S=p.get(C);S&&(p.delete(C),f(S.affinity)?.removeSystemItem(C))},listSystemTiles:()=>Array.from(p.values()).map(C=>({id:C.item.id,title:C.item.title,icon:C.item.icon,affinity:C.affinity})),getSystemTile:C=>p.get(C)?.item??null,getMenuItems:()=>i.slice(),refresh:()=>{const{core:C,plugin:S}=x();s==="classic"?(d?.replaceItems(C),a?.replaceItems(S)):s==="unified"?a?.replaceItems(g()):a?.replaceItems(S),T()},destroy:()=>{y(),m()}};e.shellRoot.setAttribute("data-desktop-mode-layout",s),b(),T();let D=Js()?.id??null;return Uh(()=>{const C=Js()?.id??null;C!==D&&(D=C,b(),T(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:s,primary:c,side:l}})))}),L}function nb(e){return window.desktopModeCreateAiAssistant?Promise.resolve(window.desktopModeCreateAiAssistant):new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-ai="1"]'),s=()=>{const r=window.desktopModeCreateAiAssistant;if(!r){n(new Error("[desktop-mode] ai-assistant bundle loaded but did not register desktopModeCreateAiAssistant"));return}t(r)};if(o){window.desktopModeCreateAiAssistant?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeAi="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))),document.head.appendChild(i)})}class ob{constructor(t,n){this._real=null,this._loadPromise=null,this._pendingAsk=null,this._intendOpen=!1,this.ask=(...o)=>this._ensure().then(s=>s.ask(...o)),this._config=t,this._scriptUrl=n}_ensure(){return this._loadPromise?this._loadPromise:(this._loadPromise=nb(this._scriptUrl).then(t=>{const n=t(this._config);return this._pendingAsk&&n.attachAsk(this._pendingAsk),this._real=n,n}),this._loadPromise)}open(){this._intendOpen=!0,this._ensure().then(t=>t.open())}close(){this._intendOpen=!1,this._real&&this._real.close()}toggle(){this.isOpen?this.close():this.open()}get isOpen(){return this._real?this._real.isOpen:this._intendOpen}attachAsk(t){this._pendingAsk=t,this._real&&this._real.attachAsk(t)}}const Tl=e=>!e||typeof e!="object"?!1:e.name==="AbortError",sb=e=>{if(!e)return[];const t=zw();if(e===!0||e==="aiCallable")return t;if(Array.isArray(e)){const n=new Set(e.map(o=>o.toLowerCase()));return t.filter(o=>n.has(o.slug))}return typeof e=="function"?t.filter(n=>{try{return e(n.slug)===!0}catch{return!1}}):[]},ib=e=>e?typeof e=="string"?{text:e,mode:"append"}:typeof e=="object"&&typeof e.text=="string"&&e.text!==""?{text:e.text,mode:e.mode==="replace"?"replace":"append"}:null:null;function rb(e,t){const n=e??"";return n!==""?n:typeof t=="string"&&t!==""?t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"?t.message:""}function ab(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function db(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",d=r.restNonce??"";if(!a||!d)throw new Error("[desktop-mode] wp.desktop.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await ze(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":d},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw Tl(c)?c:new Error(`[desktop-mode] wp.desktop.ai.ask: network error — ${String(c?.message??c)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",d=Gw(r);if(!d)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??e.fallbackContext();let l;try{l=await Promise.resolve(d.run(a,c))}catch(u){l={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:l}},o=async(s,i,r,a,d,c)=>{const l={query:s,follow_up:{tool:{slug:i,args:r},result:ab(a)}};d&&(l.system_prompt_text=d.text,l.system_prompt_mode=d.mode);let u;try{u=await t(l,c)}catch(h){if(Tl(h))throw h;return null}if(!u.ok)return null;const p=await u.json().catch(()=>({}));return(typeof p.message=="string"?p.message.trim():"")!==""?p.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[desktop-mode] wp.desktop.ai.ask: empty query passed with non-default options — likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const d=sb(r.tools),c=ib(r.systemPrompt),l={query:a};r.resumeTool&&(l.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(l.start_offset=r.startOffset),d.length>0&&(l.command_tools=d),c&&(l.system_prompt_text=c.text,l.system_prompt_mode=c.mode);const u=await t(l,r.signal);if(!u.ok){const x=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[desktop-mode] wp.desktop.ai.ask: HTTP ${u.status} — ${x.message??u.statusText}`)}const p=await u.json();if(p.answer_type!=="tool_call"||!p.tool)return{answer_type:p.answer_type,message:p.message??"",entity:p.entity??null,admin_links:p.admin_links??null,request_id:p.request_id,continue:p.continue??null};const f=await n(p,r);if(!f.ok)return f.response;const{slug:h,args:m,result:w}=f;let g=rb(p.message,w);if(r.followUp===!0){const x=await o(a,h,m,w,c,r.signal);x!==null&&(g=x)}return{answer_type:"tool_call",message:g,entity:null,admin_links:null,toolCall:{slug:h,args:m,result:w},request_id:p.request_id}}}const Mi="desktop-mode-broadcast",Nl="desktop-mode-broadcast",Dl=window.location.origin;let Wi=null;function cb(e){Wi=e}function Ol(e,t){const n=String(j("desktop-mode.broadcast.topic",e,{payload:t})??e),o=j("desktop-mode.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Mi,{detail:s})),A(v.BROADCAST,s),ye.publish(n,o),!Wi)return;const i={type:Nl,topic:n,payload:o};for(const r of Wi._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Dl)}catch{}}}function We(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){A(v.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Mi,n),()=>document.removeEventListener(Mi,n)}function lb(){window.addEventListener("message",e=>{if(e.origin!==Dl)return;const t=e.data;!t||t.type!==Nl||t._fromParent||typeof t.topic=="string"&&Ol(t.topic,t.payload)})}const Rl="[desktop-mode-bin badge]";function je(...e){try{window.localStorage?.getItem("desktopModeBinDebug")&&console.info(Rl,...e)}catch{}}function Yo(...e){console.warn(Rl,...e)}const Ve="desktop-mode-recycle-bin",ub="desktop_mode_recycle_bin_seen_ts";function Ml(){return window.wp?.desktop}const ae=re("desktop-mode/recycle-bin/badge",()=>({current:0,seenTs:0,started:!1,countUrl:""}));function Mn(e){const t=Math.max(0,Math.floor(e)),n=ae.state.current;ae.state.current=t,je("setRecycleBinBadge",{prev:n,next:t}),Xo(t)}function Wl(e){Mn(ae.state.current+e)}function pb(){return ae.state.current}function Xo(e){const t=Ml(),n=fb(),o=n?0:e;je("paintBadge",{count:e,visible:o,active:n}),t?.dock?.setBadge?.(Ve,o),t?.taskbar?.setBadge?.(Ve,o),t?.icons?.setBadge?.(Ve,o)}function fb(){const e=Ml()?.windowManager;return e?.isActiveByBaseId?e.isActiveByBaseId(Ve):!!e?.isActive?.(Ve)}function mb(e,t=""){const n=Number(e)||0,o=window.desktopModeConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl,r=o?.desktopModeBinDebug;je("startRecycleBinBadge entry",{initial:n,countUrl:t,alreadyStarted:ae.state.started,cfgCount:s,cfgUrl:i,cfgDebug:r,readyState:document.readyState});const a=Number(s);if((typeof s=="number"||typeof s=="string")&&Number.isFinite(a)||Yo("desktopModeConfig.recycleBinCount is missing — PHP filter `desktop_mode_shell_config` did not deliver. Check your PHP error log for `[desktop-mode-bin debug]` lines.",{cfg:o}),ae.state.started){Mn(n);return}ae.state.started=!0,ae.state.countUrl=t,ae.state.seenTs=Date.now(),Mn(n),wb(),gb(),yb(),bb(),vb(),hb()}function hb(){const e="desktop-mode/recycle-bin/badge-lifecycle",t=n=>{const s=n?.windowId;!s||!(s===Ve||s.startsWith(Ve+"-"))||Xo(ae.state.current)};G(v.WINDOW_OPENED,e,t),G(v.WINDOW_FOCUSED,e,t),G(v.WINDOW_BLURRED,e,t),G(v.WINDOW_MINIMIZED,e,t),G(v.WINDOW_RESTORED,e,t),G(v.WINDOW_CLOSED,e,t),G(v.WINDOW_REOPENED,e,t)}function wb(){G(v.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/badge",e=>{e?.id===Ve&&Xo(ae.state.current)})}function gb(){G(v.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/badge",e=>{e?.ids?.includes(Ve)&&Xo(ae.state.current)})}function yb(){const e=t=>{const n=t;if(!n)return;const o=Array.isArray(n.ids)?n.ids.length:0;switch(n.action){case"trashed":Wl(+o);break;case"untrashed":case"deleted":Wl(-o);break}};We("desktop-mode.post.changed",e),We("desktop-mode.page.changed",e),We("desktop-mode.attachment.changed",e),We("desktop-mode.comment.changed",e),We("desktop-mode.placement.changed",e),We("desktop-mode.shortcut.changed",e),We("desktop-mode.folder.changed",e)}function bb(){const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;if(!n||n.type!=="desktop-mode-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=ae.state.seenTs){je("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:ae.state.seenTs});return}je("postMessage triggers refetch",{ts:o,prevSeenTs:ae.state.seenTs}),ae.state.seenTs=o,kb()})}function vb(){const e=window.jQuery;if(!e){Yo("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}je("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[ub]=ae.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.desktop_mode_recycle_bin;je("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>ae.state.seenTs&&(ae.state.seenTs=o.ts),typeof o.count=="number"&&Mn(o.count))})}async function kb(){if(!ae.state.countUrl){je("refetchCount: no countUrl, skip");return}je("refetchCount: hitting",ae.state.countUrl);try{const e=await fetch(ae.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){Yo("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();je("refetchCount: response",t),typeof t.count=="number"&&Mn(t.count)}catch(e){Yo("refetchCount: fetch failed",e)}}const _b="desktop-mode-os-settings",Eb="desktop-mode-recycle-bin";function Sb(e){const t=Cb();t&&t.addFilter("desktop-mode.dock.peek-card-content","desktop-mode/built-in-peek-renderers",(n,o)=>{const s=o,i=s.window.id;return i===_b?Ib():i===Eb?xb(s,e.getRecycleBinCount):n})}function Ib(e){const t=document.createElement("span");t.className="desktop-mode-dock-peek__card-body desktop-mode-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="desktop-mode-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="desktop-mode-dock-peek__os-subtitle",o.textContent=O("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="desktop-mode-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`desktop-mode-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function xb(e,t){const n=document.createElement("span");n.className="desktop-mode-dock-peek__card-body desktop-mode-dock-peek__card-body--recycle-bin",n.setAttribute("aria-hidden","true");const o=Math.max(0,Math.floor(t()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="desktop-mode-dock-peek__bin-stage";const i=document.createElement("span");i.className="desktop-mode-dock-peek__bin-stack";for(let d=0;d<3;d++){const c=document.createElement("span");c.className="desktop-mode-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="desktop-mode-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="desktop-mode-dock-peek__bin-label",o===0?a.textContent=O("Recycle Bin — empty"):o===1?a.textContent=O("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function Cb(){return window.wp?.hooks??null}const Wn="desktop-mode-bug-report",Ab="WordPress",Lb="desktop-mode",Pl=6e3;function Tb(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="desktop-mode-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="desktop-mode-bug-report__intro",n.textContent=O("Found a bug or have a feature idea? Fill this in and we will open a pre-filled GitHub issue for you to review and submit."),t.appendChild(n),t.appendChild(Nb()),t.appendChild(Db("title",O("Title"),{placeholder:O("A short summary"),required:!0})),t.appendChild($l("description",O("What happened? What did you expect?"),{placeholder:O("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild($l("steps",O("Steps to reproduce (bug only)"),{placeholder:O("One step per line"),rows:4}));const o=Ob();t.appendChild(o);const s=document.createElement("div");s.className="desktop-mode-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="desktop-mode-bug-report__submit",i.textContent=O("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="desktop-mode-bug-report__hint",r.textContent=O("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const d=Mb(t);if(!d.title.trim()||!d.description.trim()){Rb(t,O("Title and description are both required."));return}const c=Wb(d);window.open(c,"_blank","noopener")}),e.appendChild(t)}function Nb(){const e=document.createElement("div");e.className="desktop-mode-bug-report__field desktop-mode-bug-report__field--type";const t=document.createElement("span");t.className="desktop-mode-bug-report__label",t.textContent=O("Type"),e.appendChild(t);const n=document.createElement("div");n.className="desktop-mode-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:O("Bug"),checked:!0},{value:"feature",label:O("Feature request")},{value:"question",label:O("Question")}];for(const s of o){const i=document.createElement("label");i.className="desktop-mode-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const a=document.createElement("span");a.textContent=s.label,i.appendChild(a),n.appendChild(i)}return e.appendChild(n),e}function Db(e,t,n={}){const o=document.createElement("div");o.className="desktop-mode-bug-report__field";const s=document.createElement("label");s.className="desktop-mode-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("input");return i.type="text",i.name=e,i.className="desktop-mode-bug-report__input",n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function $l(e,t,n={}){const o=document.createElement("div");o.className="desktop-mode-bug-report__field";const s=document.createElement("label");s.className="desktop-mode-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("textarea");return i.name=e,i.className="desktop-mode-bug-report__textarea",i.rows=n.rows??4,n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function Ob(){const e=document.createElement("details");e.className="desktop-mode-bug-report__metadata";const t=document.createElement("summary");t.textContent=O("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="desktop-mode-bug-report__metadata-body",n.textContent=Hl(Ul()),e.appendChild(n),e}function Rb(e,t){let n=e.querySelector(".desktop-mode-bug-report__error");n||(n=document.createElement("div"),n.className="desktop-mode-bug-report__error",n.setAttribute("role","alert"),e.prepend(n)),n.textContent=t}function Mb(e){const t=new FormData(e);return{type:t.get("type")??"bug",title:t.get("title")??"",description:t.get("description")??"",steps:t.get("steps")??""}}function Wb(e){const t=Pb(e.type),n=$b(e),o=new URLSearchParams;return o.set("title",e.title.trim()),o.set("body",n),t.length&&o.set("labels",t.join(",")),`https://github.com/${Ab}/${Lb}/issues/new?${o.toString()}`}function Pb(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function $b(e){const t=[];t.push(e.description.trim()),e.type==="bug"&&e.steps.trim()&&(t.push(""),t.push("## Steps to reproduce"),t.push(""),t.push(e.steps.trim())),t.push(""),t.push("<details><summary>Environment</summary>"),t.push(""),t.push("```"),t.push(Hl(Ul())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(` |
| 81 |
`);return n.length>Pl&&(n=n.slice(0,Pl)+` |
| 82 |
|
| 83 |
…(truncated to fit GitHub URL length limit)`),n}function Ul(){const e=window.wp?.desktop?.config;return{pluginVersion:e?.pluginVersion??"unknown",wordpressVersion:e?.wordpressVersion??"unknown",userAgent:navigator.userAgent,viewport:`${window.innerWidth}x${window.innerHeight}`,platform:navigator.platform||"unknown",currentUrl:window.location.href}}function Hl(e){return[`Plugin version: ${e.pluginVersion}`,`WordPress version: ${e.wordpressVersion}`,`User agent: ${e.userAgent}`,`Viewport: ${e.viewport}`,`Platform: ${e.platform}`,`Current URL: ${e.currentUrl}`].join(` |
| 84 |
`)}let Zo=null,Jo={installHintDismissed:!1,notificationsEnabled:!1};const Pi=new Set;function Bl(e){if(!e){Zo=null;return}Zo=e,Jo={...e.state},zl()}function Pn(){return{...Jo}}function $i(e){if(Jo={...Jo,...e},zl(),!Zo)return Pn();const t=JSON.stringify(e),n=Ub();return fetch(Zo.stateUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",...n?{"X-WP-Nonce":n}:{}},body:t}).catch(o=>{typeof console<"u"&&console.warn("[desktop-mode] pwa-state write failed:",o)}),Pn()}function Fl(e){return Pi.add(e),()=>{Pi.delete(e)}}function zl(){const e=Pn();for(const t of Array.from(Pi))try{t(e)}catch(n){typeof console<"u"&&console.error("[desktop-mode] pwa-state listener threw:",n)}}function Ub(){return window.desktopModeConfig?.restNonce??""}const Hb=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:Pn,initPwaState:Bl,subscribePwaState:Fl,updatePwaState:$i},Symbol.toStringTag,{value:"Module"}));let Qo=null,Gl=!1,jl=!1,ql=!1,bt="pending";function Bb(){if(jl)return;jl=!0;const e=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{e&&(ql||zb()||(Gb(),ql=!0,setTimeout(()=>window.location.reload(),0)))})}const Vl="wpd-sw-reload-ts",Fb=3e4;function zb(){try{const e=sessionStorage.getItem(Vl),t=e?Number.parseInt(e,10):0;return!Number.isFinite(t)||t<=0?!1:Date.now()-t<Fb}catch{return!1}}function Gb(){try{sessionStorage.setItem(Vl,String(Date.now()))}catch{}}async function jb(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return bt="unsupported",null;if(Qo||Gl)return Qo;if(!t.forceReplace){const o=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(s=>{const i=s.active?.scriptURL??s.installing?.scriptURL??"";return i!==""&&i!==e.swUrl});if(o)return bt="foreign-sw",typeof console<"u"&&console.warn("[desktop-mode] another service worker is already registered ("+o.scope+"); skipping desktop-mode SW. Set desktop_mode_pwa_force_replace_sw=true to override."),null}try{return Qo=await navigator.serviceWorker.register(e.swUrl,{scope:"/",updateViaCache:"none"}),bt="registered",Bb(),Qo}catch(n){return Gl=!0,bt="failed",typeof console<"u"&&console.warn("[desktop-mode] SW registration failed:",n),null}}function qb(){return bt}const Vb="desktop-mode-pwa-install";function Kl(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Yl(){if(Kl())return!0;const e=window.navigator;if(typeof e.getInstalledRelatedApps!="function")return!1;try{const t=await e.getInstalledRelatedApps();return Array.isArray(t)&&t.length>0}catch{return!1}}let at=null;function Kb(e,t){if(typeof window>"u")return;window.removeEventListener("beforeinstallprompt",n),window.addEventListener("beforeinstallprompt",n),window.removeEventListener("appinstalled",o),window.addEventListener("appinstalled",o);function n(s){s.preventDefault(),at=s}function o(){at=null,t({message:oe(O("Installed %s as an app."),e)})}}function Yb(e,t){return{id:Vb,title:oe(O("Install %s as an app"),e),icon:"dashicons-download",onOpen:()=>{Xb(e,t)}}}async function Xb(e,t){if(at){const n=at;at=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:O("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[desktop-mode] install prompt failed:",o)}return}if(await Yl()){t({message:oe(O("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(qb()==="foreign-sw"){t({message:O("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the desktop_mode_pwa_force_replace_sw filter to true.")});return}t({message:O("Install isn't available right now. Keep using the page; if it still doesn't appear, the app may already be installed in this browser.")})}async function Zb(){if(!at)return"unavailable";const e=at;at=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function Jb(){Promise.resolve().then(()=>Hb).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function Qb(e){const t=ye.filter("desktop-mode/notification-requested",{...e});if(!t||t.cancel===!0||!t.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=ee({message:t.body?t.title+" — "+t.body:t.title}),ye.publish("desktop-mode/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=Xl(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(d=>{if(!n){if(d==="granted"){$i({notificationsEnabled:!0}),o=Xl(t),o||r();return}r()}}),i)}function Xl(e){let t=null;try{t=new Notification(e.title,{body:e.body,icon:e.icon,tag:e.tag,requireInteraction:e.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[desktop-mode] Notification ctor threw:",n),null}if(e.onClick){const n=e.onClick;t.onclick=()=>{try{n(t)}catch(o){typeof console<"u"&&console.error("[desktop-mode] notification onClick threw:",o)}}}return ye.publish("desktop-mode/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function ev(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&$i({notificationsEnabled:!0}),e}function tv(){return typeof Notification>"u"?"unsupported":Notification.permission}function nv(e,t){e.pwa&&(Bl(e.pwa),Kb(e.pwa.appName||"WordPress",t),jb(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw}))}const Ft={START:"desktop-mode-cross-frame-drag-start",END:"desktop-mode-cross-frame-drag-end"};function ov(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-start"&&!!e.payload&&typeof e.payload=="object"}function sv(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-end"}function iv(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-payload-request"}function rv(e){const t=e;return t.kind!==void 0&&t.kind!==null?e:typeof t.id=="number"&&typeof t.url=="string"&&typeof t.mime=="string"?{kind:"attachment",id:t.id,url:t.url,title:typeof t.title=="string"?t.title:"",alt:typeof t.alt=="string"?t.alt:"",mime:t.mime,thumbnailUrl:typeof t.thumbnailUrl=="string"?t.thumbnailUrl:void 0,sizes:t.sizes&&typeof t.sizes=="object"?t.sizes:void 0}:e}class av{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(ov(n)){this._startDrag(n.payload);return}if(sv(n)){this._endDrag();return}if(iv(n)&&this._payload&&t.source)try{t.source.postMessage({type:"desktop-mode-drag-payload",payload:this._payload},this._origin)}catch{}},this._origin=window.location.origin,window.addEventListener("message",this._onMessage)}getPayload(){return this._payload}isDragging(){return this._payload!==null}start(t){this._payload!==t&&this._startDrag(t)}end(){this._endDrag()}_startDrag(t){const n=rv(t);this._payload=n,document.dispatchEvent(new CustomEvent(Ft.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(Ft.END,{detail:{payload:t}}))}}class dv{constructor(){this._targets=new Map,this._byElement=new Map}register(t){const n=this._targets.get(t.id);return n&&this._byElement.delete(n.element),this._targets.set(t.id,t),this._byElement.set(t.element,t),()=>{this._targets.get(t.id)===t&&(this._targets.delete(t.id),this._byElement.delete(t.element))}}list(){return Array.from(this._targets.values())}clear(){this._targets.clear(),this._byElement.clear()}hitTest(t){let n=t;for(;n;){if(n instanceof HTMLElement){const o=this._byElement.get(n);if(o)return o;if(n.classList.contains("desktop-mode-window"))return null}n=n.parentElement}return null}hitTestPoint(t,n){const o=document.elementFromPoint(t,n);return{target:this.hitTest(o),element:o,accepted:!1}}}const cv="desktop-mode-drag-ghost",Zl="desktop-mode-drag-ghost--accept",Jl="desktop-mode-drag-ghost--reject",lv="desktop-mode-drag-hint",Ql="desktop-mode-drag-hint--accept",eu="desktop-mode-drag-hint--reject",tu="desktop-mode-drag-hint--neutral",uv=16,pv=18;function fv(e,t,n){const o=bv(e),s=e.ghost?.offsetX??vv(e.source),i=e.ghost?.offsetY??kv(e.source);o.classList.add(cv),o.setAttribute("aria-hidden","true"),o.style.position="fixed",o.style.left="0",o.style.top="0",o.style.margin="0",o.style.pointerEvents="none",o.style.zIndex="2147483647",o.style.willChange="transform",document.body.appendChild(o);const r=hv(e),a=r?mv():null;a&&document.body.appendChild(a);const d={get element(){return o},moveTo(c,l){o.style.transform=`translate3d(${c-s}px, ${l-i}px, 0)`,a&&(a.style.transform=`translate3d(${c+uv}px, ${l+pv}px, 0)`)},setMode(c,l){o.classList.remove(Zl,Jl),c==="accept"?o.classList.add(Zl):c==="reject"&&o.classList.add(Jl),a&&r&&(a.classList.remove(Ql,eu,tu),c==="accept"?(a.classList.add(Ql),a.textContent=l?.acceptLabel??r.accept):c==="reject"?(a.classList.add(eu),a.textContent=r.reject):(a.classList.add(tu),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(c){const l=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return c()}finally{o.style.visibility=l,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return d.moveTo(t,n),d.setMode("neutral"),d}function mv(){const e=document.createElement("div");return e.className=lv,e.setAttribute("aria-hidden","true"),e.setAttribute("role","presentation"),e.style.position="fixed",e.style.left="0",e.style.top="0",e.style.margin="0",e.style.pointerEvents="none",e.style.zIndex="2147483647",e.style.willChange="transform",e}function hv(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??wv(e),reject:t?.reject??gv(),neutral:t?.neutral??yv(e)}}function wv(e){return e.type==="shortcut"?O("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?O("Drop here to move","desktop-mode"):O("Drop here","desktop-mode")}function gv(e){return O("Can’t drop here","desktop-mode")}function yv(e){return e.type==="shortcut"?O("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?O("Drop in a folder","desktop-mode"):""}function bv(e){if(e.ghost?.element)return e.ghost.element;const t=e.source.cloneNode(!0);t.removeAttribute("id");const n=e.source.getBoundingClientRect();return t.style.width=`${n.width}px`,t.style.height=`${n.height}px`,t}function vv(e){return e.offsetWidth/2}function kv(e){return e.offsetHeight/2}let nu=!1;function _v(e){nu||(nu=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const ou=4,Se={START:"desktop-mode.drag.start",MOVE:"desktop-mode.drag.move",ENTER:"desktop-mode.drag.enter",LEAVE:"desktop-mode.drag.leave",REJECTED:"desktop-mode.drag.rejected",COMMIT:"desktop-mode.drag.commit",CANCEL:"desktop-mode.drag.cancel",END:"desktop-mode.drag.end"},es="desktop-mode-file-tile--dragging",su="desktop-mode-file-tile--drop-target",iu="data-desktop-mode-trash-drop-active",ru="data-files-drop-active",au="data-desktop-mode-dragging",du="data-desktop-mode-drag-type",Ui="data-desktop-mode-drag-mode";class Ev{constructor(){this._registry=new dv,this._active=null,this._docListenersAttached=!1,this._lastLiftedEndAt=0,this._onPointerMove=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;const o=t.clientX-n._origin.clientX,s=t.clientY-n._origin.clientY;if(!n._lifted){if(Math.abs(o)<ou&&Math.abs(s)<ou)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),Ke(Se.MOVE,{payload:n.payload,clientX:t.clientX,clientY:t.clientY}))},this._onPointerUp=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;if(!n._lifted){n._finished=!0,this._active=null;try{n._callbacks.onClickOnly?.()}catch(s){console.error("[desktop-mode] drag onClickOnly threw:",s)}return}const o=this._hitTestNow(n,t.clientX,t.clientY);if(o&&o.accepted&&o.target){this._commit(n,o.target,t.clientX,t.clientY);return}this._cancel(n,o&&o.target?"rejected":"no-target")},this._onPointerCancel=t=>{const n=this._active;!n||n._pointerId!==t.pointerId||this._cancel(n,"pointercancel")}}start(t){if(this._active||t.origin.button!==0)return null;const n={payload:t.payload,isFinished:()=>n._finished,cancel:o=>this._cancel(n,o??"caller"),_origin:t.origin,_pointerId:t.origin.pointerId,_lifted:!1,_finished:!1,_callbacks:{onClickOnly:t.onClickOnly,onCancel:t.onCancel,onCommit:t.onCommit},_ghost:null,_currentTarget:null,_currentAccepted:!1};return this._active=n,this._ensureDocListeners(),_v(o=>{this._active&&this._cancel(this._active,o)}),n}registerDropTarget(t){return this._registry.register(t)}isDragging(){return this._active!==null&&this._active._lifted}recentlyEndedDrag(t=500){return this._lastLiftedEndAt===0?!1:Date.now()-this._lastLiftedEndAt<t}getActive(){return this._active}debug(){return{findOrphans:()=>cu(),listTargets:()=>this._registry.list()}}_ensureDocListeners(){this._docListenersAttached||(this._docListenersAttached=!0,document.addEventListener("pointermove",this._onPointerMove,!0),document.addEventListener("pointerup",this._onPointerUp,!0),document.addEventListener("pointercancel",this._onPointerCancel,!0))}_lift(t,n){t._lifted=!0,t.payload.source.classList.add(es),t._ghost=fv(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(au,""),document.body.setAttribute(du,String(t.payload.type)),document.body.setAttribute(Ui,"neutral")),Ke(Se.START,{payload:t.payload})}_hitTestNow(t,n,o){const s=()=>{const i=document.elementFromPoint(n,o),r=this._registry.hitTest(i);if(!r)return{target:null,accepted:!1};let a=!1;try{a=r.accept(t.payload)}catch(d){console.error("[desktop-mode] drop target accept() threw:",r.id,d)}return{target:r,accepted:a}};return t._ghost?t._ghost.withHidden(s):s()}_updateHover(t,n,o){const s=this._hitTestNow(t,n,o),i=t._currentTarget;if(s.target===i&&s.accepted===t._currentAccepted)return;i&&Hi(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(Sv(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),Ke(Se.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Ui,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),Hi(n,t),this._cleanupDom(t);const i=this._active;this._active=null;try{n.onDrop(t,{clientX:o,clientY:s})}catch(r){console.error("[desktop-mode] drop target onDrop threw:",n.id,r)}try{t._callbacks.onCommit?.(n)}catch(r){console.error("[desktop-mode] drag onCommit threw:",r)}Ke(Se.COMMIT,{payload:t.payload,targetId:n.id}),Ke(Se.END,{payload:t.payload,reason:"commit"}),this._active===i&&(this._active=null)}_cancel(t,n){if(!t._finished){t._finished=!0,t._lifted&&(this._lastLiftedEndAt=Date.now()),t._currentTarget&&Hi(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[desktop-mode] drag onCancel threw:",o)}Ke(Se.CANCEL,{payload:t.payload,reason:n}),Ke(Se.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(es)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(au),document.body.removeAttribute(du),document.body.removeAttribute(Ui)),Iv()}}function Ke(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function Sv(e,t){try{e.onEnter?.(t)}catch(n){console.error("[desktop-mode] drop target onEnter threw:",e.id,n)}Ke(Se.ENTER,{payload:t.payload,targetId:e.id})}function Hi(e,t){try{e.onLeave?.(t)}catch(n){console.error("[desktop-mode] drop target onLeave threw:",e.id,n)}Ke(Se.LEAVE,{payload:t.payload,targetId:e.id})}function cu(){if(typeof document>"u")return[];const e=[];for(const t of[`.${es}`,`.${su}`,`[${iu}]`,`[${ru}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function Iv(){for(const e of cu())e.classList.remove(es,su),e.removeAttribute(iu),e.removeAttribute(ru)}const xv=".desktop-mode-window",lu="wp-window-";function uu(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(xv);return o instanceof HTMLElement?o:null}function Cv(e){if(!e.id.startsWith(lu))return null;const t=e.id.slice(lu.length);return t.length>0?t:null}const Av="desktop-mode-iframe-drop-",ts="iframe.desktop-mode-window__iframe",Bi="data-desktop-mode-iframe-drop-active";let Fi=!1,pu=null;const Re=new Map,vt=new Map;let Ye=null,kt=null;function Lv(){document.querySelectorAll(ts).forEach(t=>{Re.has(t)||(Re.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function Tv(){Re.forEach((e,t)=>{t.style.pointerEvents=e}),Re.clear()}function fu(e,t){const n=uu(e,t);if(!n)return null;const o=n.querySelector(ts);return o instanceof HTMLIFrameElement?o:null}const mu=e=>{if(!Ye)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=fu(e.clientX,e.clientY);t!==kt&&(kt&&_t(kt,{type:"desktop-mode-drag-leave"}),kt=t,t&&_t(t,{type:"desktop-mode-drag-over",payload:Ye}))},hu=e=>{if(!Ye)return;e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const t=fu(e.clientX,e.clientY),n=Ye;if(zi(),!t)return;const o=t.getBoundingClientRect();_t(t,{type:"desktop-mode-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},wu=()=>{zi()};function Nv(e){if(Ye){Ye=e;return}Ye=e,Lv(),document.addEventListener("dragover",mu,!0),document.addEventListener("drop",hu,!0),document.addEventListener("dragend",wu,!0)}function zi(){Ye&&(Ye=null,kt&&(_t(kt,{type:"desktop-mode-drag-leave"}),kt=null),document.removeEventListener("dragover",mu,!0),document.removeEventListener("drop",hu,!0),document.removeEventListener("dragend",wu,!0),Tv())}function ns(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function _t(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function Dv(e,t,n,o){return e.registerDropTarget({id:`${Av}${o}`,element:n,accept:s=>!!ns(s),onEnter:s=>{const i=ns(s.payload);i&&(n.setAttribute(Bi,""),_t(t,{type:"desktop-mode-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(Bi),_t(t,{type:"desktop-mode-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(Bi);const r=ns(s.payload);if(!r)return;const a=t.getBoundingClientRect();_t(t,{type:"desktop-mode-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function gu(e){let t=e.parentElement;for(;t;){if(t.id.startsWith("wp-window-"))return t.id.slice(10);t=t.parentElement}return`unknown-${Math.random().toString(36).slice(2,10)}`}function Ov(e){const t=pu;if(!t)return;const n=document.querySelectorAll(ts),o=!!ns(e);console.info("[desktop-mode] drag-start: suppressing %d iframe(s); bridgeable=%s",n.length,o,e),n.forEach(s=>{if(Re.has(s)||(Re.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||vt.has(s))return;const i=s.parentElement;if(!i)return;const r=gu(s),a=Dv(t,s,i,r);vt.set(s,a)})}function Rv(){Re.forEach((e,t)=>{t.style.pointerEvents=e}),Re.clear(),vt.forEach(e=>{try{e()}catch{}}),vt.clear()}function Mv(e){Fi||(Fi=!0,pu=e,document.addEventListener(Se.START,t=>{const n=t.detail;Ov(n?.payload)}),document.addEventListener(Se.END,()=>{Rv()}),document.addEventListener(Ft.START,t=>{const n=t.detail;n?.payload&&Nv(n.payload)}),document.addEventListener(Ft.END,()=>{zi()}),G(v.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(Re))t.isConnected||Re.delete(t);for(const[t,n]of Array.from(vt))if(!t.isConnected){try{n()}catch{}vt.delete(t)}}),window.__desktopModeIframeDropDebug=()=>({installed:Fi,iframesInDom:document.querySelectorAll(ts).length,suppressedCount:Re.size,registeredCount:vt.size,suppressedIframeIds:Array.from(Re.keys()).map(gu)}))}const Wv=250,Pv=1e3,$v="desktop-mode-drag-hover";let yu=!1,Gi=null,ji=null,$n=null,Un=null,qi=null;function bu(){$n!==null&&(clearTimeout($n),$n=null)}function vu(){Un!==null&&(clearTimeout(Un),Un=null)}function Hn(){bu(),vu(),ji=null}function ku(){vu(),Un=setTimeout(()=>{Un=null,Hn()},Pv)}function Uv(e,t){const n=Gi?.getById(e);if(!(!n||n.isFocused()||!j(v.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{Gi?.focus(n)}catch(s){console.error("[desktop-mode] focus-on-drag-hover focus() threw:",e,s)}}function _u(e,t){e!==ji&&(bu(),ji=e,e!==null&&($n=setTimeout(()=>{$n=null,Uv(e,t)},Wv)))}function Eu(e,t,n){const o=uu(e,t);_u(o?Cv(o):null,n)}const Hv=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||Eu(t.clientX,t.clientY,t.payload?.type??"")},Bv=()=>{Hn()};function Fv(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;return typeof n.includes=="function"?n.includes("Files"):typeof n.contains=="function"&&n.contains("Files")}const zv=e=>{ku();const t=qi??(Fv(e)?"os-file":"external");Eu(e.clientX,e.clientY,t)},Su=()=>{Hn()},Gv=e=>{e.relatedTarget===null&&Hn()};function jv(e){if(!e)return null;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e)return n.closest("[data-window-id]")?.getAttribute("data-window-id")||null;return null}const qv=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==$v)return;const n=jv(e.source);n&&(ku(),_u(n,typeof t.payloadType=="string"?t.payloadType:"external"))},Vv=e=>{const t=e.detail;t?.payload&&(qi=t.payload.kind??"")},Kv=()=>{qi=null,Hn()};function Yv(e){yu||(yu=!0,Gi=e,document.addEventListener(Se.MOVE,Hv),document.addEventListener(Se.END,Bv),document.addEventListener(Ft.START,Vv),document.addEventListener(Ft.END,Kv),document.addEventListener("dragover",zv,!0),document.addEventListener("drop",Su,!0),document.addEventListener("dragend",Su,!0),document.addEventListener("dragleave",Gv,!0),window.addEventListener("message",qv))}function Iu(){const e=window.wp?.desktop;if(!e)return[];const t=e.windowManager,n=e.config;if(!t||!n)return[];const o=[],s=(r,a)=>({id:r.id,label:r.title,description:a,icon:r.icon,open:()=>t.open({id:r.id,baseId:r.id,url:r.url,title:r.title,icon:r.icon})});for(const r of n.dockItems??[])o.push(s(r,"Admin menu"));const i=j("desktop-mode.open-command.items",o);return Array.isArray(i)?i:o}const Xv={slug:"open",label:"Open",description:"Open an admin page or registered window.",hint:"[window]",icon:"dashicons-external",suggest(e){const t=e.trim().toLowerCase(),n=Iu();return(t===""?n:n.filter(s=>s.label.toLowerCase().includes(t)||s.id.toLowerCase().includes(t))).slice(0,12).map(s=>({value:s.label,label:s.label,description:s.description,icon:s.icon??"dashicons-external"}))},run(e,t){const n=e.trim();if(!n)return"Type the name of a window to open, for example `/open Posts`.";const o=Iu(),s=n.toLowerCase(),i=o.find(r=>r.label.toLowerCase()===s||r.id.toLowerCase()===s)??o.find(r=>r.label.toLowerCase().includes(s)||r.id.toLowerCase().includes(s));if(!i)return`No window matching **${n}** — try \`/open\` alone to see available options.`;i.open(),t.close()}};function Zv(){zo(Xv)}const be=[],Jv=new Set;function xu(e){if(!e||typeof e.id!="string"||e.id==="")return()=>{};if(typeof e.open!="function"||typeof e.close!="function"||typeof e.isOpen!="function")return()=>{};const t=be.findIndex(n=>n.id===e.id);return t>=0?be[t]=e:be.push(e),Vi(),()=>{const n=be.findIndex(o=>o.id===e.id);n>=0&&(be.splice(n,1),Vi())}}function Qv(e){const t=be.findIndex(n=>n.id===e);t>=0&&(be.splice(t,1),Vi())}function ek(){return be.slice()}function Vi(){for(const e of Array.from(Jv))try{e()}catch(t){typeof console<"u"&&console.error("[desktop-mode] palette-registry listener threw:",t)}}function Cu(){if(be.length===0)return;const e=be.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{be[0].open()}catch{}return}try{be[e].close()}catch{}const t=e+1;if(t<be.length)try{be[t].open()}catch{}}function Au(e){const t=be.find(n=>n.id===e);if(t){for(const n of be)if(n.id!==e)try{n.isOpen()&&n.close()}catch{}try{t.open()}catch{}}}let Lu=!1;function tk(){if(Lu)return;Lu=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),Cu())},!0);const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;n&&n.type==="desktop-mode-palette-cycle"&&Cu()})}const os=new Map,Ki=new Map;let Tu=!1;const Xe={contribute(e,t){return os.set(e,t),()=>{os.get(e)===t&&os.delete(e)}},subscribe(e,t){let n=Ki.get(e);return n||(n=new Set,Ki.set(e,n)),n.add(t),()=>{n.delete(t)}}};function nk(){if(Tu)return;Tu=!0;const e=window.jQuery;if(!e){console.warn("[desktop-mode/heartbeat] jQuery missing — Heartbeat bus disabled.");return}e(document).on("heartbeat-send",(...t)=>{const n=t[1];if(n)for(const[o,s]of os)try{n[o]=s()}catch(i){console.error(`[desktop-mode/heartbeat] supplier for "${o}" threw:`,i)}}),e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n)for(const[o,s]of Ki){const i=n[o];if(i!==void 0)for(const r of s)try{r(i)}catch(a){console.error(`[desktop-mode/heartbeat] subscriber for "${o}" threw:`,a)}}})}const Pe=re("desktop-mode/presence",()=>({byUser:new Map,serverTimeMs:0})),ok=5*60*1e3;let Nu=Date.now(),Du=!1;function ss(){Nu=Date.now()}function sk(e){if(!e||!e.snapshot)return;const t=Pe.state.byUser,n=new Map(t),o=[];for(const[s,i]of Object.entries(e.snapshot)){const r=Number(s);if(!Number.isFinite(r)||r<=0)continue;const d={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=t.get(r);n.set(r,d),(!c||c.status!==d.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:d.status,entry:d})}Pe.state.byUser=n,typeof e.serverTimeMs=="number"&&(Pe.state.serverTimeMs=e.serverTimeMs),Pe.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("desktop-mode-presence-changed",{detail:i})),ye.publish("desktop-mode/presence-changed",i)}ye.publish("desktop-mode/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function ik(){Du||(Du=!0,document.addEventListener("pointerdown",ss,{capture:!0,passive:!0}),document.addEventListener("keydown",ss,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||ss()}),Xe.contribute("desktop_mode_presence_active",()=>!0),Xe.contribute("desktop_mode_user_active",()=>Date.now()-Nu<ok),Xe.subscribe("desktop_mode_presence",e=>{sk(e)}))}function rk(e){const t=Pe.state.byUser.get(e);return t?t.status:"offline"}function ak(){return new Map(Pe.state.byUser)}function dk(e){return Pe.state.byUser.get(e)??null}function ck(e){return Pe.subscribe(t=>e(t))}function lk(){ss()}function uk(e){if(!Array.isArray(e)||e.length===0)return;const t=Pe.state.byUser,n=new Map(t),o=[];for(const s of e){const i=Number(s.userId);if(!Number.isFinite(i)||i<=0)continue;const r=t.get(i),a={status:s.status,lastSeenMs:typeof s.lastSeenMs=="number"?s.lastSeenMs:r?.lastSeenMs??0,lastActiveMs:typeof s.lastActiveMs=="number"?s.lastActiveMs:r?.lastActiveMs??0};n.set(i,a),(!r||r.status!==a.status)&&o.push({userId:i,oldStatus:r?r.status:null,newStatus:a.status,entry:a})}if(!(o.length===0&&n.size===t.size)){Pe.state.byUser=n,Pe.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("desktop-mode-presence-changed",{detail:i})),ye.publish("desktop-mode/presence-changed",i)}ye.publish("desktop-mode/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const pk=Object.freeze({getStatus:rk,getAll:ak,getEntry:dk,subscribe:ck,markActive:lk,applyBatch:uk}),fk="desktop_mode_nonces",Yi=new Map;let Ou=!1;function Xi(e,t){if(typeof e!="string"||e==="")return()=>{};let n=Yi.get(e);return n||(n=new Set,Yi.set(e,n)),n.add(t),()=>{n.delete(t)}}function mk(){Ou||(Ou=!0,Xe.subscribe(fk,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=Yi.get(t);if(o)for(const s of o)try{s(n)}catch(i){console.error(`[desktop-mode/nonce-refresh] updater for "${t}" threw:`,i)}}}),hk())}function hk(){Xi("wp_rest",wk),Xi("desktop-mode-plugins",e=>{Ru("desktop-mode-plugins","ajaxNonce",e)}),Xi("updates",e=>{Ru("desktop-mode-plugins","updatesNonce",e)})}function wk(e){const t=gk();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=Mu();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Ru(e,t,n){const s=Mu()?.[e];s&&typeof s=="object"&&(s[t]=n)}function gk(){if(!(typeof window>"u"))return window.desktopModeConfig}function Mu(){if(!(typeof window>"u"))return window.desktopModeWindowConfig}const zt=12;function Zi(e,t){const n=ne(e,t.adminUrl);return(t.dockItems||[]).find(o=>ne(o.url,t.adminUrl)===n||(o.submenu||[]).some(s=>ne(s.url,t.adminUrl)===n))}function Wu(e,t){const n=Math.max(200,t.width-zt*2),o=Math.max(200,t.height-zt*2),s=Math.min(e.width,n),i=Math.min(e.height,o),r=Math.max(0,t.width-s-zt),a=Math.max(0,t.height-i-zt),d=Math.max(zt,Math.min(e.x,r)),c=Math.max(zt,Math.min(e.y,a));return{x:d,y:c,width:s,height:i}}const Pu=window.location.origin;function yk(e,t){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let d;try{d=new URL(a,window.location.href)}catch(m){typeof console<"u"&&console.warn("[desktop-mode] Couldn’t parse href; letting the browser handle the click:",a,m);return}if(d.origin!==Pu)return;let c;try{c=new URL(t.adminUrl).pathname}catch(m){typeof console<"u"&&console.error("[desktop-mode] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,m),c="/wp-admin/"}if(!d.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(d.pathname)||d.searchParams.has("action")&&d.searchParams.get("action")==="logout"||d.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),mt(d.href)))return;const l=ne(d.href,t.adminUrl),u=Zi(d.href,t),p=(i.textContent||"").trim()||u?.title||"",f=!!i.closest("#wp-admin-bar-new-content"),h={id:l,baseId:l,multi:!!u?.multi||f,url:d.href,parentUrl:u?.url??d.href,title:u?.title||p,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu};if(f){e.openNew(h);return}e.open(h)},!0)}const bk="desktop-mode-registry-changed";function vk(e,t){const n=new Set;if(Array.isArray(e))for(const r of e)r&&typeof r.id=="string"&&n.add(r.id);const o=new Set;for(const r of t)r&&typeof r.id=="string"&&o.add(r.id);const s=[];for(const r of o)n.has(r)||s.push(r);const i=[];for(const r of n)o.has(r)||i.push(r);return{added:s,removed:i}}function Ji(e,t,n){const{added:o,removed:s}=vk(t,n);if(o.length===0&&s.length===0||typeof document>"u")return;const i={registry:e,added:o,removed:s};document.dispatchEvent(new CustomEvent(bk,{detail:i}))}function kk(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerUnfocusEffects:c,syncServerWindowLinkRenderers:l,syncServerDockRailRenderers:u,renderIcons:p,syncShortcuts:f}=e;return function(m){const w=m.dockItems,g=m.nativeWindows,x=m.serverWidgets,T=m.serverWallpapers,y=m.serverCommandScripts,k=m.serverCommands,N=m.serverSettingsTabScripts,b=m.serverSettingsTabs,L=m.serverDockRailRendererScripts,D=m.serverTitleBarButtonScripts,C=m.serverUnfocusEffectScripts,S=m.serverWindowLinkRendererScripts,I=m.serverWindowNotices,R=m.desktopIcons;if(!Array.isArray(w)||w.length===0)return;const F=n.dockItems;if(t(w),n.dockItems=w,Ji("dock-items",F,w),f?.(),Array.isArray(g)){const K=n.nativeWindows;o(g),n.nativeWindows=g,Ji("native-windows",K,g)}if(Array.isArray(x)&&(s(x),n.serverWidgets=x),Array.isArray(T)&&(i(T),n.serverWallpapers=T),Array.isArray(y)&&(r(y,Array.isArray(k)?k:void 0),n.serverCommandScripts=y,Array.isArray(k)&&(n.serverCommands=k)),Array.isArray(N)&&(a(N,Array.isArray(b)?b:void 0),n.serverSettingsTabScripts=N,Array.isArray(b)&&(n.serverSettingsTabs=b)),Array.isArray(D)&&(d(D),n.serverTitleBarButtonScripts=D),Array.isArray(C)&&(c(C),n.serverUnfocusEffectScripts=C),Array.isArray(S)&&(l(S),n.serverWindowLinkRendererScripts=S),Array.isArray(L)&&(u(L),n.serverDockRailRendererScripts=L),Array.isArray(I)&&(Jc(I),n.serverWindowNotices=I),Array.isArray(R)){const K=n.desktopIcons;p(R),n.desktopIcons=R,Ji("desktop-icons",K,R)}}}const _k=8e3;function Ek(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:d,syncServerTitleBarButtons:c,syncServerUnfocusEffects:l,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:p,renderIcons:f,syncShortcuts:h}=e,m=kk({applyDockItems:T=>t?.applyDockItems(T),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:d,syncServerTitleBarButtons:c,syncServerUnfocusEffects:l,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:p,renderIcons:f,syncShortcuts:h});let w=typeof o.menuSig=="string"?o.menuSig:"",g=!1;const x=()=>{if(!o.adminUrl)return Promise.resolve();const T=(()=>{try{const y=new URL("admin.php",o.adminUrl);return y.searchParams.set("desktop_mode_chromeless","1"),y.searchParams.set("desktop_mode_menu_refresh","1"),y.toString()}catch{return null}})();return T?new Promise(y=>{const k=document.createElement("iframe");k.setAttribute("aria-hidden","true"),k.tabIndex=-1,k.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",k.src=T;let N=!1;const b=()=>{N||(N=!0,window.clearTimeout(D),window.removeEventListener("message",L),k.parentNode&&k.parentNode.removeChild(k),y())},L=C=>{if(C.source!==k.contentWindow)return;const S=C.data;!S||S.type!=="desktop-mode-plugins-changed"||b()},D=window.setTimeout(()=>{A(v.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),b()},_k);window.addEventListener("message",L),document.body.appendChild(k)}):Promise.resolve()};return window.addEventListener("message",T=>{if(T.origin!==Pu)return;const y=T.data;if(y){if(y.type==="desktop-mode-plugins-changed"){y.payload&&(m(y.payload),typeof y.payload.menuSig=="string"&&(w=y.payload.menuSig));return}if(y.type==="desktop-mode-menu-signature"){const k=y.sig;typeof k=="string"&&k!==""&&k!==w&&!g&&(g=!0,x().finally(()=>{g=!1}))}}}),x}function Sk(e){if(!e)return!1;if(Array.isArray(e.windows)&&e.windows.length>0)return!0;if(typeof e.updated!="number"||e.updated<=0||!Array.isArray(e.desktops)||e.desktops.length===0)return!1;if(e.desktops.length>1)return!0;const t=e.desktops[0];return t?.id&&t.id!=="desktop-1"?!0:!!e.activeDesktop&&e.activeDesktop!=="desktop-1"}async function Ik(e,t,n){const o=n.getBoundingClientRect();Array.isArray(t.session.desktops)&&t.session.desktops.length>0&&e.seedDesktops(t.session.desktops,t.session.activeDesktop||t.session.desktops[0].id);for(const s of t.session.windows){const i=Wu(s,o),r=Zi(s.url,t),a=await e.open({id:s.id,baseId:s.baseId||s.id,desktopId:s.desktopId,multi:!!r?.multi,url:s.url,parentUrl:r?.url??s.url,title:s.title,icon:s.icon||"dashicons-admin-generic",x:i.x,y:i.y,width:i.width,height:i.height,initialState:s.state,submenu:r?.submenu});if(Array.isArray(s.externalTabs))for(const d of s.externalTabs)d&&typeof d.url=="string"&&d.url!==""&&a.addExternalTab(d.url,typeof d.label=="string"&&d.label!==""?d.label:d.url)}if(t.session.focused){const s=e.getById(t.session.focused);s&&e.focus(s)}}async function xk(e,t){if(mt(t.currentPage))return;const n=ne(t.currentPage,t.adminUrl),o=Zi(t.currentPage,t);await e.open({id:n,baseId:n,multi:!!o?.multi,url:t.currentPage,parentUrl:o?.url??t.currentPage,title:t.currentTitle,icon:t.currentIcon,submenu:o?.submenu})}function Ck(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function Qi(e,t,n,o){const s=Dd(t,n),i=window.fetch(t,s);if(o?.silent)return i;let r=o?.window;return!r&&o?.windowId&&(r=e.getById(o.windowId)??null),r||(r=e.getFocused()),r&&typeof r.trackActivity=="function"&&r.trackActivity(i).catch(()=>{}),i}const Ak=500;function Lk(e,t){let n=null,o=!1;const s=async()=>{if(o)return;const a=e.snapshot();o=!0;try{await Qi(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:a}),keepalive:!0},{silent:!0})}catch(d){A(v.SHELL_ERROR,{scope:"session-save",error:d})}finally{o=!1}},i=()=>{n!==null&&(clearTimeout(n),n=null);const a=e.snapshot(),d=new Blob([JSON.stringify({session:a})],{type:"application/json"}),c=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);navigator.sendBeacon&&navigator.sendBeacon(c,d)||s()},r=()=>{n!==null&&clearTimeout(n),n=window.setTimeout(()=>{n=null,s()},Ak)};return window.addEventListener("pagehide",i),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&i()}),r}const Tk=120;function Nk(e){document.addEventListener("desktop-mode-window-opened",e),document.addEventListener("desktop-mode-window-closed",e),document.addEventListener("desktop-mode-window-focused",e),document.addEventListener("desktop-mode-window-changed",e),G(v.DESKTOP_CREATED,"desktop-mode/session-save",e),G(v.DESKTOP_CLOSED,"desktop-mode/session-save",e),G(v.DESKTOP_SWITCHED,"desktop-mode/session-save",e)}function Dk(){const e=document.getElementById("desktop-mode-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;A(v.SHELL_RESIZED,{width:o?Math.round(o.width):window.innerWidth,height:o?Math.round(o.height):window.innerHeight})};window.addEventListener("resize",()=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(n,Tk)}),document.addEventListener("visibilitychange",()=>{A(v.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function Ok(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return j(v.DOCK_TILE_CLASS,e,o)}function Rk(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return j(v.DOCK_TILE_ELEMENT,e,o)}function Mk(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return j(v.DOCK_TILE_TOOLTIP,e,o)}function Wk(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};A(v.DOCK_TILE_RENDERED,{...o,el:e})}const Pk=[".desktop-mode-dock","#desktop-mode-dock","#desktop-mode-side-dock",".desktop-mode-dock__tooltip",".desktop-mode-dock-submenu"].join(","),er=new Set;function $k(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(Pk))return!0;for(const n of er)if(t.closest(n))return!0;return!1}function Uk(e){return typeof e!="string"||e.trim()===""?()=>{}:(er.add(e),()=>{er.delete(e)})}const Ze=new Map,Hk=window.location.origin;function $u(e){let t=Ze.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},Ze.set(e,t)),Bk(e,t),t}function Bk(e,t){const n=tr(e);if(!n||t.loadHandlerTarget===n&&t.loadHandler||(t.loadHandlerTarget&&t.loadHandler&&typeof t.loadHandlerTarget.removeEventListener=="function"&&t.loadHandlerTarget.removeEventListener("load",t.loadHandler),typeof n.addEventListener!="function"))return;const o=()=>{queueMicrotask(()=>Gt(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function Fk(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function tr(e){const t=window.wp?.desktop?.windowManager;if(t&&typeof t.getById=="function"){const o=t.getById(e);if(o?.iframe)return o.iframe;if(o?.element){const s=o.element.querySelector("iframe");if(s)return s}}return document.getElementById(`wp-window-${e}`)?.querySelector("iframe")??null}function zk(e){const t={};for(const[n,o]of e.headers){const s=[];for(const i of o){let r;try{r=typeof i.value=="function"?i.value():i.value}catch{continue}typeof r=="string"&&r!==""&&s.push(r)}s.length>0&&(t[n]=s.join(", "))}return t}function Gt(e){const t=tr(e);if(!t||!t.contentWindow)return;const n=Ze.get(e),o=n?zk(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"desktop-mode-instrument-set",headers:o,observe:s},Hk)}catch{}}G(v.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&Ze.has(t.windowId)&&Gt(t.windowId)}),G(v.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=Ze.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const dt=new Map,Gk=1e3;function Uu(e,t,n){const o=dt.get(e);if(!o||o.inflight)return;o.inflight=!0;const s=new URL(t+"desktop-mode/v1/debug",window.location.origin);s.searchParams.set("sessionId",e),s.searchParams.set("since",String(o.cursor));for(const r of o.channels.keys())s.searchParams.append("channels[]",r);const i=s.toString();fetch(i,{credentials:"same-origin",headers:{"X-WP-Nonce":n}}).then(r=>r.ok?r.json():{events:[],cursor:o.cursor}).then(r=>{if(o.inflight=!1,!!dt.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const d=o.channels.get(a.channel);if(d)for(const c of d)try{c(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=dt.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>Uu(e,t,n),Gk))})}function jk(){const e=window.desktopModeConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function qk(e,t){const n=dt.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let Vk=0;const Hu={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=$u(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),Gt(e),()=>{const r=Ze.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const d=a.indexOf(s);d>=0&&a.splice(d,1),a.length===0&&r.headers.delete(t),Gt(e),Bu(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=$u(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,Gt(e)),()=>{const i=Ze.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),Gt(e)),Bu(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=tr(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=Hu.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",d=new URL(a,window.location.origin);d.searchParams.set(i,t),o.src=d.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const e=window.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(e,t,n){qk(e,{id:++Vk,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=dt.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},dt.set(e,o));let i=o.channels.get(t);if(i||(i=new Set,o.channels.set(t,i)),i.add(n),s){const r=jk();r&&Uu(e,r.restUrl,r.restNonce)}return()=>{const r=dt.get(e);if(!r)return;const a=r.channels.get(t);a&&(a.delete(n),a.size===0&&r.channels.delete(t)),r.channels.size===0&&(r.timer&&clearTimeout(r.timer),dt.delete(e))}}}};function Bu(e){const t=Ze.get(e);t&&t.headers.size===0&&t.observers.size===0&&(Fk(t),Ze.delete(e))}async function Fu(e){return await Os(Rs()),new Promise(t=>{const n=document.createElement("wpd-confirm-dialog");n.setAttribute("open",""),e.title&&n.setAttribute("title",e.title),n.setAttribute("message",e.message),e.confirmLabel&&n.setAttribute("confirm-label",e.confirmLabel),e.cancelLabel&&n.setAttribute("cancel-label",e.cancelLabel),e.danger&&n.setAttribute("danger",""),e.hideCancel&&n.setAttribute("hide-cancel",""),e.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),t(i)};n.addEventListener("wpd-confirm",()=>o(!0)),n.addEventListener("wpd-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}function Kk(e){const t=[];for(const d of e.getVisibleRects()){if(d.state==="minimized"||d.element.offsetParent===null)continue;const c=d.element.getBoundingClientRect();t.push({id:`window:${d.windowId}`,kind:"window",rect:zu(c),face:"top",element:d.element})}const n=document.getElementById("desktop-mode-shell");if(n){const d=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:d.left,y:d.bottom-1,width:d.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".desktop-mode-dock");let s=0;for(const d of Array.from(o)){const c=d.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const l=d.getAttribute("data-desktop-mode-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,l==="bottom"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:c.width,height:1},face:"top",element:d}):l==="right"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:d}):t.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:d})}const i=document.querySelectorAll(".desktop-mode-widgets__card");let r=0;i.forEach(d=>{const c=d.getBoundingClientRect();if(c.width===0&&c.height===0)return;const l=d.dataset.widgetId??String(r++);t.push({id:`widget:${l}`,kind:"widget",rect:zu(c),face:"top",element:d})});const a=j(v.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function zu(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const Yk="__desktop_modeKeyedListKey",Xk="__desktop_modeKeyedListData";function Zk(e){const t=e.__desktop_modeKeyedList;if(t)return t;const n={byKey:new Map};return e.__desktop_modeKeyedList=n,n}function Jk(e,t,n){const o=Zk(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const d of t){const c=String(n.keyOf(d));a.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),a.add(c);const l=s.get(c);if(l){const p=l.data;n.updateItem?.(l.el,d,p),l.data=d,i.set(c,l),r.push(l.el);continue}const u=n.buildItem(d);u[Yk]=c,u[Xk]=d,i.set(c,{el:u,data:d}),r.push(u)}for(const[d,c]of s)i.has(d)||c.el.remove();for(let d=0;d<r.length;d++){const c=r[d],l=e.children[d];l!==c&&e.insertBefore(c,l??null)}o.byKey=i}function Qk(e){const t=e.__desktop_modeKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__desktop_modeKeyedList}}function e_(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:d=L=>{typeof console<"u"&&console.error("[desktop-mode] createInfiniteList:",L)}}=e;let c=e.sentinel??null;c||(c=document.createElement("div"),c.dataset.wpdInfiniteListSentinel="",c.style.height="1px",t.appendChild(c));const l=new Set;let u=r,p=!0,f=!1,h=null,m=0,w=!1,g=null;const x=L=>{if(f!==L){f=L;try{a(L)}catch(D){d(D)}}},T=()=>{g&&(g.disconnect(),g=null)},y=()=>{g||!c||w||(g=new IntersectionObserver(L=>{for(const D of L)D.isIntersecting&&k()},{rootMargin:i}),g.observe(c))},k=async()=>{if(w||f||!p)return;x(!0),h=new AbortController;const L=h;try{const D=await n(u,L.signal);if(w||L!==h)return;let C=0;const S=document.createDocumentFragment();for(const I of D.items??[]){const R=String(o(I));if(l.has(R))continue;l.add(R);const F=s(I,m+C);S.appendChild(F),C++}C>0&&(c&&c.parentNode===t?t.insertBefore(S,c):t.appendChild(S),m+=C),u=D.nextCursor??null,u||(p=!1,T())}catch(D){if(D?.name==="AbortError")return;d(D)}finally{L===h&&(x(!1),h=null)}},N=()=>{if(w)return;h?.abort(),h=null,l.clear(),u=r,p=!0,m=0;const L=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);L&&c&&t.appendChild(c),x(!1),y(),k()},b=()=>{w||(w=!0,T(),h?.abort(),h=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,x(!1))};return y(),k(),{reset:N,loadMore:k,hasMore:()=>p,isLoading:()=>f,destroy:b}}const t_=520,n_=720,o_=500;function s_(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[desktop-mode] startOAuth requires a non-empty service slug."));const n=r_(),o=a_();return ze(wn(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:e})},{source:"desktop-mode/oauth-start"}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`[desktop-mode] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>i_(s,e,t))}function i_(e,t,n){return new Promise((o,s)=>{const i=n.width??t_,r=n.height??n_,a=Math.max(0,Math.floor((window.screen.width-i)/2)),d=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${d}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),l=window.open(e.authorize_url,`desktop-mode-oauth-${t}`,c);if(!l){s(new Error("[desktop-mode] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let p=null,f=!1;const h=()=>{f||(f=!0,window.removeEventListener("message",m),p!==null&&(window.clearInterval(p),p=null))},m=w=>{if(w.origin!==u)return;const g=w.data;if(!g||g.type!=="desktop-mode-oauth-callback")return;const x=g.payload;if(h(),x&&x.ok)o(x);else{const T=x?.reason??"unknown",y=x?.message??"OAuth flow failed",k=new Error(`[desktop-mode] startOAuth(${t}) failed: ${T} — ${y}`);k.cause=x,s(k)}};window.addEventListener("message",m),p=window.setInterval(()=>{l.closed&&(h(),s(new Error(`[desktop-mode] startOAuth(${t}) cancelled — popup closed before completing.`)))},o_)})}function Gu(){return window.desktopModeConfig??{}}function r_(){const e=Gu().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function a_(){const e=Gu().restNonce;return typeof e=="string"&&e!==""?e:null}const d_=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","icons","files","confirm","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","openNewWindow","cloneTemplate","onWindow","createInfiniteList","startOAuth","repaintLoadingOverlays","loadVendorScript","getWallpaperSurfaces","registerModule","loadModules","whenReady","ready","isReady","setDefaultWindow","refreshMenu","config","ai","dragBridge","dragManager","registerCommand","unregisterCommand","listCommands","registerDestructiveAdminAction","unregisterDestructiveAdminAction","listDestructiveAdminActions","registerSettingsTab","unregisterSettingsTab","listSettingsTabs","registerDockRailRenderer","unregisterDockRailRenderer","listDockRailRenderers","openOsSettings","getOsSettings","subscribeOsSettings","updateOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","renderIcon","applyTileClasses","applyTileElement","applyTileTooltip","dispatchTileRendered","isDockElement","registerDockSelector","registerTitleBarButton","unregisterTitleBarButton","listTitleBarButtons","registerUnfocusEffect","unregisterUnfocusEffect","listUnfocusEffects","relations","registerWindowLinkRenderer","unregisterWindowLinkRenderer","listWindowLinkRenderers","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","getConnection","broadcast","subscribe","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","debug","fetch"]);function c_(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:d,registerWindow:c,openWindowById:l,openNewWindowById:u,placeSystemTile:p,setDefaultWindow:f,refreshMenu:h,openOsSettings:m,aiAssistant:w,dragBridge:g,dragManager:x,connect:T,getConnection:y,config:k}=e,N={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,icons:i,files:r,confirm:Fu,saveSession:a,hooks:Uf(),HOOKS:v,isActive:()=>!!document.getElementById("desktop-mode-shell"),registerWallpaper:b=>{fn(b),s.apply()},registerWidget:b=>{Li(b)},widgetLayer:d,widgets:{redock:b=>{d?.redock(b)}},loadVendorScript:Ee,getWallpaperSurfaces:()=>Kk(t),registerWindow:c,openWindow:l,openNewWindow:u,fetch:(b,L,D)=>Qi(t,b,L,D),repaintLoadingOverlays:dd,cloneTemplate:Oi,onWindow:Fy,createInfiniteList:e_,startOAuth:s_,registerSystemTile:b=>{p(b),A(v.DOCK_ITEM_APPENDED,{id:b.id})},registerModule:ec,loadModules:tc,whenReady:ga,ready:ga,isReady:Bf,setDefaultWindow:f,refreshMenu:h,config:k,ai:w,dragBridge:g,dragManager:x,registerCommand:zo,unregisterCommand:rc,listCommands:ac,registerDestructiveAdminAction:Zm,unregisterDestructiveAdminAction:ud,listDestructiveAdminActions:Jm,registerSettingsTab:cc,unregisterSettingsTab:lc,listSettingsTabs:uc,registerDockRailRenderer:Rd,unregisterDockRailRenderer:Wh,listDockRailRenderers:$h,openOsSettings:m,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:b=>s.subscribeOsSettings(b),updateOsSettings:(b,L={})=>{if(typeof b.wallpaper=="string"&&(s.state.wallpaper=b.wallpaper),typeof b.accent=="string"&&(s.state.accent=b.accent),typeof b.dockSize=="string"&&(s.state.dockSize=b.dockSize),typeof b.desktopLayout=="string"&&(s.state.desktopLayout=b.desktopLayout),typeof b.dockRailRenderer=="string"&&(s.state.dockRailRenderer=b.dockRailRenderer),typeof b.windowLinkRenderer=="string"&&(s.state.windowLinkRenderer=b.windowLinkRenderer),(b.windowLinkVisibility==="focus"||b.windowLinkVisibility==="always"||b.windowLinkVisibility==="off")&&(s.state.windowLinkVisibility=b.windowLinkVisibility),typeof b.windowLinksEnabled=="boolean"&&(s.state.windowLinksEnabled=b.windowLinksEnabled),typeof b.windowLinkRaiseOnFocus=="boolean"&&(s.state.windowLinkRaiseOnFocus=b.windowLinkRaiseOnFocus),typeof b.windowLinkHighlight=="boolean"&&(s.state.windowLinkHighlight=b.windowLinkHighlight),b.ai&&typeof b.ai=="object"&&(s.state.ai={...s.state.ai,...b.ai}),typeof b.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=b.nativePostsEnabled),typeof b.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=b.nativePagesEnabled),typeof b.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=b.nativeUsersEnabled),typeof b.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=b.nativePluginsEnabled),typeof b.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=b.nativeCommentsEnabled),typeof b.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=b.foldersSharingEnabled),typeof b.developerModeEnabled=="boolean"&&(s.state.developerModeEnabled=b.developerModeEnabled),Array.isArray(b.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=b.nativePostsHiddenColumns.filter(D=>typeof D=="string"&&D!=="").slice(0,32)),b.itemVisibility&&typeof b.itemVisibility=="object"){const D=["both","dock","desktop","hidden"],C={};for(const[S,I]of Object.entries(b.itemVisibility))typeof S!="string"||S===""||typeof I!="string"||!D.includes(I)||(C[S]=I);s.state.itemVisibility=C}if(Array.isArray(b.dockOrder)&&(s.state.dockOrder=b.dockOrder.filter(D=>typeof D=="string"&&D!=="").slice(0,256)),b.dockPromotedPositions&&typeof b.dockPromotedPositions=="object"){const C={};for(const[S,I]of Object.entries(b.dockPromotedPositions)){if(typeof S!="string"||S===""||!I||typeof I!="object")continue;const R=I;if(!(typeof R.x!="number"||typeof R.y!="number"||!Number.isFinite(R.x)||!Number.isFinite(R.y)||Math.abs(R.x)>1e5||Math.abs(R.y)>1e5)&&(C[S]={x:R.x,y:R.y},Object.keys(C).length>=256))break}s.state.dockPromotedPositions=C}s.save(L),(b.itemVisibility||b.dockOrder)&&o?.refresh()},deriveWindowId:(b,L)=>ne(b,L??k.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:b=>o?.getSystemTile(b)??null,getMenuItems:()=>o?.getMenuItems()??[],renderIcon:Ri,applyTileClasses:Ok,applyTileElement:Rk,applyTileTooltip:Mk,dispatchTileRendered:Wk,isDockElement:$k,registerDockSelector:Uk,registerTitleBarButton:mc,unregisterTitleBarButton:Xw,listTitleBarButtons:Jw,registerUnfocusEffect:jo,unregisterUnfocusEffect:pg,listUnfocusEffects:hi,relations:ah,registerWindowLinkRenderer:gc,unregisterWindowLinkRenderer:eg,listWindowLinkRenderers:yc,registerWindowTheme:Oc,unregisterWindowTheme:Rc,listWindowThemes:Mc,applyWindowTheme:(b,L)=>{const D=t.getById(b);D&&D.setAppearanceTheme(L)},registerWindowControl:xn,unregisterWindowControl:$c,listWindowControls:Uc,applyWindowControls:(b,L)=>{const D=t.getById(b);D&&D.setAppearanceControls(L)},registerWindowSlot:zc,unregisterWindowSlot:ki,listWindowSlots:Gc,applyWindowSlot:(b,L,D)=>{const C=t.getById(b);C&&C.setAppearanceSlot(L,D)},registerWindowNotice:Xc,unregisterWindowNotice:Ii,listWindowNotices:Zc,dismissWindowNotice:Mg,undismissWindowNotice:Wg,registerWindowChrome:Ug,unregisterWindowChrome:tl,listWindowChromes:nl,applyWindowChrome:(b,L)=>{const D=t.getById(b);D&&D.setAppearanceChrome(L)},connect:T,getConnection:y,broadcast:Ol,subscribe:We,registerPalette:xu,unregisterPalette:Qv,listPalettes:ek,openPalette:Au,devtools:Hu,createSharedStore:re,presence:pk,activity:ye,heartbeat:Xe,showToast:ee,notify:Qb,pwa:{promptInstall:Zb,undismissInstallHint:Jb,getState:Pn,subscribe:Fl,requestNotificationPermission:ev,getNotificationPermission:tv},renderKeyedList:Jk,clearKeyedList:Qk,registerNamespace:(b,L)=>{if(typeof b!="string"||b===""){console.warn("[desktop-mode] registerNamespace: name must be a non-empty string");return}if(!L||typeof L!="object"){console.warn(`[desktop-mode] registerNamespace("${b}"): api must be an object`);return}if(d_.has(b)){console.warn(`[desktop-mode] registerNamespace("${b}"): name is reserved by the shell — pick a plugin-specific key`);return}N[b]=L},getWindowConfig:b=>{const L=window.desktopModeWindowConfig;if(!L||typeof L!="object")return;const D=L[b];return D===void 0?void 0:D},debug:{window:b=>{const L=(k.nativeWindows??[]).find(F=>F.id===b);if(!L)return null;const D=L.scriptUrl||"";let C="unknown",S=!1;D&&(document.querySelector(`script[data-desktop-mode-vendor="${D.replace(/"/g,'\\"')}"]`)?(C="lazy",S=!0):Array.from(document.querySelectorAll("script[src]")).find(X=>X.src===D)&&(C="eager",S=!0));const I=window.desktopModeWindowConfig,R=!!(I&&typeof I=="object"&&Object.prototype.hasOwnProperty.call(I,b));return{id:b,scriptHandle:L.scriptHandle||"",scriptUrl:D,loadPath:C,tagInDom:S,configPresent:R,extras:{hasTranslations:!!L.scriptTranslations,l10nCount:(L.scriptL10n??[]).length,beforeCount:(L.scriptBefore??[]).length,afterCount:(L.scriptAfter??[]).length}}}}};return N}function l_(e){if(window.wp||(window.wp={}),!window.wp.desktop){window.wp.desktop=e;return}Object.assign(window.wp.desktop,e)}const nr=re("desktop-mode/layout",()=>({layout:"classic"}));function ju(e){nr.state.layout!==e&&(nr.state.layout=e,nr.notify())}class qu{constructor(t){this.shape=t}title(){return this.shape.title}icon(){return this.shape.icon}previewUrl(){return this.shape.previewUrl}ref(){return this.shape.ref}exists(){return this.shape.exists}}class u_ extends qu{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const Bn=new Map,or=new Set;function $e(e){if(!e.type)throw new Error("[desktop-mode] registerType: `type` is required.");if(!e.label)throw new Error("[desktop-mode] registerType: `label` is required.");Bn.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),A("desktop-mode.files.type-registered",e.type,e),Ku()}function p_(e){Bn.delete(e)&&(A("desktop-mode.files.type-unregistered",e),Ku())}function f_(e){const t=Bn.get(e);return t||null}function Vu(){const e=Array.from(Bn.values()).slice(),t=j("desktop-mode.files.types",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>o.sort!==s.sort?o.sort-s.sort:o.label.localeCompare(s.label)),n}function is(e){const t=Bn.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new u_(e,e.type)}function m_(e){return or.add(e),()=>or.delete(e)}function Ku(){for(const e of or)try{e()}catch(t){console.error("[desktop-mode] files registry subscriber threw:",t)}}const rs=new Map,sr=new Set;let ir={};function Yu(e){ir={...e},cr()}function rr(){return{...ir}}function Ue(e){if(!e.id)throw new Error("[desktop-mode] registerOpener: `id` is required.");if(!e.label)throw new Error("[desktop-mode] registerOpener: `label` is required.");if(!Array.isArray(e.types)||e.types.length===0)throw new Error("[desktop-mode] registerOpener: `types` must be a non-empty array.");if(!e.handler||typeof e.handler!="object")throw new Error("[desktop-mode] registerOpener: `handler` is required.");rs.set(e.id,{id:e.id,label:e.label,types:e.types.slice(),isDefault:!!e.isDefault,sort:typeof e.sort=="number"?e.sort:100,handler:e.handler}),A("desktop-mode.files.opener-registered",e.id,e),cr()}function h_(e){rs.delete(e)&&(A("desktop-mode.files.opener-unregistered",e),cr())}function w_(e){return rs.get(e)??null}function Xu(){const e=Array.from(rs.values()).slice(),t=j("desktop-mode.files.openers",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>{const i=typeof o.sort=="number"?o.sort:100,r=typeof s.sort=="number"?s.sort:100;return i!==r?i-r:o.label.localeCompare(s.label)}),n}function ar(e){return Xu().filter(t=>t.types.includes(e))}function dr(e){const t=ar(e);if(t.length===0)return null;const n=ir[e];let o=null;return n&&(o=t.find(i=>i.id===n)??null),o||(o=t.find(i=>i.isDefault)??null),o||(o=t[0]),j("desktop-mode.files.resolve-opener",o,e)??null}function g_(e){return sr.add(e),()=>sr.delete(e)}function cr(){for(const e of sr)try{e()}catch(t){console.error("[desktop-mode] openers subscriber threw:",t)}}let Fn=null;function y_(e){Fn=e}async function lr(e,t){if(!Fn)return console.warn("[desktop-mode] wp.desktop.files.open() called before the shell installed open deps. The file will not open."),!1;const n=dr(e.type());if(!n)return A("desktop-mode.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;A("desktop-mode.files.opening",{file:e,openerId:n.id});try{const o=n.handler;if(o.kind==="url"){const s=await o.url(e);if(!s)return!1;const i=o.windowId?o.windowId(e):Fn.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),d=Fn.openUrl({id:i,url:s,title:r,icon:a});return A("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"url"}),d}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=Fn.openNativeWindow(o.windowId,s);return A("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),A("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return A("desktop-mode.files.open-failed",{reason:"handler-threw",type:e.type(),ref:e.ref(),openerId:n.id,error:o}),console.error("[desktop-mode] file opener threw:",o),!1}}function b_(){$e({type:"shortcut",label:"Plugin shortcut",sort:1}),$e({type:"folder",label:"Folder",sort:5}),$e({type:"post",label:"Post",sort:10}),$e({type:"attachment",label:"Media",sort:20}),$e({type:"user",label:"User",sort:30}),$e({type:"term",label:"Taxonomy term",sort:40}),$e({type:"comment",label:"Comment",sort:50}),$e({type:"bookmark",label:"Bookmark",sort:60}),$e({type:"link",label:"Web link",sort:70}),$e({type:"embed",label:"Embedded web window",sort:80})}let ur=null;function Zu(e){ur=e}function Ju(){if(!ur)throw new Error("[desktop-mode] files REST client called before installRestDeps().");return ur}class pr extends Error{constructor(t){super(`Row was changed by ${t.actor.name||"another session"} (parent="${t.current.parentName}")`),this.name="FilesConflictError",this.status=409,this.detail=t}}async function we(e,t){const{baseUrl:n,nonce:o}=Ju(),s=wn(n,e),i=new Headers(t.headers??{});i.set("X-WP-Nonce",o),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await ze(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),a=await r.text();let d=null,c=null;if(a)try{d=JSON.parse(a)}catch(l){d=null,c=l}if(!r.ok){if(r.status===409){const u=d?.data?.data??d?.data;if(u&&typeof u=="object")throw new pr(u)}const l=d;throw new Error(`[desktop-mode] files REST ${r.status}: ${l?.code??""} ${l?.message??""}`.trim())}if(d===null){if(c&&a){const l=a.slice(0,120).replace(/\s+/g," ");throw new Error(`[desktop-mode] files REST ${r.status} returned non-JSON body — ${c.message}. First 120 chars: ${l}`)}throw new Error(`[desktop-mode] files REST ${r.status}: empty or unparseable body.`)}return d}function Me(e=0){return we(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function jt(e){return we("/placements",{method:"POST",body:JSON.stringify(e)})}function qt(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),we(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Qu(e){return we(`/placements/${e}`,{method:"DELETE"})}async function fr(e,t){const{baseUrl:n,nonce:o}=Ju(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await ze(i,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o},credentials:"same-origin",body:JSON.stringify({items:[{id:e,type:t}]})},{source:"desktop-mode/files"});if(!r.ok)throw new Error(`[desktop-mode] restore ${r.status}`);return await r.json()}function ep(){return we("/folders",{method:"GET"})}function mr(e){return we("/folders",{method:"POST",body:JSON.stringify(e)})}function tp(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),we(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function np(e){return we(`/folders/${e}`,{method:"DELETE"})}function op(e){return we("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function sp(e){return we(`/folders/${e}/shares`,{method:"GET"})}function ip(e,t){return we(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function rp(e,t,n){return we(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function ap(e,t){return we(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function dp(e,t){return we(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function cp(e,t){return we(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function lp(e){return we(`/folders/${e}/leave`,{method:"POST"})}function v_(){return we("/folder-sharing-tables/purge",{method:"POST"})}const k_=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:pr,acceptShare:dp,createFolder:mr,createPlacement:jt,deleteFolder:np,deletePlacement:Qu,denyShare:cp,installRestDeps:Zu,inviteShare:ip,leaveShare:lp,listFolders:ep,listPlacements:Me,listShares:sp,purgeFolderSharingTables:v_,restoreTrashedItem:fr,revokeShare:ap,saveAssociations:op,updateFolder:tp,updatePlacement:qt,updateShareCapability:rp},Symbol.toStringTag,{value:"Module"})),__="desktop-mode/files";function Je(){return re(__,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function Vt(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("desktop-mode-files-changed",{detail:{source:"local",...e}}))}function Kt(e,t){const n=Je(),o=new Map(n.state.placementsByFolder);o.set(e,t.slice());const s=new Set(n.state.hydratedFolders);s.add(e),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),Vt({kind:"placements-set",folderId:e})}function hr(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[desktop-mode] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=Je(),o=new Map(n.state.placementsByFolder);for(const[a,d]of o)if(d.findIndex(l=>l&&l.id===e.id)>=0&&a!==e.parentId){const l=d.filter(Boolean),u=l.findIndex(p=>p.id===e.id);u>=0&&l.splice(u,1),o.set(a,l)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),Vt({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function as(e,t="local"){const n=Je(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(d=>d&&d.id===e)>=0){const d=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,d),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),Vt({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function up(e){const t=Je(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),Vt({kind:"folders-set"})}function wr(e,t="local"){const n=Je(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),Vt({kind:"folder-upserted",folderRowId:e.id,source:t})}function gr(e,t="local"){const n=Je(),o=new Map(n.state.folders);o.delete(e);const s=new Map(n.state.placementsByFolder);s.delete(e),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),Vt({kind:"folder-removed",folderRowId:e,source:t})}function yr(e){return Je().subscribe(e)}function Et(){return Je().getState()}const J={getState:Et,subscribe:yr,setFolderPlacements:Kt,upsertPlacement:hr,upsertFolder:wr,removePlacement:as,removeFolder:gr},E_=he`:host{display:inline-block}`,S_=he`:host{position:absolute;width:var( --wpd-ribbon-size,90px );height:var( --wpd-ribbon-size,90px );overflow:hidden;pointer-events:none;z-index:var( --wpd-ribbon-z,2 )}:host( [ hidden ] ){display:none}.banner{position:absolute;display:block;width:var( --wpd-ribbon-banner-width,140px );padding:var( --wpd-ribbon-padding,4px 0 );text-align:center;font:var( --wpd-ribbon-font,700 10px/1.4 var( --desktop-mode-font,system-ui ) );letter-spacing:var( --wpd-ribbon-tracking,0.06em );text-transform:uppercase;color:var( --wpd-ribbon-fg,#fff );background:var( --wpd-ribbon-bg,var( --wp-admin-theme-color,#2271b1 ) );box-shadow:var( --wpd-ribbon-shadow,0 2px 4px rgba( 0,0,0,0.2 ) )}:host(:not( [ placement ] ) ),:host( [ placement='top-end' ] ){inset-block-start:0;inset-inline-end:0}:host(:not( [ placement ] ) ) .banner,:host( [ placement='top-end' ] ) .banner{inset-block-start:var( --wpd-ribbon-banner-offset,20px );inset-inline-end:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host( [ placement='top-start' ] ){inset-block-start:0;inset-inline-start:0}:host( [ placement='top-start' ] ) .banner{inset-block-start:var( --wpd-ribbon-banner-offset,20px );inset-inline-start:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-end' ] ){inset-block-end:0;inset-inline-end:0}:host( [ placement='bottom-end' ] ) .banner{inset-block-end:var( --wpd-ribbon-banner-offset,20px );inset-inline-end:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-start' ] ){inset-block-end:0;inset-inline-start:0}:host( [ placement='bottom-start' ] ) .banner{inset-block-end:var( --wpd-ribbon-banner-offset,20px );inset-inline-start:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host(:not( [ placement ] ) ) .banner,:host-context( [ dir='rtl' ] ):host( [ placement='top-end' ] ) .banner{transform:rotate( -45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='top-start' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-end' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-start' ] ) .banner{transform:rotate( -45deg )}:host( [ tone='success' ] ) .banner{background:var( --wpd-ribbon-success,#1a7f37 )}:host( [ tone='warning' ] ) .banner{background:var( --wpd-ribbon-warning,#9a6700 )}:host( [ tone='danger' ] ) .banner{background:var( --wpd-ribbon-danger,#cf222e )}:host( [ tone='info' ] ) .banner{background:var( --wpd-ribbon-info,#0969da )}:host( [ tone='neutral' ] ) .banner{background:var( --wpd-ribbon-neutral,#57606a )}`,fo=class fo extends pe{render(){return z`<span class="banner" part="banner"><slot></slot></span>`}};fo.props=["placement","tone"],fo.styles=[S_],fo.help=void 0;let br=fo;me("wpd-ribbon",br);const te="desktop-mode-file-tile",pp={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function I_(){const e=window.wp?.desktop?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function x_(){return window.wp?.desktop?.dragManager??null}const C_=["type","ref","label","icon","thumbnail","kind","status","selected","missing","access-gated","drag-kind","drag-title","drag-icon"],tn=class tn extends pe{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this.click())},this.addEventListener("keydown",this._keydownHandler)),this._paint()}disconnectedCallback(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null),this._keydownHandler&&(this.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null)}requestUpdate(){this.isConnected&&this._paint()}render(){return z``}_paint(){const t=this.getAttribute("type")??"",n=this.getAttribute("ref")??"",o=this.getAttribute("label")??"",s=this.getAttribute("icon")??"",i=this.getAttribute("thumbnail")??"",r=this.getAttribute("kind")??"entry",a=this.getAttribute("status")??"",d=this.hasAttribute("selected"),c=this.hasAttribute("missing"),l=this.hasAttribute("access-gated"),u=[te,`${te}--folder`,`${te}--missing`,`${te}--access-gated`,`${te}--selected`];for(const w of u)this.classList.remove(w);this.classList.add(te),r==="folder"&&this.classList.add(`${te}--folder`),c&&this.classList.add(`${te}--missing`),l&&this.classList.add(`${te}--access-gated`),d&&this.classList.add(`${te}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role","listitem"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";l?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const f=[`${te}__visual`,`${te}__label`,`${te}__lock`];for(const w of f)this.querySelectorAll(`:scope > .${w}`).forEach(g=>g.remove());this.querySelectorAll(":scope > wpd-ribbon").forEach(w=>w.remove());const h=document.createElement("span");if(h.className=`${te}__visual`,i){const w=document.createElement("img");w.src=i,w.alt="",w.loading="lazy",w.decoding="async",w.className=`${te}__preview`,w.draggable=!1,h.appendChild(w)}else if(s){const w=Ri(s,{title:o,className:`${te}__icon`});h.appendChild(w)}this.appendChild(h);const m=document.createElement("span");if(m.className=`${te}__label`,m.textContent=o,this.appendChild(m),l){const w=document.createElement("span");w.className=`${te}__lock dashicons dashicons-lock`,w.setAttribute("aria-hidden","true"),this.appendChild(w)}if(a&&a!=="publish"&&pp[a]&&I_()){const w=document.createElement("wpd-ribbon");w.setAttribute("placement","top-end"),w.setAttribute("tone",A_(a)),w.textContent=pp[a],this.appendChild(w)}Gf(this),A("desktop-mode.tile.rendered",{tile:this}),this._wireDragOut()}_wireDragOut(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null);const t=this.getAttribute("drag-kind");if(!t)return;const n=o=>{if(o.button!==0)return;const s=x_();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,a=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,d=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-d.left,offsetY:o.clientY-d.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};tn.shadow=!1,tn.props=C_,tn.styles=[E_],tn.help=void 0;let vr=tn;function A_(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}me("wpd-tile",vr);function L_(e){const t=document.createElement("wpd-tile");if(t.setAttribute("type",e.type),t.setAttribute("ref",e.ref),t.setAttribute("label",e.label),e.icon&&t.setAttribute("icon",e.icon),e.thumbnail&&t.setAttribute("thumbnail",e.thumbnail),e.role&&t.setAttribute("kind",e.role),e.status&&t.setAttribute("status",e.status),e.missing&&t.setAttribute("missing",""),e.accessGated&&t.setAttribute("access-gated",""),e.dataset)for(const[o,s]of Object.entries(e.dataset))s!=null&&(t.dataset[o]=String(s));if(Array.isArray(e.extraClasses))for(const o of e.extraClasses)o&&t.classList.add(o);const n=j("desktop-mode.tile.class",t.className,e);return n&&n!==t.className&&(t.className=n),typeof e.x=="number"&&typeof e.y=="number"&&(t.style.position="absolute",t.style.left=`${e.x}px`,t.style.top=`${e.y}px`),t}function T_(e,t){const n=is(e.file),o=n.previewUrl(),s=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"",i=s!==""?s:n.title(),r=e.meta&&typeof e.meta.iconUrl=="string"?e.meta.iconUrl.trim():"";return{type:e.file.type,ref:e.file.ref,label:i,thumbnail:o||void 0,icon:o?void 0:r||n.icon(),x:e.x,y:e.y,dataset:{placementId:e.id,folderId:t},meta:e.meta,missing:!e.file.exists,accessGated:!!e.accessGated,ariaLabel:i}}function N_(e,t){const n=is(e.file),o=L_(T_(e,t)),s=j("desktop-mode.files.tile-class",te,e);s&&s!==te&&(o.className=s);const i=j("desktop-mode.files.tile-element",null,e);return i instanceof Element&&o.appendChild(i),o.addEventListener("dblclick",r=>{if(r.preventDefault(),r.stopPropagation(),e.accessGated){ee({message:`You don’t have permission to open "${e.file.title||n.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}lr(n,{placement:{id:e.id,x:e.x,y:e.y,meta:e.meta}})}),A("desktop-mode.files.tile-rendered",{tile:o,placement:e}),o}function Qe(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}function fp(e,t){const n=s=>{if(!(s.target instanceof Node&&e.contains(s.target))){if(s.target instanceof Node)for(const i of t.siblingSelectors??[]){const r=Array.from(document.querySelectorAll(i));for(const a of r)if(a.contains(s.target))return}t.excludeOutsideTarget&&s.target instanceof Node&&t.excludeOutsideTarget.contains(s.target)||t.close()}},o=s=>{s.key==="Escape"&&t.close()};return document.addEventListener("mousedown",n,{capture:!0}),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",n,{capture:!0}),document.removeEventListener("keydown",o)}}const D_="desktop-mode-wallpaper-menu";let zn=null;function kr(){zn&&(zn.dispatchEvent(new CustomEvent("tile-menu-closed")),zn.remove(),zn=null,A("desktop-mode.files.tile-menu.closed",{}))}let mp=0;function O_(e,t){kr();const n=++mp;sn(()=>n===mp,()=>R_(e,t))}function R_(e,{placement:t,items:n}){const o=j("desktop-mode.files.tile-menu",n.slice(),t),s=(Array.isArray(o)?o:n).slice().sort((c,l)=>{const u=typeof c.sort=="number"?c.sort:100,p=typeof l.sort=="number"?l.sort:100;return u!==p?u-p:c.label.localeCompare(l.label)});if(s.length===0)return;const i=document.createElement("wpd-context-menu");i.setAttribute("open",""),i.classList.add(D_),i.dataset.placementId=String(t.id),i.style.left=`${e.x}px`,i.style.top=`${e.y}px`;const r=new Map;for(const c of s){r.set(c.id,c);const l=document.createElement("wpd-context-menu-option");l.dataset.menuItemId=c.id,l.setAttribute("value",c.id),c.danger&&l.setAttribute("danger",""),c.disabled&&l.setAttribute("disabled",""),c.icon&&l.setAttribute("icon",M_(c.icon)),l.textContent=c.label,i.appendChild(l)}i.addEventListener("wpd-context-menu-pick",c=>{const l=c.detail,u=r.get(l.id);u&&(kr(),u.onClick(new MouseEvent("click")))}),document.body.appendChild(i),zn=i;const a=i.getBoundingClientRect();a.right>window.innerWidth&&(i.style.left=`${Math.max(0,window.innerWidth-a.width-8)}px`),a.bottom>window.innerHeight&&(i.style.top=`${Math.max(0,window.innerHeight-a.height-8)}px`);const d=fp(i,{close:()=>kr()});i.addEventListener("tile-menu-closed",d),A("desktop-mode.files.tile-menu.opened",{placementId:t.id,items:s.map(c=>c.id)})}function M_(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const ve="desktop-mode-create-folder-dialog";let Gn=null;function _r(){Gn&&(Gn.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),Gn.remove(),Gn=null,A("desktop-mode.files.create-folder.closed",{}))}function Er(e){if(_r(),j("desktop-mode.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${ve}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=ve,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${ve}-title`);const i=document.createElement("h2");i.id=`${ve}-title`,i.className=`${ve}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("label");r.className=`${ve}__label`,r.htmlFor=`${ve}-input`,r.textContent=e.label??"Folder name",s.appendChild(r);const a=document.createElement("input");a.type="text",a.id=`${ve}-input`,a.className=`${ve}__input`,a.value=n,a.setAttribute("autocomplete","off"),a.setAttribute("spellcheck","false"),s.appendChild(a);const d=document.createElement("p");d.className=`${ve}__error`,d.hidden=!0,d.setAttribute("role","alert"),s.appendChild(d);const c=document.createElement("div");c.className=`${ve}__actions`;const l=document.createElement("button");l.type="button",l.className=`${ve}__btn ${ve}__btn--secondary`,l.textContent="Cancel";const u=document.createElement("button");u.type="button",u.className=`${ve}__btn ${ve}__btn--primary`,u.textContent=e.submitLabel??"Create",c.appendChild(l),c.appendChild(u),s.appendChild(c),o.appendChild(s),document.body.appendChild(o),Gn=o,a.focus(),a.select(),A("desktop-mode.files.create-folder.opened",{});const p=g=>{a.disabled=g,l.disabled=g,u.disabled=g,s.classList.toggle(`${ve}--busy`,g)},f=g=>{d.textContent=g,d.hidden=!1},h=()=>{_r(),e.onCancel?.()},m=async()=>{const g=a.value.trim();if(!g){f("Please enter a name."),a.focus();return}d.hidden=!0,p(!0);try{await e.onSubmit(g),_r()}catch(x){p(!1),f(x instanceof Error?x.message:"Could not create the folder."),a.focus(),a.select()}};l.addEventListener("click",()=>h()),u.addEventListener("click",()=>void m()),o.addEventListener("click",g=>{g.target===o&&h()});const w=g=>{g.key==="Escape"?(g.preventDefault(),h()):g.key==="Enter"&&!g.isComposing&&(g.preventDefault(),m())};s.addEventListener("keydown",w),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",w)})}const Te=16,ct=96,jn=110;function qn(e,t){const n=Math.max(0,Math.round((e-Te)/ct)),o=Math.max(0,Math.round((t-Te)/jn));return Yt(n,o)}function Yt(e,t){return{col:e,row:t,x:Te+e*ct,y:Te+t*jn}}function St(e,t,n,o){const s=qn(e,t);if(!n.has(ke(s.col,s.row)))return s;const i=o?Math.max(1,Math.floor((o.clientHeight-Te)/jn)):999;for(let r=0;r<999;r++)for(let a=0;a<i;a++)if(!n.has(ke(r,a)))return Yt(r,a);return s}function hp(e,t){const n=t?Math.max(1,Math.floor((t.clientWidth-Te)/ct)):4,o=Math.max(1,n);for(let s=0;s<999;s++)for(let i=0;i<o;i++)if(!e.has(ke(i,s)))return Yt(i,s);return Yt(0,0)}function wp(e,t){const n=new Set;for(const o of e){const s=qn(o.x,o.y);n.add(ke(s.col,s.row))}return n}function ke(e,t){return`${e},${t}`}function gp(e){return e instanceof pr}function W_(e){const t=e.detail.actor.name||"Someone else",n=e.detail.current.parentName||"another folder";return e.detail.reason==="trashed"?"This item is in the recycle bin.":e.detail.reason==="forbidden"?"You no longer have access.":e.detail.reason==="gone"?"This item was deleted.":`${t} moved this to "${n}".`}function yp(e){const t=W_(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{const s=`desktop-mode-folder-${n}`,i=window.desktopMode?.windowManager;i?.focus&&i.focus(s)||i?.open&&i.open(s)}}),ee({message:t,action:o,duration:7e3})}function ds(e,t,n){window.wp?.desktop?.broadcast?.(`desktop-mode.${e}.changed`,{source:"desktop-files",action:t,ids:n})}function bp(e){const t=window.wp?.desktop;if(!t?.showToast)return;const o=(e instanceof Error?e.message:String(e)).replace(/^\[desktop-mode\][^:]*:\s*/,"").replace(/^desktop_mode_files_[a-z_]+\s*/,"");t.showToast({message:o||"Could not move this item to the recycle bin.",duration:5e3})}function vp(e,t){const n=window.wp?.desktop;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function kp(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";J.removePlacement(t);try{await Qu(t),ds(s,"trashed",[t]),vp(`"${o}" moved to Trash`,async()=>{try{await fr(t,"placement");const i=await Me(n);J.setFolderPlacements(n,i.placements),ds(s,"untrashed",[t])}catch(i){console.error("[desktop-mode] restore failed:",i)}})}catch(i){console.error("[desktop-mode] deletePlacement failed:",i),bp(i),Me(n).then(r=>{J.setFolderPlacements(n,r.placements)})}}async function _p(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";J.removePlacement(n),J.removeFolder(t);try{await np(t),ds("folder","trashed",[t]),vp(`"${s}" moved to Trash`,async()=>{try{await fr(t,"folder");const i=await Me(o);J.setFolderPlacements(o,i.placements),ds("folder","untrashed",[t])}catch(i){console.error("[desktop-mode] restore folder failed:",i)}})}catch(i){console.error("[desktop-mode] deleteFolder failed:",i),bp(i),Me(o).then(r=>{J.setFolderPlacements(o,r.placements)})}}function P_(e){return e.file?.type==="folder"?_p(e):kp(e)}function $_(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o}}function Vn(){return window.wp?.desktop?.dragManager??null}const U_="desktop-mode-files-layer";function Ep(e,t=0){const n=document.createElement("div");n.className=U_,n.setAttribute("role","list"),n.dataset.folderId=String(t),e.appendChild(n);let o="",s=null;const i=new Set,r=E=>{for(const P of i)try{P(E)}catch(H){console.error("[desktop-mode] files: selection listener threw:",H)}},a=E=>{const P=E?E.id:null;P!==s&&(n.querySelectorAll(`.${te}--selected`).forEach(H=>H.removeAttribute("selected")),E&&n.querySelector(`[data-placement-id="${E.id}"]`)?.setAttribute("selected",""),s=P,r(E))},d=E=>{const P=new Map,H=new Set;let W=0;for(const M of E){if(!Ce(M))continue;const $=Yt(0,W);P.set(M.id,{x:$.x,y:$.y}),H.add(ke($.col,$.row)),W+=1}const V=new Map;for(const M of E){if(P.has(M.id))continue;const $=qn(M.x,M.y),Z=ke($.col,$.row);if(!H.has(Z)){H.add(Z);continue}const se=St(M.x,M.y,H,e);H.add(ke(se.col,se.row)),V.set(M.id,{x:se.x,y:se.y})}return{pinnedSlots:P,displaced:V}},c=(E,P,H,W)=>{const V=H.get(P.id),M=W.get(P.id);V?Qe(E,V.x,V.y):M?Qe(E,M.x,M.y):Qe(E,P.x,P.y)},l=(E,P,H)=>{const W=N_(E,t),V=P.get(E.id);if(V){if(Qe(W,V.x,V.y),W.classList.add(`${te}--pinned`),xp(W,E),b(W,E),Sp(E)){const $=Vn();if($){const Z=$.registerDropTarget({id:`desktop-mode-files-tile-${E.id}-reject`,element:W,accept:()=>!1,onDrop:()=>{}});m.set(E.id,Z)}}return W}const M=H.get(E.id);if(M&&Qe(W,M.x,M.y),q_(W,E,t),xp(W,E),b(W,E),E.file.type==="folder"){const $=parseInt(E.file.ref,10);if($>0){const Z=Vn();if(Z){const se=j_(Z,W,$);h.set(E.id,se)}}}else if(Sp(E)){const $=Vn();if($){const Z=$.registerDropTarget({id:`desktop-mode-files-tile-${E.id}-reject`,element:W,accept:()=>!1,onDrop:()=>{}});m.set(E.id,Z)}}return W},u=E=>{const P=new Map;for(const M of n.querySelectorAll("[data-placement-id]")){const $=M.dataset.placementId??"",Z=parseInt($,10);if($===""||Number.isNaN(Z)&&$!=="-0")return!1;P.set(Z,M)}const H=new Set;for(const M of E)H.add(M.id);for(const M of E){const $=P.get(M.id);if(!$)continue;if($.dataset.fileType!==M.file.type||$.dataset.fileRef!==M.file.ref||$.classList.contains(`${te}--pinned`)!==Ce(M))return!1}for(const[M,$]of P){if(H.has(M))continue;const Z=h.get(M);if(Z){try{Z()}catch{}h.delete(M)}const se=m.get(M);if(se){try{se()}catch{}m.delete(M)}$.remove()}const{pinnedSlots:W,displaced:V}=d(E);for(const M of E){const $=P.get(M.id);if($){c($,M,W,V);continue}n.appendChild(l(M,W,V))}return s!==null&&!n.querySelector(`[data-placement-id="${s}"]`)&&(s=null,r(null)),A("desktop-mode.files.grid-rendered",{folderId:t,count:E.length}),!0},p=E=>{const H=(E.placementsByFolder.get(t)??[]).slice().sort(($,Z)=>{const se=Ce($)?0:1,q=Ce(Z)?0:1;return se-q}),W=H_(H);if(W===o||(o=W,z_(H,n,e))||u(H))return;n.replaceChildren();for(const[,$]of h)try{$()}catch{}h.clear();for(const[,$]of m)try{$()}catch{}m.clear();const{pinnedSlots:V,displaced:M}=d(H);for(const $ of H)n.appendChild(l($,V,M));s!==null&&!n.querySelector(`[data-placement-id="${s}"]`)?(s=null,r(null)):s!==null&&n.querySelector(`[data-placement-id="${s}"]`)?.setAttribute("selected",""),A("desktop-mode.files.grid-rendered",{folderId:t,count:H.length})},f=[],h=new Map,m=new Map;let w=null,g=null;const x=E=>{if(w||E.payload.type!=="desktop-file")return;const P=document.createElement("div");P.className="desktop-mode-files-drop-preview",P.setAttribute("aria-hidden","true"),n.appendChild(P),w=P;const H=E.payload.ghost,W=H?.offsetX??0,V=H?.offsetY??0,$=E.payload.data?.placement?.id,Z=(ce,ge)=>{const Ie=n.getBoundingClientRect(),le=Math.max(0,ce-Ie.left-W),Lt=Math.max(0,ge-Ie.top-V),So=J.getState().placementsByFolder.get(t)??[],pa=cs(So,$),fa=St(le,Lt,pa,e);P.style.transform=`translate3d(${fa.x}px, ${fa.y}px, 0)`},se=E.payload.source.getBoundingClientRect();Z(se.left+W,se.top+V);const q=ce=>{Z(ce.clientX,ce.clientY)};document.addEventListener("pointermove",q),g=q},T=()=>{g&&(document.removeEventListener("pointermove",g),g=null),w&&(w.remove(),w=null)},y={id:`desktop-mode-files-canvas-${t}`,element:e,accept:E=>{if(E.type!=="desktop-file"&&E.type!=="shortcut")return!1;if(t>0&&E.type==="desktop-file"){const P=E.data;if(P.placement.file?.type==="folder"){const H=parseInt(P.placement.file.ref,10);if(!Number.isNaN(H)&&Ip(H,t))return!1}}return!0},onEnter:E=>{e.setAttribute("data-files-drop-active",""),x(E)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),T()},onDrop:(E,P)=>{e.removeAttribute("data-files-drop-active"),T();const H=n.getBoundingClientRect(),W=E.payload.ghost,V=W?.offsetX??0,M=W?.offsetY??0,$=Math.max(0,P.clientX-H.left-V),Z=Math.max(0,P.clientY-H.top-M),se=J.getState().placementsByFolder.get(t)??[];if(E.payload.type==="desktop-file"){const q=E.payload.data,ce=cs(se,q.placement.id),ge=St($,Z,ce,e),Ie={...q.placement,x:ge.x,y:ge.y,parentId:t};if(J.upsertPlacement(Ie),A("desktop-mode.files.tile-manually-placed",{folderId:t,placementId:q.placement.id}),Ir(q.placement)){const le=Sr(q.placement);le&&F_(le,ge.x,ge.y);return}qt(q.placement.id,{x:ge.x,y:ge.y,parentId:t},q.placement.updatedAtMs).then(le=>{J.upsertPlacement(le,"remote")}).catch(le=>{gp(le)?yp(le):console.error("[desktop-mode] files: drag persist failed",le),J.upsertPlacement(q.placement)});return}if(E.payload.type==="shortcut"){const q=E.payload.data,ce=cs(se),ge=hp(ce,e);jt({parentId:t,type:q.kind,ref:q.ref,x:ge.x,y:ge.y}).then(Ie=>{J.upsertPlacement(Ie),A("desktop-mode.files.shortcut-dropped",{folderId:t,placement:Ie})}).catch(Ie=>{console.error("[desktop-mode] shortcut drop failed:",Ie)})}}},k=Vn();k&&f.push(k.registerDropTarget(y));const N=E=>{E.target instanceof Element&&E.target.closest(`.${te}`)||a(null)};e.addEventListener("click",N);function b(E,P){E.addEventListener("click",H=>{H.stopPropagation(),a(P)})}p(J.getState());const L=J.subscribe(p);let D=()=>{};const C=new Promise(E=>{D=E});J.getState().hydratedFolders.has(t)?queueMicrotask(D):Me(t).then(E=>{J.setFolderPlacements(t,E.placements)}).catch(E=>{console.error("[desktop-mode] files: failed to hydrate folder",t,E)}).finally(()=>{D()});const S=()=>{const E=e.clientWidth>0?e.clientWidth:4*ct;return Math.max(1,Math.floor((E-Te)/ct))},I=(E,P)=>{const H=E.slice();switch(P){case"name-asc":H.sort((W,V)=>W.file.title.localeCompare(V.file.title));break;case"name-desc":H.sort((W,V)=>V.file.title.localeCompare(W.file.title));break;case"date-asc":H.sort((W,V)=>W.updatedAtMs-V.updatedAtMs);break;case"date-desc":H.sort((W,V)=>V.updatedAtMs-W.updatedAtMs);break}return H},R=E=>{const P=J.getState().placementsByFolder.get(t);if(!P||P.length===0)return;const H=P.filter(q=>Ce(q)),W=P.filter(q=>!Ce(q)),V=I(W,E),M=S(),$=new Set;for(let q=0;q<H.length;q+=1)$.add(ke(0,q));let Z=0;const se=()=>{for(;;){const q=Math.floor(Z/M),ce=Z%M;if(Z+=1,!$.has(ke(ce,q)))return{col:ce,row:q}}};V.forEach((q,ce)=>{const ge=se(),Ie=Te+ge.col*ct,le=Te+ge.row*jn,Lt={...q,x:Ie,y:le,sortOrder:ce};J.upsertPlacement(Lt),!Ir(q)&&qt(q.id,{x:Ie,y:le,sortOrder:ce}).catch(So=>{console.error("[desktop-mode] files: sort persist failed",So)})})},F=()=>{const E=J.getState().placementsByFolder.get(t);if(!E||E.length===0)return;const P=e.clientWidth>0?e.clientWidth:1/0;if(!E.some(q=>q.x+ct>P))return;const W=S(),V=E.filter(q=>Ce(q)),M=E.filter(q=>!Ce(q)),$=new Set;for(let q=0;q<V.length;q+=1)$.add(ke(0,q));let Z=0;const se=()=>{for(;;){const q=Math.floor(Z/W),ce=Z%W;if(Z+=1,!$.has(ke(ce,q)))return{col:ce,row:q}}};for(const q of M){const ce=se(),ge=Te+ce.col*ct,Ie=Te+ce.row*jn,le=n.querySelector(`[data-placement-id="${q.id}"]`);le&&Qe(le,ge,Ie)}};let K=e.clientWidth,X=null;return typeof ResizeObserver<"u"&&(X=new ResizeObserver(()=>{const E=e.clientWidth;E!==K&&(K=E,F())}),X.observe(e)),{host:e,folderId:t,onSelectionChange(E){return i.add(E),()=>{i.delete(E)}},sort:R,reflow:F,hydrated:C,dispose(){L(),X?.disconnect(),X=null;for(const E of f)try{E()}catch{}f.length=0;for(const E of h.values())try{E()}catch{}h.clear();for(const E of m.values())try{E()}catch{}m.clear(),e.removeEventListener("click",N),i.clear(),n.remove()}}}function H_(e){if(e.length===0)return"0";const t=[];for(const n of e)t.push(`${n.id}:${n.parentId}:${n.x}:${n.y}:${n.sortOrder}:${n.updatedAtMs}:${n.file.type}:${n.file.ref}:${n.file.title}:${n.file.icon}:${Ce(n)?1:0}`);return t.join("|")}function Ce(e){return!!e.file.pinned}function Sr(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function Ir(e){return e.id<=0||Sr(e)!==null}const B_="desktop-mode-recycle-bin";function Sp(e){return!(e.file?.type==="folder"||e.file?.ref===B_)}function cs(e,t){const n=e.slice().sort((i,r)=>{const a=Ce(i)?0:1,d=Ce(r)?0:1;return a-d}),o=new Set;let s=0;for(const i of n)if(!(t!==void 0&&i.id===t))if(Ce(i))o.add(ke(0,s)),s+=1;else{const r=qn(i.x,i.y);o.add(ke(r.col,r.row))}return o}function Ip(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=J.getState();for(const a of o.placementsByFolder.values())for(const d of a){if(d.file?.type!=="folder")continue;const c=parseInt(d.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,d.parentId)}const s=new Set;let i=t,r=256;for(;i>0&&r-- >0;){if(i===e||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function F_(e,t,n){const o=window.wp?.desktop;if(!o?.getOsSettings||!o?.updateOsSettings)return;const s=o.getOsSettings().dockPromotedPositions??{};o.updateOsSettings({dockPromotedPositions:{...s,[e]:{x:t,y:n}}})}function z_(e,t,n){const o=Array.from(t.querySelectorAll("[data-placement-id]"));if(o.length!==e.length)return!1;const s=new Map;for(const c of o){const l=c.dataset.placementId??"",u=parseInt(l,10);if(l===""||Number.isNaN(u)&&l!=="-0")return!1;s.set(u,c)}for(const c of e){const l=s.get(c.id);if(!l||l.dataset.fileType!==c.file.type||l.dataset.fileRef!==c.file.ref||l.classList.contains(`${te}--pinned`)!==Ce(c))return!1}const i=new Map,r=new Set;let a=0;for(const c of e){if(!Ce(c))continue;const l=Yt(0,a);i.set(c.id,{x:l.x,y:l.y}),r.add(ke(l.col,l.row)),a+=1}const d=new Map;for(const c of e){if(i.has(c.id))continue;const l=qn(c.x,c.y),u=ke(l.col,l.row);if(!r.has(u)){r.add(u);continue}const p=St(c.x,c.y,r,n);r.add(ke(p.col,p.row)),d.set(c.id,{x:p.x,y:p.y})}for(const c of e){const l=s.get(c.id);if(!l)continue;const u=i.get(c.id),p=d.get(c.id);u?Qe(l,u.x,u.y):p?Qe(l,p.x,p.y):Qe(l,c.x,c.y)}return!0}function G_(e){const t=window.wp?.desktop;if(!t?.getOsSettings||!t?.updateOsSettings)return;const o={...t.getOsSettings().itemVisibility??{},[e]:"dock"};t.updateOsSettings({itemVisibility:o})}function j_(e,t,n,o){const s={id:`desktop-mode-files-folder-${n}-tile-${t.dataset.placementId??"?"}`,element:t,accept:i=>{if(i.type!=="desktop-file"&&i.type!=="shortcut")return!1;if(i.type==="desktop-file"){const r=i.data;if(r.placement.file.type==="folder"&&parseInt(r.placement.file.ref,10)===n||r.placement.parentId===n||Ir(r.placement))return!1;if(r.placement.file.type==="folder"){const a=parseInt(r.placement.file.ref,10);if(!Number.isNaN(a)&&Ip(a,n))return!1}}return!0},onEnter:()=>{t.classList.add(`${te}--drop-target`)},onLeave:()=>{t.classList.remove(`${te}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${te}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a={...r.placement,parentId:n};J.upsertPlacement(a),qt(r.placement.id,{parentId:n},r.placement.updatedAtMs).then(d=>{J.upsertPlacement(d,"remote")}).catch(d=>{gp(d)?yp(d):console.error("[desktop-mode] files: move-into-folder persist failed",d),J.upsertPlacement(r.placement)});return}if(i.payload.type==="shortcut"){const r=i.payload.data,a=J.getState().placementsByFolder.get(n)??[],d=hp(cs(a));jt({parentId:n,type:r.kind,ref:r.ref,x:d.x,y:d.y}).then(c=>{J.upsertPlacement(c),A("desktop-mode.files.shortcut-dropped",{folderId:n,placement:c})}).catch(c=>{console.error("[desktop-mode] shortcut drop into folder failed:",c)})}}};return e.registerDropTarget(s)}function q_(e,t,n){e.addEventListener("pointerdown",o=>{if(o.button!==0)return;const s=Vn();if(!s)return;const r=J.getState().placementsByFolder.get(n)?.find(a=>a.id===t.id)??t;parseFloat(e.style.left)||r.x,parseFloat(e.style.top)||r.y,s.start({payload:{type:"desktop-file",source:e,data:{placement:r,sourceFolderId:n,bridgePayload:$_(r)},ghost:{offsetX:o.clientX-e.getBoundingClientRect().left,offsetY:o.clientY-e.getBoundingClientRect().top}},origin:o})})}function xp(e,t){e.addEventListener("contextmenu",n=>{n.preventDefault(),n.stopPropagation();const o=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,onClick:()=>{const i=is(t.file);lr(i)}}];if(t.file.type==="post"&&o.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>{const i=parseInt(t.file.ref,10);if(!i)return;const r=window.wp?.desktop?.myWordpress,d=(typeof t.file.postType=="string"?t.file.postType:"post")==="page"?"pages":"posts";r?.openDetail({entityId:d,postId:i,postTitle:t.file.title||`#${i}`})}}),t.file.type==="folder")o.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>{const i=parseInt(t.file.ref,10);i&&Er({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:t.file.title,onSubmit:async r=>{const a=r.trim();if(!a||a===t.file.title)return;const d=t.file.title,c={...t,file:{...t.file,title:a}};J.upsertPlacement(c);try{const l=J.getState().folders.get(i)?.updatedAtMs??0,u=await tp(i,{name:a},l);J.upsertFolder(u);const p=await Me(t.parentId);J.setFolderPlacements(t.parentId,p.placements)}catch(l){console.error("[desktop-mode] rename folder failed:",l),J.upsertPlacement({...t,file:{...t.file,title:d}})}}})}}),t.canTrash!==!1&&o.push({id:"delete-folder",label:"Move folder to Trash",icon:"dashicons-trash",sort:90,danger:!0,onClick:()=>_p(t)});else{const i=Sr(t),r=t.file.type==="shortcut";if(i||r){const a=i??t.file.ref;o.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,onClick:()=>G_(a)})}else t.canTrash!==!1&&o.push({id:"remove",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,onClick:()=>kp(t)})}O_({x:n.clientX,y:n.clientY},{placement:t,items:o})})}const Xt="desktop-mode-folder-status-bar";function V_(e,t){const n=document.createElement("div");n.className=Xt,n.setAttribute("role","status"),n.dataset.folderId=String(t),e.appendChild(n);const o=()=>{const i=Et().placementsByFolder.get(t)??[],r=i.filter(l=>l.file.type==="folder").length,a=i.length-r,d={folderId:t,totals:{files:a,folders:r,total:i.length}},c=K_(d);Y_(n,c)};o();const s=yr(()=>o());return{dispose(){s(),n.remove()}}}function K_(e){const{folders:t,files:n}=e.totals,o=[{id:"count",label:Ap(n,"file","files")+(t>0?`, ${Ap(t,"folder","folders")}`:""),align:"start",sort:10}],s=j("desktop-mode.files.folder-window.status-bar",o,e);return Array.isArray(s)?s:o}function Y_(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,d=typeof r.sort=="number"?r.sort:100;return a!==d?a-d:i.label.localeCompare(r.label)},o=t.filter(i=>(i.align??"start")==="start").sort(n),s=t.filter(i=>i.align==="end").sort(n);e.replaceChildren(),e.appendChild(Cp("start",o)),e.appendChild(Cp("end",s))}function Cp(e,t){const n=document.createElement("div");n.className=`${Xt}__cluster ${Xt}__cluster--${e}`;for(const o of t)n.appendChild(X_(o));return n}function X_(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${Xt}__segment`,n.dataset.segmentId=e.id,t&&(n.type="button",n.addEventListener("click",s=>e.onClick(s))),e.icon){const s=document.createElement("span");s.className=`${Xt}__icon dashicons ${e.icon.replace(/[^a-zA-Z0-9_-]/g,"")}`,s.setAttribute("aria-hidden","true"),n.appendChild(s)}const o=document.createElement("span");return o.className=`${Xt}__label`,o.textContent=e.label,n.appendChild(o),n}function Ap(e,t,n){return`${e} ${e===1?t:n}`}const ls="desktop-mode-icon-canvas-menu";let Kn=null,us=null,xr=null,Yn=null,Xn=null;function Z_(e,t){t.openOnBackgroundClick;const n=i=>{J_(i.target)||Lp(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(xr===e&&Kn){It();return}const a=Q_(t),d=j("desktop-mode.icon-canvas.menu",a,t.scope),c=Array.isArray(d)?d:a,l=++o;sn(()=>l===o,()=>eE(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),It()}}}function J_(e){return e instanceof Element?e.closest(".desktop-mode-file-tile")!==null:!1}function Lp(e){return e instanceof Element?e.closest(`.${ls}`)!==null:!1}function Q_(e){const n=[{id:"sort-by",label:O("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:O("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:O("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:O("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:O("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function Tp(e){return e.slice().sort((t,n)=>{const o=typeof t.sort=="number"?t.sort:100,s=typeof n.sort=="number"?n.sort:100;return o!==s?o-s:t.label.localeCompare(n.label)})}function eE(e,t,n){if(It(),e.length===0)return;xr=n;const o=Tp(e),s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(ls),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;for(const r of o){i.set(r.id,r);const a=Np(s,r);ps(r)&&a.addEventListener("mouseenter",()=>{Dp(r,a)})}s.addEventListener("wpd-context-menu-pick",r=>{const a=r.detail,d=i.get(a.id);if(d){if(ps(d)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${d.id}"]`);c&&Dp(d,c);return}It(),d.onClick?.()}}),document.body.appendChild(s),Kn=s,nE(s),queueMicrotask(()=>{Yn=r=>{Lp(r.target)||It()},Xn=r=>{r.key==="Escape"&&It()},document.addEventListener("mousedown",Yn),document.addEventListener("keydown",Xn)})}function Np(e,t){const n=document.createElement("wpd-context-menu-option");return n.dataset.menuItemId=t.id,n.setAttribute("value",t.id),t.heading&&n.setAttribute("heading",""),t.disabled&&n.setAttribute("disabled",""),t.icon&&n.setAttribute("icon",oE(t.icon)),ps(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function Dp(e,t){if(Op(),!ps(e))return;const n=document.createElement("wpd-context-menu");n.setAttribute("open",""),n.classList.add(ls,`${ls}--flyout`);const o=new Map;for(const s of Tp(e.children??[]))o.set(s.id,s),Np(n,s);n.addEventListener("wpd-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),It(),r.onClick?.())}),document.body.appendChild(n),us=n,tE(n,t)}function tE(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`;const o=e.getBoundingClientRect();o.right>window.innerWidth&&(e.style.left=`${Math.max(0,n.left-o.width)}px`),o.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-o.height-8)}px`)}function nE(e){const t=e.getBoundingClientRect();t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-8)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-8)}px`)}function ps(e){return Array.isArray(e.children)&&e.children.length>0}function Op(){us&&(us.remove(),us=null)}function It(){Op(),Kn&&(Kn.remove(),Kn=null),xr=null,Yn&&(document.removeEventListener("mousedown",Yn),Yn=null),Xn&&(document.removeEventListener("keydown",Xn),Xn=null)}function oE(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const xt="desktop-mode-breadcrumbs";function sE(e,t,n={}){if(e.replaceChildren(),e.classList.add(xt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${xt}__back`,s.setAttribute("aria-label",O("Back","desktop-mode")),s.title=O("Back","desktop-mode");const i=document.createElement("span");i.className="dashicons dashicons-arrow-left-alt2",i.setAttribute("aria-hidden","true"),s.appendChild(i),n.backDisabled&&(s.disabled=!0);const r=n.onBack;s.addEventListener("click",()=>{s.disabled||r()}),e.appendChild(s)}const o=document.createElement("nav");o.className=`${xt}__crumbs`,o.setAttribute("aria-label",O("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const d=document.createElement("span");d.className=`${xt}__sep`,d.setAttribute("aria-hidden","true"),d.textContent="›",o.appendChild(d)}if(!s.onClick){const d=document.createElement("span");d.className=`${xt}__crumb ${xt}__crumb--current`,d.setAttribute("aria-current","page"),d.textContent=s.label,o.appendChild(d);return}const r=document.createElement("button");r.type="button",r.className=`${xt}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}async function Zn(e,t={}){const n=await ze(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":iE(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function iE(){return window.wp?.desktop?.config?.restNonce??""}function rE(){const e=window.wp?.desktop?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function Jn(e){return wn(rE(),e)}function aE(e,t){const n=j("desktop-mode.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(dE(e));return}t.replaceChildren(yE()),cE(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(bE(o))})}function dE(e){const t=document.createElement("div");t.className="desktop-mode-files__access-gated";const n=document.createElement("div");n.className="desktop-mode-files__access-gated-ring";const o=document.createElement("span");o.className="dashicons dashicons-lock desktop-mode-files__access-gated-glyph",o.setAttribute("aria-hidden","true"),n.appendChild(o),t.appendChild(n);const s=document.createElement("h2");s.className="desktop-mode-files__access-gated-title",s.textContent="No permission to view",t.appendChild(s);const i=document.createElement("p");i.className="desktop-mode-files__access-gated-sub";const r=e.file.title||e.file.type;i.textContent=`You don’t have access to "${r}". The folder owner shared this folder with you, but your role doesn’t include permission to open this item.`,t.appendChild(i);const a=document.createElement("p");return a.className="desktop-mode-files__access-gated-hint",a.textContent="Ask the owner to grant access on the underlying item, or to remove it from the shared folder.",t.appendChild(a),t}async function cE(e){const t=e.file;switch(t.type){case"post":return lE(t.ref,t);case"folder":return hE(t);case"shortcut":return wE(t);case"attachment":return mE(t.ref,t);case"user":return uE(t.ref,t);case"term":return pE(t);case"comment":return fE(t.ref,t);case"bookmark":return gE(t);default:return He(t)}}async function lE(e,t){const n=parseInt(e,10);if(!n)return He(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await Zn(Jn(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return He(t);const s=et(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=fs(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="desktop-mode-my-wordpress__article-meta";const a=[];if(a.push(Rp(o.date)),o.status&&o.status!=="publish"&&a.push(o.status),r.textContent=a.join(" · "),s.appendChild(r),o.content?.rendered){const u=document.createElement("div");u.className="desktop-mode-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const d=document.createElement("footer");d.className="desktop-mode-my-wordpress__article-footer";const c=window.wp?.desktop?.myWordpress;if(c){const u=document.createElement("wpd-button");u.setAttribute("variant","secondary"),u.textContent=O("Explore details","desktop-mode"),u.title=O("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),u.addEventListener("click",()=>{const p=typeof t.postType=="string"?t.postType:"post";c.openDetail({entityId:p==="page"?"pages":"posts",postId:n,postTitle:fs(o.title.rendered)||`#${n}`})}),d.appendChild(u)}const l=document.createElement("wpd-button");return l.setAttribute("variant","primary"),l.textContent=O("Open in editor","desktop-mode"),l.addEventListener("click",()=>{const u=window.wp?.desktop?.config?.adminUrl;if(!u)return;const p=`${u}post.php?post=${n}&action=edit`,f=window.wp?.desktop?.windowManager,m=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";f?.open({id:`${m}-edit-${n}`,url:p,title:fs(o.title.rendered),icon:t.icon})}),d.appendChild(l),s.appendChild(d),s}async function uE(e,t){const n=parseInt(e,10);if(!n)return He(t);let o=null;try{o=await Zn(Jn(`desktop-mode/v1/user-stats/${n}`))}catch{return He(t)}const s=et("desktop-mode-my-wordpress__user"),i=document.createElement("header");if(i.className="desktop-mode-my-wordpress__user-header",o.profile.avatarUrl){const c=document.createElement("img");c.className="desktop-mode-my-wordpress__user-avatar",c.src=o.profile.avatarUrl,c.alt="",i.appendChild(c)}const r=document.createElement("div");r.className="desktop-mode-my-wordpress__user-headline";const a=document.createElement("h2");if(a.className="desktop-mode-my-wordpress__article-title",a.textContent=o.profile.name||t.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const c=document.createElement("div");c.className="desktop-mode-my-wordpress__user-roles";for(const l of o.profile.roleLabels){const u=document.createElement("span");u.className="desktop-mode-my-wordpress__user-role",u.textContent=l,c.appendChild(u)}r.appendChild(c)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const c=document.createElement("div");c.className="desktop-mode-my-wordpress__user-bio",c.textContent=o.profile.description,s.appendChild(c)}const d=document.createElement("div");return d.className="desktop-mode-my-wordpress__user-stats",d.appendChild(Zt(o.counts.posts.total.toLocaleString(),O("Posts","desktop-mode"))),d.appendChild(Zt(o.counts.pages.total.toLocaleString(),O("Pages","desktop-mode"))),d.appendChild(Zt(o.counts.commentsReceived.toLocaleString(),O("Comments received","desktop-mode"))),s.appendChild(d),s}async function pE(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return He(e);let o=null;try{o=await Zn(Jn(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return He(e)}const s=et(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=o.profile.name||e.title||`#${t}`,s.appendChild(i);const r=document.createElement("p");if(r.className="desktop-mode-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const d=document.createElement("div");d.className="desktop-mode-my-wordpress__article-content",d.innerHTML=o.profile.description,s.appendChild(d)}const a=document.createElement("div");return a.className="desktop-mode-my-wordpress__user-stats",a.appendChild(Zt(o.counts.posts.total.toLocaleString(),O("Posts","desktop-mode"))),a.appendChild(Zt(o.counts.commentsReceived.toLocaleString(),O("Comments","desktop-mode"))),a.appendChild(Zt(o.counts.distinctAuthors.toLocaleString(),O("Authors","desktop-mode"))),s.appendChild(a),s}async function fE(e,t){const n=parseInt(e,10);if(!n)return He(t);let o=null;try{o=await Zn(Jn(`desktop-mode/v1/comment-stats/${n}`))}catch{return He(t)}const s=et(),i=document.createElement("header");if(i.className="desktop-mode-my-wordpress__user-header",o.author.avatarUrl){const l=document.createElement("img");l.className="desktop-mode-my-wordpress__user-avatar",l.src=o.author.avatarUrl,l.alt="",i.appendChild(l)}const r=document.createElement("div");r.className="desktop-mode-my-wordpress__user-headline";const a=document.createElement("h2");a.className="desktop-mode-my-wordpress__article-title",a.textContent=o.author.name,r.appendChild(a);const d=document.createElement("p");d.className="desktop-mode-my-wordpress__article-meta",d.textContent=`${Rp(o.comment.date)} · ${o.comment.status}`,r.appendChild(d),i.appendChild(r),s.appendChild(i);const c=document.createElement("div");if(c.className="desktop-mode-my-wordpress__article-content",c.innerHTML=o.comment.rendered,s.appendChild(c),o.post){const l=document.createElement("div");l.className="desktop-mode-my-wordpress__comment-post";const u=document.createElement("a");u.className="desktop-mode-my-wordpress__comment-post-title",u.href=o.post.link,u.target="_blank",u.rel="noopener noreferrer",u.textContent=o.post.title,l.appendChild(u),s.appendChild(l)}return s}async function mE(e,t){const n=parseInt(e,10);if(!n)return He(t);let o=null;try{o=await Zn(Jn(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return He(t)}const s=et(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=fs(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="desktop-mode-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="desktop-mode-my-wordpress__article-hero";const d=o.media_details?.sizes;a.src=d?.large?.source_url??d?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),d=document.createElement("a");d.href=o.source_url,d.textContent=o.source_url,d.target="_blank",d.rel="noopener noreferrer",a.appendChild(d),s.appendChild(a)}return s}function hE(e){const t=et(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||O("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="desktop-mode-my-wordpress__article-meta",o.textContent=O("Double-click to open.","desktop-mode"),t.appendChild(o),t}function wE(e){const t=et(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||O("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="desktop-mode-my-wordpress__article-meta",o.textContent=O("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function gE(e){const t=et(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||O("Bookmark","desktop-mode"),t.appendChild(n);const o=typeof e.url=="string"?e.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",t.appendChild(s)}return t}function He(e){const t=et(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||e.type,t.appendChild(n);const o=document.createElement("p");if(o.className="desktop-mode-my-wordpress__article-meta",o.textContent=oe(O("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="desktop-mode-my-wordpress__article-meta",s.textContent=O("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function et(e=""){const t=document.createElement("article");return t.className="desktop-mode-my-wordpress__article"+(e?" "+e:""),t}function Zt(e,t){const n=document.createElement("div");n.className="desktop-mode-my-wordpress__user-stat";const o=document.createElement("span");o.className="desktop-mode-my-wordpress__user-stat-value",o.textContent=e,n.appendChild(o);const s=document.createElement("span");return s.className="desktop-mode-my-wordpress__user-stat-label",s.textContent=t,n.appendChild(s),n}function yE(){const e=document.createElement("div");e.className="desktop-mode-my-wordpress__preview-loading";const t=document.createElement("wpd-spinner");return e.appendChild(t),e}function bE(e){const t=document.createElement("div");return t.className="desktop-mode-my-wordpress__error",t.textContent=e instanceof Error?e.message:O("Unknown error.","desktop-mode"),t}function fs(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function Rp(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function Mp(){const e=document.createElement("div");return e.className="desktop-mode-my-wordpress__preview-empty",e.textContent=O("Select an item to preview it here.","desktop-mode"),e}const ms="desktop-mode-embed-",vE=800,kE=600,Cr=360,Ar=240,hs=16,Lr=new Map;function _E(e,t){const n=e.ref();if(!n)return;const o=window.wp?.desktop?.windowManager;if(!o)return;const s=t?.placement,i=s?.meta??null,r=s?`${ms}${s.id}`:`${ms}anon-${xE(n)}`,a=i?.name?.trim()??"",d=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:d,icon:e.icon(),minWidth:Cr,minHeight:Ar},l=i?.window,u=document.getElementById("desktop-mode-area"),p=u?.clientWidth??window.innerWidth,f=u?.clientHeight??window.innerHeight;if(l&&Number.isFinite(l.width)&&Number.isFinite(l.height)){const{x:h,y:m,width:w,height:g}=IE(l,p,f);c.x=h,c.y=m,c.width=w,c.height=g}else c.width=Math.min(vE,Math.max(Cr,p-hs*2)),c.height=Math.min(kE,Math.max(Ar,f-hs*2));s&&l&&Lr.set(r,{...l}),o.open(c)}let Wp=!1;function EE(){if(Wp)return;Wp=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(ms))return;const s=o.slice(ms.length),i=parseInt(s,10);if(!i)return;const d=window.wp?.desktop?.windowManager?.getById?.(o)?.element;if(!d)return;const c={x:d.offsetLeft,y:d.offsetTop,width:d.offsetWidth,height:d.offsetHeight},l=Lr.get(o);l&&l.x===c.x&&l.y===c.y&&l.width===c.width&&l.height===c.height||(Lr.set(o,c),SE(i,c))};G(v.WINDOW_DRAG_END,"desktop-mode-embed-persist",e),G(v.WINDOW_RESIZE_END,"desktop-mode-embed-persist",e)}async function SE(e,t){try{const i={...(await Me(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await qt(e,{meta:i})}catch(n){console.warn("[desktop-mode] embed window persist failed:",n)}}function IE(e,t,n){const o=Math.max(Cr,Math.min(e.width,t-hs)),s=Math.max(Ar,Math.min(e.height,n-hs)),i=Math.max(0,Math.min(e.x,Math.max(0,t-o))),r=Math.max(0,Math.min(e.y,Math.max(0,n-s)));return{x:i,y:r,width:o,height:s}}function xE(e){let t=0;for(let n=0;n<e.length;n++)t=(Math.imul(t,31)+e.charCodeAt(n))%2147483647;return Math.abs(t).toString(36)}function Qn(){const t=window.wp?.desktop?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function Pp(e){const t=typeof e.shape.url=="string"?e.shape.url:"";if(!t)return"";try{const n=new URL(t,window.location.href);if(n.protocol!=="http:"&&n.protocol!=="https:")return""}catch{return""}return t}function CE(){Ue({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Qn()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Ue({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Qn()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Ue({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Qn()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),Ue({id:"wp-term-editor",label:"Term editor",types:["term"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>{const[t,n]=e.ref().split(":");return`${Qn()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Ue({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Qn()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),Ue({id:"desktop-mode-folder-window",label:"Open folder",types:["folder"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);if(!t)return;const n=window.wp?.desktop?.windowManager;if(!n)return;const o=`desktop-mode-folder-${t}`,s=J.getState().folders.get(t),i=Number(window.desktopModeConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),d=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:d,icon:e.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window");const l=[{folderId:t,title:e.title()}];let u=null;const p=document.createElement("header");c.appendChild(p);const f=document.createElement("div");f.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",c.appendChild(f);const h=()=>{const w=l.map((g,x)=>x===l.length-1?{label:g.title}:{label:g.title,onClick:()=>{l.length=x+1,m()}});sE(p,w,{onBack:()=>{l.length<=1||(l.pop(),m())},backDisabled:l.length<=1})},m=()=>{u?.(),u=null,f.replaceChildren();const w=document.createElement("div");w.className="desktop-mode-folder-window__split",f.appendChild(w);const g=document.createElement("div");g.className="desktop-mode-folder-window__layer",w.appendChild(g);const x=document.createElement("div");x.className="desktop-mode-folder-window__preview",x.appendChild(Mp()),w.appendChild(x);const T=l[l.length-1],y=Ep(g,T.folderId),k=y.onSelectionChange(D=>{if(!D){x.replaceChildren(Mp());return}aE(D,x)}),N=D=>{if(!(D.target instanceof Element))return;const C=D.target.closest(".desktop-mode-file-tile");if(!C||C.dataset.fileType!=="folder")return;const S=parseInt(C.dataset.fileRef??"",10);if(!S)return;D.preventDefault(),D.stopPropagation();const I=C.querySelector(".desktop-mode-file-tile__label")?.textContent??`#${S}`;l.push({folderId:S,title:I}),m()};g.addEventListener("dblclick",N,!0);const b=Z_(g,{scope:`desktop-mode-folder:${T.folderId}`,onSort:D=>y.sort(D),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{Er({onSubmit:async D=>{const C=await mr({name:D}),S=J.getState().placementsByFolder.get(T.folderId)??[],I=wp(S),R=St(Te,Te,I,g),F=await jt({type:"folder",ref:String(C.id),parentId:T.folderId,x:R.x,y:R.y});J.upsertFolder(C),J.upsertPlacement(F)}})}}]}),L=V_(f,T.folderId);u=()=>{k(),b.dispose(),L.dispose(),g.removeEventListener("dblclick",N,!0),y.dispose()},h()};m()},width:720,height:480,minWidth:360,minHeight:240})}}}),Ue({id:"desktop-mode-shortcut-opener",label:"Open shortcut",types:["shortcut"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=e.shape,n=window.wp?.desktop;if(n){if(t.shortcutWindow&&n.openWindow){n.openWindow(t.shortcutWindow);return}if(t.shortcutUrl&&n.windowManager)try{const o=new URL(t.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}const s=n.config?.adminUrl,i=s?ne(o.toString(),s):`desktop-icon-${e.ref()}`,r=_l(o.toString());n.windowManager.open({id:i,baseId:i,url:o.toString(),parentUrl:r?.url??o.toString(),title:e.title(),icon:e.icon(),submenu:r?.submenu,multi:!!r?.multi})}catch{}}}}}),Ue({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Pp(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Ue({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Pp(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Ue({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{_E(e,t)}}})}const AE="desktop-mode-file-associations";function LE(){cc({id:AE,label:"File Associations",order:50,render(e){TE(e)}})}function TE(e){e.replaceChildren();const t=Vu();if(t.length===0){const i=document.createElement("p");i.className="desktop-mode-file-associations__empty",i.textContent="No file types are registered.",e.appendChild(i);return}const n=document.createElement("p");n.className="desktop-mode-file-associations__intro",n.textContent="Pick which app opens each kind of file when you double-click it on the desktop.",e.appendChild(n);const o=rr(),s=document.createElement("div");s.className="desktop-mode-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(NE(i.type,i.label,o));e.appendChild(s)}function NE(e,t,n){const o=document.createElement("div");o.className="desktop-mode-file-associations__row",o.setAttribute("role","listitem"),o.dataset.fileType=e;const s=document.createElement("label");s.className="desktop-mode-file-associations__label",s.textContent=t,o.appendChild(s);const i=ar(e);if(i.length===0){const c=document.createElement("span");return c.className="desktop-mode-file-associations__none",c.textContent="No app available",o.appendChild(c),o}const r=dr(e),a=n[e]??r?.id??"",d=document.createElement("wpd-select");d.setAttribute("value",a),d.setAttribute("aria-label",`Default app for ${t}`),d.className="desktop-mode-file-associations__select",s.htmlFor=`assoc-${e}`,d.id=`assoc-${e}`;for(const c of i){const l=document.createElement("wpd-option");l.setAttribute("value",c.id),l.textContent=c.isDefault?`${c.label} (default)`:c.label,d.appendChild(l)}return d.addEventListener("wpd-pick",c=>{const l=c.detail?.value;if(!l)return;const u={...rr(),[e]:l};Yu(u),op(u).catch(p=>{console.error("[desktop-mode] saveAssociations failed:",p)})}),o.appendChild(d),o}let Tr=null;function tt(){return Tr||(Tr=re("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set}))),Tr}function DE(e,t){const n=tt();n.state.byFolder.set(e,t),n.notify()}function OE(e){if(!e||typeof e.folderId!="number")return;const t=tt(),o=(t.state.byFolder.get(e.folderId)??[]).filter(s=>s.id!==e.id);o.push(e),t.state.byFolder.set(e.folderId,o),t.notify()}function RE(e,t){const n=tt(),o=n.state.byFolder.get(e)??[];n.state.byFolder.set(e,o.filter(s=>s.id!==t)),n.notify()}function ME(e,t){return e.id===t.id&&e.folderId===t.folderId&&e.capability===t.capability&&e.invitedAtMs===t.invitedAtMs&&e.folderName===t.folderName&&e.ownerName===t.ownerName}function $p(e){const t=tt(),n=new Map(t.state.pending.map(s=>[s.id,s]));let o=!1;for(const s of e){if(t.state.deniedFolders.has(s.folderId))continue;const i=n.get(s.id);if(i){if(ME(i,s))continue;t.state.pending=t.state.pending.map(r=>r.id===s.id?s:r)}else t.state.pending.push(s);s.invitedAtMs>t.state.sharesVersion&&(t.state.sharesVersion=s.invitedAtMs),o=!0}o&&t.notify()}function Up(e,t={}){const n=tt();n.state.pending=n.state.pending.filter(o=>o.id!==e),t.denied&&typeof t.folderId=="number"&&n.state.deniedFolders.add(t.folderId),n.notify()}const WE=he`:host{display:block;position:relative;font-size:13px}.input{width:100%;padding:8px 10px;background:var( --wpd-input-bg,rgba( 255,255,255,0.06 ) );color:inherit;border:1px solid rgba( 255,255,255,0.12 );border-radius:6px;font:inherit;box-sizing:border-box}.input:focus{outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:-1px}.dropdown{background:var( --desktop-mode-bg,#1d2327 );color:var( --desktop-mode-fg,#fff );border:1px solid rgba( 255,255,255,0.18 );border-radius:6px;overflow:auto;z-index:11000;box-shadow:0 12px 32px rgba( 0,0,0,0.5 )}.empty.error{color:#ff8080}.item{display:flex;align-items:center;gap:10px;padding:8px 10px;cursor:pointer;border:0;background:transparent;color:inherit;width:100%;text-align:start;font:inherit}.item:hover,.item:focus{background:rgba( 255,255,255,0.06 );outline:none}.avatar{width:24px;height:24px;border-radius:50%;flex:0 0 auto;background:rgba( 255,255,255,0.1 )}.name{font-weight:500}.slug{opacity:0.6;font-size:12px}.empty{padding:12px;color:rgba( 255,255,255,0.5 );font-size:12px}`,mo=class mo extends pe{constructor(){super(...arguments),this._timer=null,this._abort=null,this._results=[],this._query="",this._open=!1,this._phase="idle",this._error="",this._dropdownStyle="",this._onScrollOrResize=()=>{},this._onInput=t=>{const n=t.target.value;this._query=n,this._scheduleSearch(n)},this._onFocus=()=>{if(this._results.length===0&&this._phase==="idle"){this._scheduleSearch(this._query);return}this._open=!0,this._positionDropdown(),this.requestUpdate()},this._onBlur=()=>{setTimeout(()=>{this._open=!1,this.requestUpdate()},150)},this._pick=t=>{this.emit("wpd-user-pick",{user:t}),this._results=[],this._open=!1,this._phase="idle",this._query="";const n=this.shadowRoot?.querySelector(".input");n&&(n.value=""),this.requestUpdate()}}connectedCallback(){super.connectedCallback(),this._onScrollOrResize=()=>{this._open&&(this._positionDropdown(),this.requestUpdate())},window.addEventListener("resize",this._onScrollOrResize),window.addEventListener("scroll",this._onScrollOrResize,!0)}disconnectedCallback(){this._timer&&clearTimeout(this._timer),this._abort&&this._abort.abort(),window.removeEventListener("resize",this._onScrollOrResize),window.removeEventListener("scroll",this._onScrollOrResize,!0)}_endpoint(){const t=this.getAttribute("endpoint");return t||window.desktopModeConfig?.filesUsersSearchUrl||""}_scheduleSearch(t){this._timer&&clearTimeout(this._timer),this._phase="loading",this._open=!0,this._positionDropdown(),this.requestUpdate(),this._timer=setTimeout(()=>this._runSearch(t),200)}async _runSearch(t){const n=this._endpoint();if(!n){this._phase="error",this._error="Search endpoint is not configured.",this._results=[],this._open=!0,this.requestUpdate();return}this._abort&&this._abort.abort();const o=new AbortController;this._abort=o;const s=this.getAttribute("exclude")||"",i=n+"?q="+encodeURIComponent(t)+"&exclude="+encodeURIComponent(s);try{const r={signal:o.signal,credentials:"same-origin"},a=await ze(i,r,{source:"desktop-mode/files-user-search",silent:!0});if(!a.ok)throw new Error(`HTTP ${a.status}`);const d=await a.json();this._results=d&&Array.isArray(d.users)?d.users:[],this._phase="ready",this._error="",this._open=!0}catch(r){if(r.name==="AbortError")return;this._results=[],this._phase="error",this._error=r.message||"Search failed.",this._open=!0}this._positionDropdown(),this.requestUpdate()}_positionDropdown(){const t=this.shadowRoot?.querySelector(".input");if(!t)return;const n=t.getBoundingClientRect(),o=n.bottom+4,s=n.left,i=n.width,a=window.innerHeight-n.bottom,d=n.top,c=Math.max(120,Math.min(280,Math.max(a,d)-16));a<200&&d>a?this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${n.top-4-c}px`,`width:${i}px`,`max-height:${c}px`].join(";"):this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${o}px`,`width:${i}px`,`max-height:${c}px`].join(";")}_dropdownContent(){if(this._phase==="loading")return z`<div class="empty">Searching…</div>`;if(this._phase==="error")return z`<div class="empty error">${this._error}</div>`;if(this._results.length===0){const t=this._query?"No matches.":"No users available.";return z`<div class="empty">${t}</div>`}return this._results.map(t=>z` |
| 85 |
<button |
| 86 |
type="button" |
| 87 |
class="item" |
| 88 |
role="option" |
| 89 |
@mousedown=${n=>n.preventDefault()} |
| 90 |
@click=${()=>this._pick(t)} |
| 91 |
> |
| 92 |
<img class="avatar" src=${t.avatarUrl} alt="" /> |
| 93 |
<div> |
| 94 |
<div class="name">${t.name}</div> |
| 95 |
<div class="slug">${t.slug}</div> |
| 96 |
</div> |
| 97 |
</button> |
| 98 |
`)}render(){const t=this.getAttribute("placeholder")||"Search users…";return z` |
| 99 |
<input |
| 100 |
class="input" |
| 101 |
type="search" |
| 102 |
placeholder=${t} |
| 103 |
autocomplete="off" |
| 104 |
@input=${this._onInput} |
| 105 |
@focus=${this._onFocus} |
| 106 |
@blur=${this._onBlur} |
| 107 |
.value=${this._query} |
| 108 |
/> |
| 109 |
${this._open?z` |
| 110 |
<div class="dropdown" role="listbox" style=${this._dropdownStyle}> |
| 111 |
${this._dropdownContent()} |
| 112 |
</div> |
| 113 |
`:z``} |
| 114 |
`}};mo.props=["placeholder","exclude","endpoint"],mo.styles=[WE],mo.help=void 0;let Nr=mo;me("wpd-user-search",Nr);const PE=he`:host{display:flex;flex-wrap:wrap;gap:6px;font-size:13px}.chip{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;background:rgba( 255,255,255,0.06 );color:inherit;border:1px solid rgba( 255,255,255,0.12 );cursor:pointer;font:inherit}.chip:hover{background:rgba( 255,255,255,0.12 )}.chip[ aria-pressed='true' ]{background:var( --wp-admin-theme-color,#2271b1 );border-color:var( --wp-admin-theme-color,#2271b1 );color:#fff}.empty{color:rgba( 255,255,255,0.5 );font-size:12px}`,ho=class ho extends pe{constructor(){super(...arguments),this._onToggle=t=>{const n=!this._selectedSet().has(t);this.emit("wpd-role-toggle",{slug:t,selected:n})}}_selectedSet(){const t=this.getAttribute("selected")||"";return new Set(t.split(",").map(n=>n.trim()).filter(n=>n!==""))}_roles(){const t=this.getAttribute("roles");if(t)try{const n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return window.desktopModeConfig?.shareEligibleRoles||[]}render(){const t=this._roles();if(t.length===0)return z`<span class="empty">No eligible roles.</span>`;const n=this._selectedSet();return z` |
| 115 |
${t.map(o=>{const s=n.has(o.slug);return z` |
| 116 |
<button |
| 117 |
type="button" |
| 118 |
class="chip" |
| 119 |
aria-pressed=${s?"true":"false"} |
| 120 |
@click=${()=>this._onToggle(o.slug)} |
| 121 |
>${o.name}</button> |
| 122 |
`})} |
| 123 |
`}};ho.props=["selected","roles"],ho.styles=[PE],ho.help=void 0;let Dr=ho;me("wpd-role-picker",Dr);const $E=he`:host{display:inline-flex;padding:3px;background:var( --wpd-segmented-bg,rgba( 0,0,0,0.05 ) );border-radius:7px;gap:2px}`,UE=he`:host{flex:1 1 auto;min-width:0}button{appearance:none;display:block;width:100%;padding:8px 12px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --desktop-mode-muted,#646970 );cursor:pointer;border-radius:5px;transition:background-color 0.12s ease,color 0.12s ease;white-space:nowrap}:host( [ aria-checked='true' ] ) button{background:var( --desktop-mode-window-bg,#fff );color:var( --desktop-mode-text,#1d2327 );box-shadow:0 1px 3px rgba( 0,0,0,0.12 );font-weight:500}`,wo=class wo extends pe{render(){return this.setAttribute("role","radio"),z` |
| 124 |
<button type="button" @click=${()=>this._onPick()}> |
| 125 |
<slot></slot> |
| 126 |
</button> |
| 127 |
`}_onPick(){this.emit("wpd-segment-pick",{value:this.value})}};wo.props=["value"],wo.styles=[UE],wo.help=void 0;let Or=wo;me("wpd-segment",Or);const go=class go extends pe{connectedCallback(){super.connectedCallback(),this.addEventListener("wpd-segment-pick",t=>{const n=t.detail;t.stopPropagation(),this.value=n.value,this.emit("wpd-pick",{value:n.value})})}set items(t){const n=this.querySelectorAll(":scope > wpd-segment");for(const i of Array.from(n))i.remove();for(const i of t){const r=document.createElement("wpd-segment");r.setAttribute("value",i.value),r.textContent=i.label,this.appendChild(r)}const o=this.value;!(o!==null&&t.some(i=>i.value===o))&&t.length>0?this.value=t[0].value:this.requestUpdate()}render(){const t=this.label||"";t&&this.setAttribute("aria-label",t),this.setAttribute("role","radiogroup");const n=this.value;return queueMicrotask(()=>{const o=this.querySelectorAll("wpd-segment");for(const s of Array.from(o)){const i=s.getAttribute("value");s.setAttribute("aria-checked",i===n?"true":"false")}}),z`<slot></slot>`}};go.props=["value","label"],go.styles=[$E],go.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <wpd-segment> children where exactly one is active.",status:"stable",since:"0.9.0",props:[{name:"value",type:"string",description:"Currently selected segment value. Mirrored onto child aria-checked."},{name:"label",type:"string",description:"aria-label for the radiogroup."}],slots:[{name:"(default)",description:'<wpd-segment value="…"> children.'}],events:[{name:"wpd-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--desktop-mode-window-bg",description:"Pill background."},{name:"--desktop-mode-text",description:"Active label colour."},{name:"--desktop-mode-muted",description:"Inactive label colour."}],example:z` |
| 128 |
<wpd-segmented value="md" label="Dock size"> |
| 129 |
<wpd-segment value="sm">Small</wpd-segment> |
| 130 |
<wpd-segment value="md">Medium</wpd-segment> |
| 131 |
<wpd-segment value="lg">Large</wpd-segment> |
| 132 |
</wpd-segmented> |
| 133 |
`};let Rr=go;me("wpd-segmented",Rr);const HE=he`:host{position:fixed;top:calc( var( --wp-admin--admin-bar--height,32px ) + 16px );inset-inline-end:16px;display:flex;flex-direction:column;gap:8px;z-index:calc( var( --desktop-mode-z-fullscreen,99999 ) + 10 );pointer-events:none}`,BE=he`:host{display:flex;align-items:center;gap:12px;min-width:280px;max-width:420px;padding:10px 14px;background:#1d2327;color:#fff;border-radius:10px;border:1px solid rgba( 255,255,255,0.12 );box-shadow:0 10px 30px rgba( 0,0,0,0.4 ),0 2px 6px rgba( 0,0,0,0.18 ),inset 0 0 0 1px rgba( 255,255,255,0.04 );font-size:13px;line-height:1.4;opacity:0;transform:translateY( -8px );transition:opacity 0.18s ease,transform 0.18s ease;pointer-events:auto}:host( [ state='in' ] ){opacity:1;transform:translateY( 0 )}:host( [ state='out' ] ){opacity:0;transform:translateY( -8px )}.wpd-toast__label{flex:1}button{flex-shrink:0;padding:4px 10px;border:none;border-radius:4px;background:rgba( 255,255,255,0.12 );color:#fff;font:inherit;font-size:12px;font-weight:500;cursor:pointer;transition:background-color 0.12s ease}button:hover{background:rgba( 255,255,255,0.22 )}button:focus-visible{outline:2px solid rgba( 255,255,255,0.6 );outline-offset:2px}.wpd-toast__close{display:inline-flex;align-items:center;justify-content:center;padding:4px;border-radius:6px;background:transparent;color:rgba( 255,255,255,0.7 )}.wpd-toast__close:hover{background:rgba( 255,255,255,0.14 );color:#fff}@media ( prefers-reduced-motion:reduce ){:host{transition-duration:0.01ms}}`,Cs=class Cs extends pe{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return z`<slot></slot>`}};Cs.styles=[HE],Cs.help=void 0;let Mr=Cs;me("wpd-toast-container",Mr);const yo=class yo extends pe{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status")}render(){const t=this.action||"",n=this.hasAttribute("dismissible");return z` |
| 134 |
<span class="wpd-toast__label"><slot></slot></span> |
| 135 |
<button |
| 136 |
type="button" |
| 137 |
?hidden=${!t} |
| 138 |
@click=${o=>this._onAction(o)} |
| 139 |
> |
| 140 |
${t} |
| 141 |
</button> |
| 142 |
<button |
| 143 |
type="button" |
| 144 |
class="wpd-toast__close" |
| 145 |
aria-label=${O("Dismiss")} |
| 146 |
?hidden=${!n} |
| 147 |
@click=${o=>this._onDismiss(o)} |
| 148 |
> |
| 149 |
<svg viewBox="0 0 14 14" width="12" height="12" aria-hidden="true" focusable="false"> |
| 150 |
<path |
| 151 |
d="M3 3 L11 11 M11 3 L3 11" |
| 152 |
stroke="currentColor" |
| 153 |
stroke-width="1.7" |
| 154 |
stroke-linecap="round" |
| 155 |
fill="none" |
| 156 |
></path> |
| 157 |
</svg> |
| 158 |
</button> |
| 159 |
`}_onAction(t){t.preventDefault(),t.stopPropagation(),this.emit("wpd-toast-action",{})}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.emit("wpd-toast-dismiss",{})}};yo.props=["action","state","dismissible"],yo.styles=[BE],yo.help={title:"Toast",summary:'Single transient notification. Message is slotted; fade-in / fade-out is CSS-driven by flipping the state attribute between "in" and "out". Usually created via the showToast() helper rather than authored by hand.',status:"stable",since:"0.9.0",props:[{name:"action",type:"string",description:"Optional action button label. When set, a button renders on the right and emits wpd-toast-action on click."},{name:"state",type:"'in' | 'out'",description:'Drives the CSS fade transition. Set to "in" when rendered, flip to "out" before removal.'},{name:"dismissible",type:"boolean",description:"When set, a close (×) button renders on the right and emits wpd-toast-dismiss on click. Use for persistent toasts the user must be able to close."}],slots:[{name:"(default)",description:"Message text."}],events:[{name:"wpd-toast-action",description:"Fires when the action button is clicked.",detail:"{}"},{name:"wpd-toast-dismiss",description:"Fires when the close (×) button is clicked.",detail:"{}"}],example:z` |
| 160 |
<wpd-toast state="in" action="Undo">Post moved to trash.</wpd-toast> |
| 161 |
`};let Wr=yo;me("wpd-toast",Wr);function Hp(e,t){const n=document.createElement("wpd-segmented");n.setAttribute("value",e),n.setAttribute("label","Capability"),n.style.setProperty("--wpd-segmented-bg","rgba(255,255,255,0.06)"),n.style.setProperty("--desktop-mode-window-bg","var(--wp-admin-theme-color, #2271b1)"),n.style.setProperty("--desktop-mode-text","#fff"),n.style.setProperty("--desktop-mode-muted","rgba(255,255,255,0.65)");const o=document.createElement("wpd-segment");o.setAttribute("value","read"),o.textContent="Read",n.appendChild(o);const s=document.createElement("wpd-segment");return s.setAttribute("value","write"),s.textContent="Read + Write",n.appendChild(s),n.addEventListener("wpd-pick",i=>{const r=i.detail;t(r.value)}),n}function Bp(e,t,n={}){const o=document.createElement("wpd-button");o.setAttribute("variant","ghost"),o.setAttribute("aria-label",n.danger?"Remove":"Dismiss"),o.textContent=e;const s=n.danger?"#ff8080":"rgba(255,255,255,0.75)",i=n.danger?"1px solid rgba(255,128,128,0.45)":"1px solid rgba(255,255,255,0.18)";return o.style.setProperty("--wpd-button-fg",s),o.style.setProperty("--wpd-button-border",i),o.style.setProperty("--wpd-button-padding","6px 12px"),o.style.setProperty("--wpd-button-border-radius","7px"),o.style.setProperty("--wpd-button-min-height","34px"),o.style.minWidth="34px",o.style.fontSize="18px",o.style.lineHeight="1",o.addEventListener("click",t),o}async function Fp(e){const t=document.createElement("wpd-modal");t.setAttribute("open",""),t.setAttribute("size","lg"),t.setAttribute("title",`Share "${e.folderName}"`),document.body.appendChild(t);let n=[],o=[];const s=()=>{t.innerHTML="";const d=document.createElement("div");d.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",d.textContent=e.ownerName?`Owner: ${e.ownerName} — cannot be changed`:"Owner cannot be changed",t.appendChild(d);const c=document.createElement("div");c.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const l=document.createElement("div");l.textContent="Add people",l.style.cssText="font-weight:600;",c.appendChild(l);const u=document.createElement("wpd-user-search"),p=n.filter(k=>k.principalType==="user").map(k=>k.principalRef).concat(o.filter(k=>k.kind==="user").map(k=>k.ref));u.setAttribute("exclude",p.join(",")),u.setAttribute("placeholder","Search users…"),u.addEventListener("wpd-user-pick",k=>{const N=k.detail;o.push({kind:"user",ref:String(N.user.id),label:N.user.name,cap:"read"}),s()}),c.appendChild(u),t.appendChild(c);const f=document.createElement("div");f.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const h=document.createElement("div");h.textContent="Add roles",h.style.cssText="font-weight:600;",f.appendChild(h);const m=document.createElement("wpd-role-picker"),w=n.filter(k=>k.principalType==="role").map(k=>k.principalRef),g=o.filter(k=>k.kind==="role").map(k=>k.ref);if(m.setAttribute("selected",[...w,...g].join(",")),m.addEventListener("wpd-role-toggle",k=>{const N=k.detail,b=n.find(L=>L.principalType==="role"&&L.principalRef===N.slug);if(b){N.selected||r(b);return}if(N.selected){const L=(window.desktopModeConfig?.shareEligibleRoles??[]).find(D=>D.slug===N.slug);o.push({kind:"role",ref:N.slug,label:L?L.name:N.slug,cap:"read"})}else o=o.filter(L=>!(L.kind==="role"&&L.ref===N.slug));s()}),f.appendChild(m),t.appendChild(f),o.length>0){const k=document.createElement("div");k.style.cssText="border:1px dashed rgba(255,255,255,0.18);border-radius:8px;padding:10px;margin-bottom:14px;";const N=document.createElement("div");N.textContent="New invites (not sent yet)",N.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",k.appendChild(N);for(const L of o){const D=document.createElement("div");D.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const C=document.createElement("span");C.textContent=L.kind==="role"?`Role: ${L.label}`:L.label,C.style.flex="1",D.appendChild(C);const S=Hp(L.cap,R=>{L.cap=R});D.appendChild(S);const I=Bp("×",()=>{o=o.filter(R=>!(R.kind===L.kind&&R.ref===L.ref)),s()});D.appendChild(I),k.appendChild(D)}const b=document.createElement("wpd-button");b.setAttribute("variant","primary"),b.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,b.style.marginTop="8px",b.addEventListener("click",async()=>{if(o.length===0)return;b.setAttribute("busy",""),b.setAttribute("disabled","");const L=o.slice();let D=0,C=null;for(const S of L)try{await ip(e.folderId,{principalType:S.kind,principalRef:S.ref,capability:S.cap}),D++}catch(I){C=I;break}D>0&&(o=o.slice(D));try{await i()}catch{}ee(C?{message:`Could not send invites: ${C.message}`}:{message:D===1?"Invite sent.":`${D} invites sent.`}),b.removeAttribute("busy"),b.removeAttribute("disabled"),s()}),k.appendChild(b),t.appendChild(k)}const x=document.createElement("div");if(x.textContent="Who has access",x.style.cssText="font-weight:600;margin:8px 0 6px;",t.appendChild(x),n.length===0){const k=document.createElement("div");k.textContent="Only you can see this folder.",k.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(k)}else for(const k of n){const N=document.createElement("div");N.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const b=document.createElement("div");if(b.style.flex="1",b.textContent=k.principalType==="role"?`Role: ${k.displayName}`:k.displayName,k.state==="pending"){const S=document.createElement("span");S.textContent=" · pending",S.style.cssText="opacity:0.6;font-size:12px;",b.appendChild(S)}else if(k.state==="denied"){const S=document.createElement("span");S.textContent=" · denied",S.style.cssText="color:#d63638;font-size:12px;",b.appendChild(S)}N.appendChild(b);const L=k.capability==="write"?"write":"read",D=Hp(L,S=>{a(k,S)});N.appendChild(D);const C=Bp("×",()=>{r(k)},{danger:!0});N.appendChild(C),t.appendChild(N)}const T=document.createElement("div");T.setAttribute("slot","footer"),T.style.display="flex",T.style.justifyContent="flex-end",T.style.gap="10px",T.style.flexWrap="wrap";const y=document.createElement("wpd-button");y.setAttribute("variant","secondary"),y.textContent="Done",y.addEventListener("click",()=>t.remove()),T.appendChild(y),t.appendChild(T)},i=async()=>{try{n=(await sp(e.folderId)).shares,DE(e.folderId,n)}catch(d){ee({message:`Could not load shares: ${d.message}`})}s()},r=async d=>{try{await ap(e.folderId,d.id),RE(e.folderId,d.id),await i(),ee({message:"Access revoked."})}catch(c){ee({message:`Could not revoke: ${c.message}`})}},a=async(d,c)=>{try{const l=await rp(e.folderId,d.id,c);OE(l),await i()}catch(l){ee({message:`Could not update capability: ${l.message}`})}};t.addEventListener("wpd-modal-cancel",()=>t.remove()),s(),await i()}function FE(e){return new Promise(t=>{const n=document.createElement("wpd-modal");n.setAttribute("open",""),n.setAttribute("title",e.folderName?`${e.ownerName??"Someone"} shared "${e.folderName}" with you`:"Folder shared with you");const o=document.createElement("div"),s=e.capability==="write"?"Read + Write":"Read";o.innerHTML=` |
| 162 |
<p style="margin: 0 0 12px;">Accept the invite to add this folder to your desktop.</p> |
| 163 |
<p style="margin: 0; opacity: 0.75;">Access level: <strong>${s}</strong></p> |
| 164 |
`,n.appendChild(o);const i=document.createElement("div");i.setAttribute("slot","footer"),i.style.display="flex",i.style.justifyContent="flex-end",i.style.gap="10px",i.style.flexWrap="wrap";const r=document.createElement("wpd-button");r.setAttribute("variant","secondary"),r.textContent="Decide later",r.addEventListener("click",()=>{n.remove(),t("dismissed")});const a=document.createElement("wpd-button");a.setAttribute("variant","danger"),a.textContent="Deny",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await cp(e.folderId,e.id),tt().state.deniedFolders.add(e.folderId),tt().notify(),n.remove(),t("denied")}catch(c){ee({message:`Could not deny: ${c.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}});const d=document.createElement("wpd-button");d.setAttribute("variant","primary"),d.textContent="Accept",d.addEventListener("click",async()=>{d.setAttribute("busy",""),d.setAttribute("disabled","");try{await dp(e.folderId,e.id);try{const c=await Me(0);Kt(0,c.placements)}catch{}n.remove(),t("accepted")}catch(c){ee({message:`Could not accept: ${c.message}`}),d.removeAttribute("busy"),d.removeAttribute("disabled")}}),i.appendChild(r),i.appendChild(a),i.appendChild(d),n.appendChild(i),n.addEventListener("wpd-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}function zp(){return Number(window.desktopModeConfig?.currentUserId??0)}function Gp(){const e=window.wp?.desktop?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function jp(e){const t=Et().folders.get(e);return t?Number(t.ownerId):0}function qp(e){if(typeof e!="string")return null;const t=/^desktop-mode-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function zE(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function GE(e){return Number(e.file.ownerId??0)}function jE(){Ds("desktop-mode.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!Gp())return e;const n=zE(t);if(n===null)return e;const o=jp(n)||GE(t),s=zp();if(o===s){const r=!!t.file.shareSummary?.shared?"Manage sharing…":"Share folder…";e.push({id:"desktop-mode/folder-share",label:r,icon:"dashicons-share",sort:30,onClick:()=>{Fp({folderId:n,folderName:t.file.title||`Folder ${n}`})}})}else o>0&&e.push({id:"desktop-mode/folder-leave",label:"Leave shared folder",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await jd({title:"Leave this folder?",message:"The folder will be removed from your desktop. The original and its contents are not deleted; the owner keeps them.",confirmLabel:"Leave",danger:!0}))try{await lp(n),as(t.id);try{const d=await Me(0);Kt(0,d.placements)}catch{}const r=`desktop-mode-folder-${n}`;window.desktopMode?.windowManager?.close?.(r),ee({message:"You left the shared folder."})}catch(r){ee({message:`Could not leave: ${r.message}`})}}});return e}),mc({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!Gp())return!1;const t=e.config.baseId??e.id,n=qp(t);return n===null?!1:jp(n)===zp()},onClick:e=>{const t=e.config.baseId??e.id,n=qp(t);n!==null&&Fp({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),G("desktop-mode.files.tile-rendered","desktop-mode/folder-share",e=>{const{tile:t,placement:n}=e;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||t.querySelector(".desktop-mode-file-tile__share-badge"))return;const s=document.createElement("span");s.className="desktop-mode-file-tile__share-badge dashicons dashicons-share",s.setAttribute("aria-label","Shared folder"),s.title="Shared folder",s.style.cssText=["position:absolute","top:6px","inset-inline-end:6px","background:rgba(0,0,0,0.55)","color:#fff","border-radius:50%","width:18px","height:18px","font-size:12px","line-height:18px","text-align:center","pointer-events:none"].join(";"),t.appendChild(s)})}const Vp=new Set;function qE(){const e=window.wp?.desktop?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function VE(){const e=tt(),t=n=>{if(qE())for(const o of n.pending)Vp.has(o.id)||(Vp.add(o.id),FE({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Up(o.id):s==="denied"&&Up(o.id,{denied:!0,folderId:o.folderId})}))};e.subscribe(t),t(e.state)}b_(),CE(),EE(),LE(),jE();const Pr=window.desktopModeConfig?.serverPendingShares;Array.isArray(Pr)&&Pr.length>0&&$p(Pr),VE();const Ne={DesktopFile:qu,registerType:$e,unregisterType:p_,getType:f_,getTypes:Vu,resolve:is,subscribe:m_,registerOpener:Ue,unregisterOpener:h_,getOpener:w_,getOpeners:Xu,getOpenersForType:ar,resolveOpener:dr,subscribeOpeners:g_,getUserAssociations:rr,open:lr,rest:k_,store:{get:Je,getState:Et,subscribe:yr,setFolderPlacements:Kt,upsertPlacement:hr,removePlacement:as,setFolders:up,upsertFolder:wr,removeFolder:gr}},Kp="__synthFromDockItem";function KE(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function YE(e,t){const n=t[e.id];return{id:KE(e.id),parentId:0,x:n?n.x:0,y:n?n.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Kp]:e.id},file:{type:"shortcut",ref:`dock-promoted:${e.id}`,title:e.title,icon:e.icon,previewUrl:"",exists:!0,shortcutUrl:e.url}}}function XE(){const e=window.wp?.desktop;return e?.getMenuItems?e.getMenuItems().map(o=>({id:o.id,title:o.title,icon:o.icon,url:o.url,badge:o.badge??0,submenu:o.submenu??[],isCore:o.isCore})):window.desktopModeConfig?.dockItems??[]}function ZE(){return window.desktopModeConfig?.desktopIcons??[]}let $r=!1;const Ur=new Map;function JE(e){const t=window.wp?.desktop;if(!t?.getOsSettings||!t?.updateOsSettings)return;const o={...t.getOsSettings().dockPromotedPositions??{}};let s=!1;for(const i of e)i in o&&(delete o[i],s=!0);s&&t.updateOsSettings({dockPromotedPositions:o})}function ws(e,t={},n){if(!$r){$r=!0;try{const o=XE(),s=ZE(),i=new Map(o.map(f=>[f.id,f])),a=Ne.store.getState().placementsByFolder.get(0)??[],d=new Map;for(const f of a){const h=(f.meta??null)&&typeof f.meta=="object"?f.meta[Kp]:null;typeof h=="string"&&d.set(h,f)}const c=new Map,l=new Set(s.map(f=>f.id));for(const f of a){const h=f?.file?.ref;typeof h=="string"&&l.has(h)&&c.set(h,f)}const u=new Set;for(const f of o){const h=wt(f.id,"dock",e),m=h==="desktop"||h==="both",w=n==="spatial"&&!!f.isCore&&(h==="dock"||h==="both");(m||w)&&(u.add(f.id),d.has(f.id)||Ne.store.upsertPlacement(YE(f,t)))}const p=[];for(const[f,h]of d){if(u.has(f))continue;Ne.store.removePlacement(h.id);const w=!!i.get(f)?.isCore&&e[f]===void 0;t[f]&&!w&&p.push(f)}p.length>0&&JE(p);for(const f of s){const h=e[f.id],m=c.get(f.id);if(h==="dock"||h==="hidden"){m&&(Ur.set(f.id,m),Ne.store.removePlacement(m.id));continue}if(!m){const w=Ur.get(f.id);w&&(Ne.store.upsertPlacement(w),Ur.delete(f.id))}}}finally{$r=!1}}}function QE(e,t=()=>({}),n=()=>{}){return queueMicrotask(()=>ws(e(),t(),n())),Ne.store.subscribe(()=>{ws(e(),t(),n())})}const e0=he`:host{display:inline-flex;align-items:center;gap:6px;font-size:var( --wpd-save-status-font-size,11px );line-height:1;color:var( --wpd-save-status-fg,currentColor );vertical-align:middle;min-width:0;opacity:1;pointer-events:auto}.wpd-save-status__indicator{display:inline-flex;align-items:center;justify-content:center;width:12px;height:12px;border-radius:50%;flex-shrink:0;box-sizing:border-box;background:var( --wpd-save-status-bg,transparent );border:2px solid var( --wpd-save-status-idle-color,color-mix( in srgb,var( --wp-admin-theme-color,#2271b1 ) 55%,transparent ) );color:var( --wp-admin-theme-color,#2271b1 );transition:background-color 0.2s ease,border-color 0.2s ease,box-shadow 0.2s ease}:host( [ phase='pending' ] ) .wpd-save-status__indicator,:host( [ phase='saving' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:wpd-save-status-pulse 1.2s ease-in-out infinite}:host( [ animation='modem' ][ phase='pending' ] ) .wpd-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:wpd-save-status-modem-stutter 1.8s ease-in-out infinite,wpd-save-status-modem-glow 2.4s ease-in-out infinite}@keyframes wpd-save-status-modem-stutter{0%,4%{opacity:1}5%,30%{opacity:0.22}31%,36%{opacity:1}37%,39%{opacity:0.22}40%,44%{opacity:1}45%,67%{opacity:0.22}68%,76%{opacity:1}77%,100%{opacity:0.22}}@keyframes wpd-save-status-modem-glow{0%,12%{box-shadow:0 0 0 0 transparent}13%,22%{box-shadow:0 0 4px 0 currentColor}23%,50%{box-shadow:0 0 0 0 transparent}51%,58%{box-shadow:0 0 4px 0 currentColor}59%,84%{box-shadow:0 0 0 0 transparent}85%,94%{box-shadow:0 0 5px 0 currentColor}95%,100%{box-shadow:0 0 0 0 transparent}}@media ( prefers-reduced-motion:reduce ){:host( [ phase='pending' ] ) .wpd-save-status__indicator,:host( [ phase='saving' ] ) .wpd-save-status__indicator,:host( [ animation='modem' ][ phase='pending' ] ) .wpd-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .wpd-save-status__indicator{animation:none;opacity:0.85}}:host( [ phase='saved' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-saved-bg,#1d6f42 );border-color:transparent;color:var( --wpd-save-status-saved-bg,#1d6f42 )}:host( [ phase='failed' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-failed-bg,#d63638 );border-color:transparent;color:var( --wpd-save-status-failed-bg,#d63638 );animation:wpd-save-status-pulse 0.8s ease-in-out 2}@keyframes wpd-save-status-pulse{0%,100%{opacity:0.55;transform:scale( 0.9 )}50%{opacity:1;transform:scale( 1 )}}:host( [ mode='pill' ] ) .wpd-save-status{display:inline-flex;align-items:center;gap:6px;padding:2px 10px;border-radius:999px;background:var( --wpd-save-status-pill-bg,transparent );font-weight:500;white-space:nowrap}:host( [ mode='pill' ][ phase='saving' ] ) .wpd-save-status,:host( [ mode='pill' ][ phase='pending' ] ) .wpd-save-status{background:var( --wpd-save-status-pill-bg,rgba( 0,0,0,0.04 ) );color:var( --wpd-save-status-pill-fg,#50575e )}:host( [ mode='pill' ][ phase='saved' ] ) .wpd-save-status{background:var( --wpd-save-status-pill-bg,rgba( 30,132,73,0.12 ) );color:var( --wpd-save-status-pill-fg,#1d6f42 )}:host( [ mode='pill' ][ phase='failed' ] ) .wpd-save-status{background:var( --wpd-save-status-pill-bg,rgba( 214,54,56,0.12 ) );color:var( --wpd-save-status-pill-fg,#a02622 )}.wpd-save-status__label{min-width:0;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host( [ phase='saved' ] ) .wpd-save-status__glyph,:host( [ phase='failed' ] ) .wpd-save-status__glyph{display:inline-block;color:#fff;width:8px;height:8px}.wpd-save-status__glyph{display:none}.wpd-save-status__glyph svg{display:block;width:100%;height:100%}`,Yp="desktop-mode-os-settings-save-lifecycle",t0=2200,n0=6e3,bo=class bo extends pe{constructor(){super(...arguments),this._autoTimer=null,this._docListener=null}connectedCallback(){super.connectedCallback(),this.auto!==null&&this._installAutoListener()}disconnectedCallback(){this._removeAutoListener(),this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback(t,n,o),(t==="auto"||t==="event")&&(this._removeAutoListener(),this.auto!==null&&this._installAutoListener()),t==="phase"){this._scheduleAutoClear();const s={phase:this.phase??"idle",error:this.error??void 0};this.emit("wpd-save-status-change",s)}}render(){const t=this.phase??"idle",n=this.mode??"dot",s=(this.error??"")||this._labelForPhase(t);return s?this.setAttribute("title",s):this.removeAttribute("title"),this.setAttribute("aria-live",t==="failed"?"assertive":"polite"),this.setAttribute("role",t==="failed"?"alert":"status"),z` |
| 165 |
<span class="wpd-save-status"> |
| 166 |
<span class="wpd-save-status__indicator" aria-hidden="true"> |
| 167 |
<span class="wpd-save-status__glyph">${this._renderGlyph(t)}</span> |
| 168 |
</span> |
| 169 |
${n==="pill"?z`<span class="wpd-save-status__label" |
| 170 |
>${this._labelForPhase(t)}</span |
| 171 |
>`:z``} |
| 172 |
</span> |
| 173 |
`}_renderGlyph(t){return t==="saved"?o0():t==="failed"?s0():""}_labelForPhase(t){switch(t){case"pending":case"saving":return this["saving-label"]??"Saving…";case"saved":return this["saved-label"]??"Saved";case"failed":return(this.error??"")||"Couldn’t save";default:return this["idle-label"]??""}}_installAutoListener(){const t=this.event||Yp;this._docListener=n=>{const o=n.detail;!o||typeof o.phase!="string"||(this.phase=o.phase,o.error?this.error=o.error:o.phase!=="failed"&&this.error&&this.removeAttribute("error"))},document.addEventListener(t,this._docListener)}_removeAutoListener(){if(!this._docListener)return;const t=this.event||Yp;document.removeEventListener(t,this._docListener),this._docListener=null}_scheduleAutoClear(){this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null);const t=this.phase??"idle",n=this._autoClearMsFor(t);n<=0||(this._autoTimer=window.setTimeout(()=>{this._autoTimer=null,this.phase="idle"},n))}_autoClearMsFor(t){if(t==="saved"){const n=this["auto-clear-saved-ms"];return parseInt(n||"",10)||t0}if(t==="failed"){const n=this["auto-clear-failed-ms"];return parseInt(n||"",10)||n0}return 0}};bo.props=["phase","mode","animation","auto","event","error","saving-label","saved-label","idle-label","auto-clear-saved-ms","auto-clear-failed-ms"],bo.styles=[e0],bo.help=void 0;let Hr=bo;me("wpd-save-status",Hr);function o0(){return z` |
| 174 |
<svg |
| 175 |
viewBox="0 0 12 12" |
| 176 |
aria-hidden="true" |
| 177 |
focusable="false" |
| 178 |
fill="none" |
| 179 |
stroke="currentColor" |
| 180 |
stroke-width="2" |
| 181 |
stroke-linecap="round" |
| 182 |
stroke-linejoin="round" |
| 183 |
> |
| 184 |
<path d="M2.5 6 L5 8.5 L9.5 4" /> |
| 185 |
</svg> |
| 186 |
`}function s0(){return z` |
| 187 |
<svg |
| 188 |
viewBox="0 0 12 12" |
| 189 |
aria-hidden="true" |
| 190 |
focusable="false" |
| 191 |
fill="currentColor" |
| 192 |
> |
| 193 |
<path |
| 194 |
d="M5 2 H7 V7 H5 z M5 8.5 H7 V10.5 H5 z" |
| 195 |
/> |
| 196 |
</svg> |
| 197 |
`}const i0=he`:host{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var( --desktop-mode-text,#1d2327 );min-width:0}:host( [ hidden ] ){display:none}.wpd-textarea__label{font-size:12px;color:var( --desktop-mode-muted,#646970 )}textarea{appearance:none;-webkit-appearance:none;display:block;width:100%;min-width:0;box-sizing:border-box;padding:8px 10px;background:var( --desktop-mode-window-bg,#fff );border:1px solid var( --desktop-mode-border,#dcdcde );border-radius:6px;font:inherit;font-size:13px;line-height:1.45;color:var( --desktop-mode-text,#1d2327 );resize:vertical;transition:border-color 0.12s ease,box-shadow 0.12s ease}textarea:hover{border-color:var( --desktop-mode-muted,#8c8f94 )}textarea:focus-visible{outline:none;border-color:var( --wp-admin-theme-color,#2271b1 );box-shadow:0 0 0 1px var( --wp-admin-theme-color,#2271b1 )}textarea:disabled{opacity:0.55;cursor:not-allowed;background:rgba( 0,0,0,0.03 )}textarea[ aria-invalid='true' ]{border-color:#d63638}textarea[ aria-invalid='true' ]:focus-visible{box-shadow:0 0 0 1px #d63638}:host( [ auto-grow ] ) textarea{resize:none;overflow:hidden}`,vo=class vo extends pe{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),Gd(this)}render(){const t=this._attr("label")||"",n=this._attr("value")??"",o=this._attr("placeholder")||"",s=this._boolAttr("disabled"),i=this._boolAttr("readonly"),r=this._attr("aria-label")||t,a=this._attr("name")||"",d=Number(this._attr("rows"))||3,c=this._attr("maxlength"),l=this._attr("minlength"),u=this._boolAttr("invalid"),f=`${this.id||"wpd-unnamed"}__field`;return z` |
| 198 |
${t?z`<label class="wpd-textarea__label" for=${f}>${t}</label>`:z``} |
| 199 |
<textarea |
| 200 |
id=${f} |
| 201 |
part="textarea" |
| 202 |
.value=${n} |
| 203 |
placeholder=${o} |
| 204 |
?disabled=${s} |
| 205 |
?readonly=${i} |
| 206 |
rows=${d} |
| 207 |
maxlength=${c??""} |
| 208 |
minlength=${l??""} |
| 209 |
name=${a} |
| 210 |
aria-invalid=${u?"true":"false"} |
| 211 |
aria-label=${r||""} |
| 212 |
@input=${h=>this._onInput(h)} |
| 213 |
@change=${h=>this._onChange(h)} |
| 214 |
@keydown=${h=>this._onKeyDown(h)} |
| 215 |
></textarea> |
| 216 |
`}_attr(t){return this.getAttribute(t)}_boolAttr(t){return this.getAttribute(t)!==null}_onInput(t){const n=t.target;this._textareaEl=n,this.setAttribute("value",n.value),this.emit("wpd-input-change",{value:n.value}),this._boolAttr("auto-grow")&&this._autosize(n)}_onChange(t){const n=t.target;this.emit("wpd-input-commit",{value:n.value})}_onKeyDown(t){if(this._boolAttr("submit-on-enter")&&t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey&&!t.ctrlKey){t.preventDefault();const n=t.target;this.emit("wpd-submit",{value:n.value})}}_autosize(t){const n=Number(this._attr("max-rows"))||8,o=window.getComputedStyle(t),s=parseFloat(o.fontSize)||13,i=o.lineHeight,r=i==="normal"?s*1.45:parseFloat(i)||s*1.45,a=parseFloat(o.paddingTop)||0,d=parseFloat(o.paddingBottom)||0,c=r*n+a+d;t.style.height="auto";const l=Math.min(t.scrollHeight,c);t.style.height=`${l}px`}refreshAutosize(){this._textareaEl&&this._boolAttr("auto-grow")&&this._autosize(this._textareaEl)}focusInput(){(this.shadowRoot??this).querySelector("textarea")?.focus()}clear(){this.setAttribute("value","");const n=(this.shadowRoot??this).querySelector("textarea");n&&(n.value="",this._boolAttr("auto-grow")&&this._autosize(n))}};vo.props=["label","value","placeholder","disabled","readonly","ariaLabel","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],vo.styles=[i0],vo.help=void 0;let Br=vo;me("wpd-textarea",Br);const r0=he`:host{display:inline-flex}button{display:flex;align-items:center;justify-content:center;width:30px;height:30px;padding:0;border:none;border-radius:5px;background:transparent;color:var( --wpd-btn-color,currentColor );cursor:pointer;transition:background-color 0.15s ease,color 0.15s ease}button:hover{color:var( --wpd-btn-color-hover,currentColor );background:var( --wpd-btn-bg-hover,rgba( 0,0,0,0.06 ) )}button:focus-visible{color:var( --wpd-btn-color-hover,currentColor );background:var( --wpd-btn-bg-hover,rgba( 0,0,0,0.06 ) );outline:2px solid var( --wpd-btn-outline,currentColor );outline-offset:1px}:host( [ active ] ) button{color:var( --wpd-btn-color-hover,currentColor );background:var( --wpd-btn-bg-active,rgba( 0,0,0,0.08 ) )}:host( [ danger ] ) button:hover{color:#fff;background:var( --wpd-btn-danger-hover,#d63638 )}svg{display:block;pointer-events:none;flex-shrink:0}svg:empty{display:none}::slotted( span ){line-height:1}::slotted( svg ){display:block}`,a0={minimize:'<path d="M3 6h6" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>',maximize:'<rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="1.25" fill="none"/>',fullscreen:'<path d="M4.5 2H2v2.5M10 4.5V2H7.5M4.5 10H2V7.5M10 7.5V10H7.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',"fullscreen-exit":'<path d="M2 4.5H4.5V2M7.5 2V4.5H10M2 7.5H4.5V10M7.5 10V7.5H10" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',detach:'<path d="M5 2H2.5v7.5H10V7M6.5 2H10v3.5M10 2L5.5 6.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',reload:'<g transform="translate(0.6 0.6) scale(0.021)" fill="currentColor"><path d="m504.554 233.704-76.447 91.467c-6.329 7.572-15.417 11.479-24.571 11.479a31.872 31.872 0 0 1-20.504-7.447l-91.467-76.447c-13.561-11.334-15.366-31.515-4.032-45.075s31.515-15.366 45.075-4.032l37.506 31.347c-10.274-74.891-74.668-132.774-152.337-132.774C132.984 102.223 64 171.207 64 256s68.984 153.777 153.777 153.777c17.673 0 32 14.327 32 32s-14.327 32-32 32c-58.17 0-112.859-22.653-153.991-63.785C22.653 368.859 0 314.17 0 256s22.653-112.859 63.786-153.992c41.132-41.132 95.821-63.785 153.991-63.785s112.859 22.653 153.992 63.785c32.517 32.516 53.471 73.508 60.829 117.991l22.849-27.339c11.334-13.56 31.515-15.364 45.075-4.032 13.56 11.335 15.365 31.516 4.032 45.076z"/></g>',close:'<path d="M3.25 3.25l5.5 5.5M3.25 8.75l5.5-5.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>',menu:'<circle cx="3" cy="6" r="1.2" fill="currentColor"/><circle cx="6" cy="6" r="1.2" fill="currentColor"/><circle cx="9" cy="6" r="1.2" fill="currentColor"/>'},ko=class ko extends pe{constructor(){super(...arguments),this._activateWired=!1}render(){const t=this.icon||"",n=a0[t]||"";return z` |
| 217 |
<button type="button"> |
| 218 |
<svg |
| 219 |
width="14" |
| 220 |
height="14" |
| 221 |
viewBox="0 0 12 12" |
| 222 |
aria-hidden="true" |
| 223 |
focusable="false" |
| 224 |
></svg> |
| 225 |
<slot></slot> |
| 226 |
</button> |
| 227 |
<span data-svg-buffer style="display:none">${n}</span> |
| 228 |
`}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paintSvg()),queueMicrotask(()=>this._wireActivateEvent())}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),queueMicrotask(()=>this._paintSvg())}_paintSvg(){const t=this.shadowRoot;if(!t)return;const n=t.querySelector("svg"),o=t.querySelector("[data-svg-buffer]");if(n&&o){const s=o.textContent||"";n.innerHTML!==s&&(n.innerHTML=s)}}_wireActivateEvent(){if(this._activateWired)return;const t=this.shadowRoot;if(!t)return;const n=t.querySelector("button");n&&(this._activateWired=!0,n.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("wpd-button-activate",{bubbles:!0,composed:!0,cancelable:!0}))}))}};ko.props=["icon","active","danger"],ko.styles=[r0],ko.help=void 0;let Fr=ko;me("wpd-window-button",Fr);const lt="Sticky Note",d0="<!-- wpworkspace-sticky:",zr="-->",c0=64,l0=48,u0=180;function Gr(e){const t=p0(e.title),n=g0(f0(e.content,{stripHtmlForRendered:!0})),o=y0(e);return{localId:`guideline:${e.id}`,guidelineId:e.id,title:t,body:h0(t,n),modified:e.modified,...o>0?{modifiedMs:o}:{},link:e.link,termIds:Array.isArray(e.wp_guideline_type)?e.wp_guideline_type.filter(b0):[]}}function p0(e){const t=[];typeof e=="string"?t.push(e):e&&typeof e=="object"&&(typeof e.raw=="string"&&t.push(e.raw),typeof e.rendered=="string"&&t.push(jr(e.rendered)));for(const n of t){const o=jr(n).trim();if(o)return o}return lt}function f0(e,t={}){return typeof e=="string"?e:!e||typeof e!="object"?"":typeof e.raw=="string"&&e.raw.length>0?e.raw:typeof e.rendered=="string"?t.stripHtmlForRendered?jr(e.rendered):e.rendered:""}function Xp(e){const t=e.split(/\r?\n/).find(o=>o.trim().length>0)?.trim(),n=t&&t.length>0?t:lt;return qr(n,c0)}function m0(e){const n=e.replace(/\s+/g," ").trim()||lt;return qr(n,l0)}function h0(e,t){const n=e.trim();return!n||t.split(/\r?\n/)[0]?.trim()===n?t:t?`${n} |
| 229 |
${t}`:n}function w0(e,t=lt){const n=t.trim()||lt,o=Xp(e),s=e.search(/\r?\n/);if(s===-1){const r=o===lt?n:o;return{title:r,content:"",excerpt:Zp(r)}}let i=e.slice(s);return i=i.replace(/^\r?\n/,""),i.startsWith(` |
| 230 |
`)&&(i=i.slice(1)),{title:o,content:i,excerpt:Zp(i.trim()?i:o)}}function Zp(e){const t=e.replace(/[\n\t]+/g," ").trim();return qr(t,u0)}function g0(e){if(!e.startsWith(d0)||!e.includes(zr))return e;const t=e.indexOf(zr);let n=e.slice(t+zr.length);return n.startsWith(`\r |
| 231 |
`)?n=n.slice(2):n.startsWith(` |
| 232 |
`)&&(n=n.slice(1)),n}function jr(e){if(typeof document<"u"){const t=document.createElement("template");return t.innerHTML=e,(t.content.textContent??"").trim()}return e.replace(/<[^>]*>/g,"").trim()}function qr(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function y0(e){if(typeof e.desktop_mode_modified_ms=="number"&&Number.isFinite(e.desktop_mode_modified_ms))return e.desktop_mode_modified_ms;if(!e.modified)return 0;const t=Date.parse(e.modified);return Number.isFinite(t)?t:0}function b0(e){return typeof e=="number"&&Number.isFinite(e)}class Jp extends Error{constructor(t,n){super(t),this.name="StickyNotesRestError",this.status=n}}async function v0(e){const t=await k0(e),n=_0([...t.artifactTerms,...t.artifactsTerms],t.noteTerms,t.stickyTerms);if(n)return n;const o=await Vr(e,{slug:"artifact",name:"Artifact",parent:0}),s=await Vr(e,{slug:"note",name:"Note",parent:o.id}),i=await Vr(e,{slug:"sticky",name:"Sticky",parent:o.id});return{stickyTermId:i.id,termIds:tf([o.id,s.id,i.id])}}async function k0(e){const[t,n,o,s]=await Promise.all([Jt(e,"artifact"),Jt(e,"artifacts"),Jt(e,"note"),Jt(e,"sticky")]);return{artifactTerms:t,artifactsTerms:n,noteTerms:o,stickyTerms:s}}function _0(e,t,n){if(n.length===0)return null;const o=e.find(r=>["artifact","artifacts"].includes(r.slug))??e[0]??null,s=o?n.find(r=>Number(r.parent)===o.id)??n[0]:n[0];if(!s)return null;const i=o?t.find(r=>Number(r.parent)===o.id)??null:null;return{stickyTermId:s.id,termIds:tf([o?.id,i?.id,s.id])}}async function Qp(e,t){return(await gs(e,ef("wp/v2/guidelines",{context:"edit",status:"private",per_page:"100",orderby:"modified",order:"desc",wp_guideline_type:String(t)}),void 0,!0)).filter(o=>Array.isArray(o.wp_guideline_type)?o.wp_guideline_type.includes(t):!0).map(Gr)}async function E0(e,t,n){const o=w0(t.body,t.title),s={status:"private",title:o.title,content:o.content,excerpt:o.excerpt};t.guidelineId===null&&(s.wp_guideline_type=n.termIds);const i=t.guidelineId===null?"wp/v2/guidelines":`wp/v2/guidelines/${t.guidelineId}`,r=await gs(e,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},!1);return Gr(r)}function S0(e,t){const n=new URL("post.php",e);return n.searchParams.set("post",String(t)),n.searchParams.set("action","edit"),n.toString()}async function Jt(e,t){try{return await gs(e,ef("wp/v2/wp_guideline_type",{context:"edit",slug:t,per_page:"100"}),void 0,!0)}catch(n){if(n instanceof Jp&&(n.status===404||n.status===400))return[];throw n}}async function Vr(e,t){const n=await Jt(e,t.slug),o=n.find(s=>Number(s.parent??0)===t.parent);if(o)return o;if(n[0])return n[0];try{return await gs(e,"wp/v2/wp_guideline_type",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},!0)}catch(s){const i=await Jt(e,t.slug);if(i[0])return i[0];throw s}}async function gs(e,t,n,o=!0){const s=await ze(wn(I0(e),t),n,{source:"desktop-mode/sticky-notes",silent:o});if(!s.ok)throw new Jp(s.statusText||`${lt} request failed`,s.status);return await s.json()}function I0(e){return e.restUrl?e.restUrl:`${window.location.origin}/wp-json/`}function ef(e,t){const n=new URLSearchParams;return Object.entries(t).forEach(([o,s])=>{n.set(o,s)}),`${e}?${n.toString()}`}function tf(e){const t=[];return e.forEach(n=>{typeof n=="number"&&Number.isFinite(n)&&!t.includes(n)&&t.push(n)}),t}const x0="desktop_mode_sticky_notes_subscribe",C0="desktop_mode_sticky_notes";let nf=!1,Kr=null;function A0(e){Kr=e,!nf&&(nf=!0,Xe.contribute(x0,()=>Kr?.getHeartbeatSubscription()),Xe.subscribe(C0,t=>{Kr?.applyHeartbeatPayload(t)}))}const of="desktop-mode-sticky-notes-geometry",L0=264,T0=176,Yr=180,Xr=128,de=16,N0=1e3;class D0{constructor(t){this.root=null,this.terms=null,this.controllers=new Map,this.contextMenuInstalled=!1,this.desktopHooksInstalled=!1,this.highWaterMs=0,this.zIndexCounter=0,this.host=t.host,this.config=t.config,this.available=t.available??!0,this.openArtifact=t.openArtifact,this.getActiveDesktopId=t.getActiveDesktopId??(()=>"desktop-1"),this.onError=t.onError}async boot(){if(this.available)try{if(this.terms=await v0(this.config),!this.terms)return;this.installContextMenu(),this.installDesktopHooks();const t=await Qp(this.config,this.terms.stickyTermId);if(this.bumpHighWaterFromNotes(t),A0(this),t.length===0)return;this.ensureRoot(),sf(t).forEach((n,o)=>this.upsert(n,o))}catch(t){t instanceof Error&&console.debug("[desktop-mode] Sticky notes unavailable:",t.message)}}createNote(t=""){if(!this.terms)return;const n={localId:`local:${Date.now()}:${Math.random().toString(36).slice(2)}`,guidelineId:null,title:t.trim()?m0(t):lt,body:t,termIds:this.terms.termIds};this.upsert(n,this.controllers.size,{activate:!0}).focus()}upsert(t,n,o={}){this.ensureRoot();const s=De(t),i=this.controllers.get(s);if(i)return i.replace(t),o.activate&&this.bringToFront(i),i;const r=new O0({layer:this,note:t,index:n});return this.controllers.set(s,r),this.root?.appendChild(r.element),this.assignZIndex(r),this.applyDesktopVisibility(r),o.activate&&this.bringToFront(r),r}ensureRoot(){if(this.root)return this.root;const t=document.createElement("section");return t.className="desktop-mode-sticky-notes",t.setAttribute("aria-label",O("Sticky notes")),this.host.appendChild(t),this.root=t,t}installContextMenu(){this.contextMenuInstalled||(this.contextMenuInstalled=!0,Ds("desktop-mode.wallpaper-context-menu","desktop-mode/sticky-notes",t=>!Array.isArray(t)||!this.terms||t.some(n=>n.id==="new-sticky-note")?t:[...t,{id:"new-sticky-note",label:O("New sticky note"),icon:"dashicons-edit-page",sort:14,onClick:()=>this.createNote()}]))}installDesktopHooks(){this.desktopHooksInstalled||(this.desktopHooksInstalled=!0,G(v.DESKTOP_SWITCHED,"desktop-mode/sticky-notes",()=>this.refreshDesktopVisibility()),G(v.DESKTOP_CLOSED,"desktop-mode/sticky-notes",t=>{this.migrateDesktopAssignments(t?.desktopId,t?.migratedTo),this.refreshDesktopVisibility()}))}save(t){return this.terms?E0(this.config,t,this.terms):Promise.reject(new Error(O("Sticky term is unavailable.")))}getHeartbeatSubscription(){if(this.terms)return{stickyTermId:this.terms.stickyTermId,knownIds:this.knownGuidelineIds(),version:this.highWaterMs}}applyHeartbeatPayload(t){for(const n of t.notes??[]){const o=Gr(n);this.upsertRemote(o)}for(const n of t.removed??[])this.forgetGuidelineId(n);typeof t.serverTimeMs=="number"&&Number.isFinite(t.serverTimeMs)&&t.serverTimeMs>this.highWaterMs&&(this.highWaterMs=t.serverTimeMs),t.truncated&&this.reloadFromServer()}openNoteArtifact(t){t.guidelineId!==null&&this.openArtifact(S0(this.config.adminUrl,t.guidelineId),t.title,t.guidelineId)}notifyError(t){this.onError?.(t)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}defaultGeometry(t){const{width:n,height:o}=this.hostSize(),s=Math.min(L0,Math.max(Yr,n-de*2)),i=Math.min(T0,Math.max(Xr,o-de*2)),r=t%8*28,a=qe(n-s-32-r,de,Math.max(de,n-s-de)),d=qe(32+r,de,Math.max(de,o-i-de));return{x:a/n,y:d/o,width:s,height:i}}forget(t){this.controllers.delete(De(t.note)),t.dispose(),t.element.remove(),this.controllers.size===0&&(this.root?.remove(),this.root=null)}replaceControllerKey(t,n){const o=De(n.note);this.controllers.delete(t),this.controllers.set(o,n),M0(t,o),this.applyDesktopVisibility(n)}bumpHighWaterFromNote(t){const n=eo(t);n>this.highWaterMs&&(this.highWaterMs=n)}bringToFront(t){t.setZIndex(this.nextZIndex())}geometryForNote(t,n){const o=De(t),s=Zr(o),i=this.normalizeDesktopId(s?.desktopId),r=s?{...s,desktopId:i}:{...this.defaultGeometry(n),desktopId:i};return(!s||s.desktopId!==r.desktopId)&&Jr(o,r),r}upsertRemote(t){const n=De(t),o=this.controllers.get(n);if(o)return o.shouldReplaceFromRemote(t)?(o.replace(t),this.bumpHighWaterFromNote(t),o):(this.bumpHighWaterFromNote(t),o);const s=this.upsert(t,this.controllers.size);return this.bumpHighWaterFromNote(t),s}forgetGuidelineId(t){for(const n of this.controllers.values())if(n.note.guidelineId===t){this.forget(n);return}}knownGuidelineIds(){const t=[];for(const n of this.controllers.values())n.note.guidelineId!==null&&t.push(n.note.guidelineId);return t}bumpHighWaterFromNotes(t){t.forEach(n=>this.bumpHighWaterFromNote(n))}assignZIndex(t){t.setZIndex(this.nextZIndex())}nextZIndex(){return this.zIndexCounter+=1,this.zIndexCounter}applyDesktopVisibility(t){t.setVisible(this.isNoteOnActiveDesktop(t.note))}refreshDesktopVisibility(){for(const t of this.controllers.values())this.applyDesktopVisibility(t)}isNoteOnActiveDesktop(t){const n=De(t),o=Zr(n),s=this.normalizeDesktopId(o?.desktopId);return o&&o.desktopId!==s&&Jr(n,{...o,desktopId:s}),s===this.activeDesktopId()}migrateDesktopAssignments(t,n){if(!t||!n||t===n)return;const o=ys();let s=!1;Object.entries(o).forEach(([i,r])=>{r.desktopId===t&&(o[i]={...r,desktopId:this.normalizeDesktopId(n)},s=!0)}),s&&Qr(o)}activeDesktopId(){try{const t=this.getActiveDesktopId();return typeof t=="string"&&t?t:"desktop-1"}catch{return"desktop-1"}}normalizeDesktopId(t){return t||this.activeDesktopId()}async reloadFromServer(){if(this.terms)try{const t=await Qp(this.config,this.terms.stickyTermId),n=new Set;sf(t).forEach(o=>{o.guidelineId!==null&&n.add(o.guidelineId),this.upsertRemote(o)}),this.knownGuidelineIds().forEach(o=>{n.has(o)||this.forgetGuidelineId(o)})}catch{}}}class O0{constructor(t){this.saveTimer=null,this.geometryTimer=null,this.saving=!1,this.saveAgain=!1,this.resizeObserver=null,this.disposed=!1,this.layer=t.layer,this.note=t.note,this.index=t.index,this.element=document.createElement("article"),this.element.className="desktop-mode-sticky-note",this.element.dataset.stickyNoteId=De(this.note),this.titleEl=document.createElement("span"),this.editor=document.createElement("wpd-textarea"),this.statusEl=document.createElement("wpd-save-status"),this.openButton=document.createElement("wpd-window-button"),this.paint(),this.applyGeometry(this.layer.geometryForNote(this.note,this.index)),this.element.addEventListener("pointerdown",()=>this.layer.bringToFront(this),{capture:!0}),this.element.addEventListener("focusin",()=>this.layer.bringToFront(this)),this.watchResize()}focus(){window.setTimeout(()=>this.editor.focusInput?.(),0)}replace(t){this.note=t,this.element.dataset.stickyNoteId=De(this.note),this.titleEl.textContent=this.note.title,this.editor.setAttribute("value",this.note.body),this.refreshOpenButton()}shouldReplaceFromRemote(t){if(this.hasLocalChanges())return!1;const n=eo(this.note),o=eo(t);return!(n>0&&o>0&&o<=n&&this.note.title===t.title&&this.note.body===t.body)}setZIndex(t){this.element.style.zIndex=String(t)}setVisible(t){this.element.style.display=t?"":"none"}dispose(){this.disposed=!0,this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.geometryTimer!==null&&(window.clearTimeout(this.geometryTimer),this.geometryTimer=null),this.resizeObserver?.disconnect(),this.resizeObserver=null}paint(){this.element.innerHTML="",this.element.style.minWidth=`${Yr}px`,this.element.style.minHeight=`${Xr}px`;const t=document.createElement("div");t.className="desktop-mode-sticky-note__header";const n=document.createElement("span");n.className="desktop-mode-sticky-note__grip",n.setAttribute("aria-hidden","true"),this.titleEl.className="desktop-mode-sticky-note__title",this.titleEl.textContent=this.note.title,this.statusEl.setAttribute("mode","icon"),this.statusEl.setAttribute("phase","idle"),this.statusEl.className="desktop-mode-sticky-note__status",this.openButton.setAttribute("icon","detach"),this.openButton.setAttribute("title",O("Open artifact")),this.openButton.className="desktop-mode-sticky-note__open",this.openButton.addEventListener("wpd-button-activate",()=>{this.layer.openNoteArtifact(this.note)});const o=document.createElement("wpd-window-button");o.setAttribute("icon","close"),o.setAttribute("danger",""),o.setAttribute("title",O("Hide sticky note")),o.className="desktop-mode-sticky-note__close",o.addEventListener("wpd-button-activate",()=>this.close()),t.append(n,this.titleEl,this.statusEl,this.openButton,o),t.addEventListener("pointerdown",s=>this.startDrag(s)),this.editor.className="desktop-mode-sticky-note__editor",this.editor.setAttribute("aria-label",O("Sticky note text")),this.editor.setAttribute("rows","8"),this.editor.setAttribute("value",this.note.body),this.installEditorKeyboardGuard(),this.editor.addEventListener("wpd-input-change",s=>{const i=s.detail;this.note.body=i.value,this.note.title=Xp(i.value),this.titleEl.textContent=this.note.title,this.setPhase("pending"),this.scheduleSave()}),this.editor.addEventListener("wpd-input-commit",()=>this.flushSave()),this.element.append(t,this.editor),this.refreshOpenButton()}installEditorKeyboardGuard(){["keydown","keypress","keyup"].forEach(t=>{this.editor.addEventListener(t,n=>{n.stopPropagation()})})}refreshOpenButton(){const t=this.note.guidelineId===null;this.openButton.classList.toggle("is-disabled",t),this.openButton.setAttribute("aria-disabled",t?"true":"false")}close(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.layer.forget(this);return}this.flushSave(),this.layer.forget(this)}scheduleSave(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.setPhase("idle");return}this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},N0)}flushSave(){this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),(this.note.guidelineId!==null||this.note.body.trim().length>0)&&this.save()}async save(){if(this.saving){this.saveAgain=!0,this.setPhase("pending");return}this.saving=!0,this.setPhase("saving");const t=this.note.body;try{const n=await this.layer.save({...this.note,body:t});if(this.disposed)return;const o=De(this.note);this.note.guidelineId=n.guidelineId,this.note.modified=n.modified,this.note.link=n.link,this.note.termIds=n.termIds.length>0?n.termIds:this.note.termIds,this.note.body===t&&(this.note.title=n.title,this.titleEl.textContent=n.title),o!==De(this.note)&&(this.element.dataset.stickyNoteId=De(this.note),this.layer.replaceControllerKey(o,this)),this.layer.bumpHighWaterFromNote(this.note),this.refreshOpenButton(),this.setPhase("saved")}catch(n){if(this.disposed)return;const o=n instanceof Error?n.message:O("Could not save sticky note.");this.setPhase("failed",o),this.layer.notifyError(o)}finally{this.saving=!1,!this.disposed&&this.saveAgain&&(this.saveAgain=!1,this.scheduleSave())}}setPhase(t,n){this.statusEl.setAttribute("phase",t),n?(this.statusEl.setAttribute("error",n),this.statusEl.setAttribute("title",n)):(this.statusEl.removeAttribute("error"),this.statusEl.removeAttribute("title"))}hasLocalChanges(){const t=this.statusEl.getAttribute("phase");return this.saveTimer!==null||this.saving||this.saveAgain||t==="pending"||t==="failed"}startDrag(t){if(t.button!==0||t.target?.closest("wpd-window-button, wpd-save-status"))return;t.preventDefault();const o=this.element.getBoundingClientRect(),s=this.layerHostRect(),i=o.left-s.left,r=o.top-s.top,a=t.clientX,d=t.clientY;this.element.classList.add("desktop-mode-sticky-note--dragging"),this.element.setPointerCapture?.(t.pointerId);const c=u=>{const p=this.element.offsetWidth,f=this.element.offsetHeight,{width:h,height:m}=this.layer.hostSize(),w=qe(i+u.clientX-a,de,Math.max(de,h-p-de)),g=qe(r+u.clientY-d,de,Math.max(de,m-f-de));this.element.style.left=`${w}px`,this.element.style.top=`${g}px`},l=u=>{this.element.classList.remove("desktop-mode-sticky-note--dragging"),this.element.releasePointerCapture?.(u.pointerId),document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",l),this.persistGeometry()};document.addEventListener("pointermove",c),document.addEventListener("pointerup",l)}applyGeometry(t){const{width:n,height:o}=this.layer.hostSize(),s=qe(t.width,Yr,n-de*2),i=qe(t.height,Xr,o-de*2),r=qe(t.x*n,de,Math.max(de,n-s-de)),a=qe(t.y*o,de,Math.max(de,o-i-de));this.element.style.left=`${r}px`,this.element.style.top=`${a}px`,this.element.style.width=`${s}px`,this.element.style.height=`${i}px`}watchResize(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.geometryTimer!==null&&window.clearTimeout(this.geometryTimer),this.geometryTimer=window.setTimeout(()=>{this.geometryTimer=null,this.persistGeometry()},150)}),this.resizeObserver.observe(this.element))}persistGeometry(){const{width:t,height:n}=this.layer.hostSize(),o=parseFloat(this.element.style.left)||0,s=parseFloat(this.element.style.top)||0,i=Zr(De(this.note));Jr(De(this.note),{...i??{},x:qe(o/t,0,1),y:qe(s/n,0,1),width:this.element.offsetWidth,height:this.element.offsetHeight})}layerHostRect(){return(this.element.parentElement?.parentElement??document.body).getBoundingClientRect()}}function R0(e){const t=new D0(e);return t.boot(),t}function De(e){return e.guidelineId===null?e.localId:`guideline:${e.guidelineId}`}function eo(e){if(typeof e.modifiedMs=="number"&&Number.isFinite(e.modifiedMs))return e.modifiedMs;if(!e.modified)return 0;const t=Date.parse(e.modified);return Number.isFinite(t)?t:0}function sf(e){return[...e].sort((t,n)=>eo(t)-eo(n))}function Zr(e){const n=ys()[e];return!n||!Number.isFinite(n.x)||!Number.isFinite(n.y)||!Number.isFinite(n.width)||!Number.isFinite(n.height)?null:n}function Jr(e,t){const n=ys();n[e]=t,Qr(n)}function M0(e,t){if(e===t)return;const n=ys();n[e]&&(n[t]=n[e],delete n[e],Qr(n))}function ys(){try{const e=window.localStorage.getItem(of);return e?JSON.parse(e):{}}catch{return{}}}function Qr(e){try{window.localStorage.setItem(of,JSON.stringify(e))}catch{}}function qe(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}const W0={id:"clock",get label(){return O("Clock")},get description(){return O("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("desktop-mode-widget-clock");const t=document.createElement("div");t.className="desktop-mode-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="desktop-mode-widget-clock__date",e.appendChild(n);const o=()=>{const a=new Date;t.textContent=a.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=a.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})};o();const s=1e3-Date.now()%1e3;let i=null;const r=window.setTimeout(()=>{o(),i=window.setInterval(o,1e3)},s);return()=>{window.clearTimeout(r),i!==null&&window.clearInterval(i)}}};function P0(){Li(W0)}const rf="desktop-mode-release-card-styles",af="desktop-mode-release-host",$0='<svg viewBox="0 0 122.52 122.523" aria-hidden="true"><path fill="currentColor" d="M8.708 61.26c0 20.802 12.089 38.779 29.619 47.298L13.258 39.872a52.352 52.352 0 0 0-4.55 21.388zm87.892-2.652c0-6.495-2.333-10.993-4.334-14.494-2.664-4.329-5.161-7.995-5.161-12.324 0-4.831 3.664-9.328 8.825-9.328.233 0 .454.029.681.042-9.35-8.566-21.807-13.796-35.489-13.796-18.36 0-34.513 9.42-43.91 23.688 1.233.037 2.395.063 3.382.063 5.497 0 14.006-.667 14.006-.667 2.833-.167 3.167 3.994.337 4.329 0 0-2.847.335-6.015.501l19.138 56.925 11.502-34.493-8.187-22.432c-2.831-.166-5.51-.501-5.51-.501-2.831-.167-2.499-4.496.332-4.329 0 0 8.679.667 13.843.667 5.496 0 14.006-.667 14.006-.667 2.835-.167 3.168 3.994.337 4.329 0 0-2.852.335-6.015.501l18.992 56.494 5.242-17.517c2.272-7.269 4.001-12.49 4.001-16.989zm-34.404 7.223l-15.768 45.819a52.552 52.552 0 0 0 14.807 2.136c6.309 0 12.36-1.091 17.996-3.075a4.617 4.617 0 0 1-.374-.724L62.196 65.831zm45.192-29.81c.226 1.674.354 3.471.354 5.404 0 5.333-.996 11.328-3.996 18.824l-16.053 46.413c15.624-9.111 26.133-26.038 26.133-45.426.001-9.137-2.333-17.729-6.438-25.215zM61.262 0C27.483 0 0 27.481 0 61.26c0 33.783 27.483 61.263 61.262 61.263 33.778 0 61.265-27.48 61.265-61.263C122.526 27.481 95.04 0 61.262 0zm0 119.715c-32.23 0-58.453-26.223-58.453-58.455 0-32.23 26.222-58.451 58.453-58.451 32.229 0 58.45 26.221 58.45 58.451 0 32.232-26.221 58.455-58.45 58.455z"/></svg>',U0='<svg viewBox="0 0 14 14" aria-hidden="true"><path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" fill="none"></path></svg>',H0=` |
| 233 |
.dm-release-card { |
| 234 |
position: relative; box-sizing: border-box; width: 268px; padding: 11px; |
| 235 |
border-radius: 14px; color: #fff; |
| 236 |
font-family: var( --desktop-mode-font, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif ); |
| 237 |
background: #34373f; border: 1px solid rgba( 255, 255, 255, 0.14 ); |
| 238 |
box-shadow: 0 16px 40px rgba( 0, 0, 0, 0.55 ), 0 3px 8px rgba( 0, 0, 0, 0.3 ), inset 0 0 0 1px rgba( 255, 255, 255, 0.04 ); |
| 239 |
--accent: #2271b1; --accent-ink: #ffffff; |
| 240 |
animation: dmRcCardIn 0.5s cubic-bezier( 0.2, 1.2, 0.35, 1 ) both; |
| 241 |
} |
| 242 |
.dm-release-card, .dm-release-card * { box-sizing: border-box; } |
| 243 |
@keyframes dmRcCardIn { |
| 244 |
from { opacity: 0; transform: translateY( -16px ) scale( 0.96 ); } |
| 245 |
to { opacity: 1; transform: none; } |
| 246 |
} |
| 247 |
.dm-rc__close { |
| 248 |
position: absolute; top: 9px; right: 9px; z-index: 10; |
| 249 |
width: 22px; height: 22px; padding: 0; border: none; border-radius: 50%; |
| 250 |
display: inline-flex; align-items: center; justify-content: center; |
| 251 |
background: rgba( 0, 0, 0, 0.5 ); color: #fff; opacity: 0.72; cursor: pointer; |
| 252 |
transition: opacity 0.12s ease, background-color 0.12s ease; |
| 253 |
} |
| 254 |
.dm-rc__close:hover { opacity: 1; background: rgba( 0, 0, 0, 0.7 ); } |
| 255 |
.dm-rc__close:focus-visible { opacity: 1; outline: 2px solid #fff; outline-offset: 2px; } |
| 256 |
.dm-rc__close svg { width: 11px; height: 11px; } |
| 257 |
.dm-rc__art { position: relative; height: 150px; } |
| 258 |
.dm-rc__cover { |
| 259 |
position: absolute; left: 2px; top: 0; width: 150px; height: 150px; |
| 260 |
border-radius: 2px; overflow: hidden; z-index: 3; |
| 261 |
box-shadow: 0 8px 20px rgba( 0, 0, 0, 0.5 ), inset 0 0 0 1px rgba( 255, 255, 255, 0.08 ); |
| 262 |
} |
| 263 |
.dm-rc__canvas { width: 100%; height: 100%; display: block; } |
| 264 |
.dm-rc__disc-wrap { |
| 265 |
position: absolute; left: 94px; top: 2px; width: 148px; height: 148px; z-index: 2; |
| 266 |
border-radius: 50%; box-shadow: 0 14px 26px rgba( 0, 0, 0, 0.6 ); |
| 267 |
animation: dmRcEmerge 0.8s cubic-bezier( 0.2, 1, 0.28, 1 ) 0.45s both; |
| 268 |
} |
| 269 |
@keyframes dmRcEmerge { |
| 270 |
from { transform: translateX( -84px ); } |
| 271 |
to { transform: translateX( 0 ); } |
| 272 |
} |
| 273 |
.dm-rc__disc { |
| 274 |
position: absolute; inset: 0; border-radius: 50%; |
| 275 |
background: |
| 276 |
repeating-radial-gradient( circle at 50% 50%, rgba( 255, 255, 255, 0.05 ) 0 1px, rgba( 0, 0, 0, 0 ) 1px 2.4px ), |
| 277 |
radial-gradient( circle at 50% 50%, #1a1a1e 0 11%, #0a0a0c 12% 62%, #050506 100% ); |
| 278 |
box-shadow: inset 0 0 26px rgba( 0, 0, 0, 0.9 ), inset 0 0 0 1px rgba( 255, 255, 255, 0.05 ); |
| 279 |
animation: dmRcSettle 2.5s cubic-bezier( 0.12, 0.72, 0.16, 1 ) 0.45s both; |
| 280 |
} |
| 281 |
@keyframes dmRcSettle { |
| 282 |
from { transform: rotate( 0 ); } |
| 283 |
to { transform: rotate( 720deg ); } |
| 284 |
} |
| 285 |
.dm-rc__label { |
| 286 |
position: absolute; inset: 34%; border-radius: 50%; display: grid; place-items: center; |
| 287 |
background: var( --accent ); color: var( --accent-ink ); |
| 288 |
box-shadow: inset 0 0 0 2px rgba( 0, 0, 0, 0.18 ), 0 1px 2px rgba( 0, 0, 0, 0.4 ); |
| 289 |
} |
| 290 |
.dm-rc__label svg { width: 59%; height: 59%; display: block; } |
| 291 |
.dm-rc__sheen { |
| 292 |
position: absolute; inset: 0; border-radius: 50%; pointer-events: none; z-index: 3; |
| 293 |
background: linear-gradient( 118deg, rgba( 255, 255, 255, 0.18 ) 0%, transparent 24%, transparent 74%, rgba( 255, 255, 255, 0.1 ) 100% ); |
| 294 |
mix-blend-mode: screen; |
| 295 |
} |
| 296 |
.dm-rc__meta { |
| 297 |
display: flex; align-items: center; gap: 10px; margin-top: 11px; |
| 298 |
opacity: 0; animation: dmRcFade 0.5s ease 1.05s forwards; |
| 299 |
} |
| 300 |
@keyframes dmRcFade { to { opacity: 1; } } |
| 301 |
.dm-rc__text { flex: 1; font-size: 13px; line-height: 1.35; color: #fff; } |
| 302 |
.dm-rc__text b { font-weight: 650; } |
| 303 |
.dm-rc__btn { |
| 304 |
flex-shrink: 0; padding: 7px 12px; border: none; border-radius: 7px; |
| 305 |
color: var( --accent-ink ); background: var( --accent ); font: inherit; font-size: 12px; font-weight: 600; |
| 306 |
cursor: pointer; box-shadow: 0 2px 8px rgba( 0, 0, 0, 0.3 ); transition: filter 0.12s; |
| 307 |
} |
| 308 |
.dm-rc__btn:hover { filter: brightness( 1.12 ); } |
| 309 |
.dm-rc__btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } |
| 310 |
@media ( prefers-reduced-motion: reduce ) { |
| 311 |
.dm-release-card, .dm-rc__disc-wrap, .dm-rc__disc, .dm-rc__meta { animation: none !important; } |
| 312 |
.dm-rc__disc-wrap { transform: translateX( 0 ); } |
| 313 |
.dm-rc__meta { opacity: 1; } |
| 314 |
} |
| 315 |
`;function B0(){if(document.getElementById(rf))return;const e=document.createElement("style");e.id=rf,e.textContent=H0,document.head.appendChild(e)}function F0(){const e=document.querySelector("."+af);if(e)return e;const t=document.createElement("div");return t.className=af,t.style.cssText="position:fixed;top:calc(var(--wp-admin--admin-bar--height,32px) + 16px);inset-inline-end:16px;z-index:calc(var(--desktop-mode-z-fullscreen,99999) + 10);pointer-events:none;",document.body.appendChild(t),t}function z0(e,t,n,o){const s=new Image;s.crossOrigin="anonymous",s.addEventListener("load",()=>{const i=s.naturalWidth||0,r=s.naturalHeight||0;if(!i||!r)return;const a=320;t.width=a,t.height=a;const d=t.getContext("2d");if(!d)return;const c=Math.min(i,r);d.drawImage(s,0,0,c,c,0,0,a,a);try{const l=document.createElement("canvas");l.width=i,l.height=r;const u=l.getContext("2d");if(!u)return;u.drawImage(s,0,0);const p=u.getImageData(0,0,i,r).data,f=(k,N)=>{const b=(N*i+k)*4;return p[b]>248&&p[b+1]>248&&p[b+2]>248&&p[b+3]>200},h=k=>{for(let N=0;N<i;N+=2)if(!f(N,k))return!1;return!0},m=k=>{for(let N=0;N<r;N+=2)if(!f(k,N))return!1;return!0};let w=0;for(;w<r-1&&h(w);)w++;let g=r-1;for(;g>w&&h(g);)g--;let x=0;for(;x<i-1&&m(x);)x++;let T=i-1;for(;T>x&&m(T);)T--;const y=Math.max(1,Math.min(T-x+1,g-w+1));d.clearRect(0,0,a,a),d.drawImage(s,x,w,y,y,0,0,a,a),o||G0(e,d,a)}catch{}},{once:!0}),s.src=n}function G0(e,t,n){const{data:o}=t.getImageData(0,0,n,n),s=new Map;let i=null,r=-1;for(let u=0;u<o.length;u+=4){const p=o[u],f=o[u+1],h=o[u+2];if(o[u+3]<200)continue;const m=Math.max(p,f,h),w=Math.min(p,f,h),g=m/255,x=m===0?0:(m-w)/m;if(g<.2||x<.25)continue;const T=`${Math.floor(p/16)},${Math.floor(f/16)},${Math.floor(h/16)}`;let y=s.get(T);y||(y={r:0,g:0,b:0,n:0,score:0},s.set(T,y)),y.r+=p,y.g+=f,y.b+=h,y.n+=1,y.score+=x*g,y.score>r&&(r=y.score,i=y)}if(!i)return;const a=Math.round(i.r/i.n),d=Math.round(i.g/i.n),c=Math.round(i.b/i.n),l=(.299*a+.587*d+.114*c)/255;e.style.setProperty("--accent",`rgb(${a}, ${d}, ${c})`),e.style.setProperty("--accent-ink",l>.6?"#1a1a1a":"#ffffff")}function j0(e){B0();const t=F0();t.textContent="";const n=document.createElement("div");n.className="dm-release-card",n.setAttribute("role","status"),n.style.pointerEvents="auto",e.accent&&n.style.setProperty("--accent",e.accent),e.accentInk&&n.style.setProperty("--accent-ink",e.accentInk),n.innerHTML=`<button type="button" class="dm-rc__close">${U0}</button><div class="dm-rc__art"><div class="dm-rc__disc-wrap"><div class="dm-rc__disc"><div class="dm-rc__label">${$0}</div></div><div class="dm-rc__sheen"></div></div><div class="dm-rc__cover"><canvas class="dm-rc__canvas"></canvas></div></div><div class="dm-rc__meta"><span class="dm-rc__text"></span><button type="button" class="dm-rc__btn"></button></div>`,n.querySelector(".dm-rc__text").textContent=e.message;const o=n.querySelector(".dm-rc__close");o.setAttribute("aria-label",O("Dismiss"));const s=n.querySelector(".dm-rc__btn");s.textContent=O("Update now"),t.appendChild(n),z0(n,n.querySelector(".dm-rc__canvas"),e.artUrl,!!e.accent);let i=!1,r=null;const a=()=>{i=!0,r!==null&&(clearTimeout(r),r=null),n.remove()};return o.addEventListener("click",d=>{if(d.preventDefault(),d.stopPropagation(),i)return;if(qo(e.dismissKey),typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches){a();return}i=!0,n.style.animation="none",n.style.transition="opacity 0.2s ease",requestAnimationFrame(()=>{n.style.opacity="0"}),r=window.setTimeout(()=>n.remove(),240)}),s.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),e.onUpdate(),a()}),a}const df="desktop-mode/release-art:v1:",q0=6*60*60*1e3;function Ct(e){return typeof e=="string"?e:""}function nt(e,t){return e&&typeof e=="object"?e[t]:void 0}function V0(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}function K0(e){const t=nt(nt(e,"_embedded"),"wp:featuredmedia"),n=Array.isArray(t)?t[0]:void 0,o=nt(nt(n,"media_details"),"sizes");for(const s of["medium_large","large","1536x1536","medium"]){const i=Ct(nt(nt(o,s),"source_url"));if(i)return i}return Ct(nt(n,"source_url"))}function Y0(e,t){if(!Array.isArray(e))return null;const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp("^WordPress "+n+'\\s*[“"]([^”"]+)[”"]');for(const s of e){const i=V0(Ct(nt(nt(s,"title"),"rendered"))),r=o.exec(i);if(!r)continue;const a=K0(s);if(a)return{name:r[1].trim(),artUrl:a}}return null}function X0(e){try{const t=localStorage.getItem(df+e);if(!t)return null;const n=JSON.parse(t);return n.ok===!0&&Ct(n.name)&&Ct(n.artUrl)?{name:Ct(n.name),artUrl:Ct(n.artUrl)}:n.ok===!1&&typeof n.ts=="number"&&Date.now()-n.ts<q0?"miss":null}catch{return null}}function bs(e,t){try{localStorage.setItem(df+e,JSON.stringify(t))}catch{}}async function Z0(e){if(!e)return null;const t=X0(e);if(t==="miss")return null;if(t)return t;try{const n="https://wordpress.org/news/wp-json/wp/v2/posts?search="+encodeURIComponent(e)+"&per_page=100&_fields=title,_links,_embedded&_embed=wp:featuredmedia",o=await ze(n,{credentials:"omit"},{silent:!0,source:"desktop-mode/release-art"});if(!o.ok)return bs(e,{ok:!1,ts:Date.now()}),null;const s=Y0(await o.json(),e);return s?(bs(e,{ok:!0,name:s.name,artUrl:s.artUrl}),s):(bs(e,{ok:!1,ts:Date.now()}),null)}catch{return bs(e,{ok:!1,ts:Date.now()}),null}}function J0(e,t=5e3){return new Promise(n=>{const o=new Image;o.crossOrigin="anonymous";let s=!1;const i=r=>{s||(s=!0,n(r))};o.addEventListener("load",()=>i(!0),{once:!0}),o.addEventListener("error",()=>i(!1),{once:!0}),window.setTimeout(()=>i(!1),t),o.src=e})}function cf(e,t){if(t){const o=O('WordPress %1$s "%2$s" is available.');return oe(o,e,t)}const n=O("WordPress %s is available.");return oe(n,e)}async function Q0(e){const{update:t,openUrl:n}=e;if(!t||typeof t.version!="string"||!t.version||typeof t.url!="string"||!t.url)return;const o=t.version,s=typeof t.branch=="string"&&t.branch?t.branch:o,i=t.crossing===!0,a=`desktop-mode/core-update:${typeof t.available=="string"&&t.available?t.available:o}`;if(Vc(a))return;const d=()=>n({url:t.url,title:O("WordPress Updates")}),c=e.resolveArt??Z0,l=e.loadImage??J0,u=await c(s);if(u&&u.artUrl&&await l(u.artUrl)){j0({message:cf(o,i?u.name:""),artUrl:u.artUrl,dismissKey:a,onUpdate:d});return}ee({message:cf(o,""),persistent:!0,dismissible:!0,onDismiss:()=>qo(a),action:{label:O("Update now"),onClick:d}})}const ea="desktop-mode/starter",eS="desktop-mode/dev-mode-gate";let lf=!1;function tS({osSettings:e,layer:t}){if(lf)return;lf=!0,Ds(v.WIDGETS,eS,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==ea));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(ea):t.unmount(ea),Dn())})}function nS(e){const{layer:t}=e,n=new Set,o=new Set,s=async d=>{if(!(!d.scriptUrl||o.has(d.scriptUrl))){try{await Ee(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(c){A(v.SHELL_ERROR,{scope:"widget-script-load",id:d.id,error:c});return}o.add(d.scriptUrl)}},i=d=>{const l=(window.desktopModeWidgets||{})[d.id];return l?{id:d.id,label:d.label,description:d.description,icon:d.icon,movable:d.movable,resizable:d.resizable,minWidth:d.minWidth||void 0,minHeight:d.minHeight||void 0,maxWidth:d.maxWidth||void 0,maxHeight:d.maxHeight||void 0,defaultWidth:d.defaultWidth||void 0,defaultHeight:d.defaultHeight||void 0,mount:l}:(A(v.SHELL_ERROR,{scope:"widget-missing-mount",id:d.id,error:new Error(`[desktop-mode] No mount callback on window.desktopModeWidgets["${d.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`)}),null)},r=async d=>{if(n.has(d.id))return;await s(d);const c=i(d);if(c){try{Li(c)}catch(l){A(v.SHELL_ERROR,{scope:"widget-register",id:d.id,error:l});return}n.add(d.id),Dn(),t&&t.mountIfEnabled(d.id)}},a=d=>{n.has(d)&&(t?.unmount(d),iy(d),n.delete(d),Dn())};return async d=>{const c=new Set;for(const l of d)c.add(l.id);for(const l of Array.from(n))c.has(l)||a(l);for(const l of d)n.has(l.id)||await r(l)}}const uf=["wpd-section","wpd-button","wpd-swatch","wpd-swatch-grid","wpd-segmented","wpd-segment","wpd-select","wpd-option","wpd-multiselect","wpd-color-field","wpd-range-field","wpd-text-field","wpd-number-field","wpd-checkbox","wpd-checkbox-label","wpd-toast","wpd-toast-container","wpd-tabs","wpd-tab","wpd-tabpanel","wpd-window-button","wpd-menu","wpd-menu-item","wpd-context-menu","wpd-context-menu-option","wpd-confirm-dialog","wpd-modal","wpd-user-search","wpd-role-picker","wpd-flyout","wpd-tab-chip","wpd-stack","wpd-cluster","wpd-icon","wpd-body","wpd-panel","wpd-row","wpd-grid","wpd-display","wpd-empty-state","wpd-key","wpd-code","wpd-badge","wpd-ribbon","wpd-tile","wpd-log","wpd-steps","wpd-step","wpd-table","wpd-spinner","wpd-relative-time","wpd-avatar","wpd-textarea","wpd-chip","wpd-tag-input","wpd-form","wpd-save-status","wpd-category-picker","wpd-crumb-chain","wpd-card","wpd-rating-summary","wpd-notice","wpd-progress-bar"],pf=new Set(uf),oS=2e3,ta=new Set,ff=new WeakSet;let mf=!1;function sS(e,t){const n=e.length,o=t.length;if(n===0)return o;if(o===0)return n;const s=new Array(o+1);for(let i=0;i<=o;i++)s[i]=i;for(let i=1;i<=n;i++){let r=s[0];s[0]=i;for(let a=1;a<=o;a++){const d=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=d}}return s[o]}function iS(e){let t=null,n=1/0;for(const o of pf){const s=sS(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function rS(e){return e.startsWith("wpd-")?e.slice(4):e}function aS(e,t){if(ta.has(e))return;if(ta.add(e),pf.has(e)){const s=rS(e);console.error(`[wp.desktop] <${e}> is in the DOM but its module was never imported, so the tag will not upgrade and the component will render as inert HTML. |
| 316 |
|
| 317 |
Fix — side-effect-import the component module from wherever you render it: |
| 318 |
|
| 319 |
import '<rel>/ui/components/${s}/${s}'; |
| 320 |
|
| 321 |
Or pull every wpd-* component in one go (heavier — only do this from an entry bundle): |
| 322 |
|
| 323 |
import '<rel>/ui/components'; |
| 324 |
|
| 325 |
See docs/components-reference.md for the full list.`,` |
| 326 |
First offending element:`,t);return}const o=iS(e);if(o){console.error(`[wp.desktop] <${e}> is not a registered wpd-* component. Did you mean <${o}>? |
| 327 |
|
| 328 |
If the typo is in your template, update it. If you meant to ship a new component, register it via 'src/ui/components/<name>/<name>.ts' and add it to 'src/ui/components/tags.ts' + 'src/ui/components/index.ts'.`,` |
| 329 |
First offending element:`,t);return}console.error(`[wp.desktop] <${e}> looks like a wpd-* tag but no component by that name exists. |
| 330 |
|
| 331 |
See 'src/ui/components/index.ts' (or docs/components-reference.md) for the canonical list. If you intended to register a new component, add it to 'tags.ts' and side-effect-import its module.`,` |
| 332 |
First offending element:`,t)}function hf(e){const t=e.tagName.toLowerCase();if(!t.startsWith("wpd-")||ta.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||aS(t,e)},oS)}function wf(e){e instanceof Element&&(hf(e),e.shadowRoot&&vs(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];hf(o),o.shadowRoot&&vs(o.shadowRoot)}}function vs(e){if(ff.has(e))return;ff.add(e),wf(e),new MutationObserver(n=>{for(let o=0;o<n.length;o++){const s=n[o].addedNodes;for(let i=0;i<s.length;i++){const r=s[i];r.nodeType===1&&wf(r)}}}).observe(e,{childList:!0,subtree:!0})}function dS(){const e=Element.prototype,t=e.attachShadow;if(t.__wpdPatched)return;const n=function(o){const s=t.call(this,o);return s.mode==="open"&&vs(s),s};n.__wpdPatched=!0,e.attachShadow=n}function cS(){mf||typeof document>"u"||(mf=!0,dS(),vs(document))}const lS=new Set(["post"]);function gf(){const e=window.wp?.desktop?.myWordpress;return e&&typeof e.trashEntity=="function"?e:null}const na="data-desktop-mode-trash-drop-active",Qt="desktop-mode-recycle-bin",uS=[`.desktop-mode-file-tile[data-file-ref="${Qt}"]`,`[data-icon-id="${Qt}"]`,`[data-system-id="${Qt}"]`];function pS(){for(const e of uS){const t=document.querySelector(e);if(t instanceof HTMLElement)return t}return null}let yf=!1,to=null,no=null,bf=null;function fS(e){return e.payload.type==="desktop-file"}function mS(e){return e.payload.type==="shortcut"}function hS(e){if(!e.kind||!e.ref||!e.entityId||!lS.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return!Number.isFinite(t)||t<=0?!1:gf()!==null}function vf(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:O("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const i=o.data?.placement;return!i||i.file?.ref===Qt?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data;return hS(s)}return!1},onEnter:()=>{n.setAttribute(na,"")},onLeave:()=>{n.removeAttribute(na)},onDrop:o=>{if(n.removeAttribute(na),fS(o)){const s=o.payload.data.placement;P_(s);return}if(mS(o)){const s=o.payload.data,i=gf();if(!i?.trashEntity||!s.entityId)return;const r=Number.parseInt(s.ref,10);if(!Number.isFinite(r)||r<=0)return;i.trashEntity(s.entityId,r).catch(a=>{console.error("[desktop-mode] recycle-bin: shortcut trash failed:",a)})}}})}function wS(e){if(yf)return;yf=!0;const t=()=>{const n=pS();if(!n){to?.(),to=null;return}to&&gS(e)===n||(to?.(),to=vf(e,"recycle-bin-dock",n))};if(t(),document.addEventListener("desktop-mode-files-changed",t),G(v.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),G(v.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){bf=new MutationObserver(()=>{t()});const n=document.getElementById("desktop-mode-area")??document.body;bf.observe(n,{childList:!0,subtree:!0})}G(v.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==Qt)return;no?.(),no=null;const o=document.querySelector("[data-desktop-mode-recycle-bin-root]");o instanceof HTMLElement&&(no=vf(e,"recycle-bin-window",o))}),G(v.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===Qt&&(no?.(),no=null)})}function gS(e){const t=e.debug().listTargets().find(n=>n.id==="recycle-bin-dock");return t?t.element:null}let kf=!1,At=0;function yS(){kf||(kf=!0,Xe.contribute("desktop_mode_files_subscribe",()=>{const e=Et(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:At,sharesVersion:tt().state.sharesVersion}}),Xe.subscribe("desktop_mode_files",e=>{bS(e)}))}function bS(e){const t=e.folders??[];for(const i of t)wr(i,"remote"),i.updatedAtMs>At&&(At=i.updatedAtMs);const n=e.placements??[];for(const i of n)hr(i,"remote"),i.updatedAtMs>At&&(At=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])gr(i,"remote");for(const i of o.placements??[])as(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>At&&(At=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&$p(s),e.truncated){const i=Array.from(Et().hydratedFolders);for(const r of i)Me(r).then(a=>{Kt(r,a.placements)}).catch(()=>{})}}let _f=!1;const vS=[];function kS(){if(_f)return;_f=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||_S()};vS.push(We("desktop-mode.placement.changed",e),We("desktop-mode.shortcut.changed",e),We("desktop-mode.folder.changed",e))}function _S(){ep().then(t=>{up(t.folders)}).catch(t=>{console.error("[desktop-mode] files restore-sync: listFolders failed",t)});const e=Array.from(Et().hydratedFolders);for(const t of e)Me(t).then(n=>{Kt(t,n.placements)}).catch(n=>{console.error("[desktop-mode] files restore-sync: listPlacements failed for",t,n)})}const oo="desktop-mode-wallpaper-menu";let en=null;function Ef(){return en!==null}let Sf=0;function ES(e,t,n,o={}){so();const s=++Sf;sn(()=>s===Sf,()=>SS(e,t,n,o))}function SS(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((f,h)=>{const m=typeof f.sort=="number"?f.sort:100,w=typeof h.sort=="number"?h.sort:100;return m!==w?m-w:f.label.localeCompare(h.label)});const s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(oo),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const d=()=>{r&&(r.remove(),r=null,a=null)};for(const f of n){i.set(f.id,f);const h=document.createElement("wpd-context-menu-option");h.dataset.menuItemId=f.id,h.setAttribute("value",f.id),f.heading&&h.setAttribute("heading",""),f.disabled&&h.setAttribute("disabled",""),f.icon&&h.setAttribute("icon",If(f.icon));const m=Array.isArray(f.children)&&f.children.length>0;m&&h.setAttribute("has-children",""),h.textContent=f.label,h.addEventListener("mouseenter",()=>{if(m){c(f,h);return}d()}),s.appendChild(h)}s.addEventListener("wpd-context-menu-pick",f=>{const h=f.detail,m=i.get(h.id)??null;if(m){if(Array.isArray(m.children)&&m.children.length>0){if(f.stopPropagation(),a&&a.id===m.id){d();return}const w=s.querySelector(`[data-menu-item-id="${m.id}"]`);w&&c(m,w);return}so(),m.onClick(new MouseEvent("click"))}});function c(f,h){d();const m=document.createElement("wpd-context-menu");m.setAttribute("open",""),m.classList.add(oo,`${oo}--flyout`),m.dataset.parentId=f.id;const w=(f.children??[]).slice().sort((g,x)=>{const T=typeof g.sort=="number"?g.sort:100,y=typeof x.sort=="number"?x.sort:100;return T!==y?T-y:g.label.localeCompare(x.label)});for(const g of w){const x=document.createElement("wpd-context-menu-option");x.dataset.menuItemId=g.id,x.setAttribute("value",g.id),g.icon&&x.setAttribute("icon",If(g.icon)),g.disabled&&x.setAttribute("disabled",""),g.checked&&x.setAttribute("checked",""),x.textContent=g.label,x.addEventListener("wpd-context-menu-pick",T=>{T.stopPropagation(),so(),g.onClick(new MouseEvent("click"))}),m.appendChild(x)}document.body.appendChild(m),r=m,a=f,l(m,h)}function l(f,h){const m=h.getBoundingClientRect();f.style.position="fixed",f.style.left=`${m.right}px`,f.style.top=`${m.top}px`;const w=f.getBoundingClientRect();w.right>window.innerWidth&&(f.style.left=`${Math.max(0,m.left-w.width)}px`),w.bottom>window.innerHeight&&(f.style.top=`${Math.max(0,window.innerHeight-w.height-8)}px`)}e.appendChild(s),en=s;const u=s.getBoundingClientRect();u.right>window.innerWidth&&(s.style.left=`${Math.max(0,window.innerWidth-u.width-8)}px`),u.bottom>window.innerHeight&&(s.style.top=`${Math.max(0,window.innerHeight-u.height-8)}px`);const p=fp(s,{close:()=>so(),siblingSelectors:[`.${oo}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",p),A("desktop-mode.wallpaper-menu.opened",{items:n.map(f=>f.id)})}function so(){en&&(document.querySelectorAll(`.${oo}--flyout`).forEach(e=>e.remove()),en.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),en.remove(),en=null,A("desktop-mode.wallpaper-menu.closed",{}))}function IS(e){const t=[{id:"create-folder",label:e.labels.createFolder,icon:"dashicons-portfolio",sort:10,onClick:()=>e.createFolder()},{id:"new-url",label:e.labels.newUrl,icon:"dashicons-admin-links",sort:12,onClick:()=>e.createUrl()},{id:"sort-by",label:e.labels.sortHeading,icon:"dashicons-sort",sort:16,onClick:()=>{},children:[{id:"sort-name-asc",label:e.labels.sortNameAsc,sort:10,checked:e.currentSortMode==="name-asc",onClick:()=>e.sortIcons("name-asc")},{id:"sort-name-desc",label:e.labels.sortNameDesc,sort:20,checked:e.currentSortMode==="name-desc",onClick:()=>e.sortIcons("name-desc")},{id:"sort-date-desc",label:e.labels.sortDateDesc,sort:30,checked:e.currentSortMode==="date-desc",onClick:()=>e.sortIcons("date-desc")},{id:"sort-date-asc",label:e.labels.sortDateAsc,sort:40,checked:e.currentSortMode==="date-asc",onClick:()=>e.sortIcons("date-asc")}]},...e.includeShowDesktop===!1?[]:[{id:"show-desktop",label:e.labels.showDesktop,icon:"dashicons-desktop",sort:20,onClick:()=>e.toggleShowDesktop()}],{id:"os-settings",label:e.labels.osSettings,icon:"dashicons-admin-generic",sort:30,onClick:()=>e.openOsSettings()}],n=(e.serverItems??[]).map(i=>xS(i,e)),o=[...t,...n],s=j("desktop-mode.wallpaper-context-menu",o);return Array.isArray(s)?s:o}function xS(e,t){return{id:e.id,label:e.label,icon:e.icon,sort:e.sort,disabled:e.disabled,onClick:()=>{if(e.callbackId){const n=t.serverCallbacks?.[e.callbackId];if(typeof n=="function")return n()}A("desktop-mode.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function If(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const io="desktop-mode-url-dialog";let ro=null;function oa(){ro&&(ro.dispatchEvent(new CustomEvent("url-dialog-closed")),ro.remove(),ro=null,A("desktop-mode.files.url-dialog.closed",{}))}function CS(e){if(oa(),j("desktop-mode.files.url-dialog",null,e)===!1)return;const n=document.createElement("div");n.className=`${io}__overlay desktop-mode-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${io} desktop-mode-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${io}-title`);const s=document.createElement("h2");if(s.id=`${io}-title`,s.className="desktop-mode-create-folder-dialog__title",s.textContent=e.title,o.appendChild(s),e.description){const g=document.createElement("p");g.className=`${io}__description`,g.textContent=e.description,o.appendChild(g)}const i=document.createElement("wpd-text-field");i.setAttribute("label",e.nameLabel??"Name"),i.setAttribute("value",e.initialName??""),i.setAttribute("placeholder","My web app"),i.setAttribute("autocomplete","off"),o.appendChild(i);const r=document.createElement("wpd-text-field");r.setAttribute("label",e.urlLabel??"URL"),r.setAttribute("value",e.initialUrl??"https://"),r.setAttribute("placeholder","https://example.com"),r.setAttribute("type","url"),r.setAttribute("autocomplete","off"),o.appendChild(r);const a=document.createElement("p");a.className="desktop-mode-create-folder-dialog__error",a.hidden=!0,a.setAttribute("role","alert"),o.appendChild(a);const d=document.createElement("div");d.className="desktop-mode-create-folder-dialog__actions";const c=document.createElement("button");c.type="button",c.className="desktop-mode-create-folder-dialog__btn desktop-mode-create-folder-dialog__btn--secondary",c.textContent="Cancel";const l=document.createElement("button");l.type="button",l.className="desktop-mode-create-folder-dialog__btn desktop-mode-create-folder-dialog__btn--primary",l.textContent=e.submitLabel??"Create",d.appendChild(c),d.appendChild(l),o.appendChild(d),n.appendChild(o),document.body.appendChild(n),ro=n,queueMicrotask(()=>{const g=i.shadowRoot?.querySelector("input");g?.focus(),g?.select()}),A("desktop-mode.files.url-dialog.opened",{});const u=g=>{const x=g.value;return typeof x=="string"?x:g.shadowRoot?.querySelector("input")?.value??""},p=g=>{i.disabled=g,r.disabled=g,c.disabled=g,l.disabled=g,o.classList.toggle("desktop-mode-create-folder-dialog--busy",g)},f=g=>{a.textContent=g,a.hidden=!1},h=()=>{oa(),e.onCancel?.()},m=async()=>{const g=u(r).trim();if(!g){f("Please enter a URL.");return}const x=/^[a-z][a-z0-9+\-.]*:/i.test(g)?g:`https://${g}`;try{new URL(x)}catch{f("That doesn't look like a valid URL.");return}const T=u(i).trim();a.hidden=!0,p(!0);try{await e.onSubmit({name:T,url:x}),oa()}catch(y){p(!1),f(y instanceof Error?y.message:"Could not save.")}};c.addEventListener("click",()=>h()),l.addEventListener("click",()=>void m()),n.addEventListener("click",g=>{g.target===n&&h()});const w=g=>{g.key==="Escape"?(g.preventDefault(),h()):g.key==="Enter"&&!g.isComposing&&(g.preventDefault(),m())};o.addEventListener("keydown",w),n.addEventListener("url-dialog-closed",()=>{o.removeEventListener("keydown",w)})}const xf=[];let sa=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.desktop)return;const n={whenReady(o){if(typeof o=="function"){if(sa){Promise.resolve().then(o);return}xf.push(o)}},ready(o){n.whenReady(o)},isReady(){return sa}};t.wp.desktop=n})();const ao="desktop-mode-os-settings";let ia=[],ks=Number.POSITIVE_INFINITY,ra=!1;function ot(e,t=1500){if(ia.push(e),t<ks&&(ks=t),ra)return;ra=!0;const n=()=>{const o=ia;ia=[],ks=Number.POSITIVE_INFINITY,ra=!1;for(const s of o)try{s()}catch(i){typeof console<"u"&&console.error("[desktop-mode] scheduleIdleBoot callback threw:",i)}};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(n,{timeout:ks}):window.setTimeout(n,0)}function Cf(){const e=window.desktopModeConfig;if(!e)return;const t=document.getElementById("desktop-mode-area");if(!t)return;const n=new km(t),o=document.getElementById("desktop-mode-wallpaper"),s=e.pluginUrl||"";let i=null;o&&(i=new oc(o,s));const r=document.getElementById("desktop-mode-widgets");let a=null;P0(),Ew(),r&&(a=new Oy(r,s)),ec({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const d=new Tw({mediaUrl:e.mediaUrl,restNonce:e.restNonce,canUpload:!!e.canUpload,isAdmin:!!e.currentUserIsAdmin,extendedOptions:e.extendedOptions??null,extendedOptionsUrl:e.extendedOptionsUrl??"",osSettingsPanelBundleUrl:e.osSettingsPanelBundleUrl??""},i??new oc(document.createElement("div"),s));d.apply(),a&&tS({osSettings:d,layer:a});const c=new ob({aiSearchUrl:e.aiSearchUrl??"",aiSearchStreamUrl:e.aiSearchStreamUrl??"",restNonce:e.restNonce,getTransport:()=>"sse"},e.aiAssistantBundleUrl??"");c.attachAsk(db({config:()=>e,fallbackContext:()=>({close:()=>c.close(),openInWindow:(_,U,B)=>{n.open({url:_,title:U,icon:B??"dashicons-admin-generic"})},confirm:_=>Fu({message:_})})}));const l=new av,u=new Ev;document.addEventListener(Se.START,_=>{const B=_.detail?.payload;if(!B||B.type!=="shortcut"&&B.type!=="desktop-file")return;const Y=B.data?.bridgePayload;Y&&l.start(Y)}),document.addEventListener(Se.END,()=>{l.end()}),ot(()=>Mv(u)),ot(()=>Yv(n)),window.addEventListener("message",_=>{if(_.origin!==window.location.origin)return;const U=_.data;!U||U.type!=="desktop-mode-drop-failed"||ee({message:"Could not insert into the editor."})});const p=e.aiAssistant?.available===!0,f=()=>p&&e.aiAssistant?.assistantProviderConfigured===!0&&d.getOsSettingsSnapshot().ai.enabled!==!1;let h=null;const m=()=>{const _=f();document.body.classList.toggle("desktop-mode-ai-enabled",_),_&&!h?h=xu({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>c.open(),close:()=>c.close(),isOpen:()=>c.isOpen}):!_&&h&&(c.close(),h(),h=null)};m(),d.subscribeOsSettings(()=>m()),document.addEventListener("desktop-mode-ai-status-changed",()=>m()),tk(),Em(n),Am(n),ot(()=>{new Xg({manager:n,adminUrl:e.adminUrl}).install(),new sy({manager:n,adminUrl:e.adminUrl}).install()}),document.addEventListener("desktop-mode-open-ai",()=>{f()&&Au("desktop-mode-ai-assistant")});const w=document.getElementById("desktop-mode-dock"),g=document.getElementById("desktop-mode-shell"),x=g?.querySelector(".desktop-mode-shell__body");let T=null;const y=zy({manager:n,appendSystemTile:_=>T?.appendSystemTile(_),removeSystemTile:_=>T?.removeSystemTile(_)}),k=y.sync;zm({getSnapshot:()=>d.getOsSettingsSnapshot(),openById:_=>y.openById(_),adminUrl:e.adminUrl});const N=_=>{const U=ne(_,e.adminUrl),B=T?T.getMenuItems():e.dockItems??[];for(const Y of B){if(ne(Y.url,e.adminUrl)===U)return{title:Y.title,icon:Y.icon,url:Y.url,submenu:Y.submenu,multi:Y.multi};for(const ue of Y.submenu??[])if(ne(ue.url,e.adminUrl)===U)return{title:ue.title,icon:Y.icon,url:Y.url,multi:Y.multi}}return null};if(lh({adminUrl:e.adminUrl,deriveSlug:_=>ne(_,e.adminUrl),openWindow:_=>{n.open(_)},findDockEntry:N}),Ot({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(_,U)=>{if(!U.pathname.endsWith("/edit.php"))return!1;const B=U.searchParams.get("post_type");return!B||B==="post"},enabled:_=>_.nativePostsEnabled===!0}),Ot({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(_,U)=>U.pathname.endsWith("/edit.php")?U.searchParams.get("post_type")==="page":!1,enabled:_=>_.nativePagesEnabled===!0}),Ot({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(_,U)=>U.pathname.endsWith("/users.php"),enabled:_=>_.nativeUsersEnabled===!0}),Ot({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(_,U)=>{const B=U.pathname;return B.endsWith("/profile.php")?!0:B.endsWith("/user-edit.php")?U.searchParams.has("user_id"):!1},enabled:_=>_.nativeUsersEnabled===!0,onMatch:(_,U)=>{const B=parseInt(U.searchParams.get("user_id")??"0",10);B>0&&Ww(B)}}),Ot({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(_,U)=>U.pathname.endsWith("/edit-comments.php"),enabled:_=>_.nativeCommentsEnabled===!0}),Ot({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(_,U)=>{const B=U.pathname;return B.endsWith("/plugins.php")||B.endsWith("/plugin-install.php")},enabled:_=>_.nativePluginsEnabled===!0,onMatch:(_,U)=>{const B=U.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>DS).then(Y=>{Y.setPluginsWindowTab(B)})}}),w&&g&&x&&e.dockItems){t.classList.add("desktop-mode-area--with-dock");const _=d.getOsSettingsSnapshot().desktopLayout,U=B=>{Cl(t,B,{openWindow:y.openById,manager:n,deriveWindowId:Y=>ne(Y,e.adminUrl)})};T=tb({shellRoot:g,shellBody:x,bottomDockEl:w,desktopArea:t,windowManager:n,adminUrl:e.adminUrl,renderIcons:U,getSettings:()=>{const B=d.getOsSettingsSnapshot();return{itemVisibility:B.itemVisibility,dockOrder:B.dockOrder}}},_,e.dockItems,e.desktopIcons),T.appendSystemTile({id:ao,title:"OS Settings",icon:"dashicons-desktop",isOpen:()=>{const B=n.getById(ao);return B?(B.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:b},"core"),Kl()||T.appendSystemTile(Yb(e.pwa?.appName||"WordPress",ee),"core"),window.matchMedia("(display-mode: standalone)").addEventListener("change",B=>{B.matches&&T?.removeSystemTile("desktop-mode-pwa-install")}),Yl().then(B=>{B&&T?.removeSystemTile("desktop-mode-pwa-install")})}function b(_={}){_.tabId==="extended"&&(_={..._,tabId:"features"}),_.tabId&&(d.activeTabId=_.tabId),n.open({id:ao,baseId:ao,url:"#os-settings",title:"OS Settings",icon:"dashicons-desktop",native:!0,render:U=>d.renderPanel(U),width:820,height:720,minWidth:560,minHeight:480}),_.tabId&&d.focusTab(_.tabId)}function L(){n.open({id:Wn,baseId:Wn,url:`#${Wn}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:_=>Tb(_),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("desktop-mode-open-bug-report",()=>{L()}),T&&(T.appendSystemTile({id:Wn,title:"Report a bug",icon:"dashicons-buddicons-replies",isOpen:()=>{const _=n.getById(Wn);return _?(_.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:L},"core"),T.appendSystemTile(Dw(),"core"));const D=T?.getPrimary()??null;k(Array.isArray(e.nativeWindows)?e.nativeWindows:[]);const C=Sk(e.session),S=C?Ik(n,e,t).catch(_=>{typeof console<"u"&&console.error("[desktop-mode] session restore failed:",_)}):Promise.resolve(),I=e.defaultWindow?.enabled!==!1,R=e.defaultWindow?.url??"",F=typeof R=="string"&&R.startsWith("native:");Ck({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:C,defaultEnabled:I,isNativeDefault:F})&&S.then(()=>xk(n,e).catch(_=>{typeof console<"u"&&console.error("[desktop-mode] openCurrentPage failed:",_)}));const K=Lk(n,e);Nk(K);const X=async _=>{try{const U=await Qi(n,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:_})},{source:"desktop-mode/default-window"});if(!U.ok)throw new Error(`HTTP ${U.status}`);const B=await U.json();e.defaultWindow=B,document.dispatchEvent(new CustomEvent("desktop-mode-default-window-changed",{detail:B}))}catch(U){A(v.SHELL_ERROR,{scope:"default-window-save",error:U}),typeof console<"u"&&console.error("[desktop-mode] Failed to save default window:",U)}};if(n.onToggleStartupRequested=_=>{const U=e.defaultWindow,B=!!_.config.native,Y=B?`native:${_.id}`:_.getCurrentUrl(),ue=B?U?.url===Y:ba(U?.url??"")===ba(Y),nn=!!U?.enabled&&ue;X(nn?null:Y)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!C&&F){const _=R.slice(7);queueMicrotask(()=>{if(_===ao){b();return}y.openById(_)})}const E=_=>{T?.appendSystemTile(_)},P=nS({layer:a});P(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const H=Bw({osSettings:d});H(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]);const W=jw();W(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const V=Kw();V(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const M=Qw();M(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const $=hg();$(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const Z=wg();Z(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),yg({manager:n,osSettings:d}),dh({manager:n}),ug({manager:n,osSettings:d});const se=bg();se(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),_g()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),Ig(),xg()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),Lg()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),Jc(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),Bg()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const le=jg(n);cb(n),ot(()=>lb()),Hm(),G("desktop-mode.shell.toast","desktop-mode/shell-toast",_=>{!_||typeof _.message!="string"||ee({message:_.message,action:_.action,duration:_.duration})});const Lt=e,So=Lt.recycleBinCount;mb(Number(So)||0,typeof Lt.recycleBinCountUrl=="string"?Lt.recycleBinCountUrl:""),Sb({getRecycleBinCount:pb}),window.__desktopModeConnectionBridge=le,G(v.WINDOW_CLOSED,"desktop-mode/connection-cleanup",_=>{_?.windowId&&le.onWindowClosed(_.windowId)}),G(v.IFRAME_READY,"desktop-mode/connection-rearm",_=>{_?.windowId&&le.onIframeReady(_.windowId)});const pa=Hy(n),mI=Ek({layoutDispatcher:T,desktopArea:t,config:e,syncNativeWindows:k,syncServerWidgets:P,syncServerWallpapers:H,syncServerCommands:W,syncServerSettingsTabs:V,syncServerTitleBarButtons:M,syncServerUnfocusEffects:$,syncServerWindowLinkRenderers:Z,syncServerDockRailRenderers:se,renderIcons:_=>{if(T){T.applyDesktopIcons(_);return}Cl(t,_,{openWindow:y.openById,manager:n,deriveWindowId:U=>ne(U,e.adminUrl)})},syncShortcuts:()=>{const _=d.getOsSettingsSnapshot();ws(_.itemVisibility,_.dockPromotedPositions,_.desktopLayout)}});d.subscribeOsSettings(_=>{if(!T)return;const U=T.getLayout();T.setLayout(_.desktopLayout),As.dock=T.getPrimary(),As.sideDock=T.getSide(),As.desktopLayout=_.desktopLayout,U===_.desktopLayout&&T.refresh(),ws(_.itemVisibility,_.dockPromotedPositions,_.desktopLayout),ju(_.desktopLayout)}),QE(()=>d.getOsSettingsSnapshot().itemVisibility,()=>d.getOsSettingsSnapshot().dockPromotedPositions,()=>d.getOsSettingsSnapshot().desktopLayout),ju(d.getOsSettingsSnapshot().desktopLayout);const As=c_({manager:n,dock:D,layoutDispatcher:T,osSettings:d,iconsApi:Ky,filesApi:Ne,saveSession:K,widgetLayer:a,registerWindow:pa,openWindowById:y.openById,openNewWindowById:y.openNewById,placeSystemTile:E,setDefaultWindow:X,refreshMenu:mI,openOsSettings:b,aiAssistant:c,dragBridge:l,dragManager:u,connect:le.connect,getConnection:le.getConnection,config:e});if(l_(As),ot(()=>wS(u)),nk(),ot(()=>mk()),R0({host:t,config:e,available:e.stickyNotes?.available,getActiveDesktopId:()=>n.getActiveDesktopId(),openArtifact:(_,U)=>{const B=ne(_,e.adminUrl);n.open({id:B,baseId:B,url:_,title:U,icon:"dashicons-edit-page"})},onError:_=>{ee({message:_})}}),y_({openUrl:({id:_,url:U,title:B,icon:Y})=>(mt(U)||n.open({id:_,baseId:_,url:U,title:B,icon:Y}),!0),openNativeWindow:_=>y.openById(_),deriveWindowId:_=>ne(_,e.adminUrl)}),Yu(e.userFileAssociations??{}),Q0({update:e.coreUpdate,openUrl:({url:_,title:U})=>{mt(_)||n.open({id:"update-core",baseId:"update-core",url:_,title:U,icon:"dashicons-update"})}}),typeof e.filesUrl=="string"&&e.filesUrl){Zu({baseUrl:e.filesUrl,nonce:e.restNonce});const _=document.getElementById("desktop-mode-area");if(_){const U=Ep(_,0),B=()=>{t.classList.contains("desktop-mode-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("desktop-mode-area--booting")})},Y=setTimeout(B,2e3);U.hydrated.then(()=>{clearTimeout(Y),B()})}}ot(()=>yS()),ot(()=>kS()),ot(()=>ik()),A(v.COMPONENTS_REGISTERED,{tags:[...uf]}),Zv(),nv(e,ee);const Df=()=>{Yf(e.shellOverlaysBundleUrl??""),qf(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(Df,{timeout:1500}):window.setTimeout(Df,0),A(v.INIT,{config:e}),sa=!0;const hI=xf.splice(0);for(const _ of hI)try{_()}catch(U){A(v.SHELL_ERROR,{scope:"when-ready-cb",error:U}),typeof console<"u"&&console.error("[desktop-mode] whenReady cb threw:",U)}d.apply(),a?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),a?.disposeAll()}),Dk(),yk(n,e);const Of=(_,U=!0)=>{const B=Ne.store.getState().placementsByFolder.get(0)??[],Y=_(B),ue=Math.max(1,Math.floor((t.clientHeight-16)/110)),nn=new Set;let Tt=0;for(const Le of Y){const xe=St(16+Math.floor(Tt/ue)*96,16+Tt%ue*110,nn,t);nn.add(`${xe.col},${xe.row}`),Tt++,!(Le.x===xe.x&&Le.y===xe.y)&&(Ne.store.upsertPlacement({...Le,x:xe.x,y:xe.y,sortOrder:Tt}),U&&qt(Le.id,{x:xe.x,y:xe.y,sortOrder:Tt}).catch(it=>{console.error("[desktop-mode] relayout persist failed",it)}))}},Rf=_=>U=>{const B=U.slice();switch(_){case"name-asc":B.sort((Y,ue)=>Y.file.title.localeCompare(ue.file.title));break;case"name-desc":B.sort((Y,ue)=>ue.file.title.localeCompare(Y.file.title));break;case"date-asc":B.sort((Y,ue)=>Y.updatedAtMs-ue.updatedAtMs);break;case"date-desc":B.sort((Y,ue)=>ue.updatedAtMs-Y.updatedAtMs);break}return B},ma="desktop-mode:root-sort-mode",wI=_=>_==="name-asc"||_==="name-desc"||_==="date-asc"||_==="date-desc";let Ls=(()=>{try{const _=window.localStorage.getItem(ma);return wI(_)?_:null}catch{return null}})();const Mf=_=>{Ls=_;try{_?window.localStorage.setItem(ma,_):window.localStorage.removeItem(ma)}catch{}};if(G("desktop-mode.files.tile-manually-placed","desktop-mode/root-sort-clear",_=>{_?.folderId===0&&Mf(null)}),typeof ResizeObserver<"u"){let _=t.clientWidth,U=t.clientHeight;new ResizeObserver(()=>{if(!Ls)return;const Y=t.clientWidth,ue=t.clientHeight;Y===_&&ue===U||(_=Y,U=ue,Of(Rf(Ls),!1))}).observe(t)}let Wf=!1;t.addEventListener("pointerdown",_=>{_.isPrimary&&(Wf=_.target===t)}),t.addEventListener("click",_=>{d.state.showDesktopOnWallpaperClick&&_.target===t&&Wf&&(t.classList.contains("desktop-mode-area--overview")||Ef()||u.recentlyEndedDrag()||n.toggleShowDesktop())}),t.addEventListener("contextmenu",_=>{if(_.target!==t)return;_.preventDefault();const U=_.clientX,B=_.clientY;(()=>{if(t.classList.contains("desktop-mode-area--overview"))return;if(Ef()){so();return}const Y={x:U,y:B},ue=()=>{const Le=t.getBoundingClientRect(),xe=Math.max(0,Y.x-Le.left),it=Math.max(0,Y.y-Le.top),Io=wp(Ne.store.getState().placementsByFolder.get(0)??[]);return St(xe,it,Io,t)},nn=(Le,xe)=>{CS({title:Le,description:xe,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:it,url:Io})=>{const Pf=ue(),gI=await jt({type:"link",ref:Io,parentId:0,x:Pf.x,y:Pf.y,meta:it?{name:it}:void 0});Ne.store.upsertPlacement(gI)}})},Tt=IS({createFolder:()=>{Er({onSubmit:async Le=>{const xe=await mr({name:Le}),it=ue(),Io=await jt({type:"folder",ref:String(xe.id),parentId:0,x:it.x,y:it.y});Ne.store.upsertFolder(xe),Ne.store.upsertPlacement(Io)}})},createUrl:()=>nn("New URL","Opens the URL in a new browser tab."),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>b(),sortIcons:Le=>{Mf(Le),Of(Rf(Le))},currentSortMode:Ls,includeShowDesktop:!d.state.showDesktopOnWallpaperClick,labels:{createFolder:"New folder",showDesktop:"Show desktop",osSettings:"OS Settings",sortHeading:"Sort by",sortNameAsc:"Name (A → Z)",sortNameDesc:"Name (Z → A)",sortDateAsc:"Date (oldest first)",sortDateDesc:"Date (newest first)",newUrl:"New URL"},serverItems:e.serverWallpaperMenuItems??[]});ES(document.body,{x:U,y:B},Tt)})()}),Promise.resolve().then(()=>oI).then(_=>{_.bootOsFileDrop({config:e.dropConfig,mediaUrl:e.mediaUrl,restNonce:e.restNonce})}),document.dispatchEvent(new CustomEvent("desktop-mode-init",{detail:{config:e,restored:C}}))}cS(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Cf):Cf();const AS={tab:null,requestedAt:0};let _s=null;function aa(){if(_s)return _s;const t=window.wp?.desktop?.createSharedStore;return typeof t!="function"?null:(_s=t("desktop-mode/plugins-window/tab-target",()=>({...AS})),_s)}function LS(e){const t=aa();if(t){t.state.tab=e,t.state.requestedAt=Date.now(),t.notify();return}const n=window;n._wpdPluginsWindowTab={tab:e,requestedAt:Date.now()}}function TS(){const e=aa();if(e){const o=e.state.tab;return o!==null&&(e.state.tab=null,e.state.requestedAt=0,e.notify()),o}const t=window,n=t._wpdPluginsWindowTab;return n?(t._wpdPluginsWindowTab={tab:null,requestedAt:0},n.tab):null}function NS(e){const t=aa();return t?t.subscribe(n=>e({...n})):()=>{}}const DS=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:TS,setPluginsWindowTab:LS,subscribePluginsWindowTab:NS},Symbol.toStringTag,{value:"Module"})),fe={FILES_DETECTED:"desktop-mode.drop.files-detected",FILES_REJECTED:"desktop-mode.drop.files-rejected",DIALOG_FIELDS:"desktop-mode.drop.dialog-fields",BEFORE_UPLOAD:"desktop-mode.drop.before-upload",UPLOAD_STARTED:"desktop-mode.drop.upload-started",UPLOAD_PROGRESS:"desktop-mode.drop.upload-progress",AFTER_UPLOAD:"desktop-mode.drop.after-upload",UPLOAD_FAILED:"desktop-mode.drop.upload-failed"},OS=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function Es(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;if(typeof n.includes=="function")return n.includes("Files");if(typeof n.contains=="function")return n.contains("Files");for(let o=0;o<n.length;o++)if(n[o]==="Files")return!0;return!1}function RS(e){if(!e)return;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e)return n.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0}function MS(e){const t=window;if(t.__desktopModeOsFileDropMounted)return t.__desktopModeOsFileDropMounted;if(!e.config.enabled)return PS();const n=WS();let o=0,s=null;const i=()=>{o=0,n.classList.remove("is-active"),s!==null&&(clearTimeout(s),s=null)},r=()=>{s!==null&&clearTimeout(s),s=setTimeout(i,250)},a=m=>{Es(m)&&(m.preventDefault(),o++,n.classList.add("is-active"),r())},d=m=>{if(Es(m)){if(m.defaultPrevented){i();return}m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="copy"),r()}},c=()=>{o=Math.max(0,o-1),o===0&&n.classList.remove("is-active")},l=m=>{if(!Es(m))return;if(m.defaultPrevented){i();return}m.preventDefault(),i();const w=m.dataTransfer?.files?Array.from(m.dataTransfer.files):[];if(w.length===0)return;const g=$S(m);Af(w,g,e)},u=()=>i(),p=()=>{document.visibilityState==="hidden"&&i()},f=m=>{if(m.origin!==window.location.origin)return;const w=m.data;if(!w||w.type!=="desktop-mode-os-file-drop"||!Array.isArray(w.files)||w.files.length===0)return;const g=w.files.filter(y=>y instanceof File);if(g.length===0)return;const x=RS(m.source);if(!x)return;const T={surface:"iframe",windowId:x,x:typeof w.x=="number"?w.x:0,y:typeof w.y=="number"?w.y:0};o=0,n.classList.remove("is-active"),Af(g,T,e)};window.addEventListener("dragenter",a),window.addEventListener("dragover",d),window.addEventListener("dragleave",c),window.addEventListener("drop",l),window.addEventListener("dragend",u),document.addEventListener("visibilitychange",p),window.addEventListener("blur",u),window.addEventListener("message",f);const h={dispose:()=>{window.removeEventListener("dragenter",a),window.removeEventListener("dragover",d),window.removeEventListener("dragleave",c),window.removeEventListener("drop",l),window.removeEventListener("dragend",u),document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",u),window.removeEventListener("message",f),n.remove(),delete window.__desktopModeOsFileDropMounted}};return t.__desktopModeOsFileDropMounted=h,h}function WS(){const e=document.querySelector(".desktop-mode-os-drop-overlay");if(e)return e;const t=document.createElement("div");t.className="desktop-mode-os-drop-overlay",t.setAttribute("aria-hidden","true"),t.style.cssText=["position:fixed","inset:0","pointer-events:none","z-index:200","opacity:0","transition:opacity 120ms ease","background:radial-gradient(circle at center, rgba(34,113,177,0.18) 0%, rgba(34,113,177,0.06) 60%, transparent 100%)","box-shadow:inset 0 0 0 3px rgba(34,113,177,0.55)"].join(";");const n=document.createElement("div");n.style.cssText=["position:absolute","top:50%","left:50%","transform:translate(-50%,-50%)","padding:14px 22px","border-radius:12px","background:rgba(20,20,24,0.78)","color:#fff","font:600 14px/1.2 -apple-system,BlinkMacSystemFont,sans-serif","letter-spacing:0.02em"].join(";"),n.textContent="Drop to upload",t.appendChild(n),document.body.appendChild(t);const o=document.createElement("style");return o.textContent=".desktop-mode-os-drop-overlay.is-active{opacity:1!important;}",document.head.appendChild(o),t}function PS(){const e=o=>{if(!Es(o))return;const s=o.target;s?.closest&&OS.some(i=>s.closest(i))||o.preventDefault()};window.addEventListener("dragover",e),window.addEventListener("drop",e);const t=window,n={dispose:()=>{window.removeEventListener("dragover",e),window.removeEventListener("drop",e),delete t.__desktopModeOsFileDropMounted}};return t.__desktopModeOsFileDropMounted=n,n}function $S(e){const t=e.clientX,n=e.clientY;let o=e.target;for(;o&&o!==document.body;){if(o.tagName==="IFRAME")return{surface:"iframe",windowId:o.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0,x:t,y:n};if(o.hasAttribute("data-window-id"))return{surface:"window",windowId:o.getAttribute("data-window-id")||void 0,x:t,y:n};if(o.classList.contains("desktop-mode-folder-grid"))return{surface:"folder",x:t,y:n};if(o.id==="desktop-mode-wallpaper"||o.classList.contains("desktop-mode-wallpaper")||o.classList.contains("desktop-mode-desktop"))return{surface:"wallpaper",x:t,y:n};o=o.parentElement}return{surface:"unknown",x:t,y:n}}async function Af(e,t,n){const o=j(fe.FILES_DETECTED,e,t);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=US(o,n.config);if(i.length>0&&(A(fe.FILES_REJECTED,{rejections:i,context:t}),ee({message:i.length===1?i[0].message:`${i.length} files couldn't be uploaded.`})),s.length===0)return;const r=s.map(({file:a,mime:d})=>{const c={file:a,mime:d,fields:FS(a,d)},l=j(fe.DIALOG_FIELDS,c,t);return!l||typeof l!="object"||!("fields"in l)||typeof l.fields!="object"?c:l});await n.openDialog(r,t)}function US(e,t){const n=[],o=[];for(const s of e){if(s.size===0){o.push({file:s,reason:"empty",message:`“${s.name}” is empty.`});continue}if(t.maxSize>0&&s.size>t.maxSize){o.push({file:s,reason:"size",message:`“${s.name}” exceeds the ${jS(t.maxSize)} upload limit.`});continue}const i=HS(s,t.allowedMimes,t.extToMime);if(!i){o.push({file:s,reason:"mime",message:`“${s.name}” is not an allowed file type.`});continue}n.push({file:s,mime:i})}return{accepted:n,rejected:o}}function HS(e,t,n){if(t.length===0)return null;const o=e.type.toLowerCase();if(o&&t.includes(o))return o;const s=Lf(e.name);if(!s)return null;if(n){for(const[r,a]of Object.entries(n))if(r.split("|").includes(s)&&t.includes(a))return a;return null}const i=BS[s];return i&&t.includes(i)?i:null}const BS={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",avif:"image/avif",heic:"image/heic",heif:"image/heif",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",pdf:"application/pdf"};function Lf(e){const t=e.lastIndexOf(".");return t<0?"":e.slice(t+1).toLowerCase()}function FS(e,t){const n=zS(e.name),o=Lf(n),s=o?n.slice(0,n.length-o.length-1):n,i=GS(s);return{title:i,altText:t.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function zS(e){return e.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function GS(e){const t=e.replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Upload"}function jS(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function Ss(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,o=0;for(;n>=1024&&o<t.length-1;)n/=1024,o++;const s=n>=100||o===0?0:1;return`${n.toFixed(s)} ${t[o]}`}const qS=he`:host{display:block;--wpd-progress-track-bg:var( --desktop-mode-control-bg,rgba( 0,0,0,0.08 ) );--wpd-progress-fill:var( --wp-admin-theme-color,#2271b1 );--wpd-progress-height:6px;--wpd-progress-radius:999px;--wpd-progress-label-color:inherit;--wpd-progress-label-size:12px;--wpd-progress-label-gap:4px;width:100%;font:inherit;color:var( --wpd-progress-label-color )}:host( [ hidden ] ){display:none}.header{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:var( --wpd-progress-label-gap );font-size:var( --wpd-progress-label-size );line-height:1.3}.label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.percent{font-variant-numeric:tabular-nums;opacity:0.75;flex-shrink:0}.track{position:relative;width:100%;height:var( --wpd-progress-height );background:var( --wpd-progress-track-bg );border-radius:var( --wpd-progress-radius );overflow:hidden}.fill{position:absolute;inset-block:0;inset-inline-start:0;width:0;background:var( --wpd-progress-fill );border-radius:inherit;transition:width 0.18s ease-out}:host( [ tone='success' ] ){--wpd-progress-fill:var( --desktop-mode-status-success,#3a8a3a )}:host( [ tone='warning' ] ){--wpd-progress-fill:var( --desktop-mode-status-warning,#dba617 )}:host( [ tone='danger' ] ){--wpd-progress-fill:var( --desktop-mode-status-danger,#d63638 )}:host( [ indeterminate ] ) .fill{width:33%;animation:wpd-progress-sweep 1.1s linear infinite;transition:none}@keyframes wpd-progress-sweep{0%{transform:translateX( -120% )}100%{transform:translateX( 320% )}}@media ( prefers-reduced-motion:reduce ){.fill{transition:none}:host( [ indeterminate ] ) .fill{animation:none;width:100%;opacity:0.6}}`,_o=class _o extends pe{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return z`<div class="root" part="root"> |
| 333 |
<div class="header" part="header" hidden> |
| 334 |
<span class="label" part="label"></span> |
| 335 |
<span class="percent" part="percent"></span> |
| 336 |
</div> |
| 337 |
<div class="track" part="track"> |
| 338 |
<div class="fill" part="fill"></div> |
| 339 |
</div> |
| 340 |
</div>`}requestUpdate(){super.requestUpdate(),queueMicrotask(()=>this._paint())}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paint())}_paint(){const t=this.shadowRoot;if(!t)return;const n=this._readMax(),o=this.hasAttribute("indeterminate")||n<=0,s=o?0:this._readValue(n),i=o?0:s/n,r=Math.round(i*100),a=this.getAttribute("label")??"",d=this.hasAttribute("show-percent"),c=t.querySelector(".fill");c&&!o?c.style.width=`${(i*100).toFixed(2)}%`:c&&o&&c.style.removeProperty("width");const l=t.querySelector(".header"),u=t.querySelector(".label"),p=t.querySelector(".percent");if(l&&u&&p){const h=a||d&&!o;l.hidden=!h,u.textContent=a,p.hidden=!(d&&!o),p.textContent=`${r}%`}this._syncAria(n,s,o,a);const f=t.querySelector(".track");f&&(f.setAttribute("role","progressbar"),f.setAttribute("aria-valuemin","0"),o?(f.removeAttribute("aria-valuenow"),f.removeAttribute("aria-valuemax")):(f.setAttribute("aria-valuemax",String(n)),f.setAttribute("aria-valuenow",String(s))),a?f.setAttribute("aria-label",a):f.removeAttribute("aria-label"))}_syncAria(t,n,o,s){this.setAttribute("role","progressbar"),this.setAttribute("aria-valuemin","0"),o?(this.removeAttribute("aria-valuenow"),this.removeAttribute("aria-valuemax")):(this.setAttribute("aria-valuemax",String(t)),this.setAttribute("aria-valuenow",String(n)));const i=this.getAttribute("aria-label");s?(i===null||i===this._ownedAriaLabel)&&(this.setAttribute("aria-label",s),this._ownedAriaLabel=s):i!==null&&i===this._ownedAriaLabel&&(this.removeAttribute("aria-label"),this._ownedAriaLabel=null)}_readMax(){const t=this.getAttribute("max");if(t===null)return 100;const n=parseFloat(t);return Number.isFinite(n)?n:100}_readValue(t){const n=parseFloat(this.getAttribute("value")??"0");return!Number.isFinite(n)||n<0?0:n>t?t:n}};_o.props=["value","max","indeterminate","tone","label","showPercent"],_o.styles=[qS],_o.help=void 0;let da=_o;me("wpd-progress-bar",da);const Be=new Map;let st=null;function VS(){if(document.body.hasAttribute("data-desktop-mode-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const e="desktop-mode/os-file-drop-hud";G(fe.UPLOAD_STARTED,e,t=>KS(t.file,t.fields,t.abort)),G(fe.UPLOAD_PROGRESS,e,t=>YS(t.file,t.loaded,t.total,t.indeterminate)),G(fe.AFTER_UPLOAD,e,t=>XS(t.file,t.fields,t.result)),G(fe.UPLOAD_FAILED,e,t=>ZS(t.file,t.error))}function KS(e,t,n){const o=JS(),s=document.createElement("div");s.className="desktop-mode-upload-hud__row";const i=document.createElement("div");i.className="desktop-mode-upload-hud__meta";const r=document.createElement("div");r.className="desktop-mode-upload-hud__name",r.textContent=t.filename||e.name,r.title=t.filename||e.name;const a=document.createElement("div");a.className="desktop-mode-upload-hud__status",a.textContent="Uploading…",i.append(r,a);const d=document.createElement("wpd-progress-bar");d.setAttribute("indeterminate",""),d.setAttribute("show-percent","");const c=document.createElement("div");c.className="desktop-mode-upload-hud__actions";const l=document.createElement("wpd-button");l.setAttribute("variant","tertiary"),l.setAttribute("size","small"),l.textContent="Cancel",l.addEventListener("click",()=>{const u=Be.get(e);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):ca(u))}),c.appendChild(l),s.append(i,d,c),o.querySelector(".desktop-mode-upload-hud__list").appendChild(s),Be.set(e,{file:e,abort:n,root:s,bar:d,statusEl:a,cancelBtn:l,state:"running",lingerTimer:null}),Is()}function YS(e,t,n,o){const s=Be.get(e);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${Ss(t)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(t)),s.statusEl.textContent=`${Ss(t)} / ${Ss(n)}`))}function XS(e,t,n){const o=Be.get(e);o&&(o.state="success",o.bar.removeAttribute("indeterminate"),o.bar.setAttribute("value","100"),o.bar.setAttribute("max","100"),o.bar.setAttribute("tone","success"),o.statusEl.textContent="Uploaded",o.cancelBtn.textContent="Dismiss",o.lingerTimer=setTimeout(()=>ca(o),2500),Is(),ye.publish("desktop-mode/upload-hud-complete",{filename:t.filename||n.filename,attachmentId:n.id}))}function ZS(e,t){const n=Be.get(e);n&&(n.bar.removeAttribute("indeterminate"),n.bar.setAttribute("tone","danger"),n.cancelBtn.textContent="Dismiss",n.cancelBtn.disabled=!1,t.name==="UploadAbortedError"?(n.state="aborted",n.statusEl.textContent="Cancelled"):(n.state="failed",n.statusEl.textContent=t.message||"Upload failed"),Is())}function ca(e){e.lingerTimer&&clearTimeout(e.lingerTimer),Be.delete(e.file),e.root.remove(),Is(),Be.size===0&&st&&(st.hidden=!0)}function JS(){if(st&&st.isConnected)return st.hidden=!1,st;const e=document.createElement("div");e.className="desktop-mode-upload-hud",e.setAttribute("role","region"),e.setAttribute("aria-label","Uploads");const t=document.createElement("div");t.className="desktop-mode-upload-hud__header";const n=document.createElement("div");n.className="desktop-mode-upload-hud__title",n.textContent="Uploads";const o=document.createElement("button");o.type="button",o.className="desktop-mode-upload-hud__close",o.setAttribute("aria-label","Hide upload panel"),o.textContent="×",o.addEventListener("click",()=>{for(const i of[...Be.values()])i.state!=="running"&&ca(i);Be.size===0&&(e.hidden=!0)}),t.append(n,o);const s=document.createElement("div");return s.className="desktop-mode-upload-hud__list",e.append(t,s),document.body.appendChild(e),st=e,e}function Is(){if(!st)return;const e=st.querySelector(".desktop-mode-upload-hud__title");if(!e)return;const t=Be.size,n=[...Be.values()].filter(o=>o.state==="running").length;n>0?e.textContent=n===t?`Uploading ${n} file${n===1?"":"s"}…`:`${n} of ${t} uploading…`:t>0?e.textContent=`Uploads (${t})`:e.textContent="Uploads"}function QS(){if(document.body.hasAttribute("data-desktop-mode-suppress-media-library-refresh"))return;const e=window;e.__wpdMediaLibraryRefresher||(e.__wpdMediaLibraryRefresher=!0,G(fe.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>eI()))}function eI(){const e=document.querySelectorAll("iframe");for(const t of Array.from(e))if(tI(Tf(t)))try{t.contentWindow?.location.reload()}catch{const n=Tf(t);n&&t.setAttribute("src",n)}}function Tf(e){try{return e.contentWindow?.location.href??e.src??""}catch{return e.src??""}}function tI(e){return e?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(e):!1}function nI(e){const t=e.config||{enabled:!1,allowedMimes:[],maxSize:0};VS(),QS(),MS({config:t,mediaUrl:e.mediaUrl,restNonce:e.restNonce,openDialog:async(n,o)=>{const{openUploadDialog:s}=await Promise.resolve().then(()=>fI);await s({entries:n,context:o,mediaUrl:e.mediaUrl,restNonce:e.restNonce})}})}const oI=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:fe,bootOsFileDrop:nI},Symbol.toStringTag,{value:"Module"})),sI=he`:host{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var( --desktop-mode-text,#1d2327 );min-width:0}:host( [ hidden ] ){display:none}.wpd-text-field__label{font-size:12px;color:var( --desktop-mode-muted,#646970 )}.wpd-text-field__row{position:relative;display:flex;align-items:center;width:100%}input{appearance:none;-webkit-appearance:none;display:block;width:100%;min-width:0;box-sizing:border-box;padding:7px 10px;background:var( --desktop-mode-window-bg,#fff );border:1px solid var( --desktop-mode-border,#dcdcde );border-radius:6px;font:inherit;font-size:13px;color:var( --desktop-mode-text,#1d2327 );transition:border-color 0.12s ease,box-shadow 0.12s ease}.wpd-text-field__suffix{position:absolute;inset-inline-end:10px;top:50%;transform:translateY( -50% );pointer-events:none;font-size:12px;color:var( --desktop-mode-muted,#646970 )}.wpd-text-field__row--has-reveal input{padding-inline-end:36px}.wpd-text-field__reveal{position:absolute;inset-inline-end:0;top:0;bottom:0;width:34px;display:flex;align-items:center;justify-content:center;padding:0;border:none;background:transparent;color:var( --desktop-mode-muted,#646970 );cursor:pointer;border-radius:0 6px 6px 0;transition:color 0.12s ease}.wpd-text-field__reveal:hover{color:var( --wp-admin-theme-color,#2271b1 )}.wpd-text-field__reveal:focus-visible{outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:-2px;border-radius:0 6px 6px 0}.wpd-text-field__reveal:disabled{opacity:0.45;cursor:not-allowed}.wpd-text-field__input--masked{-webkit-text-security:disc;text-security:disc}@supports not ( ( -webkit-text-security:disc ) or ( text-security:disc ) ){.wpd-text-field__input--masked{font-family:text-security-disc,"password",monospace;letter-spacing:0.2em}}input:hover{border-color:var( --desktop-mode-muted,#8c8f94 )}input:focus-visible{outline:none;border-color:var( --wp-admin-theme-color,#2271b1 );box-shadow:0 0 0 1px var( --wp-admin-theme-color,#2271b1 )}input:disabled{opacity:0.55;cursor:not-allowed;background:rgba( 0,0,0,0.03 )}input[ aria-invalid='true' ]{border-color:#d63638}input[ aria-invalid='true' ]:focus-visible{box-shadow:0 0 0 1px #d63638}input[ type='number' ]::-webkit-inner-spin-button,input[ type='number' ]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}input[ type='number' ]{-moz-appearance:textfield}`,Eo=class Eo extends pe{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),Gd(this)}render(){const t=this.label||"",n=this.value??"",o=this.placeholder||"",s=this.disabled!==null,i=this.readonly!==null,r=this.autocomplete,a=this.type||"text",d=a==="password";let c=r||"off";d&&(!r||c==="off")&&(c="new-password");const l=this.maxlength,u=this.minlength,p=this.pattern||"",f=this.name||"",h=this.suffix||"",m=this.invalid!==null,w=this.reveal!==null,g=a==="password",x=g&&!(w&&this._revealed);let T;g||w&&this._revealed?T="text":T=a;const y=w?"wpd-text-field__row wpd-text-field__row--has-reveal":"wpd-text-field__row",k=x?"wpd-text-field__input wpd-text-field__input--masked":"wpd-text-field__input",b=`${this.id||"wpd-unnamed"}__input`;return z` |
| 341 |
${t?z`<label |
| 342 |
class="wpd-text-field__label" |
| 343 |
for=${b} |
| 344 |
>${t}</label>`:z``} |
| 345 |
<span class=${y}> |
| 346 |
<input |
| 347 |
id=${b} |
| 348 |
class=${k} |
| 349 |
type=${T} |
| 350 |
.value=${n} |
| 351 |
placeholder=${o} |
| 352 |
?disabled=${s} |
| 353 |
?readonly=${i} |
| 354 |
autocomplete=${c} |
| 355 |
maxlength=${l??""} |
| 356 |
minlength=${u??""} |
| 357 |
pattern=${p} |
| 358 |
name=${f} |
| 359 |
aria-invalid=${m?"true":"false"} |
| 360 |
aria-label=${t||""} |
| 361 |
@input=${L=>this._onInput(L)} |
| 362 |
@change=${L=>this._onChange(L)} |
| 363 |
@keydown=${L=>this._onKeyDown(L)} |
| 364 |
/> |
| 365 |
${h?z`<span class="wpd-text-field__suffix">${h}</span>`:z``} |
| 366 |
${w?this._renderRevealButton(s):z``} |
| 367 |
</span> |
| 368 |
`}_renderRevealButton(t){const n=this._revealed?"Hide":"Show";return z` |
| 369 |
<button |
| 370 |
type="button" |
| 371 |
class="wpd-text-field__reveal" |
| 372 |
aria-label=${n} |
| 373 |
aria-pressed=${this._revealed?"true":"false"} |
| 374 |
?disabled=${t} |
| 375 |
tabindex="0" |
| 376 |
@click=${()=>this._onToggleReveal()} |
| 377 |
> |
| 378 |
${this._revealed?rI():iI()} |
| 379 |
</button> |
| 380 |
`}_onToggleReveal(){this._revealed=!this._revealed,this.requestUpdate()}_onInput(t){const n=t.target;this.value=n.value,this.emit("wpd-input-change",{value:n.value})}_onChange(t){const n=t.target;this.emit("wpd-input-commit",{value:n.value})}_onKeyDown(t){if(t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey){const n=t.target;this.emit("wpd-submit",{value:n.value})}}};Eo.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],Eo.styles=[sI],Eo.help=void 0;let la=Eo;me("wpd-text-field",la);function iI(){return z` |
| 381 |
<svg |
| 382 |
viewBox="0 0 16 16" |
| 383 |
width="14" |
| 384 |
height="14" |
| 385 |
fill="none" |
| 386 |
stroke="currentColor" |
| 387 |
stroke-width="1.5" |
| 388 |
stroke-linecap="round" |
| 389 |
stroke-linejoin="round" |
| 390 |
aria-hidden="true" |
| 391 |
focusable="false" |
| 392 |
> |
| 393 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 394 |
<circle cx="8" cy="8" r="2" /> |
| 395 |
</svg> |
| 396 |
`}function rI(){return z` |
| 397 |
<svg |
| 398 |
viewBox="0 0 16 16" |
| 399 |
width="14" |
| 400 |
height="14" |
| 401 |
fill="none" |
| 402 |
stroke="currentColor" |
| 403 |
stroke-width="1.5" |
| 404 |
stroke-linecap="round" |
| 405 |
stroke-linejoin="round" |
| 406 |
aria-hidden="true" |
| 407 |
focusable="false" |
| 408 |
> |
| 409 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 410 |
<circle cx="8" cy="8" r="2" /> |
| 411 |
<line x1="2" y1="2" x2="14" y2="14" /> |
| 412 |
</svg> |
| 413 |
`}async function aI(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=j(fe.BEFORE_UPLOAD,t,e.context);if(!n)throw new Nf;const o=new FormData,s=n.fields.filename!==n.file.name?new File([n.file],n.fields.filename,{type:n.mime||n.file.type}):n.file;return o.append("file",s),o.append("title",n.fields.title),o.append("alt_text",n.fields.altText),o.append("caption",n.fields.caption),o.append("description",n.fields.description),new Promise((i,r)=>{const a=new XMLHttpRequest;a.open("POST",e.mediaUrl,!0),a.withCredentials=!0,a.setRequestHeader("X-WP-Nonce",e.restNonce),a.responseType="text";let d=!1,c=!1,l=!1;const u=()=>{if(l=!0,!c){d=!0;try{a.abort()}catch{}}};A(fe.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:u}),a.upload.addEventListener("progress",p=>{A(fe.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:p.loaded,total:p.lengthComputable?p.total:0,indeterminate:!p.lengthComputable})}),a.upload.addEventListener("load",()=>{c=!0,A(fe.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:n.file.size,total:n.file.size,indeterminate:!1})}),a.addEventListener("error",()=>{if(d)return;const p=new Error("Network error during upload.");A(fe.UPLOAD_FAILED,{file:n.file,error:p,context:e.context}),r(p)}),a.addEventListener("abort",()=>{const p=new ua;A(fe.UPLOAD_FAILED,{file:n.file,error:p,context:e.context}),r(p)}),a.addEventListener("load",()=>{if(d)return;if(a.status<200||a.status>=300){const h=cI(a),m=new Error(h);A(fe.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}let p;try{p=JSON.parse(a.responseText)}catch(h){const m=h instanceof Error?h:new Error("Could not parse server response.");A(fe.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}if(l&&p.id){dI(e.mediaUrl,e.restNonce,p.id);const h=new ua;A(fe.UPLOAD_FAILED,{file:n.file,error:h,context:e.context}),r(h);return}const f={id:p.id,url:p.source_url,mime:p.mime_type||n.mime,title:p.title?.rendered||n.fields.title,filename:p.media_details?.file||n.fields.filename};A(fe.AFTER_UPLOAD,{file:n.file,result:f,fields:n.fields,context:e.context}),i(f)}),a.send(o)})}class Nf extends Error{constructor(){super("Upload cancelled by desktop-mode.drop.before-upload filter."),this.name="UploadCancelledError"}}class ua extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function dI(e,t,n){const o=`${e.replace(/\/$/,"")}/${n}?force=true`,s=new XMLHttpRequest;return s.open("DELETE",o,!0),s.withCredentials=!0,s.setRequestHeader("X-WP-Nonce",t),new Promise(i=>{s.addEventListener("loadend",()=>{(s.status<200||s.status>=300)&&console.warn(`[os-file-drop] late-cancel cleanup failed for attachment ${n} (HTTP ${s.status}). The attachment remains in the Media Library; delete it manually.`),i()}),s.addEventListener("error",()=>{console.warn(`[os-file-drop] late-cancel cleanup network error for attachment ${n}. The attachment remains in the Media Library; delete it manually.`),i()});try{s.send()}catch(r){console.warn(`[os-file-drop] late-cancel cleanup could not be dispatched for attachment ${n}:`,r),i()}})}function cI(e){const t=`Upload failed (HTTP ${e.status}).`,n=e.responseText;if(!n)return t;try{const o=JSON.parse(n);if(o&&typeof o.message=="string")return o.message}catch{}return t}async function lI(e){if(e.entries.length===0)return;const t=document.createElement("wpd-modal");t.setAttribute("open",""),t.setAttribute("size","md"),t.setAttribute("title",e.entries.length===1?"Upload to Media Library":`Upload ${e.entries.length} files to Media Library`),document.body.appendChild(t);const n=e.entries.map(r=>({...r.fields})),o=()=>{t.innerHTML="";const r=document.createElement("div");r.style.cssText="display:flex;flex-direction:column;gap:18px;max-height:60vh;overflow:auto;padding-right:6px;",e.entries.forEach((l,u)=>{r.appendChild(s(l,n[u],u+1))}),t.appendChild(r);const a=document.createElement("div");a.setAttribute("slot","footer"),a.style.cssText="display:flex;gap:8px;justify-content:flex-end;";const d=document.createElement("wpd-button");d.setAttribute("variant","secondary"),d.textContent="Cancel",d.addEventListener("click",()=>{t.remove()});const c=document.createElement("wpd-button");c.setAttribute("variant","primary"),c.textContent=e.entries.length===1?"Upload":`Upload ${e.entries.length} files`,c.addEventListener("click",()=>{i(c,d)}),a.appendChild(d),a.appendChild(c),t.appendChild(a)},s=(r,a,d)=>{const c=document.createElement("div");c.style.cssText="display:flex;flex-direction:column;gap:8px;border:1px solid rgba(255,255,255,0.08);border-radius:10px;padding:14px;";const l=document.createElement("div");l.style.cssText="display:flex;gap:10px;align-items:center;font-weight:600;";const u=document.createElement("span");u.textContent=e.entries.length===1?"":`#${d} · `,u.style.opacity="0.6";const p=document.createElement("span");p.textContent=r.file.name,p.style.cssText="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const f=document.createElement("span");return f.textContent=`${r.mime||"unknown"} · ${Ss(r.file.size)}`,f.style.cssText="opacity:0.6;font-size:12px;",l.appendChild(u),l.appendChild(p),l.appendChild(f),c.appendChild(l),c.appendChild(xs("Title",a.title,h=>a.title=h)),c.appendChild(xs("Filename",a.filename,h=>a.filename=h)),r.mime.startsWith("image/")&&c.appendChild(xs("Alt text",a.altText,h=>a.altText=h)),c.appendChild(xs("Caption",a.caption,h=>a.caption=h)),c.appendChild(uI("Description",a.description,h=>a.description=h)),c},i=async(r,a)=>{r.disabled=!0,a.disabled=!0,r.textContent="Uploading…";const d=e.entries.length;let c=0,l=0,u=0;const p=[];for(let f=0;f<d;f++){const h=e.entries[f];try{await aI({file:h.file,mime:h.mime,fields:n[f],context:e.context,mediaUrl:e.mediaUrl,restNonce:e.restNonce}),c++}catch(m){if(m instanceof Nf){u++;continue}if(m instanceof ua){u++;continue}l++;const w=m instanceof Error?m.message:"Upload failed.";p.push(`“${h.file.name}” — ${w}`)}}t.remove(),pI({total:d,successes:c,failures:l,cancelled:u,failureDetails:p})};o(),await new Promise(r=>{t.addEventListener("wpd-modal-cancel",()=>{t.remove(),r()});const a=new MutationObserver(()=>{t.isConnected||(a.disconnect(),r())});a.observe(document.body,{childList:!0,subtree:!0})})}function xs(e,t,n){const o=document.createElement("wpd-text-field");return o.setAttribute("label",e),o.setAttribute("value",t),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function uI(e,t,n){const o=document.createElement("wpd-textarea");return o.setAttribute("label",e),o.setAttribute("value",t),o.setAttribute("rows","3"),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function pI(e){const{total:t,successes:n,failures:o,cancelled:s,failureDetails:i}=e;if(t===0)return;if(t===1){n===1?ee({message:"Uploaded to Media Library."}):o===1&&i[0]?ee({message:i[0]}):s===1&&ee({message:"Upload cancelled."});return}if(n===t){ee({message:`Uploaded ${n} files to Media Library.`});return}if(s===t){ee({message:"All uploads cancelled."});return}if(o===t){ee({message:o===1&&i[0]?i[0]:`${o} uploads failed.`});return}const r=[];n>0&&r.push(`Uploaded ${n} file${n===1?"":"s"}.`),s>0&&r.push(`Cancelled ${s}.`),o>0&&r.push(`Failed ${o}.`),ee({message:r.join(" ")})}const fI=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:lI},Symbol.toStringTag,{value:"Module"}));return Ts.clampGeometryToViewport=Wu,Object.defineProperty(Ts,Symbol.toStringTag,{value:"Module"}),Ts}({}); |
| 414 |
|