PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 0.8.7
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v0.8.7
1.1.10 1.1.9 1.1.8 1.1.7 1.1.6 1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.1 1.0.0 0.9.8 0.9.7 0.9.6 0.9.4 0.9.5 0.9.3 0.9.2 0.9.1 0.9.0 0.8.9 0.8.8 0.8.7 All 34 releases
desktop-mode / assets / js / desktop.min.js

desktop.min.js in OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin 0.8.7, at assets/js/desktop.min.js

265 lines 419.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var desktopMode=function(Fo){"use strict";var zo=typeof document<"u"?document.currentScript:null;function pu(){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}pu();function Ze(){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 fu(e,t,n,o){Ze().addFilter(e,t,n,o)}function q(e,t,n,o){Ze().addAction(e,t,n,o)}function Ji(e,t){return Ze().removeAction(e,t)}function z(e,t,...n){return Ze().applyFilters(e,t,...n)}function _(e,...t){Ze().doAction(e,...t)}function Qi(e){return Ze().didAction(e)}function mu(){return Ze()}const v={INIT:"desktop-mode.init",WALLPAPERS:"desktop-mode.wallpapers",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",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_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",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 hu=0;function er(e){if(Qi(v.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++hu}`;q(v.INIT,t,e)}function wu(){return Qi(v.INIT)>0}let ut=null;function jn(){return!!window.desktopModeWindowSystem}function tr(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-window-system="1"]'),s=()=>{if(jn()){t();return}n(new Error("[desktop-mode] window-system bundle loaded but did not register `window.desktopModeWindowSystem`."))};if(o){jn()?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 gu(){return window.desktopModeConfig?.windowSystemBundleUrl??""}function yu(e){!e||jn()||ut||(ut=tr(e).catch(t=>{ut=null,typeof console<"u"&&console.warn("[desktop-mode] window-system preload failed; will retry on first open():",t)}))}async function bu(e){if(jn())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 ut||(ut=tr(e)),await ut,window.desktopModeWindowSystem}const vu="wpd-confirm-dialog";let pt=null;function Pt(){return typeof window.customElements<"u"&&!!window.customElements.get(vu)}function nr(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-shell-overlays="1"]'),s=()=>{if(Pt()){t();return}n(new Error("[desktop-mode] shell-overlays bundle loaded but did not register the overlay components."))};if(o){Pt()?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 ku(e){!e||Pt()||pt||(pt=nr(e).catch(t=>{pt=null,typeof console<"u"&&console.warn("[desktop-mode] shell-overlays preload failed; will retry on first overlay use:",t)}))}function jo(e){return Pt()||!e?Promise.resolve():(pt||(pt=nr(e)),pt)}function Go(){return window.desktopModeConfig?.shellOverlaysBundleUrl??""}function $t(e,t){const n=Go();if(Pt()||!n){t();return}jo(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[desktop-mode] shell-overlays failed to load; menu/dialog suppressed:",o)})}const or="desktop-mode";function qo(){return window.wp?.i18n}function O(e,t=or){return qo()?.__(e,t)??e}function Wt(e,t,n,o=or){return qo()?._n(e,t,n,o)??(n===1?e:t)}function te(e,...t){const n=qo()?.sprintf;if(n)return n(e,...t);let o=0;return e.replace(/%[sd]/g,()=>String(t[o++]??""))}function _u(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 Eu(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 Su(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 Ko(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 b=f%s,m=Math.floor(f/s),w=t.left+r+b*(c+a),g=t.top+n+r+m*(l+a)+d,E=p.element.offsetWidth,D=p.element.offsetHeight,y=Math.min(c/E,u/D),S=E*y,h=D*y;return{win:p,x:w+(c-S)/2,y:g+(u-h)/2,scale:y}})}const sr=120;function Cu(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,_(v.OVERVIEW_ENTERING,{}),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=ir(e),e._desktop.appendChild(e._overviewTopBar);const d=Ko(n,r,sr);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 b=Yo(l);u.insertAdjacentElement("afterend",b),e._overviewLabels.set(l.win.id,b)}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 b=e.getById(u.id);_(v.OVERVIEW_WINDOW_CLICK,{windowId:u.id}),ft(e,b,!0)},e._overviewKeyHandler=l=>{if(l.key==="Escape"){ft(e);return}if(l.key==="Enter"){if(l.preventDefault(),e._overviewAddTileFocused){rr(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&&_(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&_(v.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),window.setTimeout(()=>{e._overviewActive&&_(v.OVERVIEW_ENTERED,{})},300)}function ir(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(Au(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(),rr(e)}),n.appendChild(o),t}function rr(e){const t=lr(e);e._overviewAddTileFocused=!1,ar(e,t.id)}function Au(e,t){const n=document.createElement("button");n.type="button",n.className="desktop-mode-overview-top-bar__tile",n.dataset.desktopId=t.id,t.id===e._activeDesktopId&&!e._overviewAddTileFocused&&n.classList.add("desktop-mode-overview-top-bar__tile--active"),n.setAttribute("aria-label",te(O("Switch to %s"),t.label));const o=document.createElement("span");o.className="desktop-mode-overview-top-bar__tile-preview";const s=e._stack.filter(a=>a.config.desktopId===t.id).length;if(s>0){const a=document.createElement("span");a.className="desktop-mode-overview-top-bar__tile-count",a.textContent=String(s),o.appendChild(a)}n.appendChild(o);const i=document.createElement("span");i.className="desktop-mode-overview-top-bar__tile-label",i.textContent=t.label,n.appendChild(i);const r=document.createElement("span");return r.className="desktop-mode-overview-top-bar__tile-close",r.setAttribute("role","button"),r.setAttribute("tabindex","0"),r.setAttribute("aria-label",te(O("Close %s"),t.label)),r.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>',r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),pr(e,t.id),Vo(e)}),n.appendChild(r),n.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),ar(e,t.id)}),n}function Vo(e){if(!e._overviewTopBar)return;const t=ir(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function ar(e,t){ur(e,t),ft(e)}function Yo(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=te(Wt("· %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,_(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,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"),window.setTimeout(()=>{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),_(v.OVERVIEW_EXITED,{windowId:t&&n?t.id:void 0,reason:t&&n?"select":"cancel"})},280),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&&(_(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function xu(e){return[...e._desktops]}function dr(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function Iu(e){return dr(e).id}function cr(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none"}function Xo(e){for(const t of e._stack)cr(e,t)}function lr(e){e._desktopSeq++;const t={id:`desktop-${e._desktopSeq}`,label:te(O("Desktop %d"),e._desktopSeq)};return e._desktops.push(t),_(v.DESKTOP_CREATED,{desktopId:t.id}),t}function ur(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)fr(e),Vo(e);else{Xo(e),n?.direction&&Lu(e,n.direction);const s=[...e._stack].reverse().find(i=>i.config.desktopId===t&&i.state!=="minimized");s&&e.focus(s)}_(v.DESKTOP_SWITCHED,{from:o,to:t})}function Lu(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 pr(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?fr(e):Xo(e),_(v.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function fr(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(),Xo(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=Ko(t,o,sr);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=Yo(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function Tu(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 Nu(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;_(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"}})),_(v.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function Du(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=Su(t.length,n.width,n.height),s=z(v.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=_u(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;_(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 b=f%i,m=Math.floor(f/i);p.element.style.left=`${a+b*(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"}})),_(v.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}const mr="desktop-mode-snap-to-grid";function Ou(){try{return window.localStorage.getItem(mr)==="1"}catch{return!1}}function Ru(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(mr,t?"1":"0")}catch{}_(v.ARRANGE_SNAP_CHANGED,{enabled:t})}}function Mu(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=z(v.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=Eu(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function Pu(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){hr(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=Hu(e,n),i=Ko(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=Yo(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"){Ut(e);return}const u=e.getById(d.id);if(!u){Ut(e);return}$u(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&Ut(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 $u(e,t){const n=e._splitOverviewZone;if(!n){Ut(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),_(v.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),Ut(e)}function Ut(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();hr(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 hr(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const wr=30,Wu=260;function Uu(e,t){return e<=t.left+wr?"left":e>=t.right-wr?"right":null}function Bu(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 Hu(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 Fu(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=Bu(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 Zo(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()},Wu)}function zu(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=Uu(n,o),i=e._snapPendingZone;s?(Fu(e,s),i!==s&&_(v.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(Zo(e),_(v.SNAP_ZONE_CANCELED,{windowId:t.id}))}function ju(e,t){const n=e._snapPendingZone;return n?(Zo(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),_(v.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{Pu(e,t,n)}),!0):!1}function Gu(e){e._snapPendingZone&&Zo(e)}const gr="desktop-mode-native-window-geometry",yr=64,Oe=8192;function Gn(){try{const e=window.localStorage.getItem(gr);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function br(e){try{window.localStorage.setItem(gr,JSON.stringify(e))}catch{}}function vr(e){if(!e)return null;const n=Gn()[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>Oe||s>Oe)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<=Oe&&a<=Oe;return{width:Math.round(o),height:Math.round(s),...d?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function kr(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>Oe||o>Oe)return;const s=Gn(),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||(Bt(s,e,{width:n,height:o,...typeof a=="number"&&typeof d=="number"?{x:a,y:d}:{},...r?{state:r}:{}}),Ht(s))}function _r(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>Oe||o>Oe)return;const s=Gn(),i=s[e];i&&(i.x===n&&i.y===o||(Bt(s,e,{...i,x:n,y:o}),Ht(s)))}function Er(e,t,n){if(!e)return;const o=Gn(),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>Oe||r>Oe)return;Bt(o,e,{width:i,height:r,state:t}),Ht(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;Bt(o,e,r),Ht(o);return}s.state!==t&&(Bt(o,e,{...s,state:t}),Ht(o))}function Bt(e,t,n){delete e[t],e[t]=n}function Ht(e){const t=Object.keys(e);if(t.length>yr){const n={};for(const o of t.slice(-yr))n[o]=e[o];br(n);return}br(e)}const qu=100,qn=30;class Ku{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=Ou(),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._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();const r={windowId:o.id,baseId:n,wasMinimized:i};return document.dispatchEvent(new CustomEvent("desktop-mode-window-reopened",{detail:r})),_(v.WINDOW_REOPENED,r),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*qn,i=40+this.cascadeIndex%8*qn;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*qn,r=40+this.cascadeIndex%8*qn,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",b=typeof t.initialState=="string",m=!l||!u||!b||!p||!f?vr(a):null,w=t.width??(m?Math.max(m.width,d):o),g=t.height??(m?Math.max(m.height,c):s),E=t.initialState??(m?.state==="maximized"?"maximized":void 0);let D,y;if(m&&typeof m.x=="number"&&typeof m.y=="number"){const H=Math.max(0,n.width-w-12),K=Math.max(0,n.height-g-12);D=Math.max(12,Math.min(m.x,H)),y=Math.max(12,Math.min(m.y,K))}const S=t.x??D??i,h=t.y??y??r,L=l||u||p||f||b,C=!!m,T={x:S,y:h,width:w,height:g,state:E};let I;try{I=z(v.WINDOW_GEOMETRY,T,{windowId:t.id,baseId:a,hasSavedGeometry:C,callerPinned:L,desktopRect:{width:n.width,height:n.height}})}catch(N){_(v.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:N}),typeof console<"u"&&console.error(`[desktop-mode] WINDOW_GEOMETRY filter threw for "${t.id}":`,N),I=T}const k=(N,H)=>typeof N=="number"&&Number.isFinite(N)?N:H,R=I&&typeof I=="object"?I:T,x=Math.max(k(R.width,w),d),W=Math.max(k(R.height,g),c),M=k(R.x,S),j=k(R.y,h),Y=R.state??E,oe={icon:t.icon||"dashicons-admin-generic",...t,x:M,y:j,width:x,height:W,minWidth:d,minHeight:c,...Y?{initialState:Y}:{},baseId:a,desktopId:t.desktopId||this._activeDesktopId};this.cascadeIndex++;const[se]=await Promise.all([bu(gu()),jo(Go())]),F=se.createWindow(oe);F.onFocusRequest=N=>this.focus(N),F.onClose=N=>this.remove(N),F.onMinimize=()=>{const N=this._stack.filter(H=>H.state!=="minimized");N.length>0&&this.focus(N[N.length-1])},F.onOpenAnother=N=>{const H=N.config.baseId||N.id;N.config.native&&window.wp?.desktop?.openNewWindow?.(H,{source:"open-another"})||this.openNew({id:H,baseId:H,url:N.config.url||"",title:N.config.title,icon:N.config.icon,submenu:N.config.submenu,multi:!0})},F.onOpenInNewWindow=N=>{const H=N.config.baseId||N.id;if(N.config.native&&window.wp?.desktop?.openNewWindow?.(H,{source:"open-in-new-window"}))return;const K=N.getCurrentUrl();this.openNew({id:H,baseId:H,url:K||N.config.url||"",title:N.config.title,icon:N.config.icon,submenu:N.config.submenu,multi:!0})},F.onToggleStartup=N=>{this.onToggleStartupRequested?.(N)},F.snapConfigProvider=()=>this.getSnapConfig(),F.onDragMove=(N,H)=>{zu(this,N,H)},F.onDragEnd=N=>this._snapPendingZone?ju(this,N):(Gu(this),!1),this._stack.push(F),this._desktop.appendChild(F.element),cr(this,F),F.hydrateNative(),this.focus(F);const U={windowId:F.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("desktop-mode-window-opened",{detail:U})),_(v.WINDOW_OPENED,U),F}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&&z(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(qu+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})),_(v.WINDOW_BLURRED,r)}const i={windowId:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-focused",{detail:i})),_(v.WINDOW_FOCUSED,i)}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1),this._stack.length>0&&this.focus(this._stack[this._stack.length-1]);const o={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("desktop-mode-window-closing",{detail:o})),_(v.WINDOW_CLOSING,o);const s={windowId:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-closed",{detail:s})),_(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))}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")return!1;const o=this.getFocused();return!!o&&o.id===t}getDesktops(){return xu(this)}getActiveDesktop(){return dr(this)}getActiveDesktopId(){return Iu(this)}createDesktop(){return lr(this)}switchDesktop(t,n){ur(this,t,n)}closeDesktop(t){pr(this,t)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=z(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));_(v.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=z(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 _(v.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r}),a}minimizeAll(){const t=[];for(const n of this._stack.slice())if(n.state!=="minimized")try{n.minimize(),t.push(n)}catch(o){typeof console<"u"&&console.error("[desktop-mode] minimizeAll: window.minimize() threw for",n.id,o)}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.state==="minimized")try{o.restore()}catch(s){typeof console<"u"&&console.error("[desktop-mode] restoreFrom: window.restore() threw for",o.id,s)}}toggleShowDesktop(){const t=this._stack.slice();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(){Nu(this)}tile(){Du(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){Ru(this,t)}getSnapConfig(){return Mu(this)}enterOverview(){Cu(this)}exitOverview(t,n=!1){ft(this,t,n)}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){Tu(this,t,n)}}function Vu(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 Sr(e,t){if(e._overviewActive)return;const n=Vu(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 Cr=!1;function Ar(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 Yu(e){if(Cr)return;Cr=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(Ar(document)||(n.preventDefault(),Sr(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"||Sr(e,o.direction==="prev"?"prev":"next")})}function xr(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 Ir(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,Vo(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function Xu(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function Zu(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Lr(e){return e._overviewActive?(e.exitOverview(),!0):!1}function Ju(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function Qu(e){return Ju(e)?(e.toggleShowDesktop(),!0):!1}let Tr=!1;function ep(e){Tr||(Tr=!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"||Ar(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Ir(e,"prev"):xr(e,"prev");break;case"ArrowRight":n=e._overviewActive?Ir(e,"next"):xr(e,"next");break;case"ArrowUp":n=Lr(e)||Qu(e)||Xu(e);break;case"ArrowDown":n=Lr(e)||Zu(e);break}n&&t.preventDefault()},!0))}const tp=["post_type","page","taxonomy","path","post","p"];function Nr(e){return e.replace(/\.php/g,"-php").replace(/[?&=]/g,"-").replace(/[^a-zA-Z0-9_-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")||"index"}function de(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 tp){const c=n.searchParams.get(d);c&&r.set(d,c)}const a=r.toString();return Nr(a?`${i}?${a}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),Nr(o)}function np(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function op(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 Dr(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 Or(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}const Rr=new Map,sp=new Map;function Jo(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 Mr(e,t,n,o){const s={channel:n,windowId:t},i=Jo(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=Jo(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 ip(e,t,n){const o=Jo(Rr,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function rp(e,t,n){Mr(Rr,e,t,n)}function ap(e,t,n){Mr(sp,e,t,n)}const Pr=new Set,dp=new Set,$r=new Map;function cp(e){if(!Pr.has(e)){Pr.add(e);const t=$r.get(e);if(t){$r.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)}}}dp.delete(e)&&(_(v.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("desktop-mode-window-content-loaded",{detail:{windowId:e}})))}const lp=Symbol.for("desktop-mode/window-config");function up(e){return e[lp]}function Wr(){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 pp(e){let t=Wr();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=z(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 fp(e){e.querySelector(":scope .desktop-mode-window__loading")?.remove()}function Ur(e){const t=e.querySelector(":scope .desktop-mode-window__body");if(!t||t.querySelector(":scope .desktop-mode-window__loading"))return;const o=up(e);t.appendChild(o?pp(o):Wr())}const mp=250;let Br=!1;function Hr(e){return e?document.getElementById(`wp-window-${e}`):null}function hp(){Br||(Br=!0,wp())}function wp(){q(v.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=Hr(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .desktop-mode-window__body");n&&(n.classList.add("desktop-mode-window__body--loading"),Ur(t))}),q(v.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=Hr(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")||fp(t)},mp))}),q(v.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Fr())})}function Fr(){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(),Ur(n))})}const zr="__desktopModeSharedStores";function gp(){const e=window;let t=e[zr];return t||(t=new Map,e[zr]=t),t}function re(e,t){const n=gp();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 Ft=re("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function yp(e){Ft.state.deps=e}function mt(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=Ft.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>bp(e.id)}function bp(e){const t=Ft.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function jr(e){const{deps:t,remaps:n}=Ft.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 ht(e){const{deps:t,remaps:n}=Ft.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 vp="desktop-mode.activity.";function Qo(e){return`${vp}${String(e)}`}let kp=0;const ue={publish(e,t){_(Qo(e),t)},subscribe(e,t){const n=`desktop-mode/activity-sub/${++kp}`,o=Qo(e);q(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,Ji(o,n))}},filter(e,t,...n){return z(Qo(e),t,...n)}},_p=4e3,Ep=200;function X(e){const t=ue.filter("desktop-mode/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return $t(()=>!n,()=>{o=Sp(t)}),()=>{n=!0,o&&o()}}function Sp(e){const t=Cp(),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()})),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()},Ep))};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),s=window.setTimeout(i,e.duration??_p),ue.publish("desktop-mode/toast-shown",{...e}),i}function Cp(){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 es=re("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function Ap(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=es.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Gr(e.id)}function Gr(e){const t=es.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function xp(){return es.state.entries.slice()}const Ip=re("desktop-mode/admin-link-deps",()=>({deps:null}));function Lp(e){Ip.state.deps=e}function Kn(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 Tp 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 ze(e,t,n){if(t.length!==0)throw new Tp(e,t,n)}const qr=re("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),wt=qr.state.seed,Np=qr.state.listeners;function zt(e){ze("Wallpaper",Kn(e,Xr),e);const t=wt.findIndex(n=>n.id===e.id);t>=0?wt[t]=e:wt.push(e),Vr()}function Kr(e){const t=wt.findIndex(n=>n.id===e);t>=0&&(wt.splice(t,1),Vr())}function Vr(){const e=Array.from(Np);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] wallpaper registry listener threw:",n)}}function Yr(){const e=wt.slice(),t=z(v.WALLPAPERS,e);return Array.isArray(t)?t.filter(Dp):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.wallpapers` filter returned a non-array; falling back to seed list."),e)}function ts(e){return Yr().find(t=>t.id===e)}const Xr=[{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 Dp(e){return Kn(e,Xr).length===0}const Zr="desktop-mode-os-settings",Op="custom-gradient",Jr="custom-image",ns="dark",Qr=[{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 ea(){const t=window.wp?.desktop?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return Qr;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:Qr}function ta(){const t=window.wp?.desktop?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:ns}const os=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],Rp=[{id:"classic",label:"Classic"},{id:"unified",label:"Unified"},{id:"spatial",label:"Spatial"}],J={wallpaper:ns,accent:"wp-blue",dockSize:"default",desktopLayout:"classic",dockRailRenderer:"default",customGradient:{from:"#2271b1",to:"#7c3aed",angle:135},customImage:null,libraryHdOnly:!0,ai:{enabled:!1,provider:"openai",apiKey:"",apiKeys:{},transport:"off"},heartbeatRate:60,nativePostsEnabled:!0,nativePostsHiddenColumns:[],nativePagesEnabled:!0,nativeUsersEnabled:!0,nativePluginsEnabled:!0,nativeCommentsEnabled:!0,showDesktopOnWallpaperClick:!1,showPostStatusRibbons:!0,foldersSharingEnabled:!0,itemVisibility:{},dockOrder:[],dockPromotedPositions:{}},Mp=[{id:"off",label:"Off"},{id:"sse",label:"Streaming (SSE)"}],Pp=[{id:"openai",label:"OpenAI",apiKeyLabel:"OpenAI API key",apiKeyLink:"https://platform.openai.com/api-keys"}];function $p(){const t=window.desktopModeConfig?.aiProviders;return!Array.isArray(t)||t.length===0?Pp:t.map(n=>({id:n.id,label:n.label,description:n.description,apiKeyLabel:n.api_key_label,apiKeyLink:n.api_key_link}))}function na(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const oa="X-WP-Nonce";function sa(e,t){const n=Wp();if(!n)return t;const o=Up(e);if(!o||!Bp(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(oa)?t:(i.set(oa,n),{...t??{},headers:i})}function Wp(){if(typeof window>"u")return;const t=window.desktopModeConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function Up(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 Bp(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function je(e,t,n={}){const o=window.wp?.desktop?.fetch;if(typeof o=="function")return o(e,t,n);const s=sa(e,t);return fetch(e,s)}function Hp(){const e=Fp();if(e){const t=ia(e);return is(t),t}try{const t=window.localStorage.getItem(Zr);if(t)return ia(JSON.parse(t))}catch{}return Zp()}function Fp(){const t=window.desktopModeConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}function ia(e){const t=ea();return{wallpaper:typeof e.wallpaper=="string"&&e.wallpaper!==""?e.wallpaper:ta(),accent:t.some(n=>n.id===e.accent)?e.accent:J.accent,dockSize:os.some(n=>n.id===e.dockSize)?e.dockSize:J.dockSize,desktopLayout:Rp.some(n=>n.id===e.desktopLayout)?e.desktopLayout:J.desktopLayout,dockRailRenderer:typeof e.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(e.dockRailRenderer)?e.dockRailRenderer:J.dockRailRenderer,customGradient:Qp(e.customGradient),customImage:ef(e.customImage),libraryHdOnly:typeof e.libraryHdOnly=="boolean"?e.libraryHdOnly:J.libraryHdOnly,ai:Jp(e.ai),heartbeatRate:e.heartbeatRate===15||e.heartbeatRate===30||e.heartbeatRate===45||e.heartbeatRate===60?e.heartbeatRate:J.heartbeatRate,nativePostsEnabled:typeof e.nativePostsEnabled=="boolean"?e.nativePostsEnabled:J.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(e.nativePostsHiddenColumns)?e.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):J.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof e.nativePagesEnabled=="boolean"?e.nativePagesEnabled:J.nativePagesEnabled,nativeUsersEnabled:typeof e.nativeUsersEnabled=="boolean"?e.nativeUsersEnabled:J.nativeUsersEnabled,nativePluginsEnabled:typeof e.nativePluginsEnabled=="boolean"?e.nativePluginsEnabled:J.nativePluginsEnabled,nativeCommentsEnabled:typeof e.nativeCommentsEnabled=="boolean"?e.nativeCommentsEnabled:J.nativeCommentsEnabled,showDesktopOnWallpaperClick:typeof e.showDesktopOnWallpaperClick=="boolean"?e.showDesktopOnWallpaperClick:J.showDesktopOnWallpaperClick,showPostStatusRibbons:typeof e.showPostStatusRibbons=="boolean"?e.showPostStatusRibbons:J.showPostStatusRibbons,foldersSharingEnabled:typeof e.foldersSharingEnabled=="boolean"?e.foldersSharingEnabled:J.foldersSharingEnabled,itemVisibility:zp(e.itemVisibility),dockOrder:jp(e.dockOrder),dockPromotedPositions:Gp(e.dockPromotedPositions)}}function zp(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 jp(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 Gp(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 Vn=null;const qp=250;let jt=null;function Kp(e){jt=ss(e)}function ss(e){return{...e,customGradient:{...e.customGradient},customImage:e.customImage?{...e.customImage}:null,ai:{...e.ai,apiKeys:{...e.ai.apiKeys}},nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),itemVisibility:{...e.itemVisibility},dockOrder:e.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function Vp(e,t={}){is(e),Yp(e,t.windowId)}function is(e){try{window.localStorage.setItem(Zr,JSON.stringify(e))}catch{}}function Yp(e,t){Vn!==null&&clearTimeout(Vn),t&&(rs=t),gt("pending"),Vn=setTimeout(()=>{Vn=null;const n=rs;rs=null,Xp(e,n)},qp)}let rs=null;function Xp(e,t){const n=window.desktopModeConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){gt("saved");return}gt("saving");const i=t||"desktop-mode-os-settings";je(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}`);jt=ss(e),gt("saved")}).catch(r=>{jt?(is(jt),gt("failed",r instanceof Error?r.message:String(r),ss(jt))):gt("failed",r instanceof Error?r.message:String(r))})}function gt(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 Zp(){return{...J,customGradient:{...J.customGradient},customImage:null,ai:{...J.ai}}}function Jp(e){if(!e||typeof e!="object")return{...J.ai,apiKeys:{}};const{enabled:t,provider:n,apiKey:o,apiKeys:s,transport:i}=e,r=$p(),a=typeof n=="string"&&r.some(l=>l.id===n)?n:J.ai.provider,d={};if(s&&typeof s=="object")for(const[l,u]of Object.entries(s))typeof u=="string"&&(d[l]=u.slice(0,512));const c=typeof i=="string"&&Mp.some(l=>l.id===i)?i:J.ai.transport;return{enabled:typeof t=="boolean"?t:J.ai.enabled,provider:a,apiKey:typeof o=="string"?o:J.ai.apiKey,apiKeys:d,transport:c}}function Qp(e){if(!e||typeof e!="object")return{...J.customGradient};const{from:t,to:n,angle:o}=e;return{from:na(t)?t:J.customGradient.from,to:na(n)?n:J.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:J.customGradient.angle}}function ef(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 Gt=re("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),Ge=Gt.state.registry,as=Gt.state.listeners,tf=/^[a-z0-9_-]+$/;function ra(e){if(!e||typeof e!="object")throw new TypeError("[desktop-mode] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!tf.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).`);Ge.set(e.id,e),Yn()}function nf(e){Ge.delete(e)&&Yn()}function of(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Ge.entries()))o.owner===e&&(Ge.delete(n),t++);return t>0&&Yn(),t}function sf(){return Array.from(Ge.values())}function rf(e){return as.add(e),()=>{as.delete(e)}}function af(e){Gt.state.activeId!==e&&(Gt.state.activeId=e,Yn())}function ds(){return Ge.get(Gt.state.activeId)??Ge.get("default")??Ge.values().next().value}function Yn(){const e=Array.from(as);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] dock-rail-renderer listener threw:",n)}}function cs(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 df=180,cf=220,aa=32;function da(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"&&lf(e)&&(i=!0,a(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},df)))},l=f=>{n&&f.relatedTarget instanceof Node&&n.contains(f.relatedTarget)||(i=!1,r(),u())},u=()=>{a(),s=window.setTimeout(()=>{s=null,!i&&d()},cf)},p=()=>{e.suppressTooltip(!0),n=uf(e,()=>d()),document.body.appendChild(n),yf(n),bf(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 lf(e){return e.getInstances().length>=1}function uf(e,t){const n=document.createElement("div");n.className="desktop-mode-dock-peek",n.setAttribute("role","menu"),n.setAttribute("aria-label",te(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=pf(r,e,i++,t);o.appendChild(a)}if(e.enableGhost!==!1){const r=mf(e,i,t);o.appendChild(r)}return n}function pf(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*aa}ms`);const i=e.config.title||t.item.title;s.style.setProperty("--peek-card-hue",`${cs(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",np(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=z(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",()=>{ff(t,e,s,o)}),s.addEventListener("pointerenter",()=>{t.windowManager.getFocused()!==e&&t.windowManager.focus(e)}),z(v.DOCK_PEEK_CARD_ELEMENT,s,p)}function ff(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 mf(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*aa}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=te(O("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{hf(e,n)}),o}function hf(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const wf=12,gf=["--wp-admin-theme-color","--desktop-mode-titlebar-bg","--desktop-mode-titlebar-bg-focused","--desktop-mode-titlebar-color","--desktop-mode-titlebar-color-focused"];function yf(e){const t=document.querySelector(".desktop-mode-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of gf){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function bf(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(()=>vf(e))}function vf(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=wf;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 Xn(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 kf(e){return`desktop:${e}`}function _f(e){return`dock:${e}`}function Ef(e){return e.startsWith("dock:")?e.slice(5):e.startsWith("desktop:")?e.slice(8):e}function Zn(e,t,n){const o=n[e];return o||t}function ca(e){return e==="dock"||e==="both"}function la(e){return e==="desktop"||e==="both"}function Sf(e,t,n,o){const s=n.itemVisibility,i=n.dockOrder,r=[];for(const a of e){const d=Zn(a.id,"dock",s);ca(d)&&r.push(a)}for(const a of t){const d=Zn(a.id,"desktop",s);ca(d)&&(a.window&&o&&o.has(a.window)||r.push({id:_f(a.id),title:a.title,icon:a.icon,url:a.url||"",windowId:a.window||void 0,badge:0,submenu:[],isCore:!1}))}return Af(r,i)}function Cf(e,t,n){const o=[];for(const i of e){const r=Zn(i.id,"desktop",n);la(r)&&o.push(i)}let s=0;for(const i of t){const r=Zn(i.id,"dock",n);la(r)&&o.push({id:kf(i.id),title:i.title,icon:i.icon,window:"",url:i.url||"",position:2e3+s++})}return o}function Af(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 B(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function xf(e){return!!e&&e.__wpdHtml===!0}const If="$$wpd$$",he=/\$\$wpd\$\$(\d+)\$\$/g;function Lf(e){let t=e[0];for(let n=1;n<e.length;n++)t+=`${If}${n-1}$$`+e[n];return t}const ua=new WeakMap;function pa(e){const t=ua.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=Lf(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,b=p.value,m=f[0];if(he.test(b))if(he.lastIndex=0,m==="@"){const w=he.exec(b);he.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=he.exec(b);he.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=he.exec(b);he.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 E=0,D;for(he.lastIndex=0;(D=he.exec(b))!==null;)w.push(b.slice(E,D.index)),g.push(Number(D[1])),E=D.index+D[0].length;w.push(b.slice(E)),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 b=p.textContent||"";if(!he.test(b)){he.lastIndex=0;continue}he.lastIndex=0;const m=p.parentNode;let w=0,g;const E=[],D=[];for(he.lastIndex=0;(g=he.exec(b))!==null;){g.index>w&&E.push(document.createTextNode(b.slice(w,g.index)));const y=document.createTextNode("");E.push(y),D.push({path:[...d,f+E.length-1],kind:"node",valueIndex:Number(g[1])}),w=g.index+g[0].length}w<b.length&&E.push(document.createTextNode(b.slice(w)));for(const y of E)m.insertBefore(y,p);m.removeChild(p),l+=E.length-1,o.push(...D)}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 ua.set(e,r),r}const fa=new WeakMap;function Tf(e,t){const n=fa.get(t);if(n&&n.strings===e.strings){Jn(n.parts,e.values);return}const o=pa(e.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s);for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s),Jn(i,e.values),fa.set(t,{strings:e.strings,parts:i})}function Jn(e,t){for(const n of e)if(n.kind==="node")ls(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+=ma(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 ls(e,t){if(t==null||t===!1){e.state&&(yt(e.state),e.state=null);return}if(Array.isArray(t)){Rf(e,t);return}if(xf(t)){Of(e,t);return}if(t instanceof Node){Nf(e,t);return}Df(e,ma(t))}function Nf(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&yt(n),Qn(e,[t]),e.state={shape:"node",node:t})}function Df(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&yt(n);const o=document.createTextNode(t);Qn(e,[o]),e.state={shape:"text",node:o,text:t}}function Of(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){Jn(n.parts,t.values);return}n&&yt(n);const o=pa(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);Qn(e,[s]),Jn(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function Rf(e,t){const n=e.state;if(n?.shape==="array"&&n.entries.length===t.length){for(let s=0;s<t.length;s++)ls(n.entries[s],t[s]);return}n&&yt(n);const o=[];for(const s of t){const i=document.createTextNode("");Qn(e,[i]);const r={anchor:i,state:null};ls(r,s),o.push(r)}e.state={shape:"array",entries:o}}function Qn(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function yt(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&&yt(t.state),t.anchor.remove()}function ma(e){return e==null||e===!1?"":String(e)}const Xe=class Xe 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(ha)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=Mf(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=ha(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&&Tf(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(!Xe._lightStylesAdopted.has(t)){Xe._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)}}}};Xe.props=[],Xe.styles=[],Xe.shadow=!0,Xe._lightStylesAdopted=new WeakSet;let ce=Xe;function we(e,t){customElements.get(e)||customElements.define(e,t)}function ha(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Mf(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const Pf=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function ge(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(Pf){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function $f(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(us(o));for(const r of n)t.push("tab-"+us(r));const i=e.getAttribute("label");return i&&t.push(us(i)),t.length===0?"wpd-unnamed":"wpd-"+t.filter(r=>r!=="").join("-")}function us(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function wa(e){if(e.id)return e.id;const t=$f(e);return e.id=t,t}const Wf=ge`: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 )}`,Tn=class Tn extends ce{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 B`
2 <div class="dialog" tabindex="-1">
3 ${a?B`<button
4 type="button"
5 class="close"
6 aria-label="Close"
7 @click=${()=>this._cancel()}
8 >&times;</button>`:B``}
9 ${t?B`<h2 class="title">${t}</h2>`:B``}
10 ${n?B`<p class="message">${n}</p>`:B``}
11 <div class="actions">
12 ${r?B``:B`<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 `}};Tn.props=["open","title","message","confirm-label","cancel-label","danger","hide-cancel","dismissable"],Tn.styles=[Wf],Tn.help=void 0;let ps=Tn;we("wpd-confirm-dialog",ps);function ga(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 Uf="http://localhost/";function eo(e,t){const n=typeof window<"u"&&window.location?window.location.href:Uf,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 ya(){return window.wp?.desktop??null}let Je=null;function qt(){Je&&(Je.remove(),Je=null)}function Kt(e,t){const n=ya();if(!n?.getOsSettings||!n?.updateOsSettings)return;const s={...n.getOsSettings().itemVisibility};s[e]=t,n.updateOsSettings({itemVisibility:s})}let ba=0;function va(e){qt();const t=++ba;$t(()=>t===ba,()=>Bf(e))}function Bf(e){qt();const t=Ef(e.id),n=[];if(e.surface==="dock"?(n.push({id:"hide-from-dock",label:O("Hide from dock"),icon:"dashicons-hidden",onPick:()=>Kt(t,"desktop")}),n.push({id:"show-on-desktop-too",label:O("Also show on desktop"),icon:"dashicons-desktop",onPick:()=>Kt(t,"both")})):(n.push({id:"hide-from-desktop",label:O("Hide from desktop"),icon:"dashicons-hidden",onPick:()=>Kt(t,"dock")}),n.push({id:"show-on-dock-too",label:O("Also show on dock"),icon:"dashicons-menu",onPick:()=>Kt(t,"both")})),n.push({id:"hide-everywhere",label:O("Hide everywhere"),icon:"dashicons-no",danger:!0,onPick:()=>Kt(t,"hidden")}),n.push({id:"open-settings",label:O("Apps & Icons settings…"),icon:"dashicons-admin-generic",onPick:()=>{ya()?.openOsSettings?.({tabId:"apps-icons"})}}),e.pluginFile){const d=e.pluginFile,c=e.pluginName||e.title;n.push({kind:"separator"}),n.push({id:"deactivate-plugin",label:te(O("Deactivate %s…"),c),icon:"dashicons-trash",danger:!0,onPick:()=>{Hf(d,c)}})}const o=document.createElement("wpd-context-menu");o.setAttribute("open",""),o.classList.add("desktop-mode-item-visibility-menu"),o.dataset.itemId=e.id,o.style.position="fixed",o.style.left="-9999px",o.style.top="-9999px",o.style.visibility="hidden",o.style.zIndex="1000000";const s=new Map;for(const d of n){if(d.kind==="separator"){const l=document.createElement("hr");l.style.cssText="border: 0; border-top: 1px solid var( --wpd-context-menu-separator-color, rgba(255,255,255,0.12) ); margin: 4px 6px;",o.appendChild(l);continue}s.set(d.id,d);const c=document.createElement("wpd-context-menu-option");c.dataset.menuItemId=d.id,c.setAttribute("value",d.id),d.icon&&c.setAttribute("icon",d.icon),d.danger&&c.setAttribute("danger",""),c.textContent=d.label,o.appendChild(c)}o.addEventListener("wpd-context-menu-pick",d=>{const c=d.detail,l=c?.id||c?.value||"",u=s.get(l);qt();try{u?.onPick()}catch{}}),document.body.appendChild(o),Je=o,requestAnimationFrame(()=>{if(o!==Je)return;const d=o.getBoundingClientRect(),c=8;let l=e.x,u;e.surface==="dock"?u=Math.max(c,e.y-d.height-c):(u=e.y,u+d.height+c>window.innerHeight&&(u=Math.max(c,e.y-d.height))),l+d.width+c>window.innerWidth&&(l=Math.max(c,e.x-d.width)),o.style.left=`${l}px`,o.style.top=`${u}px`,o.style.visibility=""});const r=d=>{Je&&(Je.contains(d.target)||(qt(),document.removeEventListener("mousedown",r,!0),document.removeEventListener("keydown",a,!0)))},a=d=>{d.key==="Escape"&&(qt(),document.removeEventListener("mousedown",r,!0),document.removeEventListener("keydown",a,!0))};document.addEventListener("mousedown",r,!0),document.addEventListener("keydown",a,!0)}async function Hf(e,t){if(!await ga({title:te(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=eo(s,`wp/v2/plugins/${a}`);try{const p=await je(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){X({message:te(O("Could not deactivate %s."),t),duration:4e3}),console.error("[desktop-mode] deactivate plugin failed",p);return}const c=Ff(e),l=c.length>0?te(O("%1$s deactivated. Closed %2$d window(s)."),t,c.length):te(O("%s deactivated."),t);X({message:l,duration:3e3}),window.wp?.desktop?.refreshMenu?.()}function Ff(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 be=class be{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/${++be.instanceCounter}`,this.container.setAttribute("data-desktop-mode-dock-placement",i),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.container.querySelectorAll(".desktop-mode-dock__separator--group").forEach(i=>i.remove()),this.itemElements.clear(),this.items=t;const n=this.buildHookContextBase();_(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.systemSeparator?this.container.insertBefore(d,this.systemSeparator):this.container.appendChild(d)}o=!0}const r=this.createItemButton(i);this.itemElements.set(i.id,r),this.systemSeparator?this.container.insertBefore(r,this.systemSeparator):this.container.appendChild(r),s++;const a=this.badgeOverrides.get(i.id);if(a!==void 0){const d=r.querySelector(".desktop-mode-dock__item-primary");ka(d??r,a)}_(v.DOCK_TILE_RENDERED,{...n,item:i,isSystem:!1,el:r})}this.updateActiveStates(),_(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),_(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");ka(i??o,s),ue.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.container.appendChild(this.systemSeparator));const n=this.createSystemItemButton(t);this.systemItemElements.set(t.id,n),this.container.appendChild(n),this.updateActiveStates(),_(v.DOCK_TILE_RENDERED,{...this.buildHookContextBase(),item:t,isSystem:!0,el:n})}render(){if(be.activeDragReset){const o=be.activeDragReset;be.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.container.innerHTML="";const t=this.buildHookContextBase();_(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.container.childElementCount>0){const i=document.createElement("div");i.className="desktop-mode-dock__separator desktop-mode-dock__separator--group",i.setAttribute("aria-hidden","true"),this.container.appendChild(i)}n=!0}const s=this.createItemButton(o);this.itemElements.set(o.id,s),this.container.appendChild(s),_(v.DOCK_TILE_RENDERED,{...t,item:o,isSystem:!1,el:s})}_(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=z(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=da({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:""},getInstances:()=>{const d=this.windowManager.getById(t.id);return d?[d]:[]},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),z(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=z(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",te(Wt("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.addEventListener("contextmenu",l=>{l.preventDefault(),va({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=da({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>{if(t.multi)return this.windowManager.getAllByBaseId(d);const l=this.windowManager.getById(d)||this.windowManager.getById(t.id);return l?[l]:[]},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),z(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",E),document.removeEventListener("pointerup",h),document.removeEventListener("pointercancel",L),document.removeEventListener("keydown",C,!0),window.removeEventListener("blur",T),document.removeEventListener("visibilitychange",I),l=-1,u=null},b=k=>!!k&&k instanceof HTMLElement&&k.classList.contains("desktop-mode-dock__item")&&!k.classList.contains("desktop-mode-dock__item--system")&&!!k.dataset.menuSlug,m=k=>{for(const R of Array.from(this.container.children))R instanceof HTMLElement&&R!==t&&b(R)&&k(R)},w=()=>{const k=[];for(const R of Array.from(this.container.children))b(R)&&k.push(R.dataset.menuSlug);return k},g=k=>{m(R=>{const x=k.get(R);if(!x)return;const W=R.getBoundingClientRect(),M=x.left-W.left,j=x.top-W.top;if(Math.abs(M)<.5&&Math.abs(j)<.5)return;R.style.transition="none",R.style.transform=`translate(${M}px, ${j}px)`,R.offsetHeight,R.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",R.style.transform="";const Y=()=>{R.style.transition="",R.style.transform="",R.removeEventListener("transitionend",Y)};R.addEventListener("transitionend",Y)})},E=k=>{if(l!==-1&&k.pointerId!==l)return;if(!i){const F=k.clientX-r,U=k.clientY-a;if(F*F+U*U<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 R=k.clientX-r,x=k.clientY-a;t.style.transform=`translate(${R}px, ${x}px)`;const M=document.elementFromPoint(k.clientX,k.clientY)?.closest(".desktop-mode-dock__item");if(!M||M===t||!b(M))return;const j=M.getBoundingClientRect();let Y;this.orientation==="bottom"?Y=k.clientX<j.left+j.width/2:Y=k.clientY<j.top+j.height/2;const oe=new Map;m(F=>{oe.set(F,F.getBoundingClientRect())});let se=!1;if(Y?M!==t.nextSibling&&(this.container.insertBefore(t,M),se=!0):M.nextSibling!==t&&(this.container.insertBefore(t,M.nextSibling),se=!0),se){t.style.transform="";const F=t.getBoundingClientRect();r=F.left+F.width/2,a=F.top+F.height/2,t.style.transform=`translate(${k.clientX-r}px, ${k.clientY-a}px)`,g(oe)}},D=()=>{t.classList.remove("desktop-mode-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",E),document.removeEventListener("pointerup",h),document.removeEventListener("pointercancel",L),document.removeEventListener("keydown",C,!0),window.removeEventListener("blur",T),document.removeEventListener("visibilitychange",I),l=-1,u=null,i=!1,be.activeDragReset===f&&(be.activeDragReset=null)},y=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const k=()=>{t.style.transition="",t.removeEventListener("transitionend",k)};t.addEventListener("transitionend",k)},S=k=>{const R=window.wp?.desktop;if(!R?.getOsSettings||!R?.updateOsSettings)return;const x=R.getOsSettings().dockOrder,W=new Set(k),M=[];let j=!1;for(const Y of x){if(W.has(Y)){j||(M.push(...k),j=!0);continue}M.push(Y)}j||M.push(...k),R.updateOsSettings({dockOrder:M})},h=k=>{if(l!==-1&&k.pointerId!==l)return;if(!i){D();return}p=!0;const R=w();y(),D(),R.length===d.length&&R.every((W,M)=>W===d[M])||S(R),setTimeout(()=>{p=!1},200)},L=k=>{if(!(k&&l!==-1&&k.pointerId!==l)){if(i&&c!==void 0){const R=new Map;m(x=>{R.set(x,x.getBoundingClientRect())}),this.container.insertBefore(t,c),g(R)}y(),D()}},C=k=>{k.key==="Escape"&&L()},T=()=>L(),I=()=>{document.visibilityState!=="visible"&&L()};t.addEventListener("pointerdown",k=>{if(k.button===0){if(be.activeDragReset){const R=be.activeDragReset;be.activeDragReset=null,R()}(i||l!==-1)&&f(),r=k.clientX,a=k.clientY,l=k.pointerId,i=!1,be.activeDragReset=f,document.addEventListener("pointermove",E),document.addEventListener("pointerup",h),document.addEventListener("pointercancel",L),document.addEventListener("keydown",C,!0),window.addEventListener("blur",T),document.addEventListener("visibilitychange",I)}}),t.addEventListener("click",k=>{p&&(k.preventDefault(),k.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=cs(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=z(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(Xn(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(Xn(t.url)||ht(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(Xn(t.url))return;const n=window.wp?.desktop?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=jr(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 de(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:jr(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)}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);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=i=>(i.config.desktopId||o)===o;for(const i of this.items){const r=this.itemElements.get(i.id);if(!r)continue;const a=this.resolveItemBaseId(i),d=i.multi?this.windowManager.getAllByBaseId(a).filter(s):[],c=this.windowManager.getById(a),l=!i.multi&&!!c&&s(c),u=i.multi?d.length>0:l,p=n===a&&!!t&&s(t);r.classList.toggle("desktop-mode-dock__item--active",u),r.classList.toggle("desktop-mode-dock__item--focused",p)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const a=i.isOpen?i.isOpen():!1,d=!!t&&t.id===i.id;r.classList.toggle("desktop-mode-dock__item--active",a),r.classList.toggle("desktop-mode-dock__item--focused",d)}}};be.instanceCounter=0,be.activeDragReset=null;let to=be;function ka(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",te(Wt("%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",te(Wt("%d notification","%d notifications",t),t)),e.appendChild(s)}const _a=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),fs={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 to(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[_a]: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 no(e){if(!e)return null;const n=e[_a];return n instanceof to?n:null}function zf(){ra(fs)}function Ea(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}function jf(e){zt({id:Op,label:O("Custom gradient"),type:"css",preview:Ea(e.state),resolveValue:()=>Ea(e.state)})}function Gf(e){if(!e.customImage){Kr(Jr);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`;zt({id:Jr,label:O("Custom image"),type:"css",value:n,preview:n})}let oo=null;function qf(e){return window.desktopModeRenderOsSettingsPanel?Promise.resolve(window.desktopModeRenderOsSettingsPanel):oo||(oo=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)}),oo)}class Kf{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=Hp(),Kp(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))}),jf(this),Gf(this.state)}getOsSettingsSnapshot(){return{wallpaper:this.state.wallpaper,accent:this.state.accent,dockSize:this.state.dockSize,desktopLayout:this.state.desktopLayout,dockRailRenderer:this.state.dockRailRenderer,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,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;const n=ts(this.state.wallpaper)||ts(ta())||ts(ns)||Yr()[0];n&&this.layer.apply(n);const o=ea(),s=o.find(a=>a.id===this.state.accent)??o[0],i=os.find(a=>a.id===this.state.dockSize)??os[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),af(this.state.dockRailRenderer)}save(t={}){if(Vp(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)}}}renderPanel(t){this._lastRenderedBody=t;const n=window.desktopModeRenderOsSettingsPanel;if(n){n(this,t);return}qf(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 Vf="desktop-mode-exit";function Yf(){return{id:Vf,title:O("Exit Desktop Mode"),icon:"dashicons-exit",onOpen:()=>{Xf()}}}async function Xf(){const e=window.desktopModeAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Sa(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{}Sa(o)}function Sa(e){try{window.top.location.href=e}catch{window.location.href=e}}const Zf={userId:null,requestedAt:0,tabRequested:!1};let so=null;function Jf(){if(so)return so;const t=window.wp?.desktop?.createSharedStore;return typeof t!="function"?null:(so=t("desktop-mode/user-edit/target",()=>({...Zf})),so)}function Qf(e){const t=Jf();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 ms=new Map;function ke(e,t){const n=ms.get(e);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-desktop-mode-vendor="${em(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&&io(t.translations);for(const c of t?.l10n??[])io(c);for(const c of t?.before??[])io(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??[])io(c);s()},{once:!0}),d.addEventListener("error",()=>{ms.delete(e),d.remove(),i(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(d)});return ms.set(e,o),o}function io(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.desktopModeVendorInline="1",document.head.appendChild(t)}function em(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}const ro=new Map;function Ca(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}ro.set(e.id,e)}function tm(){return Array.from(ro.keys())}async function Aa(e){if(!e||e.length===0)return;const t=e.filter(n=>!ro.has(n));if(t.length>0)throw new Error(`[desktop-mode] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${tm().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=ro.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():ke(o.url)}))}function xa(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:nm(),visible:!document.hidden}}function nm(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class Ia{constructor(t,n){this.generation=0,this.active=null,this.boundVisibilityChange=()=>{this.active&&_(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,_(v.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){_(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(xa(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=xa(t.id,this.pluginUrl);_(v.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?Aa(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},_(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(om(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="",_(v.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),_(v.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[desktop-mode] Wallpaper "${t}" failed to mount:`,n)}}function om(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}function sm(e){const{osSettings:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await ke(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter})}catch(l){_(v.SHELL_ERROR,{scope:"wallpaper-script-load",id:c.id,error:l})}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},a=async c=>{if(n.has(c.id))return;const l=r(c);if(l){zt(l),n.add(c.id),t.apply();return}await s(c);const u=i(c.id);if(!u){_(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{zt(u)}catch(p){_(v.SHELL_ERROR,{scope:"wallpaper-register",id:c.id,error:p});return}n.add(c.id),t.apply()},d=c=>{n.has(c)&&(Kr(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 La=/^[a-z0-9_/-]+$/,Ta=re("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),Qe=Ta.state.registry,im=Ta.state.listeners;function ao(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)"):La.test(n)||t.push(`slug (must match ${La} — 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)")),ze("Command",t,e),Qe.set(n,{...e,slug:n}),hs()}function Na(e){Qe.delete(e.toLowerCase())&&hs()}function co(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Qe.entries()))o.owner===e&&(Qe.delete(n),t++);return t>0&&hs(),t}function Da(){return Array.from(Qe.values())}function rm(){const e=[];for(const t of Qe.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function am(e){return Qe.get(e.toLowerCase())??null}function hs(){const e=Array.from(im);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] command-registry listener threw:",n)}}function dm(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(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 Da())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))Na(l);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Oa=re("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),Vt=Oa.state.registry,cm=Oa.state.listeners;function Ra(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}Vt.set(t,{...e,id:t}),ws()}function Ma(e){Vt.delete(e.toLowerCase())&&ws()}function lm(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Vt.entries()))o.owner===e&&(Vt.delete(n),t++);return t>0&&ws(),t}function Pa(){return Array.from(Vt.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function ws(){const e=Array.from(cm);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] settings-tab-registry listener threw:",n)}}function um(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(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=>{lm(r);const a=n.get(r);if(a){const d=new Set(Pa().map(c=>c.id));for(const c of a)d.has(c)&&Ma(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 $a=re("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),Yt=$a.state.registry,pm=$a.state.listeners,Wa=/^[a-z0-9_/-]+$/;function Ua(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Wa.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Wa} — 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)")),ze("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();Yt.set(n,{...e,id:n}),gs()}function fm(e){Yt.delete(e.toLowerCase())&&gs()}function mm(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&&gs(),t}function hm(){return Array.from(Yt.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function gs(){const e=Array.from(pm);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] title-bar-button registry listener threw:",n)}}function wm(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){_(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)||(mm(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function gm(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){_(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)||(of(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Ba=re("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),Xt=Ba.state.registry,ym=Ba.state.listeners,Ha=/^[a-z0-9_/-]+$/;function Fa(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)"):Ha.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Ha} — 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)")}ze("WindowTheme",t,e);const n=e.id.trim().toLowerCase();Xt.set(n,{...e,id:n}),ys()}function za(e){Xt.delete(e.toLowerCase())&&ys()}function bm(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Xt.entries()))o.owner===e&&(Xt.delete(n),t++);return t>0&&ys(),t}function ja(){return Array.from(Xt.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function ys(){const e=Array.from(ym);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-theme registry listener threw:",n)}}function vm(){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 ke(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(c){_(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 ja())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{Fa({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){_(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)za(f),o.delete(f);bm(u),e.delete(u)}a(c);for(const u of d)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const Ga=re("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),Zt=Ga.state.registry,km=Ga.state.listeners,qa=/^[a-z0-9_/-]+$/;function Jt(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):qa.test(e.id.trim().toLowerCase())||t.push(`id (must match ${qa} — 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")')),ze("WindowControl",t,e);const n=e.id.trim().toLowerCase();Zt.set(n,{...e,id:n}),bs()}function Ka(e){Zt.delete(e.toLowerCase())&&bs()}function _m(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Zt.entries()))o.owner===e&&(Zt.delete(n),t++);return t>0&&bs(),t}function Va(){return Array.from(Zt.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function bs(){const e=Array.from(km);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-control registry listener threw:",n)}}function Em(){Jt({id:"core/minimize",label:O("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),Jt({id:"core/maximize",label:O("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),Jt({id:"core/focus-tab",label:O("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),Jt({id:"core/close",label:O("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function Sm(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(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 Va())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))Ka(l);_m(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Ya=re("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),Qt=Ya.state.registry,Cm=Ya.state.listeners,Xa=/^[a-z0-9_/-]+$/,Za=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Ja(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Xa.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Xa} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):Za.has(e.slot)||t.push(`slot (must be one of ${Array.from(Za).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),ze("WindowSlot",t,e);const n=e.id.trim().toLowerCase();Qt.set(n,{...e,id:n}),ks()}function vs(e){Qt.delete(e.toLowerCase())&&ks()}function Am(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Qt.entries()))o.owner===e&&(Qt.delete(n),t++);return t>0&&ks(),t}function Qa(){return Array.from(Qt.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function ks(){const e=Array.from(Cm);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-slot registry listener threw:",n)}}function xm(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(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 Qa())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))vs(l);Am(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Im="desktop-mode-notice-dismissed";function Lm(){const t=window.wp?.desktop?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function ed(){return`${Im}:${Lm()}`}function _s(){try{const e=window.localStorage.getItem(ed());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function td(e){try{window.localStorage.setItem(ed(),JSON.stringify(e))}catch{}}function Tm(e){return e?_s()[e]===!0:!1}function nd(e){if(!e)return;const t=_s();t[e]=!0,td(t)}function od(e){if(!e)return;const t=_s();t[e]&&(delete t[e],td(t))}const Nm=ge`: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 ) )}`,Nn=class Nn extends ce{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&Tm(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&nd(t),this.emit("wpd-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&od(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return B`
29 <span
30 class="wpd-notice__icon dashicons ${t??""}"
31 ?hidden=${!t}
32 aria-hidden="true"
33 ></span>
34 <span class="wpd-notice__label"><slot></slot></span>
35 <button
36 type="button"
37 class="wpd-notice__close"
38 ?hidden=${!n}
39 aria-label=${O("Dismiss notice")}
40 @click=${o=>this._onDismiss(o)}
41 >
42 <svg viewBox="0 0 14 14" aria-hidden="true">
43 <path
44 d="M3 3 L11 11 M11 3 L3 11"
45 stroke="currentColor"
46 stroke-width="1.6"
47 stroke-linecap="round"
48 fill="none"
49 ></path>
50 </svg>
51 </button>
52 `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};Nn.props=["tone","notDismissible","icon","noticeId"],Nn.styles=[Nm],Nn.help=void 0;let Es=Nn;we("wpd-notice",Es);const en=re("desktop-mode/window-notices",()=>({entries:new Map})),Dm=/^[a-z0-9_/-]+$/;function sd(e){return`desktop-mode-notice/${e.toLowerCase()}`}function Om(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 id(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!Dm.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};en.state.entries.set(t,n);const o=sd(t);return Ja({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=en.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=en.state.entries.get(t);i&&s.appendChild(Om(i))}}),()=>Ss(t)}function Ss(e){const t=String(e??"").trim().toLowerCase();t&&en.state.entries.delete(t)&&vs(sd(t))}function rd(){return Array.from(en.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 Rm(e){const t=String(e??"").trim().toLowerCase();t&&nd(t)}function Mm(e){const t=String(e??"").trim().toLowerCase();t&&od(t)}function Pm(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 ad(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),id({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:Pm(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of rd())n.owner==="__server__"&&(t.has(n.id)||Ss(n.id))}const dd=re("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),tn=dd.state.registry,$m=dd.state.listeners,cd=/^[a-z0-9_/-]+$/;function Wm(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):cd.test(e.id.trim().toLowerCase())||t.push(`id (must match ${cd} — 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)")),ze("WindowChrome",t,e);const n=e.id.trim().toLowerCase();tn.set(n,{...e,id:n}),Cs()}function ld(e){tn.delete(e.toLowerCase())&&Cs()}function Um(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(tn.entries()))o.owner===e&&(tn.delete(n),t++);return t>0&&Cs(),t}function ud(){return Array.from(tn.values()).sort((e,t)=>e.id.localeCompare(t.id))}function Cs(){const e=Array.from($m);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-chrome registry listener threw:",n)}}function Bm(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(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 ud())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))ld(l);Um(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const As=window.location.origin;let Hm=0;const nn=new Map,bt=new Map,on=new Map;function Fm(e,t){return on.set(e,t),()=>{on.get(e)===t&&on.delete(e)}}function zm(){return`desktop-mode-conn-${++Hm}`}function jm(e){const t=(a,d)=>{try{a.contentWindow?.postMessage(d,As)}catch(c){typeof console<"u"&&console.error("[desktop-mode] connection: postMessage failed",c)}},n=(a,d={})=>{const c=zm(),l=Array.isArray(d.topics)?[...d.topics]:[],u=new Map,p=[];let f=!1,b=!1;const m=()=>{const h=on.get(a);return h||(e.getById(a)?.iframe??null)},w=()=>{if(m())return!1;const h=e.getById(a);return!!h&&h.config?.native===!0},g=[],E=()=>{const h=m();if(h)for(;p.length;){const L=p.shift();t(h,{type:"desktop-mode-bridge-publish",connectionId:c,topic:L.topic,payload:L.payload})}},D={id:c,target:a,isOpen:()=>f,subscribe(h,L){const C=L;if(w()){const I=ip(a,h,(k,R)=>{_(v.CONNECTION_MESSAGE,{connectionId:c,topic:R.channel,direction:"in"});try{C(k,{topic:R.channel})}catch(x){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",x)}});return g.push(I),I}let T=u.get(h);return T||(T=new Set,u.set(h,T)),T.add(C),()=>{T?.delete(C)}},send(h,L){if(b)return;if(_(v.CONNECTION_MESSAGE,{connectionId:c,topic:h,direction:"out"}),w()){ap(a,h,L);return}if(!f){p.push({topic:h,payload:L});return}const C=m();C&&t(C,{type:"desktop-mode-bridge-publish",connectionId:c,topic:h,payload:L})},disconnect(){D._destroy("disconnect")},_targetWindow:m,_handleIframeMessage(h){if(!h||typeof h!="object")return;const L=h;if(L.type==="desktop-mode-bridge-handshake-ack"){if(f)return;f=!0,_(v.CONNECTION_OPENED,{connectionId:c,targetWindowId:a,topics:l});try{d.onOpen?.()}catch(C){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",C)}E();return}if(L.type==="desktop-mode-bridge-publish"){const C=h,T=typeof C.topic=="string"?C.topic:"";if(!T)return;_(v.CONNECTION_MESSAGE,{connectionId:c,topic:T,direction:"in"});const I=u.get(T);if(I)for(const R of Array.from(I))try{R(C.payload,{topic:T})}catch(x){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",x)}const k=u.get("*");if(k)for(const R of Array.from(k))try{R(C.payload,{topic:T})}catch(x){typeof console<"u"&&console.error("[desktop-mode] connection wildcard subscriber threw:",x)}return}L.type==="desktop-mode-bridge-disconnect"&&D._destroy("disconnect")},_destroy(h){if(b)return;b=!0;const L=f;f=!1,nn.delete(c);const C=bt.get(a);C&&(C.delete(c),C.size===0&&bt.delete(a));for(const T of g.splice(0))try{T()}catch{}if(L){const T=m();T&&t(T,{type:"desktop-mode-bridge-disconnect",connectionId:c})}_(v.CONNECTION_CLOSED,{connectionId:c,reason:h});try{d.onClose?.(h)}catch(T){typeof console<"u"&&console.error("[desktop-mode] connection.onClose threw:",T)}}};nn.set(c,D);let y=bt.get(a);if(y||(y=new Set,bt.set(a,y)),y.add(c),w())return Promise.resolve().then(()=>{if(!(b||f)){f=!0,_(v.CONNECTION_OPENED,{connectionId:c,targetWindowId:a,topics:l});try{d.onOpen?.()}catch(h){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",h)}}}),D;const S=m();return S&&t(S,{type:"desktop-mode-bridge-handshake",connectionId:c,topics:l}),D},o=(a,d)=>{if(!a||typeof a!="object")return;const c=a;if(typeof c.type!="string"||!c.type.startsWith("desktop-mode-bridge-"))return;if(c.type==="desktop-mode-bridge-connection-request"&&typeof c.requestId=="string"&&typeof d=="string"&&d!==""){s(d,c.requestId,Array.isArray(c.topics)?c.topics:[]);return}if(typeof c.connectionId!="string")return;nn.get(c.connectionId)?._handleIframeMessage(a)},s=(a,d,c)=>{const u=on.get(a)??e.getById(a)?.iframe??null;if(!u)return;const p=z(v.IFRAME_CONNECTION_REQUEST,!0,{windowId:a,requestId:d,topics:c.slice()});if(p===!1){try{u.contentWindow?.postMessage({type:"desktop-mode-bridge-connection-ack",requestId:d,accepted:!1,reason:"rejected"},As)}catch{}return}const f=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:c,b=n(a,{topics:f});try{u.contentWindow?.postMessage({type:"desktop-mode-bridge-connection-ack",requestId:d,accepted:!0,connectionId:b.id},As)}catch{}};return{connect:n,routeIncomingFromIframe:o,onIframeReady:a=>{const d=bt.get(a);if(d)for(const c of Array.from(d)){const l=nn.get(c);if(!l||l.isOpen())continue;const u=l._targetWindow();u&&t(u,{type:"desktop-mode-bridge-handshake",connectionId:l.id,topics:[]})}},onWindowClosed:a=>{const d=bt.get(a);if(d)for(const c of Array.from(d))nn.get(c)?._destroy("window-closed")}}}const Gm={};function qm(...e){(typeof{url:zo&&zo.tagName.toUpperCase()==="SCRIPT"&&zo.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&Gm?"production":void 0)!=="production"&&console.log(...e)}const Km="iframe:";function xs(e){return Km+e}function pd(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function Vm(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}class Ym{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"&&(co(xs(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{}co(xs(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){qm("[wpd-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=xs(t);co(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=Vm(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?Or(s.iconSvg):"",a={slug:i,label:s.label,icon:pd(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,pd(s)):this.runProxy(t,s.name)};try{ao(a)}catch(d){console.error("[desktop-mode] iframe-bridge: dropping bad command",a,d)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),ht(t))return;const r=de(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 fd="global",Xm=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,Zm=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,Jm=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,Qm=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,eh=/getSiteEditorPage\s*\(|site-editor\.php/,th=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function nh(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 oh{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 E=m[g];w[g]=E&&E.name?E.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 E=g&&Array.isArray(g.commands)?g.commands:[],D=a(()=>u(E),[E]);return i(()=>{l.perLoader[w.name]=E,p()},[D]),i(()=>()=>{delete l.perLoader[w.name],p()},[]),null},b=()=>{const m=d(S=>{const h=S("core/commands");return!h||typeof h.getCommandLoaders!="function"?[]:[...h.getCommandLoaders(!1)||[],...h.getCommandLoaders(!0)||[]]},[]),w=d(S=>{const h=S("core/commands");return!h||typeof h.getCommands!="function"?[]:[...h.getCommands(!1)||[],...h.getCommands(!0)||[]]},[]),g=a(()=>Array.isArray(m)?m.map(S=>S&&S.name||""):[],[m]),E=g.join("|");i(()=>{l.loadersList=g,p()},[E]);const D=a(()=>u(Array.isArray(w)?w:[]),[w]);if(i(()=>{l.statics=Array.isArray(w)?w:[],p()},[D]),!Array.isArray(m)||m.length===0)return null;const y=[];for(const S of m)!S||typeof S.hook!="function"||y.push(s(f,{key:S.name,loader:S}));return s(n.Fragment||"div",null,y)};try{this.root=n.createRoot(c),this.root.render(s(b))}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||""}
53 `;if(s!==this.lastFingerprint){this.lastFingerprint=s,co(fd);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!==""?Or(i.iconSvg):void 0,owner:fd,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{ao(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=nh(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(Xm)||i.match(Zm)||i.match(Jm);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(Qm.test(i)){const d=eh.test(i)?n.name.match(th):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(),ht(t))return;const r=de(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=de(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 vt=[];function Is(e){ze("Widget",Kn(e,hd),e);const t=vt.findIndex(n=>n.id===e.id);t>=0?vt[t]=e:vt.push(e)}function sh(e){const t=vt.findIndex(n=>n.id===e);t>=0&&vt.splice(t,1)}function md(){const e=vt.slice(),t=z(v.WIDGETS,e);return Array.isArray(t)?t.filter(ih):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.widgets` filter returned a non-array; falling back to seed list."),e)}function sn(e){return md().find(t=>t.id===e)}const hd=[{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 ih(e){return Kn(e,hd).length===0}let Re=null;function rh(e){if(Re)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),gd(o,e),document.body.appendChild(t),ah(t,e.anchor);const s=a=>{const d=a.target;d&&(t.contains(d)||e.anchor.contains(d)||wd())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&wd()};document.addEventListener("keydown",i),Re={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function lo(){if(!Re)return;const e=Re.panel.querySelector(".desktop-mode-widget-picker__list");e&&gd(e,Re.options)}function wd(){Re&&(document.removeEventListener("pointerdown",Re.onOutsidePointerDown,!0),document.removeEventListener("keydown",Re.onKeyDown),Re.panel.remove(),Re=null)}function gd(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=te(O("%s (already added)"),s.label):a=te(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 ah(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 Ls="desktop-mode-widgets__card--floating",dh="desktop-mode-widgets__card--movable",ch="desktop-mode-widgets__card--resizable",yd="desktop-mode-widgets__card--dragging",bd="desktop-mode-widgets__card--resizing",lh=160,uh=80,ph=280,fh=180,uo=20,vd=5,mh=vd*vd,hh='input, textarea, select, button, a, [contenteditable="true"]';function wh(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(dh),i&&o.classList.add(ch),s?o.appendChild(gh(e,n.onRemove,n.onRedock)):o.appendChild(bh(e,n.onRemove));const r=document.createElement("div");r.className="desktop-mode-widgets__card-body",o.appendChild(r);let a=!1;t.geometry&&(Ts(o,t.geometry),o.classList.add(Ls),a=!0);const d=[];if(i)for(const l of _h()){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(kh(o,u,l,e,t,n,()=>a))}let c=null;if(s){const l=o.querySelector(".desktop-mode-widgets__chrome");l&&(c=vh(o,l,e,t,n,u=>{a=u}))}return{card:o,body:r,dispose:()=>{for(const l of d)try{l()}catch{}if(c)try{c()}catch{}o.remove()}}}function gh(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(yh(e,n));const r=kd(e,t);return o.appendChild(r),o}function yh(e,t){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-redock",n.setAttribute("aria-label",te(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 bh(e,t){const n=kd(e,t);return n.classList.add("desktop-mode-widgets__card-close--corner"),n}function kd(e,t){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-close",n.setAttribute("aria-label",te(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 vh(e,t,n,o,s,i){let r=null,a=0,d=0,c=0,l=0,u=!1;const p=w=>{if(w.button!==0)return;const g=w.target;g&&g.closest(hh)||(w.preventDefault(),r=w.pointerId,a=w.clientX,d=w.clientY,u=!1,c=parseFloat(e.style.left)||0,l=parseFloat(e.style.top)||0,t.setPointerCapture(r))},f=()=>{if(!e.classList.contains(Ls)){const w=o.floatingParent.getBoundingClientRect(),g=e.getBoundingClientRect(),E={x:g.left-w.left,y:g.top-w.top,width:g.width||n.defaultWidth||ph,height:g.height||n.defaultHeight||fh};Ts(e,E),e.classList.add(Ls),i(!0),s.onLiberate(E),c=parseFloat(e.style.left)||0,l=parseFloat(e.style.top)||0}e.classList.add(yd)},b=w=>{if(r===null||w.pointerId!==r)return;const g=w.clientX-a,E=w.clientY-d;if(!u){if(g*g+E*E<mh)return;u=!0,f()}const D=Sh(c+g,l+E,e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${D.x}px`,e.style.top=`${D.y}px`},m=w=>{if(!(r===null||w.pointerId!==r)){try{t.releasePointerCapture(r)}catch{}r=null,u&&(u=!1,e.classList.remove(yd),s.onGeometryChanged(_d(e)))}};return t.addEventListener("pointerdown",p),t.addEventListener("pointermove",b),t.addEventListener("pointerup",m),t.addEventListener("pointercancel",m),()=>{t.removeEventListener("pointerdown",p),t.removeEventListener("pointermove",b),t.removeEventListener("pointerup",m),t.removeEventListener("pointercancel",m)}}function kh(e,t,n,o,s,i,r){let a=null,d=0,c=0,l=0,u=0,p=0,f=0;const b=g=>{if(g.button!==0||!r()&&!Eh(n))return;g.preventDefault(),g.stopPropagation(),a=g.pointerId,d=g.clientX,c=g.clientY;const E=e.getBoundingClientRect(),D=s.floatingParent.getBoundingClientRect();l=E.left-D.left,u=E.top-D.top,p=E.width,f=E.height,t.setPointerCapture(a),e.classList.add(bd)},m=g=>{if(a===null||g.pointerId!==a)return;const E=g.clientX-d,D=g.clientY-c,y=Ch(n,E,D,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(bd),i.onGeometryChanged(_d(e))}};return t.addEventListener("pointerdown",b),t.addEventListener("pointermove",m),t.addEventListener("pointerup",w),t.addEventListener("pointercancel",w),()=>{t.removeEventListener("pointerdown",b),t.removeEventListener("pointermove",m),t.removeEventListener("pointerup",w),t.removeEventListener("pointercancel",w)}}function _h(){return["n","e","s","w","ne","nw","se","sw"]}function Eh(e){return e==="s"}function Ts(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 _d(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function Sh(e,t,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,a=Math.max(0,i-n-uo),d=Math.max(0,r-o-uo);return{x:Math.min(Math.max(uo,e),a),y:Math.min(Math.max(uo,t),d)}}function Ch(e,t,n,o,s,i,r,a,d,c){const l=a.minWidth??lh,u=a.minHeight??uh,p=a.maxWidth??1/0,f=a.maxHeight??1/0,b=d.clientWidth||d.getBoundingClientRect().width,m=d.clientHeight||d.getBoundingClientRect().height;let w=o,g=s,E=i,D=r;if((e==="e"||e==="ne"||e==="se")&&(E=po(i+t,l,Math.min(p,b-o))),e==="w"||e==="nw"||e==="sw"){const y=po(i-t,l,Math.min(p,o+i));w=o+(i-y),E=y}if((e==="s"||e==="se"||e==="sw")&&(D=po(r+n,u,Math.min(f,m-s))),e==="n"||e==="ne"||e==="nw"){const y=po(r-n,u,Math.min(f,s+r));g=s+(r-y),D=y}return c||(E=i,w=o),{x:w,y:g,width:E,height:D}}function po(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const Ed="desktop-mode-widgets",Sd="desktop-mode-widgets-geometry";function Cd(){try{return window.localStorage.getItem(Ed)}catch{return null}}function Ah(){const e=Cd();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Ns(e){try{window.localStorage.setItem(Ed,JSON.stringify(e))}catch{}}function xh(){try{const e=window.localStorage.getItem(Sd);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=Ih(s);i&&(n[o]=i)}return n}catch{return{}}}function Ds(e){try{window.localStorage.setItem(Sd,JSON.stringify(e))}catch{}}function Ih(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 Lh(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 Th=["clock"];class Nh{constructor(t,n,o){this.mounted=new Map,this.generation=0,this.root=t,this.pluginUrl=n,this.enabledIds=Ah(),this.geometry=xh(),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(){Cd()===null&&(this.enabledIds=Th.filter(t=>!!sn(t)),Ns(this.enabledIds));for(const t of this.enabledIds)this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){this.enabledIds.includes(t)||sn(t)&&(this.enabledIds.push(t),Ns(this.enabledIds),this.mountById(t),this.paintEmptyState(),_(v.WIDGET_ADDED,{id:t}),lo())}remove(t){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(Ns(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],Ds(this.geometry)),this.unmountById(t),this.paintEmptyState(),_(v.WIDGET_REMOVED,{id:t}),lo())}getEnabledIds(){return[...this.enabledIds]}mountIfEnabled(t){sn(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 sn(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=sn(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=wh(n,{floatingParent:this.floatingHost,geometry:s},{onRemove:()=>this.remove(t),onGeometryChanged:u=>this.persistGeometry(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:Lh(t)};_(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,_(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(Dh(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){_(v.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){_(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)),_(v.WIDGET_MOUNT_FAILED,{id:t,error:n}),_(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(),rh({anchor:t,registry:()=>md(),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),Ts(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],Ds(this.geometry));const o=n.frame.card;o.classList.remove("desktop-mode-widgets__card--floating"),o.style.left="",o.style.top="",o.style.width="",o.style.height="",this.listEl.appendChild(o),this.paintEmptyState()}persistGeometry(t,n){this.geometry[t]=n,Ds(this.geometry)}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 Dh(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const Oh=280,Rh=220,Mh=520,Ph=400;function $h(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=Fm(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{}cp(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!==""&&rp(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 Wh(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=$h(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??Mh,height:t.height??Ph,minWidth:t.minWidth??Oh,minHeight:t.minHeight??Rh,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let Uh=0;function Bh(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++Uh}`,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)Ji(c,o)}};for(const[c,l]of i){const u=t[c];u&&(r.push(l),q(l,o,p=>{const f=p;if(f.windowId!==e)return;const{windowId:b,...m}=f;u(m),c==="closed"&&!s&&d()}))}return d}function Hh(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 S=vr(y.id);return S?{width:Math.max(S.width,y.minWidth),height:Math.max(S.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 S=document.createElement("template");S.id=y.templateId,S.innerHTML=y.templateHtml,document.body.appendChild(S),i.add(y.templateId)},u=y=>{const S=y.styleUrl;if(!S||a.has(S))return;const h=S.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${h}"]`)){const C=document.createElement("link");C.rel="stylesheet",C.href=S,y.styleHandle&&(C.dataset.desktopModeStyleHandle=y.styleHandle),document.head.appendChild(C)}if(Array.isArray(y.styleInline))for(const C of y.styleInline){if(typeof C!="string"||C==="")continue;const T=document.createElement("style");y.styleHandle&&(T.dataset.desktopModeStyleHandle=y.styleHandle),T.textContent=C,document.head.appendChild(T)}a.add(S)},p=async y=>{if(!(!y.scriptUrl||r.has(y.scriptUrl))){try{await ke(y.scriptUrl,{translations:y.scriptTranslations,l10n:y.scriptL10n,before:y.scriptBefore,after:y.scriptAfter})}catch(S){_(v.SHELL_ERROR,{scope:"native-window-script-load",id:y.id,error:S})}r.add(y.scriptUrl)}},f=y=>{const h=(window.desktopModeNativeWindows||{})[y.id],L=(T,I)=>(T.appendChild(Os(y.templateId)),h?.(T,I)),C=c(y);t.open({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:C.width,height:C.height,minWidth:y.minWidth,minHeight:y.minHeight,render:L,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle})},b=y=>{const h=(window.desktopModeNativeWindows||{})[y.id],L=(T,I)=>(T.appendChild(Os(y.templateId)),h?.(T,I)),C=c(y);t.openNew({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:C.width,height:C.height,minWidth:y.minWidth,minHeight:y.minHeight,initialState:"normal",render:L,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)}),_(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 S=new Set;for(const h of y)S.add(h.id),d.set(h.id,h);for(const h of Array.from(s))S.has(h)||w(h);for(const h of y)s.has(h.id)||await m(h)},E=(y,S={})=>{const h=d.get(y);return h?(ue.publish("desktop-mode/open-requested",{windowId:y,source:S.source??"api"}),f(h),!0):!1},D=(y,S={})=>{const h=d.get(y);return h?(ue.publish("desktop-mode/open-requested",{windowId:y,source:S.source??"api"}),b(h),!0):!1};return q(v.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",y=>{const S=y,h=S?.windowId,L=S?.width,C=S?.height;if(!h||typeof L!="number"||typeof C!="number")return;const T=t.getById(h);if(!T||T.state!=="normal")return;const I=T.config.baseId||T.id;kr(I,{width:L,height:C}),T.element&&_r(I,{x:T.element.offsetLeft,y:T.element.offsetTop})}),q(v.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",y=>{const S=y?.windowId;if(!S)return;const h=t.getById(S);if(!h||h.state!=="normal"||!h.element)return;const L=h.config.baseId||h.id;kr(L,{width:h.element.offsetWidth,height:h.element.offsetHeight}),_r(L,{x:h.element.offsetLeft,y:h.element.offsetTop})}),q(v.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",y=>{const S=y?.windowId;if(!S)return;const h=t.getById(S);if(!h)return;const L=h.config.baseId||h.id,C=d.get(L),T=C?{width:C.width,height:C.height}:{width:h.config.width,height:h.config.height};Er(L,"maximized",T)}),q(v.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",y=>{const S=y?.windowId;if(!S)return;const h=t.getById(S);if(!h)return;const L=h.config.baseId||h.id;Er(L,null)}),{sync:g,openById:E,openNewById:D}}function Os(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 Rs(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 Ad(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return Ad(e,n);const s=document.createElement("span");s.className=`${n} desktop-mode-icon-letter`.trim(),s.setAttribute("aria-hidden","true");const i=Fh(o);s.textContent=i;const r=cs(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 Ad(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 Fh(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 xd="desktop-mode-icon__badge",rn=new Map;function zh(e){return Math.max(0,Math.floor(Number(e)||0))}function Id(e,t){if(!e)return;const n=Vh(e);if(!n)return;const o=zh(t),s=rn.get(e)??0;o!==s&&(o===0?rn.delete(e):rn.set(e,o),Nd(n,o),ue.publish("desktop-mode/badge-changed",{itemId:e,count:o,rail:"icon"}),_(v.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function jh(e){Id(e,0)}function Gh(e){return rn.get(e)??0}const qh={setBadge:Id,clearBadge:jh,getBadge:Gh};function Kh(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 Ld="";function Td(e,t,n){const o=Kh(t);if(o===Ld&&e.querySelector(":scope > .desktop-mode-icons"))return;Ld=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=Xh(d,n),l=rn.get(d.id)??0;l>0&&Nd(c,l),i.appendChild(c),a.set(d.id,c)}e.appendChild(i),_(v.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(d=>d.id),container:i,tiles:a})}function Vh(e){if(!e)return null;const t=document.querySelector(".desktop-mode-icons");return t?t.querySelector(`[data-icon-id="${Yh(e)}"]`):null}function Nd(e,t){const n=e.querySelector(`:scope > .${xd}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=te(Wt("%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=xd,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function Yh(e){const t=window.CSS;return t?.escape?t.escape(e):e}function Xh(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=Rs(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(),_(v.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),Zh(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),va({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function Zh(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(Xn(e.url))return;try{const n=new URL(e.url,window.location.origin);t.manager.open({id:`desktop-icon-${e.id}`,url:n.toString(),title:e.title,icon:e.icon})}catch{}}}const Dd="desktop-mode-side-dock";function Jh(e,t){return{id:`dock-core:${e.id}`,title:e.title,icon:e.icon,window:"",url:e.url,position:1e3+t}}function Qh(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=I=>I==="core"&&d?d:a,b=()=>{const I=document.getElementById(Dd);if(I)return I;const k=document.createElement("nav");return k.id=Dd,k.className="desktop-mode-dock",k.setAttribute("role","toolbar"),k.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(k,e.shellBody.firstChild),k},m=()=>{u&&u.parentNode&&u.parentNode.removeChild(u),u=null},w=()=>e.getSettings?.()??{itemVisibility:{},dockOrder:[]},g=()=>{const I=new Set;for(const k of p.values())I.add(k.item.id);return Sf(i,r,w(),I)},E=()=>{const I=g(),k=[],R=[];for(const x of I)x.isCore?k.push(x):R.push(x);return{core:k,plugin:R}},D=()=>{const I=w();if(s!=="spatial"){e.renderIcons(Cf(r,i,I.itemVisibility));return}const{core:k}=E(),R=k.map(Jh),x=[];let W=0;for(const M of i){const j=I.itemVisibility[M.id];(j==="desktop"||j==="both")&&x.push({id:`dock:${M.id}`,title:M.title,icon:M.icon,window:"",url:M.url||"",position:2e3+W++})}e.renderIcons([...R,...x])},y=()=>{if(a){try{a.destroy()}catch(I){_(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:I})}a=null,c=null}if(d){try{d.destroy()}catch(I){_(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:I})}d=null,l=null}},S=I=>{const k=ds();if(!k)return _(v.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return k.mount(I)}catch(R){if(_(v.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:k.id,error:R}),k===fs)return null;try{return fs.mount(I)}catch{return null}}},h=(I,k,R)=>({container:I,items:k,fullMenu:i.slice(),fullSystemTiles:Array.from(p.values()).map(x=>x.item),orientation:R,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:x=>{const W=de(x.url,e.adminUrl);e.windowManager.open({id:W,baseId:W,url:x.url,parentUrl:x.url,title:x.title,icon:x.icon.startsWith("dashicons-")?x.icon:"dashicons-admin-generic",submenu:x.submenu,multi:!!x.multi})},openSubmenuPick:(x,W)=>{e.windowManager.open({id:de(W.url,e.adminUrl),baseId:de(x.url,e.adminUrl),url:W.url,parentUrl:x.url,title:x.title,icon:x.icon.startsWith("dashicons-")?x.icon:"dashicons-admin-generic",submenu:x.submenu,multi:!!x.multi})},openSystemItem:x=>x.onOpen()}),L=()=>{y();const{core:I,plugin:k}=E();s==="classic"?(u=b(),d=S(h(u,I,"left")),l=no(d),a=S(h(e.bottomDockEl,k,"bottom")),c=no(a)):s==="unified"?(m(),a=S(h(e.bottomDockEl,g(),"bottom")),c=no(a)):(m(),a=S(h(e.bottomDockEl,k,"bottom")),c=no(a));for(const R of p.values())f(R.affinity)?.appendSystemItem(R.item)},C={getLayout:()=>s,getPrimary:()=>c,getSide:()=>l,setLayout:I=>{I!==s&&(s=I,e.shellRoot.setAttribute("data-desktop-mode-layout",I),L(),D(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:I,primary:c,side:l}})))},applyDockItems:I=>{i=I;const{core:k,plugin:R}=E();s==="classic"?(d?.replaceItems(k),a?.replaceItems(R)):s==="unified"?a?.replaceItems(g()):a?.replaceItems(R),D()},applyDesktopIcons:I=>{r=I??[],D()},appendSystemTile:(I,k="plugin")=>{p.set(I.id,{item:I,affinity:k}),f(k)?.appendSystemItem(I)},removeSystemTile:I=>{const k=p.get(I);k&&(p.delete(I),f(k.affinity)?.removeSystemItem(I))},listSystemTiles:()=>Array.from(p.values()).map(I=>({id:I.item.id,title:I.item.title,icon:I.item.icon,affinity:I.affinity})),getSystemTile:I=>p.get(I)?.item??null,getMenuItems:()=>i.slice(),refresh:()=>{const{core:I,plugin:k}=E();s==="classic"?(d?.replaceItems(I),a?.replaceItems(k)):s==="unified"?a?.replaceItems(g()):a?.replaceItems(k),D()},destroy:()=>{y(),m()}};e.shellRoot.setAttribute("data-desktop-mode-layout",s),L(),D();let T=ds()?.id??null;return rf(()=>{const I=ds()?.id??null;I!==T&&(T=I,L(),D(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:s,primary:c,side:l}})))}),C}function ew(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 tw{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=ew(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 Od=e=>!e||typeof e!="object"?!1:e.name==="AbortError",nw=e=>{if(!e)return[];const t=rm();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}}):[]},ow=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 sw(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 iw(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function rw(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 je(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 Od(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=am(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:iw(a)}};d&&(l.system_prompt_text=d.text,l.system_prompt_mode=d.mode);let u;try{u=await t(l,c)}catch(b){if(Od(b))throw b;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=nw(r.tools),c=ow(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 E=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[desktop-mode] wp.desktop.ai.ask: HTTP ${u.status} — ${E.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:b,args:m,result:w}=f;let g=sw(p.message,w);if(r.followUp===!0){const E=await o(a,b,m,w,c,r.signal);E!==null&&(g=E)}return{answer_type:"tool_call",message:g,entity:null,admin_links:null,toolCall:{slug:b,args:m,result:w},request_id:p.request_id}}}const Ms="desktop-mode-broadcast",Rd="desktop-mode-broadcast",Md=window.location.origin;let Ps=null;function aw(e){Ps=e}function Pd(e,t){const n=String(z("desktop-mode.broadcast.topic",e,{payload:t})??e),o=z("desktop-mode.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Ms,{detail:s})),_(v.BROADCAST,s),ue.publish(n,o),!Ps)return;const i={type:Rd,topic:n,payload:o};for(const r of Ps._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Md)}catch{}}}function xe(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){_(v.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Ms,n),()=>document.removeEventListener(Ms,n)}function dw(){window.addEventListener("message",e=>{if(e.origin!==Md)return;const t=e.data;!t||t.type!==Rd||t._fromParent||typeof t.topic=="string"&&Pd(t.topic,t.payload)})}const $d="[desktop-mode-bin badge]";function Me(...e){try{window.localStorage?.getItem("desktopModeBinDebug")&&console.info($d,...e)}catch{}}function fo(...e){console.warn($d,...e)}const et="desktop-mode-recycle-bin",cw="desktop_mode_recycle_bin_seen_ts";function Wd(){return window.wp?.desktop}const ne=re("desktop-mode/recycle-bin/badge",()=>({current:0,seenTs:0,started:!1,countUrl:""}));function an(e){const t=Math.max(0,Math.floor(e)),n=ne.state.current;ne.state.current=t,Me("setRecycleBinBadge",{prev:n,next:t}),mo(t)}function Ud(e){an(ne.state.current+e)}function lw(){return ne.state.current}function mo(e){const t=Wd(),n=uw(),o=n?0:e;Me("paintBadge",{count:e,visible:o,active:n}),t?.dock?.setBadge?.(et,o),t?.taskbar?.setBadge?.(et,o),t?.icons?.setBadge?.(et,o)}function uw(){return!!Wd()?.windowManager?.isActive?.(et)}function pw(e,t=""){const n=Number(e)||0,o=window.desktopModeConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl,r=o?.desktopModeBinDebug;Me("startRecycleBinBadge entry",{initial:n,countUrl:t,alreadyStarted:ne.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)||fo("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}),ne.state.started){an(n);return}ne.state.started=!0,ne.state.countUrl=t,ne.state.seenTs=Date.now(),an(n),mw(),hw(),ww(),gw(),yw(),fw()}function fw(){const e="desktop-mode/recycle-bin/badge-lifecycle",t=n=>{n?.windowId===et&&mo(ne.state.current)};q(v.WINDOW_OPENED,e,t),q(v.WINDOW_FOCUSED,e,t),q(v.WINDOW_BLURRED,e,t),q(v.WINDOW_MINIMIZED,e,t),q(v.WINDOW_RESTORED,e,t),q(v.WINDOW_CLOSED,e,t),q(v.WINDOW_REOPENED,e,t)}function mw(){q(v.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/badge",e=>{e?.id===et&&mo(ne.state.current)})}function hw(){q(v.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/badge",e=>{e?.ids?.includes(et)&&mo(ne.state.current)})}function ww(){const e=t=>{const n=t;if(!n)return;const o=Array.isArray(n.ids)?n.ids.length:0;switch(n.action){case"trashed":Ud(+o);break;case"untrashed":case"deleted":Ud(-o);break}};xe("desktop-mode.post.changed",e),xe("desktop-mode.page.changed",e),xe("desktop-mode.attachment.changed",e),xe("desktop-mode.comment.changed",e),xe("desktop-mode.placement.changed",e),xe("desktop-mode.shortcut.changed",e),xe("desktop-mode.folder.changed",e)}function gw(){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<=ne.state.seenTs){Me("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:ne.state.seenTs});return}Me("postMessage triggers refetch",{ts:o,prevSeenTs:ne.state.seenTs}),ne.state.seenTs=o,bw()})}function yw(){const e=window.jQuery;if(!e){fo("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}Me("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[cw]=ne.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.desktop_mode_recycle_bin;Me("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>ne.state.seenTs&&(ne.state.seenTs=o.ts),typeof o.count=="number"&&an(o.count))})}async function bw(){if(!ne.state.countUrl){Me("refetchCount: no countUrl, skip");return}Me("refetchCount: hitting",ne.state.countUrl);try{const e=await fetch(ne.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){fo("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();Me("refetchCount: response",t),typeof t.count=="number"&&an(t.count)}catch(e){fo("refetchCount: fetch failed",e)}}const vw="desktop-mode-os-settings",kw="desktop-mode-recycle-bin";function _w(e){const t=Cw();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===vw?Ew():i===kw?Sw(s,e.getRecycleBinCount):n})}function Ew(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 Sw(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 Cw(){return window.wp?.hooks??null}const dn="desktop-mode-bug-report",Aw="WordPress",xw="desktop-mode",Bd=6e3;function Iw(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(Lw()),t.appendChild(Tw("title",O("Title"),{placeholder:O("A short summary"),required:!0})),t.appendChild(Hd("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(Hd("steps",O("Steps to reproduce (bug only)"),{placeholder:O("One step per line"),rows:4}));const o=Nw();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=Ow(t);if(!d.title.trim()||!d.description.trim()){Dw(t,O("Title and description are both required."));return}const c=Rw(d);window.open(c,"_blank","noopener")}),e.appendChild(t)}function Lw(){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 Tw(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 Hd(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 Nw(){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=zd(Fd()),e.appendChild(n),e}function Dw(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 Ow(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 Rw(e){const t=Mw(e.type),n=Pw(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/${Aw}/${xw}/issues/new?${o.toString()}`}function Mw(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function Pw(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(zd(Fd())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(`
54 `);return n.length>Bd&&(n=n.slice(0,Bd)+`
55
56 …(truncated to fit GitHub URL length limit)`),n}function Fd(){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 zd(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(`
57 `)}let ho=null,wo={installHintDismissed:!1,notificationsEnabled:!1};const $s=new Set;function jd(e){if(!e){ho=null;return}ho=e,wo={...e.state},qd()}function cn(){return{...wo}}function Ws(e){if(wo={...wo,...e},qd(),!ho)return cn();const t=JSON.stringify(e),n=$w();return fetch(ho.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)}),cn()}function Gd(e){return $s.add(e),()=>{$s.delete(e)}}function qd(){const e=cn();for(const t of Array.from($s))try{t(e)}catch(n){typeof console<"u"&&console.error("[desktop-mode] pwa-state listener threw:",n)}}function $w(){return window.desktopModeConfig?.restNonce??""}const Ww=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:cn,initPwaState:jd,subscribePwaState:Gd,updatePwaState:Ws},Symbol.toStringTag,{value:"Module"}));let go=null,Kd=!1,Vd=!1,Yd=!1,tt="pending";function Uw(){if(Vd)return;Vd=!0;const e=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{e&&(Yd||Hw()||(Fw(),Yd=!0,setTimeout(()=>window.location.reload(),0)))})}const Xd="wpd-sw-reload-ts",Bw=3e4;function Hw(){try{const e=sessionStorage.getItem(Xd),t=e?Number.parseInt(e,10):0;return!Number.isFinite(t)||t<=0?!1:Date.now()-t<Bw}catch{return!1}}function Fw(){try{sessionStorage.setItem(Xd,String(Date.now()))}catch{}}async function zw(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return tt="unsupported",null;if(go||Kd)return go;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 tt="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 go=await navigator.serviceWorker.register(e.swUrl,{scope:"/",updateViaCache:"none"}),tt="registered",Uw(),go}catch(n){return Kd=!0,tt="failed",typeof console<"u"&&console.warn("[desktop-mode] SW registration failed:",n),null}}function jw(){return tt}const Gw="desktop-mode-pwa-install";function Zd(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Jd(){if(Zd())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 qe=null;function qw(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(),qe=s}function o(){qe=null,t({message:te(O("Installed %s as an app."),e)})}}function Kw(e,t){return{id:Gw,title:te(O("Install %s as an app"),e),icon:"dashicons-download",onOpen:()=>{Vw(e,t)}}}async function Vw(e,t){if(qe){const n=qe;qe=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 Jd()){t({message:te(O("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(jw()==="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 Yw(){if(!qe)return"unavailable";const e=qe;qe=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function Xw(){Promise.resolve().then(()=>Ww).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function Zw(e){const t=ue.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=X({message:t.body?t.title+" — "+t.body:t.title}),ue.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=Qd(t),i):a==="denied"?(r(),i):(Notification.requestPermission().then(d=>{if(!n){if(d==="granted"){Ws({notificationsEnabled:!0}),o=Qd(t);return}r()}}),i)}function Qd(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),()=>{}}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 ue.publish("desktop-mode/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function Jw(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&Ws({notificationsEnabled:!0}),e}function Qw(){return typeof Notification>"u"?"unsupported":Notification.permission}function eg(e,t){e.pwa&&(jd(e.pwa),qw(e.pwa.appName||"WordPress",t),zw(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw}))}const ec={START:"desktop-mode-cross-frame-drag-start",END:"desktop-mode-cross-frame-drag-end"};function tg(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-start"&&!!e.payload&&typeof e.payload=="object"}function ng(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-end"}function og(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-payload-request"}class sg{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(tg(n)){this._startDrag(n.payload);return}if(ng(n)){this._endDrag();return}if(og(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){this._payload=t,document.dispatchEvent(new CustomEvent(ec.START,{detail:{payload:t}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(ec.END,{detail:{payload:t}}))}}class ig{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 rg="desktop-mode-drag-ghost",tc="desktop-mode-drag-ghost--accept",nc="desktop-mode-drag-ghost--reject",ag="desktop-mode-drag-hint",oc="desktop-mode-drag-hint--accept",sc="desktop-mode-drag-hint--reject",ic="desktop-mode-drag-hint--neutral",dg=16,cg=18;function lg(e,t,n){const o=wg(e),s=e.ghost?.offsetX??gg(e.source),i=e.ghost?.offsetY??yg(e.source);o.classList.add(rg),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=pg(e),a=r?ug():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+dg}px, ${l+cg}px, 0)`)},setMode(c){o.classList.remove(tc,nc),c==="accept"?o.classList.add(tc):c==="reject"&&o.classList.add(nc),a&&r&&(a.classList.remove(oc,sc,ic),c==="accept"?(a.classList.add(oc),a.textContent=r.accept):c==="reject"?(a.classList.add(sc),a.textContent=r.reject):(a.classList.add(ic),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 ug(){const e=document.createElement("div");return e.className=ag,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 pg(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??fg(e),reject:t?.reject??mg(),neutral:t?.neutral??hg(e)}}function fg(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 mg(e){return O("Can’t drop here","desktop-mode")}function hg(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 wg(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 gg(e){return e.offsetWidth/2}function yg(e){return e.offsetHeight/2}let rc=!1;function bg(e){rc||(rc=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const ac=4,_e={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"},yo="desktop-mode-file-tile--dragging",dc="desktop-mode-file-tile--drop-target",cc="data-desktop-mode-trash-drop-active",lc="data-files-drop-active",uc="data-desktop-mode-dragging",pc="data-desktop-mode-drag-type",Us="data-desktop-mode-drag-mode";class vg{constructor(){this._registry=new ig,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)<ac&&Math.abs(s)<ac)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),Pe(_e.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(),bg(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:()=>fc(),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(yo),t._ghost=lg(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(uc,""),document.body.setAttribute(pc,String(t.payload.type)),document.body.setAttribute(Us,"neutral")),Pe(_e.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&&Bs(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(kg(s.target,t),t._ghost?.setMode("accept"),r="accept"):(t._ghost?.setMode("reject"),Pe(_e.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Us,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),Bs(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)}Pe(_e.COMMIT,{payload:t.payload,targetId:n.id}),Pe(_e.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&&Bs(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[desktop-mode] drag onCancel threw:",o)}Pe(_e.CANCEL,{payload:t.payload,reason:n}),Pe(_e.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(yo)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(uc),document.body.removeAttribute(pc),document.body.removeAttribute(Us)),_g()}}function Pe(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function kg(e,t){try{e.onEnter?.(t)}catch(n){console.error("[desktop-mode] drop target onEnter threw:",e.id,n)}Pe(_e.ENTER,{payload:t.payload,targetId:e.id})}function Bs(e,t){try{e.onLeave?.(t)}catch(n){console.error("[desktop-mode] drop target onLeave threw:",e.id,n)}Pe(_e.LEAVE,{payload:t.payload,targetId:e.id})}function fc(){if(typeof document>"u")return[];const e=[];for(const t of[`.${yo}`,`.${dc}`,`[${cc}]`,`[${lc}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function _g(){for(const e of fc())e.classList.remove(yo,dc),e.removeAttribute(cc),e.removeAttribute(lc)}const Eg="desktop-mode-iframe-drop-",mc="iframe.desktop-mode-window__iframe",Hs="data-desktop-mode-iframe-drop-active";let Fs=!1,hc=null;const Ke=new Map,kt=new Map;function bo(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function zs(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function Sg(e,t,n,o){return e.registerDropTarget({id:`${Eg}${o}`,element:n,accept:s=>!!bo(s),onEnter:s=>{const i=bo(s.payload);i&&(n.setAttribute(Hs,""),zs(t,{type:"desktop-mode-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(Hs),zs(t,{type:"desktop-mode-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(Hs);const r=bo(s.payload);if(!r)return;const a=t.getBoundingClientRect();zs(t,{type:"desktop-mode-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function wc(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 Cg(e){const t=hc;if(!t)return;const n=document.querySelectorAll(mc),o=!!bo(e);console.info("[desktop-mode] drag-start: suppressing %d iframe(s); bridgeable=%s",n.length,o,e),n.forEach(s=>{if(Ke.has(s)||(Ke.set(s,s.style.pointerEvents),s.style.pointerEvents="none",!o))return;const i=s.parentElement;if(!i)return;const r=wc(s),a=Sg(t,s,i,r);kt.set(s,a)})}function Ag(){Ke.forEach((e,t)=>{t.style.pointerEvents=e}),Ke.clear(),kt.forEach(e=>{try{e()}catch{}}),kt.clear()}function xg(e){Fs||(Fs=!0,hc=e,document.addEventListener(_e.START,t=>{const n=t.detail;Cg(n?.payload)}),document.addEventListener(_e.END,()=>{Ag()}),q(v.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(Ke))t.isConnected||Ke.delete(t);for(const[t,n]of Array.from(kt))if(!t.isConnected){try{n()}catch{}kt.delete(t)}}),window.__desktopModeIframeDropDebug=()=>({installed:Fs,iframesInDom:document.querySelectorAll(mc).length,suppressedCount:Ke.size,registeredCount:kt.size,suppressedIframeIds:Array.from(Ke.keys()).map(wc)}))}function gc(){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=z("desktop-mode.open-command.items",o);return Array.isArray(i)?i:o}const Ig={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=gc();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=gc(),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 Lg(){ao(Ig)}const pe=[],Tg=new Set;function yc(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=pe.findIndex(n=>n.id===e.id);return t>=0?pe[t]=e:pe.push(e),js(),()=>{const n=pe.findIndex(o=>o.id===e.id);n>=0&&(pe.splice(n,1),js())}}function Ng(e){const t=pe.findIndex(n=>n.id===e);t>=0&&(pe.splice(t,1),js())}function Dg(){return pe.slice()}function js(){for(const e of Array.from(Tg))try{e()}catch(t){typeof console<"u"&&console.error("[desktop-mode] palette-registry listener threw:",t)}}function bc(){if(pe.length===0)return;const e=pe.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{pe[0].open()}catch{}return}try{pe[e].close()}catch{}const t=e+1;if(t<pe.length)try{pe[t].open()}catch{}}function vc(e){const t=pe.find(n=>n.id===e);if(t){for(const n of pe)if(n.id!==e)try{n.isOpen()&&n.close()}catch{}try{t.open()}catch{}}}let kc=!1;function Og(){if(kc)return;kc=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),bc())},!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"&&bc()})}const vo=new Map,Gs=new Map;let _c=!1;const nt={contribute(e,t){return vo.set(e,t),()=>{vo.get(e)===t&&vo.delete(e)}},subscribe(e,t){let n=Gs.get(e);return n||(n=new Set,Gs.set(e,n)),n.add(t),()=>{n.delete(t)}}};function Rg(){if(_c)return;_c=!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 vo)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 Gs){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 Ie=re("desktop-mode/presence",()=>({byUser:new Map,serverTimeMs:0})),Mg=5*60*1e3;let Ec=Date.now(),Sc=!1;function ko(){Ec=Date.now()}function Pg(e){if(!e||!e.snapshot)return;const t=Ie.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})}Ie.state.byUser=n,typeof e.serverTimeMs=="number"&&(Ie.state.serverTimeMs=e.serverTimeMs),Ie.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})),ue.publish("desktop-mode/presence-changed",i)}ue.publish("desktop-mode/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function $g(){Sc||(Sc=!0,document.addEventListener("pointerdown",ko,{capture:!0,passive:!0}),document.addEventListener("keydown",ko,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||ko()}),nt.contribute("desktop_mode_presence_active",()=>!0),nt.contribute("desktop_mode_user_active",()=>Date.now()-Ec<Mg),nt.subscribe("desktop_mode_presence",e=>{Pg(e)}))}function Wg(e){const t=Ie.state.byUser.get(e);return t?t.status:"offline"}function Ug(){return new Map(Ie.state.byUser)}function Bg(e){return Ie.state.byUser.get(e)??null}function Hg(e){return Ie.subscribe(t=>e(t))}function Fg(){ko()}function zg(e){if(!Array.isArray(e)||e.length===0)return;const t=Ie.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)){Ie.state.byUser=n,Ie.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})),ue.publish("desktop-mode/presence-changed",i)}ue.publish("desktop-mode/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const jg=Object.freeze({getStatus:Wg,getAll:Ug,getEntry:Bg,subscribe:Hg,markActive:Fg,applyBatch:zg}),Gg="desktop_mode_nonces",qs=new Map;let Cc=!1;function Ks(e,t){if(typeof e!="string"||e==="")return()=>{};let n=qs.get(e);return n||(n=new Set,qs.set(e,n)),n.add(t),()=>{n.delete(t)}}function qg(){Cc||(Cc=!0,nt.subscribe(Gg,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=qs.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)}}}),Kg())}function Kg(){Ks("wp_rest",Vg),Ks("desktop-mode-plugins",e=>{Ac("desktop-mode-plugins","ajaxNonce",e)}),Ks("updates",e=>{Ac("desktop-mode-plugins","updatesNonce",e)})}function Vg(e){const t=Yg();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=xc();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Ac(e,t,n){const s=xc()?.[e];s&&typeof s=="object"&&(s[t]=n)}function Yg(){if(!(typeof window>"u"))return window.desktopModeConfig}function xc(){if(!(typeof window>"u"))return window.desktopModeWindowConfig}const _t=12;function Vs(e,t){const n=de(e,t.adminUrl);return(t.dockItems||[]).find(o=>de(o.url,t.adminUrl)===n||(o.submenu||[]).some(s=>de(s.url,t.adminUrl)===n))}function Ic(e,t){const n=Math.max(200,t.width-_t*2),o=Math.max(200,t.height-_t*2),s=Math.min(e.width,n),i=Math.min(e.height,o),r=Math.max(0,t.width-s-_t),a=Math.max(0,t.height-i-_t),d=Math.max(_t,Math.min(e.x,r)),c=Math.max(_t,Math.min(e.y,a));return{x:d,y:c,width:s,height:i}}const Lc=window.location.origin;function Xg(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(f){typeof console<"u"&&console.warn("[desktop-mode] Couldn’t parse href; letting the browser handle the click:",a,f);return}if(d.origin!==Lc)return;let c;try{c=new URL(t.adminUrl).pathname}catch(f){typeof console<"u"&&console.error("[desktop-mode] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,f),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(),ht(d.href)))return;const l=de(d.href,t.adminUrl),u=Vs(d.href,t),p=(i.textContent||"").trim()||u?.title||"";e.open({id:l,baseId:l,multi:!!u?.multi,url:d.href,parentUrl:u?.url??d.href,title:u?.title||p,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu})},!0)}const Zg="desktop-mode-registry-changed";function Jg(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 Ys(e,t,n){const{added:o,removed:s}=Jg(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(Zg,{detail:i}))}function Qg(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerDockRailRenderers:c,renderIcons:l}=e;return function(p){const f=p.dockItems,b=p.nativeWindows,m=p.serverWidgets,w=p.serverWallpapers,g=p.serverCommandScripts,E=p.serverCommands,D=p.serverSettingsTabScripts,y=p.serverSettingsTabs,S=p.serverDockRailRendererScripts,h=p.serverTitleBarButtonScripts,L=p.serverWindowNotices,C=p.desktopIcons;if(!Array.isArray(f)||f.length===0)return;const T=n.dockItems;if(t(f),n.dockItems=f,Ys("dock-items",T,f),Array.isArray(b)){const I=n.nativeWindows;o(b),n.nativeWindows=b,Ys("native-windows",I,b)}if(Array.isArray(m)&&(s(m),n.serverWidgets=m),Array.isArray(w)&&(i(w),n.serverWallpapers=w),Array.isArray(g)&&(r(g,Array.isArray(E)?E:void 0),n.serverCommandScripts=g,Array.isArray(E)&&(n.serverCommands=E)),Array.isArray(D)&&(a(D,Array.isArray(y)?y:void 0),n.serverSettingsTabScripts=D,Array.isArray(y)&&(n.serverSettingsTabs=y)),Array.isArray(h)&&(d(h),n.serverTitleBarButtonScripts=h),Array.isArray(S)&&(c(S),n.serverDockRailRendererScripts=S),Array.isArray(L)&&(ad(L),n.serverWindowNotices=L),Array.isArray(C)){const I=n.desktopIcons;l(C),n.desktopIcons=C,Ys("desktop-icons",I,C)}}}const ey=8e3;function ty(e){const{layoutDispatcher:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerDockRailRenderers:c,renderIcons:l}=e,u=Qg({applyDockItems:f=>t?.applyDockItems(f),config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerDockRailRenderers:c,renderIcons:l});return window.addEventListener("message",f=>{if(f.origin!==Lc)return;const b=f.data;!b||b.type!=="desktop-mode-plugins-changed"||b.payload&&u(b.payload)}),()=>{if(!n.adminUrl)return Promise.resolve();const f=(()=>{try{const b=new URL("admin.php",n.adminUrl);return b.searchParams.set("desktop_mode_chromeless","1"),b.searchParams.set("desktop_mode_menu_refresh","1"),b.toString()}catch{return null}})();return f?new Promise(b=>{const m=document.createElement("iframe");m.setAttribute("aria-hidden","true"),m.tabIndex=-1,m.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",m.src=f;let w=!1;const g=()=>{w||(w=!0,window.clearTimeout(D),window.removeEventListener("message",E),m.parentNode&&m.parentNode.removeChild(m),b())},E=y=>{if(y.source!==m.contentWindow)return;const S=y.data;!S||S.type!=="desktop-mode-plugins-changed"||g()},D=window.setTimeout(()=>{_(v.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),g()},ey);window.addEventListener("message",E),document.body.appendChild(m)}):Promise.resolve()}}async function ny(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=Ic(s,o),r=Vs(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 oy(e,t){if(ht(t.currentPage))return;const n=de(t.currentPage,t.adminUrl),o=Vs(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 sy(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function Xs(e,t,n,o){const s=sa(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 iy=500;function ry(e,t){let n=null,o=!1;const s=async()=>{if(o)return;const a=e.snapshot();o=!0;try{await Xs(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){_(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()},iy)};return window.addEventListener("pagehide",i),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&i()}),r}const ay=120;function dy(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)}function cy(){const e=document.getElementById("desktop-mode-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;_(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,ay)}),document.addEventListener("visibilitychange",()=>{_(v.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function ly(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 z(v.DOCK_TILE_CLASS,e,o)}function uy(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 z(v.DOCK_TILE_ELEMENT,e,o)}function py(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 z(v.DOCK_TILE_TOOLTIP,e,o)}function fy(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};_(v.DOCK_TILE_RENDERED,{...o,el:e})}const my=[".desktop-mode-dock","#desktop-mode-dock","#desktop-mode-side-dock",".desktop-mode-dock__tooltip",".desktop-mode-dock-submenu"].join(","),Zs=new Set;function hy(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(my))return!0;for(const n of Zs)if(t.closest(n))return!0;return!1}function wy(e){return typeof e!="string"||e.trim()===""?()=>{}:(Zs.add(e),()=>{Zs.delete(e)})}const $e=new Map,gy=window.location.origin;function Tc(e){let t=$e.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},$e.set(e,t)),yy(e,t),t}function yy(e,t){const n=Js(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(()=>Et(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function by(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function Js(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 vy(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 Et(e){const t=Js(e);if(!t||!t.contentWindow)return;const n=$e.get(e),o=n?vy(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"desktop-mode-instrument-set",headers:o,observe:s},gy)}catch{}}q(v.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&$e.has(t.windowId)&&Et(t.windowId)}),q(v.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=$e.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const Ve=new Map,ky=1e3;function Nc(e,t,n){const o=Ve.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,!!Ve.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=Ve.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>Nc(e,t,n),ky))})}function _y(){const e=window.desktopModeConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function Ey(e,t){const n=Ve.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let Sy=0;const Dc={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=Tc(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),Et(e),()=>{const r=$e.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),Et(e),Oc(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=Tc(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,Et(e)),()=>{const i=$e.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),Et(e)),Oc(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=Js(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=Dc.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){Ey(e,{id:++Sy,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=Ve.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},Ve.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=_y();r&&Nc(e,r.restUrl,r.restNonce)}return()=>{const r=Ve.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),Ve.delete(e))}}}};function Oc(e){const t=$e.get(e);t&&t.headers.size===0&&t.observers.size===0&&(by(t),$e.delete(e))}async function Rc(e){return await jo(Go()),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 Cy(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:Mc(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:Mc(c),face:"top",element:d})});const a=z(v.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function Mc(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const Ay="__desktop_modeKeyedListKey",xy="__desktop_modeKeyedListData";function Iy(e){const t=e.__desktop_modeKeyedList;if(t)return t;const n={byKey:new Map};return e.__desktop_modeKeyedList=n,n}function Ly(e,t,n){const o=Iy(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[Ay]=c,u[xy]=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 Ty(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 Ny(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:d=C=>{typeof console<"u"&&console.error("[desktop-mode] createInfiniteList:",C)}}=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,b=null,m=0,w=!1,g=null;const E=C=>{if(f!==C){f=C;try{a(C)}catch(T){d(T)}}},D=()=>{g&&(g.disconnect(),g=null)},y=()=>{g||!c||w||(g=new IntersectionObserver(C=>{for(const T of C)T.isIntersecting&&S()},{rootMargin:i}),g.observe(c))},S=async()=>{if(w||f||!p)return;E(!0),b=new AbortController;const C=b;try{const T=await n(u,C.signal);if(w||C!==b)return;let I=0;const k=document.createDocumentFragment();for(const R of T.items??[]){const x=String(o(R));if(l.has(x))continue;l.add(x);const W=s(R,m+I);k.appendChild(W),I++}I>0&&(c&&c.parentNode===t?t.insertBefore(k,c):t.appendChild(k),m+=I),u=T.nextCursor??null,u||(p=!1,D())}catch(T){if(T?.name==="AbortError")return;d(T)}finally{C===b&&(E(!1),b=null)}},h=()=>{if(w)return;b?.abort(),b=null,l.clear(),u=r,p=!0,m=0;const C=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);C&&c&&t.appendChild(c),E(!1),y(),S()},L=()=>{w||(w=!0,D(),b?.abort(),b=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,E(!1))};return y(),S(),{reset:h,loadMore:S,hasMore:()=>p,isLoading:()=>f,destroy:L}}const Dy=520,Oy=720,Ry=500;function My(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[desktop-mode] startOAuth requires a non-empty service slug."));const n=$y(),o=Wy();return je(eo(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=>Py(s,e,t))}function Py(e,t,n){return new Promise((o,s)=>{const i=n.width??Dy,r=n.height??Oy,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 b=()=>{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 E=g.payload;if(b(),E&&E.ok)o(E);else{const D=E?.reason??"unknown",y=E?.message??"OAuth flow failed",S=new Error(`[desktop-mode] startOAuth(${t}) failed: ${D} — ${y}`);S.cause=E,s(S)}};window.addEventListener("message",m),p=window.setInterval(()=>{l.closed&&(b(),s(new Error(`[desktop-mode] startOAuth(${t}) cancelled — popup closed before completing.`)))},Ry)})}function Pc(){return window.desktopModeConfig??{}}function $y(){const e=Pc().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function Wy(){const e=Pc().restNonce;return typeof e=="string"&&e!==""?e:null}const Uy=new Set(["windowManager","dock","taskbar","icons","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","cloneTemplate","onWindow","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","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","broadcast","subscribe","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","debug","fetch"]);function By(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:b,openOsSettings:m,aiAssistant:w,dragBridge:g,dragManager:E,connect:D,config:y}=e,S={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,icons:i,files:r,confirm:Rc,saveSession:a,hooks:mu(),HOOKS:v,isActive:()=>!!document.getElementById("desktop-mode-shell"),registerWallpaper:h=>{zt(h),s.apply()},registerWidget:h=>{Is(h)},widgetLayer:d,widgets:{redock:h=>{d?.redock(h)}},loadVendorScript:ke,getWallpaperSurfaces:()=>Cy(t),registerWindow:c,openWindow:l,openNewWindow:u,fetch:(h,L,C)=>Xs(t,h,L,C),repaintLoadingOverlays:Fr,cloneTemplate:Os,onWindow:Bh,createInfiniteList:Ny,startOAuth:My,registerSystemTile:h=>{p(h),_(v.DOCK_ITEM_APPENDED,{id:h.id})},registerModule:Ca,loadModules:Aa,whenReady:er,ready:er,isReady:wu,setDefaultWindow:f,refreshMenu:b,config:y,ai:w,dragBridge:g,dragManager:E,registerCommand:ao,unregisterCommand:Na,listCommands:Da,registerDestructiveAdminAction:Ap,unregisterDestructiveAdminAction:Gr,listDestructiveAdminActions:xp,registerSettingsTab:Ra,unregisterSettingsTab:Ma,listSettingsTabs:Pa,registerDockRailRenderer:ra,unregisterDockRailRenderer:nf,listDockRailRenderers:sf,openOsSettings:m,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:h=>s.subscribeOsSettings(h),updateOsSettings:(h,L={})=>{if(typeof h.wallpaper=="string"&&(s.state.wallpaper=h.wallpaper),typeof h.accent=="string"&&(s.state.accent=h.accent),typeof h.dockSize=="string"&&(s.state.dockSize=h.dockSize),typeof h.desktopLayout=="string"&&(s.state.desktopLayout=h.desktopLayout),typeof h.dockRailRenderer=="string"&&(s.state.dockRailRenderer=h.dockRailRenderer),h.ai&&typeof h.ai=="object"&&(s.state.ai={...s.state.ai,...h.ai}),typeof h.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=h.nativePostsEnabled),typeof h.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=h.nativePagesEnabled),typeof h.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=h.nativeUsersEnabled),typeof h.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=h.nativePluginsEnabled),typeof h.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=h.nativeCommentsEnabled),typeof h.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=h.foldersSharingEnabled),Array.isArray(h.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=h.nativePostsHiddenColumns.filter(C=>typeof C=="string"&&C!=="").slice(0,32)),h.itemVisibility&&typeof h.itemVisibility=="object"){const C=["both","dock","desktop","hidden"],T={};for(const[I,k]of Object.entries(h.itemVisibility))typeof I!="string"||I===""||typeof k!="string"||!C.includes(k)||(T[I]=k);s.state.itemVisibility=T}if(Array.isArray(h.dockOrder)&&(s.state.dockOrder=h.dockOrder.filter(C=>typeof C=="string"&&C!=="").slice(0,256)),h.dockPromotedPositions&&typeof h.dockPromotedPositions=="object"){const T={};for(const[I,k]of Object.entries(h.dockPromotedPositions)){if(typeof I!="string"||I===""||!k||typeof k!="object")continue;const R=k;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)&&(T[I]={x:R.x,y:R.y},Object.keys(T).length>=256))break}s.state.dockPromotedPositions=T}s.save(L),(h.itemVisibility||h.dockOrder)&&o?.refresh()},deriveWindowId:(h,L)=>de(h,L??y.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:h=>o?.getSystemTile(h)??null,getMenuItems:()=>o?.getMenuItems()??[],renderIcon:Rs,applyTileClasses:ly,applyTileElement:uy,applyTileTooltip:py,dispatchTileRendered:fy,isDockElement:hy,registerDockSelector:wy,registerTitleBarButton:Ua,unregisterTitleBarButton:fm,listTitleBarButtons:hm,registerWindowTheme:Fa,unregisterWindowTheme:za,listWindowThemes:ja,applyWindowTheme:(h,L)=>{const C=t.getById(h);C&&C.setAppearanceTheme(L)},registerWindowControl:Jt,unregisterWindowControl:Ka,listWindowControls:Va,applyWindowControls:(h,L)=>{const C=t.getById(h);C&&C.setAppearanceControls(L)},registerWindowSlot:Ja,unregisterWindowSlot:vs,listWindowSlots:Qa,applyWindowSlot:(h,L,C)=>{const T=t.getById(h);T&&T.setAppearanceSlot(L,C)},registerWindowNotice:id,unregisterWindowNotice:Ss,listWindowNotices:rd,dismissWindowNotice:Rm,undismissWindowNotice:Mm,registerWindowChrome:Wm,unregisterWindowChrome:ld,listWindowChromes:ud,applyWindowChrome:(h,L)=>{const C=t.getById(h);C&&C.setAppearanceChrome(L)},connect:D,broadcast:Pd,subscribe:xe,registerPalette:yc,unregisterPalette:Ng,listPalettes:Dg,openPalette:vc,devtools:Dc,createSharedStore:re,presence:jg,activity:ue,heartbeat:nt,showToast:X,notify:Zw,pwa:{promptInstall:Yw,undismissInstallHint:Xw,getState:cn,subscribe:Gd,requestNotificationPermission:Jw,getNotificationPermission:Qw},renderKeyedList:Ly,clearKeyedList:Ty,registerNamespace:(h,L)=>{if(typeof h!="string"||h===""){console.warn("[desktop-mode] registerNamespace: name must be a non-empty string");return}if(!L||typeof L!="object"){console.warn(`[desktop-mode] registerNamespace("${h}"): api must be an object`);return}if(Uy.has(h)){console.warn(`[desktop-mode] registerNamespace("${h}"): name is reserved by the shell — pick a plugin-specific key`);return}S[h]=L},getWindowConfig:h=>{const L=window.desktopModeWindowConfig;if(!L||typeof L!="object")return;const C=L[h];return C===void 0?void 0:C},debug:{window:h=>{const L=(y.nativeWindows??[]).find(x=>x.id===h);if(!L)return null;const C=L.scriptUrl||"";let T="unknown",I=!1;C&&(document.querySelector(`script[data-desktop-mode-vendor="${C.replace(/"/g,'\\"')}"]`)?(T="lazy",I=!0):Array.from(document.querySelectorAll("script[src]")).find(M=>M.src===C)&&(T="eager",I=!0));const k=window.desktopModeWindowConfig,R=!!(k&&typeof k=="object"&&Object.prototype.hasOwnProperty.call(k,h));return{id:h,scriptHandle:L.scriptHandle||"",scriptUrl:C,loadPath:T,tagInDom:I,configPresent:R,extras:{hasTranslations:!!L.scriptTranslations,l10nCount:(L.scriptL10n??[]).length,beforeCount:(L.scriptBefore??[]).length,afterCount:(L.scriptAfter??[]).length}}}}};return S}function Hy(e){if(window.wp||(window.wp={}),!window.wp.desktop){window.wp.desktop=e;return}Object.assign(window.wp.desktop,e)}const Qs=re("desktop-mode/layout",()=>({layout:"classic"}));function $c(e){Qs.state.layout!==e&&(Qs.state.layout=e,Qs.notify())}class Wc{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 Fy extends Wc{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const ln=new Map,ei=new Set;function Le(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.");ln.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),_("desktop-mode.files.type-registered",e.type,e),Bc()}function zy(e){ln.delete(e)&&(_("desktop-mode.files.type-unregistered",e),Bc())}function jy(e){const t=ln.get(e);return t||null}function Uc(){const e=Array.from(ln.values()).slice(),t=z("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 _o(e){const t=ln.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new Fy(e,e.type)}function Gy(e){return ei.add(e),()=>ei.delete(e)}function Bc(){for(const e of ei)try{e()}catch(t){console.error("[desktop-mode] files registry subscriber threw:",t)}}const Eo=new Map,ti=new Set;let ni={};function Hc(e){ni={...e},ri()}function oi(){return{...ni}}function Te(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.");Eo.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}),_("desktop-mode.files.opener-registered",e.id,e),ri()}function qy(e){Eo.delete(e)&&(_("desktop-mode.files.opener-unregistered",e),ri())}function Ky(e){return Eo.get(e)??null}function Fc(){const e=Array.from(Eo.values()).slice(),t=z("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 si(e){return Fc().filter(t=>t.types.includes(e))}function ii(e){const t=si(e);if(t.length===0)return null;const n=ni[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]),z("desktop-mode.files.resolve-opener",o,e)??null}function Vy(e){return ti.add(e),()=>ti.delete(e)}function ri(){for(const e of ti)try{e()}catch(t){console.error("[desktop-mode] openers subscriber threw:",t)}}let un=null;function Yy(e){un=e}async function ai(e,t){if(!un)return console.warn("[desktop-mode] wp.desktop.files.open() called before the shell installed open deps. The file will not open."),!1;const n=ii(e.type());if(!n)return _("desktop-mode.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;_("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):un.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),d=un.openUrl({id:i,url:s,title:r,icon:a});return _("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=un.openNativeWindow(o.windowId,s);return _("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),_("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return _("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 Xy(){Le({type:"shortcut",label:"Plugin shortcut",sort:1}),Le({type:"folder",label:"Folder",sort:5}),Le({type:"post",label:"Post",sort:10}),Le({type:"attachment",label:"Media",sort:20}),Le({type:"user",label:"User",sort:30}),Le({type:"term",label:"Taxonomy term",sort:40}),Le({type:"comment",label:"Comment",sort:50}),Le({type:"bookmark",label:"Bookmark",sort:60}),Le({type:"link",label:"Web link",sort:70}),Le({type:"embed",label:"Embedded web window",sort:80})}let di=null;function zc(e){di=e}function jc(){if(!di)throw new Error("[desktop-mode] files REST client called before installRestDeps().");return di}class ci 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 le(e,t){const{baseUrl:n,nonce:o}=jc(),s=eo(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 je(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 ci(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 Ae(e=0){return le(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function St(e){return le("/placements",{method:"POST",body:JSON.stringify(e)})}function Ct(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),le(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Gc(e){return le(`/placements/${e}`,{method:"DELETE"})}async function li(e,t){const{baseUrl:n,nonce:o}=jc(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await je(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 qc(){return le("/folders",{method:"GET"})}function ui(e){return le("/folders",{method:"POST",body:JSON.stringify(e)})}function Kc(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),le(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Vc(e){return le(`/folders/${e}`,{method:"DELETE"})}function Yc(e){return le("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function Xc(e){return le(`/folders/${e}/shares`,{method:"GET"})}function Zc(e,t){return le(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function Jc(e,t,n){return le(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function Qc(e,t){return le(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function el(e,t){return le(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function tl(e,t){return le(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function nl(e){return le(`/folders/${e}/leave`,{method:"POST"})}function Zy(){return le("/folder-sharing-tables/purge",{method:"POST"})}const Jy=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:ci,acceptShare:el,createFolder:ui,createPlacement:St,deleteFolder:Vc,deletePlacement:Gc,denyShare:tl,installRestDeps:zc,inviteShare:Zc,leaveShare:nl,listFolders:qc,listPlacements:Ae,listShares:Xc,purgeFolderSharingTables:Zy,restoreTrashedItem:li,revokeShare:Qc,saveAssociations:Yc,updateFolder:Kc,updatePlacement:Ct,updateShareCapability:Jc},Symbol.toStringTag,{value:"Module"})),Qy="desktop-mode/files";function We(){return re(Qy,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function At(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("desktop-mode-files-changed",{detail:{source:"local",...e}}))}function xt(e,t){const n=We(),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(),At({kind:"placements-set",folderId:e})}function pi(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=We(),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(),At({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function So(e,t="local"){const n=We(),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(),At({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function ol(e){const t=We(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),At({kind:"folders-set"})}function fi(e,t="local"){const n=We(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),At({kind:"folder-upserted",folderRowId:e.id,source:t})}function mi(e,t="local"){const n=We(),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(),At({kind:"folder-removed",folderRowId:e,source:t})}function hi(e){return We().subscribe(e)}function ot(){return We().getState()}const V={getState:ot,subscribe:hi,setFolderPlacements:xt,upsertPlacement:pi,upsertFolder:fi,removePlacement:So,removeFolder:mi},eb=ge`:host{display:inline-block}`,tb=ge`: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 )}`,Dn=class Dn extends ce{render(){return B`<span class="banner" part="banner"><slot></slot></span>`}};Dn.props=["placement","tone"],Dn.styles=[tb],Dn.help=void 0;let wi=Dn;we("wpd-ribbon",wi);const Q="desktop-mode-file-tile",sl={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function nb(){const e=window.wp?.desktop?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function ob(){return window.wp?.desktop?.dragManager??null}const sb=["type","ref","label","icon","thumbnail","kind","status","selected","missing","access-gated","drag-kind","drag-title","drag-icon"],Rt=class Rt extends ce{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 B``}_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=[Q,`${Q}--folder`,`${Q}--missing`,`${Q}--access-gated`,`${Q}--selected`];for(const w of u)this.classList.remove(w);this.classList.add(Q),r==="folder"&&this.classList.add(`${Q}--folder`),c&&this.classList.add(`${Q}--missing`),l&&this.classList.add(`${Q}--access-gated`),d&&this.classList.add(`${Q}--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=[`${Q}__visual`,`${Q}__label`,`${Q}__lock`];for(const w of f)this.querySelectorAll(`:scope > .${w}`).forEach(g=>g.remove());this.querySelectorAll(":scope > wpd-ribbon").forEach(w=>w.remove());const b=document.createElement("span");if(b.className=`${Q}__visual`,i){const w=document.createElement("img");w.src=i,w.alt="",w.loading="lazy",w.decoding="async",w.className=`${Q}__preview`,w.draggable=!1,b.appendChild(w)}else if(s){const w=Rs(s,{title:o,className:`${Q}__icon`});b.appendChild(w)}this.appendChild(b);const m=document.createElement("span");if(m.className=`${Q}__label`,m.textContent=o,this.appendChild(m),l){const w=document.createElement("span");w.className=`${Q}__lock dashicons dashicons-lock`,w.setAttribute("aria-hidden","true"),this.appendChild(w)}if(a&&a!=="publish"&&sl[a]&&nb()){const w=document.createElement("wpd-ribbon");w.setAttribute("placement","top-end"),w.setAttribute("tone",ib(a)),w.textContent=sl[a],this.appendChild(w)}op(this),_("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=ob();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)}};Rt.shadow=!1,Rt.props=sb,Rt.styles=[eb],Rt.help=void 0;let gi=Rt;function ib(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}we("wpd-tile",gi);function rb(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=z("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 ab(e,t){const n=_o(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 db(e,t){const n=_o(e.file),o=rb(ab(e,t)),s=z("desktop-mode.files.tile-class",Q,e);s&&s!==Q&&(o.className=s);const i=z("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){X({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}ai(n,{placement:{id:e.id,x:e.x,y:e.y,meta:e.meta}})}),_("desktop-mode.files.tile-rendered",{tile:o,placement:e}),o}function It(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}function il(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 cb="desktop-mode-wallpaper-menu";let pn=null;function yi(){pn&&(pn.dispatchEvent(new CustomEvent("tile-menu-closed")),pn.remove(),pn=null,_("desktop-mode.files.tile-menu.closed",{}))}let rl=0;function lb(e,t){yi();const n=++rl;$t(()=>n===rl,()=>ub(e,t))}function ub(e,{placement:t,items:n}){const o=z("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(cb),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",pb(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&&(yi(),u.onClick(new MouseEvent("click")))}),document.body.appendChild(i),pn=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=il(i,{close:()=>yi()});i.addEventListener("tile-menu-closed",d),_("desktop-mode.files.tile-menu.opened",{placementId:t.id,items:s.map(c=>c.id)})}function pb(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const fe="desktop-mode-create-folder-dialog";let fn=null;function bi(){fn&&(fn.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),fn.remove(),fn=null,_("desktop-mode.files.create-folder.closed",{}))}function vi(e){if(bi(),z("desktop-mode.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${fe}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=fe,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${fe}-title`);const i=document.createElement("h2");i.id=`${fe}-title`,i.className=`${fe}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("label");r.className=`${fe}__label`,r.htmlFor=`${fe}-input`,r.textContent=e.label??"Folder name",s.appendChild(r);const a=document.createElement("input");a.type="text",a.id=`${fe}-input`,a.className=`${fe}__input`,a.value=n,a.setAttribute("autocomplete","off"),a.setAttribute("spellcheck","false"),s.appendChild(a);const d=document.createElement("p");d.className=`${fe}__error`,d.hidden=!0,d.setAttribute("role","alert"),s.appendChild(d);const c=document.createElement("div");c.className=`${fe}__actions`;const l=document.createElement("button");l.type="button",l.className=`${fe}__btn ${fe}__btn--secondary`,l.textContent="Cancel";const u=document.createElement("button");u.type="button",u.className=`${fe}__btn ${fe}__btn--primary`,u.textContent=e.submitLabel??"Create",c.appendChild(l),c.appendChild(u),s.appendChild(c),o.appendChild(s),document.body.appendChild(o),fn=o,a.focus(),a.select(),_("desktop-mode.files.create-folder.opened",{});const p=g=>{a.disabled=g,l.disabled=g,u.disabled=g,s.classList.toggle(`${fe}--busy`,g)},f=g=>{d.textContent=g,d.hidden=!1},b=()=>{bi(),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),bi()}catch(E){p(!1),f(E instanceof Error?E.message:"Could not create the folder."),a.focus(),a.select()}};l.addEventListener("click",()=>b()),u.addEventListener("click",()=>void m()),o.addEventListener("click",g=>{g.target===o&&b()});const w=g=>{g.key==="Escape"?(g.preventDefault(),b()):g.key==="Enter"&&!g.isComposing&&(g.preventDefault(),m())};s.addEventListener("keydown",w),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",w)})}const Ee=16,Ye=96,mn=110;function hn(e,t){const n=Math.max(0,Math.round((e-Ee)/Ye)),o=Math.max(0,Math.round((t-Ee)/mn));return Lt(n,o)}function Lt(e,t){return{col:e,row:t,x:Ee+e*Ye,y:Ee+t*mn}}function st(e,t,n,o){const s=hn(e,t);if(!n.has(me(s.col,s.row)))return s;const i=o?Math.max(1,Math.floor((o.clientHeight-Ee)/mn)):999;for(let r=0;r<999;r++)for(let a=0;a<i;a++)if(!n.has(me(r,a)))return Lt(r,a);return s}function al(e,t){const n=t?Math.max(1,Math.floor((t.clientWidth-Ee)/Ye)):4,o=Math.max(1,n);for(let s=0;s<999;s++)for(let i=0;i<o;i++)if(!e.has(me(i,s)))return Lt(i,s);return Lt(0,0)}function dl(e,t){const n=new Set;for(const o of e){const s=hn(o.x,o.y);n.add(me(s.col,s.row))}return n}function me(e,t){return`${e},${t}`}function cl(e){return e instanceof ci}function fb(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 ll(e){const t=fb(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)}}),X({message:t,action:o,duration:7e3})}function Co(e,t,n){window.wp?.desktop?.broadcast?.(`desktop-mode.${e}.changed`,{source:"desktop-files",action:t,ids:n})}function ul(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 pl(e,t){const n=window.wp?.desktop;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function fl(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";V.removePlacement(t);try{await Gc(t),Co(s,"trashed",[t]),pl(`"${o}" moved to Trash`,async()=>{try{await li(t,"placement");const i=await Ae(n);V.setFolderPlacements(n,i.placements),Co(s,"untrashed",[t])}catch(i){console.error("[desktop-mode] restore failed:",i)}})}catch(i){console.error("[desktop-mode] deletePlacement failed:",i),ul(i),Ae(n).then(r=>{V.setFolderPlacements(n,r.placements)})}}async function ml(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";V.removePlacement(n),V.removeFolder(t);try{await Vc(t),Co("folder","trashed",[t]),pl(`"${s}" moved to Trash`,async()=>{try{await li(t,"folder");const i=await Ae(o);V.setFolderPlacements(o,i.placements),Co("folder","untrashed",[t])}catch(i){console.error("[desktop-mode] restore folder failed:",i)}})}catch(i){console.error("[desktop-mode] deleteFolder failed:",i),ul(i),Ae(o).then(r=>{V.setFolderPlacements(o,r.placements)})}}function mb(e){return e.file?.type==="folder"?ml(e):fl(e)}function hb(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 wn(){return window.wp?.desktop?.dragManager??null}const wb="desktop-mode-files-layer";function hl(e,t=0){const n=document.createElement("div");n.className=wb,n.setAttribute("role","list"),n.dataset.folderId=String(t),e.appendChild(n);let o="",s=null;const i=new Set,r=x=>{for(const W of i)try{W(x)}catch(M){console.error("[desktop-mode] files: selection listener threw:",M)}},a=x=>{const W=x?x.id:null;W!==s&&(n.querySelectorAll(`.${Q}--selected`).forEach(M=>M.removeAttribute("selected")),x&&n.querySelector(`[data-placement-id="${x.id}"]`)?.setAttribute("selected",""),s=W,r(x))},d=x=>{const M=(x.placementsByFolder.get(t)??[]).slice().sort((U,N)=>{const H=Se(U)?0:1,K=Se(N)?0:1;return H-K}),j=gb(M);if(j===o||(o=j,vb(M,n,e)))return;n.replaceChildren();for(const[,U]of l)try{U()}catch{}l.clear();for(const[,U]of u)try{U()}catch{}u.clear();const Y=new Map,oe=new Set;let se=0;for(const U of M){if(!Se(U))continue;const N=Lt(0,se);Y.set(U.id,{x:N.x,y:N.y}),oe.add(me(N.col,N.row)),se+=1}const F=new Map;for(const U of M){if(Y.has(U.id))continue;const N=hn(U.x,U.y),H=me(N.col,N.row);if(!oe.has(H)){oe.add(H);continue}const K=st(U.x,U.y,oe,e);oe.add(me(K.col,K.row)),F.set(U.id,{x:K.x,y:K.y})}for(const U of M){const N=db(U,t),H=Y.get(U.id);if(H){if(It(N,H.x,H.y),N.classList.add(`${Q}--pinned`),yl(N,U),D(N,U),wl(U)){const Z=wn();if(Z){const ee=Z.registerDropTarget({id:`desktop-mode-files-tile-${U.id}-reject`,element:N,accept:()=>!1,onDrop:()=>{}});u.set(U.id,ee)}}n.appendChild(N);continue}const K=F.get(U.id);if(K&&It(N,K.x,K.y),Eb(N,U,t),yl(N,U),D(N,U),U.file.type==="folder"){const Z=parseInt(U.file.ref,10);if(Z>0){const ee=wn();if(ee){const dt=_b(ee,N,Z);l.set(U.id,dt)}}}else if(wl(U)){const Z=wn();if(Z){const ee=Z.registerDropTarget({id:`desktop-mode-files-tile-${U.id}-reject`,element:N,accept:()=>!1,onDrop:()=>{}});u.set(U.id,ee)}}n.appendChild(N)}s!==null&&!n.querySelector(`[data-placement-id="${s}"]`)?(s=null,r(null)):s!==null&&n.querySelector(`[data-placement-id="${s}"]`)?.setAttribute("selected",""),_("desktop-mode.files.grid-rendered",{folderId:t,count:M.length})},c=[],l=new Map,u=new Map;let p=null,f=null;const b=x=>{if(p||x.payload.type!=="desktop-file")return;const W=document.createElement("div");W.className="desktop-mode-files-drop-preview",W.setAttribute("aria-hidden","true"),n.appendChild(W),p=W;const M=x.payload.ghost,j=M?.offsetX??0,Y=M?.offsetY??0,se=x.payload.data?.placement?.id,F=(H,K)=>{const Z=n.getBoundingClientRect(),ee=Math.max(0,H-Z.left-j),dt=Math.max(0,K-Z.top-Y),Bo=V.getState().placementsByFolder.get(t)??[],Xi=Ao(Bo,se),ct=st(ee,dt,Xi,e);W.style.transform=`translate3d(${ct.x}px, ${ct.y}px, 0)`},U=x.payload.source.getBoundingClientRect();F(U.left+j,U.top+Y);const N=H=>{F(H.clientX,H.clientY)};document.addEventListener("pointermove",N),f=N},m=()=>{f&&(document.removeEventListener("pointermove",f),f=null),p&&(p.remove(),p=null)},w={id:`desktop-mode-files-canvas-${t}`,element:e,accept:x=>{if(x.type!=="desktop-file"&&x.type!=="shortcut")return!1;if(t>0&&x.type==="desktop-file"){const W=x.data;if(W.placement.file?.type==="folder"){const M=parseInt(W.placement.file.ref,10);if(!Number.isNaN(M)&&gl(M,t))return!1}}return!0},onEnter:x=>{e.setAttribute("data-files-drop-active",""),b(x)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),m()},onDrop:(x,W)=>{e.removeAttribute("data-files-drop-active"),m();const M=n.getBoundingClientRect(),j=x.payload.ghost,Y=j?.offsetX??0,oe=j?.offsetY??0,se=Math.max(0,W.clientX-M.left-Y),F=Math.max(0,W.clientY-M.top-oe),U=V.getState().placementsByFolder.get(t)??[];if(x.payload.type==="desktop-file"){const N=x.payload.data,H=Ao(U,N.placement.id),K=st(se,F,H,e),Z={...N.placement,x:K.x,y:K.y,parentId:t};if(V.upsertPlacement(Z),_("desktop-mode.files.tile-manually-placed",{folderId:t,placementId:N.placement.id}),_i(N.placement)){const ee=ki(N.placement);ee&&bb(ee,K.x,K.y);return}Ct(N.placement.id,{x:K.x,y:K.y,parentId:t},N.placement.updatedAtMs).then(ee=>{V.upsertPlacement(ee,"remote")}).catch(ee=>{cl(ee)?ll(ee):console.error("[desktop-mode] files: drag persist failed",ee),V.upsertPlacement(N.placement)});return}if(x.payload.type==="shortcut"){const N=x.payload.data,H=Ao(U),K=al(H,e);St({parentId:t,type:N.kind,ref:N.ref,x:K.x,y:K.y}).then(Z=>{V.upsertPlacement(Z),_("desktop-mode.files.shortcut-dropped",{folderId:t,placement:Z})}).catch(Z=>{console.error("[desktop-mode] shortcut drop failed:",Z)})}}},g=wn();g&&c.push(g.registerDropTarget(w));const E=x=>{x.target instanceof Element&&x.target.closest(`.${Q}`)||a(null)};e.addEventListener("click",E);function D(x,W){x.addEventListener("click",M=>{M.stopPropagation(),a(W)})}d(V.getState());const y=V.subscribe(d);let S=()=>{};const h=new Promise(x=>{S=x});V.getState().hydratedFolders.has(t)?queueMicrotask(S):Ae(t).then(x=>{V.setFolderPlacements(t,x.placements)}).catch(x=>{console.error("[desktop-mode] files: failed to hydrate folder",t,x)}).finally(()=>{S()});const L=()=>{const x=e.clientWidth>0?e.clientWidth:4*Ye;return Math.max(1,Math.floor((x-Ee)/Ye))},C=(x,W)=>{const M=x.slice();switch(W){case"name-asc":M.sort((j,Y)=>j.file.title.localeCompare(Y.file.title));break;case"name-desc":M.sort((j,Y)=>Y.file.title.localeCompare(j.file.title));break;case"date-asc":M.sort((j,Y)=>j.updatedAtMs-Y.updatedAtMs);break;case"date-desc":M.sort((j,Y)=>Y.updatedAtMs-j.updatedAtMs);break}return M},T=x=>{const W=V.getState().placementsByFolder.get(t);if(!W||W.length===0)return;const M=W.filter(N=>Se(N)),j=W.filter(N=>!Se(N)),Y=C(j,x),oe=L(),se=new Set;for(let N=0;N<M.length;N+=1)se.add(me(0,N));let F=0;const U=()=>{for(;;){const N=Math.floor(F/oe),H=F%oe;if(F+=1,!se.has(me(H,N)))return{col:H,row:N}}};Y.forEach((N,H)=>{const K=U(),Z=Ee+K.col*Ye,ee=Ee+K.row*mn,dt={...N,x:Z,y:ee,sortOrder:H};V.upsertPlacement(dt),!_i(N)&&Ct(N.id,{x:Z,y:ee,sortOrder:H}).catch(Bo=>{console.error("[desktop-mode] files: sort persist failed",Bo)})})},I=()=>{const x=V.getState().placementsByFolder.get(t);if(!x||x.length===0)return;const W=e.clientWidth>0?e.clientWidth:1/0;if(!x.some(N=>N.x+Ye>W))return;const j=L(),Y=x.filter(N=>Se(N)),oe=x.filter(N=>!Se(N)),se=new Set;for(let N=0;N<Y.length;N+=1)se.add(me(0,N));let F=0;const U=()=>{for(;;){const N=Math.floor(F/j),H=F%j;if(F+=1,!se.has(me(H,N)))return{col:H,row:N}}};for(const N of oe){const H=U(),K=Ee+H.col*Ye,Z=Ee+H.row*mn,ee=n.querySelector(`[data-placement-id="${N.id}"]`);ee&&It(ee,K,Z)}};let k=e.clientWidth,R=null;return typeof ResizeObserver<"u"&&(R=new ResizeObserver(()=>{const x=e.clientWidth;x!==k&&(k=x,I())}),R.observe(e)),{host:e,folderId:t,onSelectionChange(x){return i.add(x),()=>{i.delete(x)}},sort:T,reflow:I,hydrated:h,dispose(){y(),R?.disconnect(),R=null;for(const x of c)try{x()}catch{}c.length=0;for(const x of l.values())try{x()}catch{}l.clear();for(const x of u.values())try{x()}catch{}u.clear(),e.removeEventListener("click",E),i.clear(),n.remove()}}}function gb(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}:${Se(n)?1:0}`);return t.join("|")}function Se(e){return!!e.file.pinned}function ki(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function _i(e){return e.id<=0||ki(e)!==null}const yb="desktop-mode-recycle-bin";function wl(e){return!(e.file?.type==="folder"||e.file?.ref===yb)}function Ao(e,t){const n=e.slice().sort((i,r)=>{const a=Se(i)?0:1,d=Se(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(Se(i))o.add(me(0,s)),s+=1;else{const r=hn(i.x,i.y);o.add(me(r.col,r.row))}return o}function gl(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=V.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 bb(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 vb(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(`${Q}--pinned`)!==Se(c))return!1}const i=new Map,r=new Set;let a=0;for(const c of e){if(!Se(c))continue;const l=Lt(0,a);i.set(c.id,{x:l.x,y:l.y}),r.add(me(l.col,l.row)),a+=1}const d=new Map;for(const c of e){if(i.has(c.id))continue;const l=hn(c.x,c.y),u=me(l.col,l.row);if(!r.has(u)){r.add(u);continue}const p=st(c.x,c.y,r,n);r.add(me(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?It(l,u.x,u.y):p?It(l,p.x,p.y):It(l,c.x,c.y)}return!0}function kb(e){const t=window.wp?.desktop;if(!t?.getOsSettings||!t?.updateOsSettings)return;const o={...t.getOsSettings().itemVisibility??{},[e]:"dock"};t.updateOsSettings({itemVisibility:o})}function _b(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||_i(r.placement))return!1;if(r.placement.file.type==="folder"){const a=parseInt(r.placement.file.ref,10);if(!Number.isNaN(a)&&gl(a,n))return!1}}return!0},onEnter:()=>{t.classList.add(`${Q}--drop-target`)},onLeave:()=>{t.classList.remove(`${Q}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${Q}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a={...r.placement,parentId:n};V.upsertPlacement(a),Ct(r.placement.id,{parentId:n},r.placement.updatedAtMs).then(d=>{V.upsertPlacement(d,"remote")}).catch(d=>{cl(d)?ll(d):console.error("[desktop-mode] files: move-into-folder persist failed",d),V.upsertPlacement(r.placement)});return}if(i.payload.type==="shortcut"){const r=i.payload.data,a=V.getState().placementsByFolder.get(n)??[],d=al(Ao(a));St({parentId:n,type:r.kind,ref:r.ref,x:d.x,y:d.y}).then(c=>{V.upsertPlacement(c),_("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 Eb(e,t,n){e.addEventListener("pointerdown",o=>{if(o.button!==0)return;const s=wn();if(!s)return;const r=V.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:hb(r)},ghost:{offsetX:o.clientX-e.getBoundingClientRect().left,offsetY:o.clientY-e.getBoundingClientRect().top}},origin:o})})}function yl(e,t){e.addEventListener("contextmenu",n=>{n.preventDefault(),n.stopPropagation();const o=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,onClick:()=>{const i=_o(t.file);ai(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&&vi({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}};V.upsertPlacement(c);try{const l=V.getState().folders.get(i)?.updatedAtMs??0,u=await Kc(i,{name:a},l);V.upsertFolder(u);const p=await Ae(t.parentId);V.setFolderPlacements(t.parentId,p.placements)}catch(l){console.error("[desktop-mode] rename folder failed:",l),V.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:()=>ml(t)});else{const i=ki(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:()=>kb(a)})}else t.canTrash!==!1&&o.push({id:"remove",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,onClick:()=>fl(t)})}lb({x:n.clientX,y:n.clientY},{placement:t,items:o})})}const Tt="desktop-mode-folder-status-bar";function Sb(e,t){const n=document.createElement("div");n.className=Tt,n.setAttribute("role","status"),n.dataset.folderId=String(t),e.appendChild(n);const o=()=>{const i=ot().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=Cb(d);Ab(n,c)};o();const s=hi(()=>o());return{dispose(){s(),n.remove()}}}function Cb(e){const{folders:t,files:n}=e.totals,o=[{id:"count",label:vl(n,"file","files")+(t>0?`, ${vl(t,"folder","folders")}`:""),align:"start",sort:10}],s=z("desktop-mode.files.folder-window.status-bar",o,e);return Array.isArray(s)?s:o}function Ab(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(bl("start",o)),e.appendChild(bl("end",s))}function bl(e,t){const n=document.createElement("div");n.className=`${Tt}__cluster ${Tt}__cluster--${e}`;for(const o of t)n.appendChild(xb(o));return n}function xb(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${Tt}__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=`${Tt}__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=`${Tt}__label`,o.textContent=e.label,n.appendChild(o),n}function vl(e,t,n){return`${e} ${e===1?t:n}`}const xo="desktop-mode-icon-canvas-menu";let gn=null,Io=null,Ei=null,yn=null,bn=null;function Ib(e,t){t.openOnBackgroundClick;const n=i=>{Lb(i.target)||kl(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(Ei===e&&gn){it();return}const a=Tb(t),d=z("desktop-mode.icon-canvas.menu",a,t.scope),c=Array.isArray(d)?d:a,l=++o;$t(()=>l===o,()=>Nb(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),it()}}}function Lb(e){return e instanceof Element?e.closest(".desktop-mode-file-tile")!==null:!1}function kl(e){return e instanceof Element?e.closest(`.${xo}`)!==null:!1}function Tb(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 _l(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 Nb(e,t,n){if(it(),e.length===0)return;Ei=n;const o=_l(e),s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(xo),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=El(s,r);Lo(r)&&a.addEventListener("mouseenter",()=>{Sl(r,a)})}s.addEventListener("wpd-context-menu-pick",r=>{const a=r.detail,d=i.get(a.id);if(d){if(Lo(d)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${d.id}"]`);c&&Sl(d,c);return}it(),d.onClick?.()}}),document.body.appendChild(s),gn=s,Ob(s),queueMicrotask(()=>{yn=r=>{kl(r.target)||it()},bn=r=>{r.key==="Escape"&&it()},document.addEventListener("mousedown",yn),document.addEventListener("keydown",bn)})}function El(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",Rb(t.icon)),Lo(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function Sl(e,t){if(Cl(),!Lo(e))return;const n=document.createElement("wpd-context-menu");n.setAttribute("open",""),n.classList.add(xo,`${xo}--flyout`);const o=new Map;for(const s of _l(e.children??[]))o.set(s.id,s),El(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),Io=n,Db(n,t)}function Db(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 Ob(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 Lo(e){return Array.isArray(e.children)&&e.children.length>0}function Cl(){Io&&(Io.remove(),Io=null)}function it(){Cl(),gn&&(gn.remove(),gn=null),Ei=null,yn&&(document.removeEventListener("mousedown",yn),yn=null),bn&&(document.removeEventListener("keydown",bn),bn=null)}function Rb(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const rt="desktop-mode-breadcrumbs";function Mb(e,t,n={}){if(e.replaceChildren(),e.classList.add(rt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${rt}__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=`${rt}__crumbs`,o.setAttribute("aria-label",O("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const d=document.createElement("span");d.className=`${rt}__sep`,d.setAttribute("aria-hidden","true"),d.textContent="›",o.appendChild(d)}if(!s.onClick){const d=document.createElement("span");d.className=`${rt}__crumb ${rt}__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=`${rt}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}async function vn(e,t={}){const n=await je(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":Pb(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function Pb(){return window.wp?.desktop?.config?.restNonce??""}function $b(){const e=window.wp?.desktop?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function kn(e){return eo($b(),e)}function Wb(e,t){const n=z("desktop-mode.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(Ub(e));return}t.replaceChildren(Yb()),Bb(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(Xb(o))})}function Ub(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 Bb(e){const t=e.file;switch(t.type){case"post":return Hb(t.ref,t);case"folder":return qb(t);case"shortcut":return Kb(t);case"attachment":return Gb(t.ref,t);case"user":return Fb(t.ref,t);case"term":return zb(t);case"comment":return jb(t.ref,t);case"bookmark":return Vb(t);default:return Ne(t)}}async function Hb(e,t){const n=parseInt(e,10);if(!n)return Ne(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await vn(kn(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return Ne(t);const s=Ue(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=To(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(Al(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:To(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:To(o.title.rendered),icon:t.icon})}),d.appendChild(l),s.appendChild(d),s}async function Fb(e,t){const n=parseInt(e,10);if(!n)return Ne(t);let o=null;try{o=await vn(kn(`desktop-mode/v1/user-stats/${n}`))}catch{return Ne(t)}const s=Ue("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(Nt(o.counts.posts.total.toLocaleString(),O("Posts","desktop-mode"))),d.appendChild(Nt(o.counts.pages.total.toLocaleString(),O("Pages","desktop-mode"))),d.appendChild(Nt(o.counts.commentsReceived.toLocaleString(),O("Comments received","desktop-mode"))),s.appendChild(d),s}async function zb(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return Ne(e);let o=null;try{o=await vn(kn(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return Ne(e)}const s=Ue(),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(Nt(o.counts.posts.total.toLocaleString(),O("Posts","desktop-mode"))),a.appendChild(Nt(o.counts.commentsReceived.toLocaleString(),O("Comments","desktop-mode"))),a.appendChild(Nt(o.counts.distinctAuthors.toLocaleString(),O("Authors","desktop-mode"))),s.appendChild(a),s}async function jb(e,t){const n=parseInt(e,10);if(!n)return Ne(t);let o=null;try{o=await vn(kn(`desktop-mode/v1/comment-stats/${n}`))}catch{return Ne(t)}const s=Ue(),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=`${Al(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 Gb(e,t){const n=parseInt(e,10);if(!n)return Ne(t);let o=null;try{o=await vn(kn(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return Ne(t)}const s=Ue(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=To(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 qb(e){const t=Ue(),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 Kb(e){const t=Ue(),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 Vb(e){const t=Ue(),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 Ne(e){const t=Ue(),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=te(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 Ue(e=""){const t=document.createElement("article");return t.className="desktop-mode-my-wordpress__article"+(e?" "+e:""),t}function Nt(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 Yb(){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 Xb(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 To(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function Al(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function xl(){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 No="desktop-mode-embed-",Zb=800,Jb=600,Si=360,Ci=240,Do=16,Ai=new Map;function Qb(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?`${No}${s.id}`:`${No}anon-${ov(n)}`,a=i?.name?.trim()??"",d=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:d,icon:e.icon(),minWidth:Si,minHeight:Ci},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:b,y:m,width:w,height:g}=nv(l,p,f);c.x=b,c.y=m,c.width=w,c.height=g}else c.width=Math.min(Zb,Math.max(Si,p-Do*2)),c.height=Math.min(Jb,Math.max(Ci,f-Do*2));s&&l&&Ai.set(r,{...l}),o.open(c)}let Il=!1;function ev(){if(Il)return;Il=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(No))return;const s=o.slice(No.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=Ai.get(o);l&&l.x===c.x&&l.y===c.y&&l.width===c.width&&l.height===c.height||(Ai.set(o,c),tv(i,c))};q(v.WINDOW_DRAG_END,"desktop-mode-embed-persist",e),q(v.WINDOW_RESIZE_END,"desktop-mode-embed-persist",e)}async function tv(e,t){try{const i={...(await Ae(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await Ct(e,{meta:i})}catch(n){console.warn("[desktop-mode] embed window persist failed:",n)}}function nv(e,t,n){const o=Math.max(Si,Math.min(e.width,t-Do)),s=Math.max(Ci,Math.min(e.height,n-Do)),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 ov(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 _n(){const t=window.wp?.desktop?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function sv(){Te({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_n()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Te({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_n()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Te({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_n()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),Te({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`${_n()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Te({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_n()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),Te({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=V.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 b=()=>{const w=l.map((g,E)=>E===l.length-1?{label:g.title}:{label:g.title,onClick:()=>{l.length=E+1,m()}});Mb(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 E=document.createElement("div");E.className="desktop-mode-folder-window__preview",E.appendChild(xl()),w.appendChild(E);const D=l[l.length-1],y=hl(g,D.folderId),S=y.onSelectionChange(T=>{if(!T){E.replaceChildren(xl());return}Wb(T,E)}),h=T=>{if(!(T.target instanceof Element))return;const I=T.target.closest(".desktop-mode-file-tile");if(!I||I.dataset.fileType!=="folder")return;const k=parseInt(I.dataset.fileRef??"",10);if(!k)return;T.preventDefault(),T.stopPropagation();const R=I.querySelector(".desktop-mode-file-tile__label")?.textContent??`#${k}`;l.push({folderId:k,title:R}),m()};g.addEventListener("dblclick",h,!0);const L=Ib(g,{scope:`desktop-mode-folder:${D.folderId}`,onSort:T=>y.sort(T),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{vi({onSubmit:async T=>{const I=await ui({name:T}),k=V.getState().placementsByFolder.get(D.folderId)??[],R=dl(k),x=st(Ee,Ee,R,g),W=await St({type:"folder",ref:String(I.id),parentId:D.folderId,x:x.x,y:x.y});V.upsertFolder(I),V.upsertPlacement(W)}})}}]}),C=Sb(f,D.folderId);u=()=>{S(),L.dispose(),C.dispose(),g.removeEventListener("dblclick",h,!0),y.dispose()},b()};m()},width:720,height:480,minWidth:360,minHeight:240})}}}),Te({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=`desktop-icon-${e.ref()}`;n.windowManager.open({id:s,baseId:s,url:o.toString(),title:e.title(),icon:e.icon()})}catch{}}}}}),Te({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=e.ref();t&&window.open(t,"_blank","noopener,noreferrer")}}}),Te({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=e.ref();t&&window.open(t,"_blank","noopener,noreferrer")}}}),Te({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{Qb(e,t)}}})}const iv="desktop-mode-file-associations";function rv(){Ra({id:iv,label:"File Associations",order:50,render(e){av(e)}})}function av(e){e.replaceChildren();const t=Uc();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=oi(),s=document.createElement("div");s.className="desktop-mode-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(dv(i.type,i.label,o));e.appendChild(s)}function dv(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=si(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=ii(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={...oi(),[e]:l};Hc(u),Yc(u).catch(p=>{console.error("[desktop-mode] saveAssociations failed:",p)})}),o.appendChild(d),o}let xi=null;function Be(){return xi||(xi=re("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set}))),xi}function cv(e,t){const n=Be();n.state.byFolder.set(e,t),n.notify()}function lv(e){if(!e||typeof e.folderId!="number")return;const t=Be(),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 uv(e,t){const n=Be(),o=n.state.byFolder.get(e)??[];n.state.byFolder.set(e,o.filter(s=>s.id!==t)),n.notify()}function pv(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 Ll(e){const t=Be(),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(pv(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 Tl(e,t={}){const n=Be();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 fv=ge`: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{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}`,Nl='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',On=class On extends ce{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(Nl)),o=Array.from(t.querySelectorAll(Nl));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 B`
58 <div class="dialog" tabindex="-1">
59 ${t?B`
60 <div class="header">
61 <h2 class="title">${t}</h2>
62 <div class="header-actions">
63 <slot name="header-actions"></slot>
64 ${n?B``:B`<button
65 type="button"
66 class="close"
67 aria-label="Close"
68 @click=${()=>this._cancel()}
69 >×</button>`}
70 </div>
71 </div>
72 `:B``}
73 <div class="body">
74 <slot></slot>
75 </div>
76 <div class="footer">
77 <slot name="footer"></slot>
78 </div>
79 </div>
80 `}};On.props=["open","title","size","mandatory"],On.styles=[fv],On.help=void 0;let Ii=On;we("wpd-modal",Ii);const mv=ge`: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}`,Rn=class Rn extends ce{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 je(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 B`<div class="empty">Searching…</div>`;if(this._phase==="error")return B`<div class="empty error">${this._error}</div>`;if(this._results.length===0){const t=this._query?"No matches.":"No users available.";return B`<div class="empty">${t}</div>`}return this._results.map(t=>B`
81 <button
82 type="button"
83 class="item"
84 role="option"
85 @mousedown=${n=>n.preventDefault()}
86 @click=${()=>this._pick(t)}
87 >
88 <img class="avatar" src=${t.avatarUrl} alt="" />
89 <div>
90 <div class="name">${t.name}</div>
91 <div class="slug">${t.slug}</div>
92 </div>
93 </button>
94 `)}render(){const t=this.getAttribute("placeholder")||"Search users…";return B`
95 <input
96 class="input"
97 type="search"
98 placeholder=${t}
99 autocomplete="off"
100 @input=${this._onInput}
101 @focus=${this._onFocus}
102 @blur=${this._onBlur}
103 .value=${this._query}
104 />
105 ${this._open?B`
106 <div class="dropdown" role="listbox" style=${this._dropdownStyle}>
107 ${this._dropdownContent()}
108 </div>
109 `:B``}
110 `}};Rn.props=["placeholder","exclude","endpoint"],Rn.styles=[mv],Rn.help=void 0;let Li=Rn;we("wpd-user-search",Li);const hv=ge`: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}`,Mn=class Mn extends ce{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 B`<span class="empty">No eligible roles.</span>`;const n=this._selectedSet();return B`
111 ${t.map(o=>{const s=n.has(o.slug);return B`
112 <button
113 type="button"
114 class="chip"
115 aria-pressed=${s?"true":"false"}
116 @click=${()=>this._onToggle(o.slug)}
117 >${o.name}</button>
118 `})}
119 `}};Mn.props=["selected","roles"],Mn.styles=[hv],Mn.help=void 0;let Ti=Mn;we("wpd-role-picker",Ti);const wv=ge`:host{display:inline-flex;padding:3px;background:var( --wpd-segmented-bg,rgba( 0,0,0,0.05 ) );border-radius:7px;gap:2px}`,gv=ge`: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}`,Pn=class Pn extends ce{render(){return this.setAttribute("role","radio"),B`
120 <button type="button" @click=${()=>this._onPick()}>
121 <slot></slot>
122 </button>
123 `}_onPick(){this.emit("wpd-segment-pick",{value:this.value})}};Pn.props=["value"],Pn.styles=[gv],Pn.help=void 0;let Ni=Pn;we("wpd-segment",Ni);const $n=class $n extends ce{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")}}),B`<slot></slot>`}};$n.props=["value","label"],$n.styles=[wv],$n.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:B`
124 <wpd-segmented value="md" label="Dock size">
125 <wpd-segment value="sm">Small</wpd-segment>
126 <wpd-segment value="md">Medium</wpd-segment>
127 <wpd-segment value="lg">Large</wpd-segment>
128 </wpd-segmented>
129 `};let Di=$n;we("wpd-segmented",Di);const yv=ge`: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: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}`,Wn=class Wn extends ce{render(){const t=this.disabled!==null,n=this.type||"button";return B`
130 <button part="button" type=${n} ?disabled=${t}>
131 <slot></slot>
132 </button>
133 `}};Wn.props=["variant","disabled","type","busy","fill-cell"],Wn.styles=[yv],Wn.help=void 0;let Oi=Wn;we("wpd-button",Oi);const bv=ge`: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}`,vv=ge`:host{display:flex;align-items:center;gap:12px;min-width:280px;max-width:420px;padding:10px 14px;background:#1d2327;color:#fff;border-radius:8px;box-shadow:0 8px 24px rgba( 0,0,0,0.2 ),0 2px 6px rgba( 0,0,0,0.1 );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}@media ( prefers-reduced-motion:reduce ){:host{transition-duration:0.01ms}}`,Uo=class Uo extends ce{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return B`<slot></slot>`}};Uo.styles=[bv],Uo.help=void 0;let Ri=Uo;we("wpd-toast-container",Ri);const Un=class Un extends ce{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status")}render(){const t=this.action||"";return B`
134 <span class="wpd-toast__label"><slot></slot></span>
135 <button
136 type="button"
137 ?hidden=${!t}
138 @click=${n=>this._onAction(n)}
139 >
140 ${t}
141 </button>
142 `}_onAction(t){t.preventDefault(),t.stopPropagation(),this.emit("wpd-toast-action",{})}};Un.props=["action","state"],Un.styles=[vv],Un.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.'}],slots:[{name:"(default)",description:"Message text."}],events:[{name:"wpd-toast-action",description:"Fires when the action button is clicked.",detail:"{}"}],example:B`
143 <wpd-toast state="in" action="Undo">Post moved to trash.</wpd-toast>
144 `};let Mi=Un;we("wpd-toast",Mi);function Dl(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 Ol(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 Rl(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(S=>S.principalType==="user").map(S=>S.principalRef).concat(o.filter(S=>S.kind==="user").map(S=>S.ref));u.setAttribute("exclude",p.join(",")),u.setAttribute("placeholder","Search users…"),u.addEventListener("wpd-user-pick",S=>{const h=S.detail;o.push({kind:"user",ref:String(h.user.id),label:h.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 b=document.createElement("div");b.textContent="Add roles",b.style.cssText="font-weight:600;",f.appendChild(b);const m=document.createElement("wpd-role-picker"),w=n.filter(S=>S.principalType==="role").map(S=>S.principalRef),g=o.filter(S=>S.kind==="role").map(S=>S.ref);if(m.setAttribute("selected",[...w,...g].join(",")),m.addEventListener("wpd-role-toggle",S=>{const h=S.detail,L=n.find(C=>C.principalType==="role"&&C.principalRef===h.slug);if(L){h.selected||r(L);return}if(h.selected){const C=(window.desktopModeConfig?.shareEligibleRoles??[]).find(T=>T.slug===h.slug);o.push({kind:"role",ref:h.slug,label:C?C.name:h.slug,cap:"read"})}else o=o.filter(C=>!(C.kind==="role"&&C.ref===h.slug));s()}),f.appendChild(m),t.appendChild(f),o.length>0){const S=document.createElement("div");S.style.cssText="border:1px dashed rgba(255,255,255,0.18);border-radius:8px;padding:10px;margin-bottom:14px;";const h=document.createElement("div");h.textContent="New invites (not sent yet)",h.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",S.appendChild(h);for(const C of o){const T=document.createElement("div");T.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const I=document.createElement("span");I.textContent=C.kind==="role"?`Role: ${C.label}`:C.label,I.style.flex="1",T.appendChild(I);const k=Dl(C.cap,x=>{C.cap=x});T.appendChild(k);const R=Ol("×",()=>{o=o.filter(x=>!(x.kind===C.kind&&x.ref===C.ref)),s()});T.appendChild(R),S.appendChild(T)}const L=document.createElement("wpd-button");L.setAttribute("variant","primary"),L.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,L.style.marginTop="8px",L.addEventListener("click",async()=>{if(o.length===0)return;L.setAttribute("busy",""),L.setAttribute("disabled","");const C=o.slice();let T=0,I=null;for(const k of C)try{await Zc(e.folderId,{principalType:k.kind,principalRef:k.ref,capability:k.cap}),T++}catch(R){I=R;break}T>0&&(o=o.slice(T));try{await i()}catch{}X(I?{message:`Could not send invites: ${I.message}`}:{message:T===1?"Invite sent.":`${T} invites sent.`}),L.removeAttribute("busy"),L.removeAttribute("disabled"),s()}),S.appendChild(L),t.appendChild(S)}const E=document.createElement("div");if(E.textContent="Who has access",E.style.cssText="font-weight:600;margin:8px 0 6px;",t.appendChild(E),n.length===0){const S=document.createElement("div");S.textContent="Only you can see this folder.",S.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(S)}else for(const S of n){const h=document.createElement("div");h.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const L=document.createElement("div");if(L.style.flex="1",L.textContent=S.principalType==="role"?`Role: ${S.displayName}`:S.displayName,S.state==="pending"){const k=document.createElement("span");k.textContent=" · pending",k.style.cssText="opacity:0.6;font-size:12px;",L.appendChild(k)}else if(S.state==="denied"){const k=document.createElement("span");k.textContent=" · denied",k.style.cssText="color:#d63638;font-size:12px;",L.appendChild(k)}h.appendChild(L);const C=S.capability==="write"?"write":"read",T=Dl(C,k=>{a(S,k)});h.appendChild(T);const I=Ol("×",()=>{r(S)},{danger:!0});h.appendChild(I),t.appendChild(h)}const D=document.createElement("div");D.setAttribute("slot","footer"),D.style.display="flex",D.style.justifyContent="flex-end",D.style.gap="10px",D.style.flexWrap="wrap";const y=document.createElement("wpd-button");y.setAttribute("variant","secondary"),y.textContent="Done",y.addEventListener("click",()=>t.remove()),D.appendChild(y),t.appendChild(D)},i=async()=>{try{n=(await Xc(e.folderId)).shares,cv(e.folderId,n)}catch(d){X({message:`Could not load shares: ${d.message}`})}s()},r=async d=>{try{await Qc(e.folderId,d.id),uv(e.folderId,d.id),await i(),X({message:"Access revoked."})}catch(c){X({message:`Could not revoke: ${c.message}`})}},a=async(d,c)=>{try{const l=await Jc(e.folderId,d.id,c);lv(l),await i()}catch(l){X({message:`Could not update capability: ${l.message}`})}};t.addEventListener("wpd-modal-cancel",()=>t.remove()),s(),await i()}function kv(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=`
145 <p style="margin: 0 0 12px;">Accept the invite to add this folder to your desktop.</p>
146 <p style="margin: 0; opacity: 0.75;">Access level: <strong>${s}</strong></p>
147 `,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 tl(e.folderId,e.id),Be().state.deniedFolders.add(e.folderId),Be().notify(),n.remove(),t("denied")}catch(c){X({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 el(e.folderId,e.id);try{const c=await Ae(0);xt(0,c.placements)}catch{}n.remove(),t("accepted")}catch(c){X({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 Ml(){return Number(window.desktopModeConfig?.currentUserId??0)}function Pl(){const e=window.wp?.desktop?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function $l(e){const t=ot().folders.get(e);return t?Number(t.ownerId):0}function Wl(e){if(typeof e!="string")return null;const t=/^desktop-mode-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function _v(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function Ev(e){return Number(e.file.ownerId??0)}function Sv(){fu("desktop-mode.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!Pl())return e;const n=_v(t);if(n===null)return e;const o=$l(n)||Ev(t),s=Ml();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:()=>{Rl({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 ga({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 nl(n),So(t.id);try{const d=await Ae(0);xt(0,d.placements)}catch{}const r=`desktop-mode-folder-${n}`;window.desktopMode?.windowManager?.close?.(r),X({message:"You left the shared folder."})}catch(r){X({message:`Could not leave: ${r.message}`})}}});return e}),Ua({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!Pl())return!1;const t=e.config.baseId??e.id,n=Wl(t);return n===null?!1:$l(n)===Ml()},onClick:e=>{const t=e.config.baseId??e.id,n=Wl(t);n!==null&&Rl({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),q("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 Ul=new Set;function Cv(){const e=window.wp?.desktop?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function Av(){const e=Be(),t=n=>{if(Cv())for(const o of n.pending)Ul.has(o.id)||(Ul.add(o.id),kv({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Tl(o.id):s==="denied"&&Tl(o.id,{denied:!0,folderId:o.folderId})}))};e.subscribe(t),t(e.state)}Xy(),sv(),ev(),rv(),Sv();const Pi=window.desktopModeConfig?.serverPendingShares;Array.isArray(Pi)&&Pi.length>0&&Ll(Pi),Av();const Ce={DesktopFile:Wc,registerType:Le,unregisterType:zy,getType:jy,getTypes:Uc,resolve:_o,subscribe:Gy,registerOpener:Te,unregisterOpener:qy,getOpener:Ky,getOpeners:Fc,getOpenersForType:si,resolveOpener:ii,subscribeOpeners:Vy,getUserAssociations:oi,open:ai,rest:Jy,store:{get:We,getState:ot,subscribe:hi,setFolderPlacements:xt,upsertPlacement:pi,removePlacement:So,setFolders:ol,upsertFolder:fi,removeFolder:mi}},Bl="__synthFromDockItem";function xv(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function Iv(e,t){const n=t[e.id];return{id:xv(e.id),parentId:0,x:n?n.x:0,y:n?n.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Bl]:e.id},file:{type:"shortcut",ref:`dock-promoted:${e.id}`,title:e.title,icon:e.icon,previewUrl:"",exists:!0,shortcutUrl:e.url}}}function Lv(){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??[]})):window.desktopModeConfig?.dockItems??[]}function Tv(){return window.desktopModeConfig?.desktopIcons??[]}let $i=!1;const Wi=new Map;function Ui(e,t={}){if(!$i){$i=!0;try{const n=Lv(),o=Tv(),i=Ce.store.getState().placementsByFolder.get(0)??[],r=new Map;for(const l of i){const u=(l.meta??null)&&typeof l.meta=="object"?l.meta[Bl]:null;typeof u=="string"&&r.set(u,l)}const a=new Map,d=new Set(o.map(l=>l.id));for(const l of i){const u=l?.file?.ref;typeof u=="string"&&d.has(u)&&a.set(u,l)}const c=new Set;for(const l of n){const u=e[l.id];(u==="desktop"||u==="both")&&(c.add(l.id),r.has(l.id)||Ce.store.upsertPlacement(Iv(l,t)))}for(const[l,u]of r)c.has(l)||Ce.store.removePlacement(u.id);for(const l of o){const u=e[l.id],p=a.get(l.id);if(u==="dock"||u==="hidden"){p&&(Wi.set(l.id,p),Ce.store.removePlacement(p.id));continue}if(!p){const f=Wi.get(l.id);f&&(Ce.store.upsertPlacement(f),Wi.delete(l.id))}}}finally{$i=!1}}}function Nv(e,t=()=>({})){return queueMicrotask(()=>Ui(e(),t())),Ce.store.subscribe(()=>{Ui(e(),t())})}const Dv={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 Ov(){Is(Dv)}function Rv(e){const{layer:t}=e,n=new Set,o=new Set,s=async d=>{if(!(!d.scriptUrl||o.has(d.scriptUrl))){try{await ke(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(c){_(v.SHELL_ERROR,{scope:"widget-script-load",id:d.id,error:c})}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}:(_(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{Is(c)}catch(l){_(v.SHELL_ERROR,{scope:"widget-register",id:d.id,error:l});return}n.add(d.id),lo(),t&&t.mountIfEnabled(d.id)}},a=d=>{n.has(d)&&(t?.unmount(d),sh(d),n.delete(d),lo())};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 Hl=["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-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-notice"],Fl=new Set(Hl),Mv=2e3,Bi=new Set,zl=new WeakSet;let jl=!1;function Pv(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 $v(e){let t=null,n=1/0;for(const o of Fl){const s=Pv(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function Wv(e){return e.startsWith("wpd-")?e.slice(4):e}function Uv(e,t){if(Bi.has(e))return;if(Bi.add(e),Fl.has(e)){const s=Wv(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.
148
149 Fix — side-effect-import the component module from wherever you render it:
150
151 import '<rel>/ui/components/${s}/${s}';
152
153 Or pull every wpd-* component in one go (heavier — only do this from an entry bundle):
154
155 import '<rel>/ui/components';
156
157 See docs/components-reference.md for the full list.`,`
158 First offending element:`,t);return}const o=$v(e);if(o){console.error(`[wp.desktop] <${e}> is not a registered wpd-* component. Did you mean <${o}>?
159
160 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'.`,`
161 First offending element:`,t);return}console.error(`[wp.desktop] <${e}> looks like a wpd-* tag but no component by that name exists.
162
163 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.`,`
164 First offending element:`,t)}function Gl(e){const t=e.tagName.toLowerCase();if(!t.startsWith("wpd-")||Bi.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||Uv(t,e)},Mv)}function ql(e){e instanceof Element&&(Gl(e),e.shadowRoot&&Oo(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];Gl(o),o.shadowRoot&&Oo(o.shadowRoot)}}function Oo(e){if(zl.has(e))return;zl.add(e),ql(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&&ql(r)}}}).observe(e,{childList:!0,subtree:!0})}function Bv(){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"&&Oo(s),s};n.__wpdPatched=!0,e.attachShadow=n}function Hv(){jl||typeof document>"u"||(jl=!0,Bv(),Oo(document))}const Hi="data-desktop-mode-trash-drop-active",Dt="desktop-mode-recycle-bin",Fv=[`.desktop-mode-file-tile[data-file-ref="${Dt}"]`,`[data-icon-id="${Dt}"]`,`[data-system-id="${Dt}"]`];function zv(){for(const e of Fv){const t=document.querySelector(e);if(t instanceof HTMLElement)return t}return null}let Kl=!1,En=null,Sn=null,Vl=null;function jv(e){return e.payload.type==="desktop-file"}function Yl(e,t,n){return e.registerDropTarget({id:t,element:n,accept:o=>{if(o.type!=="desktop-file")return!1;const i=o.data?.placement;return!i||i.file?.ref===Dt?!1:i.canTrash!==!1},onEnter:()=>{n.setAttribute(Hi,"")},onLeave:()=>{n.removeAttribute(Hi)},onDrop:o=>{if(n.removeAttribute(Hi),!jv(o))return;const s=o.payload.data.placement;mb(s)}})}function Gv(e){if(Kl)return;Kl=!0;const t=()=>{const n=zv();if(!n){En?.(),En=null;return}En&&qv(e)===n||(En?.(),En=Yl(e,"recycle-bin-dock",n))};if(t(),document.addEventListener("desktop-mode-files-changed",t),document.addEventListener("desktop-mode-desktop-icons-rendered",t),q(v.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){Vl=new MutationObserver(()=>{t()});const n=document.getElementById("desktop-mode-area")??document.body;Vl.observe(n,{childList:!0,subtree:!0})}q(v.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==Dt)return;Sn?.(),Sn=null;const o=document.querySelector("[data-desktop-mode-recycle-bin-root]");o instanceof HTMLElement&&(Sn=Yl(e,"recycle-bin-window",o))}),q(v.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===Dt&&(Sn?.(),Sn=null)})}function qv(e){const t=e.debug().listTargets().find(n=>n.id==="recycle-bin-dock");return t?t.element:null}let Xl=!1,at=0;function Kv(){Xl||(Xl=!0,nt.contribute("desktop_mode_files_subscribe",()=>{const e=ot(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:at,sharesVersion:Be().state.sharesVersion}}),nt.subscribe("desktop_mode_files",e=>{Vv(e)}))}function Vv(e){const t=e.folders??[];for(const i of t)fi(i,"remote"),i.updatedAtMs>at&&(at=i.updatedAtMs);const n=e.placements??[];for(const i of n)pi(i,"remote"),i.updatedAtMs>at&&(at=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])mi(i,"remote");for(const i of o.placements??[])So(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>at&&(at=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&Ll(s),e.truncated){const i=Array.from(ot().hydratedFolders);for(const r of i)Ae(r).then(a=>{xt(r,a.placements)}).catch(()=>{})}}let Zl=!1;const Yv=[];function Xv(){if(Zl)return;Zl=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||Zv()};Yv.push(xe("desktop-mode.placement.changed",e),xe("desktop-mode.shortcut.changed",e),xe("desktop-mode.folder.changed",e))}function Zv(){qc().then(t=>{ol(t.folders)}).catch(t=>{console.error("[desktop-mode] files restore-sync: listFolders failed",t)});const e=Array.from(ot().hydratedFolders);for(const t of e)Ae(t).then(n=>{xt(t,n.placements)}).catch(n=>{console.error("[desktop-mode] files restore-sync: listPlacements failed for",t,n)})}const Cn="desktop-mode-wallpaper-menu";let Ot=null;function Jl(){return Ot!==null}let Ql=0;function Jv(e,t,n,o={}){An();const s=++Ql;$t(()=>s===Ql,()=>Qv(e,t,n,o))}function Qv(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((f,b)=>{const m=typeof f.sort=="number"?f.sort:100,w=typeof b.sort=="number"?b.sort:100;return m!==w?m-w:f.label.localeCompare(b.label)});const s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(Cn),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 b=document.createElement("wpd-context-menu-option");b.dataset.menuItemId=f.id,b.setAttribute("value",f.id),f.heading&&b.setAttribute("heading",""),f.disabled&&b.setAttribute("disabled",""),f.icon&&b.setAttribute("icon",eu(f.icon));const m=Array.isArray(f.children)&&f.children.length>0;m&&b.setAttribute("has-children",""),b.textContent=f.label,b.addEventListener("mouseenter",()=>{if(m){c(f,b);return}d()}),s.appendChild(b)}s.addEventListener("wpd-context-menu-pick",f=>{const b=f.detail,m=i.get(b.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}An(),m.onClick(new MouseEvent("click"))}});function c(f,b){d();const m=document.createElement("wpd-context-menu");m.setAttribute("open",""),m.classList.add(Cn,`${Cn}--flyout`),m.dataset.parentId=f.id;const w=(f.children??[]).slice().sort((g,E)=>{const D=typeof g.sort=="number"?g.sort:100,y=typeof E.sort=="number"?E.sort:100;return D!==y?D-y:g.label.localeCompare(E.label)});for(const g of w){const E=document.createElement("wpd-context-menu-option");E.dataset.menuItemId=g.id,E.setAttribute("value",g.id),g.icon&&E.setAttribute("icon",eu(g.icon)),g.disabled&&E.setAttribute("disabled",""),g.checked&&E.setAttribute("checked",""),E.textContent=g.label,E.addEventListener("wpd-context-menu-pick",D=>{D.stopPropagation(),An(),g.onClick(new MouseEvent("click"))}),m.appendChild(E)}document.body.appendChild(m),r=m,a=f,l(m,b)}function l(f,b){const m=b.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),Ot=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=il(s,{close:()=>An(),siblingSelectors:[`.${Cn}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",p),_("desktop-mode.wallpaper-menu.opened",{items:n.map(f=>f.id)})}function An(){Ot&&(document.querySelectorAll(`.${Cn}--flyout`).forEach(e=>e.remove()),Ot.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),Ot.remove(),Ot=null,_("desktop-mode.wallpaper-menu.closed",{}))}function ek(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=>tk(i,e)),o=[...t,...n],s=z("desktop-mode.wallpaper-context-menu",o);return Array.isArray(s)?s:o}function tk(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()}_("desktop-mode.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function eu(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const xn="desktop-mode-url-dialog";let In=null;function Fi(){In&&(In.dispatchEvent(new CustomEvent("url-dialog-closed")),In.remove(),In=null,_("desktop-mode.files.url-dialog.closed",{}))}function nk(e){if(Fi(),z("desktop-mode.files.url-dialog",null,e)===!1)return;const n=document.createElement("div");n.className=`${xn}__overlay desktop-mode-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${xn} desktop-mode-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${xn}-title`);const s=document.createElement("h2");if(s.id=`${xn}-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=`${xn}__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),In=n,queueMicrotask(()=>{const g=i.shadowRoot?.querySelector("input");g?.focus(),g?.select()}),_("desktop-mode.files.url-dialog.opened",{});const u=g=>{const E=g.value;return typeof E=="string"?E: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},b=()=>{Fi(),e.onCancel?.()},m=async()=>{const g=u(r).trim();if(!g){f("Please enter a URL.");return}const E=/^[a-z][a-z0-9+\-.]*:/i.test(g)?g:`https://${g}`;try{new URL(E)}catch{f("That doesn't look like a valid URL.");return}const D=u(i).trim();a.hidden=!0,p(!0);try{await e.onSubmit({name:D,url:E}),Fi()}catch(y){p(!1),f(y instanceof Error?y.message:"Could not save.")}};c.addEventListener("click",()=>b()),l.addEventListener("click",()=>void m()),n.addEventListener("click",g=>{g.target===n&&b()});const w=g=>{g.key==="Escape"?(g.preventDefault(),b()):g.key==="Enter"&&!g.isComposing&&(g.preventDefault(),m())};o.addEventListener("keydown",w),n.addEventListener("url-dialog-closed",()=>{o.removeEventListener("keydown",w)})}const tu=[];let zi=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.desktop)return;const n={whenReady(o){if(typeof o=="function"){if(zi){Promise.resolve().then(o);return}tu.push(o)}},ready(o){n.whenReady(o)},isReady(){return zi}};t.wp.desktop=n})();const Ln="desktop-mode-os-settings";function nu(){const e=window.desktopModeConfig;if(!e)return;const t=document.getElementById("desktop-mode-area");if(!t)return;const n=new Ku(t),o=document.getElementById("desktop-mode-wallpaper"),s=e.pluginUrl||"";let i=null;o&&(i=new Ia(o,s));const r=document.getElementById("desktop-mode-widgets");let a=null;Ov(),zf(),r&&(a=new Nh(r,s)),Ca({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const d=new Kf({mediaUrl:e.mediaUrl,restNonce:e.restNonce,canUpload:!!e.canUpload,isAdmin:!!e.currentUserIsAdmin,aiPlatformSettings:e.aiPlatformSettings??null,aiPlatformSettingsUrl:e.aiPlatformSettingsUrl??"",extendedOptions:e.extendedOptions??null,extendedOptionsUrl:e.extendedOptionsUrl??"",osSettingsPanelBundleUrl:e.osSettingsPanelBundleUrl??""},i??new Ia(document.createElement("div"),s));d.apply();const c=new tw({aiSearchUrl:e.aiSearchUrl??"",aiSearchStreamUrl:e.aiSearchStreamUrl??"",restNonce:e.restNonce,getTransport:()=>d.getOsSettingsSnapshot().ai.transport},e.aiAssistantBundleUrl??"");c.attachAsk(rw({config:()=>e,fallbackContext:()=>({close:()=>c.close(),openInWindow:(A,P,$)=>{n.open({url:A,title:P,icon:$??"dashicons-admin-generic"})},confirm:A=>Rc({message:A})})}));const l=new sg,u=new vg;document.addEventListener(_e.START,A=>{const $=A.detail?.payload;if(!$||$.type!=="shortcut"&&$.type!=="desktop-file")return;const G=$.data?.bridgePayload;G&&l.start(G)}),document.addEventListener(_e.END,()=>{l.end()}),xg(u),window.addEventListener("message",A=>{if(A.origin!==window.location.origin)return;const P=A.data;!P||P.type!=="desktop-mode-drop-failed"||X({message:"Could not insert into the editor."})}),yc({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>c.open(),close:()=>c.close(),isOpen:()=>c.isOpen}),Og(),Yu(n),ep(n),new Ym({manager:n,adminUrl:e.adminUrl}).install(),new oh({manager:n,adminUrl:e.adminUrl}).install(),document.addEventListener("desktop-mode-open-ai",()=>{vc("desktop-mode-ai-assistant")});const p=document.getElementById("desktop-mode-dock"),f=document.getElementById("desktop-mode-shell"),b=f?.querySelector(".desktop-mode-shell__body");let m=null;const w=Hh({manager:n,appendSystemTile:A=>m?.appendSystemTile(A),removeSystemTile:A=>m?.removeSystemTile(A)}),g=w.sync;yp({getSnapshot:()=>d.getOsSettingsSnapshot(),openById:A=>w.openById(A),adminUrl:e.adminUrl});const E=A=>{const P=de(A,e.adminUrl),$=m?m.getMenuItems():e.dockItems??[];for(const G of $){if(de(G.url,e.adminUrl)===P)return{title:G.title,icon:G.icon,url:G.url,submenu:G.submenu,multi:G.multi};for(const ie of G.submenu??[])if(de(ie.url,e.adminUrl)===P)return{title:ie.title,icon:G.icon,url:G.url,multi:G.multi}}return null};if(Lp({adminUrl:e.adminUrl,deriveSlug:A=>de(A,e.adminUrl),openWindow:A=>{n.open(A)},findDockEntry:E}),mt({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(A,P)=>{if(!P.pathname.endsWith("/edit.php"))return!1;const $=P.searchParams.get("post_type");return!$||$==="post"},enabled:A=>A.nativePostsEnabled===!0}),mt({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(A,P)=>P.pathname.endsWith("/edit.php")?P.searchParams.get("post_type")==="page":!1,enabled:A=>A.nativePagesEnabled===!0}),mt({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(A,P)=>P.pathname.endsWith("/users.php"),enabled:A=>A.nativeUsersEnabled===!0}),mt({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(A,P)=>{const $=P.pathname;return $.endsWith("/profile.php")?!0:$.endsWith("/user-edit.php")?P.searchParams.has("user_id"):!1},enabled:A=>A.nativeUsersEnabled===!0,onMatch:(A,P)=>{const $=parseInt(P.searchParams.get("user_id")??"0",10);$>0&&Qf($)}}),mt({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(A,P)=>P.pathname.endsWith("/edit-comments.php"),enabled:A=>A.nativeCommentsEnabled===!0}),mt({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(A,P)=>{const $=P.pathname;return $.endsWith("/plugins.php")||$.endsWith("/plugin-install.php")},enabled:A=>A.nativePluginsEnabled===!0,onMatch:(A,P)=>{const $=P.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>ak).then(G=>{G.setPluginsWindowTab($)})}}),p&&f&&b&&e.dockItems){t.classList.add("desktop-mode-area--with-dock");const A=d.getOsSettingsSnapshot().desktopLayout,P=$=>{Td(t,$,{openWindow:w.openById,manager:n})};m=Qh({shellRoot:f,shellBody:b,bottomDockEl:p,desktopArea:t,windowManager:n,adminUrl:e.adminUrl,renderIcons:P,getSettings:()=>{const $=d.getOsSettingsSnapshot();return{itemVisibility:$.itemVisibility,dockOrder:$.dockOrder}}},A,e.dockItems,e.desktopIcons),m.appendSystemTile({id:Ln,title:"OS Settings",icon:"dashicons-desktop",isOpen:()=>{const $=n.getById(Ln);return $?($.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:D},"core"),Zd()||m.appendSystemTile(Kw(e.pwa?.appName||"WordPress",X),"core"),window.matchMedia("(display-mode: standalone)").addEventListener("change",$=>{$.matches&&m?.removeSystemTile("desktop-mode-pwa-install")}),Jd().then($=>{$&&m?.removeSystemTile("desktop-mode-pwa-install")})}function D(){n.open({id:Ln,baseId:Ln,url:"#os-settings",title:"OS Settings",icon:"dashicons-desktop",native:!0,render:A=>d.renderPanel(A),width:820,height:720,minWidth:560,minHeight:480})}function y(){n.open({id:dn,baseId:dn,url:`#${dn}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:A=>Iw(A),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("desktop-mode-open-bug-report",()=>{y()}),m&&(m.appendSystemTile({id:dn,title:"Report a bug",icon:"dashicons-buddicons-replies",isOpen:()=>{const A=n.getById(dn);return A?(A.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:y},"core"),m.appendSystemTile(Yf(),"core"));const S=m?.getPrimary()??null;g(Array.isArray(e.nativeWindows)?e.nativeWindows:[]);const h=!!(e.session&&e.session.windows&&e.session.windows.length>0),L=h?ny(n,e,t).catch(A=>{typeof console<"u"&&console.error("[desktop-mode] session restore failed:",A)}):Promise.resolve(),C=e.defaultWindow?.enabled!==!1,T=e.defaultWindow?.url??"",I=typeof T=="string"&&T.startsWith("native:");sy({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:h,defaultEnabled:C,isNativeDefault:I})&&L.then(()=>oy(n,e).catch(A=>{typeof console<"u"&&console.error("[desktop-mode] openCurrentPage failed:",A)}));const k=ry(n,e);dy(k);const R=async A=>{try{const P=await Xs(n,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:A})},{source:"desktop-mode/default-window"});if(!P.ok)throw new Error(`HTTP ${P.status}`);const $=await P.json();e.defaultWindow=$,document.dispatchEvent(new CustomEvent("desktop-mode-default-window-changed",{detail:$}))}catch(P){_(v.SHELL_ERROR,{scope:"default-window-save",error:P}),typeof console<"u"&&console.error("[desktop-mode] Failed to save default window:",P)}};if(n.onToggleStartupRequested=A=>{const P=e.defaultWindow,$=!!A.config.native,G=$?`native:${A.id}`:A.getCurrentUrl(),ie=$?P?.url===G:Dr(P?.url??"")===Dr(G),Mt=!!P?.enabled&&ie;R(Mt?null:G)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!h&&I){const A=T.slice(7);queueMicrotask(()=>{if(A===Ln){D();return}w.openById(A)})}const x=A=>{m?.appendSystemTile(A)},W=Rv({layer:a});W(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const M=sm({osSettings:d});M(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]);const j=dm();j(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const Y=um();Y(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const oe=wm();oe(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const se=gm();se(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),vm()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),Em(),Sm()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),xm()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),ad(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),Bm()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const K=jm(n);aw(n),dw(),hp(),q("desktop-mode.shell.toast","desktop-mode/shell-toast",A=>{!A||typeof A.message!="string"||X({message:A.message,action:A.action,duration:A.duration})});const Z=e,ee=Z.recycleBinCount;pw(Number(ee)||0,typeof Z.recycleBinCountUrl=="string"?Z.recycleBinCountUrl:""),_w({getRecycleBinCount:lw}),window.__desktopModeConnectionBridge=K,q(v.WINDOW_CLOSED,"desktop-mode/connection-cleanup",A=>{A?.windowId&&K.onWindowClosed(A.windowId)}),q(v.IFRAME_READY,"desktop-mode/connection-rearm",A=>{A?.windowId&&K.onIframeReady(A.windowId)});const dt=Wh(n),Xi=ty({layoutDispatcher:m,config:e,syncNativeWindows:g,syncServerWidgets:W,syncServerWallpapers:M,syncServerCommands:j,syncServerSettingsTabs:Y,syncServerTitleBarButtons:oe,syncServerDockRailRenderers:se,renderIcons:A=>{if(m){m.applyDesktopIcons(A);return}Td(t,A,{openWindow:w.openById,manager:n})}});d.subscribeOsSettings(A=>{if(!m)return;const P=m.getLayout();m.setLayout(A.desktopLayout),ct.dock=m.getPrimary(),ct.sideDock=m.getSide(),ct.desktopLayout=A.desktopLayout,P===A.desktopLayout&&m.refresh(),Ui(A.itemVisibility,A.dockPromotedPositions),$c(A.desktopLayout)}),Nv(()=>d.getOsSettingsSnapshot().itemVisibility,()=>d.getOsSettingsSnapshot().dockPromotedPositions),$c(d.getOsSettingsSnapshot().desktopLayout);const ct=By({manager:n,dock:S,layoutDispatcher:m,osSettings:d,iconsApi:qh,filesApi:Ce,saveSession:k,widgetLayer:a,registerWindow:dt,openWindowById:w.openById,openNewWindowById:w.openNewById,placeSystemTile:x,setDefaultWindow:R,refreshMenu:Xi,openOsSettings:D,aiAssistant:c,dragBridge:l,dragManager:u,connect:K.connect,config:e});if(Hy(ct),Gv(u),Rg(),qg(),Yy({openUrl:({id:A,url:P,title:$,icon:G})=>(ht(P)||n.open({id:A,baseId:A,url:P,title:$,icon:G}),!0),openNativeWindow:A=>w.openById(A),deriveWindowId:A=>de(A,e.adminUrl)}),Hc(e.userFileAssociations??{}),typeof e.filesUrl=="string"&&e.filesUrl){zc({baseUrl:e.filesUrl,nonce:e.restNonce});const A=document.getElementById("desktop-mode-area");if(A){const P=hl(A,0),$=()=>{t.classList.contains("desktop-mode-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("desktop-mode-area--booting")})},G=setTimeout($,2e3);P.hydrated.then(()=>{clearTimeout(G),$()})}}Kv(),Xv(),$g(),_(v.COMPONENTS_REGISTERED,{tags:[...Hl]}),Lg(),eg(e,X);const au=()=>{ku(e.shellOverlaysBundleUrl??""),yu(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(au,{timeout:1500}):window.setTimeout(au,0),_(v.INIT,{config:e}),zi=!0;const jk=tu.splice(0);for(const A of jk)try{A()}catch(P){_(v.SHELL_ERROR,{scope:"when-ready-cb",error:P}),typeof console<"u"&&console.error("[desktop-mode] whenReady cb threw:",P)}d.apply(),a?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),a?.disposeAll()}),cy(),Xg(n,e);const du=(A,P=!0)=>{const $=Ce.store.getState().placementsByFolder.get(0)??[],G=A($),ie=Math.max(1,Math.floor((t.clientHeight-16)/110)),Mt=new Set;let lt=0;for(const ve of G){const ye=st(16+Math.floor(lt/ie)*96,16+lt%ie*110,Mt,t);Mt.add(`${ye.col},${ye.row}`),lt++,!(ve.x===ye.x&&ve.y===ye.y)&&(Ce.store.upsertPlacement({...ve,x:ye.x,y:ye.y,sortOrder:lt}),P&&Ct(ve.id,{x:ye.x,y:ye.y,sortOrder:lt}).catch(Fe=>{console.error("[desktop-mode] relayout persist failed",Fe)}))}},cu=A=>P=>{const $=P.slice();switch(A){case"name-asc":$.sort((G,ie)=>G.file.title.localeCompare(ie.file.title));break;case"name-desc":$.sort((G,ie)=>ie.file.title.localeCompare(G.file.title));break;case"date-asc":$.sort((G,ie)=>G.updatedAtMs-ie.updatedAtMs);break;case"date-desc":$.sort((G,ie)=>ie.updatedAtMs-G.updatedAtMs);break}return $},Zi="desktop-mode:root-sort-mode",Gk=A=>A==="name-asc"||A==="name-desc"||A==="date-asc"||A==="date-desc";let Ho=(()=>{try{const A=window.localStorage.getItem(Zi);return Gk(A)?A:null}catch{return null}})();const lu=A=>{Ho=A;try{A?window.localStorage.setItem(Zi,A):window.localStorage.removeItem(Zi)}catch{}};if(q("desktop-mode.files.tile-manually-placed","desktop-mode/root-sort-clear",A=>{A?.folderId===0&&lu(null)}),typeof ResizeObserver<"u"){let A=t.clientWidth,P=t.clientHeight;new ResizeObserver(()=>{if(!Ho)return;const G=t.clientWidth,ie=t.clientHeight;G===A&&ie===P||(A=G,P=ie,du(cu(Ho),!1))}).observe(t)}t.addEventListener("click",A=>{d.state.showDesktopOnWallpaperClick&&A.target===t&&(t.classList.contains("desktop-mode-area--overview")||Jl()||u.recentlyEndedDrag()||n.toggleShowDesktop())}),t.addEventListener("contextmenu",A=>{if(A.target!==t)return;A.preventDefault();const P=A.clientX,$=A.clientY;(()=>{if(t.classList.contains("desktop-mode-area--overview"))return;if(Jl()){An();return}const G={x:P,y:$},ie=()=>{const ve=t.getBoundingClientRect(),ye=Math.max(0,G.x-ve.left),Fe=Math.max(0,G.y-ve.top),zn=dl(Ce.store.getState().placementsByFolder.get(0)??[]);return st(ye,Fe,zn,t)},Mt=(ve,ye)=>{nk({title:ve,description:ye,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:Fe,url:zn})=>{const uu=ie(),qk=await St({type:"link",ref:zn,parentId:0,x:uu.x,y:uu.y,meta:Fe?{name:Fe}:void 0});Ce.store.upsertPlacement(qk)}})},lt=ek({createFolder:()=>{vi({onSubmit:async ve=>{const ye=await ui({name:ve}),Fe=ie(),zn=await St({type:"folder",ref:String(ye.id),parentId:0,x:Fe.x,y:Fe.y});Ce.store.upsertFolder(ye),Ce.store.upsertPlacement(zn)}})},createUrl:()=>Mt("New URL","Opens the URL in a new browser tab."),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>D(),sortIcons:ve=>{lu(ve),du(cu(ve))},currentSortMode:Ho,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??[]});Jv(document.body,{x:P,y:$},lt)})()}),Promise.resolve().then(()=>Dk).then(A=>{A.bootOsFileDrop({config:e.dropConfig,mediaUrl:e.mediaUrl,restNonce:e.restNonce})}),document.dispatchEvent(new CustomEvent("desktop-mode-init",{detail:{config:e,restored:h}}))}Hv(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",nu):nu();const ok={tab:null,requestedAt:0};let Ro=null;function ji(){if(Ro)return Ro;const t=window.wp?.desktop?.createSharedStore;return typeof t!="function"?null:(Ro=t("desktop-mode/plugins-window/tab-target",()=>({...ok})),Ro)}function sk(e){const t=ji();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 ik(){const e=ji();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 rk(e){const t=ji();return t?t.subscribe(n=>e({...n})):()=>{}}const ak=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:ik,setPluginsWindowTab:sk,subscribePluginsWindowTab:rk},Symbol.toStringTag,{value:"Module"})),ae={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"},dk=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function Mo(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 ck(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 lk(e){const t=window;if(t.__desktopModeOsFileDropMounted)return t.__desktopModeOsFileDropMounted;if(!e.config.enabled)return pk();const n=uk();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=>{Mo(m)&&(m.preventDefault(),o++,n.classList.add("is-active"),r())},d=m=>{if(Mo(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(!Mo(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=fk(m);ou(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 E=ck(m.source);if(!E)return;const D={surface:"iframe",windowId:E,x:typeof w.x=="number"?w.x:0,y:typeof w.y=="number"?w.y:0};o=0,n.classList.remove("is-active"),ou(g,D,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 b={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=b,b}function uk(){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 pk(){const e=o=>{if(!Mo(o))return;const s=o.target;s?.closest&&dk.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 fk(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 ou(e,t,n){const o=z(ae.FILES_DETECTED,e,t);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=mk(o,n.config);if(i.length>0&&(_(ae.FILES_REJECTED,{rejections:i,context:t}),X({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:gk(a,d)},l=z(ae.DIALOG_FIELDS,c,t);return!l||typeof l!="object"||!("fields"in l)||typeof l.fields!="object"?c:l});await n.openDialog(r,t)}function mk(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 ${vk(t.maxSize)} upload limit.`});continue}const i=hk(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 hk(e,t,n){if(t.length===0)return null;const o=e.type.toLowerCase();if(o&&t.includes(o))return o;const s=su(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=wk[s];return i&&t.includes(i)?i:null}const wk={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 su(e){const t=e.lastIndexOf(".");return t<0?"":e.slice(t+1).toLowerCase()}function gk(e,t){const n=yk(e.name),o=su(n),s=o?n.slice(0,n.length-o.length-1):n,i=bk(s);return{title:i,altText:t.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function yk(e){return e.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function bk(e){const t=e.replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Upload"}function vk(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}function Po(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 kk=ge`: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}}`,Bn=class Bn extends ce{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return B`<div class="root" part="root">
165 <div class="header" part="header" hidden>
166 <span class="label" part="label"></span>
167 <span class="percent" part="percent"></span>
168 </div>
169 <div class="track" part="track">
170 <div class="fill" part="fill"></div>
171 </div>
172 </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 b=a||d&&!o;l.hidden=!b,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}};Bn.props=["value","max","indeterminate","tone","label","showPercent"],Bn.styles=[kk],Bn.help=void 0;let Gi=Bn;we("wpd-progress-bar",Gi);const De=new Map;let He=null;function _k(){if(document.body.hasAttribute("data-desktop-mode-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const e="desktop-mode/os-file-drop-hud";q(ae.UPLOAD_STARTED,e,t=>Ek(t.file,t.fields,t.abort)),q(ae.UPLOAD_PROGRESS,e,t=>Sk(t.file,t.loaded,t.total,t.indeterminate)),q(ae.AFTER_UPLOAD,e,t=>Ck(t.file,t.fields,t.result)),q(ae.UPLOAD_FAILED,e,t=>Ak(t.file,t.error))}function Ek(e,t,n){const o=xk(),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=De.get(e);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):qi(u))}),c.appendChild(l),s.append(i,d,c),o.querySelector(".desktop-mode-upload-hud__list").appendChild(s),De.set(e,{file:e,abort:n,root:s,bar:d,statusEl:a,cancelBtn:l,state:"running",lingerTimer:null}),$o()}function Sk(e,t,n,o){const s=De.get(e);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${Po(t)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(t)),s.statusEl.textContent=`${Po(t)} / ${Po(n)}`))}function Ck(e,t,n){const o=De.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(()=>qi(o),2500),$o(),ue.publish("desktop-mode/upload-hud-complete",{filename:t.filename||n.filename,attachmentId:n.id}))}function Ak(e,t){const n=De.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"),$o())}function qi(e){e.lingerTimer&&clearTimeout(e.lingerTimer),De.delete(e.file),e.root.remove(),$o(),De.size===0&&He&&(He.hidden=!0)}function xk(){if(He&&He.isConnected)return He.hidden=!1,He;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[...De.values()])i.state!=="running"&&qi(i);De.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),He=e,e}function $o(){if(!He)return;const e=He.querySelector(".desktop-mode-upload-hud__title");if(!e)return;const t=De.size,n=[...De.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 Ik(){if(document.body.hasAttribute("data-desktop-mode-suppress-media-library-refresh"))return;const e=window;e.__wpdMediaLibraryRefresher||(e.__wpdMediaLibraryRefresher=!0,q(ae.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>Lk()))}function Lk(){const e=document.querySelectorAll("iframe");for(const t of Array.from(e))if(Tk(iu(t)))try{t.contentWindow?.location.reload()}catch{const n=iu(t);n&&t.setAttribute("src",n)}}function iu(e){try{return e.contentWindow?.location.href??e.src??""}catch{return e.src??""}}function Tk(e){return e?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(e):!1}function Nk(e){const t=e.config||{enabled:!1,allowedMimes:[],maxSize:0};_k(),Ik(),lk({config:t,mediaUrl:e.mediaUrl,restNonce:e.restNonce,openDialog:async(n,o)=>{const{openUploadDialog:s}=await Promise.resolve().then(()=>zk);await s({entries:n,context:o,mediaUrl:e.mediaUrl,restNonce:e.restNonce})}})}const Dk=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:ae,bootOsFileDrop:Nk},Symbol.toStringTag,{value:"Module"})),Ok=ge`: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}`,Hn=class Hn extends ce{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),wa(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||"",b=this.suffix||"",m=this.invalid!==null,w=this.reveal!==null,g=a==="password",E=g&&!(w&&this._revealed);let D;g||w&&this._revealed?D="text":D=a;const y=w?"wpd-text-field__row wpd-text-field__row--has-reveal":"wpd-text-field__row",S=E?"wpd-text-field__input wpd-text-field__input--masked":"wpd-text-field__input",L=`${this.id||"wpd-unnamed"}__input`;return B`
173 ${t?B`<label
174 class="wpd-text-field__label"
175 for=${L}
176 >${t}</label>`:B``}
177 <span class=${y}>
178 <input
179 id=${L}
180 class=${S}
181 type=${D}
182 .value=${n}
183 placeholder=${o}
184 ?disabled=${s}
185 ?readonly=${i}
186 autocomplete=${c}
187 maxlength=${l??""}
188 minlength=${u??""}
189 pattern=${p}
190 name=${f}
191 aria-invalid=${m?"true":"false"}
192 aria-label=${t||""}
193 @input=${C=>this._onInput(C)}
194 @change=${C=>this._onChange(C)}
195 @keydown=${C=>this._onKeyDown(C)}
196 />
197 ${b?B`<span class="wpd-text-field__suffix">${b}</span>`:B``}
198 ${w?this._renderRevealButton(s):B``}
199 </span>
200 `}_renderRevealButton(t){const n=this._revealed?"Hide":"Show";return B`
201 <button
202 type="button"
203 class="wpd-text-field__reveal"
204 aria-label=${n}
205 aria-pressed=${this._revealed?"true":"false"}
206 ?disabled=${t}
207 tabindex="0"
208 @click=${()=>this._onToggleReveal()}
209 >
210 ${this._revealed?Mk():Rk()}
211 </button>
212 `}_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})}}};Hn.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],Hn.styles=[Ok],Hn.help=void 0;let Ki=Hn;we("wpd-text-field",Ki);function Rk(){return B`
213 <svg
214 viewBox="0 0 16 16"
215 width="14"
216 height="14"
217 fill="none"
218 stroke="currentColor"
219 stroke-width="1.5"
220 stroke-linecap="round"
221 stroke-linejoin="round"
222 aria-hidden="true"
223 focusable="false"
224 >
225 <path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" />
226 <circle cx="8" cy="8" r="2" />
227 </svg>
228 `}function Mk(){return B`
229 <svg
230 viewBox="0 0 16 16"
231 width="14"
232 height="14"
233 fill="none"
234 stroke="currentColor"
235 stroke-width="1.5"
236 stroke-linecap="round"
237 stroke-linejoin="round"
238 aria-hidden="true"
239 focusable="false"
240 >
241 <path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" />
242 <circle cx="8" cy="8" r="2" />
243 <line x1="2" y1="2" x2="14" y2="14" />
244 </svg>
245 `}const Pk=ge`: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}`,Fn=class Fn extends ce{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),wa(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("name")||"",a=Number(this._attr("rows"))||3,d=this._attr("maxlength"),c=this._attr("minlength"),l=this._boolAttr("invalid"),p=`${this.id||"wpd-unnamed"}__field`;return B`
246 ${t?B`<label class="wpd-textarea__label" for=${p}>${t}</label>`:B``}
247 <textarea
248 id=${p}
249 part="textarea"
250 .value=${n}
251 placeholder=${o}
252 ?disabled=${s}
253 ?readonly=${i}
254 rows=${a}
255 maxlength=${d??""}
256 minlength=${c??""}
257 name=${r}
258 aria-invalid=${l?"true":"false"}
259 aria-label=${t||""}
260 @input=${f=>this._onInput(f)}
261 @change=${f=>this._onChange(f)}
262 @keydown=${f=>this._onKeyDown(f)}
263 ></textarea>
264 `}_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))}};Fn.props=["label","value","placeholder","disabled","readonly","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],Fn.styles=[Pk],Fn.help=void 0;let Vi=Fn;we("wpd-textarea",Vi);async function $k(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=z(ae.BEFORE_UPLOAD,t,e.context);if(!n)throw new ru;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{}}};_(ae.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:u}),a.upload.addEventListener("progress",p=>{_(ae.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,_(ae.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.");_(ae.UPLOAD_FAILED,{file:n.file,error:p,context:e.context}),r(p)}),a.addEventListener("abort",()=>{const p=new Yi;_(ae.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 b=Uk(a),m=new Error(b);_(ae.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}let p;try{p=JSON.parse(a.responseText)}catch(b){const m=b instanceof Error?b:new Error("Could not parse server response.");_(ae.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}if(l&&p.id){Wk(e.mediaUrl,e.restNonce,p.id);const b=new Yi;_(ae.UPLOAD_FAILED,{file:n.file,error:b,context:e.context}),r(b);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};_(ae.AFTER_UPLOAD,{file:n.file,result:f,fields:n.fields,context:e.context}),i(f)}),a.send(o)})}class ru extends Error{constructor(){super("Upload cancelled by desktop-mode.drop.before-upload filter."),this.name="UploadCancelledError"}}class Yi extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function Wk(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 Uk(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 Bk(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"} · ${Po(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(Wo("Title",a.title,b=>a.title=b)),c.appendChild(Wo("Filename",a.filename,b=>a.filename=b)),r.mime.startsWith("image/")&&c.appendChild(Wo("Alt text",a.altText,b=>a.altText=b)),c.appendChild(Wo("Caption",a.caption,b=>a.caption=b)),c.appendChild(Hk("Description",a.description,b=>a.description=b)),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 b=e.entries[f];try{await $k({file:b.file,mime:b.mime,fields:n[f],context:e.context,mediaUrl:e.mediaUrl,restNonce:e.restNonce}),c++}catch(m){if(m instanceof ru){u++;continue}if(m instanceof Yi){u++;continue}l++;const w=m instanceof Error?m.message:"Upload failed.";p.push(`“${b.file.name}” — ${w}`)}}t.remove(),Fk({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 Wo(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 Hk(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 Fk(e){const{total:t,successes:n,failures:o,cancelled:s,failureDetails:i}=e;if(t===0)return;if(t===1){n===1?X({message:"Uploaded to Media Library."}):o===1&&i[0]?X({message:i[0]}):s===1&&X({message:"Upload cancelled."});return}if(n===t){X({message:`Uploaded ${n} files to Media Library.`});return}if(s===t){X({message:"All uploads cancelled."});return}if(o===t){X({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}.`),X({message:r.join(" ")})}const zk=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:Bk},Symbol.toStringTag,{value:"Module"}));return Fo.clampGeometryToViewport=Ic,Object.defineProperty(Fo,Symbol.toStringTag,{value:"Module"}),Fo}({});
265