| 1 |
var desktopMode=function(ds){"use strict";var ls=typeof document<"u"?document.currentScript:null;function ep(){const t=window;t.wp=t.wp??{};const e=t.wp;e.desktop||(e.desktop={});const n=e.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 l=o.indexOf(d);l!==-1&&o.splice(l,1)}},__pendingKinds:o};n.myWordpress=s}ep();function dt(){const t=window.wp?.hooks;if(!t)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 t}function Tr(t,e,n,o){dt().addFilter(t,e,n,o)}function j(t,e,n,o){dt().addAction(t,e,n,o)}function Nr(t,e){return dt().removeAction(t,e)}function q(t,e,...n){return dt().applyFilters(t,e,...n)}function C(t,...e){dt().doAction(t,...e)}function Dr(t){return dt().didAction(t)}function tp(){return dt()}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 np=0;function Or(t){if(Dr(v.INIT)>0){Promise.resolve().then(t);return}const e=`desktop-mode/when-ready-${++np}`;j(v.INIT,e,t)}function op(){return Dr(v.INIT)>0}let _t=null;function ao(){return!!window.desktopModeWindowSystem}function Rr(t){return new Promise((e,n)=>{const o=document.querySelector('script[data-desktop-mode-window-system="1"]'),s=()=>{if(ao()){e();return}n(new Error("[desktop-mode] window-system bundle loaded but did not register `window.desktopModeWindowSystem`."))};if(o){ao()?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=t,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 sp(){return window.desktopModeConfig?.windowSystemBundleUrl??""}function ip(t){!t||ao()||_t||(_t=Rr(t).catch(e=>{_t=null,typeof console<"u"&&console.warn("[desktop-mode] window-system preload failed; will retry on first open():",e)}))}async function rp(t){if(ao())return window.desktopModeWindowSystem;if(!t){const e=window.desktopModeWindowSystem;if(e)return e;throw new Error("[desktop-mode] ensureWindowSystemLoaded(): no bundle URL configured and `window.desktopModeWindowSystem` is not pre-registered.")}return _t||(_t=Rr(t)),await _t,window.desktopModeWindowSystem}const ap="wpd-confirm-dialog";let Et=null;function Kt(){return typeof window.customElements<"u"&&!!window.customElements.get(ap)}function Mr(t){return new Promise((e,n)=>{const o=document.querySelector('script[data-desktop-mode-shell-overlays="1"]'),s=()=>{if(Kt()){e();return}n(new Error("[desktop-mode] shell-overlays bundle loaded but did not register the overlay components."))};if(o){Kt()?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=t,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 dp(t){!t||Kt()||Et||(Et=Mr(t).catch(e=>{Et=null,typeof console<"u"&&console.warn("[desktop-mode] shell-overlays preload failed; will retry on first overlay use:",e)}))}function cs(t){return Kt()||!t?Promise.resolve():(Et||(Et=Mr(t)),Et)}function us(){return window.desktopModeConfig?.shellOverlaysBundleUrl??""}function Yt(t,e){const n=us();if(Kt()||!n){e();return}cs(n).then(()=>{t()&&e()}).catch(o=>{typeof console<"u"&&console.warn("[desktop-mode] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Pr="desktop-mode";function ps(){return window.wp?.i18n}function N(t,e=Pr){return ps()?.__(t,e)??t}function Xt(t,e,n,o=Pr){return ps()?._n(t,e,n,o)??(n===1?t:e)}function oe(t,...e){const n=ps()?.sprintf;if(n)return n(t,...e);let o=0;return t.replace(/%[sd]/g,()=>String(e[o++]??""))}function lp(t,e){if(!t||typeof t!="object")return!1;const n=t.cols,o=t.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)>=e}function cp(t){if(!t||typeof t!="object")return!1;const e=t.cellWidth,n=t.cellHeight;return typeof e!="number"||typeof n!="number"||!Number.isFinite(e)||!Number.isFinite(n)?!1:e>0&&n>0}function up(t,e,n){if(t<=1)return{cols:1,rows:1};const o=e/Math.max(1,n),s=6;let i={cols:t,rows:1,score:1/0};for(let r=1;r<=Math.min(s,t);r++){const a=Math.min(s,Math.ceil(t/r));if(r*a<t)continue;const d=e/r/Math.max(1,n/a),l=Math.abs(d-o),c=r*a-t,u=l+c*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function fs(t,e,n=0){const o=t.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,d=34,l=(e.width-r*2-a*(s-1))/s,c=(e.height-r*2-n-a*(i-1))/i,u=Math.max(40,c-d);return t.map((p,f)=>{const g=f%s,m=Math.floor(f/s),h=e.left+r+g*(l+a),w=e.top+n+r+m*(c+a)+d,x=p.element.offsetWidth,D=p.element.offsetHeight,y=Math.min(l/x,u/D),E=x*y,L=D*y;return{win:p,x:h+(l-E)/2,y:w+(u-L)/2,scale:y}})}const $r=120;function pp(t){if(t._overviewActive)return;const e=t._stack.filter(c=>c.config.desktopId===t._activeDesktopId);if(e.length>0&&e.every(c=>c.state==="minimized"))for(const c of e)try{c.restore()}catch(u){typeof console<"u"&&console.error("[desktop-mode] enterOverview: window.restore() threw for",c.id,u)}const n=t._stack.filter(c=>c.state!=="minimized"&&c.config.desktopId===t._activeDesktopId);t._overviewActive=!0,C(v.OVERVIEW_ENTERING,{}),t._overviewSnapshot.clear();for(const c of n)t._overviewSnapshot.set(c.id,{transform:c.element.style.transform||"",transition:c.element.style.transition||""});for(const c of n)c.state==="fullscreen"&&c.toggleFullscreen();const o=t._desktop.getBoundingClientRect(),s=Array.from(document.querySelectorAll(".desktop-mode-dock"));let i=0;for(const c of s){const u=c.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);t._desktop.classList.add("desktop-mode-area--overview"),document.getElementById("desktop-mode-shell")?.classList.add("desktop-mode-shell--overview"),t._overviewTopBar=Wr(t),t._desktop.appendChild(t._overviewTopBar);const d=fs(n,r,$r);t._overviewLabels.clear();for(const c of d){const u=c.win.element;u.classList.add("desktop-mode-window--overview");const p=c.x-u.offsetLeft,f=c.y-u.offsetTop;u.style.transform=`translate(${p}px, ${f}px) scale(${c.scale})`;const g=hs(c);u.insertAdjacentElement("afterend",g),t._overviewLabels.set(c.win.id,g)}const l=c=>{const u=c.target,p=u?.closest(".desktop-mode-window--overview");return p?{id:p.id.replace(/^wp-window-/,""),element:p}:u===t._desktop?{id:"backdrop",element:t._desktop}:null};t._overviewPointerDownHandler=c=>{if(c.button!==0){t._overviewPressTarget=null;return}t._overviewPressTarget=l(c),t._overviewPressTarget&&(c.preventDefault(),c.stopPropagation())},t._overviewPointerUpHandler=c=>{if(c.button!==0)return;const u=t._overviewPressTarget;if(t._overviewPressTarget=null,!u)return;const p=u.element.getBoundingClientRect();if(!(c.clientX>=p.left&&c.clientX<=p.right&&c.clientY>=p.top&&c.clientY<=p.bottom))return;if(c.preventDefault(),c.stopPropagation(),u.id==="backdrop"){St(t);return}const g=t.getById(u.id);C(v.OVERVIEW_WINDOW_CLICK,{windowId:u.id}),St(t,g,!0)},t._overviewKeyHandler=c=>{if(c.key==="Escape"){St(t);return}if(c.key==="Enter"){if(c.preventDefault(),t._overviewAddTileFocused){Ur(t);return}St(t)}},t._desktop.addEventListener("pointerdown",t._overviewPointerDownHandler,!0),t._desktop.addEventListener("pointerup",t._overviewPointerUpHandler,!0),t._overviewClickBlocker=c=>{c.target?.closest(".desktop-mode-overview-top-bar")||(c.stopPropagation(),c.preventDefault())},t._desktop.addEventListener("click",t._overviewClickBlocker,!0),document.addEventListener("keydown",t._overviewKeyHandler),t._lastOverviewHoverId=null,t._overviewMouseHandler=c=>{const p=c.target?.closest(".desktop-mode-window--overview"),f=p?p.id.replace(/^wp-window-/,""):null;f!==t._lastOverviewHoverId&&(t._lastOverviewHoverId&&C(v.OVERVIEW_WINDOW_UNHOVER,{windowId:t._lastOverviewHoverId}),f&&C(v.OVERVIEW_WINDOW_HOVER,{windowId:f}),t._lastOverviewHoverId=f)},t._desktop.addEventListener("mouseover",t._overviewMouseHandler),window.setTimeout(()=>{t._overviewActive&&C(v.OVERVIEW_ENTERED,{})},300)}function Wr(t){const e=document.createElement("div");e.className="desktop-mode-overview-top-bar";const n=document.createElement("div");n.className="desktop-mode-overview-top-bar__list",e.appendChild(n);for(const s of t._desktops)n.appendChild(fp(t,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",t._overviewAddTileFocused&&o.classList.add("desktop-mode-overview-top-bar__tile--cursor"),o.setAttribute("aria-label",N("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(),Ur(t)}),n.appendChild(o),e}function Ur(t){const e=zr(t);t._overviewAddTileFocused=!1,Br(t,e.id)}function fp(t,e){const n=document.createElement("button");n.type="button",n.className="desktop-mode-overview-top-bar__tile",n.dataset.desktopId=e.id,e.id===t._activeDesktopId&&!t._overviewAddTileFocused&&n.classList.add("desktop-mode-overview-top-bar__tile--active"),n.setAttribute("aria-label",oe(N("Switch to %s"),e.label));const o=document.createElement("span");o.className="desktop-mode-overview-top-bar__tile-preview";const s=t._stack.filter(a=>a.config.desktopId===e.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=e.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",oe(N("Close %s"),e.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(),Gr(t,e.id),ms(t)}),n.appendChild(r),n.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Br(t,e.id)}),n}function ms(t){if(!t._overviewTopBar)return;const e=Wr(t);t._overviewTopBar.replaceWith(e),t._overviewTopBar=e}function Br(t,e){jr(t,e),St(t)}function hs(t){const e=document.createElement("div");e.className="desktop-mode-overview-label",e.dataset.windowId=t.win.id;const n=t.win.element.offsetWidth*t.scale;e.style.left=`${t.x}px`,e.style.top=`${t.y-34}px`,e.style.width=`${n}px`;const o=t.win.config.icon||"dashicons-admin-generic",s=document.createElement("span");s.className=`desktop-mode-overview-label__icon dashicons ${o}`,s.setAttribute("aria-hidden","true"),e.appendChild(s);const i=document.createElement("span");i.className="desktop-mode-overview-label__title",i.textContent=t.win.config.title,e.appendChild(i);const r=t.win.getExternalTabCount();if(r>0){const a=document.createElement("span");a.className="desktop-mode-overview-label__meta",a.textContent=oe(Xt("· %d open tab","· %d open tabs",r),r),e.appendChild(a)}return e}function St(t,e,n=!1){if(!t._overviewActive)return;t._overviewActive=!1,t._overviewAddTileFocused=!1,C(v.OVERVIEW_EXITING,{windowId:e&&n?e.id:void 0,reason:e&&n?"select":"cancel"}),t._desktop.classList.remove("desktop-mode-area--overview"),document.getElementById("desktop-mode-shell")?.classList.remove("desktop-mode-shell--overview");for(const[i,r]of t._overviewSnapshot){const a=t.getById(i);a&&(a.element.style.transform=r.transform)}e&&n&&(t.focus(e),e.maximize());for(const i of t._overviewLabels.values())i.classList.add("desktop-mode-overview-label--out");t._overviewTopBar&&t._overviewTopBar.classList.add("desktop-mode-overview-top-bar--out"),window.setTimeout(()=>{for(const i of t._stack)i.element.classList.remove("desktop-mode-window--overview");for(const i of t._overviewLabels.values())i.remove();t._overviewLabels.clear(),t._overviewSnapshot.clear(),t._overviewTopBar&&(t._overviewTopBar.remove(),t._overviewTopBar=null),t._overviewClickBlocker&&(t._desktop.removeEventListener("click",t._overviewClickBlocker,!0),t._overviewClickBlocker=null),C(v.OVERVIEW_EXITED,{windowId:e&&n?e.id:void 0,reason:e&&n?"select":"cancel"})},280),t._overviewPointerDownHandler&&(t._desktop.removeEventListener("pointerdown",t._overviewPointerDownHandler,!0),t._overviewPointerDownHandler=null),t._overviewPointerUpHandler&&(t._desktop.removeEventListener("pointerup",t._overviewPointerUpHandler,!0),t._overviewPointerUpHandler=null),t._overviewPressTarget=null,t._overviewKeyHandler&&(document.removeEventListener("keydown",t._overviewKeyHandler),t._overviewKeyHandler=null),t._overviewMouseHandler&&(t._desktop.removeEventListener("mouseover",t._overviewMouseHandler),t._overviewMouseHandler=null),t._lastOverviewHoverId&&(C(v.OVERVIEW_WINDOW_UNHOVER,{windowId:t._lastOverviewHoverId}),t._lastOverviewHoverId=null)}function mp(t){return[...t._desktops]}function Hr(t){return t._desktops.find(n=>n.id===t._activeDesktopId)??t._desktops[0]}function hp(t){return Hr(t).id}function Fr(t,e){const n=e.config.desktopId===t._activeDesktopId;e.element.style.display=n?"":"none"}function ws(t){for(const e of t._stack)Fr(t,e)}function zr(t){t._desktopSeq++;const e={id:`desktop-${t._desktopSeq}`,label:oe(N("Desktop %d"),t._desktopSeq)};return t._desktops.push(e),C(v.DESKTOP_CREATED,{desktopId:e.id}),e}function jr(t,e,n){if(e===t._activeDesktopId||!t._desktops.some(s=>s.id===e))return;const o=t._activeDesktopId;if(t._activeDesktopId=e,t._overviewActive)qr(t),ms(t);else{ws(t),n?.direction&&wp(t,n.direction);const s=[...t._stack].reverse().find(i=>i.config.desktopId===e&&i.state!=="minimized");s&&t.focus(s)}C(v.DESKTOP_SWITCHED,{from:o,to:e})}function wp(t,e){const n=t._desktop,o=e==="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 Gr(t,e){if(t._desktops.length<=1)return;const n=t._desktops.findIndex(r=>r.id===e);if(n===-1)return;const o=n>0?n-1:1,s=t._desktops[o];for(const r of t._stack)r.config.desktopId===e&&(r.config.desktopId=s.id);t._desktops.splice(n,1),t._activeDesktopId===e&&(t._activeDesktopId=s.id),t._overviewActive?qr(t):ws(t),C(v.DESKTOP_CLOSED,{desktopId:e,migratedTo:s.id})}function qr(t){for(const[i,r]of t._overviewSnapshot){const a=t.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 t._overviewLabels.values())i.remove();t._overviewLabels.clear(),t._overviewSnapshot.clear(),ws(t);const e=t._stack.filter(i=>i.state!=="minimized"&&i.config.desktopId===t._activeDesktopId);if(e.length===0)return;for(const i of e)t._overviewSnapshot.set(i.id,{transform:i.element.style.transform||"",transition:i.element.style.transition||""});const n=t._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=fs(e,o,$r);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 l=hs(i);r.insertAdjacentElement("afterend",l),t._overviewLabels.set(i.win.id,l)}}function gp(t,e,n){if(e.length===0)return;t._desktops=e.map(s=>({...s})),t._activeDesktopId=e.some(s=>s.id===n)?n:e[0].id;let o=0;for(const s of e){const i=s.id.match(/^desktop-(\d+)$/);if(i){const r=parseInt(i[1],10);Number.isFinite(r)&&r>o&&(o=r)}}t._desktopSeq=Math.max(t._desktopSeq,o)}function yp(t){const e=t._stack.filter(u=>u.config.desktopId===t._activeDesktopId);if(e.length===0)return;C(v.ARRANGE_CASCADE_STARTING,{windowCount:e.length});for(const u of e)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=t._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)),l=Math.min(a,d);e.forEach((u,p)=>{const f=p%Math.max(1,l);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 c=t.getFocused();c&&t.focus(c),document.dispatchEvent(new CustomEvent("desktop-mode-window-changed",{detail:{reason:"cascade"}})),C(v.ARRANGE_CASCADE_APPLIED,{windowCount:e.length})}function bp(t){const e=t._stack.filter(p=>p.config.desktopId===t._activeDesktopId);if(e.length===0)return;for(const p of e)p.state==="minimized"&&p.restore(),p.state==="fullscreen"&&p.toggleFullscreen(),p.state==="maximized"&&p.toggleMaximize();const n=t._desktop.getBoundingClientRect(),o=up(e.length,n.width,n.height),s=q(v.ARRANGE_TILE_DIMENSIONS,o,{windowCount:e.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=lp(s,e.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;C(v.ARRANGE_TILE_STARTING,{windowCount:e.length,cols:i,rows:r});const a=16,d=12,l=Math.floor((n.width-a*2-d*(i-1))/i),c=Math.floor((n.height-a*2-d*(r-1))/r);e.forEach((p,f)=>{const g=f%i,m=Math.floor(f/i);p.element.style.left=`${a+g*(l+d)}px`,p.element.style.top=`${a+m*(c+d)}px`,p.element.style.width=`${l}px`,p.element.style.height=`${c}px`});const u=t.getFocused();u&&t.focus(u),document.dispatchEvent(new CustomEvent("desktop-mode-window-changed",{detail:{reason:"tile"}})),C(v.ARRANGE_TILE_APPLIED,{windowCount:e.length,cols:i,rows:r})}const Vr="desktop-mode-snap-to-grid";function vp(){try{return window.localStorage.getItem(Vr)==="1"}catch{return!1}}function kp(t,e){if(t._snapEnabled!==e){t._snapEnabled=e;try{window.localStorage.setItem(Vr,e?"1":"0")}catch{}C(v.ARRANGE_SNAP_CHANGED,{enabled:e})}}function _p(t){if(!t._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const e=t._desktop.getBoundingClientRect(),n=e.width>=e.height?12:8,o={cellWidth:Math.max(40,Math.round(e.width/n)),cellHeight:Math.max(40,Math.round(e.height/Math.round(n*.66)))},s=q(v.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:e.width,areaHeight:e.height}),{cellWidth:i,cellHeight:r}=cp(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function Ep(t,e,n){if(t._splitOverviewActive)return;t._splitOverviewActive=!0,t._splitOverviewAnchor=e,t._splitOverviewZone=n;const o=t._stack.filter(a=>a!==e&&a.state!=="minimized"&&a.config.desktopId===t._activeDesktopId);if(o.length===0){Kr(t);return}t._splitOverviewSnapshot.clear();for(const a of o)t._splitOverviewSnapshot.set(a.id,{transform:a.element.style.transform||"",transition:a.element.style.transition||""});t._desktop.classList.add("desktop-mode-area--split-overview");const s=Ip(t,n),i=fs(o,s,0);t._splitOverviewLabels.clear();for(const a of i){const d=a.win.element;d.classList.add("desktop-mode-window--overview");const l=a.x-d.offsetLeft,c=a.y-d.offsetTop;d.style.transform=`translate(${l}px, ${c}px) scale(${a.scale})`;const u=hs(a);d.insertAdjacentElement("afterend",u),t._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const d=a.target,l=d?.closest(".desktop-mode-window--overview");return l?{id:l.id.replace(/^wp-window-/,""),element:l}:d?{id:"dismiss",element:t._desktop}:null};t._splitOverviewPointerDown=a=>{if(a.button!==0){t._splitOverviewPressTarget=null;return}t._splitOverviewPressTarget=r(a),t._splitOverviewPressTarget&&(a.preventDefault(),a.stopPropagation())},t._splitOverviewPointerUp=a=>{if(a.button!==0)return;const d=t._splitOverviewPressTarget;if(t._splitOverviewPressTarget=null,!d)return;const l=d.element.getBoundingClientRect();if(!(a.clientX>=l.left&&a.clientX<=l.right&&a.clientY>=l.top&&a.clientY<=l.bottom))return;if(a.preventDefault(),a.stopPropagation(),d.id==="dismiss"){Zt(t);return}const u=t.getById(d.id);if(!u){Zt(t);return}Sp(t,u)},t._splitOverviewKey=a=>{a.key==="Escape"&&Zt(t)},t._splitOverviewClickBlocker=a=>{a.stopPropagation(),a.preventDefault()},t._desktop.addEventListener("pointerdown",t._splitOverviewPointerDown,!0),t._desktop.addEventListener("pointerup",t._splitOverviewPointerUp,!0),t._desktop.addEventListener("click",t._splitOverviewClickBlocker,!0),document.addEventListener("keydown",t._splitOverviewKey)}function Sp(t,e){const n=t._splitOverviewZone;if(!n){Zt(t);return}const o=n==="left"?"right":"left";e.element.style.transform="",e.element.classList.remove("desktop-mode-window--overview"),e.applySnap(o),t._splitOverviewSnapshot.delete(e.id),t.focus(e),C(v.SNAP_SPLIT_FILLED,{windowId:e.id,zone:o}),Zt(t)}function Zt(t){if(!t._splitOverviewActive)return;t._splitOverviewActive=!1;for(const[n,o]of t._splitOverviewSnapshot){const s=t.getById(n);s&&(s.element.style.transform=o.transform)}for(const n of t._splitOverviewLabels.values())n.classList.add("desktop-mode-overview-label--out");t._desktop.classList.remove("desktop-mode-area--split-overview"),window.setTimeout(()=>{for(const n of t._stack)t._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("desktop-mode-window--overview");for(const n of t._splitOverviewLabels.values())n.remove();Kr(t)},260),t._splitOverviewPointerDown&&(t._desktop.removeEventListener("pointerdown",t._splitOverviewPointerDown,!0),t._splitOverviewPointerDown=null),t._splitOverviewPointerUp&&(t._desktop.removeEventListener("pointerup",t._splitOverviewPointerUp,!0),t._splitOverviewPointerUp=null),t._splitOverviewClickBlocker&&(t._desktop.removeEventListener("click",t._splitOverviewClickBlocker,!0),t._splitOverviewClickBlocker=null),t._splitOverviewKey&&(document.removeEventListener("keydown",t._splitOverviewKey),t._splitOverviewKey=null),t._splitOverviewPressTarget=null}function Kr(t){t._splitOverviewSnapshot.clear(),t._splitOverviewLabels.clear(),t._splitOverviewAnchor=null,t._splitOverviewZone=null,t._splitOverviewActive=!1}const Yr=30,Cp=260;function xp(t,e){return t<=e.left+Yr?"left":t>=e.right-Yr?"right":null}function Ap(t,e){const n=t._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:e==="left"?0:n.width-o,y:0,width:o,height:s}}function Ip(t,e){const n=t._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return e==="left"?new DOMRect(o,0,o,s):new DOMRect(0,0,o,s)}function Lp(t,e){if(t._snapPendingZone===e&&t._snapPreviewEl)return;if(t._snapPendingZone=e,!t._snapPreviewEl){const o=document.createElement("div");o.className="desktop-mode-snap-preview",o.setAttribute("aria-hidden","true"),t._desktop.appendChild(o),t._snapPreviewEl=o,Promise.resolve().then(()=>{o.classList.add("desktop-mode-snap-preview--visible")})}const n=Ap(t,e);t._snapPreviewEl.style.left=`${n.x}px`,t._snapPreviewEl.style.top=`${n.y}px`,t._snapPreviewEl.style.width=`${n.width}px`,t._snapPreviewEl.style.height=`${n.height}px`,t._snapPreviewEl.dataset.zone=e}function gs(t){if(!t._snapPreviewEl){t._snapPendingZone=null;return}const e=t._snapPreviewEl;t._snapPreviewEl=null,t._snapPendingZone=null,e.classList.remove("desktop-mode-snap-preview--visible"),window.setTimeout(()=>{e.remove()},Cp)}function Tp(t,e,n){if(t._splitOverviewActive)return;const o=t._desktop.getBoundingClientRect(),s=xp(n,o),i=t._snapPendingZone;s?(Lp(t,s),i!==s&&C(v.SNAP_ZONE_PENDING,{windowId:e.id,zone:s})):i&&(gs(t),C(v.SNAP_ZONE_CANCELED,{windowId:e.id}))}function Np(t,e){const n=t._snapPendingZone;return n?(gs(t),e.state==="normal"&&(e._savedGeometry={x:e.element.offsetLeft,y:e.element.offsetTop,width:e.element.offsetWidth,height:e.element.offsetHeight}),e.applySnap(n),C(v.SNAP_ZONE_COMMITTED,{windowId:e.id,zone:n}),window.requestAnimationFrame(()=>{Ep(t,e,n)}),!0):!1}function Dp(t){t._snapPendingZone&&gs(t)}const Xr="desktop-mode-native-window-geometry",Zr=64,Be=8192;function lo(){try{const t=window.localStorage.getItem(Xr);if(!t)return{};const e=JSON.parse(t);return!e||typeof e!="object"?{}:e}catch{return{}}}function Jr(t){try{window.localStorage.setItem(Xr,JSON.stringify(t))}catch{}}function Qr(t){if(!t)return null;const n=lo()[t];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>Be||s>Be)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<=Be&&a<=Be;return{width:Math.round(o),height:Math.round(s),...d?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function ea(t,e){if(!t)return;const n=Math.round(Number(e.width)),o=Math.round(Number(e.height));if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0||n>Be||o>Be)return;const s=lo(),i=s[t],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||(Jt(s,t,{width:n,height:o,...typeof a=="number"&&typeof d=="number"?{x:a,y:d}:{},...r?{state:r}:{}}),Qt(s))}function ta(t,e){if(!t)return;const n=Math.round(Number(e.x)),o=Math.round(Number(e.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>Be||o>Be)return;const s=lo(),i=s[t];i&&(i.x===n&&i.y===o||(Jt(s,t,{...i,x:n,y:o}),Qt(s)))}function na(t,e,n){if(!t)return;const o=lo(),s=o[t];if(!s){if(e===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>Be||r>Be)return;Jt(o,t,{width:i,height:r,state:e}),Qt(o);return}if(e===null){if(!s.state)return;const{state:i,...r}=s;Jt(o,t,r),Qt(o);return}s.state!==e&&(Jt(o,t,{...s,state:e}),Qt(o))}function Jt(t,e,n){delete t[e],t[e]=n}function Qt(t){const e=Object.keys(t);if(e.length>Zr){const n={};for(const o of e.slice(-Zr))n[o]=t[o];Jr(n);return}Jr(t)}const Op=100,co=30;class Rp{constructor(e){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=vp(),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=e,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(e)),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const e=this._desktop.ownerDocument?.activeElement??null;if(!e||e.tagName!=="IFRAME")return;const n=e.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 e of this._stack){const n=e.element.parentElement;if(n){if(e.state==="maximized")e.element.classList.add("desktop-mode-window--reflowing"),e.element.style.width=`${n.clientWidth}px`,e.element.style.height=`${n.clientHeight}px`;else if(e.state==="snapped-left"||e.state==="snapped-right"){e.element.classList.add("desktop-mode-window--reflowing");const o=Math.floor(n.clientWidth/2),s=n.clientHeight,i=e.state==="snapped-left"?0:o;e.element.style.left=`${i}px`,e.element.style.top="0px",e.element.style.width=`${o}px`,e.element.style.height=`${s}px`}}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const e of this._stack)e.element.classList.remove("desktop-mode-window--reflowing")},140)}}async open(e){if(!e||typeof e!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(e===null?"null":typeof e));if(typeof e.id!="string"||e.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof e.url!="string"||e.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 e.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=e.baseId||e.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})),C(v.WINDOW_REOPENED,r),o}const s=this.getByBaseId(n)?this.nextInstanceId(n):e.id;return this.createWindow({...e,id:s,baseId:n})}async openNew(e){const n=e.baseId||e.id,o=this.nextInstanceId(n),s=40+this.cascadeIndex%8*co,i=40+this.cascadeIndex%8*co;return this.createWindow({initialState:"normal",x:s,y:i,...e,id:o,baseId:n})}async createWindow(e){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*co,r=40+this.cascadeIndex%8*co,a=e.baseId||e.id,d=e.minWidth??320,l=e.minHeight??200,c=typeof e.width=="number",u=typeof e.height=="number",p=typeof e.x=="number",f=typeof e.y=="number",g=typeof e.initialState=="string",m=!c||!u||!g||!p||!f?Qr(a):null,h=e.width??(m?Math.max(m.width,d):o),w=e.height??(m?Math.max(m.height,l):s),x=e.initialState??(m?.state==="maximized"?"maximized":void 0);let D,y;if(m&&typeof m.x=="number"&&typeof m.y=="number"){const $=Math.max(0,n.width-h-12),G=Math.max(0,n.height-w-12);D=Math.max(12,Math.min(m.x,$)),y=Math.max(12,Math.min(m.y,G))}const E=e.x??D??i,L=e.y??y??r,b=c||u||p||f||g,A=!!m,I={x:E,y:L,width:h,height:w,state:x};let _;try{_=q(v.WINDOW_GEOMETRY,I,{windowId:e.id,baseId:a,hasSavedGeometry:A,callerPinned:b,desktopRect:{width:n.width,height:n.height}})}catch(R){C(v.SHELL_ERROR,{scope:"window-geometry-filter",windowId:e.id,error:R}),typeof console<"u"&&console.error(`[desktop-mode] WINDOW_GEOMETRY filter threw for "${e.id}":`,R),_=I}const k=(R,$)=>typeof R=="number"&&Number.isFinite(R)?R:$,O=_&&typeof _=="object"?_:I,M=Math.max(k(O.width,h),d),X=Math.max(k(O.height,w),l),Z=k(O.x,E),te=k(O.y,L),T=O.state??x,F={icon:e.icon||"dashicons-admin-generic",...e,x:Z,y:te,width:M,height:X,minWidth:d,minHeight:l,...T?{initialState:T}:{},baseId:a,desktopId:e.desktopId||this._activeDesktopId};this.cascadeIndex++;const[H]=await Promise.all([rp(sp()),cs(us())]),P=H.createWindow(F);P.onFocusRequest=R=>this.focus(R),P.onClose=R=>this.remove(R),P.onMinimize=()=>{const R=this._stack.filter($=>$.state!=="minimized");R.length>0&&this.focus(R[R.length-1])},P.onOpenAnother=R=>{const $=R.config.baseId||R.id;R.config.native&&window.wp?.desktop?.openNewWindow?.($,{source:"open-another"})||this.openNew({id:$,baseId:$,url:R.config.url||"",title:R.config.title,icon:R.config.icon,submenu:R.config.submenu,multi:!0})},P.onOpenInNewWindow=R=>{const $=R.config.baseId||R.id;if(R.config.native&&window.wp?.desktop?.openNewWindow?.($,{source:"open-in-new-window"}))return;const G=R.getCurrentUrl();this.openNew({id:$,baseId:$,url:G||R.config.url||"",title:R.config.title,icon:R.config.icon,submenu:R.config.submenu,multi:!0})},P.onToggleStartup=R=>{this.onToggleStartupRequested?.(R)},P.snapConfigProvider=()=>this.getSnapConfig(),P.onDragMove=(R,$)=>{Tp(this,R,$)},P.onDragEnd=R=>this._snapPendingZone?Np(this,R):(Dp(this),!1),this._stack.push(P),this._desktop.appendChild(P.element),Fr(this,P),P.hydrateNative(),this.focus(P);const V={windowId:P.id,page:e.url,title:e.title,url:e.url};return document.dispatchEvent(new CustomEvent("desktop-mode-window-opened",{detail:V})),C(v.WINDOW_OPENED,V),P}nextInstanceId(e){const n=new Set(this._stack.map(s=>s.id));if(!n.has(e))return e;let o=2;for(;n.has(`${e}-${o}`);)o++;return`${e}-${o}`}focus(e){const n=this._stack.length>0?this._stack[this._stack.length-1]:null,o=this._stack.find(r=>r!==e&&r.isFocused()&&r.isFullscreen());o&&q(v.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:o.id,focusedTo:e.id})&&o.toggleFullscreen();const s=this._stack.indexOf(e);if(s>-1&&this._stack.splice(s,1),this._stack.push(e),this._stack.forEach((r,a)=>{r.setZIndex(Op+a),r.setFocused(a===this._stack.length-1)}),n&&n!==e&&n.id!==e.id){const r={windowId:n.id,focusedTo:e.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-blurred",{detail:r})),C(v.WINDOW_BLURRED,r)}const i={windowId:e.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-focused",{detail:i})),C(v.WINDOW_FOCUSED,i)}remove(e){const n=this._stack.indexOf(e);n>-1&&this._stack.splice(n,1),this._stack.length>0&&this.focus(this._stack[this._stack.length-1]);const o={windowId:e.id,element:e.element};document.dispatchEvent(new CustomEvent("desktop-mode-window-closing",{detail:o})),C(v.WINDOW_CLOSING,o);const s={windowId:e.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-closed",{detail:s})),C(v.WINDOW_CLOSED,s)}getById(e){return this._stack.find(n=>n.id===e)}getByBaseId(e){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===e)return o}}getByBaseIdOnActiveDesktop(e){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==e)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(e){const n=o=>{if(o===e)return 1;const s=`${e}-`;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)===e).sort((o,s)=>n(o.id)-n(s.id))}getAll(){return[...this._stack]}findByIframeSource(e){if(e)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===e)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(e){const n=this.getById(e);if(!n||n.state==="minimized")return!1;const o=this.getFocused();return!!o&&o.id===e}getDesktops(){return mp(this)}getActiveDesktop(){return Hr(this)}getActiveDesktopId(){return hp(this)}createDesktop(){return zr(this)}switchDesktop(e,n){jr(this,e,n)}closeDesktop(e){Gr(this,e)}getPrimaryDesktopId(){const e=this.getDesktops(),n=e.length>0?e[0].id:"desktop-1",o=q(v.PRIMARY_DESKTOP_ID,n,e);return typeof o!="string"||o===""?n:e.some(i=>i.id===o)?o:n}closeAll(e){const n=new Set(e?.exceptIds??[]),o=this._stack.filter(d=>!n.has(d.id));C(v.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=q(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(l){typeof console<"u"&&console.error("[desktop-mode] closeAll: window.close() threw for",d.id,l)}return C(v.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r}),a}minimizeAll(){const e=[];for(const n of this._stack.slice())if(n.state!=="minimized")try{n.minimize(),e.push(n)}catch(o){typeof console<"u"&&console.error("[desktop-mode] minimizeAll: window.minimize() threw for",n.id,o)}return e}restoreFrom(e){if(!Array.isArray(e))return;const n=new Set(this._stack);for(const o of e)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 e=this._stack.slice();if(e.length===0)return!1;if(e.every(o=>o.state==="minimized")){for(const o of e)try{o.restore()}catch{}return!1}return this.minimizeAll(),!0}cascade(){yp(this)}tile(){bp(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(e){kp(this,e)}getSnapConfig(){return _p(this)}enterOverview(){pp(this)}exitOverview(e,n=!1){St(this,e,n)}getVisibleRects(){return this._stack.map(e=>{const n=e.getSnapshot();return{windowId:e.id,rect:{x:n.x,y:n.y,width:n.width,height:n.height},state:n.state,element:e.element}})}snapshot(){const e=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=e&&!e.config.native?e.id:"";return{windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Math.floor(Date.now()/1e3)}}seedDesktops(e,n){gp(this,e,n)}}function Mp(t){const e=t.getActiveDesktopId(),n=Array.from(t._desktop.children);return t.getAll().filter(o=>(o.config.desktopId||e)===e).sort((o,s)=>n.indexOf(o.element)-n.indexOf(s.element))}function oa(t,e){if(t._overviewActive)return;const n=Mp(t);if(n.length<2)return;const o=t.getFocused(),r=((o?n.indexOf(o):-1)+(e==="next"?1:-1)+n.length)%n.length,a=n[r];a.state==="minimized"?a.restore():t.focus(a)}let sa=!1;function ia(t){let e=t.activeElement;for(;e&&e.shadowRoot&&e.shadowRoot.activeElement;)e=e.shadowRoot.activeElement;if(!e)return!1;if(e instanceof HTMLIFrameElement||e instanceof HTMLTextAreaElement)return!0;if(e instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(e.type);if(e instanceof HTMLElement&&e.isContentEditable===!0)return!0;const n=e.getAttribute("contenteditable");return n!==null&&n!=="false"}function Pp(t){if(sa)return;sa=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(ia(document)||(n.preventDefault(),oa(t,n.shiftKey?"prev":"next")))},!0);const e=window.location.origin;window.addEventListener("message",n=>{if(n.origin!==e)return;const o=n.data;!o||o.type!=="desktop-mode-window-switch"||oa(t,o.direction==="prev"?"prev":"next")})}function ra(t,e){const n=t.getDesktops();if(n.length<2)return!1;const o=t.getActiveDesktopId(),s=n.findIndex(a=>a.id===o);if(s===-1)return!1;const r=(s+(e==="next"?1:-1)+n.length)%n.length;return r===s?!1:(t.switchDesktop(n[r].id,{direction:e}),!0)}function aa(t,e){if(!t._overviewActive)return!1;const n=t.getDesktops(),o=n.length+1,s=n.length,i=t._overviewAddTileFocused?s:n.findIndex(d=>d.id===t.getActiveDesktopId());if(i===-1)return!1;const a=(i+(e==="next"?1:-1)+o)%o;return a===i?!1:a===s?(t._overviewAddTileFocused=!0,ms(t),!0):(t._overviewAddTileFocused=!1,t.switchDesktop(n[a].id,{direction:e}),!0)}function $p(t){return t._overviewActive?t.exitOverview():t.enterOverview(),!0}function Wp(t){return t._overviewActive||t.getAll().length===0?!1:(t.toggleShowDesktop(),!0)}function da(t){return t._overviewActive?(t.exitOverview(),!0):!1}function Up(t){const e=t.getAll();return e.length===0?!1:e.every(n=>n.state==="minimized")}function Bp(t){return Up(t)?(t.toggleShowDesktop(),!0):!1}let la=!1;function Hp(t){la||(la=!0,document.addEventListener("keydown",e=>{if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.code!=="ArrowLeft"&&e.code!=="ArrowRight"&&e.code!=="ArrowUp"&&e.code!=="ArrowDown"||ia(document))return;let n=!1;switch(e.code){case"ArrowLeft":n=t._overviewActive?aa(t,"prev"):ra(t,"prev");break;case"ArrowRight":n=t._overviewActive?aa(t,"next"):ra(t,"next");break;case"ArrowUp":n=da(t)||Bp(t)||$p(t);break;case"ArrowDown":n=da(t)||Wp(t);break}n&&e.preventDefault()},!0))}const Fp=["post_type","page","taxonomy","path","post","p"];function ca(t){return t.replace(/\.php/g,"-php").replace(/[?&=]/g,"-").replace(/[^a-zA-Z0-9_-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")||"index"}function le(t,e){let n=null;try{n=new URL(t,e)}catch{n=null}if(n){const s=new URL(e).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams;for(const d of Fp){const l=n.searchParams.get(d);l&&r.set(d,l)}const a=r.toString();return ca(a?`${i}?${a}`:i)}let o=t.replace(e,"");return o.startsWith("/")&&(o=o.substring(1)),ca(o)}function zp(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}function jp(t){t.style.setProperty("--desktop-mode-file-tile-enter-delay",`${(Math.random()*.25).toFixed(3)}s`),t.style.setProperty("--desktop-mode-file-tile-enter-duration",`${(.3+Math.random()*.25).toFixed(3)}s`)}function ua(t){try{const e=new URL(t,window.location.origin);return e.searchParams.delete("desktop_mode_chromeless"),e.searchParams.delete("desktop_mode_portal"),e.pathname.replace(/\/+$/,"")+"?"+e.searchParams.toString()}catch{return t}}function pa(t){if(typeof t!="string"||t===""||typeof DOMParser>"u")return"";let e;try{e=new DOMParser().parseFromString(t,"image/svg+xml")}catch{return""}const n=e.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||e.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 l=d.name.toLowerCase(),c=d.value.trim().toLowerCase();if(l.startsWith("on")){a.removeAttribute(d.name);continue}c.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 fa=new Map,Gp=new Map;function ys(t,e,n,o){let s=t.get(e);if(!s){if(!o)return;s=new Map,t.set(e,s)}let i=s.get(n);if(!i){if(!o)return;i=new Set,s.set(n,i)}return i}function ma(t,e,n,o){const s={channel:n,windowId:e},i=ys(t,e,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=ys(t,e,"*",!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 "${e}" threw:`,d)}}function qp(t,e,n){const o=ys(fa,t,e,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function Vp(t,e,n){ma(fa,t,e,n)}function Kp(t,e,n){ma(Gp,t,e,n)}const ha=new Set,Yp=new Set,wa=new Map;function Xp(t){if(!ha.has(t)){ha.add(t);const e=wa.get(t);if(e){wa.delete(t);for(const n of e)try{n.flush()}catch(o){typeof console<"u"&&console.error(`[desktop-mode] flushing queued window-send for "${n.channel}" threw:`,o)}}}Yp.delete(t)&&(C(v.WINDOW_CONTENT_LOADED,{windowId:t}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("desktop-mode-window-content-loaded",{detail:{windowId:t}})))}const Zp=Symbol.for("desktop-mode/window-config");function Jp(t){return t[Zp]}function ga(){const t=document.createElement("div");t.className="desktop-mode-window__loading",t.setAttribute("aria-hidden","true");const e=document.createElement("wpd-spinner");return e.setAttribute("preset","classic"),e.setAttribute("size","clamp(96px, 14vw, 192px)"),e.setAttribute("label",N("Loading window content")),t.appendChild(e),t}function Qp(t){let e=ga();const n={windowId:t.id,config:t};if(typeof t.loading?.render=="function")try{t.loading.render(e,n)}catch(o){typeof console<"u"&&console.error(`[desktop-mode] loading.render threw for "${t.id}":`,o)}try{const o=q(v.WINDOW_LOADING_OVERLAY,e,n);o instanceof HTMLElement&&(e=o)}catch(o){typeof console<"u"&&console.error(`[desktop-mode] WINDOW_LOADING_OVERLAY filter threw for "${t.id}":`,o)}return e&&!e.classList.contains("desktop-mode-window__loading")&&e.classList.add("desktop-mode-window__loading"),e}function ef(t){t.querySelector(":scope .desktop-mode-window__loading")?.remove()}function ya(t){const e=t.querySelector(":scope .desktop-mode-window__body");if(!e||e.querySelector(":scope .desktop-mode-window__loading"))return;const o=Jp(t);e.appendChild(o?Qp(o):ga())}const tf=250;let ba=!1;function va(t){return t?document.getElementById(`wp-window-${t}`):null}function nf(){ba||(ba=!0,of())}function of(){j(v.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",t=>{const e=va(t?.windowId??"");if(!e)return;const n=e.querySelector(":scope .desktop-mode-window__body");n&&(n.classList.add("desktop-mode-window__body--loading"),ya(e))}),j(v.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",t=>{const e=va(t?.windowId??"");if(!e)return;const n=e.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")||ef(e)},tf))}),j(v.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>ka())})}function ka(){document.querySelectorAll(".desktop-mode-window__body--loading").forEach(e=>{const n=e.closest(".desktop-mode-window");n&&(e.querySelector(":scope .desktop-mode-window__loading")?.remove(),ya(n))})}const _a="__desktopModeSharedStores";function sf(){const t=window;let e=t[_a];return e||(e=new Map,t[_a]=e),e}function ce(t,e){const n=sf();let o=n.get(t);o||(o={state:e(),listeners:new Set,rebuild:e},n.set(t,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:${t}] 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:${t}] 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 en=ce("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function rf(t){en.state.deps=t}function Ct(t){if(!t||typeof t.id!="string"||t.id.trim()==="")return()=>{};if(typeof t.nativeWindowId!="string"||t.nativeWindowId==="")return()=>{};if(typeof t.matches!="function")return()=>{};const e=en.state.remaps,n=e.findIndex(o=>o.id===t.id);return n>=0&&e.splice(n,1),e.push(t),()=>af(t.id)}function af(t){const e=en.state.remaps,n=e.findIndex(o=>o.id===t);n>=0&&e.splice(n,1)}function Ea(t){const{deps:e,remaps:n}=en.state;if(!e||!t)return null;let o;try{o=new URL(t,e.adminUrl)}catch{return null}const s=e.getSnapshot();for(const i of n)if(i.matches(t,o)&&!(i.enabled&&!i.enabled(s)))return i.nativeWindowId;return null}function xt(t){const{deps:e,remaps:n}=en.state;if(!e||!t)return!1;let o;try{o=new URL(t,e.adminUrl)}catch{return!1}const s=e.getSnapshot();for(const i of n)if(i.matches(t,o)&&!(i.enabled&&!i.enabled(s))){if(i.onMatch)try{i.onMatch(t,o)}catch(r){console.warn(`[desktop-mode] URL remap onMatch hook threw for "${i.id}":`,r)}if(e.openById(i.nativeWindowId))return!0}return!1}const df="desktop-mode.activity.";function bs(t){return`${df}${String(t)}`}let lf=0;const ge={publish(t,e){C(bs(t),e)},subscribe(t,e){const n=`desktop-mode/activity-sub/${++lf}`,o=bs(t);j(o,n,i=>e(i));let s=!1;return()=>{s||(s=!0,Nr(o,n))}},filter(t,e,...n){return q(bs(t),e,...n)}},cf=4e3,uf=200;function J(t){const e=ge.filter("desktop-mode/toast-requested",{...t});if(!e||e.cancel===!0)return()=>{};let n=!1,o=null;return Yt(()=>!n,()=>{o=pf(e)}),()=>{n=!0,o&&o()}}function pf(t){const e=ff(),n=document.createElement("wpd-toast");n.textContent=t.message,t.action&&(n.setAttribute("action",t.action.label),n.addEventListener("wpd-toast-action",()=>{t.action?.onClick(),i()})),e.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()},uf))};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),s=window.setTimeout(i,t.duration??cf),ge.publish("desktop-mode/toast-shown",{...t}),i}function ff(){const t=document.querySelector("wpd-toast-container");if(t)return t;const e=document.createElement("wpd-toast-container");return document.body.appendChild(e),e}const vs=ce("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function mf(t){if(!t||typeof t.id!="string"||t.id.trim()==="")return()=>{};if(typeof t.matches!="function")return()=>{};const e=vs.state.entries,n=e.findIndex(o=>o.id===t.id);return n>=0&&e.splice(n,1),e.push(t),()=>Sa(t.id)}function Sa(t){const e=vs.state.entries,n=e.findIndex(o=>o.id===t);n>=0&&e.splice(n,1)}function hf(){return vs.state.entries.slice()}const wf=ce("desktop-mode/admin-link-deps",()=>({deps:null}));function gf(t){wf.state.deps=t}function uo(t,e){if(!t||typeof t!="object")return["def (not an object)"];const n=t,o=[];for(const s of e)s.valid(n)||o.push(`${s.field} (${s.message})`);return o}class yf extends Error{constructor(e,n,o){super(`[desktop-mode] ${e} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=e,this.errors=n,this.def=o}}function tt(t,e,n){if(e.length!==0)throw new yf(t,e,n)}const Ca=ce("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),At=Ca.state.seed,bf=Ca.state.listeners;function tn(t){tt("Wallpaper",uo(t,La),t);const e=At.findIndex(n=>n.id===t.id);e>=0?At[e]=t:At.push(t),Aa()}function xa(t){const e=At.findIndex(n=>n.id===t);e>=0&&(At.splice(e,1),Aa())}function Aa(){const t=Array.from(bf);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] wallpaper registry listener threw:",n)}}function Ia(){const t=At.slice(),e=q(v.WALLPAPERS,t);return Array.isArray(e)?e.filter(vf):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.wallpapers` filter returned a non-array; falling back to seed list."),t)}function ks(t){return Ia().find(e=>e.id===t)}const La=[{field:"id",message:"missing or not a non-empty string",valid:t=>typeof t.id=="string"&&t.id!==""},{field:"label",message:"missing or not a non-empty string",valid:t=>typeof t.label=="string"&&t.label!==""},{field:"preview",message:"missing or not a non-empty string",valid:t=>typeof t.preview=="string"&&t.preview!==""},{field:"type",message:'must be "css" or "canvas"',valid:t=>t.type==="css"||t.type==="canvas"},{field:"value/resolveValue/mount",message:"css types need `value` or `resolveValue`; canvas types need `mount`",valid:t=>t.type==="css"?typeof t.value=="string"||typeof t.resolveValue=="function":t.type==="canvas"?typeof t.mount=="function":!0}];function vf(t){return uo(t,La).length===0}const Ta="desktop-mode-os-settings",kf="custom-gradient",Na="custom-image",_s="dark",Da=[{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 Oa(){const e=window.wp?.desktop?.config?.accentColors;if(!Array.isArray(e)||e.length===0)return Da;const n=[];for(const o of e)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:Da}function Ra(){const e=window.wp?.desktop?.config?.defaultWallpaper;return typeof e=="string"&&e!==""?e:_s}const Es=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],_f=[{id:"classic",label:"Classic"},{id:"unified",label:"Unified"},{id:"spatial",label:"Spatial"}],ee={wallpaper:_s,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:{}},Ef=[{id:"off",label:"Off"},{id:"sse",label:"Streaming (SSE)"}],Sf=[{id:"openai",label:"OpenAI",apiKeyLabel:"OpenAI API key",apiKeyLink:"https://platform.openai.com/api-keys"}];function Cf(){const e=window.desktopModeConfig?.aiProviders;return!Array.isArray(e)||e.length===0?Sf:e.map(n=>({id:n.id,label:n.label,description:n.description,apiKeyLabel:n.api_key_label,apiKeyLink:n.api_key_link}))}function Ma(t){return typeof t=="string"&&/^#[0-9a-f]{3,8}$/i.test(t)}const Pa="X-WP-Nonce";function $a(t,e){const n=xf();if(!n)return e;const o=Af(t);if(!o||!If(o))return e;const s=e?.headers??(typeof Request<"u"&&t instanceof Request?t.headers:void 0),i=new Headers(s??{});return i.has(Pa)?e:(i.set(Pa,n),{...e??{},headers:i})}function xf(){if(typeof window>"u")return;const e=window.desktopModeConfig?.restNonce;return typeof e=="string"&&e.length>0?e:void 0}function Af(t){try{const e=typeof window<"u"&&window.location?window.location.href:void 0;return typeof t=="string"?new URL(t,e):t instanceof URL?t:typeof Request<"u"&&t instanceof Request?new URL(t.url,e):null}catch{return null}}function If(t){return typeof window>"u"||!window.location||t.origin!==window.location.origin?!1:!!(t.pathname.includes("/wp-json/")||t.searchParams.has("rest_route"))}function je(t,e,n={}){const o=window.wp?.desktop?.fetch;if(typeof o=="function")return o(t,e,n);const s=$a(t,e);return fetch(t,s)}function Lf(){const t=Tf();if(t){const e=Wa(t);return Cs(e),e}try{const e=window.localStorage.getItem(Ta);if(e)return Wa(JSON.parse(e))}catch{}return Uf()}function Tf(){const e=window.desktopModeConfig?.osSettings;return!e||typeof e!="object"||Array.isArray(e)?null:e}function Wa(t){const e=Oa();return{wallpaper:typeof t.wallpaper=="string"&&t.wallpaper!==""?t.wallpaper:Ra(),accent:e.some(n=>n.id===t.accent)?t.accent:ee.accent,dockSize:Es.some(n=>n.id===t.dockSize)?t.dockSize:ee.dockSize,desktopLayout:_f.some(n=>n.id===t.desktopLayout)?t.desktopLayout:ee.desktopLayout,dockRailRenderer:typeof t.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(t.dockRailRenderer)?t.dockRailRenderer:ee.dockRailRenderer,customGradient:Hf(t.customGradient),customImage:Ff(t.customImage),libraryHdOnly:typeof t.libraryHdOnly=="boolean"?t.libraryHdOnly:ee.libraryHdOnly,ai:Bf(t.ai),heartbeatRate:t.heartbeatRate===15||t.heartbeatRate===30||t.heartbeatRate===45||t.heartbeatRate===60?t.heartbeatRate:ee.heartbeatRate,nativePostsEnabled:typeof t.nativePostsEnabled=="boolean"?t.nativePostsEnabled:ee.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(t.nativePostsHiddenColumns)?t.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):ee.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof t.nativePagesEnabled=="boolean"?t.nativePagesEnabled:ee.nativePagesEnabled,nativeUsersEnabled:typeof t.nativeUsersEnabled=="boolean"?t.nativeUsersEnabled:ee.nativeUsersEnabled,nativePluginsEnabled:typeof t.nativePluginsEnabled=="boolean"?t.nativePluginsEnabled:ee.nativePluginsEnabled,nativeCommentsEnabled:typeof t.nativeCommentsEnabled=="boolean"?t.nativeCommentsEnabled:ee.nativeCommentsEnabled,showDesktopOnWallpaperClick:typeof t.showDesktopOnWallpaperClick=="boolean"?t.showDesktopOnWallpaperClick:ee.showDesktopOnWallpaperClick,showPostStatusRibbons:typeof t.showPostStatusRibbons=="boolean"?t.showPostStatusRibbons:ee.showPostStatusRibbons,foldersSharingEnabled:typeof t.foldersSharingEnabled=="boolean"?t.foldersSharingEnabled:ee.foldersSharingEnabled,itemVisibility:Nf(t.itemVisibility),dockOrder:Df(t.dockOrder),dockPromotedPositions:Of(t.dockPromotedPositions)}}function Nf(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e=["both","dock","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(t)){if(o>=256)break;if(typeof s!="string"||s===""||typeof i!="string")continue;const r=i;e.includes(r)&&(n[s]=r,o++)}return n}function Df(t){if(!Array.isArray(t))return[];const e=[],n=new Set;for(const o of t)if(!(typeof o!="string"||o===""||n.has(o))&&(n.add(o),e.push(o),e.length>=256))break;return e}function Of(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};let n=0;const o=1e5;for(const[s,i]of Object.entries(t)){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||(e[s]={x:r.x,y:r.y},n++)}return e}let po=null;const Rf=250;let nn=null;function Mf(t){nn=Ss(t)}function Ss(t){return{...t,customGradient:{...t.customGradient},customImage:t.customImage?{...t.customImage}:null,ai:{...t.ai,apiKeys:{...t.ai.apiKeys}},nativePostsHiddenColumns:t.nativePostsHiddenColumns.slice(),itemVisibility:{...t.itemVisibility},dockOrder:t.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(t.dockPromotedPositions).map(([e,n])=>[e,{...n}]))}}function Pf(t,e={}){Cs(t),$f(t,e.windowId)}function Cs(t){try{window.localStorage.setItem(Ta,JSON.stringify(t))}catch{}}function $f(t,e){po!==null&&clearTimeout(po),e&&(xs=e),It("pending"),po=setTimeout(()=>{po=null;const n=xs;xs=null,Wf(t,n)},Rf)}let xs=null;function Wf(t,e){const n=window.desktopModeConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){It("saved");return}It("saving");const i=e||"desktop-mode-os-settings";je(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:t})},{windowId:i}).then(r=>{if(!r.ok)throw new Error(`${r.status} ${r.statusText}`);nn=Ss(t),It("saved")}).catch(r=>{nn?(Cs(nn),It("failed",r instanceof Error?r.message:String(r),Ss(nn))):It("failed",r instanceof Error?r.message:String(r))})}function It(t,e,n){const o={phase:t};e&&(o.error=e),n&&(o.rolledBackTo=n),document.dispatchEvent(new CustomEvent("desktop-mode-os-settings-save-lifecycle",{detail:o}))}function Uf(){return{...ee,customGradient:{...ee.customGradient},customImage:null,ai:{...ee.ai}}}function Bf(t){if(!t||typeof t!="object")return{...ee.ai,apiKeys:{}};const{enabled:e,provider:n,apiKey:o,apiKeys:s,transport:i}=t,r=Cf(),a=typeof n=="string"&&r.some(c=>c.id===n)?n:ee.ai.provider,d={};if(s&&typeof s=="object")for(const[c,u]of Object.entries(s))typeof u=="string"&&(d[c]=u.slice(0,512));const l=typeof i=="string"&&Ef.some(c=>c.id===i)?i:ee.ai.transport;return{enabled:typeof e=="boolean"?e:ee.ai.enabled,provider:a,apiKey:typeof o=="string"?o:ee.ai.apiKey,apiKeys:d,transport:l}}function Hf(t){if(!t||typeof t!="object")return{...ee.customGradient};const{from:e,to:n,angle:o}=t;return{from:Ma(e)?e:ee.customGradient.from,to:Ma(n)?n:ee.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:ee.customGradient.angle}}function Ff(t){if(!t||typeof t!="object")return null;const{id:e,url:n}=t;return typeof e!="number"||!Number.isFinite(e)||e<=0||typeof n!="string"||!/^https?:\/\//i.test(n)?null:{id:e,url:n}}const on=ce("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),nt=on.state.registry,As=on.state.listeners,zf=/^[a-z0-9_-]+$/;function Ua(t){if(!t||typeof t!="object")throw new TypeError("[desktop-mode] registerDockRailRenderer: renderer must be an object.");if(typeof t.id!="string"||!zf.test(t.id))throw new TypeError(`[desktop-mode] registerDockRailRenderer: id must match /^[a-z0-9_-]+$/, got: ${String(t.id)}`);if(typeof t.label!="string"||t.label==="")throw new TypeError("[desktop-mode] registerDockRailRenderer: label must be a non-empty string.");if(typeof t.mount!="function")throw new TypeError("[desktop-mode] registerDockRailRenderer: mount must be a function.");if(t.apiVersion!==void 0&&t.apiVersion!==1)throw new TypeError(`[desktop-mode] registerDockRailRenderer: unsupported apiVersion ${t.apiVersion} (this shell speaks v1).`);nt.set(t.id,t),fo()}function jf(t){nt.delete(t)&&fo()}function Gf(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(nt.entries()))o.owner===t&&(nt.delete(n),e++);return e>0&&fo(),e}function qf(){return Array.from(nt.values())}function Vf(t){return As.add(t),()=>{As.delete(t)}}function Kf(t){on.state.activeId!==t&&(on.state.activeId=t,fo())}function Is(){return nt.get(on.state.activeId)??nt.get("default")??nt.values().next().value}function fo(){const t=Array.from(As);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] dock-rail-renderer listener threw:",n)}}function Ls(t){if(!t)return 214;let e=5381;for(let n=0;n<t.length;n++)e=Math.imul(e,33)+t.charCodeAt(n);return(e%360+360)%360}const Yf=180,Xf=220,Ba=32;function Ha(t){const{tile:e}=t;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),t.suppressTooltip(!1)},l=f=>{f.pointerType==="mouse"&&Zf(t)&&(i=!0,a(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},Yf)))},c=f=>{n&&f.relatedTarget instanceof Node&&n.contains(f.relatedTarget)||(i=!1,r(),u())},u=()=>{a(),s=window.setTimeout(()=>{s=null,!i&&d()},Xf)},p=()=>{t.suppressTooltip(!0),n=Jf(t,()=>d()),document.body.appendChild(n),im(n),rm(n,e,t.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("desktop-mode-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,a()}),n.addEventListener("pointerleave",f=>{f.relatedTarget instanceof Node&&e.contains(f.relatedTarget)||(i=!1,u())})};return e.addEventListener("pointerenter",l),e.addEventListener("pointerleave",c),()=>{e.removeEventListener("pointerenter",l),e.removeEventListener("pointerleave",c),d()}}function Zf(t){return t.getInstances().length>=1}function Jf(t,e){const n=document.createElement("div");n.className="desktop-mode-dock-peek",n.setAttribute("role","menu"),n.setAttribute("aria-label",oe(N("%s — open windows"),t.item.title));const o=document.createElement("div");o.className="desktop-mode-dock-peek__cards",n.appendChild(o);const s=t.getInstances();let i=0;for(const r of s){const a=Qf(r,t,i++,e);o.appendChild(a)}if(t.enableGhost!==!1){const r=tm(t,i,e);o.appendChild(r)}return n}function Qf(t,e,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*Ba}ms`);const i=t.config.title||e.item.title;s.style.setProperty("--peek-card-hue",`${Ls(t.id||i)}`),s.style.setProperty("--peek-card-vt-name",`desktop-mode-peek-card-${t.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 l=t.config.icon||e.item.icon;l.startsWith("dashicons-")?d.classList.add("dashicons",zp(l)):d.classList.add("dashicons","dashicons-admin-generic"),r.appendChild(d);const c=document.createElement("span");c.className="desktop-mode-dock-peek__card-label",c.textContent=i,r.appendChild(c),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 h=document.createElement("span");h.className="desktop-mode-dock-peek__card-line",u.appendChild(h)}const p={window:t,item:e.item},f=q(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",()=>{em(e,t,s,o)}),s.addEventListener("pointerenter",()=>{e.windowManager.getFocused()!==t&&e.windowManager.focus(t)}),q(v.DOCK_PEEK_CARD_ELEMENT,s,p)}function em(t,e,n,o){const s=document,i=`desktop-mode-peek-card-${e.id}`,r=()=>{o(),t.windowManager.focus(e)};if(typeof s.startViewTransition!="function"){r();return}const a=e.element;n.style.setProperty("view-transition-name",i),a.style.setProperty("view-transition-name",i);const d=s.startViewTransition(r),l=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},c=d;c.finished&&typeof c.finished.then=="function"?c.finished.then(l,l):Promise.resolve().then(l)}function tm(t,e,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(e)),o.style.setProperty("--peek-card-delay",`${e*Ba}ms`);const s=document.createElement("span");s.className="desktop-mode-dock-peek__card-plus",s.setAttribute("aria-hidden","true"),s.textContent="+",o.appendChild(s);const i=document.createElement("span");return i.className="desktop-mode-dock-peek__card-label",i.textContent=oe(N("New %s"),t.item.title),o.appendChild(i),o.addEventListener("click",()=>{nm(t,n)}),o}function nm(t,e){const n=document,o=()=>{e(),t.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const om=12,sm=["--wp-admin-theme-color","--desktop-mode-titlebar-bg","--desktop-mode-titlebar-bg-focused","--desktop-mode-titlebar-color","--desktop-mode-titlebar-color-focused"];function im(t){const e=document.querySelector(".desktop-mode-shell");if(!e)return;const n=window.getComputedStyle(e);for(const o of sm){const s=n.getPropertyValue(o).trim();s&&t.style.setProperty(o,s)}}function rm(t,e,n){const o=e.getBoundingClientRect();t.dataset.orientation=n,n==="bottom"?(t.style.left=`${o.left+o.width/2}px`,t.style.top=`${o.top-12}px`):n==="right"?(t.style.top=`${o.top+o.height/2}px`,t.style.left=`${o.left-12}px`):(t.style.top=`${o.top+o.height/2}px`,t.style.left=`${o.right+12}px`),requestAnimationFrame(()=>am(t))}function am(t,e){const n=t.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=om;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)&&(t.style.setProperty("--peek-clamp-x",`${a}px`),t.style.setProperty("--peek-clamp-y",`${r}px`),t.classList.add("desktop-mode-dock-peek--clamped"))}function mo(t){try{const e=new URL(t,window.location.origin);return e.origin===window.location.origin?!1:(window.open(e.toString(),"_blank","noopener,noreferrer"),!0)}catch{return!1}}function dm(t){return`desktop:${t}`}function lm(t){return`dock:${t}`}function cm(t){return t.startsWith("dock:")?t.slice(5):t.startsWith("desktop:")?t.slice(8):t}function ho(t,e,n){const o=n[t];return o||e}function Fa(t){return t==="dock"||t==="both"}function za(t){return t==="desktop"||t==="both"}function um(t,e,n,o){const s=n.itemVisibility,i=n.dockOrder,r=[];for(const a of t){const d=ho(a.id,"dock",s);Fa(d)&&r.push(a)}for(const a of e){const d=ho(a.id,"desktop",s);Fa(d)&&(a.window&&o&&o.has(a.window)||r.push({id:lm(a.id),title:a.title,icon:a.icon,url:a.url||"",windowId:a.window||void 0,badge:0,submenu:[],isCore:!1}))}return fm(r,i)}function pm(t,e,n){const o=[];for(const i of t){const r=ho(i.id,"desktop",n);za(r)&&o.push(i)}let s=0;for(const i of e){const r=ho(i.id,"dock",n);za(r)&&o.push({id:dm(i.id),title:i.title,icon:i.icon,window:"",url:i.url||"",position:2e3+s++})}return o}function fm(t,e){if(e.length===0||t.length<=1)return t;const n=new Map;for(const i of t)n.set(i.id,i);const o=[],s=new Set;for(const i of e){const r=n.get(i);r&&(o.push(r),s.add(i))}for(const i of t)s.has(i.id)||o.push(i);return o}function B(t,...e){return{__wpdHtml:!0,strings:t,values:e}}function mm(t){return!!t&&t.__wpdHtml===!0}const hm="$$wpd$$",_e=/\$\$wpd\$\$(\d+)\$\$/g;function wm(t){let e=t[0];for(let n=1;n<t.length;n++)e+=`${hm}${n-1}$$`+t[n];return e}const ja=new WeakMap;function Ga(t){const e=ja.get(t);if(e)return e;const n=document.createElement("template");n.innerHTML=wm(t);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,g=p.value,m=f[0];if(_e.test(g))if(_e.lastIndex=0,m==="@"){const h=_e.exec(g);_e.lastIndex=0,o.push({path:d,kind:"event",name:f.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(f)}else if(m==="."){const h=_e.exec(g);_e.lastIndex=0,o.push({path:d,kind:"prop",name:f.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(f)}else if(m==="?"){const h=_e.exec(g);_e.lastIndex=0,o.push({path:d,kind:"bool",name:f.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(f)}else{const h=[],w=[];let x=0,D;for(_e.lastIndex=0;(D=_e.exec(g))!==null;)h.push(g.slice(x,D.index)),w.push(Number(D[1])),x=D.index+D[0].length;h.push(g.slice(x)),o.push({path:d,kind:"attr",name:f,template:h,valueIndices:w}),u.setAttribute(f,"")}}}const l=Array.from(a.childNodes);let c=0;for(let u=0;u<l.length;u++){const p=l[u],f=u+c;if(p.nodeType===Node.TEXT_NODE){const g=p.textContent||"";if(!_e.test(g)){_e.lastIndex=0;continue}_e.lastIndex=0;const m=p.parentNode;let h=0,w;const x=[],D=[];for(_e.lastIndex=0;(w=_e.exec(g))!==null;){w.index>h&&x.push(document.createTextNode(g.slice(h,w.index)));const y=document.createTextNode("");x.push(y),D.push({path:[...d,f+x.length-1],kind:"node",valueIndex:Number(w[1])}),h=w.index+w[0].length}h<g.length&&x.push(document.createTextNode(g.slice(h)));for(const y of x)m.insertBefore(y,p);m.removeChild(p),c+=x.length-1,o.push(...D)}else s(p,[...d,f])}};s(n.content,[]);const r={template:n,buildParts:a=>{const d=[];for(const l of o){let c=a;for(const u of l.path)c=c.childNodes[u];l.kind==="node"?d.push({kind:"node",valueIndex:l.valueIndex,child:{anchor:c,state:null}}):l.kind==="attr"?d.push({kind:"attr",element:c,name:l.name,template:l.template,valueIndices:l.valueIndices}):l.kind==="event"?d.push({kind:"event",valueIndex:l.valueIndex,element:c,name:l.name}):l.kind==="prop"?d.push({kind:"prop",valueIndex:l.valueIndex,element:c,name:l.name}):l.kind==="bool"&&d.push({kind:"bool",valueIndex:l.valueIndex,element:c,name:l.name})}return d}};return ja.set(t,r),r}const qa=new WeakMap;function gm(t,e){const n=qa.get(e);if(n&&n.strings===t.strings){wo(n.parts,t.values);return}const o=Ga(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s);for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(s),wo(i,t.values),qa.set(e,{strings:t.strings,parts:i})}function wo(t,e){for(const n of t)if(n.kind==="node")Ts(n.child,e[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;s<n.valueIndices.length;s++)o+=Va(e[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=e[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=e[n.valueIndex];o!==n.last&&(n.last=o,n.element[n.name]=o)}else if(n.kind==="bool"){const o=!!e[n.valueIndex];o!==n.last&&(n.last=o,o?n.element.setAttribute(n.name,""):n.element.removeAttribute(n.name))}}function Ts(t,e){if(e==null||e===!1){t.state&&(Lt(t.state),t.state=null);return}if(Array.isArray(e)){km(t,e);return}if(mm(e)){vm(t,e);return}if(e instanceof Node){ym(t,e);return}bm(t,Va(e))}function ym(t,e){const n=t.state;n?.shape==="node"&&n.node===e||(n&&Lt(n),go(t,[e]),t.state={shape:"node",node:e})}function bm(t,e){const n=t.state;if(n?.shape==="text"){n.text!==e&&(n.node.textContent=e,n.text=e);return}n&&Lt(n);const o=document.createTextNode(e);go(t,[o]),t.state={shape:"text",node:o,text:e}}function vm(t,e){const n=t.state;if(n?.shape==="template"&&n.strings===e.strings){wo(n.parts,e.values);return}n&&Lt(n);const o=Ga(e.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);go(t,[s]),wo(i,e.values),t.state={shape:"template",strings:e.strings,parts:i,nodes:r}}function km(t,e){const n=t.state;if(n?.shape==="array"&&n.entries.length===e.length){for(let s=0;s<e.length;s++)Ts(n.entries[s],e[s]);return}n&&Lt(n);const o=[];for(const s of e){const i=document.createTextNode("");go(t,[i]);const r={anchor:i,state:null};Ts(r,s),o.push(r)}t.state={shape:"array",entries:o}}function go(t,e){const n=t.anchor.parentNode;if(n)for(const o of e)n.insertBefore(o,t.anchor)}function Lt(t){if(t.shape==="text"){t.node.remove();return}if(t.shape==="template"){for(const e of t.nodes)e.parentNode&&e.parentNode.removeChild(e);return}if(t.shape==="node"){t.node.parentNode&&t.node.parentNode.removeChild(t.node);return}for(const e of t.entries)e.state&&Lt(e.state),e.anchor.remove()}function Va(t){return t==null||t===!1?"":String(t)}const at=class at 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(Ka)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(e,n,o){if(n===o)return;const s=_m(e);this._propValues[s]=o,this.requestUpdate()}get classNames(){return Array.from(this.classList)}set classNames(e){if(e==null){this.removeAttribute("class");return}const o=(Array.isArray(e)?e:String(e).split(/\s+/)).map(s=>String(s).trim()).filter(s=>s!=="");this.className=o.join(" ")}requestUpdate(){this._scheduleRender()}emit(e,n){return this.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,composed:!0}))}_installPropAccessors(){const e=this.constructor;for(const n of e.props){if(Object.getOwnPropertyDescriptor(this,n))continue;const o=Ka(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&&gm(this.render(),this._renderRoot)}))}_adoptStyles(){const e=this.constructor;if(e.styles.length!==0)if(e.shadow&&this.shadowRoot){const n=e.styles.map(o=>o.sheet).filter(o=>o!==null);if(this.shadowRoot.adoptedStyleSheets=n,n.length!==e.styles.length){for(const o of e.styles)if(!o.sheet){const s=document.createElement("style");s.textContent=o.cssText,this.shadowRoot.appendChild(s)}}}else this._adoptLightStyles(e)}_adoptLightStyles(e){if(!at._lightStylesAdopted.has(e)){at._lightStylesAdopted.add(e);for(const n of e.styles){const o=document.createElement("style");o.dataset.wpdUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};at.props=[],at.styles=[],at.shadow=!0,at._lightStylesAdopted=new WeakSet;let ue=at;function fe(t,e){customElements.get(t)||customElements.define(t,e)}function Ka(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function _m(t){return t.replace(/-([a-z])/g,(e,n)=>n.toUpperCase())}const Em=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function me(t,...e){let n=t[0];for(let o=1;o<t.length;o++){const s=e[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+=t[o]}if(Em){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function Sm(t){const e=[],n=[];let o=null,s=t.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&&e.push(Ns(o));for(const r of n)e.push("tab-"+Ns(r));const i=t.getAttribute("label");return i&&e.push(Ns(i)),e.length===0?"wpd-unnamed":"wpd-"+e.filter(r=>r!=="").join("-")}function Ns(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ya(t){if(t.id)return t.id;const e=Sm(t);return t.id=e,e}const Cm=me`: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 )}`,zn=class zn extends ue{constructor(){super(...arguments),this._onKey=e=>{e.key==="Escape"&&(e.preventDefault(),this._cancel()),e.key==="Enter"&&!e.isComposing&&(e.preventDefault(),this._confirm())},this._onBackdrop=e=>{const n=e.composedPath();(n.length>0?n[0]:e.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 e=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 |
>×</button>`:B``} |
| 9 |
${e?B`<h2 class="title">${e}</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 |
`}};zn.props=["open","title","message","confirm-label","cancel-label","danger","hide-cancel","dismissable"],zn.styles=[Cm],zn.help=void 0;let Ds=zn;fe("wpd-confirm-dialog",Ds);function Xa(t){return new Promise(e=>{const n=document.createElement("wpd-confirm-dialog");n.setAttribute("open",""),t.title&&n.setAttribute("title",t.title),n.setAttribute("message",t.message),t.confirmLabel&&n.setAttribute("confirm-label",t.confirmLabel),t.cancelLabel&&n.setAttribute("cancel-label",t.cancelLabel),t.danger&&n.setAttribute("danger",""),t.hideCancel&&n.setAttribute("hide-cancel",""),t.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),e(i)};n.addEventListener("wpd-confirm",()=>o(!0)),n.addEventListener("wpd-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}const xm="http://localhost/";function sn(t,e){const n=typeof window<"u"&&window.location?window.location.href:xm,o=new URL(t,n),s=e.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")??"/",l=d.endsWith("/")?d:d+"/";o.searchParams.set("rest_route",l+r)}else{const d=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=d+r}return a&&new URLSearchParams(a).forEach((l,c)=>{o.searchParams.append(c,l)}),o.toString()}function Za(){return window.wp?.desktop??null}let lt=null;function rn(){lt&&(lt.remove(),lt=null)}function an(t,e){const n=Za();if(!n?.getOsSettings||!n?.updateOsSettings)return;const s={...n.getOsSettings().itemVisibility};s[t]=e,n.updateOsSettings({itemVisibility:s})}let Ja=0;function Qa(t){rn();const e=++Ja;Yt(()=>e===Ja,()=>Am(t))}function Am(t){rn();const e=cm(t.id),n=[];if(t.surface==="dock"?(n.push({id:"hide-from-dock",label:N("Hide from dock"),icon:"dashicons-hidden",onPick:()=>an(e,"desktop")}),n.push({id:"show-on-desktop-too",label:N("Also show on desktop"),icon:"dashicons-desktop",onPick:()=>an(e,"both")})):(n.push({id:"hide-from-desktop",label:N("Hide from desktop"),icon:"dashicons-hidden",onPick:()=>an(e,"dock")}),n.push({id:"show-on-dock-too",label:N("Also show on dock"),icon:"dashicons-menu",onPick:()=>an(e,"both")})),n.push({id:"hide-everywhere",label:N("Hide everywhere"),icon:"dashicons-no",danger:!0,onPick:()=>an(e,"hidden")}),n.push({id:"open-settings",label:N("Apps & Icons settings…"),icon:"dashicons-admin-generic",onPick:()=>{Za()?.openOsSettings?.({tabId:"apps-icons"})}}),t.pluginFile){const d=t.pluginFile,l=t.pluginName||t.title;n.push({kind:"separator"}),n.push({id:"deactivate-plugin",label:oe(N("Deactivate %s…"),l),icon:"dashicons-trash",danger:!0,onPick:()=>{Im(d,l)}})}const o=document.createElement("wpd-context-menu");o.setAttribute("open",""),o.classList.add("desktop-mode-item-visibility-menu"),o.dataset.itemId=t.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 c=document.createElement("hr");c.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(c);continue}s.set(d.id,d);const l=document.createElement("wpd-context-menu-option");l.dataset.menuItemId=d.id,l.setAttribute("value",d.id),d.icon&&l.setAttribute("icon",d.icon),d.danger&&l.setAttribute("danger",""),l.textContent=d.label,o.appendChild(l)}o.addEventListener("wpd-context-menu-pick",d=>{const l=d.detail,c=l?.id||l?.value||"",u=s.get(c);rn();try{u?.onPick()}catch{}}),document.body.appendChild(o),lt=o,requestAnimationFrame(()=>{if(o!==lt)return;const d=o.getBoundingClientRect(),l=8;let c=t.x,u;t.surface==="dock"?u=Math.max(l,t.y-d.height-l):(u=t.y,u+d.height+l>window.innerHeight&&(u=Math.max(l,t.y-d.height))),c+d.width+l>window.innerWidth&&(c=Math.max(l,t.x-d.width)),o.style.left=`${c}px`,o.style.top=`${u}px`,o.style.visibility=""});const r=d=>{lt&&(lt.contains(d.target)||(rn(),document.removeEventListener("mousedown",r,!0),document.removeEventListener("keydown",a,!0)))},a=d=>{d.key==="Escape"&&(rn(),document.removeEventListener("mousedown",r,!0),document.removeEventListener("keydown",a,!0))};document.addEventListener("mousedown",r,!0),document.addEventListener("keydown",a,!0)}async function Im(t,e){if(!await Xa({title:oe(N("Deactivate %s?"),e),message:N("This plugin will stop running on the site. You can re-activate it later from the Plugins screen."),confirmLabel:N("Deactivate"),cancelLabel:N("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=(t.endsWith(".php")?t.slice(0,-4):t).split("/").map(encodeURIComponent).join("/"),d=sn(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){J({message:oe(N("Could not deactivate %s."),e),duration:4e3}),console.error("[desktop-mode] deactivate plugin failed",p);return}const l=Lm(t),c=l.length>0?oe(N("%1$s deactivated. Closed %2$d window(s)."),e,l.length):oe(N("%s deactivated."),e);J({message:c,duration:3e3}),window.wp?.desktop?.refreshMenu?.()}function Lm(t){const e=window.wp?.desktop;if(!e?.windowManager?.getAll)return[];const o=(e.getMenuItems?.()??[]).filter(l=>l.pluginFile===t);if(o.length===0)return[];const s=new Set;for(const l of o)s.add(l.id),e.deriveWindowId&&s.add(e.deriveWindowId(l.url));const i=new Map,r=e.windowManager.getAll()??[],a=e.deriveWindowId;for(const l of r){if(s.has(l.id)){i.set(l.id,l);continue}if(l.config?.baseId&&s.has(l.config.baseId)){i.set(l.id,l);continue}if(a&&l.config?.url){const c=a(l.config.url);if(s.has(c)){i.set(l.id,l);continue}}if(a&&l.iframe){let c="";try{c=l.iframe.src||""}catch{}if(c){const u=a(c);s.has(u)&&i.set(l.id,l)}}}const d=[];for(const l of i.values()){d.push(l.config?.title??l.id);try{l.close()}catch{}}return d}const Ce=class Ce{constructor(e,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=e,this.windowManager=n,this.items=o,this.adminUrl=s,this.orientation=i,this.rail=i==="bottom"?"taskbar":"dock",this.hooksNamespace=`desktop-mode/dock/${++Ce.instanceCounter}`,this.container.setAttribute("data-desktop-mode-dock-placement",i);const r=document.createElement("div");r.className="desktop-mode-dock__scroll";const a=document.createElement("div");a.className="desktop-mode-dock__pinned",e.appendChild(r),e.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="desktop-mode-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("desktop-mode-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("desktop-mode-dock__tooltip--before"):this.tooltip.classList.add("desktop-mode-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.render(),this.bindWindowEvents()}buildHookContextBase(){return{rail:this.rail,orientation:this.orientation,dockId:this.container.id,container:this.container}}setOrientation(e){this.orientation!==e&&(this.orientation=e,this.container.setAttribute("data-desktop-mode-dock-placement",e),this.tooltip.classList.remove("desktop-mode-dock__tooltip--above","desktop-mode-dock__tooltip--before","desktop-mode-dock__tooltip--after"),e==="bottom"?this.tooltip.classList.add("desktop-mode-dock__tooltip--above"):e==="right"?this.tooltip.classList.add("desktop-mode-dock__tooltip--before"):this.tooltip.classList.add("desktop-mode-dock__tooltip--after"))}replaceItems(e){for(const i of this.itemElements.keys()){const r=this.peekTeardowns.get(i);r&&(r(),this.peekTeardowns.delete(i))}for(const i of this.itemElements.values())i.remove();this.itemHost.querySelectorAll(".desktop-mode-dock__separator--group").forEach(i=>i.remove()),this.itemElements.clear(),this.items=e;const n=this.buildHookContextBase();C(v.DOCK_BEFORE_RENDER,{...n,items:e,tileElements:this.itemElements});let o=!1,s=0;for(const i of e){if(!o&&i.isCore===!1){if(s>0){const d=document.createElement("div");d.className="desktop-mode-dock__separator desktop-mode-dock__separator--group",d.setAttribute("aria-hidden","true"),this.itemHost.appendChild(d)}o=!0}const r=this.createItemButton(i);this.itemElements.set(i.id,r),this.itemHost.appendChild(r),s++;const a=this.badgeOverrides.get(i.id);if(a!==void 0){const d=r.querySelector(".desktop-mode-dock__item-primary");ed(d??r,a)}C(v.DOCK_TILE_RENDERED,{...n,item:i,isSystem:!1,el:r})}this.updateActiveStates(),C(v.DOCK_AFTER_RENDER,{...n,items:e,tileElements:this.itemElements})}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(e){const n=this.systemItemElements.get(e);n&&(n.remove(),this.systemItemElements.delete(e),this.systemItems=this.systemItems.filter(o=>o.id!==e),this.badgeOverrides.delete(e),this.systemItemElements.size===0&&this.systemSeparator&&(this.systemSeparator.remove(),this.systemSeparator=null),C(v.DOCK_ITEM_REMOVED,{id:e,placement:this.rail}))}setBadge(e,n){const o=this._resolveTileElement(e);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(e):this.badgeOverrides.set(e,s);const i=o.querySelector(".desktop-mode-dock__item-primary");ed(i??o,s),ge.publish("desktop-mode/badge-changed",{itemId:e,count:s,rail:this.rail})}clearBadge(e){this.setBadge(e,0)}setAttention(e,n,o={}){const s=this._resolveTileElement(e);if(!s)return;const i=this.attentionTimers.get(e);if(i!==void 0&&(window.clearTimeout(i),this.attentionTimers.delete(e)),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(e),this.setAttention(e,null)},a);this.attentionTimers.set(e,d)}}_resolveTileElement(e){return this.itemElements.get(e)??this.systemItemElements.get(e)??null}appendSystemItem(e){this.systemItems.push(e),this.systemSeparator||(this.systemSeparator=document.createElement("div"),this.systemSeparator.className="desktop-mode-dock__separator",this.systemSeparator.setAttribute("aria-hidden","true"),this.systemHost.appendChild(this.systemSeparator));const n=this.createSystemItemButton(e);this.systemItemElements.set(e.id,n),this.systemHost.appendChild(n),this.updateActiveStates(),C(v.DOCK_TILE_RENDERED,{...this.buildHookContextBase(),item:e,isSystem:!0,el:n})}render(){if(Ce.activeDragReset){const o=Ce.activeDragReset;Ce.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="";const e=this.buildHookContextBase();C(v.DOCK_BEFORE_RENDER,{...e,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of this.items){if(!n&&o.isCore===!1){if(this.itemHost.childElementCount>0){const i=document.createElement("div");i.className="desktop-mode-dock__separator desktop-mode-dock__separator--group",i.setAttribute("aria-hidden","true"),this.itemHost.appendChild(i)}n=!0}const s=this.createItemButton(o);this.itemElements.set(o.id,s),this.itemHost.appendChild(s),C(v.DOCK_TILE_RENDERED,{...e,item:o,isSystem:!1,el:s})}C(v.DOCK_AFTER_RENDER,{...e,items:this.items,tileElements:this.itemElements})}createSystemItemButton(e){const n={...this.buildHookContextBase(),item:e,isSystem:!0},o=document.createElement("div"),s=["desktop-mode-dock__item","desktop-mode-dock__item--system"],i=q(v.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=e.id;const r=document.createElement("button");r.className="desktop-mode-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",e.title),r.appendChild(this.resolveIcon(e.icon,e.title)),r.addEventListener("click",()=>e.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,e.title,n);const a=Ha({tile:o,item:{id:e.id,title:e.title,icon:e.icon,url:""},getInstances:()=>{const d=this.windowManager.getById(e.id);return d?[d]:[]},enableGhost:!!e.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(e.onOpenNew??e.onOpen)()},suppressTooltip:d=>{d&&this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${e.id}`,a),q(v.DOCK_TILE_ELEMENT,o,n)}createItemButton(e){const n={...this.buildHookContextBase(),item:e,isSystem:!1},o=document.createElement("div"),s=["desktop-mode-dock__item"];e.multi&&s.push("desktop-mode-dock__item--multi");const i=q(v.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=e.id;const r=document.createElement("button");r.className="desktop-mode-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",e.title);const a=this.resolveIcon(e.icon,e.title,e.url);if(r.appendChild(a),e.badge>0){const c=e.badge>99?"99+":String(e.badge),u=document.createElement("span");u.className="desktop-mode-dock__badge",u.textContent=c,u.setAttribute("aria-label",oe(Xt("%d update","%d updates",e.badge),e.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(e)}),o.addEventListener("contextmenu",c=>{c.preventDefault(),Qa({x:c.clientX,y:c.clientY,id:e.id,title:e.title,surface:"dock",pluginFile:e.pluginFile??null,pluginName:e.pluginName??null})}),o.appendChild(r),this.bindTooltipFiltered(o,e.title,n);const d=this.resolveItemBaseId(e),l=Ha({tile:o,item:{id:e.id,title:e.title,icon:e.icon,url:e.url},getInstances:()=>{if(e.multi)return this.windowManager.getAllByBaseId(d);const c=this.windowManager.getById(d)||this.windowManager.getById(e.id);return c?[c]:[]},enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(e),suppressTooltip:c=>{c&&this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}});return this.peekTeardowns.set(e.id,l),this.attachDragReorder(o,e.id),q(v.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(e,n){let i=!1,r=0,a=0,d=[],l=null,c=-1,u=null,p=!1;const f=()=>{i=!1,e.classList.remove("desktop-mode-dock__item--dragging"),e.style.transform="",e.style.transition="",document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",L),document.removeEventListener("pointercancel",b),document.removeEventListener("keydown",A,!0),window.removeEventListener("blur",I),document.removeEventListener("visibilitychange",_),c=-1,u=null},g=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 O of Array.from(this.itemHost.children))O instanceof HTMLElement&&O!==e&&g(O)&&k(O)},h=()=>{const k=[];for(const O of Array.from(this.itemHost.children))g(O)&&k.push(O.dataset.menuSlug);return k},w=k=>{m(O=>{const M=k.get(O);if(!M)return;const X=O.getBoundingClientRect(),Z=M.left-X.left,te=M.top-X.top;if(Math.abs(Z)<.5&&Math.abs(te)<.5)return;O.style.transition="none",O.style.transform=`translate(${Z}px, ${te}px)`,O.offsetHeight,O.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",O.style.transform="";const T=()=>{O.style.transition="",O.style.transform="",O.removeEventListener("transitionend",T)};O.addEventListener("transitionend",T)})},x=k=>{if(c!==-1&&k.pointerId!==c)return;if(!i){const P=k.clientX-r,V=k.clientY-a;if(P*P+V*V<5*5)return;i=!0,d=h(),l=e.nextSibling,u=e.getBoundingClientRect(),e.classList.add("desktop-mode-dock__item--dragging"),this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}if(!u)return;const O=k.clientX-r,M=k.clientY-a;e.style.transform=`translate(${O}px, ${M}px)`;const Z=document.elementFromPoint(k.clientX,k.clientY)?.closest(".desktop-mode-dock__item");if(!Z||Z===e||!g(Z))return;const te=Z.getBoundingClientRect();let T;this.orientation==="bottom"?T=k.clientX<te.left+te.width/2:T=k.clientY<te.top+te.height/2;const F=new Map;m(P=>{F.set(P,P.getBoundingClientRect())});let H=!1;if(T?Z!==e.nextSibling&&(this.itemHost.insertBefore(e,Z),H=!0):Z.nextSibling!==e&&(this.itemHost.insertBefore(e,Z.nextSibling),H=!0),H){e.style.transform="";const P=e.getBoundingClientRect();r=P.left+P.width/2,a=P.top+P.height/2,e.style.transform=`translate(${k.clientX-r}px, ${k.clientY-a}px)`,w(F)}},D=()=>{e.classList.remove("desktop-mode-dock__item--dragging"),e.style.transform="",e.style.transition="",document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",L),document.removeEventListener("pointercancel",b),document.removeEventListener("keydown",A,!0),window.removeEventListener("blur",I),document.removeEventListener("visibilitychange",_),c=-1,u=null,i=!1,Ce.activeDragReset===f&&(Ce.activeDragReset=null)},y=()=>{e.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",e.style.transform="";const k=()=>{e.style.transition="",e.removeEventListener("transitionend",k)};e.addEventListener("transitionend",k)},E=k=>{const O=window.wp?.desktop;if(!O?.getOsSettings||!O?.updateOsSettings)return;const M=O.getOsSettings().dockOrder,X=new Set(k),Z=[];let te=!1;for(const T of M){if(X.has(T)){te||(Z.push(...k),te=!0);continue}Z.push(T)}te||Z.push(...k),O.updateOsSettings({dockOrder:Z})},L=k=>{if(c!==-1&&k.pointerId!==c)return;if(!i){D();return}p=!0;const O=h();y(),D(),O.length===d.length&&O.every((X,Z)=>X===d[Z])||E(O),setTimeout(()=>{p=!1},200)},b=k=>{if(!(k&&c!==-1&&k.pointerId!==c)){if(i&&l!==void 0){const O=new Map;m(M=>{O.set(M,M.getBoundingClientRect())}),this.itemHost.insertBefore(e,l),w(O)}y(),D()}},A=k=>{k.key==="Escape"&&b()},I=()=>b(),_=()=>{document.visibilityState!=="visible"&&b()};e.addEventListener("pointerdown",k=>{if(k.button===0){if(Ce.activeDragReset){const O=Ce.activeDragReset;Ce.activeDragReset=null,O()}(i||c!==-1)&&f(),r=k.clientX,a=k.clientY,c=k.pointerId,i=!1,Ce.activeDragReset=f,document.addEventListener("pointermove",x),document.addEventListener("pointerup",L),document.addEventListener("pointercancel",b),document.addEventListener("keydown",A,!0),window.addEventListener("blur",I),document.addEventListener("visibilitychange",_)}}),e.addEventListener("click",k=>{p&&(k.preventDefault(),k.stopImmediatePropagation())},!0)}resolveIcon(e,n,o){if(e.startsWith("dashicons-")&&e!=="dashicons-admin-generic"){const s=document.createElement("span");return s.className=`dashicons ${e}`,s.setAttribute("aria-hidden","true"),s}if(e.startsWith("data:image/svg+xml;base64,")){const s=e.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(s))return this._makeSvgIcon(e)}if(e.startsWith("url("))return this._makeSvgIcon(e);if(e.startsWith("http://")||e.startsWith("https://")){const s=document.createElement("img");return s.className="desktop-mode-dock__item-img",s.src=e,s.alt="",s.setAttribute("aria-hidden","true"),s}if(o){const s=this._extractNativeMenuIcon(o);if(s)return s}if(e==="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(e){const n=document.createElement("span");return n.className="desktop-mode-dock__item-svg",n.style.backgroundImage=e.startsWith("url(")?e:`url("${e}")`,n.style.backgroundSize="contain",n.style.backgroundRepeat="no-repeat",n.style.backgroundPosition="center",n.setAttribute("aria-hidden","true"),n}_extractNativeMenuIcon(e){const n=document.getElementById("adminmenu");if(!n)return null;let o;try{const p=new URL(e,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 c=window.getComputedStyle(r,"::before").backgroundImage;if(c&&c!=="none"&&!c.includes('url("")'))return this._makeSvgIcon(c);const u=window.getComputedStyle(r).backgroundImage;return u&&u!=="none"&&!u.includes('url("")')?this._makeSvgIcon(u):null}createLetterBadge(e){const n=document.createElement("span");n.className="desktop-mode-dock__item-letter",n.setAttribute("aria-hidden","true");const o=e.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=Ls(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(e,n,o){const s=q(v.DOCK_TILE_TOOLTIP,n,o);e.dataset.dockTooltip=s,s!==""&&(e.addEventListener("pointerenter",()=>{this.positionTooltip(e,s),this.tooltip.classList.add("desktop-mode-dock__tooltip--visible")}),e.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}))}positionTooltip(e,n){const o=e.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(e){if(e.id.startsWith("dock:")){const o=e.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(mo(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(mo(e.url)||xt(e.url))return;const n=this.deriveWindowId(e.url);this.windowManager.open({id:n,baseId:n,url:e.url,parentUrl:e.url,title:e.title,icon:e.icon.startsWith("dashicons-")?e.icon:"dashicons-admin-generic",submenu:e.submenu,multi:!!e.multi})}openNewInstance(e){if(mo(e.url))return;const n=window.wp?.desktop?.openNewWindow;if(e.windowId&&!e.url&&n?.(e.windowId,{source:"dock-peek"}))return;const o=Ea(e.url);if(o&&n?.(o,{source:"dock-peek"}))return;const s=this.deriveWindowId(e.url);this.windowManager.openNew({id:s,baseId:s,url:e.url,parentUrl:e.url,title:e.title,icon:e.icon.startsWith("dashicons-")?e.icon:"dashicons-admin-generic",submenu:e.submenu,multi:!0})}deriveWindowId(e){return le(e,this.adminUrl)}resolveItemBaseId(e){return e.windowId?e.windowId:Ea(e.url)??this.deriveWindowId(e.url)}bindWindowEvents(){const e=()=>this.updateActiveStates();this.boundRefresh=e,document.addEventListener("desktop-mode-window-opened",e),document.addEventListener("desktop-mode-window-closed",e),document.addEventListener("desktop-mode-window-focused",e),window.wp?.hooks?.addAction?.("desktop-mode.desktop.switched",this.hooksNamespace,e),window.wp?.hooks?.addAction?.("desktop-mode.desktop.closed",this.hooksNamespace,e)}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 e of this.attentionTimers.values())window.clearTimeout(e);this.attentionTimers.clear();for(const e of this.peekTeardowns.values())e();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 e=this.windowManager.getFocused(),n=e?e.config.baseId||e.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):[],l=this.windowManager.getById(a),c=!i.multi&&!!l&&s(l),u=i.multi?d.length>0:c,p=n===a&&!!e&&s(e);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=!!e&&e.id===i.id;r.classList.toggle("desktop-mode-dock__item--active",a),r.classList.toggle("desktop-mode-dock__item--focused",d)}}};Ce.instanceCounter=0,Ce.activeDragReset=null;let yo=Ce;function ed(t,e){const n=t.querySelector(":scope > .desktop-mode-dock__badge");if(e<=0){n?.remove();return}const o=e>99?"99+":String(e);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",oe(Xt("%d notification","%d notifications",e),e));return}const s=document.createElement("span");s.className="desktop-mode-dock__badge",s.textContent=o,s.setAttribute("aria-label",oe(Xt("%d notification","%d notifications",e),e)),t.appendChild(s)}const td=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),Os={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(t){const e=new yo(t.container,t.windowManager,t.items,t.adminUrl,t.orientation);return{[td]:e,replaceItems:o=>e.replaceItems(o),appendSystemItem:o=>e.appendSystemItem(o),removeSystemItem:o=>e.removeSystemItem(o),setBadge:(o,s)=>e.setBadge(o,s),setAttention:(o,s,i)=>e.setAttention(o,s,i),setOrientation:o=>e.setOrientation(o),destroy:()=>e.destroy()}}};function bo(t){if(!t)return null;const n=t[td];return n instanceof yo?n:null}function Tm(){Ua(Os)}function nd(t){const{from:e,to:n,angle:o}=t.customGradient;return`linear-gradient(${o}deg, ${e}, ${n})`}function Nm(t){tn({id:kf,label:N("Custom gradient"),type:"css",preview:nd(t.state),resolveValue:()=>nd(t.state)})}function Dm(t){if(!t.customImage){xa(Na);return}const n=`url("${encodeURI(t.customImage.url)}") center/cover no-repeat, #1d2327`;tn({id:Na,label:N("Custom image"),type:"css",value:n,preview:n})}let vo=null;function Om(t){return window.desktopModeRenderOsSettingsPanel?Promise.resolve(window.desktopModeRenderOsSettingsPanel):vo||(vo=new Promise((e,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}e(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=t,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)}),vo)}class Rm{constructor(e,n){this.activeEditorTeardown=null,this.tabRegistryUnsubscribe=null,this.activeTabId=null,this.osSettingsListeners=new Set,this._lastRenderedBody=null,this.config=e,this.layer=n,this.state=Lf(),Mf(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))}),Nm(this),Dm(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(([e,n])=>[e,{...n}]))}}subscribeOsSettings(e){return this.osSettingsListeners.add(e),()=>{this.osSettingsListeners.delete(e)}}apply(){const e=document.getElementById("desktop-mode-shell");if(!e)return;const n=ks(this.state.wallpaper)||ks(Ra())||ks(_s)||Ia()[0];n&&this.layer.apply(n);const o=Oa(),s=o.find(a=>a.id===this.state.accent)??o[0],i=Es.find(a=>a.id===this.state.dockSize)??Es[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`),e.setAttribute("data-desktop-mode-layout",this.state.desktopLayout),Kf(this.state.dockRailRenderer)}save(e={}){if(Pf(this.state,e),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(e){this._lastRenderedBody=e;const n=window.desktopModeRenderOsSettingsPanel;if(n){n(this,e);return}Om(this.config.osSettingsPanelBundleUrl??"").then(o=>{e.isConnected&&o(this,e)}).catch(o=>{typeof console<"u"&&console.error("[desktop-mode] OS Settings panel failed to load:",o)})}}const Mm="desktop-mode-exit";function Pm(){return{id:Mm,title:N("Exit Desktop Mode"),icon:"dashicons-exit",onOpen:()=>{$m()}}}async function $m(){const t=window.desktopModeAdminBar,e=t?.classicUrl||"/wp-admin/";if(!t?.ajaxUrl||!t?.nonce){od(e);return}const n=new URLSearchParams;n.set("action","save-desktop-mode"),n.set("nonce",t.nonce),n.set("enabled","");let o=e;try{const s=await fetch(t.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{}od(o)}function od(t){try{window.top.location.href=t}catch{window.location.href=t}}const Wm={userId:null,requestedAt:0,tabRequested:!1};let ko=null;function Um(){if(ko)return ko;const e=window.wp?.desktop?.createSharedStore;return typeof e!="function"?null:(ko=e("desktop-mode/user-edit/target",()=>({...Wm})),ko)}function Bm(t){const e=Um();if(e){e.state.userId=t,e.state.requestedAt=Date.now(),e.state.tabRequested=!0,e.notify();return}const n=window;n._wpdUserEditTarget={userId:t,requestedAt:Date.now(),tabRequested:!0}}const Rs=new Map;function Ae(t,e){const n=Rs.get(t);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-desktop-mode-vendor="${Hm(t)}"]`,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 ${t}`)),{once:!0});return}e?.translations&&_o(e.translations);for(const l of e?.l10n??[])_o(l);for(const l of e?.before??[])_o(l);const d=document.createElement("script");d.src=t,d.async=!0,d.dataset.desktopModeVendor=t,d.addEventListener("load",()=>{d.dataset.loaded="1";for(const l of e?.after??[])_o(l);s()},{once:!0}),d.addEventListener("error",()=>{Rs.delete(t),d.remove(),i(new Error(`Failed to load ${t}`))},{once:!0}),document.head.appendChild(d)});return Rs.set(t,o),o}function _o(t){if(!t)return;const e=document.createElement("script");e.textContent=t,e.dataset.desktopModeVendorInline="1",document.head.appendChild(e)}function Hm(t){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}const Eo=new Map;function sd(t){if(!t||typeof t.id!="string"||t.id===""){typeof console<"u"&&console.warn("[desktop-mode] Ignored invalid module registration:",t);return}if(typeof t.url!="string"||t.url===""){typeof console<"u"&&console.warn(`[desktop-mode] Module "${t.id}" has no url; ignored.`);return}Eo.set(t.id,t)}function Fm(){return Array.from(Eo.keys())}async function id(t){if(!t||t.length===0)return;const e=t.filter(n=>!Eo.has(n));if(e.length>0)throw new Error(`[desktop-mode] Unknown module(s) in needs: ${e.map(n=>`"${n}"`).join(", ")}. Known modules: ${Fm().join(", ")||"(none)"}.`);await Promise.all(t.map(n=>{const o=Eo.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():Ae(o.url)}))}function rd(t,e){return{id:t,pluginUrl:e,prefersReducedMotion:zm(),visible:!document.hidden}}function zm(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class ad{constructor(e,n){this.generation=0,this.active=null,this.boundVisibilityChange=()=>{this.active&&C(v.WALLPAPER_VISIBILITY,{id:this.active.id,state:document.hidden?"hidden":"visible"})},this.element=e,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(e){const n=++this.generation;if(this.teardownActive(),e.type==="css"){this.applyCss(e);return}this.applyCanvas(e,n)}teardownActive(){if(!this.active)return;const{id:e,teardown:n}=this.active;this.active=null,C(v.WALLPAPER_UNMOUNTING,{id:e});try{n()}catch(o){C(v.SHELL_ERROR,{scope:"wallpaper-teardown",id:e,error:o}),typeof console<"u"&&console.error(`[desktop-mode] Wallpaper "${e}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(e){const n=e.resolveValue?e.resolveValue(rd(e.id,this.pluginUrl)):e.value;typeof n=="string"&&(this.element.style.setProperty("--desktop-mode-bg",n),document.getElementById("desktop-mode-shell")?.style.setProperty("--desktop-mode-bg",n))}applyCanvas(e,n){const o=rd(e.id,this.pluginUrl);C(v.WALLPAPER_MOUNTING,{id:e.id,container:this.element,ctx:o});const s=e.needs&&e.needs.length>0?id(e.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:e.id,teardown:r},C(v.WALLPAPER_MOUNTED,{id:e.id,container:this.element,ctx:o})};s.then(()=>{if(n!==this.generation)return;let r;try{r=e.mount(this.element,o)}catch(a){this.handleMountFailure(e.id,a);return}if(jm(r)){r.then(i,a=>{n===this.generation&&this.handleMountFailure(e.id,a)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(e.id,r)})}handleMountFailure(e,n){this.element.innerHTML="",C(v.WALLPAPER_MOUNT_FAILED,{id:e,error:n}),C(v.SHELL_ERROR,{scope:"wallpaper-mount",id:e,error:n}),typeof console<"u"&&console.error(`[desktop-mode] Wallpaper "${e}" failed to mount:`,n)}}function jm(t){return!!t&&typeof t=="object"&&typeof t.then=="function"}function Gm(t){const{osSettings:e}=t,n=new Set,o=new Set,s=async l=>{if(!(!l.scriptUrl||o.has(l.scriptUrl))){try{await Ae(l.scriptUrl,{translations:l.scriptTranslations,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){C(v.SHELL_ERROR,{scope:"wallpaper-script-load",id:l.id,error:c})}o.add(l.scriptUrl)}},i=l=>(window.desktopModeWallpapers||{})[l]??null,r=l=>l.type!=="css"||l.value===""?null:{id:l.id,label:l.label,type:"css",value:l.value,preview:l.preview!==""?l.preview:l.value},a=async l=>{if(n.has(l.id))return;const c=r(l);if(c){tn(c),n.add(l.id),e.apply();return}await s(l);const u=i(l.id);if(!u){C(v.SHELL_ERROR,{scope:"wallpaper-missing-def",id:l.id,error:new Error(`[desktop-mode] No wallpaper def on window.desktopModeWallpapers["${l.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)});return}try{tn(u)}catch(p){C(v.SHELL_ERROR,{scope:"wallpaper-register",id:l.id,error:p});return}n.add(l.id),e.apply()},d=l=>{n.has(l)&&(xa(l),n.delete(l),e.apply())};return async l=>{const c=new Set;for(const u of l)c.add(u.id);for(const u of Array.from(n))c.has(u)||d(u);for(const u of l)n.has(u.id)||await a(u)}}const dd=/^[a-z0-9_/-]+$/,ld=ce("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),ct=ld.state.registry,qm=ld.state.listeners;function So(t){const e=[],n=typeof t?.slug=="string"?t.slug.trim().toLowerCase():"";!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.slug!="string"||t.slug.trim()===""?e.push("slug (missing)"):dd.test(n)||e.push(`slug (must match ${dd} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),typeof t.run!="function"&&e.push("run (must be a function)")),tt("Command",e,t),ct.set(n,{...t,slug:n}),Ms()}function cd(t){ct.delete(t.toLowerCase())&&Ms()}function Co(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(ct.entries()))o.owner===t&&(ct.delete(n),e++);return e>0&&Ms(),e}function ud(){return Array.from(ct.values())}function Vm(){const t=[];for(const e of ct.values())e.aiCallable===!0&&t.push({slug:e.slug,label:e.label,description:e.description??"",hint:e.hint??""});return t}function Km(t){return ct.get(t.toLowerCase())??null}function Ms(){const t=Array.from(qm);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] command-registry listener threw:",n)}}function Ym(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await Ae(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(v.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.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 l=a.get(d.scriptHandle);l||(l=new Set,a.set(d.scriptHandle,l)),l.add(d.slug)}return a},i=r=>{const a=new Set;for(const l of ud())l.owner===r&&a.add(l.slug);const d=n.get(r);if(d)for(const l of d)a.add(l);return a};return async(r,a)=>{const d=new Set;for(const l of r)l.handle&&d.add(l.handle);for(const l of Array.from(t))if(!d.has(l)){for(const c of i(l))cd(c);t.delete(l)}for(const l of r)!l.handle||t.has(l.handle)||await o(l);n=s(a)}}const pd=ce("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),dn=pd.state.registry,Xm=pd.state.listeners;function fd(t){if(!t||typeof t.id!="string"||t.id.trim()===""||typeof t.label!="string"||t.label.trim()===""||typeof t.render!="function")return;const e=t.id.trim().toLowerCase();if(!/^[a-z0-9_\-]+$/.test(e)){typeof console<"u"&&console.warn("[desktop-mode] registerSettingsTab: id must be [a-z0-9_-]+, got",t.id);return}dn.set(e,{...t,id:e}),Ps()}function md(t){dn.delete(t.toLowerCase())&&Ps()}function Zm(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(dn.entries()))o.owner===t&&(dn.delete(n),e++);return e>0&&Ps(),e}function hd(){return Array.from(dn.values()).sort((t,e)=>(t.order??100)-(e.order??100))}function Ps(){const t=Array.from(Xm);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] settings-tab-registry listener threw:",n)}}function Jm(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await Ae(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(v.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.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 l=a.get(d.scriptHandle);l||(l=new Set,a.set(d.scriptHandle,l)),l.add(d.id)}return a},i=r=>{Zm(r);const a=n.get(r);if(a){const d=new Set(hd().map(l=>l.id));for(const l of a)d.has(l)&&md(l)}};return async(r,a)=>{const d=new Set;for(const l of r)l.handle&&d.add(l.handle);for(const l of Array.from(t))d.has(l)||(i(l),t.delete(l));for(const l of r)!l.handle||t.has(l.handle)||await o(l);n=s(a)}}const wd=ce("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),ln=wd.state.registry,Qm=wd.state.listeners,gd=/^[a-z0-9_/-]+$/;function yd(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):gd.test(t.id.trim().toLowerCase())||e.push(`id (must match ${gd} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),(typeof t.icon!="string"||t.icon.trim()==="")&&e.push("icon (missing)"),typeof t.match!="function"&&e.push("match (must be a function)"),typeof t.onClick!="function"&&typeof t.render!="function"&&e.push("onClick|render (at least one must be a function)")),tt("TitleBarButton",e,t);const n=t.id.trim().toLowerCase();ln.set(n,{...t,id:n}),$s()}function eh(t){ln.delete(t.toLowerCase())&&$s()}function th(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(ln.entries()))o.owner===t&&(ln.delete(n),e++);return e>0&&$s(),e}function nh(){return Array.from(ln.values()).sort((t,e)=>(t.order??100)-(e.order??100))}function $s(){const t=Array.from(Qm);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] title-bar-button registry listener threw:",n)}}function oh(){const t=new Set,e=new Set,n=async o=>{if(!o.scriptUrl||e.has(o.scriptUrl)){t.add(o.handle);return}try{await Ae(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){C(v.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}e.add(o.scriptUrl),t.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(t))s.has(i)||(th(i),t.delete(i));for(const i of o)!i.handle||t.has(i.handle)||await n(i)}}function sh(){const t=new Set,e=new Set,n=async o=>{if(!o.scriptUrl||e.has(o.scriptUrl)){t.add(o.handle);return}try{await Ae(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){C(v.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}e.add(o.scriptUrl),t.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(t))s.has(i)||(Gf(i),t.delete(i));for(const i of o)!i.handle||t.has(i.handle)||await n(i)}}const bd=ce("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),cn=bd.state.registry,ih=bd.state.listeners,vd=/^[a-z0-9_/-]+$/;function kd(t){const e=[];if(!t||typeof t!="object")e.push("def (not an object)");else{if(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):vd.test(t.id.trim().toLowerCase())||e.push(`id (must match ${vd} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!t.tokens||typeof t.tokens!="object")e.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(t.tokens))if(!o.startsWith("--")){e.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof t.match!="function"&&e.push("match (must be a function)")}tt("WindowTheme",e,t);const n=t.id.trim().toLowerCase();cn.set(n,{...t,id:n}),Ws()}function _d(t){cn.delete(t.toLowerCase())&&Ws()}function rh(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(cn.entries()))o.owner===t&&(cn.delete(n),e++);return e>0&&Ws(),e}function Ed(){return Array.from(cn.values()).sort((t,e)=>(t.priority??100)-(e.priority??100))}function Ws(){const t=Array.from(ih);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-theme registry listener threw:",n)}}function ah(){const t=new Set,e=new Set;let n=new Map;const o=new Set,s=async d=>{if(!d.scriptUrl||e.has(d.scriptUrl)){t.add(d.handle);return}try{await Ae(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(l){C(v.SHELL_ERROR,{scope:"window-theme-script-load",handle:d.handle,url:d.scriptUrl,error:l});return}e.add(d.scriptUrl),t.add(d.handle)},i=d=>{const l=new Map;if(!d)return l;for(const c of d){if(!c.scriptHandle||!c.id)continue;let u=l.get(c.scriptHandle);u||(u=new Set,l.set(c.scriptHandle,u)),u.add(c.id)}return l},r=d=>{const l=new Set;for(const u of Ed())u.owner===d&&l.add(u.id);const c=n.get(d);if(c)for(const u of c)l.add(u);return l},a=d=>{if(d){for(const l of d)if(!(!l.id||!l.tokens))try{kd({id:l.id,label:l.label,tokens:l.tokens,priority:l.priority,match:()=>!0,owner:l.scriptHandle||void 0}),o.add(l.id)}catch(c){C(v.SHELL_ERROR,{scope:"window-theme-shell-register",id:l.id,error:c})}}};return async(d,l)=>{const c=new Set;for(const u of d)u.handle&&c.add(u.handle);for(const u of Array.from(t)){if(c.has(u))continue;const p=r(u);for(const f of p)_d(f),o.delete(f);rh(u),t.delete(u)}a(l);for(const u of d)!u.handle||t.has(u.handle)||await s(u);n=i(l)}}const Sd=ce("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),un=Sd.state.registry,dh=Sd.state.listeners,Cd=/^[a-z0-9_/-]+$/;function pn(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):Cd.test(t.id.trim().toLowerCase())||e.push(`id (must match ${Cd} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof t.label!="string"||t.label.trim()==="")&&e.push("label (missing)"),typeof t.onClick!="function"&&typeof t.render!="function"&&e.push("onClick|render (at least one must be a function)"),typeof t.render!="function"&&(typeof t.icon!="string"||t.icon.trim()==="")&&e.push("icon (required when render is omitted)"),typeof t.match!="function"&&e.push("match (must be a function)"),t.placement!==void 0&&t.placement!=="left"&&t.placement!=="right"&&t.placement!=="controls"&&e.push('placement (must be "left", "right", or "controls")')),tt("WindowControl",e,t);const n=t.id.trim().toLowerCase();un.set(n,{...t,id:n}),Us()}function xd(t){un.delete(t.toLowerCase())&&Us()}function lh(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(un.entries()))o.owner===t&&(un.delete(n),e++);return e>0&&Us(),e}function Ad(){return Array.from(un.values()).sort((t,e)=>{const n=t.order??100,o=e.order??100;return n!==o?n-o:t.id.localeCompare(e.id)})}function Us(){const t=Array.from(dh);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-control registry listener threw:",n)}}function ch(){pn({id:"core/minimize",label:N("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:t=>{t.minimize()}}),pn({id:"core/maximize",label:N("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:t=>{t.toggleMaximize()}}),pn({id:"core/focus-tab",label:N("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:t=>{t.toggleFullscreen()}}),pn({id:"core/close",label:N("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:t=>{t.close()}})}function uh(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await Ae(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(v.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.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 l=a.get(d.scriptHandle);l||(l=new Set,a.set(d.scriptHandle,l)),l.add(d.id)}return a},i=r=>{const a=new Set;for(const l of Ad())l.owner===r&&a.add(l.id);const d=n.get(r);if(d)for(const l of d)a.add(l);return a};return async(r,a)=>{const d=new Set;for(const l of r)l.handle&&d.add(l.handle);for(const l of Array.from(t))if(!d.has(l)){for(const c of i(l))xd(c);lh(l),t.delete(l)}for(const l of r)!l.handle||t.has(l.handle)||await o(l);n=s(a)}}const Id=ce("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),fn=Id.state.registry,ph=Id.state.listeners,Ld=/^[a-z0-9_/-]+$/,Td=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Nd(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):Ld.test(t.id.trim().toLowerCase())||e.push(`id (must match ${Ld} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof t.slot!="string"||t.slot.trim()===""?e.push("slot (missing)"):Td.has(t.slot)||e.push(`slot (must be one of ${Array.from(Td).join(", ")})`),typeof t.match!="function"&&e.push("match (must be a function)"),typeof t.render!="function"&&e.push("render (must be a function)")),tt("WindowSlot",e,t);const n=t.id.trim().toLowerCase();fn.set(n,{...t,id:n}),Hs()}function Bs(t){fn.delete(t.toLowerCase())&&Hs()}function fh(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(fn.entries()))o.owner===t&&(fn.delete(n),e++);return e>0&&Hs(),e}function Dd(){return Array.from(fn.values()).sort((t,e)=>{const n=t.order??100,o=e.order??100;return n!==o?n-o:t.id.localeCompare(e.id)})}function Hs(){const t=Array.from(ph);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-slot registry listener threw:",n)}}function mh(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await Ae(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(v.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.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 l=a.get(d.scriptHandle);l||(l=new Set,a.set(d.scriptHandle,l)),l.add(d.id)}return a},i=r=>{const a=new Set;for(const l of Dd())l.owner===r&&a.add(l.id);const d=n.get(r);if(d)for(const l of d)a.add(l);return a};return async(r,a)=>{const d=new Set;for(const l of r)l.handle&&d.add(l.handle);for(const l of Array.from(t))if(!d.has(l)){for(const c of i(l))Bs(c);fh(l),t.delete(l)}for(const l of r)!l.handle||t.has(l.handle)||await o(l);n=s(a)}}const hh="desktop-mode-notice-dismissed";function wh(){const e=window.wp?.desktop?.config?.currentUserId;return typeof e=="number"&&e>0?String(e):"anon"}function Od(){return`${hh}:${wh()}`}function Fs(){try{const t=window.localStorage.getItem(Od());if(!t)return{};const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{}}function Rd(t){try{window.localStorage.setItem(Od(),JSON.stringify(t))}catch{}}function gh(t){return t?Fs()[t]===!0:!1}function Md(t){if(!t)return;const e=Fs();e[t]=!0,Rd(e)}function Pd(t){if(!t)return;const e=Fs();e[t]&&(delete e[t],Rd(e))}const yh=me`: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 ) )}`,jn=class jn extends ue{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const e=this.getAttribute("notice-id");e&&gh(e)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const e=this.getAttribute("notice-id");e&&Md(e),this.emit("wpd-notice-dismiss",{noticeId:e??void 0})}undismiss(){const e=this.getAttribute("notice-id");e&&Pd(e),this.hidden=!1}render(){const e=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return B` |
| 29 |
<span |
| 30 |
class="wpd-notice__icon dashicons ${e??""}" |
| 31 |
?hidden=${!e} |
| 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=${N("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(e){e.preventDefault(),e.stopPropagation(),this.dismiss()}};jn.props=["tone","notDismissible","icon","noticeId"],jn.styles=[yh],jn.help=void 0;let zs=jn;fe("wpd-notice",zs);const mn=ce("desktop-mode/window-notices",()=>({entries:new Map})),bh=/^[a-z0-9_/-]+$/;function $d(t){return`desktop-mode-notice/${t.toLowerCase()}`}function vh(t){const e=document.createElement("wpd-notice");return e.setAttribute("tone",t.tone??"info"),e.setAttribute("notice-id",t.id),t.dismissible===!1&&e.setAttribute("not-dismissible",""),t.icon&&e.setAttribute("icon",t.icon),e.innerHTML=t.message,e}function Wd(t){if(!t||typeof t!="object")return()=>{};const e=String(t.id??"").trim().toLowerCase();if(!e||!bh.test(e))return()=>{};if(typeof t.message!="string"||t.message==="")return()=>{};const n={...t,id:e};mn.state.entries.set(e,n);const o=$d(e);return Nd({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=mn.state.entries.get(e);if(!i)return!1;if(typeof i.match!="function")return!0;try{return i.match(s)===!0}catch{return!1}},render:s=>{const i=mn.state.entries.get(e);i&&s.appendChild(vh(i))}}),()=>js(e)}function js(t){const e=String(t??"").trim().toLowerCase();e&&mn.state.entries.delete(e)&&Bs($d(e))}function Ud(){return Array.from(mn.state.entries.values()).sort((t,e)=>{const n=t.order??100,o=e.order??100;return n!==o?n-o:t.id.localeCompare(e.id)})}function kh(t){const e=String(t??"").trim().toLowerCase();e&&Md(e)}function _h(t){const e=String(t??"").trim().toLowerCase();e&&Pd(e)}function Eh(t){if(!t)return;const e=new Set;if(typeof t.window=="string"&&t.window!==""&&e.add(t.window),Array.isArray(t.windows))for(const o of t.windows)typeof o=="string"&&o!==""&&e.add(o);const n=typeof t.urlContains=="string"&&t.urlContains!==""?t.urlContains.toLowerCase():null;if(!(e.size===0&&n===null))return o=>!(e.size>0&&!e.has(o.id)||n!==null&&!(typeof o.config.url=="string"?o.config.url.toLowerCase():"").includes(n))}function Bd(t){const e=new Set;for(const n of t)!n||typeof n.id!="string"||!n.id||(e.add(n.id.toLowerCase()),Wd({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:Eh(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of Ud())n.owner==="__server__"&&(e.has(n.id)||js(n.id))}const Hd=ce("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),hn=Hd.state.registry,Sh=Hd.state.listeners,Fd=/^[a-z0-9_/-]+$/;function Ch(t){const e=[];!t||typeof t!="object"?e.push("def (not an object)"):(typeof t.id!="string"||t.id.trim()===""?e.push("id (missing)"):Fd.test(t.id.trim().toLowerCase())||e.push(`id (must match ${Fd} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof t.match!="function"&&e.push("match (must be a function)"),typeof t.render!="function"&&e.push("render (must be a function)")),tt("WindowChrome",e,t);const n=t.id.trim().toLowerCase();hn.set(n,{...t,id:n}),Gs()}function zd(t){hn.delete(t.toLowerCase())&&Gs()}function xh(t){if(!t)return 0;let e=0;for(const[n,o]of Array.from(hn.entries()))o.owner===t&&(hn.delete(n),e++);return e>0&&Gs(),e}function jd(){return Array.from(hn.values()).sort((t,e)=>t.id.localeCompare(e.id))}function Gs(){const t=Array.from(Sh);for(const e of t)try{e()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-chrome registry listener threw:",n)}}function Ah(){const t=new Set,e=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||e.has(r.scriptUrl)){t.add(r.handle);return}try{await Ae(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(v.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}e.add(r.scriptUrl),t.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 l=a.get(d.scriptHandle);l||(l=new Set,a.set(d.scriptHandle,l)),l.add(d.id)}return a},i=r=>{const a=new Set;for(const l of jd())l.owner===r&&a.add(l.id);const d=n.get(r);if(d)for(const l of d)a.add(l);return a};return async(r,a)=>{const d=new Set;for(const l of r)l.handle&&d.add(l.handle);for(const l of Array.from(t))if(!d.has(l)){for(const c of i(l))zd(c);xh(l),t.delete(l)}for(const l of r)!l.handle||t.has(l.handle)||await o(l);n=s(a)}}const qs=window.location.origin;let Ih=0;const Tt=new Map,Nt=new Map,wn=new Map;function Lh(t,e){return wn.set(t,e),()=>{wn.get(t)===e&&wn.delete(t)}}function Th(){return`desktop-mode-conn-${++Ih}`}function Nh(t){const e=(d,l)=>{try{d.contentWindow?.postMessage(l,qs)}catch(c){typeof console<"u"&&console.error("[desktop-mode] connection: postMessage failed",c)}},n=(d,l={})=>{const c=Th(),u=Array.isArray(l.topics)?[...l.topics]:[],p=new Map,f=[];let g=!1,m=!1;const h=()=>{const b=wn.get(d);return b||(t.getById(d)?.iframe??null)},w=()=>{if(h())return!1;const b=t.getById(d);return!!b&&b.config?.native===!0},x=[],D=()=>{const b=h();if(b)for(;f.length;){const A=f.shift();e(b,{type:"desktop-mode-bridge-publish",connectionId:c,topic:A.topic,payload:A.payload})}},y={id:c,target:d,isOpen:()=>g,subscribe(b,A){const I=A;if(w()){const k=qp(d,b,(O,M)=>{C(v.CONNECTION_MESSAGE,{connectionId:c,topic:M.channel,direction:"in"});try{I(O,{topic:M.channel})}catch(X){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",X)}});return x.push(k),k}let _=p.get(b);return _||(_=new Set,p.set(b,_)),_.add(I),()=>{_?.delete(I)}},send(b,A){if(m)return;if(C(v.CONNECTION_MESSAGE,{connectionId:c,topic:b,direction:"out"}),w()){Kp(d,b,A);return}if(!g){f.push({topic:b,payload:A});return}const I=h();I&&e(I,{type:"desktop-mode-bridge-publish",connectionId:c,topic:b,payload:A})},disconnect(){y._destroy("disconnect")},_targetWindow:h,_handleIframeMessage(b){if(!b||typeof b!="object")return;const A=b;if(A.type==="desktop-mode-bridge-handshake-ack"){if(g)return;g=!0,C(v.CONNECTION_OPENED,{connectionId:c,targetWindowId:d,topics:u,connection:y});try{l.onOpen?.()}catch(I){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",I)}D();return}if(A.type==="desktop-mode-bridge-publish"){const I=b,_=typeof I.topic=="string"?I.topic:"";if(!_)return;C(v.CONNECTION_MESSAGE,{connectionId:c,topic:_,direction:"in"});const k=p.get(_);if(k)for(const M of Array.from(k))try{M(I.payload,{topic:_})}catch(X){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",X)}const O=p.get("*");if(O)for(const M of Array.from(O))try{M(I.payload,{topic:_})}catch(X){typeof console<"u"&&console.error("[desktop-mode] connection wildcard subscriber threw:",X)}return}A.type==="desktop-mode-bridge-disconnect"&&y._destroy("disconnect")},_destroy(b){if(m)return;m=!0;const A=g;g=!1,Tt.delete(c);const I=Nt.get(d);I&&(I.delete(c),I.size===0&&Nt.delete(d));for(const _ of x.splice(0))try{_()}catch{}if(A){const _=h();_&&e(_,{type:"desktop-mode-bridge-disconnect",connectionId:c})}C(v.CONNECTION_CLOSED,{connectionId:c,reason:b});try{l.onClose?.(b)}catch(_){typeof console<"u"&&console.error("[desktop-mode] connection.onClose threw:",_)}}};Tt.set(c,y);let E=Nt.get(d);if(E||(E=new Set,Nt.set(d,E)),E.add(c),w())return Promise.resolve().then(()=>{if(!(m||g)){g=!0,C(v.CONNECTION_OPENED,{connectionId:c,targetWindowId:d,topics:u});try{l.onOpen?.()}catch(b){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",b)}}}),y;const L=h();return L&&e(L,{type:"desktop-mode-bridge-handshake",connectionId:c,targetWindowId:d,topics:u}),y},o=(d,l)=>{if(!d||typeof d!="object")return;const c=d;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 l=="string"&&l!==""){s(l,c.requestId,Array.isArray(c.topics)?c.topics:[]);return}if(typeof c.connectionId!="string")return;Tt.get(c.connectionId)?._handleIframeMessage(d)},s=(d,l,c)=>{const p=wn.get(d)??t.getById(d)?.iframe??null;if(!p)return;const f=q(v.IFRAME_CONNECTION_REQUEST,!0,{windowId:d,requestId:l,topics:c.slice()});if(f===!1){try{p.contentWindow?.postMessage({type:"desktop-mode-bridge-connection-ack",requestId:l,accepted:!1,reason:"rejected"},qs)}catch{}return}const g=f&&typeof f=="object"&&Array.isArray(f.topics)?f.topics:c,m=n(d,{topics:g});try{p.contentWindow?.postMessage({type:"desktop-mode-bridge-connection-ack",requestId:l,accepted:!0,connectionId:m.id},qs)}catch{}};return{connect:n,getConnection:d=>Tt.get(d)??null,routeIncomingFromIframe:o,onIframeReady:d=>{const l=Nt.get(d);if(l)for(const c of Array.from(l)){const u=Tt.get(c);if(!u||u.isOpen())continue;const p=u._targetWindow();p&&e(p,{type:"desktop-mode-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:d=>{const l=Nt.get(d);if(l)for(const c of Array.from(l))Tt.get(c)?._destroy("window-closed")}}}const Dh={};function Oh(...t){(typeof{url:ls&&ls.tagName.toUpperCase()==="SCRIPT"&&ls.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&Dh?"production":void 0)!=="production"&&console.log(...t)}const Rh="iframe:";function Vs(t){return Rh+t}function Gd(t){return t.icon&&typeof t.icon=="string"&&t.icon.startsWith("dashicons-")?t.icon:t.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function Mh(t,e){const n=e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}class Ph{constructor(e){this.subscribedWindowId=null,this.manager=e.manager,this.adminUrl=e.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(Vs(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 e=this.manager.getFocused();e&&this.onFocused(e.id)}onFocused(e){if(this.subscribedWindowId!==e){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(Vs(this.subscribedWindowId))}this.subscribedWindowId=e,this.sendSubscribe(e)}}sendSubscribe(e){const n=this.manager.getById(e);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"desktop-mode-commands-subscribe"},window.location.origin)}catch(o){Oh("[wpd-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(e,n){const o=Vs(e);Co(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=Mh(e,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?pa(s.iconSvg):"",a={slug:i,label:s.label,icon:Gd(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,Gd(s)):this.runProxy(e,s.name)};try{So(a)}catch(d){console.error("[desktop-mode] iframe-bridge: dropping bad command",a,d)}}}runNavigate(e,n,o){return(s,i)=>{if(i.close(),xt(e))return;const r=le(e,this.adminUrl);this.manager.open({id:r,baseId:r,url:e,title:n,icon:o})}}runProxy(e,n){return(o,s)=>{s.close();const i=this.manager.getById(e);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 qd="global",$h=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,Wh=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,Uh=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,Bh=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,Hh=/getSiteEditorPage\s*\(|site-editor\.php/,Fh=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function zh(t){const e=window.__desktopModeMenuCommands;if(!Array.isArray(e))return null;for(const n of e)if(n&&typeof n=="object"&&n.name===t&&typeof n.url=="string"&&n.url!=="")return{label:typeof n.label=="string"?n.label:"",url:n.url};return null}class jh{constructor(e){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=e.manager,this.adminUrl=e.adminUrl}install(){this.tryMount(0)}tryMount(e){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){e<40&&window.setTimeout(()=>this.tryMount(e+1),150);return}this.mount()}mount(){const e=window.wp,n=e.element,o=e.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 l=document.createElement("div");l.setAttribute("aria-hidden","true"),l.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(l),this.host=l;const c={perLoader:{},statics:[],loadersList:[]},u=m=>{if(!Array.isArray(m)||m.length===0)return"";const h=new Array(m.length);for(let w=0;w<m.length;w++){const x=m[w];h[w]=x&&x.name?x.name:""}return h.join("|")},p=()=>{let m=[];for(const h of c.loadersList){const w=c.perLoader[h];Array.isArray(w)&&(m=m.concat(w))}Array.isArray(c.statics)&&(m=m.concat(c.statics)),this.callbackCache=Object.create(null);for(const h of m)h&&h.name&&typeof h.callback=="function"&&(this.callbackCache[h.name]=h.callback);this.publish(m)},f=m=>{const h=m.loader;let w=null;try{w=h.hook({search:""})}catch{}const x=w&&Array.isArray(w.commands)?w.commands:[],D=a(()=>u(x),[x]);return i(()=>{c.perLoader[h.name]=x,p()},[D]),i(()=>()=>{delete c.perLoader[h.name],p()},[]),null},g=()=>{const m=d(E=>{const L=E("core/commands");return!L||typeof L.getCommandLoaders!="function"?[]:[...L.getCommandLoaders(!1)||[],...L.getCommandLoaders(!0)||[]]},[]),h=d(E=>{const L=E("core/commands");return!L||typeof L.getCommands!="function"?[]:[...L.getCommands(!1)||[],...L.getCommands(!0)||[]]},[]),w=a(()=>Array.isArray(m)?m.map(E=>E&&E.name||""):[],[m]),x=w.join("|");i(()=>{c.loadersList=w,p()},[x]);const D=a(()=>u(Array.isArray(h)?h:[]),[h]);if(i(()=>{c.statics=Array.isArray(h)?h:[],p()},[D]),!Array.isArray(m)||m.length===0)return null;const y=[];for(const E of m)!E||typeof E.hook!="function"||y.push(s(f,{key:E.name,loader:E}));return s(n.Fragment||"div",null,y)};try{this.root=n.createRoot(l),this.root.render(s(g))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(e){const n=Object.create(null),o=[];for(const i of e)!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(qd);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!==""?pa(i.iconSvg):void 0,owner:qd,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{So(d)}catch(l){console.error("[desktop-mode] shell-harvester: dropping bad command",d,l)}}}}classify(e){const n={name:String(e.name),label:String(e.label),icon:typeof e.icon=="string"?e.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof e.callback=="function"?e.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;e.icon&&typeof e.icon!="string"&&(n.iconSvg=this.renderIcon(e.icon));const s=zh(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 e.callback=="function"){let i="";try{i=Function.prototype.toString.call(e.callback)}catch{i=""}const r=i.match($h)||i.match(Wh)||i.match(Uh);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(Bh.test(i)){const d=Hh.test(i)?n.name.match(Fh):null;if(d){const l=d[1],c=d[2],u=`/${l}/${c}`;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(e){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(e);if(typeof o=="string"&&o.toLowerCase().startsWith("<svg"))return o}catch{}return""}iconFor(e){return e.icon&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}runNavigate(e,n,o){return(s,i)=>{if(i.close(),xt(e))return;const r=le(e,this.adminUrl);this.manager.open({id:r,baseId:r,url:e,title:n,icon:o})}}runInvoke(e,n,o){return(s,i)=>{i.close();const r=this.callbackCache[e];if(typeof r!="function")return;const a=this.runWithNavCapture(r);if(a){const d=le(a,this.adminUrl);this.manager.open({id:d,baseId:d,url:a,title:n,icon:o})}}}runWithNavCapture(e){let n=null;const o=d=>{n===null&&typeof d=="string"&&d!==""&&(n=d)},s=window.location,i=new Proxy(s,{get(d,l){const c=d[l];return l==="assign"||l==="replace"?u=>o(u):typeof c=="function"?c.bind(d):c},set(d,l,c){return l==="href"&&o(c),!0}}),r=[],a=d=>{try{Object.defineProperty(d,"location",{configurable:!0,get:()=>i,set:l=>o(l)}),r.push({obj:d,key:"location"})}catch{}};a(document),a(window);try{e({close:()=>{}})}catch{}finally{for(const d of r)try{delete d.obj[d.key]}catch{}}return n}}const Dt=[];function Ks(t){tt("Widget",uo(t,Kd),t);const e=Dt.findIndex(n=>n.id===t.id);e>=0?Dt[e]=t:Dt.push(t)}function Gh(t){const e=Dt.findIndex(n=>n.id===t);e>=0&&Dt.splice(e,1)}function Vd(){const t=Dt.slice(),e=q(v.WIDGETS,t);return Array.isArray(e)?e.filter(qh):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.widgets` filter returned a non-array; falling back to seed list."),t)}function gn(t){return Vd().find(e=>e.id===t)}const Kd=[{field:"id",message:"missing or not a non-empty string",valid:t=>typeof t.id=="string"&&t.id!==""},{field:"label",message:"missing or not a non-empty string",valid:t=>typeof t.label=="string"&&t.label!==""},{field:"description",message:"not a string",valid:t=>typeof t.description=="string"},{field:"icon",message:"missing or not a non-empty string",valid:t=>typeof t.icon=="string"&&t.icon!==""},{field:"mount",message:"not a function",valid:t=>typeof t.mount=="function"}];function qh(t){return uo(t,Kd).length===0}let He=null;function Vh(t){if(He)return;const e=document.createElement("div");e.className="desktop-mode-widget-picker",e.setAttribute("role","menu"),e.setAttribute("aria-label",N("Add widget"));const n=document.createElement("div");n.className="desktop-mode-widget-picker__title",n.textContent=N("Add widget"),e.appendChild(n);const o=document.createElement("div");o.className="desktop-mode-widget-picker__list",e.appendChild(o),Xd(o,t),document.body.appendChild(e),Kh(e,t.anchor);const s=a=>{const d=a.target;d&&(e.contains(d)||t.anchor.contains(d)||Yd())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&Yd()};document.addEventListener("keydown",i),He={panel:e,options:t,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function xo(){if(!He)return;const t=He.panel.querySelector(".desktop-mode-widget-picker__list");t&&Xd(t,He.options)}function Yd(){He&&(document.removeEventListener("pointerdown",He.onOutsidePointerDown,!0),document.removeEventListener("keydown",He.onKeyDown),He.panel.remove(),He=null)}function Xd(t,e){t.innerHTML="";const n=new Set(e.enabledIds()),o=e.registry();if(o.length===0){const s=document.createElement("div");s.className="desktop-mode-widget-picker__empty",s.textContent=N("No widgets available. Activate a plugin that registers one, or see the docs for the registerWidget API."),t.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="desktop-mode-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("desktop-mode-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=oe(N("%s (already added)"),s.label):a=oe(N("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 l=document.createElement("span");l.className="desktop-mode-widget-picker__entry-text";const c=document.createElement("span");if(c.className="desktop-mode-widget-picker__entry-label",c.textContent=s.label,l.appendChild(c),s.description){const u=document.createElement("span");u.className="desktop-mode-widget-picker__entry-description",u.textContent=s.description,l.appendChild(u)}if(i.appendChild(l),r){const u=document.createElement("span");u.className="desktop-mode-widget-picker__entry-status",u.textContent=N("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),e.onAdd(s.id)}),t.appendChild(i)}}function Kh(t,e){const n=e.getBoundingClientRect();t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.style.visibility="hidden";const o=t.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),t.style.left=`${Math.round(a)}px`,t.style.top=`${Math.round(d)}px`,t.style.visibility=""}const Ys="desktop-mode-widgets__card--floating",Yh="desktop-mode-widgets__card--movable",Xh="desktop-mode-widgets__card--resizable",Zd="desktop-mode-widgets__card--dragging",Jd="desktop-mode-widgets__card--resizing",Zh=160,Jh=80,Qh=280,ew=180,Ao=20,Qd=5,tw=Qd*Qd,nw='input, textarea, select, button, a, [contenteditable="true"]';function ow(t,e,n){const o=document.createElement("div");o.className="desktop-mode-widgets__card",o.dataset.widgetId=t.id;const s=t.movable===!0,i=t.resizable===!0;s&&o.classList.add(Yh),i&&o.classList.add(Xh),s?o.appendChild(sw(t,n.onRemove,n.onRedock)):o.appendChild(rw(t,n.onRemove));const r=document.createElement("div");r.className="desktop-mode-widgets__card-body",o.appendChild(r);let a=!1;e.geometry&&(Xs(o,e.geometry),o.classList.add(Ys),a=!0);const d=[];if(i)for(const c of lw()){const u=document.createElement("div");u.className=`desktop-mode-widgets__resize desktop-mode-widgets__resize--${c}`,u.setAttribute("aria-hidden","true"),u.dataset.dir=c,o.appendChild(u),d.push(dw(o,u,c,t,e,n,()=>a))}let l=null;if(s){const c=o.querySelector(".desktop-mode-widgets__chrome");c&&(l=aw(o,c,t,e,n,u=>{a=u}))}return{card:o,body:r,dispose:()=>{for(const c of d)try{c()}catch{}if(l)try{l()}catch{}o.remove()}}}function sw(t,e,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=t.label,o.appendChild(i),o.appendChild(iw(t,n));const r=el(t,e);return o.appendChild(r),o}function iw(t,e){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-redock",n.setAttribute("aria-label",oe(N("Dock %s back to widget column"),t.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(),e()}),n.dataset.noDrag="true",n}function rw(t,e){const n=el(t,e);return n.classList.add("desktop-mode-widgets__card-close--corner"),n}function el(t,e){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-close",n.setAttribute("aria-label",oe(N("Remove %s"),t.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(),e()}),n}function aw(t,e,n,o,s,i){let r=null,a=0,d=0,l=0,c=0,u=!1;const p=h=>{if(h.button!==0)return;const w=h.target;w&&w.closest(nw)||(h.preventDefault(),r=h.pointerId,a=h.clientX,d=h.clientY,u=!1,l=parseFloat(t.style.left)||0,c=parseFloat(t.style.top)||0,e.setPointerCapture(r))},f=()=>{if(!t.classList.contains(Ys)){const h=o.floatingParent.getBoundingClientRect(),w=t.getBoundingClientRect(),x={x:w.left-h.left,y:w.top-h.top,width:w.width||n.defaultWidth||Qh,height:w.height||n.defaultHeight||ew};Xs(t,x),t.classList.add(Ys),i(!0),s.onLiberate(x),l=parseFloat(t.style.left)||0,c=parseFloat(t.style.top)||0}t.classList.add(Zd)},g=h=>{if(r===null||h.pointerId!==r)return;const w=h.clientX-a,x=h.clientY-d;if(!u){if(w*w+x*x<tw)return;u=!0,f()}const D=uw(l+w,c+x,t.offsetWidth,t.offsetHeight,o.floatingParent);t.style.left=`${D.x}px`,t.style.top=`${D.y}px`},m=h=>{if(!(r===null||h.pointerId!==r)){try{e.releasePointerCapture(r)}catch{}r=null,u&&(u=!1,t.classList.remove(Zd),s.onGeometryChanged(tl(t)))}};return e.addEventListener("pointerdown",p),e.addEventListener("pointermove",g),e.addEventListener("pointerup",m),e.addEventListener("pointercancel",m),()=>{e.removeEventListener("pointerdown",p),e.removeEventListener("pointermove",g),e.removeEventListener("pointerup",m),e.removeEventListener("pointercancel",m)}}function dw(t,e,n,o,s,i,r){let a=null,d=0,l=0,c=0,u=0,p=0,f=0;const g=w=>{if(w.button!==0||!r()&&!cw(n))return;w.preventDefault(),w.stopPropagation(),a=w.pointerId,d=w.clientX,l=w.clientY;const x=t.getBoundingClientRect(),D=s.floatingParent.getBoundingClientRect();c=x.left-D.left,u=x.top-D.top,p=x.width,f=x.height,e.setPointerCapture(a),t.classList.add(Jd)},m=w=>{if(a===null||w.pointerId!==a)return;const x=w.clientX-d,D=w.clientY-l,y=pw(n,x,D,c,u,p,f,o,s.floatingParent,r());r()&&(t.style.left=`${y.x}px`,t.style.top=`${y.y}px`,t.style.width=`${y.width}px`),t.style.height=`${y.height}px`},h=w=>{if(!(a===null||w.pointerId!==a)){try{e.releasePointerCapture(a)}catch{}a=null,t.classList.remove(Jd),i.onGeometryChanged(tl(t))}};return e.addEventListener("pointerdown",g),e.addEventListener("pointermove",m),e.addEventListener("pointerup",h),e.addEventListener("pointercancel",h),()=>{e.removeEventListener("pointerdown",g),e.removeEventListener("pointermove",m),e.removeEventListener("pointerup",h),e.removeEventListener("pointercancel",h)}}function lw(){return["n","e","s","w","ne","nw","se","sw"]}function cw(t){return t==="s"}function Xs(t,e){t.style.left=`${e.x}px`,t.style.top=`${e.y}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`}function tl(t){return{x:parseFloat(t.style.left)||0,y:parseFloat(t.style.top)||0,width:t.offsetWidth,height:t.offsetHeight}}function uw(t,e,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,a=Math.max(0,i-n-Ao),d=Math.max(0,r-o-Ao);return{x:Math.min(Math.max(Ao,t),a),y:Math.min(Math.max(Ao,e),d)}}function pw(t,e,n,o,s,i,r,a,d,l){const c=a.minWidth??Zh,u=a.minHeight??Jh,p=a.maxWidth??1/0,f=a.maxHeight??1/0,g=d.clientWidth||d.getBoundingClientRect().width,m=d.clientHeight||d.getBoundingClientRect().height;let h=o,w=s,x=i,D=r;if((t==="e"||t==="ne"||t==="se")&&(x=Io(i+e,c,Math.min(p,g-o))),t==="w"||t==="nw"||t==="sw"){const y=Io(i-e,c,Math.min(p,o+i));h=o+(i-y),x=y}if((t==="s"||t==="se"||t==="sw")&&(D=Io(r+n,u,Math.min(f,m-s))),t==="n"||t==="ne"||t==="nw"){const y=Io(r-n,u,Math.min(f,s+r));w=s+(r-y),D=y}return l||(x=i,h=o),{x:h,y:w,width:x,height:D}}function Io(t,e,n){return n<e?e:Math.min(Math.max(t,e),n)}const nl="desktop-mode-widgets",ol="desktop-mode-widgets-geometry";function sl(){try{return window.localStorage.getItem(nl)}catch{return null}}function fw(){const t=sl();if(t===null)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}catch{return[]}}function Zs(t){try{window.localStorage.setItem(nl,JSON.stringify(t))}catch{}}function mw(){try{const t=window.localStorage.getItem(ol);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[o,s]of Object.entries(e)){const i=hw(s);i&&(n[o]=i)}return n}catch{return{}}}function Js(t){try{window.localStorage.setItem(ol,JSON.stringify(t))}catch{}}function hw(t){if(!t||typeof t!="object")return null;const{x:e,y:n,width:o,height:s}=t;return typeof e!="number"||!Number.isFinite(e)||typeof n!="number"||!Number.isFinite(n)||typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||s<=0?null:{x:e,y:n,width:o,height:s}}function ww(t){const e=`desktop-mode.widget.${t}.`,n=o=>{try{return localStorage.getItem(e+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(e+o,JSON.stringify(s))}catch{}},remove(o){try{localStorage.removeItem(e+o)}catch{}},clear(){try{for(let o=localStorage.length-1;o>=0;o--){const s=localStorage.key(o);s&&s.startsWith(e)&&localStorage.removeItem(s)}}catch{}}}}const gw=["clock"];class yw{constructor(e,n,o){this.mounted=new Map,this.generation=0,this.root=e,this.pluginUrl=n,this.enabledIds=fw(),this.geometry=mw(),this.floatingHost=o??e.parentElement??e,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(){sl()===null&&(this.enabledIds=gw.filter(e=>!!gn(e)),Zs(this.enabledIds));for(const e of this.enabledIds)this.mounted.has(e)||this.mountById(e);this.paintEmptyState()}add(e){this.enabledIds.includes(e)||gn(e)&&(this.enabledIds.push(e),Zs(this.enabledIds),this.mountById(e),this.paintEmptyState(),C(v.WIDGET_ADDED,{id:e}),xo())}remove(e){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==e),this.enabledIds.length!==n&&(Zs(this.enabledIds),this.geometry[e]&&(delete this.geometry[e],Js(this.geometry)),this.unmountById(e),this.paintEmptyState(),C(v.WIDGET_REMOVED,{id:e}),xo())}getEnabledIds(){return[...this.enabledIds]}mountIfEnabled(e){gn(e)&&this.enabledIds.includes(e)&&(this.mounted.has(e)||(this.mountById(e),this.paintEmptyState()))}unmount(e){this.mounted.has(e)&&(this.unmountById(e),this.paintEmptyState())}ensureMounted(e){return gn(e)?(this.enabledIds.includes(e)||this.add(e),!0):!1}disposeAll(){for(const e of Array.from(this.mounted.keys()))this.unmountById(e)}mountById(e){const n=gn(e);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[e]:void 0,i=ow(n,{floatingParent:this.floatingHost,geometry:s},{onRemove:()=>this.remove(e),onGeometryChanged:u=>this.persistGeometry(e,u),onLiberate:u=>this.liberate(e,u),onRedock:()=>this.redock(e)}),r=!!s,a={id:e,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(e,a),this.placeCard(i.card,r);const d={id:e,pluginUrl:this.pluginUrl,storage:ww(e)};C(v.WIDGET_MOUNTING,{id:e,container:i.body,ctx:d});const l=u=>{const p=this.mounted.get(e);if(!p||p.generation!==o){try{u()}catch{}return}p.teardown=u,C(v.WIDGET_MOUNTED,{id:e,container:i.body,ctx:d})};let c;try{c=n.mount(i.body,d)}catch(u){this.handleMountFailure(e,u);return}if(bw(c)){c.then(l,u=>{this.mounted.get(e)?.generation===o&&this.handleMountFailure(e,u)});return}l(c)}unmountById(e){const n=this.mounted.get(e);if(n){C(v.WIDGET_UNMOUNTING,{id:e});try{n.teardown?.()}catch(o){C(v.SHELL_ERROR,{scope:"widget-teardown",id:e,error:o}),typeof console<"u"&&console.error(`[desktop-mode] Widget "${e}" teardown threw:`,o)}this.generation++,n.frame.dispose(),this.mounted.delete(e)}}handleMountFailure(e,n){const o=this.mounted.get(e);o&&(o.frame.dispose(),this.mounted.delete(e)),C(v.WIDGET_MOUNT_FAILED,{id:e,error:n}),C(v.SHELL_ERROR,{scope:"widget-mount",id:e,error:n}),typeof console<"u"&&console.error(`[desktop-mode] Widget "${e}" failed to mount:`,n)}buildAddTile(){const e=document.createElement("button");e.type="button",e.className="desktop-mode-widgets__add",e.setAttribute("aria-label",N("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=N("Add widget"),e.appendChild(n),e.appendChild(o),e.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Vh({anchor:e,registry:()=>Vd(),enabledIds:()=>[...this.enabledIds],onAdd:i=>this.add(i)})}),e}placeCard(e,n){n?this.floatingHost.appendChild(e):this.listEl.appendChild(e)}liberate(e,n){const o=this.mounted.get(e);!o||o.floating||(o.floating=!0,this.floatingHost.appendChild(o.frame.card),Xs(o.frame.card,n),this.persistGeometry(e,n),this.paintEmptyState())}redock(e){const n=this.mounted.get(e);if(!n||!n.floating)return;n.floating=!1,this.geometry[e]&&(delete this.geometry[e],Js(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(e,n){this.geometry[e]=n,Js(this.geometry)}paintEmptyState(){let e=0;for(const n of this.mounted.values())n.floating||e++;this.root.classList.toggle("desktop-mode-widgets--has-widgets",e>0)}}function bw(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}const vw=280,kw=220,_w=520,Ew=400;function Sw(t,e,n){return o=>{const s=document.createElement("iframe");s.style.width="100%",s.style.height="100%",s.style.border="0",s.setAttribute("src",t.url),typeof t.sandbox=="string"&&t.sandbox!==""&&s.setAttribute("sandbox",t.sandbox),o.style.padding="0",o.appendChild(s);const i=Lh(n,s);e.push(i);let r;try{r=new URL(t.url,window.location.origin).origin}catch{r=window.location.origin}let a=null;const d=new Promise(u=>{a=u}),l=()=>{if(t.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{}Xp(n),a?.()};s.addEventListener("load",l);const c=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!==""&&Vp(n,p.channel,p.payload);try{t.onMessage?.(u.data)}catch(f){typeof console<"u"&&console.error("[desktop-mode] iframeContent.onMessage threw:",f)}};return window.addEventListener("message",c),e.push(()=>{window.removeEventListener("message",c),s.removeEventListener("load",l)}),d}}function Cw(t){return async e=>{const n=e.render;let o=n;const s=[];e.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=Sw(e.iframeContent,s,e.id));const i=e.onClose,r=s.length?()=>{for(const d of s)try{d()}catch{}i?.()}:i;return await t.open({id:e.id,baseId:e.baseId||e.id,native:!0,url:e.url||`#${e.id}`,title:e.title,icon:e.icon,x:e.x??0,y:e.y??0,width:e.width??_w,height:e.height??Ew,minWidth:e.minWidth??vw,minHeight:e.minHeight??kw,render:o,onClose:r,onResize:e.onResize,autofocus:e.autofocus,initialState:e.initialState,ownerHandle:e.ownerHandle,multi:e.multi,desktopId:e.desktopId})}}let xw=0;function Aw(t,e,n={}){const o=`desktop-mode/on-window/${t}/${++xw}`,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 l of r)Nr(l,o)}};for(const[l,c]of i){const u=e[l];u&&(r.push(c),j(c,o,p=>{const f=p;if(f.windowId!==t)return;const{windowId:g,...m}=f;u(m),l==="closed"&&!s&&d()}))}return d}function Iw(t){const{manager:e,appendSystemTile:n,removeSystemTile:o}=t,s=new Set,i=new Set,r=new Set,a=new Set,d=new Map,l=y=>{const E=Qr(y.id);return E?{width:Math.max(E.width,y.minWidth),height:Math.max(E.height,y.minHeight)}:{width:y.width,height:y.height}},c=y=>{if(i.has(y.templateId))return;if(document.getElementById(y.templateId)){i.add(y.templateId);return}if(!y.templateHtml)return;const E=document.createElement("template");E.id=y.templateId,E.innerHTML=y.templateHtml,document.body.appendChild(E),i.add(y.templateId)},u=y=>{const E=y.styleUrl;if(!E||a.has(E))return;const L=E.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${L}"]`)){const A=document.createElement("link");A.rel="stylesheet",A.href=E,y.styleHandle&&(A.dataset.desktopModeStyleHandle=y.styleHandle),document.head.appendChild(A)}if(Array.isArray(y.styleInline))for(const A of y.styleInline){if(typeof A!="string"||A==="")continue;const I=document.createElement("style");y.styleHandle&&(I.dataset.desktopModeStyleHandle=y.styleHandle),I.textContent=A,document.head.appendChild(I)}a.add(E)},p=async y=>{if(!(!y.scriptUrl||r.has(y.scriptUrl))){try{await Ae(y.scriptUrl,{translations:y.scriptTranslations,l10n:y.scriptL10n,before:y.scriptBefore,after:y.scriptAfter})}catch(E){C(v.SHELL_ERROR,{scope:"native-window-script-load",id:y.id,error:E})}r.add(y.scriptUrl)}},f=y=>{const L=(window.desktopModeNativeWindows||{})[y.id],b=(I,_)=>(I.appendChild(Qs(y.templateId)),L?.(I,_)),A=l(y);e.open({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:A.width,height:A.height,minWidth:y.minWidth,minHeight:y.minHeight,render:b,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle})},g=y=>{const L=(window.desktopModeNativeWindows||{})[y.id],b=(I,_)=>(I.appendChild(Qs(y.templateId)),L?.(I,_)),A=l(y);e.openNew({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:A.width,height:A.height,minWidth:y.minWidth,minHeight:y.minHeight,initialState:"normal",render:b,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle})},m=async y=>{if(!s.has(y.id)){if(y.placement==="none"){c(y),u(y),await p(y),s.add(y.id);return}c(y),u(y),await p(y),n({id:y.id,title:y.title,icon:y.icon,isOpen:()=>!!e.getById(y.id),onOpen:()=>f(y)}),C(v.DOCK_ITEM_APPENDED,{id:y.id}),s.add(y.id)}},h=y=>{s.has(y)&&(o(y),s.delete(y),d.delete(y))},w=async y=>{const E=new Set;for(const L of y)E.add(L.id),d.set(L.id,L);for(const L of Array.from(s))E.has(L)||h(L);for(const L of y)s.has(L.id)||await m(L)},x=(y,E={})=>{const L=d.get(y);return L?(ge.publish("desktop-mode/open-requested",{windowId:y,source:E.source??"api"}),f(L),!0):!1},D=(y,E={})=>{const L=d.get(y);return L?(ge.publish("desktop-mode/open-requested",{windowId:y,source:E.source??"api"}),g(L),!0):!1};return j(v.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",y=>{const E=y,L=E?.windowId,b=E?.width,A=E?.height;if(!L||typeof b!="number"||typeof A!="number")return;const I=e.getById(L);if(!I||I.state!=="normal")return;const _=I.config.baseId||I.id;ea(_,{width:b,height:A}),I.element&&ta(_,{x:I.element.offsetLeft,y:I.element.offsetTop})}),j(v.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E)return;const L=e.getById(E);if(!L||L.state!=="normal"||!L.element)return;const b=L.config.baseId||L.id;ea(b,{width:L.element.offsetWidth,height:L.element.offsetHeight}),ta(b,{x:L.element.offsetLeft,y:L.element.offsetTop})}),j(v.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E)return;const L=e.getById(E);if(!L)return;const b=L.config.baseId||L.id,A=d.get(b),I=A?{width:A.width,height:A.height}:{width:L.config.width,height:L.config.height};na(b,"maximized",I)}),j(v.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E)return;const L=e.getById(E);if(!L)return;const b=L.config.baseId||L.id;na(b,null)}),{sync:w,openById:x,openNewById:D}}function Qs(t){let e=null;if(typeof t=="string"){const n=document.getElementById(t);n instanceof HTMLTemplateElement&&(e=n)}else e=t;if(!e)throw new Error(`[desktop-mode] cloneTemplate: no <template> found for ${typeof t=="string"?`#${t}`:"<reference>"}`);return e.content.cloneNode(!0)}function ei(t,e){const n=e.className??"",o=e.title??"";if(typeof t=="string"&&t.startsWith("dashicons-")){const a=document.createElement("span");return a.className=`dashicons ${t} ${n}`.trim(),a.setAttribute("aria-hidden","true"),a}if(typeof t=="string"&&t.startsWith("data:image/svg+xml;base64,")){const a=t.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("${t}")`,d.style.backgroundRepeat="no-repeat",d.style.backgroundPosition="center",d.style.backgroundSize="contain",d.style.display="inline-block",d}}if(typeof t=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(t)){const a=t.indexOf(","),d=a>=0?t.slice(a+1):"";if(/^[A-Za-z0-9+/=]+$/.test(d))return il(t,n)}if(typeof t=="string"&&(t.startsWith("http://")||t.startsWith("https://")))return il(t,n);const s=document.createElement("span");s.className=`${n} desktop-mode-icon-letter`.trim(),s.setAttribute("aria-hidden","true");const i=Lw(o);s.textContent=i;const r=Ls(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 il(t,e){const n=document.createElement("img");return n.className=e,n.src=t,n.alt="",n.setAttribute("aria-hidden","true"),n.draggable=!1,n}function Lw(t){const e=(t??"").trim();if(e==="")return"?";const n=e.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 rl="desktop-mode-icon__badge",yn=new Map;function Tw(t){return Math.max(0,Math.floor(Number(t)||0))}function al(t,e){if(!t)return;const n=Mw(t);if(!n)return;const o=Tw(e),s=yn.get(t)??0;o!==s&&(o===0?yn.delete(t):yn.set(t,o),cl(n,o),ge.publish("desktop-mode/badge-changed",{itemId:t,count:o,rail:"icon"}),C(v.ICON_BADGE_CHANGED,{iconId:t,count:o,previousCount:s}))}function Nw(t){al(t,0)}function Dw(t){return yn.get(t)??0}const Ow={setBadge:al,clearBadge:Nw,getBadge:Dw};function Rw(t){return!t||t.length===0?"":t.map(e=>`${e.id}|${e.title}|${e.icon}|${e.window??""}|${e.url??""}|${e.position??0}|${e.pinned?1:0}`).join(";")}let dl="";function ll(t,e,n){const o=Rw(e);if(o===dl&&t.querySelector(":scope > .desktop-mode-icons"))return;dl=o;const s=t.querySelector(":scope > .desktop-mode-icons");if(s&&s.remove(),!e||e.length===0)return;const i=document.createElement("div");i.className="desktop-mode-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",N("Desktop icons"));const r=[...e].sort((d,l)=>{const c=d.pinned?0:1,u=l.pinned?0:1;return c-u}),a=new Map;for(const d of r){const l=$w(d,n),c=yn.get(d.id)??0;c>0&&cl(l,c),i.appendChild(l),a.set(d.id,l)}t.appendChild(i),C(v.DESKTOP_ICONS_RENDERED,{ids:(e??[]).map(d=>d.id),container:i,tiles:a})}function Mw(t){if(!t)return null;const e=document.querySelector(".desktop-mode-icons");return e?e.querySelector(`[data-icon-id="${Pw(t)}"]`):null}function cl(t,e){const n=t.querySelector(`:scope > .${rl}`);if(e<=0){n?.remove();return}const o=e>99?"99+":String(e),s=oe(Xt("%d notification","%d notifications",e),e);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",s);return}const i=document.createElement("span");i.className=rl,i.textContent=o,i.setAttribute("aria-label",s),t.appendChild(i)}function Pw(t){const e=window.CSS;return e?.escape?e.escape(t):t}function $w(t,e){const n=document.createElement("button");n.type="button",n.className=t.pinned?"desktop-mode-icon desktop-mode-icon--pinned":"desktop-mode-icon",n.dataset.iconId=t.id,t.pinned&&(n.dataset.pinned="1"),n.setAttribute("role","listitem"),n.setAttribute("aria-label",t.title);const o=ei(t.icon,{title:t.title,className:"desktop-mode-icon__image"});n.appendChild(o);const s=document.createElement("span");return s.className="desktop-mode-icon__label",s.textContent=t.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),C(v.DESKTOP_ICON_CLICKED,{id:t.id,target:t.window?"window":"url"}),Ww(t,e)}),n.addEventListener("contextmenu",i=>{t.pinned||(i.preventDefault(),i.stopPropagation(),Qa({x:i.clientX,y:i.clientY,id:t.id,title:t.title,surface:"desktop"}))}),n}function Ww(t,e){if(t.window)return e.openWindow(t.window),void 0;if(t.url){if(mo(t.url))return;try{const n=new URL(t.url,window.location.origin);e.manager.open({id:`desktop-icon-${t.id}`,url:n.toString(),title:t.title,icon:t.icon})}catch{}}}const ul="desktop-mode-side-dock";function Uw(t,e){return{id:`dock-core:${t.id}`,title:t.title,icon:t.icon,window:"",url:t.url,position:1e3+e}}function Bw(t,e,n,o){let s=e,i=n,r=o??[],a=null,d=null,l=null,c=null,u=null;const p=new Map,f=_=>_==="core"&&d?d:a,g=()=>{const _=document.getElementById(ul);if(_)return _;const k=document.createElement("nav");return k.id=ul,k.className="desktop-mode-dock",k.setAttribute("role","toolbar"),k.setAttribute("aria-label","Core admin navigation"),t.shellBody.insertBefore(k,t.shellBody.firstChild),k},m=()=>{u&&u.parentNode&&u.parentNode.removeChild(u),u=null},h=()=>t.getSettings?.()??{itemVisibility:{},dockOrder:[]},w=()=>{const _=new Set;for(const k of p.values())_.add(k.item.id);return um(i,r,h(),_)},x=()=>{const _=w(),k=[],O=[];for(const M of _)M.isCore?k.push(M):O.push(M);return{core:k,plugin:O}},D=()=>{const _=h();if(s!=="spatial"){t.renderIcons(pm(r,i,_.itemVisibility));return}const{core:k}=x(),O=k.map(Uw),M=[];let X=0;for(const Z of i){const te=_.itemVisibility[Z.id];(te==="desktop"||te==="both")&&M.push({id:`dock:${Z.id}`,title:Z.title,icon:Z.icon,window:"",url:Z.url||"",position:2e3+X++})}t.renderIcons([...O,...M])},y=()=>{if(a){try{a.destroy()}catch(_){C(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:_})}a=null,l=null}if(d){try{d.destroy()}catch(_){C(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:_})}d=null,c=null}},E=_=>{const k=Is();if(!k)return C(v.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return k.mount(_)}catch(O){if(C(v.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:k.id,error:O}),k===Os)return null;try{return Os.mount(_)}catch{return null}}},L=(_,k,O)=>({container:_,items:k,fullMenu:i.slice(),fullSystemTiles:Array.from(p.values()).map(M=>M.item),orientation:O,windowManager:t.windowManager,adminUrl:t.adminUrl,openItem:M=>{const X=le(M.url,t.adminUrl);t.windowManager.open({id:X,baseId:X,url:M.url,parentUrl:M.url,title:M.title,icon:M.icon.startsWith("dashicons-")?M.icon:"dashicons-admin-generic",submenu:M.submenu,multi:!!M.multi})},openSubmenuPick:(M,X)=>{t.windowManager.open({id:le(X.url,t.adminUrl),baseId:le(M.url,t.adminUrl),url:X.url,parentUrl:M.url,title:M.title,icon:M.icon.startsWith("dashicons-")?M.icon:"dashicons-admin-generic",submenu:M.submenu,multi:!!M.multi})},openSystemItem:M=>M.onOpen()}),b=()=>{y();const{core:_,plugin:k}=x();s==="classic"?(u=g(),d=E(L(u,_,"left")),c=bo(d),a=E(L(t.bottomDockEl,k,"bottom")),l=bo(a)):s==="unified"?(m(),a=E(L(t.bottomDockEl,w(),"bottom")),l=bo(a)):(m(),a=E(L(t.bottomDockEl,k,"bottom")),l=bo(a));for(const O of p.values())f(O.affinity)?.appendSystemItem(O.item)},A={getLayout:()=>s,getPrimary:()=>l,getSide:()=>c,setLayout:_=>{_!==s&&(s=_,t.shellRoot.setAttribute("data-desktop-mode-layout",_),b(),D(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:_,primary:l,side:c}})))},applyDockItems:_=>{i=_;const{core:k,plugin:O}=x();s==="classic"?(d?.replaceItems(k),a?.replaceItems(O)):s==="unified"?a?.replaceItems(w()):a?.replaceItems(O),D()},applyDesktopIcons:_=>{r=_??[],D()},appendSystemTile:(_,k="plugin")=>{p.set(_.id,{item:_,affinity:k}),f(k)?.appendSystemItem(_)},removeSystemTile:_=>{const k=p.get(_);k&&(p.delete(_),f(k.affinity)?.removeSystemItem(_))},listSystemTiles:()=>Array.from(p.values()).map(_=>({id:_.item.id,title:_.item.title,icon:_.item.icon,affinity:_.affinity})),getSystemTile:_=>p.get(_)?.item??null,getMenuItems:()=>i.slice(),refresh:()=>{const{core:_,plugin:k}=x();s==="classic"?(d?.replaceItems(_),a?.replaceItems(k)):s==="unified"?a?.replaceItems(w()):a?.replaceItems(k),D()},destroy:()=>{y(),m()}};t.shellRoot.setAttribute("data-desktop-mode-layout",s),b(),D();let I=Is()?.id??null;return Vf(()=>{const _=Is()?.id??null;_!==I&&(I=_,b(),D(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:s,primary:l,side:c}})))}),A}function Hw(t){return window.desktopModeCreateAiAssistant?Promise.resolve(window.desktopModeCreateAiAssistant):new Promise((e,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}e(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=t,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 Fw{constructor(e,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=e,this._scriptUrl=n}_ensure(){return this._loadPromise?this._loadPromise:(this._loadPromise=Hw(this._scriptUrl).then(e=>{const n=e(this._config);return this._pendingAsk&&n.attachAsk(this._pendingAsk),this._real=n,n}),this._loadPromise)}open(){this._intendOpen=!0,this._ensure().then(e=>e.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(e){this._pendingAsk=e,this._real&&this._real.attachAsk(e)}}const pl=t=>!t||typeof t!="object"?!1:t.name==="AbortError",zw=t=>{if(!t)return[];const e=Vm();if(t===!0||t==="aiCallable")return e;if(Array.isArray(t)){const n=new Set(t.map(o=>o.toLowerCase()));return e.filter(o=>n.has(o.slug))}return typeof t=="function"?e.filter(n=>{try{return t(n.slug)===!0}catch{return!1}}):[]},jw=t=>t?typeof t=="string"?{text:t,mode:"append"}:typeof t=="object"&&typeof t.text=="string"&&t.text!==""?{text:t.text,mode:t.mode==="replace"?"replace":"append"}:null:null;function Gw(t,e){const n=t??"";return n!==""?n:typeof e=="string"&&e!==""?e:e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?e.message:""}function qw(t){return t===void 0?{value:null}:typeof t=="object"&&t!==null?t:{value:t}}function Vw(t){const e=async(s,i)=>{const r=t.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(l){throw pl(l)?l:new Error(`[desktop-mode] wp.desktop.ai.ask: network error — ${String(l?.message??l)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",d=Km(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 l=i.commandContext??t.fallbackContext();let c;try{c=await Promise.resolve(d.run(a,l))}catch(u){c={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:c}},o=async(s,i,r,a,d,l)=>{const c={query:s,follow_up:{tool:{slug:i,args:r},result:qw(a)}};d&&(c.system_prompt_text=d.text,c.system_prompt_mode=d.mode);let u;try{u=await e(c,l)}catch(g){if(pl(g))throw g;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=zw(r.tools),l=jw(r.systemPrompt),c={query:a};r.resumeTool&&(c.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(c.start_offset=r.startOffset),d.length>0&&(c.command_tools=d),l&&(c.system_prompt_text=l.text,c.system_prompt_mode=l.mode);const u=await e(c,r.signal);if(!u.ok){const x=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[desktop-mode] wp.desktop.ai.ask: HTTP ${u.status} — ${x.message??u.statusText}`)}const p=await u.json();if(p.answer_type!=="tool_call"||!p.tool)return{answer_type:p.answer_type,message:p.message??"",entity:p.entity??null,admin_links:p.admin_links??null,request_id:p.request_id,continue:p.continue??null};const f=await n(p,r);if(!f.ok)return f.response;const{slug:g,args:m,result:h}=f;let w=Gw(p.message,h);if(r.followUp===!0){const x=await o(a,g,m,h,l,r.signal);x!==null&&(w=x)}return{answer_type:"tool_call",message:w,entity:null,admin_links:null,toolCall:{slug:g,args:m,result:h},request_id:p.request_id}}}const ti="desktop-mode-broadcast",fl="desktop-mode-broadcast",ml=window.location.origin;let ni=null;function Kw(t){ni=t}function hl(t,e){const n=String(q("desktop-mode.broadcast.topic",t,{payload:e})??t),o=q("desktop-mode.broadcast.payload",e,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(ti,{detail:s})),C(v.BROADCAST,s),ge.publish(n,o),!ni)return;const i={type:fl,topic:n,payload:o};for(const r of ni._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,ml)}catch{}}}function Re(t,e){const n=o=>{const s=o.detail;if(s&&!(t!=="*"&&s.topic!==t))try{e(s.payload,{topic:s.topic})}catch(i){C(v.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(ti,n),()=>document.removeEventListener(ti,n)}function Yw(){window.addEventListener("message",t=>{if(t.origin!==ml)return;const e=t.data;!e||e.type!==fl||e._fromParent||typeof e.topic=="string"&&hl(e.topic,e.payload)})}const wl="[desktop-mode-bin badge]";function Fe(...t){try{window.localStorage?.getItem("desktopModeBinDebug")&&console.info(wl,...t)}catch{}}function Lo(...t){console.warn(wl,...t)}const ut="desktop-mode-recycle-bin",Xw="desktop_mode_recycle_bin_seen_ts";function gl(){return window.wp?.desktop}const ie=ce("desktop-mode/recycle-bin/badge",()=>({current:0,seenTs:0,started:!1,countUrl:""}));function bn(t){const e=Math.max(0,Math.floor(t)),n=ie.state.current;ie.state.current=e,Fe("setRecycleBinBadge",{prev:n,next:e}),To(e)}function yl(t){bn(ie.state.current+t)}function Zw(){return ie.state.current}function To(t){const e=gl(),n=Jw(),o=n?0:t;Fe("paintBadge",{count:t,visible:o,active:n}),e?.dock?.setBadge?.(ut,o),e?.taskbar?.setBadge?.(ut,o),e?.icons?.setBadge?.(ut,o)}function Jw(){return!!gl()?.windowManager?.isActive?.(ut)}function Qw(t,e=""){const n=Number(t)||0,o=window.desktopModeConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl,r=o?.desktopModeBinDebug;Fe("startRecycleBinBadge entry",{initial:n,countUrl:e,alreadyStarted:ie.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)||Lo("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}),ie.state.started){bn(n);return}ie.state.started=!0,ie.state.countUrl=e,ie.state.seenTs=Date.now(),bn(n),tg(),ng(),og(),sg(),ig(),eg()}function eg(){const t="desktop-mode/recycle-bin/badge-lifecycle",e=n=>{n?.windowId===ut&&To(ie.state.current)};j(v.WINDOW_OPENED,t,e),j(v.WINDOW_FOCUSED,t,e),j(v.WINDOW_BLURRED,t,e),j(v.WINDOW_MINIMIZED,t,e),j(v.WINDOW_RESTORED,t,e),j(v.WINDOW_CLOSED,t,e),j(v.WINDOW_REOPENED,t,e)}function tg(){j(v.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/badge",t=>{t?.id===ut&&To(ie.state.current)})}function ng(){j(v.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/badge",t=>{t?.ids?.includes(ut)&&To(ie.state.current)})}function og(){const t=e=>{const n=e;if(!n)return;const o=Array.isArray(n.ids)?n.ids.length:0;switch(n.action){case"trashed":yl(+o);break;case"untrashed":case"deleted":yl(-o);break}};Re("desktop-mode.post.changed",t),Re("desktop-mode.page.changed",t),Re("desktop-mode.attachment.changed",t),Re("desktop-mode.comment.changed",t),Re("desktop-mode.placement.changed",t),Re("desktop-mode.shortcut.changed",t),Re("desktop-mode.folder.changed",t)}function sg(){const t=window.location.origin;window.addEventListener("message",e=>{if(e.origin!==t)return;const n=e.data;if(!n||n.type!=="desktop-mode-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=ie.state.seenTs){Fe("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:ie.state.seenTs});return}Fe("postMessage triggers refetch",{ts:o,prevSeenTs:ie.state.seenTs}),ie.state.seenTs=o,rg()})}function ig(){const t=window.jQuery;if(!t){Lo("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}Fe("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),t(document).on("heartbeat-send",(...e)=>{const n=e[1];n&&(n[Xw]=ie.state.seenTs)}),t(document).on("heartbeat-tick",(...e)=>{const o=e[1]?.desktop_mode_recycle_bin;Fe("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>ie.state.seenTs&&(ie.state.seenTs=o.ts),typeof o.count=="number"&&bn(o.count))})}async function rg(){if(!ie.state.countUrl){Fe("refetchCount: no countUrl, skip");return}Fe("refetchCount: hitting",ie.state.countUrl);try{const t=await fetch(ie.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!t.ok){Lo("refetchCount: non-OK",t.status,t.statusText);return}const e=await t.json();Fe("refetchCount: response",e),typeof e.count=="number"&&bn(e.count)}catch(t){Lo("refetchCount: fetch failed",t)}}const ag="desktop-mode-os-settings",dg="desktop-mode-recycle-bin";function lg(t){const e=pg();e&&e.addFilter("desktop-mode.dock.peek-card-content","desktop-mode/built-in-peek-renderers",(n,o)=>{const s=o,i=s.window.id;return i===ag?cg():i===dg?ug(s,t.getRecycleBinCount):n})}function cg(t){const e=document.createElement("span");e.className="desktop-mode-dock-peek__card-body desktop-mode-dock-peek__card-body--os-settings",e.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="desktop-mode-dock-peek__os-hero dashicons dashicons-admin-generic",e.appendChild(n);const o=document.createElement("span");o.className="desktop-mode-dock-peek__os-subtitle",o.textContent=N("System Preferences"),e.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 e.appendChild(s),e}function ug(t,e){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(e()||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 l=document.createElement("span");l.className="desktop-mode-dock-peek__bin-slip",i.appendChild(l)}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=N("Recycle Bin — empty"):o===1?a.textContent=N("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function pg(){return window.wp?.hooks??null}const vn="desktop-mode-bug-report",fg="WordPress",mg="desktop-mode",bl=6e3;function hg(t){t.classList.add("desktop-mode-bug-report"),t.replaceChildren();const e=document.createElement("form");e.className="desktop-mode-bug-report__form",e.setAttribute("novalidate","");const n=document.createElement("p");n.className="desktop-mode-bug-report__intro",n.textContent=N("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."),e.appendChild(n),e.appendChild(wg()),e.appendChild(gg("title",N("Title"),{placeholder:N("A short summary"),required:!0})),e.appendChild(vl("description",N("What happened? What did you expect?"),{placeholder:N("Describe the issue or the feature you have in mind."),rows:5,required:!0})),e.appendChild(vl("steps",N("Steps to reproduce (bug only)"),{placeholder:N("One step per line"),rows:4}));const o=yg();e.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=N("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="desktop-mode-bug-report__hint",r.textContent=N("You will review and submit on GitHub."),s.appendChild(r),e.appendChild(s),e.addEventListener("submit",a=>{a.preventDefault();const d=vg(e);if(!d.title.trim()||!d.description.trim()){bg(e,N("Title and description are both required."));return}const l=kg(d);window.open(l,"_blank","noopener")}),t.appendChild(e)}function wg(){const t=document.createElement("div");t.className="desktop-mode-bug-report__field desktop-mode-bug-report__field--type";const e=document.createElement("span");e.className="desktop-mode-bug-report__label",e.textContent=N("Type"),t.appendChild(e);const n=document.createElement("div");n.className="desktop-mode-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:N("Bug"),checked:!0},{value:"feature",label:N("Feature request")},{value:"question",label:N("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 t.appendChild(n),t}function gg(t,e,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=e,o.appendChild(s);const i=document.createElement("input");return i.type="text",i.name=t,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 vl(t,e,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=e,o.appendChild(s);const i=document.createElement("textarea");return i.name=t,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 yg(){const t=document.createElement("details");t.className="desktop-mode-bug-report__metadata";const e=document.createElement("summary");e.textContent=N("Environment included with the report"),t.appendChild(e);const n=document.createElement("pre");return n.className="desktop-mode-bug-report__metadata-body",n.textContent=_l(kl()),t.appendChild(n),t}function bg(t,e){let n=t.querySelector(".desktop-mode-bug-report__error");n||(n=document.createElement("div"),n.className="desktop-mode-bug-report__error",n.setAttribute("role","alert"),t.prepend(n)),n.textContent=e}function vg(t){const e=new FormData(t);return{type:e.get("type")??"bug",title:e.get("title")??"",description:e.get("description")??"",steps:e.get("steps")??""}}function kg(t){const e=_g(t.type),n=Eg(t),o=new URLSearchParams;return o.set("title",t.title.trim()),o.set("body",n),e.length&&o.set("labels",e.join(",")),`https://github.com/${fg}/${mg}/issues/new?${o.toString()}`}function _g(t){switch(t){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function Eg(t){const e=[];e.push(t.description.trim()),t.type==="bug"&&t.steps.trim()&&(e.push(""),e.push("## Steps to reproduce"),e.push(""),e.push(t.steps.trim())),e.push(""),e.push("<details><summary>Environment</summary>"),e.push(""),e.push("```"),e.push(_l(kl())),e.push("```"),e.push(""),e.push("</details>");let n=e.join(` |
| 54 |
`);return n.length>bl&&(n=n.slice(0,bl)+` |
| 55 |
|
| 56 |
…(truncated to fit GitHub URL length limit)`),n}function kl(){const t=window.wp?.desktop?.config;return{pluginVersion:t?.pluginVersion??"unknown",wordpressVersion:t?.wordpressVersion??"unknown",userAgent:navigator.userAgent,viewport:`${window.innerWidth}x${window.innerHeight}`,platform:navigator.platform||"unknown",currentUrl:window.location.href}}function _l(t){return[`Plugin version: ${t.pluginVersion}`,`WordPress version: ${t.wordpressVersion}`,`User agent: ${t.userAgent}`,`Viewport: ${t.viewport}`,`Platform: ${t.platform}`,`Current URL: ${t.currentUrl}`].join(` |
| 57 |
`)}let No=null,Do={installHintDismissed:!1,notificationsEnabled:!1};const oi=new Set;function El(t){if(!t){No=null;return}No=t,Do={...t.state},Cl()}function kn(){return{...Do}}function si(t){if(Do={...Do,...t},Cl(),!No)return kn();const e=JSON.stringify(t),n=Sg();return fetch(No.stateUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",...n?{"X-WP-Nonce":n}:{}},body:e}).catch(o=>{typeof console<"u"&&console.warn("[desktop-mode] pwa-state write failed:",o)}),kn()}function Sl(t){return oi.add(t),()=>{oi.delete(t)}}function Cl(){const t=kn();for(const e of Array.from(oi))try{e(t)}catch(n){typeof console<"u"&&console.error("[desktop-mode] pwa-state listener threw:",n)}}function Sg(){return window.desktopModeConfig?.restNonce??""}const Cg=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:kn,initPwaState:El,subscribePwaState:Sl,updatePwaState:si},Symbol.toStringTag,{value:"Module"}));let Oo=null,xl=!1,Al=!1,Il=!1,pt="pending";function xg(){if(Al)return;Al=!0;const t=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{t&&(Il||Ig()||(Lg(),Il=!0,setTimeout(()=>window.location.reload(),0)))})}const Ll="wpd-sw-reload-ts",Ag=3e4;function Ig(){try{const t=sessionStorage.getItem(Ll),e=t?Number.parseInt(t,10):0;return!Number.isFinite(e)||e<=0?!1:Date.now()-e<Ag}catch{return!1}}function Lg(){try{sessionStorage.setItem(Ll,String(Date.now()))}catch{}}async function Tg(t,e={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!t?.swUrl||!window.isSecureContext)return pt="unsupported",null;if(Oo||xl)return Oo;if(!e.forceReplace){const o=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(s=>{const i=s.active?.scriptURL??s.installing?.scriptURL??"";return i!==""&&i!==t.swUrl});if(o)return pt="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 Oo=await navigator.serviceWorker.register(t.swUrl,{scope:"/",updateViaCache:"none"}),pt="registered",xg(),Oo}catch(n){return xl=!0,pt="failed",typeof console<"u"&&console.warn("[desktop-mode] SW registration failed:",n),null}}function Ng(){return pt}const Dg="desktop-mode-pwa-install";function Tl(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Nl(){if(Tl())return!0;const t=window.navigator;if(typeof t.getInstalledRelatedApps!="function")return!1;try{const e=await t.getInstalledRelatedApps();return Array.isArray(e)&&e.length>0}catch{return!1}}let ot=null;function Og(t,e){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(),ot=s}function o(){ot=null,e({message:oe(N("Installed %s as an app."),t)})}}function Rg(t,e){return{id:Dg,title:oe(N("Install %s as an app"),t),icon:"dashicons-download",onOpen:()=>{Mg(t,e)}}}async function Mg(t,e){if(ot){const n=ot;ot=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&e({message:N("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[desktop-mode] install prompt failed:",o)}return}if(await Nl()){e({message:oe(N("%s is already installed. Open it from your apps menu or home screen."),t)});return}if(Ng()==="foreign-sw"){e({message:N("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}e({message:N("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 Pg(){if(!ot)return"unavailable";const t=ot;ot=null;try{return await t.prompt(),(await t.userChoice).outcome}catch{return"unavailable"}}function $g(){Promise.resolve().then(()=>Cg).then(t=>{t.updatePwaState({installHintDismissed:!1})})}function Wg(t){const e=ge.filter("desktop-mode/notification-requested",{...t});if(!e||e.cancel===!0||!e.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=J({message:e.body?e.title+" — "+e.body:e.title}),ge.publish("desktop-mode/notification-shown",{...e,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=Dl(e),i):a==="denied"?(r(),i):(Notification.requestPermission().then(d=>{if(!n){if(d==="granted"){si({notificationsEnabled:!0}),o=Dl(e);return}r()}}),i)}function Dl(t){let e=null;try{e=new Notification(t.title,{body:t.body,icon:t.icon,tag:t.tag,requireInteraction:t.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[desktop-mode] Notification ctor threw:",n),()=>{}}if(t.onClick){const n=t.onClick;e.onclick=()=>{try{n(e)}catch(o){typeof console<"u"&&console.error("[desktop-mode] notification onClick threw:",o)}}}return ge.publish("desktop-mode/notification-shown",{...t,fallback:null}),()=>{e&&e.close()}}async function Ug(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const t=await Notification.requestPermission();return t==="granted"&&si({notificationsEnabled:!0}),t}function Bg(){return typeof Notification>"u"?"unsupported":Notification.permission}function Hg(t,e){t.pwa&&(El(t.pwa),Og(t.pwa.appName||"WordPress",e),Tg(t.pwa,{forceReplace:!!t.pwa.forceReplaceSw}))}const Ro={START:"desktop-mode-cross-frame-drag-start",END:"desktop-mode-cross-frame-drag-end"};function Fg(t){return!!t&&typeof t=="object"&&t.type==="desktop-mode-drag-start"&&!!t.payload&&typeof t.payload=="object"}function zg(t){return!!t&&typeof t=="object"&&t.type==="desktop-mode-drag-end"}function jg(t){return!!t&&typeof t=="object"&&t.type==="desktop-mode-drag-payload-request"}function Gg(t){const e=t;return e.kind!==void 0&&e.kind!==null?t:typeof e.id=="number"&&typeof e.url=="string"&&typeof e.mime=="string"?{kind:"attachment",id:e.id,url:e.url,title:typeof e.title=="string"?e.title:"",alt:typeof e.alt=="string"?e.alt:"",mime:e.mime,thumbnailUrl:typeof e.thumbnailUrl=="string"?e.thumbnailUrl:void 0,sizes:e.sizes&&typeof e.sizes=="object"?e.sizes:void 0}:t}class qg{constructor(){this._payload=null,this._onMessage=e=>{if(e.origin!==this._origin)return;const n=e.data;if(Fg(n)){this._startDrag(n.payload);return}if(zg(n)){this._endDrag();return}if(jg(n)&&this._payload&&e.source)try{e.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(e){this._payload!==e&&this._startDrag(e)}end(){this._endDrag()}_startDrag(e){const n=Gg(e);this._payload=n,document.dispatchEvent(new CustomEvent(Ro.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const e=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(Ro.END,{detail:{payload:e}}))}}class Vg{constructor(){this._targets=new Map,this._byElement=new Map}register(e){const n=this._targets.get(e.id);return n&&this._byElement.delete(n.element),this._targets.set(e.id,e),this._byElement.set(e.element,e),()=>{this._targets.get(e.id)===e&&(this._targets.delete(e.id),this._byElement.delete(e.element))}}list(){return Array.from(this._targets.values())}clear(){this._targets.clear(),this._byElement.clear()}hitTest(e){let n=e;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(e,n){const o=document.elementFromPoint(e,n);return{target:this.hitTest(o),element:o,accepted:!1}}}const Kg="desktop-mode-drag-ghost",Ol="desktop-mode-drag-ghost--accept",Rl="desktop-mode-drag-ghost--reject",Yg="desktop-mode-drag-hint",Ml="desktop-mode-drag-hint--accept",Pl="desktop-mode-drag-hint--reject",$l="desktop-mode-drag-hint--neutral",Xg=16,Zg=18;function Jg(t,e,n){const o=sy(t),s=t.ghost?.offsetX??iy(t.source),i=t.ghost?.offsetY??ry(t.source);o.classList.add(Kg),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=ey(t),a=r?Qg():null;a&&document.body.appendChild(a);const d={get element(){return o},moveTo(l,c){o.style.transform=`translate3d(${l-s}px, ${c-i}px, 0)`,a&&(a.style.transform=`translate3d(${l+Xg}px, ${c+Zg}px, 0)`)},setMode(l){o.classList.remove(Ol,Rl),l==="accept"?o.classList.add(Ol):l==="reject"&&o.classList.add(Rl),a&&r&&(a.classList.remove(Ml,Pl,$l),l==="accept"?(a.classList.add(Ml),a.textContent=r.accept):l==="reject"?(a.classList.add(Pl),a.textContent=r.reject):(a.classList.add($l),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(l){const c=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return l()}finally{o.style.visibility=c,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return d.moveTo(e,n),d.setMode("neutral"),d}function Qg(){const t=document.createElement("div");return t.className=Yg,t.setAttribute("aria-hidden","true"),t.setAttribute("role","presentation"),t.style.position="fixed",t.style.left="0",t.style.top="0",t.style.margin="0",t.style.pointerEvents="none",t.style.zIndex="2147483647",t.style.willChange="transform",t}function ey(t){const e=t.ghost?.hint;return e?.hidden?null:{accept:e?.accept??ty(t),reject:e?.reject??ny(),neutral:e?.neutral??oy(t)}}function ty(t){return t.type==="shortcut"?N("Drop here to create shortcut","desktop-mode"):t.type==="desktop-file"?N("Drop here to move","desktop-mode"):N("Drop here","desktop-mode")}function ny(t){return N("Can’t drop here","desktop-mode")}function oy(t){return t.type==="shortcut"?N("Drop on the desktop or a folder","desktop-mode"):t.type==="desktop-file"?N("Drop in a folder","desktop-mode"):""}function sy(t){if(t.ghost?.element)return t.ghost.element;const e=t.source.cloneNode(!0);e.removeAttribute("id");const n=t.source.getBoundingClientRect();return e.style.width=`${n.width}px`,e.style.height=`${n.height}px`,e}function iy(t){return t.offsetWidth/2}function ry(t){return t.offsetHeight/2}let Wl=!1;function ay(t){Wl||(Wl=!0,document.addEventListener("keydown",e=>{e.key==="Escape"&&t("escape")}),window.addEventListener("blur",()=>{t("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&t("visibility")}))}const Ul=4,Ie={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"},Mo="desktop-mode-file-tile--dragging",Bl="desktop-mode-file-tile--drop-target",Hl="data-desktop-mode-trash-drop-active",Fl="data-files-drop-active",zl="data-desktop-mode-dragging",jl="data-desktop-mode-drag-type",ii="data-desktop-mode-drag-mode";class dy{constructor(){this._registry=new Vg,this._active=null,this._docListenersAttached=!1,this._lastLiftedEndAt=0,this._onPointerMove=e=>{const n=this._active;if(!n||n._pointerId!==e.pointerId)return;const o=e.clientX-n._origin.clientX,s=e.clientY-n._origin.clientY;if(!n._lifted){if(Math.abs(o)<Ul&&Math.abs(s)<Ul)return;this._lift(n,e)}n._ghost&&(n._ghost.moveTo(e.clientX,e.clientY),this._updateHover(n,e.clientX,e.clientY),Ge(Ie.MOVE,{payload:n.payload,clientX:e.clientX,clientY:e.clientY}))},this._onPointerUp=e=>{const n=this._active;if(!n||n._pointerId!==e.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,e.clientX,e.clientY);if(o&&o.accepted&&o.target){this._commit(n,o.target,e.clientX,e.clientY);return}this._cancel(n,o&&o.target?"rejected":"no-target")},this._onPointerCancel=e=>{const n=this._active;!n||n._pointerId!==e.pointerId||this._cancel(n,"pointercancel")}}start(e){if(this._active||e.origin.button!==0)return null;const n={payload:e.payload,isFinished:()=>n._finished,cancel:o=>this._cancel(n,o??"caller"),_origin:e.origin,_pointerId:e.origin.pointerId,_lifted:!1,_finished:!1,_callbacks:{onClickOnly:e.onClickOnly,onCancel:e.onCancel,onCommit:e.onCommit},_ghost:null,_currentTarget:null,_currentAccepted:!1};return this._active=n,this._ensureDocListeners(),ay(o=>{this._active&&this._cancel(this._active,o)}),n}registerDropTarget(e){return this._registry.register(e)}isDragging(){return this._active!==null&&this._active._lifted}recentlyEndedDrag(e=500){return this._lastLiftedEndAt===0?!1:Date.now()-this._lastLiftedEndAt<e}getActive(){return this._active}debug(){return{findOrphans:()=>Gl(),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(e,n){e._lifted=!0,e.payload.source.classList.add(Mo),e._ghost=Jg(e.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(zl,""),document.body.setAttribute(jl,String(e.payload.type)),document.body.setAttribute(ii,"neutral")),Ge(Ie.START,{payload:e.payload})}_hitTestNow(e,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(e.payload)}catch(d){console.error("[desktop-mode] drop target accept() threw:",r.id,d)}return{target:r,accepted:a}};return e._ghost?e._ghost.withHidden(s):s()}_updateHover(e,n,o){const s=this._hitTestNow(e,n,o),i=e._currentTarget;if(s.target===i&&s.accepted===e._currentAccepted)return;i&&ri(i,e),e._currentTarget=s.target,e._currentAccepted=s.accepted;let r;s.target?s.accepted?(ly(s.target,e),e._ghost?.setMode("accept"),r="accept"):(e._ghost?.setMode("reject"),Ge(Ie.REJECTED,{payload:e.payload,targetId:s.target.id}),r="reject"):(e._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(ii,r)}_commit(e,n,o,s){e._finished=!0,this._lastLiftedEndAt=Date.now(),ri(n,e),this._cleanupDom(e);const i=this._active;this._active=null;try{n.onDrop(e,{clientX:o,clientY:s})}catch(r){console.error("[desktop-mode] drop target onDrop threw:",n.id,r)}try{e._callbacks.onCommit?.(n)}catch(r){console.error("[desktop-mode] drag onCommit threw:",r)}Ge(Ie.COMMIT,{payload:e.payload,targetId:n.id}),Ge(Ie.END,{payload:e.payload,reason:"commit"}),this._active===i&&(this._active=null)}_cancel(e,n){if(!e._finished){e._finished=!0,e._lifted&&(this._lastLiftedEndAt=Date.now()),e._currentTarget&&ri(e._currentTarget,e),this._cleanupDom(e),this._active=null;try{e._callbacks.onCancel?.(n)}catch(o){console.error("[desktop-mode] drag onCancel threw:",o)}Ge(Ie.CANCEL,{payload:e.payload,reason:n}),Ge(Ie.END,{payload:e.payload,reason:n})}}_cleanupDom(e){try{e.payload.source.classList.remove(Mo)}catch{}e._ghost?.dispose(),e._ghost=null,e._currentTarget=null,e._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(zl),document.body.removeAttribute(jl),document.body.removeAttribute(ii)),cy()}}function Ge(t,e){typeof document>"u"||document.dispatchEvent(new CustomEvent(t,{detail:e}))}function ly(t,e){try{t.onEnter?.(e)}catch(n){console.error("[desktop-mode] drop target onEnter threw:",t.id,n)}Ge(Ie.ENTER,{payload:e.payload,targetId:t.id})}function ri(t,e){try{t.onLeave?.(e)}catch(n){console.error("[desktop-mode] drop target onLeave threw:",t.id,n)}Ge(Ie.LEAVE,{payload:e.payload,targetId:t.id})}function Gl(){if(typeof document>"u")return[];const t=[];for(const e of[`.${Mo}`,`.${Bl}`,`[${Hl}]`,`[${Fl}]`])document.querySelectorAll(e).forEach(n=>t.push(n));return t}function cy(){for(const t of Gl())t.classList.remove(Mo,Bl),t.removeAttribute(Hl),t.removeAttribute(Fl)}const uy="desktop-mode-iframe-drop-",Po="iframe.desktop-mode-window__iframe",ai="data-desktop-mode-iframe-drop-active";let di=!1,ql=null;const De=new Map,ft=new Map;let qe=null,mt=null;function py(){document.querySelectorAll(Po).forEach(e=>{De.has(e)||(De.set(e,e.style.pointerEvents),e.style.pointerEvents="none")})}function fy(){De.forEach((t,e)=>{e.style.pointerEvents=t}),De.clear()}function Vl(t,e){const n=document.elementFromPoint(t,e);if(!n)return null;const o=n.closest(".desktop-mode-window");if(!(o instanceof HTMLElement))return null;const s=o.querySelector(Po);return s instanceof HTMLIFrameElement?s:null}const Kl=t=>{if(!qe)return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy");const e=Vl(t.clientX,t.clientY);e!==mt&&(mt&&ht(mt,{type:"desktop-mode-drag-leave"}),mt=e,e&&ht(e,{type:"desktop-mode-drag-over",payload:qe}))},Yl=t=>{if(!qe)return;t.preventDefault(),t.stopPropagation(),typeof t.stopImmediatePropagation=="function"&&t.stopImmediatePropagation();const e=Vl(t.clientX,t.clientY),n=qe;if(li(),!e)return;const o=e.getBoundingClientRect();ht(e,{type:"desktop-mode-drop",payload:n,position:{x:t.clientX-o.left,y:t.clientY-o.top}})},Xl=()=>{li()};function my(t){if(qe){qe=t;return}qe=t,py(),document.addEventListener("dragover",Kl,!0),document.addEventListener("drop",Yl,!0),document.addEventListener("dragend",Xl,!0)}function li(){qe&&(qe=null,mt&&(ht(mt,{type:"desktop-mode-drag-leave"}),mt=null),document.removeEventListener("dragover",Kl,!0),document.removeEventListener("drop",Yl,!0),document.removeEventListener("dragend",Xl,!0),fy())}function $o(t){if(!t||typeof t!="object")return;const e=t;return e.type!=="shortcut"&&e.type!=="desktop-file"?void 0:e.data?.bridgePayload}function ht(t,e){const n=t.contentWindow;if(n)try{n.postMessage(e,window.location.origin)}catch{}}function hy(t,e,n,o){return t.registerDropTarget({id:`${uy}${o}`,element:n,accept:s=>!!$o(s),onEnter:s=>{const i=$o(s.payload);i&&(n.setAttribute(ai,""),ht(e,{type:"desktop-mode-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(ai),ht(e,{type:"desktop-mode-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(ai);const r=$o(s.payload);if(!r)return;const a=e.getBoundingClientRect();ht(e,{type:"desktop-mode-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function Zl(t){let e=t.parentElement;for(;e;){if(e.id.startsWith("wp-window-"))return e.id.slice(10);e=e.parentElement}return`unknown-${Math.random().toString(36).slice(2,10)}`}function wy(t){const e=ql;if(!e)return;const n=document.querySelectorAll(Po),o=!!$o(t);console.info("[desktop-mode] drag-start: suppressing %d iframe(s); bridgeable=%s",n.length,o,t),n.forEach(s=>{if(De.has(s)||(De.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||ft.has(s))return;const i=s.parentElement;if(!i)return;const r=Zl(s),a=hy(e,s,i,r);ft.set(s,a)})}function gy(){De.forEach((t,e)=>{e.style.pointerEvents=t}),De.clear(),ft.forEach(t=>{try{t()}catch{}}),ft.clear()}function yy(t){di||(di=!0,ql=t,document.addEventListener(Ie.START,e=>{const n=e.detail;wy(n?.payload)}),document.addEventListener(Ie.END,()=>{gy()}),document.addEventListener(Ro.START,e=>{const n=e.detail;n?.payload&&my(n.payload)}),document.addEventListener(Ro.END,()=>{li()}),j(v.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[e]of Array.from(De))e.isConnected||De.delete(e);for(const[e,n]of Array.from(ft))if(!e.isConnected){try{n()}catch{}ft.delete(e)}}),window.__desktopModeIframeDropDebug=()=>({installed:di,iframesInDom:document.querySelectorAll(Po).length,suppressedCount:De.size,registeredCount:ft.size,suppressedIframeIds:Array.from(De.keys()).map(Zl)}))}function Jl(){const t=window.wp?.desktop;if(!t)return[];const e=t.windowManager,n=t.config;if(!e||!n)return[];const o=[],s=(r,a)=>({id:r.id,label:r.title,description:a,icon:r.icon,open:()=>e.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=q("desktop-mode.open-command.items",o);return Array.isArray(i)?i:o}const by={slug:"open",label:"Open",description:"Open an admin page or registered window.",hint:"[window]",icon:"dashicons-external",suggest(t){const e=t.trim().toLowerCase(),n=Jl();return(e===""?n:n.filter(s=>s.label.toLowerCase().includes(e)||s.id.toLowerCase().includes(e))).slice(0,12).map(s=>({value:s.label,label:s.label,description:s.description,icon:s.icon??"dashicons-external"}))},run(t,e){const n=t.trim();if(!n)return"Type the name of a window to open, for example `/open Posts`.";const o=Jl(),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(),e.close()}};function vy(){So(by)}const ye=[],ky=new Set;function Ql(t){if(!t||typeof t.id!="string"||t.id==="")return()=>{};if(typeof t.open!="function"||typeof t.close!="function"||typeof t.isOpen!="function")return()=>{};const e=ye.findIndex(n=>n.id===t.id);return e>=0?ye[e]=t:ye.push(t),ci(),()=>{const n=ye.findIndex(o=>o.id===t.id);n>=0&&(ye.splice(n,1),ci())}}function _y(t){const e=ye.findIndex(n=>n.id===t);e>=0&&(ye.splice(e,1),ci())}function Ey(){return ye.slice()}function ci(){for(const t of Array.from(ky))try{t()}catch(e){typeof console<"u"&&console.error("[desktop-mode] palette-registry listener threw:",e)}}function ec(){if(ye.length===0)return;const t=ye.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(t===-1){try{ye[0].open()}catch{}return}try{ye[t].close()}catch{}const e=t+1;if(e<ye.length)try{ye[e].open()}catch{}}function tc(t){const e=ye.find(n=>n.id===t);if(e){for(const n of ye)if(n.id!==t)try{n.isOpen()&&n.close()}catch{}try{e.open()}catch{}}}let nc=!1;function Sy(){if(nc)return;nc=!0,document.addEventListener("keydown",e=>{!(e.metaKey||e.ctrlKey)||e.key!=="k"||e.shiftKey||e.altKey||(e.preventDefault(),e.stopImmediatePropagation(),ec())},!0);const t=window.location.origin;window.addEventListener("message",e=>{if(e.origin!==t)return;const n=e.data;n&&n.type==="desktop-mode-palette-cycle"&&ec()})}const Wo=new Map,ui=new Map;let oc=!1;const Ve={contribute(t,e){return Wo.set(t,e),()=>{Wo.get(t)===e&&Wo.delete(t)}},subscribe(t,e){let n=ui.get(t);return n||(n=new Set,ui.set(t,n)),n.add(e),()=>{n.delete(e)}}};function Cy(){if(oc)return;oc=!0;const t=window.jQuery;if(!t){console.warn("[desktop-mode/heartbeat] jQuery missing — Heartbeat bus disabled.");return}t(document).on("heartbeat-send",(...e)=>{const n=e[1];if(n)for(const[o,s]of Wo)try{n[o]=s()}catch(i){console.error(`[desktop-mode/heartbeat] supplier for "${o}" threw:`,i)}}),t(document).on("heartbeat-tick",(...e)=>{const n=e[1];if(n)for(const[o,s]of ui){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 Me=ce("desktop-mode/presence",()=>({byUser:new Map,serverTimeMs:0})),xy=5*60*1e3;let sc=Date.now(),ic=!1;function Uo(){sc=Date.now()}function Ay(t){if(!t||!t.snapshot)return;const e=Me.state.byUser,n=new Map(e),o=[];for(const[s,i]of Object.entries(t.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},l=e.get(r);n.set(r,d),(!l||l.status!==d.status)&&o.push({userId:r,oldStatus:l?l.status:null,newStatus:d.status,entry:d})}Me.state.byUser=n,typeof t.serverTimeMs=="number"&&(Me.state.serverTimeMs=t.serverTimeMs),Me.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})),ge.publish("desktop-mode/presence-changed",i)}ge.publish("desktop-mode/presence-snapshot-applied",{applied:Object.keys(t.snapshot).length,transitions:o.length})}function Iy(){ic||(ic=!0,document.addEventListener("pointerdown",Uo,{capture:!0,passive:!0}),document.addEventListener("keydown",Uo,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||Uo()}),Ve.contribute("desktop_mode_presence_active",()=>!0),Ve.contribute("desktop_mode_user_active",()=>Date.now()-sc<xy),Ve.subscribe("desktop_mode_presence",t=>{Ay(t)}))}function Ly(t){const e=Me.state.byUser.get(t);return e?e.status:"offline"}function Ty(){return new Map(Me.state.byUser)}function Ny(t){return Me.state.byUser.get(t)??null}function Dy(t){return Me.subscribe(e=>t(e))}function Oy(){Uo()}function Ry(t){if(!Array.isArray(t)||t.length===0)return;const e=Me.state.byUser,n=new Map(e),o=[];for(const s of t){const i=Number(s.userId);if(!Number.isFinite(i)||i<=0)continue;const r=e.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===e.size)){Me.state.byUser=n,Me.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})),ge.publish("desktop-mode/presence-changed",i)}ge.publish("desktop-mode/presence-snapshot-applied",{applied:t.length,transitions:o.length})}}const My=Object.freeze({getStatus:Ly,getAll:Ty,getEntry:Ny,subscribe:Dy,markActive:Oy,applyBatch:Ry}),Py="desktop_mode_nonces",pi=new Map;let rc=!1;function fi(t,e){if(typeof t!="string"||t==="")return()=>{};let n=pi.get(t);return n||(n=new Set,pi.set(t,n)),n.add(e),()=>{n.delete(e)}}function $y(){rc||(rc=!0,Ve.subscribe(Py,t=>{if(!(!t||typeof t!="object"))for(const[e,n]of Object.entries(t)){if(typeof n!="string"||n==="")continue;const o=pi.get(e);if(o)for(const s of o)try{s(n)}catch(i){console.error(`[desktop-mode/nonce-refresh] updater for "${e}" threw:`,i)}}}),Wy())}function Wy(){fi("wp_rest",Uy),fi("desktop-mode-plugins",t=>{ac("desktop-mode-plugins","ajaxNonce",t)}),fi("updates",t=>{ac("desktop-mode-plugins","updatesNonce",t)})}function Uy(t){const e=By();e&&typeof e.restNonce=="string"&&(e.restNonce=t);const n=dc();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=t)}function ac(t,e,n){const s=dc()?.[t];s&&typeof s=="object"&&(s[e]=n)}function By(){if(!(typeof window>"u"))return window.desktopModeConfig}function dc(){if(!(typeof window>"u"))return window.desktopModeWindowConfig}const Ot=12;function mi(t,e){const n=le(t,e.adminUrl);return(e.dockItems||[]).find(o=>le(o.url,e.adminUrl)===n||(o.submenu||[]).some(s=>le(s.url,e.adminUrl)===n))}function lc(t,e){const n=Math.max(200,e.width-Ot*2),o=Math.max(200,e.height-Ot*2),s=Math.min(t.width,n),i=Math.min(t.height,o),r=Math.max(0,e.width-s-Ot),a=Math.max(0,e.height-i-Ot),d=Math.max(Ot,Math.min(t.x,r)),l=Math.max(Ot,Math.min(t.y,a));return{x:d,y:l,width:s,height:i}}const cc=window.location.origin;function Hy(t,e){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!==cc)return;let l;try{l=new URL(e.adminUrl).pathname}catch(f){typeof console<"u"&&console.error("[desktop-mode] config.adminUrl is not a valid URL; falling back to /wp-admin/:",e.adminUrl,f),l="/wp-admin/"}if(!d.pathname.startsWith(l)||/\/(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(),xt(d.href)))return;const c=le(d.href,e.adminUrl),u=mi(d.href,e),p=(i.textContent||"").trim()||u?.title||"";t.open({id:c,baseId:c,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 Fy="desktop-mode-registry-changed";function zy(t,e){const n=new Set;if(Array.isArray(t))for(const r of t)r&&typeof r.id=="string"&&n.add(r.id);const o=new Set;for(const r of e)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 hi(t,e,n){const{added:o,removed:s}=zy(e,n);if(o.length===0&&s.length===0||typeof document>"u")return;const i={registry:t,added:o,removed:s};document.dispatchEvent(new CustomEvent(Fy,{detail:i}))}function jy(t){const{applyDockItems:e,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerDockRailRenderers:l,renderIcons:c}=t;return function(p){const f=p.dockItems,g=p.nativeWindows,m=p.serverWidgets,h=p.serverWallpapers,w=p.serverCommandScripts,x=p.serverCommands,D=p.serverSettingsTabScripts,y=p.serverSettingsTabs,E=p.serverDockRailRendererScripts,L=p.serverTitleBarButtonScripts,b=p.serverWindowNotices,A=p.desktopIcons;if(!Array.isArray(f)||f.length===0)return;const I=n.dockItems;if(e(f),n.dockItems=f,hi("dock-items",I,f),Array.isArray(g)){const _=n.nativeWindows;o(g),n.nativeWindows=g,hi("native-windows",_,g)}if(Array.isArray(m)&&(s(m),n.serverWidgets=m),Array.isArray(h)&&(i(h),n.serverWallpapers=h),Array.isArray(w)&&(r(w,Array.isArray(x)?x:void 0),n.serverCommandScripts=w,Array.isArray(x)&&(n.serverCommands=x)),Array.isArray(D)&&(a(D,Array.isArray(y)?y:void 0),n.serverSettingsTabScripts=D,Array.isArray(y)&&(n.serverSettingsTabs=y)),Array.isArray(L)&&(d(L),n.serverTitleBarButtonScripts=L),Array.isArray(E)&&(l(E),n.serverDockRailRendererScripts=E),Array.isArray(b)&&(Bd(b),n.serverWindowNotices=b),Array.isArray(A)){const _=n.desktopIcons;c(A),n.desktopIcons=A,hi("desktop-icons",_,A)}}}const Gy=8e3;function qy(t){const{layoutDispatcher:e,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerDockRailRenderers:l,renderIcons:c}=t,u=jy({applyDockItems:f=>e?.applyDockItems(f),config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerDockRailRenderers:l,renderIcons:c});return window.addEventListener("message",f=>{if(f.origin!==cc)return;const g=f.data;!g||g.type!=="desktop-mode-plugins-changed"||g.payload&&u(g.payload)}),()=>{if(!n.adminUrl)return Promise.resolve();const f=(()=>{try{const g=new URL("admin.php",n.adminUrl);return g.searchParams.set("desktop_mode_chromeless","1"),g.searchParams.set("desktop_mode_menu_refresh","1"),g.toString()}catch{return null}})();return f?new Promise(g=>{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 h=!1;const w=()=>{h||(h=!0,window.clearTimeout(D),window.removeEventListener("message",x),m.parentNode&&m.parentNode.removeChild(m),g())},x=y=>{if(y.source!==m.contentWindow)return;const E=y.data;!E||E.type!=="desktop-mode-plugins-changed"||w()},D=window.setTimeout(()=>{C(v.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),w()},Gy);window.addEventListener("message",x),document.body.appendChild(m)}):Promise.resolve()}}function Vy(t){if(!t)return!1;if(Array.isArray(t.windows)&&t.windows.length>0)return!0;if(typeof t.updated!="number"||t.updated<=0||!Array.isArray(t.desktops)||t.desktops.length===0)return!1;if(t.desktops.length>1)return!0;const e=t.desktops[0];return e?.id&&e.id!=="desktop-1"?!0:!!t.activeDesktop&&t.activeDesktop!=="desktop-1"}async function Ky(t,e,n){const o=n.getBoundingClientRect();Array.isArray(e.session.desktops)&&e.session.desktops.length>0&&t.seedDesktops(e.session.desktops,e.session.activeDesktop||e.session.desktops[0].id);for(const s of e.session.windows){const i=lc(s,o),r=mi(s.url,e),a=await t.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(e.session.focused){const s=t.getById(e.session.focused);s&&t.focus(s)}}async function Yy(t,e){if(xt(e.currentPage))return;const n=le(e.currentPage,e.adminUrl),o=mi(e.currentPage,e);await t.open({id:n,baseId:n,multi:!!o?.multi,url:e.currentPage,parentUrl:o?.url??e.currentPage,title:e.currentTitle,icon:e.currentIcon,submenu:o?.submenu})}function Xy(t){return!(t.fromPortal&&!t.fromPortalIntent&&(t.hasSession||!t.defaultEnabled||t.isNativeDefault))}function wi(t,e,n,o){const s=$a(e,n),i=window.fetch(e,s);if(o?.silent)return i;let r=o?.window;return!r&&o?.windowId&&(r=t.getById(o.windowId)??null),r||(r=t.getFocused()),r&&typeof r.trackActivity=="function"&&r.trackActivity(i).catch(()=>{}),i}const Zy=500;function Jy(t,e){let n=null,o=!1;const s=async()=>{if(o)return;const a=t.snapshot();o=!0;try{await wi(t,e.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({session:a}),keepalive:!0},{silent:!0})}catch(d){C(v.SHELL_ERROR,{scope:"session-save",error:d})}finally{o=!1}},i=()=>{n!==null&&(clearTimeout(n),n=null);const a=t.snapshot(),d=new Blob([JSON.stringify({session:a})],{type:"application/json"}),l=e.sessionUrl+(e.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(e.restNonce);navigator.sendBeacon&&navigator.sendBeacon(l,d)||s()},r=()=>{n!==null&&clearTimeout(n),n=window.setTimeout(()=>{n=null,s()},Zy)};return window.addEventListener("pagehide",i),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&i()}),r}const Qy=120;function eb(t){document.addEventListener("desktop-mode-window-opened",t),document.addEventListener("desktop-mode-window-closed",t),document.addEventListener("desktop-mode-window-focused",t),document.addEventListener("desktop-mode-window-changed",t),j(v.DESKTOP_CREATED,"desktop-mode/session-save",t),j(v.DESKTOP_CLOSED,"desktop-mode/session-save",t),j(v.DESKTOP_SWITCHED,"desktop-mode/session-save",t)}function tb(){const t=document.getElementById("desktop-mode-shell");let e=null;const n=()=>{e=null;const o=t?t.getBoundingClientRect():null;C(v.SHELL_RESIZED,{width:o?Math.round(o.width):window.innerWidth,height:o?Math.round(o.height):window.innerHeight})};window.addEventListener("resize",()=>{e!==null&&window.clearTimeout(e),e=window.setTimeout(n,Qy)}),document.addEventListener("visibilitychange",()=>{C(v.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function nb(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};return q(v.DOCK_TILE_CLASS,t,o)}function ob(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};return q(v.DOCK_TILE_ELEMENT,t,o)}function sb(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};return q(v.DOCK_TILE_TOOLTIP,t,o)}function ib(t,e,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:e,isSystem:n.isSystem};C(v.DOCK_TILE_RENDERED,{...o,el:t})}const rb=[".desktop-mode-dock","#desktop-mode-dock","#desktop-mode-side-dock",".desktop-mode-dock__tooltip",".desktop-mode-dock-submenu"].join(","),gi=new Set;function ab(t){if(!t||typeof t.closest!="function")return!1;const e=t;if(e.closest(rb))return!0;for(const n of gi)if(e.closest(n))return!0;return!1}function db(t){return typeof t!="string"||t.trim()===""?()=>{}:(gi.add(t),()=>{gi.delete(t)})}const Ke=new Map,lb=window.location.origin;function uc(t){let e=Ke.get(t);return e||(e={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},Ke.set(t,e)),cb(t,e),e}function cb(t,e){const n=yi(t);if(!n||e.loadHandlerTarget===n&&e.loadHandler||(e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),typeof n.addEventListener!="function"))return;const o=()=>{queueMicrotask(()=>Rt(t))};n.addEventListener("load",o),e.loadHandler=o,e.loadHandlerTarget=n}function ub(t){t.loadHandlerTarget&&t.loadHandler&&typeof t.loadHandlerTarget.removeEventListener=="function"&&t.loadHandlerTarget.removeEventListener("load",t.loadHandler),t.loadHandler=null,t.loadHandlerTarget=null}function yi(t){const e=window.wp?.desktop?.windowManager;if(e&&typeof e.getById=="function"){const o=e.getById(t);if(o?.iframe)return o.iframe;if(o?.element){const s=o.element.querySelector("iframe");if(s)return s}}return document.getElementById(`wp-window-${t}`)?.querySelector("iframe")??null}function pb(t){const e={};for(const[n,o]of t.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&&(e[n]=s.join(", "))}return e}function Rt(t){const e=yi(t);if(!e||!e.contentWindow)return;const n=Ke.get(t),o=n?pb(n):{},s=!!n&&n.observeCount>0;try{e.contentWindow.postMessage({type:"desktop-mode-instrument-set",headers:o,observe:s},lb)}catch{}}j(v.IFRAME_READY,"desktop-mode/devtools/replay",t=>{const e=t;e&&typeof e.windowId=="string"&&Ke.has(e.windowId)&&Rt(e.windowId)}),j(v.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",t=>{const e=t;if(!e||typeof e.windowId!="string")return;const n=Ke.get(e.windowId);if(n)for(const o of n.observers)try{o(e)}catch{}});const st=new Map,fb=1e3;function pc(t,e,n){const o=st.get(t);if(!o||o.inflight)return;o.inflight=!0;const s=new URL(e+"desktop-mode/v1/debug",window.location.origin);s.searchParams.set("sessionId",t),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,!!st.has(t)){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 l of d)try{l(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=st.get(t);r&&r.channels.size>0&&(r.timer=setTimeout(()=>pc(t,e,n),fb))})}function mb(){const t=window.desktopModeConfig;return!t||!t.restUrl||!t.restNonce?null:{restUrl:t.restUrl,restNonce:t.restNonce}}function hb(t,e){const n=st.get(t);if(!n)return;const o=n.channels.get(e.channel);if(o)for(const s of o)try{s(e)}catch{}}let wb=0;const fc={addRequestHeader(t,e,n){if(typeof t!="string"||t==="")return()=>{};if(typeof e!="string"||e==="")return()=>{};const o=uc(t),s={value:n};let i=o.headers.get(e);return i||(i=[],o.headers.set(e,i)),i.push(s),Rt(t),()=>{const r=Ke.get(t);if(!r)return;const a=r.headers.get(e);if(!a)return;const d=a.indexOf(s);d>=0&&a.splice(d,1),a.length===0&&r.headers.delete(e),Rt(t),mc(t)}},onRequest(t,e,n){if(typeof t!="string"||t==="")return()=>{};if(typeof e!="function")return()=>{};const o=uc(t);o.observers.add(e);const s=!!n?.observe;return s&&(o.observeCount++,Rt(t)),()=>{const i=Ke.get(t);i&&(i.observers.delete(e),s&&(i.observeCount=Math.max(0,i.observeCount-1),Rt(t)),mc(t))}},reloadWithDebugSession(t,e,n){if(typeof t!="string"||t===""||typeof e!="string"||e==="")return null;const o=yi(t);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=fc.addRequestHeader(t,s,e);try{const a=o.getAttribute("src")||o.src||"",d=new URL(a,window.location.origin);d.searchParams.set(i,e),o.src=d.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const t=window.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(t,e,n){hb(t,{id:++wb,t:Date.now(),channel:e,payload:n})},subscribe(t,e,n){let o=st.get(t);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},st.set(t,o));let i=o.channels.get(e);if(i||(i=new Set,o.channels.set(e,i)),i.add(n),s){const r=mb();r&&pc(t,r.restUrl,r.restNonce)}return()=>{const r=st.get(t);if(!r)return;const a=r.channels.get(e);a&&(a.delete(n),a.size===0&&r.channels.delete(e)),r.channels.size===0&&(r.timer&&clearTimeout(r.timer),st.delete(t))}}}};function mc(t){const e=Ke.get(t);e&&e.headers.size===0&&e.observers.size===0&&(ub(e),Ke.delete(t))}async function hc(t){return await cs(us()),new Promise(e=>{const n=document.createElement("wpd-confirm-dialog");n.setAttribute("open",""),t.title&&n.setAttribute("title",t.title),n.setAttribute("message",t.message),t.confirmLabel&&n.setAttribute("confirm-label",t.confirmLabel),t.cancelLabel&&n.setAttribute("cancel-label",t.cancelLabel),t.danger&&n.setAttribute("danger",""),t.hideCancel&&n.setAttribute("hide-cancel",""),t.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),e(i)};n.addEventListener("wpd-confirm",()=>o(!0)),n.addEventListener("wpd-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}function gb(t){const e=[];for(const d of t.getVisibleRects()){if(d.state==="minimized"||d.element.offsetParent===null)continue;const l=d.element.getBoundingClientRect();e.push({id:`window:${d.windowId}`,kind:"window",rect:wc(l),face:"top",element:d.element})}const n=document.getElementById("desktop-mode-shell");if(n){const d=n.getBoundingClientRect();e.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 l=d.getBoundingClientRect();if(l.width<=0||l.height<=0)continue;const c=d.getAttribute("data-desktop-mode-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,c==="bottom"?e.push({id:u,kind:"dock",rect:{x:l.left,y:l.top,width:l.width,height:1},face:"top",element:d}):c==="right"?e.push({id:u,kind:"dock",rect:{x:l.left,y:l.top,width:1,height:l.height},face:"left",element:d}):e.push({id:u,kind:"dock",rect:{x:l.right-1,y:l.top,width:1,height:l.height},face:"right",element:d})}const i=document.querySelectorAll(".desktop-mode-widgets__card");let r=0;i.forEach(d=>{const l=d.getBoundingClientRect();if(l.width===0&&l.height===0)return;const c=d.dataset.widgetId??String(r++);e.push({id:`widget:${c}`,kind:"widget",rect:wc(l),face:"top",element:d})});const a=q(v.WALLPAPER_SURFACES,e);return Array.isArray(a)?a:e}function wc(t){return{x:t.left,y:t.top,width:t.width,height:t.height}}const yb="__desktop_modeKeyedListKey",bb="__desktop_modeKeyedListData";function vb(t){const e=t.__desktop_modeKeyedList;if(e)return e;const n={byKey:new Map};return t.__desktop_modeKeyedList=n,n}function kb(t,e,n){const o=vb(t),s=o.byKey,i=new Map,r=[],a=new Set;for(const d of e){const l=String(n.keyOf(d));a.has(l)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",l),a.add(l);const c=s.get(l);if(c){const p=c.data;n.updateItem?.(c.el,d,p),c.data=d,i.set(l,c),r.push(c.el);continue}const u=n.buildItem(d);u[yb]=l,u[bb]=d,i.set(l,{el:u,data:d}),r.push(u)}for(const[d,l]of s)i.has(d)||l.el.remove();for(let d=0;d<r.length;d++){const l=r[d],c=t.children[d];c!==l&&t.insertBefore(l,c??null)}o.byKey=i}function _b(t){const e=t.__desktop_modeKeyedList;if(e){for(const n of e.byKey.values())n.el.remove();e.byKey.clear(),delete t.__desktop_modeKeyedList}}function Eb(t){const{root:e,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:d=A=>{typeof console<"u"&&console.error("[desktop-mode] createInfiniteList:",A)}}=t;let l=t.sentinel??null;l||(l=document.createElement("div"),l.dataset.wpdInfiniteListSentinel="",l.style.height="1px",e.appendChild(l));const c=new Set;let u=r,p=!0,f=!1,g=null,m=0,h=!1,w=null;const x=A=>{if(f!==A){f=A;try{a(A)}catch(I){d(I)}}},D=()=>{w&&(w.disconnect(),w=null)},y=()=>{w||!l||h||(w=new IntersectionObserver(A=>{for(const I of A)I.isIntersecting&&E()},{rootMargin:i}),w.observe(l))},E=async()=>{if(h||f||!p)return;x(!0),g=new AbortController;const A=g;try{const I=await n(u,A.signal);if(h||A!==g)return;let _=0;const k=document.createDocumentFragment();for(const O of I.items??[]){const M=String(o(O));if(c.has(M))continue;c.add(M);const X=s(O,m+_);k.appendChild(X),_++}_>0&&(l&&l.parentNode===e?e.insertBefore(k,l):e.appendChild(k),m+=_),u=I.nextCursor??null,u||(p=!1,D())}catch(I){if(I?.name==="AbortError")return;d(I)}finally{A===g&&(x(!1),g=null)}},L=()=>{if(h)return;g?.abort(),g=null,c.clear(),u=r,p=!0,m=0;const A=l&&l.parentNode===e;for(;e.firstChild;)e.removeChild(e.firstChild);A&&l&&e.appendChild(l),x(!1),y(),E()},b=()=>{h||(h=!0,D(),g?.abort(),g=null,!t.sentinel&&l&&l.parentNode===e&&e.removeChild(l),l=null,x(!1))};return y(),E(),{reset:L,loadMore:E,hasMore:()=>p,isLoading:()=>f,destroy:b}}const Sb=520,Cb=720,xb=500;function Ab(t,e={}){if(typeof t!="string"||t==="")return Promise.reject(new Error("[desktop-mode] startOAuth requires a non-empty service slug."));const n=Lb(),o=Tb();return je(sn(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:t})},{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=>Ib(s,t,e))}function Ib(t,e,n){return new Promise((o,s)=>{const i=n.width??Sb,r=n.height??Cb,a=Math.max(0,Math.floor((window.screen.width-i)/2)),d=Math.max(0,Math.floor((window.screen.height-r)/2)),l=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${d}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),c=window.open(t.authorize_url,`desktop-mode-oauth-${e}`,l);if(!c){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 g=()=>{f||(f=!0,window.removeEventListener("message",m),p!==null&&(window.clearInterval(p),p=null))},m=h=>{if(h.origin!==u)return;const w=h.data;if(!w||w.type!=="desktop-mode-oauth-callback")return;const x=w.payload;if(g(),x&&x.ok)o(x);else{const D=x?.reason??"unknown",y=x?.message??"OAuth flow failed",E=new Error(`[desktop-mode] startOAuth(${e}) failed: ${D} — ${y}`);E.cause=x,s(E)}};window.addEventListener("message",m),p=window.setInterval(()=>{c.closed&&(g(),s(new Error(`[desktop-mode] startOAuth(${e}) cancelled — popup closed before completing.`)))},xb)})}function gc(){return window.desktopModeConfig??{}}function Lb(){const t=gc().restRoot;return typeof t=="string"&&t!==""?t:`${window.location.origin}/wp-json/`}function Tb(){const t=gc().restNonce;return typeof t=="string"&&t!==""?t:null}const Nb=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 Db(t){const{manager:e,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:d,registerWindow:l,openWindowById:c,openNewWindowById:u,placeSystemTile:p,setDefaultWindow:f,refreshMenu:g,openOsSettings:m,aiAssistant:h,dragBridge:w,dragManager:x,connect:D,getConnection:y,config:E}=t,L={windowManager:e,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,icons:i,files:r,confirm:hc,saveSession:a,hooks:tp(),HOOKS:v,isActive:()=>!!document.getElementById("desktop-mode-shell"),registerWallpaper:b=>{tn(b),s.apply()},registerWidget:b=>{Ks(b)},widgetLayer:d,widgets:{redock:b=>{d?.redock(b)}},loadVendorScript:Ae,getWallpaperSurfaces:()=>gb(e),registerWindow:l,openWindow:c,openNewWindow:u,fetch:(b,A,I)=>wi(e,b,A,I),repaintLoadingOverlays:ka,cloneTemplate:Qs,onWindow:Aw,createInfiniteList:Eb,startOAuth:Ab,registerSystemTile:b=>{p(b),C(v.DOCK_ITEM_APPENDED,{id:b.id})},registerModule:sd,loadModules:id,whenReady:Or,ready:Or,isReady:op,setDefaultWindow:f,refreshMenu:g,config:E,ai:h,dragBridge:w,dragManager:x,registerCommand:So,unregisterCommand:cd,listCommands:ud,registerDestructiveAdminAction:mf,unregisterDestructiveAdminAction:Sa,listDestructiveAdminActions:hf,registerSettingsTab:fd,unregisterSettingsTab:md,listSettingsTabs:hd,registerDockRailRenderer:Ua,unregisterDockRailRenderer:jf,listDockRailRenderers:qf,openOsSettings:m,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:b=>s.subscribeOsSettings(b),updateOsSettings:(b,A={})=>{if(typeof b.wallpaper=="string"&&(s.state.wallpaper=b.wallpaper),typeof b.accent=="string"&&(s.state.accent=b.accent),typeof b.dockSize=="string"&&(s.state.dockSize=b.dockSize),typeof b.desktopLayout=="string"&&(s.state.desktopLayout=b.desktopLayout),typeof b.dockRailRenderer=="string"&&(s.state.dockRailRenderer=b.dockRailRenderer),b.ai&&typeof b.ai=="object"&&(s.state.ai={...s.state.ai,...b.ai}),typeof b.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=b.nativePostsEnabled),typeof b.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=b.nativePagesEnabled),typeof b.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=b.nativeUsersEnabled),typeof b.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=b.nativePluginsEnabled),typeof b.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=b.nativeCommentsEnabled),typeof b.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=b.foldersSharingEnabled),Array.isArray(b.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=b.nativePostsHiddenColumns.filter(I=>typeof I=="string"&&I!=="").slice(0,32)),b.itemVisibility&&typeof b.itemVisibility=="object"){const I=["both","dock","desktop","hidden"],_={};for(const[k,O]of Object.entries(b.itemVisibility))typeof k!="string"||k===""||typeof O!="string"||!I.includes(O)||(_[k]=O);s.state.itemVisibility=_}if(Array.isArray(b.dockOrder)&&(s.state.dockOrder=b.dockOrder.filter(I=>typeof I=="string"&&I!=="").slice(0,256)),b.dockPromotedPositions&&typeof b.dockPromotedPositions=="object"){const _={};for(const[k,O]of Object.entries(b.dockPromotedPositions)){if(typeof k!="string"||k===""||!O||typeof O!="object")continue;const M=O;if(!(typeof M.x!="number"||typeof M.y!="number"||!Number.isFinite(M.x)||!Number.isFinite(M.y)||Math.abs(M.x)>1e5||Math.abs(M.y)>1e5)&&(_[k]={x:M.x,y:M.y},Object.keys(_).length>=256))break}s.state.dockPromotedPositions=_}s.save(A),(b.itemVisibility||b.dockOrder)&&o?.refresh()},deriveWindowId:(b,A)=>le(b,A??E.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:b=>o?.getSystemTile(b)??null,getMenuItems:()=>o?.getMenuItems()??[],renderIcon:ei,applyTileClasses:nb,applyTileElement:ob,applyTileTooltip:sb,dispatchTileRendered:ib,isDockElement:ab,registerDockSelector:db,registerTitleBarButton:yd,unregisterTitleBarButton:eh,listTitleBarButtons:nh,registerWindowTheme:kd,unregisterWindowTheme:_d,listWindowThemes:Ed,applyWindowTheme:(b,A)=>{const I=e.getById(b);I&&I.setAppearanceTheme(A)},registerWindowControl:pn,unregisterWindowControl:xd,listWindowControls:Ad,applyWindowControls:(b,A)=>{const I=e.getById(b);I&&I.setAppearanceControls(A)},registerWindowSlot:Nd,unregisterWindowSlot:Bs,listWindowSlots:Dd,applyWindowSlot:(b,A,I)=>{const _=e.getById(b);_&&_.setAppearanceSlot(A,I)},registerWindowNotice:Wd,unregisterWindowNotice:js,listWindowNotices:Ud,dismissWindowNotice:kh,undismissWindowNotice:_h,registerWindowChrome:Ch,unregisterWindowChrome:zd,listWindowChromes:jd,applyWindowChrome:(b,A)=>{const I=e.getById(b);I&&I.setAppearanceChrome(A)},connect:D,getConnection:y,broadcast:hl,subscribe:Re,registerPalette:Ql,unregisterPalette:_y,listPalettes:Ey,openPalette:tc,devtools:fc,createSharedStore:ce,presence:My,activity:ge,heartbeat:Ve,showToast:J,notify:Wg,pwa:{promptInstall:Pg,undismissInstallHint:$g,getState:kn,subscribe:Sl,requestNotificationPermission:Ug,getNotificationPermission:Bg},renderKeyedList:kb,clearKeyedList:_b,registerNamespace:(b,A)=>{if(typeof b!="string"||b===""){console.warn("[desktop-mode] registerNamespace: name must be a non-empty string");return}if(!A||typeof A!="object"){console.warn(`[desktop-mode] registerNamespace("${b}"): api must be an object`);return}if(Nb.has(b)){console.warn(`[desktop-mode] registerNamespace("${b}"): name is reserved by the shell — pick a plugin-specific key`);return}L[b]=A},getWindowConfig:b=>{const A=window.desktopModeWindowConfig;if(!A||typeof A!="object")return;const I=A[b];return I===void 0?void 0:I},debug:{window:b=>{const A=(E.nativeWindows??[]).find(X=>X.id===b);if(!A)return null;const I=A.scriptUrl||"";let _="unknown",k=!1;I&&(document.querySelector(`script[data-desktop-mode-vendor="${I.replace(/"/g,'\\"')}"]`)?(_="lazy",k=!0):Array.from(document.querySelectorAll("script[src]")).find(te=>te.src===I)&&(_="eager",k=!0));const O=window.desktopModeWindowConfig,M=!!(O&&typeof O=="object"&&Object.prototype.hasOwnProperty.call(O,b));return{id:b,scriptHandle:A.scriptHandle||"",scriptUrl:I,loadPath:_,tagInDom:k,configPresent:M,extras:{hasTranslations:!!A.scriptTranslations,l10nCount:(A.scriptL10n??[]).length,beforeCount:(A.scriptBefore??[]).length,afterCount:(A.scriptAfter??[]).length}}}}};return L}function Ob(t){if(window.wp||(window.wp={}),!window.wp.desktop){window.wp.desktop=t;return}Object.assign(window.wp.desktop,t)}const bi=ce("desktop-mode/layout",()=>({layout:"classic"}));function yc(t){bi.state.layout!==t&&(bi.state.layout=t,bi.notify())}class bc{constructor(e){this.shape=e}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 Rb extends bc{constructor(e,n){super(e),this.typeSlug=n}type(){return this.typeSlug}}const _n=new Map,vi=new Set;function Pe(t){if(!t.type)throw new Error("[desktop-mode] registerType: `type` is required.");if(!t.label)throw new Error("[desktop-mode] registerType: `label` is required.");_n.set(t.type,{type:t.type,label:t.label,sort:typeof t.sort=="number"?t.sort:100,DesktopFile:t.DesktopFile}),C("desktop-mode.files.type-registered",t.type,t),kc()}function Mb(t){_n.delete(t)&&(C("desktop-mode.files.type-unregistered",t),kc())}function Pb(t){const e=_n.get(t);return e||null}function vc(){const t=Array.from(_n.values()).slice(),e=q("desktop-mode.files.types",t),n=Array.isArray(e)?e:t;return n.sort((o,s)=>o.sort!==s.sort?o.sort-s.sort:o.label.localeCompare(s.label)),n}function Bo(t){const e=_n.get(t.type);return e?.DesktopFile?new e.DesktopFile(t):new Rb(t,t.type)}function $b(t){return vi.add(t),()=>vi.delete(t)}function kc(){for(const t of vi)try{t()}catch(e){console.error("[desktop-mode] files registry subscriber threw:",e)}}const Ho=new Map,ki=new Set;let _i={};function _c(t){_i={...t},xi()}function Ei(){return{..._i}}function $e(t){if(!t.id)throw new Error("[desktop-mode] registerOpener: `id` is required.");if(!t.label)throw new Error("[desktop-mode] registerOpener: `label` is required.");if(!Array.isArray(t.types)||t.types.length===0)throw new Error("[desktop-mode] registerOpener: `types` must be a non-empty array.");if(!t.handler||typeof t.handler!="object")throw new Error("[desktop-mode] registerOpener: `handler` is required.");Ho.set(t.id,{id:t.id,label:t.label,types:t.types.slice(),isDefault:!!t.isDefault,sort:typeof t.sort=="number"?t.sort:100,handler:t.handler}),C("desktop-mode.files.opener-registered",t.id,t),xi()}function Wb(t){Ho.delete(t)&&(C("desktop-mode.files.opener-unregistered",t),xi())}function Ub(t){return Ho.get(t)??null}function Ec(){const t=Array.from(Ho.values()).slice(),e=q("desktop-mode.files.openers",t),n=Array.isArray(e)?e:t;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(t){return Ec().filter(e=>e.types.includes(t))}function Ci(t){const e=Si(t);if(e.length===0)return null;const n=_i[t];let o=null;return n&&(o=e.find(i=>i.id===n)??null),o||(o=e.find(i=>i.isDefault)??null),o||(o=e[0]),q("desktop-mode.files.resolve-opener",o,t)??null}function Bb(t){return ki.add(t),()=>ki.delete(t)}function xi(){for(const t of ki)try{t()}catch(e){console.error("[desktop-mode] openers subscriber threw:",e)}}let En=null;function Hb(t){En=t}async function Ai(t,e){if(!En)return console.warn("[desktop-mode] wp.desktop.files.open() called before the shell installed open deps. The file will not open."),!1;const n=Ci(t.type());if(!n)return C("desktop-mode.files.open-failed",{reason:"no-opener",type:t.type(),ref:t.ref()}),!1;C("desktop-mode.files.opening",{file:t,openerId:n.id});try{const o=n.handler;if(o.kind==="url"){const s=await o.url(t);if(!s)return!1;const i=o.windowId?o.windowId(t):En.deriveWindowId(s),r=o.title?o.title(t):t.title(),a=t.icon(),d=En.openUrl({id:i,url:s,title:r,icon:a});return C("desktop-mode.files.opened",{file:t,openerId:n.id,kind:"url"}),d}if(o.kind==="window"){const s=o.config?o.config(t):void 0,i=En.openNativeWindow(o.windowId,s);return C("desktop-mode.files.opened",{file:t,openerId:n.id,kind:"window"}),i}return await o.open(t,e),C("desktop-mode.files.opened",{file:t,openerId:n.id,kind:"js"}),!0}catch(o){return C("desktop-mode.files.open-failed",{reason:"handler-threw",type:t.type(),ref:t.ref(),openerId:n.id,error:o}),console.error("[desktop-mode] file opener threw:",o),!1}}function Fb(){Pe({type:"shortcut",label:"Plugin shortcut",sort:1}),Pe({type:"folder",label:"Folder",sort:5}),Pe({type:"post",label:"Post",sort:10}),Pe({type:"attachment",label:"Media",sort:20}),Pe({type:"user",label:"User",sort:30}),Pe({type:"term",label:"Taxonomy term",sort:40}),Pe({type:"comment",label:"Comment",sort:50}),Pe({type:"bookmark",label:"Bookmark",sort:60}),Pe({type:"link",label:"Web link",sort:70}),Pe({type:"embed",label:"Embedded web window",sort:80})}let Ii=null;function Sc(t){Ii=t}function Cc(){if(!Ii)throw new Error("[desktop-mode] files REST client called before installRestDeps().");return Ii}class Li extends Error{constructor(e){super(`Row was changed by ${e.actor.name||"another session"} (parent="${e.current.parentName}")`),this.name="FilesConflictError",this.status=409,this.detail=e}}async function he(t,e){const{baseUrl:n,nonce:o}=Cc(),s=sn(n,t),i=new Headers(e.headers??{});i.set("X-WP-Nonce",o),e.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await je(s,{...e,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),a=await r.text();let d=null,l=null;if(a)try{d=JSON.parse(a)}catch(c){d=null,l=c}if(!r.ok){if(r.status===409){const u=d?.data?.data??d?.data;if(u&&typeof u=="object")throw new Li(u)}const c=d;throw new Error(`[desktop-mode] files REST ${r.status}: ${c?.code??""} ${c?.message??""}`.trim())}if(d===null){if(l&&a){const c=a.slice(0,120).replace(/\s+/g," ");throw new Error(`[desktop-mode] files REST ${r.status} returned non-JSON body — ${l.message}. First 120 chars: ${c}`)}throw new Error(`[desktop-mode] files REST ${r.status}: empty or unparseable body.`)}return d}function Oe(t=0){return he(`/placements?folder=${encodeURIComponent(String(t))}`,{method:"GET"})}function Mt(t){return he("/placements",{method:"POST",body:JSON.stringify(t)})}function Pt(t,e,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),he(`/placements/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:o})}function xc(t){return he(`/placements/${t}`,{method:"DELETE"})}async function Ti(t,e){const{baseUrl:n,nonce:o}=Cc(),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:t,type:e}]})},{source:"desktop-mode/files"});if(!r.ok)throw new Error(`[desktop-mode] restore ${r.status}`);return await r.json()}function Ac(){return he("/folders",{method:"GET"})}function Ni(t){return he("/folders",{method:"POST",body:JSON.stringify(t)})}function Ic(t,e,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),he(`/folders/${t}`,{method:"PATCH",body:JSON.stringify(e),headers:o})}function Lc(t){return he(`/folders/${t}`,{method:"DELETE"})}function Tc(t){return he("/associations",{method:"PUT",body:JSON.stringify({associations:t})})}function Nc(t){return he(`/folders/${t}/shares`,{method:"GET"})}function Dc(t,e){return he(`/folders/${t}/shares`,{method:"POST",body:JSON.stringify(e)})}function Oc(t,e,n){return he(`/folders/${t}/shares/${e}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function Rc(t,e){return he(`/folders/${t}/shares/${e}`,{method:"DELETE"})}function Mc(t,e){return he(`/folders/${t}/shares/${e}/accept`,{method:"POST"})}function Pc(t,e){return he(`/folders/${t}/shares/${e}/deny`,{method:"POST"})}function $c(t){return he(`/folders/${t}/leave`,{method:"POST"})}function zb(){return he("/folder-sharing-tables/purge",{method:"POST"})}const jb=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:Li,acceptShare:Mc,createFolder:Ni,createPlacement:Mt,deleteFolder:Lc,deletePlacement:xc,denyShare:Pc,installRestDeps:Sc,inviteShare:Dc,leaveShare:$c,listFolders:Ac,listPlacements:Oe,listShares:Nc,purgeFolderSharingTables:zb,restoreTrashedItem:Ti,revokeShare:Rc,saveAssociations:Tc,updateFolder:Ic,updatePlacement:Pt,updateShareCapability:Oc},Symbol.toStringTag,{value:"Module"})),Gb="desktop-mode/files";function Ye(){return ce(Gb,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function $t(t){typeof document>"u"||document.dispatchEvent(new CustomEvent("desktop-mode-files-changed",{detail:{source:"local",...t}}))}function Wt(t,e){const n=Ye(),o=new Map(n.state.placementsByFolder);o.set(t,e.slice());const s=new Set(n.state.hydratedFolders);s.add(t),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),$t({kind:"placements-set",folderId:t})}function Di(t,e="local"){if(!t||typeof t.id!="number"){console.warn("[desktop-mode] upsertPlacement called with a non-placement value; ignoring.",t);return}const n=Ye(),o=new Map(n.state.placementsByFolder);for(const[a,d]of o)if(d.findIndex(c=>c&&c.id===t.id)>=0&&a!==t.parentId){const c=d.filter(Boolean),u=c.findIndex(p=>p.id===t.id);u>=0&&c.splice(u,1),o.set(a,c)}const i=(o.get(t.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===t.id);r>=0?i[r]=t:i.push(t),o.set(t.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),$t({kind:"placement-upserted",placementId:t.id,folderId:t.parentId,source:e})}function Fo(t,e="local"){const n=Ye(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(d=>d&&d.id===t)>=0){const d=r.filter(Boolean).filter(l=>l.id!==t);o.set(i,d),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),$t({kind:"placement-removed",placementId:t,folderId:s,source:e}))}function Wc(t){const e=Ye(),n=new Map;for(const o of t)n.set(o.id,o);e.state={...e.state,folders:n},e.notify(),$t({kind:"folders-set"})}function Oi(t,e="local"){const n=Ye(),o=new Map(n.state.folders);o.set(t.id,t),n.state={...n.state,folders:o},n.notify(),$t({kind:"folder-upserted",folderRowId:t.id,source:e})}function Ri(t,e="local"){const n=Ye(),o=new Map(n.state.folders);o.delete(t);const s=new Map(n.state.placementsByFolder);s.delete(t),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),$t({kind:"folder-removed",folderRowId:t,source:e})}function Mi(t){return Ye().subscribe(t)}function wt(){return Ye().getState()}const Y={getState:wt,subscribe:Mi,setFolderPlacements:Wt,upsertPlacement:Di,upsertFolder:Oi,removePlacement:Fo,removeFolder:Ri},qb=me`:host{display:inline-block}`,Vb=me`: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 )}`,Gn=class Gn extends ue{render(){return B`<span class="banner" part="banner"><slot></slot></span>`}};Gn.props=["placement","tone"],Gn.styles=[Vb],Gn.help=void 0;let Pi=Gn;fe("wpd-ribbon",Pi);const Q="desktop-mode-file-tile",Uc={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function Kb(){const t=window.wp?.desktop?.getOsSettings;if(typeof t!="function")return!0;try{return t()?.showPostStatusRibbons!==!1}catch{return!0}}function Yb(){return window.wp?.desktop?.dragManager??null}const Xb=["type","ref","label","icon","thumbnail","kind","status","selected","missing","access-gated","drag-kind","drag-title","drag-icon"],Gt=class Gt extends ue{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=e=>{(e.key==="Enter"||e.key===" ")&&(e.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 e=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"),l=this.hasAttribute("missing"),c=this.hasAttribute("access-gated"),u=[Q,`${Q}--folder`,`${Q}--missing`,`${Q}--access-gated`,`${Q}--selected`];for(const h of u)this.classList.remove(h);this.classList.add(Q),r==="folder"&&this.classList.add(`${Q}--folder`),l&&this.classList.add(`${Q}--missing`),c&&this.classList.add(`${Q}--access-gated`),d&&this.classList.add(`${Q}--selected`),this.dataset.fileType=e,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.";c?(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 h of f)this.querySelectorAll(`:scope > .${h}`).forEach(w=>w.remove());this.querySelectorAll(":scope > wpd-ribbon").forEach(h=>h.remove());const g=document.createElement("span");if(g.className=`${Q}__visual`,i){const h=document.createElement("img");h.src=i,h.alt="",h.loading="lazy",h.decoding="async",h.className=`${Q}__preview`,h.draggable=!1,g.appendChild(h)}else if(s){const h=ei(s,{title:o,className:`${Q}__icon`});g.appendChild(h)}this.appendChild(g);const m=document.createElement("span");if(m.className=`${Q}__label`,m.textContent=o,this.appendChild(m),c){const h=document.createElement("span");h.className=`${Q}__lock dashicons dashicons-lock`,h.setAttribute("aria-hidden","true"),this.appendChild(h)}if(a&&a!=="publish"&&Uc[a]&&Kb()){const h=document.createElement("wpd-ribbon");h.setAttribute("placement","top-end"),h.setAttribute("tone",Zb(a)),h.textContent=Uc[a],this.appendChild(h)}jp(this),C("desktop-mode.tile.rendered",{tile:this}),this._wireDragOut()}_wireDragOut(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null);const e=this.getAttribute("drag-kind");if(!e)return;const n=o=>{if(o.button!==0)return;const s=Yb();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:e,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)}};Gt.shadow=!1,Gt.props=Xb,Gt.styles=[qb],Gt.help=void 0;let $i=Gt;function Zb(t){switch(t){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}fe("wpd-tile",$i);function Jb(t){const e=document.createElement("wpd-tile");if(e.setAttribute("type",t.type),e.setAttribute("ref",t.ref),e.setAttribute("label",t.label),t.icon&&e.setAttribute("icon",t.icon),t.thumbnail&&e.setAttribute("thumbnail",t.thumbnail),t.role&&e.setAttribute("kind",t.role),t.status&&e.setAttribute("status",t.status),t.missing&&e.setAttribute("missing",""),t.accessGated&&e.setAttribute("access-gated",""),t.dataset)for(const[o,s]of Object.entries(t.dataset))s!=null&&(e.dataset[o]=String(s));if(Array.isArray(t.extraClasses))for(const o of t.extraClasses)o&&e.classList.add(o);const n=q("desktop-mode.tile.class",e.className,t);return n&&n!==e.className&&(e.className=n),typeof t.x=="number"&&typeof t.y=="number"&&(e.style.position="absolute",e.style.left=`${t.x}px`,e.style.top=`${t.y}px`),e}function Qb(t,e){const n=Bo(t.file),o=n.previewUrl(),s=t.meta&&typeof t.meta.name=="string"?t.meta.name.trim():"",i=s!==""?s:n.title(),r=t.meta&&typeof t.meta.iconUrl=="string"?t.meta.iconUrl.trim():"";return{type:t.file.type,ref:t.file.ref,label:i,thumbnail:o||void 0,icon:o?void 0:r||n.icon(),x:t.x,y:t.y,dataset:{placementId:t.id,folderId:e},meta:t.meta,missing:!t.file.exists,accessGated:!!t.accessGated,ariaLabel:i}}function ev(t,e){const n=Bo(t.file),o=Jb(Qb(t,e)),s=q("desktop-mode.files.tile-class",Q,t);s&&s!==Q&&(o.className=s);const i=q("desktop-mode.files.tile-element",null,t);return i instanceof Element&&o.appendChild(i),o.addEventListener("dblclick",r=>{if(r.preventDefault(),r.stopPropagation(),t.accessGated){J({message:`You don’t have permission to open "${t.file.title||n.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}Ai(n,{placement:{id:t.id,x:t.x,y:t.y,meta:t.meta}})}),C("desktop-mode.files.tile-rendered",{tile:o,placement:t}),o}function Xe(t,e,n){t.style.left=`${e}px`,t.style.top=`${n}px`}function Bc(t,e){const n=s=>{if(!(s.target instanceof Node&&t.contains(s.target))){if(s.target instanceof Node)for(const i of e.siblingSelectors??[]){const r=Array.from(document.querySelectorAll(i));for(const a of r)if(a.contains(s.target))return}e.excludeOutsideTarget&&s.target instanceof Node&&e.excludeOutsideTarget.contains(s.target)||e.close()}},o=s=>{s.key==="Escape"&&e.close()};return document.addEventListener("mousedown",n,{capture:!0}),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",n,{capture:!0}),document.removeEventListener("keydown",o)}}const tv="desktop-mode-wallpaper-menu";let Sn=null;function Wi(){Sn&&(Sn.dispatchEvent(new CustomEvent("tile-menu-closed")),Sn.remove(),Sn=null,C("desktop-mode.files.tile-menu.closed",{}))}let Hc=0;function nv(t,e){Wi();const n=++Hc;Yt(()=>n===Hc,()=>ov(t,e))}function ov(t,{placement:e,items:n}){const o=q("desktop-mode.files.tile-menu",n.slice(),e),s=(Array.isArray(o)?o:n).slice().sort((l,c)=>{const u=typeof l.sort=="number"?l.sort:100,p=typeof c.sort=="number"?c.sort:100;return u!==p?u-p:l.label.localeCompare(c.label)});if(s.length===0)return;const i=document.createElement("wpd-context-menu");i.setAttribute("open",""),i.classList.add(tv),i.dataset.placementId=String(e.id),i.style.left=`${t.x}px`,i.style.top=`${t.y}px`;const r=new Map;for(const l of s){r.set(l.id,l);const c=document.createElement("wpd-context-menu-option");c.dataset.menuItemId=l.id,c.setAttribute("value",l.id),l.danger&&c.setAttribute("danger",""),l.disabled&&c.setAttribute("disabled",""),l.icon&&c.setAttribute("icon",sv(l.icon)),c.textContent=l.label,i.appendChild(c)}i.addEventListener("wpd-context-menu-pick",l=>{const c=l.detail,u=r.get(c.id);u&&(Wi(),u.onClick(new MouseEvent("click")))}),document.body.appendChild(i),Sn=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=Bc(i,{close:()=>Wi()});i.addEventListener("tile-menu-closed",d),C("desktop-mode.files.tile-menu.opened",{placementId:e.id,items:s.map(l=>l.id)})}function sv(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}const be="desktop-mode-create-folder-dialog";let Cn=null;function Ui(){Cn&&(Cn.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),Cn.remove(),Cn=null,C("desktop-mode.files.create-folder.closed",{}))}function Bi(t){if(Ui(),q("desktop-mode.files.create-folder.dialog",null,t)===!1)return;const n=(t.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${be}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=be,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${be}-title`);const i=document.createElement("h2");i.id=`${be}-title`,i.className=`${be}__title`,i.textContent=t.title??"New folder",s.appendChild(i);const r=document.createElement("label");r.className=`${be}__label`,r.htmlFor=`${be}-input`,r.textContent=t.label??"Folder name",s.appendChild(r);const a=document.createElement("input");a.type="text",a.id=`${be}-input`,a.className=`${be}__input`,a.value=n,a.setAttribute("autocomplete","off"),a.setAttribute("spellcheck","false"),s.appendChild(a);const d=document.createElement("p");d.className=`${be}__error`,d.hidden=!0,d.setAttribute("role","alert"),s.appendChild(d);const l=document.createElement("div");l.className=`${be}__actions`;const c=document.createElement("button");c.type="button",c.className=`${be}__btn ${be}__btn--secondary`,c.textContent="Cancel";const u=document.createElement("button");u.type="button",u.className=`${be}__btn ${be}__btn--primary`,u.textContent=t.submitLabel??"Create",l.appendChild(c),l.appendChild(u),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),Cn=o,a.focus(),a.select(),C("desktop-mode.files.create-folder.opened",{});const p=w=>{a.disabled=w,c.disabled=w,u.disabled=w,s.classList.toggle(`${be}--busy`,w)},f=w=>{d.textContent=w,d.hidden=!1},g=()=>{Ui(),t.onCancel?.()},m=async()=>{const w=a.value.trim();if(!w){f("Please enter a name."),a.focus();return}d.hidden=!0,p(!0);try{await t.onSubmit(w),Ui()}catch(x){p(!1),f(x instanceof Error?x.message:"Could not create the folder."),a.focus(),a.select()}};c.addEventListener("click",()=>g()),u.addEventListener("click",()=>void m()),o.addEventListener("click",w=>{w.target===o&&g()});const h=w=>{w.key==="Escape"?(w.preventDefault(),g()):w.key==="Enter"&&!w.isComposing&&(w.preventDefault(),m())};s.addEventListener("keydown",h),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",h)})}const Le=16,it=96,xn=110;function An(t,e){const n=Math.max(0,Math.round((t-Le)/it)),o=Math.max(0,Math.round((e-Le)/xn));return Ut(n,o)}function Ut(t,e){return{col:t,row:e,x:Le+t*it,y:Le+e*xn}}function gt(t,e,n,o){const s=An(t,e);if(!n.has(ve(s.col,s.row)))return s;const i=o?Math.max(1,Math.floor((o.clientHeight-Le)/xn)):999;for(let r=0;r<999;r++)for(let a=0;a<i;a++)if(!n.has(ve(r,a)))return Ut(r,a);return s}function Fc(t,e){const n=e?Math.max(1,Math.floor((e.clientWidth-Le)/it)):4,o=Math.max(1,n);for(let s=0;s<999;s++)for(let i=0;i<o;i++)if(!t.has(ve(i,s)))return Ut(i,s);return Ut(0,0)}function zc(t,e){const n=new Set;for(const o of t){const s=An(o.x,o.y);n.add(ve(s.col,s.row))}return n}function ve(t,e){return`${t},${e}`}function jc(t){return t instanceof Li}function iv(t){const e=t.detail.actor.name||"Someone else",n=t.detail.current.parentName||"another folder";return t.detail.reason==="trashed"?"This item is in the recycle bin.":t.detail.reason==="forbidden"?"You no longer have access.":t.detail.reason==="gone"?"This item was deleted.":`${e} moved this to "${n}".`}function Gc(t){const e=iv(t),n=t.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)}}),J({message:e,action:o,duration:7e3})}function zo(t,e,n){window.wp?.desktop?.broadcast?.(`desktop-mode.${t}.changed`,{source:"desktop-files",action:e,ids:n})}function qc(t){const e=window.wp?.desktop;if(!e?.showToast)return;const o=(t instanceof Error?t.message:String(t)).replace(/^\[desktop-mode\][^:]*:\s*/,"").replace(/^desktop_mode_files_[a-z_]+\s*/,"");e.showToast({message:o||"Could not move this item to the recycle bin.",duration:5e3})}function Vc(t,e){const n=window.wp?.desktop;n?.showToast&&n.showToast({message:t,duration:6e3,action:{label:"Undo",onClick:e}})}async function Kc(t){const e=t.id,n=t.parentId,o=t.file?.title??"Item",s=t.file?.type==="shortcut"?"shortcut":"placement";Y.removePlacement(e);try{await xc(e),zo(s,"trashed",[e]),Vc(`"${o}" moved to Trash`,async()=>{try{await Ti(e,"placement");const i=await Oe(n);Y.setFolderPlacements(n,i.placements),zo(s,"untrashed",[e])}catch(i){console.error("[desktop-mode] restore failed:",i)}})}catch(i){console.error("[desktop-mode] deletePlacement failed:",i),qc(i),Oe(n).then(r=>{Y.setFolderPlacements(n,r.placements)})}}async function Yc(t){const e=parseInt(t.file.ref,10);if(!e)return;const n=t.id,o=t.parentId,s=t.file?.title??"Folder";Y.removePlacement(n),Y.removeFolder(e);try{await Lc(e),zo("folder","trashed",[e]),Vc(`"${s}" moved to Trash`,async()=>{try{await Ti(e,"folder");const i=await Oe(o);Y.setFolderPlacements(o,i.placements),zo("folder","untrashed",[e])}catch(i){console.error("[desktop-mode] restore folder failed:",i)}})}catch(i){console.error("[desktop-mode] deleteFolder failed:",i),qc(i),Oe(o).then(r=>{Y.setFolderPlacements(o,r.placements)})}}function rv(t){return t.file?.type==="folder"?Yc(t):Kc(t)}function av(t){const e=t.file;if(!e)return;const n=parseInt(String(e.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(e.title??"");if(e.type==="attachment"){const s=String(e.sourceUrl??e.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(e.alt??""),mime:String(e.mime??""),thumbnailUrl:e.previewUrl?String(e.previewUrl):void 0}}if(e.type==="post")return{kind:"post",id:n,postType:String(e.postType??"post"),url:String(e.link??""),title:o};if(e.type==="user")return{kind:"user",id:n,url:String(e.link??""),title:o}}function In(){return window.wp?.desktop?.dragManager??null}const dv="desktop-mode-files-layer";function Xc(t,e=0){const n=document.createElement("div");n.className=dv,n.setAttribute("role","list"),n.dataset.folderId=String(e),t.appendChild(n);let o="",s=null;const i=new Set,r=T=>{for(const F of i)try{F(T)}catch(H){console.error("[desktop-mode] files: selection listener threw:",H)}},a=T=>{const F=T?T.id:null;F!==s&&(n.querySelectorAll(`.${Q}--selected`).forEach(H=>H.removeAttribute("selected")),T&&n.querySelector(`[data-placement-id="${T.id}"]`)?.setAttribute("selected",""),s=F,r(T))},d=T=>{const F=new Map,H=new Set;let P=0;for(const R of T){if(!Se(R))continue;const $=Ut(0,P);F.set(R.id,{x:$.x,y:$.y}),H.add(ve($.col,$.row)),P+=1}const V=new Map;for(const R of T){if(F.has(R.id))continue;const $=An(R.x,R.y),G=ve($.col,$.row);if(!H.has(G)){H.add(G);continue}const ne=gt(R.x,R.y,H,t);H.add(ve(ne.col,ne.row)),V.set(R.id,{x:ne.x,y:ne.y})}return{pinnedSlots:F,displaced:V}},l=(T,F,H,P)=>{const V=H.get(F.id),R=P.get(F.id);V?Xe(T,V.x,V.y):R?Xe(T,R.x,R.y):Xe(T,F.x,F.y)},c=(T,F,H)=>{const P=ev(T,e),V=F.get(T.id);if(V){if(Xe(P,V.x,V.y),P.classList.add(`${Q}--pinned`),Qc(P,T),b(P,T),Zc(T)){const $=In();if($){const G=$.registerDropTarget({id:`desktop-mode-files-tile-${T.id}-reject`,element:P,accept:()=>!1,onDrop:()=>{}});m.set(T.id,G)}}return P}const R=H.get(T.id);if(R&&Xe(P,R.x,R.y),hv(P,T,e),Qc(P,T),b(P,T),T.file.type==="folder"){const $=parseInt(T.file.ref,10);if($>0){const G=In();if(G){const ne=mv(G,P,$);g.set(T.id,ne)}}}else if(Zc(T)){const $=In();if($){const G=$.registerDropTarget({id:`desktop-mode-files-tile-${T.id}-reject`,element:P,accept:()=>!1,onDrop:()=>{}});m.set(T.id,G)}}return P},u=T=>{const F=new Map;for(const R of n.querySelectorAll("[data-placement-id]")){const $=R.dataset.placementId??"",G=parseInt($,10);if($===""||Number.isNaN(G)&&$!=="-0")return!1;F.set(G,R)}const H=new Set;for(const R of T)H.add(R.id);for(const R of T){const $=F.get(R.id);if(!$)continue;if($.dataset.fileType!==R.file.type||$.dataset.fileRef!==R.file.ref||$.classList.contains(`${Q}--pinned`)!==Se(R))return!1}for(const[R,$]of F){if(H.has(R))continue;const G=g.get(R);if(G){try{G()}catch{}g.delete(R)}const ne=m.get(R);if(ne){try{ne()}catch{}m.delete(R)}$.remove()}const{pinnedSlots:P,displaced:V}=d(T);for(const R of T){const $=F.get(R.id);if($){l($,R,P,V);continue}n.appendChild(c(R,P,V))}return s!==null&&!n.querySelector(`[data-placement-id="${s}"]`)&&(s=null,r(null)),C("desktop-mode.files.grid-rendered",{folderId:e,count:T.length}),!0},p=T=>{const H=(T.placementsByFolder.get(e)??[]).slice().sort(($,G)=>{const ne=Se($)?0:1,z=Se(G)?0:1;return ne-z}),P=lv(H);if(P===o||(o=P,pv(H,n,t))||u(H))return;n.replaceChildren();for(const[,$]of g)try{$()}catch{}g.clear();for(const[,$]of m)try{$()}catch{}m.clear();const{pinnedSlots:V,displaced:R}=d(H);for(const $ of H)n.appendChild(c($,V,R));s!==null&&!n.querySelector(`[data-placement-id="${s}"]`)?(s=null,r(null)):s!==null&&n.querySelector(`[data-placement-id="${s}"]`)?.setAttribute("selected",""),C("desktop-mode.files.grid-rendered",{folderId:e,count:H.length})},f=[],g=new Map,m=new Map;let h=null,w=null;const x=T=>{if(h||T.payload.type!=="desktop-file")return;const F=document.createElement("div");F.className="desktop-mode-files-drop-preview",F.setAttribute("aria-hidden","true"),n.appendChild(F),h=F;const H=T.payload.ghost,P=H?.offsetX??0,V=H?.offsetY??0,$=T.payload.data?.placement?.id,G=(se,we)=>{const ke=n.getBoundingClientRect(),ae=Math.max(0,se-ke.left-P),qt=Math.max(0,we-ke.top-V),so=Y.getState().placementsByFolder.get(e)??[],rs=jo(so,$),io=gt(ae,qt,rs,t);F.style.transform=`translate3d(${io.x}px, ${io.y}px, 0)`},ne=T.payload.source.getBoundingClientRect();G(ne.left+P,ne.top+V);const z=se=>{G(se.clientX,se.clientY)};document.addEventListener("pointermove",z),w=z},D=()=>{w&&(document.removeEventListener("pointermove",w),w=null),h&&(h.remove(),h=null)},y={id:`desktop-mode-files-canvas-${e}`,element:t,accept:T=>{if(T.type!=="desktop-file"&&T.type!=="shortcut")return!1;if(e>0&&T.type==="desktop-file"){const F=T.data;if(F.placement.file?.type==="folder"){const H=parseInt(F.placement.file.ref,10);if(!Number.isNaN(H)&&Jc(H,e))return!1}}return!0},onEnter:T=>{t.setAttribute("data-files-drop-active",""),x(T)},onLeave:()=>{t.removeAttribute("data-files-drop-active"),D()},onDrop:(T,F)=>{t.removeAttribute("data-files-drop-active"),D();const H=n.getBoundingClientRect(),P=T.payload.ghost,V=P?.offsetX??0,R=P?.offsetY??0,$=Math.max(0,F.clientX-H.left-V),G=Math.max(0,F.clientY-H.top-R),ne=Y.getState().placementsByFolder.get(e)??[];if(T.payload.type==="desktop-file"){const z=T.payload.data,se=jo(ne,z.placement.id),we=gt($,G,se,t),ke={...z.placement,x:we.x,y:we.y,parentId:e};if(Y.upsertPlacement(ke),C("desktop-mode.files.tile-manually-placed",{folderId:e,placementId:z.placement.id}),Fi(z.placement)){const ae=Hi(z.placement);ae&&uv(ae,we.x,we.y);return}Pt(z.placement.id,{x:we.x,y:we.y,parentId:e},z.placement.updatedAtMs).then(ae=>{Y.upsertPlacement(ae,"remote")}).catch(ae=>{jc(ae)?Gc(ae):console.error("[desktop-mode] files: drag persist failed",ae),Y.upsertPlacement(z.placement)});return}if(T.payload.type==="shortcut"){const z=T.payload.data,se=jo(ne),we=Fc(se,t);Mt({parentId:e,type:z.kind,ref:z.ref,x:we.x,y:we.y}).then(ke=>{Y.upsertPlacement(ke),C("desktop-mode.files.shortcut-dropped",{folderId:e,placement:ke})}).catch(ke=>{console.error("[desktop-mode] shortcut drop failed:",ke)})}}},E=In();E&&f.push(E.registerDropTarget(y));const L=T=>{T.target instanceof Element&&T.target.closest(`.${Q}`)||a(null)};t.addEventListener("click",L);function b(T,F){T.addEventListener("click",H=>{H.stopPropagation(),a(F)})}p(Y.getState());const A=Y.subscribe(p);let I=()=>{};const _=new Promise(T=>{I=T});Y.getState().hydratedFolders.has(e)?queueMicrotask(I):Oe(e).then(T=>{Y.setFolderPlacements(e,T.placements)}).catch(T=>{console.error("[desktop-mode] files: failed to hydrate folder",e,T)}).finally(()=>{I()});const k=()=>{const T=t.clientWidth>0?t.clientWidth:4*it;return Math.max(1,Math.floor((T-Le)/it))},O=(T,F)=>{const H=T.slice();switch(F){case"name-asc":H.sort((P,V)=>P.file.title.localeCompare(V.file.title));break;case"name-desc":H.sort((P,V)=>V.file.title.localeCompare(P.file.title));break;case"date-asc":H.sort((P,V)=>P.updatedAtMs-V.updatedAtMs);break;case"date-desc":H.sort((P,V)=>V.updatedAtMs-P.updatedAtMs);break}return H},M=T=>{const F=Y.getState().placementsByFolder.get(e);if(!F||F.length===0)return;const H=F.filter(z=>Se(z)),P=F.filter(z=>!Se(z)),V=O(P,T),R=k(),$=new Set;for(let z=0;z<H.length;z+=1)$.add(ve(0,z));let G=0;const ne=()=>{for(;;){const z=Math.floor(G/R),se=G%R;if(G+=1,!$.has(ve(se,z)))return{col:se,row:z}}};V.forEach((z,se)=>{const we=ne(),ke=Le+we.col*it,ae=Le+we.row*xn,qt={...z,x:ke,y:ae,sortOrder:se};Y.upsertPlacement(qt),!Fi(z)&&Pt(z.id,{x:ke,y:ae,sortOrder:se}).catch(so=>{console.error("[desktop-mode] files: sort persist failed",so)})})},X=()=>{const T=Y.getState().placementsByFolder.get(e);if(!T||T.length===0)return;const F=t.clientWidth>0?t.clientWidth:1/0;if(!T.some(z=>z.x+it>F))return;const P=k(),V=T.filter(z=>Se(z)),R=T.filter(z=>!Se(z)),$=new Set;for(let z=0;z<V.length;z+=1)$.add(ve(0,z));let G=0;const ne=()=>{for(;;){const z=Math.floor(G/P),se=G%P;if(G+=1,!$.has(ve(se,z)))return{col:se,row:z}}};for(const z of R){const se=ne(),we=Le+se.col*it,ke=Le+se.row*xn,ae=n.querySelector(`[data-placement-id="${z.id}"]`);ae&&Xe(ae,we,ke)}};let Z=t.clientWidth,te=null;return typeof ResizeObserver<"u"&&(te=new ResizeObserver(()=>{const T=t.clientWidth;T!==Z&&(Z=T,X())}),te.observe(t)),{host:t,folderId:e,onSelectionChange(T){return i.add(T),()=>{i.delete(T)}},sort:M,reflow:X,hydrated:_,dispose(){A(),te?.disconnect(),te=null;for(const T of f)try{T()}catch{}f.length=0;for(const T of g.values())try{T()}catch{}g.clear();for(const T of m.values())try{T()}catch{}m.clear(),t.removeEventListener("click",L),i.clear(),n.remove()}}}function lv(t){if(t.length===0)return"0";const e=[];for(const n of t)e.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 e.join("|")}function Se(t){return!!t.file.pinned}function Hi(t){const e=t.meta;if(!e||typeof e!="object")return null;const n=e.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function Fi(t){return t.id<=0||Hi(t)!==null}const cv="desktop-mode-recycle-bin";function Zc(t){return!(t.file?.type==="folder"||t.file?.ref===cv)}function jo(t,e){const n=t.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(!(e!==void 0&&i.id===e))if(Se(i))o.add(ve(0,s)),s+=1;else{const r=An(i.x,i.y);o.add(ve(r.col,r.row))}return o}function Jc(t,e){if(e<=0||t<=0)return!1;if(t===e)return!0;const n=new Map,o=Y.getState();for(const a of o.placementsByFolder.values())for(const d of a){if(d.file?.type!=="folder")continue;const l=parseInt(d.file.ref,10);Number.isNaN(l)||l<=0||n.has(l)||n.set(l,d.parentId)}const s=new Set;let i=e,r=256;for(;i>0&&r-- >0;){if(i===t||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function uv(t,e,n){const o=window.wp?.desktop;if(!o?.getOsSettings||!o?.updateOsSettings)return;const s=o.getOsSettings().dockPromotedPositions??{};o.updateOsSettings({dockPromotedPositions:{...s,[t]:{x:e,y:n}}})}function pv(t,e,n){const o=Array.from(e.querySelectorAll("[data-placement-id]"));if(o.length!==t.length)return!1;const s=new Map;for(const l of o){const c=l.dataset.placementId??"",u=parseInt(c,10);if(c===""||Number.isNaN(u)&&c!=="-0")return!1;s.set(u,l)}for(const l of t){const c=s.get(l.id);if(!c||c.dataset.fileType!==l.file.type||c.dataset.fileRef!==l.file.ref||c.classList.contains(`${Q}--pinned`)!==Se(l))return!1}const i=new Map,r=new Set;let a=0;for(const l of t){if(!Se(l))continue;const c=Ut(0,a);i.set(l.id,{x:c.x,y:c.y}),r.add(ve(c.col,c.row)),a+=1}const d=new Map;for(const l of t){if(i.has(l.id))continue;const c=An(l.x,l.y),u=ve(c.col,c.row);if(!r.has(u)){r.add(u);continue}const p=gt(l.x,l.y,r,n);r.add(ve(p.col,p.row)),d.set(l.id,{x:p.x,y:p.y})}for(const l of t){const c=s.get(l.id);if(!c)continue;const u=i.get(l.id),p=d.get(l.id);u?Xe(c,u.x,u.y):p?Xe(c,p.x,p.y):Xe(c,l.x,l.y)}return!0}function fv(t){const e=window.wp?.desktop;if(!e?.getOsSettings||!e?.updateOsSettings)return;const o={...e.getOsSettings().itemVisibility??{},[t]:"dock"};e.updateOsSettings({itemVisibility:o})}function mv(t,e,n,o){const s={id:`desktop-mode-files-folder-${n}-tile-${e.dataset.placementId??"?"}`,element:e,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||Fi(r.placement))return!1;if(r.placement.file.type==="folder"){const a=parseInt(r.placement.file.ref,10);if(!Number.isNaN(a)&&Jc(a,n))return!1}}return!0},onEnter:()=>{e.classList.add(`${Q}--drop-target`)},onLeave:()=>{e.classList.remove(`${Q}--drop-target`)},onDrop:i=>{if(e.classList.remove(`${Q}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a={...r.placement,parentId:n};Y.upsertPlacement(a),Pt(r.placement.id,{parentId:n},r.placement.updatedAtMs).then(d=>{Y.upsertPlacement(d,"remote")}).catch(d=>{jc(d)?Gc(d):console.error("[desktop-mode] files: move-into-folder persist failed",d),Y.upsertPlacement(r.placement)});return}if(i.payload.type==="shortcut"){const r=i.payload.data,a=Y.getState().placementsByFolder.get(n)??[],d=Fc(jo(a));Mt({parentId:n,type:r.kind,ref:r.ref,x:d.x,y:d.y}).then(l=>{Y.upsertPlacement(l),C("desktop-mode.files.shortcut-dropped",{folderId:n,placement:l})}).catch(l=>{console.error("[desktop-mode] shortcut drop into folder failed:",l)})}}};return t.registerDropTarget(s)}function hv(t,e,n){t.addEventListener("pointerdown",o=>{if(o.button!==0)return;const s=In();if(!s)return;const r=Y.getState().placementsByFolder.get(n)?.find(a=>a.id===e.id)??e;parseFloat(t.style.left)||r.x,parseFloat(t.style.top)||r.y,s.start({payload:{type:"desktop-file",source:t,data:{placement:r,sourceFolderId:n,bridgePayload:av(r)},ghost:{offsetX:o.clientX-t.getBoundingClientRect().left,offsetY:o.clientY-t.getBoundingClientRect().top}},origin:o})})}function Qc(t,e){t.addEventListener("contextmenu",n=>{n.preventDefault(),n.stopPropagation();const o=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,onClick:()=>{const i=Bo(e.file);Ai(i)}}];if(e.file.type==="post"&&o.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>{const i=parseInt(e.file.ref,10);if(!i)return;const r=window.wp?.desktop?.myWordpress,d=(typeof e.file.postType=="string"?e.file.postType:"post")==="page"?"pages":"posts";r?.openDetail({entityId:d,postId:i,postTitle:e.file.title||`#${i}`})}}),e.file.type==="folder")o.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>{const i=parseInt(e.file.ref,10);i&&Bi({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:e.file.title,onSubmit:async r=>{const a=r.trim();if(!a||a===e.file.title)return;const d=e.file.title,l={...e,file:{...e.file,title:a}};Y.upsertPlacement(l);try{const c=Y.getState().folders.get(i)?.updatedAtMs??0,u=await Ic(i,{name:a},c);Y.upsertFolder(u);const p=await Oe(e.parentId);Y.setFolderPlacements(e.parentId,p.placements)}catch(c){console.error("[desktop-mode] rename folder failed:",c),Y.upsertPlacement({...e,file:{...e.file,title:d}})}}})}}),e.canTrash!==!1&&o.push({id:"delete-folder",label:"Move folder to Trash",icon:"dashicons-trash",sort:90,danger:!0,onClick:()=>Yc(e)});else{const i=Hi(e),r=e.file.type==="shortcut";if(i||r){const a=i??e.file.ref;o.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,onClick:()=>fv(a)})}else e.canTrash!==!1&&o.push({id:"remove",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,onClick:()=>Kc(e)})}nv({x:n.clientX,y:n.clientY},{placement:e,items:o})})}const Bt="desktop-mode-folder-status-bar";function wv(t,e){const n=document.createElement("div");n.className=Bt,n.setAttribute("role","status"),n.dataset.folderId=String(e),t.appendChild(n);const o=()=>{const i=wt().placementsByFolder.get(e)??[],r=i.filter(c=>c.file.type==="folder").length,a=i.length-r,d={folderId:e,totals:{files:a,folders:r,total:i.length}},l=gv(d);yv(n,l)};o();const s=Mi(()=>o());return{dispose(){s(),n.remove()}}}function gv(t){const{folders:e,files:n}=t.totals,o=[{id:"count",label:tu(n,"file","files")+(e>0?`, ${tu(e,"folder","folders")}`:""),align:"start",sort:10}],s=q("desktop-mode.files.folder-window.status-bar",o,t);return Array.isArray(s)?s:o}function yv(t,e){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=e.filter(i=>(i.align??"start")==="start").sort(n),s=e.filter(i=>i.align==="end").sort(n);t.replaceChildren(),t.appendChild(eu("start",o)),t.appendChild(eu("end",s))}function eu(t,e){const n=document.createElement("div");n.className=`${Bt}__cluster ${Bt}__cluster--${t}`;for(const o of e)n.appendChild(bv(o));return n}function bv(t){const e=typeof t.onClick=="function",n=document.createElement(e?"button":"span");if(n.className=`${Bt}__segment`,n.dataset.segmentId=t.id,e&&(n.type="button",n.addEventListener("click",s=>t.onClick(s))),t.icon){const s=document.createElement("span");s.className=`${Bt}__icon dashicons ${t.icon.replace(/[^a-zA-Z0-9_-]/g,"")}`,s.setAttribute("aria-hidden","true"),n.appendChild(s)}const o=document.createElement("span");return o.className=`${Bt}__label`,o.textContent=t.label,n.appendChild(o),n}function tu(t,e,n){return`${t} ${t===1?e:n}`}const Go="desktop-mode-icon-canvas-menu";let Ln=null,qo=null,zi=null,Tn=null,Nn=null;function vv(t,e){e.openOnBackgroundClick;const n=i=>{kv(i.target)||nu(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(zi===t&&Ln){yt();return}const a=_v(e),d=q("desktop-mode.icon-canvas.menu",a,e.scope),l=Array.isArray(d)?d:a,c=++o;Yt(()=>c===o,()=>Ev(l,{x:i,y:r},t))};return t.addEventListener("contextmenu",n),{dispose:()=>{t.removeEventListener("contextmenu",n),yt()}}}function kv(t){return t instanceof Element?t.closest(".desktop-mode-file-tile")!==null:!1}function nu(t){return t instanceof Element?t.closest(`.${Go}`)!==null:!1}function _v(t){const n=[{id:"sort-by",label:N("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:N("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>t.onSort("name-asc")},{id:"sort-name-desc",label:N("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>t.onSort("name-desc")},{id:"sort-date-desc",label:N("Newest first","desktop-mode"),sort:30,onClick:()=>t.onSort("date-desc")},{id:"sort-date-asc",label:N("Oldest first","desktop-mode"),sort:40,onClick:()=>t.onSort("date-asc")}]}];return Array.isArray(t.extraItems)&&n.push(...t.extraItems),n}function ou(t){return t.slice().sort((e,n)=>{const o=typeof e.sort=="number"?e.sort:100,s=typeof n.sort=="number"?n.sort:100;return o!==s?o-s:e.label.localeCompare(n.label)})}function Ev(t,e,n){if(yt(),t.length===0)return;zi=n;const o=ou(t),s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(Go),s.style.left=`${e.x}px`,s.style.top=`${e.y}px`;const i=new Map;for(const r of o){i.set(r.id,r);const a=su(s,r);Vo(r)&&a.addEventListener("mouseenter",()=>{iu(r,a)})}s.addEventListener("wpd-context-menu-pick",r=>{const a=r.detail,d=i.get(a.id);if(d){if(Vo(d)){r.stopPropagation();const l=s.querySelector(`[data-menu-item-id="${d.id}"]`);l&&iu(d,l);return}yt(),d.onClick?.()}}),document.body.appendChild(s),Ln=s,Cv(s),queueMicrotask(()=>{Tn=r=>{nu(r.target)||yt()},Nn=r=>{r.key==="Escape"&&yt()},document.addEventListener("mousedown",Tn),document.addEventListener("keydown",Nn)})}function su(t,e){const n=document.createElement("wpd-context-menu-option");return n.dataset.menuItemId=e.id,n.setAttribute("value",e.id),e.heading&&n.setAttribute("heading",""),e.disabled&&n.setAttribute("disabled",""),e.icon&&n.setAttribute("icon",xv(e.icon)),Vo(e)&&n.setAttribute("has-children",""),n.textContent=e.label,t.appendChild(n),n}function iu(t,e){if(ru(),!Vo(t))return;const n=document.createElement("wpd-context-menu");n.setAttribute("open",""),n.classList.add(Go,`${Go}--flyout`);const o=new Map;for(const s of ou(t.children??[]))o.set(s.id,s),su(n,s);n.addEventListener("wpd-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),yt(),r.onClick?.())}),document.body.appendChild(n),qo=n,Sv(n,e)}function Sv(t,e){const n=e.getBoundingClientRect();t.style.position="fixed",t.style.left=`${n.right}px`,t.style.top=`${n.top}px`;const o=t.getBoundingClientRect();o.right>window.innerWidth&&(t.style.left=`${Math.max(0,n.left-o.width)}px`),o.bottom>window.innerHeight&&(t.style.top=`${Math.max(0,window.innerHeight-o.height-8)}px`)}function Cv(t){const e=t.getBoundingClientRect();e.right>window.innerWidth&&(t.style.left=`${Math.max(0,window.innerWidth-e.width-8)}px`),e.bottom>window.innerHeight&&(t.style.top=`${Math.max(0,window.innerHeight-e.height-8)}px`)}function Vo(t){return Array.isArray(t.children)&&t.children.length>0}function ru(){qo&&(qo.remove(),qo=null)}function yt(){ru(),Ln&&(Ln.remove(),Ln=null),zi=null,Tn&&(document.removeEventListener("mousedown",Tn),Tn=null),Nn&&(document.removeEventListener("keydown",Nn),Nn=null)}function xv(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}const bt="desktop-mode-breadcrumbs";function Av(t,e,n={}){if(t.replaceChildren(),t.classList.add(bt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${bt}__back`,s.setAttribute("aria-label",N("Back","desktop-mode")),s.title=N("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()}),t.appendChild(s)}const o=document.createElement("nav");o.className=`${bt}__crumbs`,o.setAttribute("aria-label",N("Breadcrumb","desktop-mode")),e.forEach((s,i)=>{if(i>0){const d=document.createElement("span");d.className=`${bt}__sep`,d.setAttribute("aria-hidden","true"),d.textContent="›",o.appendChild(d)}if(!s.onClick){const d=document.createElement("span");d.className=`${bt}__crumb ${bt}__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=`${bt}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),t.appendChild(o)}async function Dn(t,e={}){const n=await je(t,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":Iv(),...e.headers??{}},...e});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function Iv(){return window.wp?.desktop?.config?.restNonce??""}function Lv(){const t=window.wp?.desktop?.config;return t?.restUrl?t.restUrl.endsWith("/")?t.restUrl:t.restUrl+"/":`${window.location.origin}/wp-json/`}function On(t){return sn(Lv(),t)}function Tv(t,e){const n=q("desktop-mode.files.preview",null,t);if(n instanceof HTMLElement){e.replaceChildren(n);return}if(t.accessGated){e.replaceChildren(Nv(t));return}e.replaceChildren(Hv()),Dv(t).then(o=>{e.replaceChildren(o)}).catch(o=>{e.replaceChildren(Fv(o))})}function Nv(t){const e=document.createElement("div");e.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),e.appendChild(n);const s=document.createElement("h2");s.className="desktop-mode-files__access-gated-title",s.textContent="No permission to view",e.appendChild(s);const i=document.createElement("p");i.className="desktop-mode-files__access-gated-sub";const r=t.file.title||t.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.`,e.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.",e.appendChild(a),e}async function Dv(t){const e=t.file;switch(e.type){case"post":return Ov(e.ref,e);case"folder":return Wv(e);case"shortcut":return Uv(e);case"attachment":return $v(e.ref,e);case"user":return Rv(e.ref,e);case"term":return Mv(e);case"comment":return Pv(e.ref,e);case"bookmark":return Bv(e);default:return We(e)}}async function Ov(t,e){const n=parseInt(t,10);if(!n)return We(e);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await Dn(On(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return We(e);const s=Ze(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=Ko(o.title.rendered)||e.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="desktop-mode-my-wordpress__article-meta";const a=[];if(a.push(au(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 l=window.wp?.desktop?.myWordpress;if(l){const u=document.createElement("wpd-button");u.setAttribute("variant","secondary"),u.textContent=N("Explore details","desktop-mode"),u.title=N("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),u.addEventListener("click",()=>{const p=typeof e.postType=="string"?e.postType:"post";l.openDetail({entityId:p==="page"?"pages":"posts",postId:n,postTitle:Ko(o.title.rendered)||`#${n}`})}),d.appendChild(u)}const c=document.createElement("wpd-button");return c.setAttribute("variant","primary"),c.textContent=N("Open in editor","desktop-mode"),c.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 e.postType=="string"?e.postType:"post")==="page"?"pages":"posts";f?.open({id:`${m}-edit-${n}`,url:p,title:Ko(o.title.rendered),icon:e.icon})}),d.appendChild(c),s.appendChild(d),s}async function Rv(t,e){const n=parseInt(t,10);if(!n)return We(e);let o=null;try{o=await Dn(On(`desktop-mode/v1/user-stats/${n}`))}catch{return We(e)}const s=Ze("desktop-mode-my-wordpress__user"),i=document.createElement("header");if(i.className="desktop-mode-my-wordpress__user-header",o.profile.avatarUrl){const l=document.createElement("img");l.className="desktop-mode-my-wordpress__user-avatar",l.src=o.profile.avatarUrl,l.alt="",i.appendChild(l)}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||e.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const l=document.createElement("div");l.className="desktop-mode-my-wordpress__user-roles";for(const c of o.profile.roleLabels){const u=document.createElement("span");u.className="desktop-mode-my-wordpress__user-role",u.textContent=c,l.appendChild(u)}r.appendChild(l)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const l=document.createElement("div");l.className="desktop-mode-my-wordpress__user-bio",l.textContent=o.profile.description,s.appendChild(l)}const d=document.createElement("div");return d.className="desktop-mode-my-wordpress__user-stats",d.appendChild(Ht(o.counts.posts.total.toLocaleString(),N("Posts","desktop-mode"))),d.appendChild(Ht(o.counts.pages.total.toLocaleString(),N("Pages","desktop-mode"))),d.appendChild(Ht(o.counts.commentsReceived.toLocaleString(),N("Comments received","desktop-mode"))),s.appendChild(d),s}async function Mv(t){const e=parseInt(t.ref,10),n=typeof t.taxonomy=="string"&&t.taxonomy?t.taxonomy:"category";if(!e)return We(t);let o=null;try{o=await Dn(On(`desktop-mode/v1/term-stats/${n}/${e}`))}catch{return We(t)}const s=Ze(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=o.profile.name||t.title||`#${e}`,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(Ht(o.counts.posts.total.toLocaleString(),N("Posts","desktop-mode"))),a.appendChild(Ht(o.counts.commentsReceived.toLocaleString(),N("Comments","desktop-mode"))),a.appendChild(Ht(o.counts.distinctAuthors.toLocaleString(),N("Authors","desktop-mode"))),s.appendChild(a),s}async function Pv(t,e){const n=parseInt(t,10);if(!n)return We(e);let o=null;try{o=await Dn(On(`desktop-mode/v1/comment-stats/${n}`))}catch{return We(e)}const s=Ze(),i=document.createElement("header");if(i.className="desktop-mode-my-wordpress__user-header",o.author.avatarUrl){const c=document.createElement("img");c.className="desktop-mode-my-wordpress__user-avatar",c.src=o.author.avatarUrl,c.alt="",i.appendChild(c)}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=`${au(o.comment.date)} · ${o.comment.status}`,r.appendChild(d),i.appendChild(r),s.appendChild(i);const l=document.createElement("div");if(l.className="desktop-mode-my-wordpress__article-content",l.innerHTML=o.comment.rendered,s.appendChild(l),o.post){const c=document.createElement("div");c.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,c.appendChild(u),s.appendChild(c)}return s}async function $v(t,e){const n=parseInt(t,10);if(!n)return We(e);let o=null;try{o=await Dn(On(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return We(e)}const s=Ze(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=Ko(o.title.rendered)||e.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 Wv(t){const e=Ze(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=t.title||N("(folder)","desktop-mode"),e.appendChild(n);const o=document.createElement("p");return o.className="desktop-mode-my-wordpress__article-meta",o.textContent=N("Double-click to open.","desktop-mode"),e.appendChild(o),e}function Uv(t){const e=Ze(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=t.title||N("Shortcut","desktop-mode"),e.appendChild(n);const o=document.createElement("p");return o.className="desktop-mode-my-wordpress__article-meta",o.textContent=N("Plugin shortcut. Double-click to open.","desktop-mode"),e.appendChild(o),e}function Bv(t){const e=Ze(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=t.title||N("Bookmark","desktop-mode"),e.appendChild(n);const o=typeof t.url=="string"?t.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",e.appendChild(s)}return e}function We(t){const e=Ze(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=t.title||t.type,e.appendChild(n);const o=document.createElement("p");if(o.className="desktop-mode-my-wordpress__article-meta",o.textContent=oe(N("Type: %s","desktop-mode"),t.type),e.appendChild(o),!t.exists){const s=document.createElement("p");s.className="desktop-mode-my-wordpress__article-meta",s.textContent=N("The underlying entity is no longer available.","desktop-mode"),e.appendChild(s)}return e}function Ze(t=""){const e=document.createElement("article");return e.className="desktop-mode-my-wordpress__article"+(t?" "+t:""),e}function Ht(t,e){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=t,n.appendChild(o);const s=document.createElement("span");return s.className="desktop-mode-my-wordpress__user-stat-label",s.textContent=e,n.appendChild(s),n}function Hv(){const t=document.createElement("div");t.className="desktop-mode-my-wordpress__preview-loading";const e=document.createElement("wpd-spinner");return t.appendChild(e),t}function Fv(t){const e=document.createElement("div");return e.className="desktop-mode-my-wordpress__error",e.textContent=t instanceof Error?t.message:N("Unknown error.","desktop-mode"),e}function Ko(t){const e=document.createElement("div");return e.innerHTML=t,(e.textContent??"").trim()}function au(t){if(!t)return"";try{return new Date(t).toLocaleString()}catch{return t}}function du(){const t=document.createElement("div");return t.className="desktop-mode-my-wordpress__preview-empty",t.textContent=N("Select an item to preview it here.","desktop-mode"),t}const Yo="desktop-mode-embed-",zv=800,jv=600,ji=360,Gi=240,Xo=16,qi=new Map;function Gv(t,e){const n=t.ref();if(!n)return;const o=window.wp?.desktop?.windowManager;if(!o)return;const s=e?.placement,i=s?.meta??null,r=s?`${Yo}${s.id}`:`${Yo}anon-${Yv(n)}`,a=i?.name?.trim()??"",d=a!==""?a:t.title(),l={id:r,baseId:r,url:n,title:d,icon:t.icon(),minWidth:ji,minHeight:Gi},c=i?.window,u=document.getElementById("desktop-mode-area"),p=u?.clientWidth??window.innerWidth,f=u?.clientHeight??window.innerHeight;if(c&&Number.isFinite(c.width)&&Number.isFinite(c.height)){const{x:g,y:m,width:h,height:w}=Kv(c,p,f);l.x=g,l.y=m,l.width=h,l.height=w}else l.width=Math.min(zv,Math.max(ji,p-Xo*2)),l.height=Math.min(jv,Math.max(Gi,f-Xo*2));s&&c&&qi.set(r,{...c}),o.open(l)}let lu=!1;function qv(){if(lu)return;lu=!0;const t=e=>{const o=e?.windowId;if(!o||!o.startsWith(Yo))return;const s=o.slice(Yo.length),i=parseInt(s,10);if(!i)return;const d=window.wp?.desktop?.windowManager?.getById?.(o)?.element;if(!d)return;const l={x:d.offsetLeft,y:d.offsetTop,width:d.offsetWidth,height:d.offsetHeight},c=qi.get(o);c&&c.x===l.x&&c.y===l.y&&c.width===l.width&&c.height===l.height||(qi.set(o,l),Vv(i,l))};j(v.WINDOW_DRAG_END,"desktop-mode-embed-persist",t),j(v.WINDOW_RESIZE_END,"desktop-mode-embed-persist",t)}async function Vv(t,e){try{const i={...(await Oe(0)).placements.find(r=>r.id===t)?.meta??{},window:e};await Pt(t,{meta:i})}catch(n){console.warn("[desktop-mode] embed window persist failed:",n)}}function Kv(t,e,n){const o=Math.max(ji,Math.min(t.width,e-Xo)),s=Math.max(Gi,Math.min(t.height,n-Xo)),i=Math.max(0,Math.min(t.x,Math.max(0,e-o))),r=Math.max(0,Math.min(t.y,Math.max(0,n-s)));return{x:i,y:r,width:o,height:s}}function Yv(t){let e=0;for(let n=0;n<t.length;n++)e=(Math.imul(e,31)+t.charCodeAt(n))%2147483647;return Math.abs(e).toString(36)}function Rn(){const e=window.wp?.desktop?.config?.adminUrl??"/wp-admin/";return e.endsWith("/")?e:`${e}/`}function Xv(){$e({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Rn()}post.php?post=${encodeURIComponent(t.ref())}&action=edit`}}),$e({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Rn()}post.php?post=${encodeURIComponent(t.ref())}&action=edit`}}),$e({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Rn()}user-edit.php?user_id=${encodeURIComponent(t.ref())}`}}),$e({id:"wp-term-editor",label:"Term editor",types:["term"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>{const[e,n]=t.ref().split(":");return`${Rn()}term.php?taxonomy=${encodeURIComponent(e??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),$e({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:t=>`${Rn()}comment.php?action=editcomment&c=${encodeURIComponent(t.ref())}`}}),$e({id:"desktop-mode-folder-window",label:"Open folder",types:["folder"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=parseInt(t.ref(),10);if(!e)return;const n=window.wp?.desktop?.windowManager;if(!n)return;const o=`desktop-mode-folder-${e}`,s=Y.getState().folders.get(e),i=Number(window.desktopModeConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=t.title(),d=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${e}`,title:d,icon:t.icon(),native:!0,render:l=>{l.replaceChildren(),l.classList.add("desktop-mode-folder-window");const c=[{folderId:e,title:t.title()}];let u=null;const p=document.createElement("header");l.appendChild(p);const f=document.createElement("div");f.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",l.appendChild(f);const g=()=>{const h=c.map((w,x)=>x===c.length-1?{label:w.title}:{label:w.title,onClick:()=>{c.length=x+1,m()}});Av(p,h,{onBack:()=>{c.length<=1||(c.pop(),m())},backDisabled:c.length<=1})},m=()=>{u?.(),u=null,f.replaceChildren();const h=document.createElement("div");h.className="desktop-mode-folder-window__split",f.appendChild(h);const w=document.createElement("div");w.className="desktop-mode-folder-window__layer",h.appendChild(w);const x=document.createElement("div");x.className="desktop-mode-folder-window__preview",x.appendChild(du()),h.appendChild(x);const D=c[c.length-1],y=Xc(w,D.folderId),E=y.onSelectionChange(I=>{if(!I){x.replaceChildren(du());return}Tv(I,x)}),L=I=>{if(!(I.target instanceof Element))return;const _=I.target.closest(".desktop-mode-file-tile");if(!_||_.dataset.fileType!=="folder")return;const k=parseInt(_.dataset.fileRef??"",10);if(!k)return;I.preventDefault(),I.stopPropagation();const O=_.querySelector(".desktop-mode-file-tile__label")?.textContent??`#${k}`;c.push({folderId:k,title:O}),m()};w.addEventListener("dblclick",L,!0);const b=vv(w,{scope:`desktop-mode-folder:${D.folderId}`,onSort:I=>y.sort(I),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{Bi({onSubmit:async I=>{const _=await Ni({name:I}),k=Y.getState().placementsByFolder.get(D.folderId)??[],O=zc(k),M=gt(Le,Le,O,w),X=await Mt({type:"folder",ref:String(_.id),parentId:D.folderId,x:M.x,y:M.y});Y.upsertFolder(_),Y.upsertPlacement(X)}})}}]}),A=wv(f,D.folderId);u=()=>{E(),b.dispose(),A.dispose(),w.removeEventListener("dblclick",L,!0),y.dispose()},g()};m()},width:720,height:480,minWidth:360,minHeight:240})}}}),$e({id:"desktop-mode-shortcut-opener",label:"Open shortcut",types:["shortcut"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=t.shape,n=window.wp?.desktop;if(n){if(e.shortcutWindow&&n.openWindow){n.openWindow(e.shortcutWindow);return}if(e.shortcutUrl&&n.windowManager)try{const o=new URL(e.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}const s=`desktop-icon-${t.ref()}`;n.windowManager.open({id:s,baseId:s,url:o.toString(),title:t.title(),icon:t.icon()})}catch{}}}}}),$e({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=t.ref();e&&window.open(e,"_blank","noopener,noreferrer")}}}),$e({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:t=>{const e=t.ref();e&&window.open(e,"_blank","noopener,noreferrer")}}}),$e({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(t,e)=>{Gv(t,e)}}})}const Zv="desktop-mode-file-associations";function Jv(){fd({id:Zv,label:"File Associations",order:50,render(t){Qv(t)}})}function Qv(t){t.replaceChildren();const e=vc();if(e.length===0){const i=document.createElement("p");i.className="desktop-mode-file-associations__empty",i.textContent="No file types are registered.",t.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.",t.appendChild(n);const o=Ei(),s=document.createElement("div");s.className="desktop-mode-file-associations__list",s.setAttribute("role","list");for(const i of e)s.appendChild(ek(i.type,i.label,o));t.appendChild(s)}function ek(t,e,n){const o=document.createElement("div");o.className="desktop-mode-file-associations__row",o.setAttribute("role","listitem"),o.dataset.fileType=t;const s=document.createElement("label");s.className="desktop-mode-file-associations__label",s.textContent=e,o.appendChild(s);const i=Si(t);if(i.length===0){const l=document.createElement("span");return l.className="desktop-mode-file-associations__none",l.textContent="No app available",o.appendChild(l),o}const r=Ci(t),a=n[t]??r?.id??"",d=document.createElement("wpd-select");d.setAttribute("value",a),d.setAttribute("aria-label",`Default app for ${e}`),d.className="desktop-mode-file-associations__select",s.htmlFor=`assoc-${t}`,d.id=`assoc-${t}`;for(const l of i){const c=document.createElement("wpd-option");c.setAttribute("value",l.id),c.textContent=l.isDefault?`${l.label} (default)`:l.label,d.appendChild(c)}return d.addEventListener("wpd-pick",l=>{const c=l.detail?.value;if(!c)return;const u={...Ei(),[t]:c};_c(u),Tc(u).catch(p=>{console.error("[desktop-mode] saveAssociations failed:",p)})}),o.appendChild(d),o}let Vi=null;function Je(){return Vi||(Vi=ce("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set}))),Vi}function tk(t,e){const n=Je();n.state.byFolder.set(t,e),n.notify()}function nk(t){if(!t||typeof t.folderId!="number")return;const e=Je(),o=(e.state.byFolder.get(t.folderId)??[]).filter(s=>s.id!==t.id);o.push(t),e.state.byFolder.set(t.folderId,o),e.notify()}function ok(t,e){const n=Je(),o=n.state.byFolder.get(t)??[];n.state.byFolder.set(t,o.filter(s=>s.id!==e)),n.notify()}function sk(t,e){return t.id===e.id&&t.folderId===e.folderId&&t.capability===e.capability&&t.invitedAtMs===e.invitedAtMs&&t.folderName===e.folderName&&t.ownerName===e.ownerName}function cu(t){const e=Je(),n=new Map(e.state.pending.map(s=>[s.id,s]));let o=!1;for(const s of t){if(e.state.deniedFolders.has(s.folderId))continue;const i=n.get(s.id);if(i){if(sk(i,s))continue;e.state.pending=e.state.pending.map(r=>r.id===s.id?s:r)}else e.state.pending.push(s);s.invitedAtMs>e.state.sharesVersion&&(e.state.sharesVersion=s.invitedAtMs),o=!0}o&&e.notify()}function uu(t,e={}){const n=Je();n.state.pending=n.state.pending.filter(o=>o.id!==t),e.denied&&typeof e.folderId=="number"&&n.state.deniedFolders.add(e.folderId),n.notify()}const ik=me`: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}`,pu='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',qn=class qn extends ue{constructor(){super(...arguments),this._prevFocus=null,this._onKey=e=>{if(e.key==="Escape"&&!this.hasAttribute("mandatory")){e.preventDefault(),this._cancel();return}if(e.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=e.composedPath()[0]||r;e.shiftKey&&a===o?(e.preventDefault(),s.focus()):!e.shiftKey&&a===s&&(e.preventDefault(),o.focus())}},this._onBackdrop=e=>{if(this.hasAttribute("mandatory"))return;const n=e.composedPath();(n.length>0?n[0]:e.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(e,n,o){if(super.attributeChangedCallback?.(e,n,o),e==="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 e=this.shadowRoot;if(!e)return[];const n=Array.from(this.querySelectorAll(pu)),o=Array.from(e.querySelectorAll(pu));return[...n,...o].filter(s=>s.offsetParent!==null||s.tagName==="BUTTON")}_focusFirst(){const e=this._focusables();e.length>0?e[0].focus():this.shadowRoot?.querySelector(".dialog")?.focus?.()}_cancel(){const e=new CustomEvent("wpd-modal-cancel",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(e)&&this.hideModal()}render(){const e=this.getAttribute("title")??"",n=this.hasAttribute("mandatory");return B` |
| 58 |
<div class="dialog" tabindex="-1"> |
| 59 |
${e?B` |
| 60 |
<div class="header"> |
| 61 |
<h2 class="title">${e}</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 |
`}};qn.props=["open","title","size","mandatory"],qn.styles=[ik],qn.help=void 0;let Ki=qn;fe("wpd-modal",Ki);const rk=me`: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}`,Vn=class Vn extends ue{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=e=>{const n=e.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=e=>{this.emit("wpd-user-pick",{user:e}),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 e=this.getAttribute("endpoint");return e||window.desktopModeConfig?.filesUsersSearchUrl||""}_scheduleSearch(e){this._timer&&clearTimeout(this._timer),this._phase="loading",this._open=!0,this._positionDropdown(),this.requestUpdate(),this._timer=setTimeout(()=>this._runSearch(e),200)}async _runSearch(e){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(e)+"&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 e=this.shadowRoot?.querySelector(".input");if(!e)return;const n=e.getBoundingClientRect(),o=n.bottom+4,s=n.left,i=n.width,a=window.innerHeight-n.bottom,d=n.top,l=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-l}px`,`width:${i}px`,`max-height:${l}px`].join(";"):this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${o}px`,`width:${i}px`,`max-height:${l}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 e=this._query?"No matches.":"No users available.";return B`<div class="empty">${e}</div>`}return this._results.map(e=>B` |
| 81 |
<button |
| 82 |
type="button" |
| 83 |
class="item" |
| 84 |
role="option" |
| 85 |
@mousedown=${n=>n.preventDefault()} |
| 86 |
@click=${()=>this._pick(e)} |
| 87 |
> |
| 88 |
<img class="avatar" src=${e.avatarUrl} alt="" /> |
| 89 |
<div> |
| 90 |
<div class="name">${e.name}</div> |
| 91 |
<div class="slug">${e.slug}</div> |
| 92 |
</div> |
| 93 |
</button> |
| 94 |
`)}render(){const e=this.getAttribute("placeholder")||"Search users…";return B` |
| 95 |
<input |
| 96 |
class="input" |
| 97 |
type="search" |
| 98 |
placeholder=${e} |
| 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 |
`}};Vn.props=["placeholder","exclude","endpoint"],Vn.styles=[rk],Vn.help=void 0;let Yi=Vn;fe("wpd-user-search",Yi);const ak=me`: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}`,Kn=class Kn extends ue{constructor(){super(...arguments),this._onToggle=e=>{const n=!this._selectedSet().has(e);this.emit("wpd-role-toggle",{slug:e,selected:n})}}_selectedSet(){const e=this.getAttribute("selected")||"";return new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}_roles(){const e=this.getAttribute("roles");if(e)try{const n=JSON.parse(e);if(Array.isArray(n))return n}catch{}return window.desktopModeConfig?.shareEligibleRoles||[]}render(){const e=this._roles();if(e.length===0)return B`<span class="empty">No eligible roles.</span>`;const n=this._selectedSet();return B` |
| 111 |
${e.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 |
`}};Kn.props=["selected","roles"],Kn.styles=[ak],Kn.help=void 0;let Xi=Kn;fe("wpd-role-picker",Xi);const dk=me`:host{display:inline-flex;padding:3px;background:var( --wpd-segmented-bg,rgba( 0,0,0,0.05 ) );border-radius:7px;gap:2px}`,lk=me`: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}`,Yn=class Yn extends ue{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})}};Yn.props=["value"],Yn.styles=[lk],Yn.help=void 0;let Zi=Yn;fe("wpd-segment",Zi);const Xn=class Xn extends ue{connectedCallback(){super.connectedCallback(),this.addEventListener("wpd-segment-pick",e=>{const n=e.detail;e.stopPropagation(),this.value=n.value,this.emit("wpd-pick",{value:n.value})})}set items(e){const n=this.querySelectorAll(":scope > wpd-segment");for(const i of Array.from(n))i.remove();for(const i of e){const r=document.createElement("wpd-segment");r.setAttribute("value",i.value),r.textContent=i.label,this.appendChild(r)}const o=this.value;!(o!==null&&e.some(i=>i.value===o))&&e.length>0?this.value=e[0].value:this.requestUpdate()}render(){const e=this.label||"";e&&this.setAttribute("aria-label",e),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>`}};Xn.props=["value","label"],Xn.styles=[dk],Xn.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 Ji=Xn;fe("wpd-segmented",Ji);const ck=me`: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}`,Zn=class Zn extends ue{render(){const e=this.disabled!==null,n=this.type||"button";return B` |
| 130 |
<button part="button" type=${n} ?disabled=${e}> |
| 131 |
<slot></slot> |
| 132 |
</button> |
| 133 |
`}};Zn.props=["variant","disabled","type","busy","fill-cell"],Zn.styles=[ck],Zn.help=void 0;let Qi=Zn;fe("wpd-button",Qi);const uk=me`: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}`,pk=me`: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}}`,is=class is extends ue{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return B`<slot></slot>`}};is.styles=[uk],is.help=void 0;let er=is;fe("wpd-toast-container",er);const Jn=class Jn extends ue{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status")}render(){const e=this.action||"";return B` |
| 134 |
<span class="wpd-toast__label"><slot></slot></span> |
| 135 |
<button |
| 136 |
type="button" |
| 137 |
?hidden=${!e} |
| 138 |
@click=${n=>this._onAction(n)} |
| 139 |
> |
| 140 |
${e} |
| 141 |
</button> |
| 142 |
`}_onAction(e){e.preventDefault(),e.stopPropagation(),this.emit("wpd-toast-action",{})}};Jn.props=["action","state"],Jn.styles=[pk],Jn.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 tr=Jn;fe("wpd-toast",tr);function fu(t,e){const n=document.createElement("wpd-segmented");n.setAttribute("value",t),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;e(r.value)}),n}function mu(t,e,n={}){const o=document.createElement("wpd-button");o.setAttribute("variant","ghost"),o.setAttribute("aria-label",n.danger?"Remove":"Dismiss"),o.textContent=t;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",e),o}async function hu(t){const e=document.createElement("wpd-modal");e.setAttribute("open",""),e.setAttribute("size","lg"),e.setAttribute("title",`Share "${t.folderName}"`),document.body.appendChild(e);let n=[],o=[];const s=()=>{e.innerHTML="";const d=document.createElement("div");d.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",d.textContent=t.ownerName?`Owner: ${t.ownerName} — cannot be changed`:"Owner cannot be changed",e.appendChild(d);const l=document.createElement("div");l.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const c=document.createElement("div");c.textContent="Add people",c.style.cssText="font-weight:600;",l.appendChild(c);const u=document.createElement("wpd-user-search"),p=n.filter(E=>E.principalType==="user").map(E=>E.principalRef).concat(o.filter(E=>E.kind==="user").map(E=>E.ref));u.setAttribute("exclude",p.join(",")),u.setAttribute("placeholder","Search users…"),u.addEventListener("wpd-user-pick",E=>{const L=E.detail;o.push({kind:"user",ref:String(L.user.id),label:L.user.name,cap:"read"}),s()}),l.appendChild(u),e.appendChild(l);const f=document.createElement("div");f.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const g=document.createElement("div");g.textContent="Add roles",g.style.cssText="font-weight:600;",f.appendChild(g);const m=document.createElement("wpd-role-picker"),h=n.filter(E=>E.principalType==="role").map(E=>E.principalRef),w=o.filter(E=>E.kind==="role").map(E=>E.ref);if(m.setAttribute("selected",[...h,...w].join(",")),m.addEventListener("wpd-role-toggle",E=>{const L=E.detail,b=n.find(A=>A.principalType==="role"&&A.principalRef===L.slug);if(b){L.selected||r(b);return}if(L.selected){const A=(window.desktopModeConfig?.shareEligibleRoles??[]).find(I=>I.slug===L.slug);o.push({kind:"role",ref:L.slug,label:A?A.name:L.slug,cap:"read"})}else o=o.filter(A=>!(A.kind==="role"&&A.ref===L.slug));s()}),f.appendChild(m),e.appendChild(f),o.length>0){const E=document.createElement("div");E.style.cssText="border:1px dashed rgba(255,255,255,0.18);border-radius:8px;padding:10px;margin-bottom:14px;";const L=document.createElement("div");L.textContent="New invites (not sent yet)",L.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",E.appendChild(L);for(const A of o){const I=document.createElement("div");I.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const _=document.createElement("span");_.textContent=A.kind==="role"?`Role: ${A.label}`:A.label,_.style.flex="1",I.appendChild(_);const k=fu(A.cap,M=>{A.cap=M});I.appendChild(k);const O=mu("×",()=>{o=o.filter(M=>!(M.kind===A.kind&&M.ref===A.ref)),s()});I.appendChild(O),E.appendChild(I)}const b=document.createElement("wpd-button");b.setAttribute("variant","primary"),b.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,b.style.marginTop="8px",b.addEventListener("click",async()=>{if(o.length===0)return;b.setAttribute("busy",""),b.setAttribute("disabled","");const A=o.slice();let I=0,_=null;for(const k of A)try{await Dc(t.folderId,{principalType:k.kind,principalRef:k.ref,capability:k.cap}),I++}catch(O){_=O;break}I>0&&(o=o.slice(I));try{await i()}catch{}J(_?{message:`Could not send invites: ${_.message}`}:{message:I===1?"Invite sent.":`${I} invites sent.`}),b.removeAttribute("busy"),b.removeAttribute("disabled"),s()}),E.appendChild(b),e.appendChild(E)}const x=document.createElement("div");if(x.textContent="Who has access",x.style.cssText="font-weight:600;margin:8px 0 6px;",e.appendChild(x),n.length===0){const E=document.createElement("div");E.textContent="Only you can see this folder.",E.style.cssText="opacity:0.6;font-size:12px;",e.appendChild(E)}else for(const E of n){const L=document.createElement("div");L.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const b=document.createElement("div");if(b.style.flex="1",b.textContent=E.principalType==="role"?`Role: ${E.displayName}`:E.displayName,E.state==="pending"){const k=document.createElement("span");k.textContent=" · pending",k.style.cssText="opacity:0.6;font-size:12px;",b.appendChild(k)}else if(E.state==="denied"){const k=document.createElement("span");k.textContent=" · denied",k.style.cssText="color:#d63638;font-size:12px;",b.appendChild(k)}L.appendChild(b);const A=E.capability==="write"?"write":"read",I=fu(A,k=>{a(E,k)});L.appendChild(I);const _=mu("×",()=>{r(E)},{danger:!0});L.appendChild(_),e.appendChild(L)}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",()=>e.remove()),D.appendChild(y),e.appendChild(D)},i=async()=>{try{n=(await Nc(t.folderId)).shares,tk(t.folderId,n)}catch(d){J({message:`Could not load shares: ${d.message}`})}s()},r=async d=>{try{await Rc(t.folderId,d.id),ok(t.folderId,d.id),await i(),J({message:"Access revoked."})}catch(l){J({message:`Could not revoke: ${l.message}`})}},a=async(d,l)=>{try{const c=await Oc(t.folderId,d.id,l);nk(c),await i()}catch(c){J({message:`Could not update capability: ${c.message}`})}};e.addEventListener("wpd-modal-cancel",()=>e.remove()),s(),await i()}function fk(t){return new Promise(e=>{const n=document.createElement("wpd-modal");n.setAttribute("open",""),n.setAttribute("title",t.folderName?`${t.ownerName??"Someone"} shared "${t.folderName}" with you`:"Folder shared with you");const o=document.createElement("div"),s=t.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(),e("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 Pc(t.folderId,t.id),Je().state.deniedFolders.add(t.folderId),Je().notify(),n.remove(),e("denied")}catch(l){J({message:`Could not deny: ${l.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 Mc(t.folderId,t.id);try{const l=await Oe(0);Wt(0,l.placements)}catch{}n.remove(),e("accepted")}catch(l){J({message:`Could not accept: ${l.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(),e("dismissed")}),document.body.appendChild(n)})}function wu(){return Number(window.desktopModeConfig?.currentUserId??0)}function gu(){const t=window.wp?.desktop?.getOsSettings?.();return t?t.foldersSharingEnabled!==!1:!0}function yu(t){const e=wt().folders.get(t);return e?Number(e.ownerId):0}function bu(t){if(typeof t!="string")return null;const e=/^desktop-mode-folder-(\d+)$/.exec(t);return e?Number(e[1]):null}function mk(t){if(t.file.type!=="folder")return null;const e=Number(t.file.ref);return!Number.isFinite(e)||e<=0?null:e}function hk(t){return Number(t.file.ownerId??0)}function wk(){Tr("desktop-mode.files.tile-menu","desktop-mode/folder-share",(t,e)=>{if(!gu())return t;const n=mk(e);if(n===null)return t;const o=yu(n)||hk(e),s=wu();if(o===s){const r=!!e.file.shareSummary?.shared?"Manage sharing…":"Share folder…";t.push({id:"desktop-mode/folder-share",label:r,icon:"dashicons-share",sort:30,onClick:()=>{hu({folderId:n,folderName:e.file.title||`Folder ${n}`})}})}else o>0&&t.push({id:"desktop-mode/folder-leave",label:"Leave shared folder",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await Xa({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 $c(n),Fo(e.id);try{const d=await Oe(0);Wt(0,d.placements)}catch{}const r=`desktop-mode-folder-${n}`;window.desktopMode?.windowManager?.close?.(r),J({message:"You left the shared folder."})}catch(r){J({message:`Could not leave: ${r.message}`})}}});return t}),yd({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:t=>{if(!gu())return!1;const e=t.config.baseId??t.id,n=bu(e);return n===null?!1:yu(n)===wu()},onClick:t=>{const e=t.config.baseId??t.id,n=bu(e);n!==null&&hu({folderId:n,folderName:t.config.title||`Folder ${n}`})}}),j("desktop-mode.files.tile-rendered","desktop-mode/folder-share",t=>{const{tile:e,placement:n}=t;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||e.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(";"),e.appendChild(s)})}const vu=new Set;function gk(){const t=window.wp?.desktop?.getOsSettings?.();return t?t.foldersSharingEnabled!==!1:!0}function yk(){const t=Je(),e=n=>{if(gk())for(const o of n.pending)vu.has(o.id)||(vu.add(o.id),fk({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?uu(o.id):s==="denied"&&uu(o.id,{denied:!0,folderId:o.folderId})}))};t.subscribe(e),e(t.state)}Fb(),Xv(),qv(),Jv(),wk();const nr=window.desktopModeConfig?.serverPendingShares;Array.isArray(nr)&&nr.length>0&&cu(nr),yk();const Te={DesktopFile:bc,registerType:Pe,unregisterType:Mb,getType:Pb,getTypes:vc,resolve:Bo,subscribe:$b,registerOpener:$e,unregisterOpener:Wb,getOpener:Ub,getOpeners:Ec,getOpenersForType:Si,resolveOpener:Ci,subscribeOpeners:Bb,getUserAssociations:Ei,open:Ai,rest:jb,store:{get:Ye,getState:wt,subscribe:Mi,setFolderPlacements:Wt,upsertPlacement:Di,removePlacement:Fo,setFolders:Wc,upsertFolder:Oi,removeFolder:Ri}},ku="__synthFromDockItem";function bk(t){let e=0;for(let n=0;n<t.length;n++)e=(e*31+t.charCodeAt(n))%2147483647;return-(e+1)}function vk(t,e){const n=e[t.id];return{id:bk(t.id),parentId:0,x:n?n.x:0,y:n?n.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[ku]:t.id},file:{type:"shortcut",ref:`dock-promoted:${t.id}`,title:t.title,icon:t.icon,previewUrl:"",exists:!0,shortcutUrl:t.url}}}function kk(){const t=window.wp?.desktop;return t?.getMenuItems?t.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 _k(){return window.desktopModeConfig?.desktopIcons??[]}let or=!1;const sr=new Map;function ir(t,e={}){if(!or){or=!0;try{const n=kk(),o=_k(),i=Te.store.getState().placementsByFolder.get(0)??[],r=new Map;for(const c of i){const u=(c.meta??null)&&typeof c.meta=="object"?c.meta[ku]:null;typeof u=="string"&&r.set(u,c)}const a=new Map,d=new Set(o.map(c=>c.id));for(const c of i){const u=c?.file?.ref;typeof u=="string"&&d.has(u)&&a.set(u,c)}const l=new Set;for(const c of n){const u=t[c.id];(u==="desktop"||u==="both")&&(l.add(c.id),r.has(c.id)||Te.store.upsertPlacement(vk(c,e)))}for(const[c,u]of r)l.has(c)||Te.store.removePlacement(u.id);for(const c of o){const u=t[c.id],p=a.get(c.id);if(u==="dock"||u==="hidden"){p&&(sr.set(c.id,p),Te.store.removePlacement(p.id));continue}if(!p){const f=sr.get(c.id);f&&(Te.store.upsertPlacement(f),sr.delete(c.id))}}}finally{or=!1}}}function Ek(t,e=()=>({})){return queueMicrotask(()=>ir(t(),e())),Te.store.subscribe(()=>{ir(t(),e())})}const Sk=me`:host{display:inline-flex;align-items:center;gap:6px;font-size:var( --wpd-save-status-font-size,11px );line-height:1;color:var( --wpd-save-status-fg,currentColor );vertical-align:middle;min-width:0;opacity:1;pointer-events:auto}.wpd-save-status__indicator{display:inline-flex;align-items:center;justify-content:center;width:12px;height:12px;border-radius:50%;flex-shrink:0;box-sizing:border-box;background:var( --wpd-save-status-bg,transparent );border:2px solid var( --wpd-save-status-idle-color,color-mix( in srgb,var( --wp-admin-theme-color,#2271b1 ) 55%,transparent ) );color:var( --wp-admin-theme-color,#2271b1 );transition:background-color 0.2s ease,border-color 0.2s ease,box-shadow 0.2s ease}:host( [ phase='pending' ] ) .wpd-save-status__indicator,:host( [ phase='saving' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:wpd-save-status-pulse 1.2s ease-in-out infinite}:host( [ animation='modem' ][ phase='pending' ] ) .wpd-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:wpd-save-status-modem-stutter 1.8s ease-in-out infinite,wpd-save-status-modem-glow 2.4s ease-in-out infinite}@keyframes wpd-save-status-modem-stutter{0%,4%{opacity:1}5%,30%{opacity:0.22}31%,36%{opacity:1}37%,39%{opacity:0.22}40%,44%{opacity:1}45%,67%{opacity:0.22}68%,76%{opacity:1}77%,100%{opacity:0.22}}@keyframes wpd-save-status-modem-glow{0%,12%{box-shadow:0 0 0 0 transparent}13%,22%{box-shadow:0 0 4px 0 currentColor}23%,50%{box-shadow:0 0 0 0 transparent}51%,58%{box-shadow:0 0 4px 0 currentColor}59%,84%{box-shadow:0 0 0 0 transparent}85%,94%{box-shadow:0 0 5px 0 currentColor}95%,100%{box-shadow:0 0 0 0 transparent}}@media ( prefers-reduced-motion:reduce ){:host( [ phase='pending' ] ) .wpd-save-status__indicator,:host( [ phase='saving' ] ) .wpd-save-status__indicator,:host( [ animation='modem' ][ phase='pending' ] ) .wpd-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .wpd-save-status__indicator{animation:none;opacity:0.85}}:host( [ phase='saved' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-saved-bg,#1d6f42 );border-color:transparent;color:var( --wpd-save-status-saved-bg,#1d6f42 )}:host( [ phase='failed' ] ) .wpd-save-status__indicator{background:var( --wpd-save-status-failed-bg,#d63638 );border-color:transparent;color:var( --wpd-save-status-failed-bg,#d63638 );animation:wpd-save-status-pulse 0.8s ease-in-out 2}@keyframes wpd-save-status-pulse{0%,100%{opacity:0.55;transform:scale( 0.9 )}50%{opacity:1;transform:scale( 1 )}}:host( [ mode='pill' ] ) .wpd-save-status{display:inline-flex;align-items:center;gap:6px;padding:2px 10px;border-radius:999px;background:var( --wpd-save-status-pill-bg,transparent );font-weight:500;white-space:nowrap}:host( [ mode='pill' ][ phase='saving' ] ) .wpd-save-status,:host( [ mode='pill' ][ phase='pending' ] ) .wpd-save-status{background:var( --wpd-save-status-pill-bg,rgba( 0,0,0,0.04 ) );color:var( --wpd-save-status-pill-fg,#50575e )}:host( [ mode='pill' ][ phase='saved' ] ) .wpd-save-status{background:var( --wpd-save-status-pill-bg,rgba( 30,132,73,0.12 ) );color:var( --wpd-save-status-pill-fg,#1d6f42 )}:host( [ mode='pill' ][ phase='failed' ] ) .wpd-save-status{background:var( --wpd-save-status-pill-bg,rgba( 214,54,56,0.12 ) );color:var( --wpd-save-status-pill-fg,#a02622 )}.wpd-save-status__label{min-width:0;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host( [ phase='saved' ] ) .wpd-save-status__glyph,:host( [ phase='failed' ] ) .wpd-save-status__glyph{display:inline-block;color:#fff;width:8px;height:8px}.wpd-save-status__glyph{display:none}.wpd-save-status__glyph svg{display:block;width:100%;height:100%}`,_u="desktop-mode-os-settings-save-lifecycle",Ck=2200,xk=6e3,Qn=class Qn extends ue{constructor(){super(...arguments),this._autoTimer=null,this._docListener=null}connectedCallback(){super.connectedCallback(),this.auto!==null&&this._installAutoListener()}disconnectedCallback(){this._removeAutoListener(),this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null)}attributeChangedCallback(e,n,o){if(super.attributeChangedCallback(e,n,o),(e==="auto"||e==="event")&&(this._removeAutoListener(),this.auto!==null&&this._installAutoListener()),e==="phase"){this._scheduleAutoClear();const s={phase:this.phase??"idle",error:this.error??void 0};this.emit("wpd-save-status-change",s)}}render(){const e=this.phase??"idle",n=this.mode??"dot",s=(this.error??"")||this._labelForPhase(e);return s?this.setAttribute("title",s):this.removeAttribute("title"),this.setAttribute("aria-live",e==="failed"?"assertive":"polite"),this.setAttribute("role",e==="failed"?"alert":"status"),B` |
| 148 |
<span class="wpd-save-status"> |
| 149 |
<span class="wpd-save-status__indicator" aria-hidden="true"> |
| 150 |
<span class="wpd-save-status__glyph">${this._renderGlyph(e)}</span> |
| 151 |
</span> |
| 152 |
${n==="pill"?B`<span class="wpd-save-status__label" |
| 153 |
>${this._labelForPhase(e)}</span |
| 154 |
>`:B``} |
| 155 |
</span> |
| 156 |
`}_renderGlyph(e){return e==="saved"?Ak():e==="failed"?Ik():""}_labelForPhase(e){switch(e){case"pending":case"saving":return this["saving-label"]??"Saving…";case"saved":return this["saved-label"]??"Saved";case"failed":return(this.error??"")||"Couldn’t save";default:return this["idle-label"]??""}}_installAutoListener(){const e=this.event||_u;this._docListener=n=>{const o=n.detail;!o||typeof o.phase!="string"||(this.phase=o.phase,o.error?this.error=o.error:o.phase!=="failed"&&this.error&&this.removeAttribute("error"))},document.addEventListener(e,this._docListener)}_removeAutoListener(){if(!this._docListener)return;const e=this.event||_u;document.removeEventListener(e,this._docListener),this._docListener=null}_scheduleAutoClear(){this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null);const e=this.phase??"idle",n=this._autoClearMsFor(e);n<=0||(this._autoTimer=window.setTimeout(()=>{this._autoTimer=null,this.phase="idle"},n))}_autoClearMsFor(e){if(e==="saved"){const n=this["auto-clear-saved-ms"];return parseInt(n||"",10)||Ck}if(e==="failed"){const n=this["auto-clear-failed-ms"];return parseInt(n||"",10)||xk}return 0}};Qn.props=["phase","mode","animation","auto","event","error","saving-label","saved-label","idle-label","auto-clear-saved-ms","auto-clear-failed-ms"],Qn.styles=[Sk],Qn.help=void 0;let rr=Qn;fe("wpd-save-status",rr);function Ak(){return B` |
| 157 |
<svg |
| 158 |
viewBox="0 0 12 12" |
| 159 |
aria-hidden="true" |
| 160 |
focusable="false" |
| 161 |
fill="none" |
| 162 |
stroke="currentColor" |
| 163 |
stroke-width="2" |
| 164 |
stroke-linecap="round" |
| 165 |
stroke-linejoin="round" |
| 166 |
> |
| 167 |
<path d="M2.5 6 L5 8.5 L9.5 4" /> |
| 168 |
</svg> |
| 169 |
`}function Ik(){return B` |
| 170 |
<svg |
| 171 |
viewBox="0 0 12 12" |
| 172 |
aria-hidden="true" |
| 173 |
focusable="false" |
| 174 |
fill="currentColor" |
| 175 |
> |
| 176 |
<path |
| 177 |
d="M5 2 H7 V7 H5 z M5 8.5 H7 V10.5 H5 z" |
| 178 |
/> |
| 179 |
</svg> |
| 180 |
`}const Lk=me`: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}`,eo=class eo extends ue{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),Ya(this)}render(){const e=this._attr("label")||"",n=this._attr("value")??"",o=this._attr("placeholder")||"",s=this._boolAttr("disabled"),i=this._boolAttr("readonly"),r=this._attr("aria-label")||e,a=this._attr("name")||"",d=Number(this._attr("rows"))||3,l=this._attr("maxlength"),c=this._attr("minlength"),u=this._boolAttr("invalid"),f=`${this.id||"wpd-unnamed"}__field`;return B` |
| 181 |
${e?B`<label class="wpd-textarea__label" for=${f}>${e}</label>`:B``} |
| 182 |
<textarea |
| 183 |
id=${f} |
| 184 |
part="textarea" |
| 185 |
.value=${n} |
| 186 |
placeholder=${o} |
| 187 |
?disabled=${s} |
| 188 |
?readonly=${i} |
| 189 |
rows=${d} |
| 190 |
maxlength=${l??""} |
| 191 |
minlength=${c??""} |
| 192 |
name=${a} |
| 193 |
aria-invalid=${u?"true":"false"} |
| 194 |
aria-label=${r||""} |
| 195 |
@input=${g=>this._onInput(g)} |
| 196 |
@change=${g=>this._onChange(g)} |
| 197 |
@keydown=${g=>this._onKeyDown(g)} |
| 198 |
></textarea> |
| 199 |
`}_attr(e){return this.getAttribute(e)}_boolAttr(e){return this.getAttribute(e)!==null}_onInput(e){const n=e.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(e){const n=e.target;this.emit("wpd-input-commit",{value:n.value})}_onKeyDown(e){if(this._boolAttr("submit-on-enter")&&e.key==="Enter"&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey){e.preventDefault();const n=e.target;this.emit("wpd-submit",{value:n.value})}}_autosize(e){const n=Number(this._attr("max-rows"))||8,o=window.getComputedStyle(e),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,l=r*n+a+d;e.style.height="auto";const c=Math.min(e.scrollHeight,l);e.style.height=`${c}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))}};eo.props=["label","value","placeholder","disabled","readonly","ariaLabel","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],eo.styles=[Lk],eo.help=void 0;let ar=eo;fe("wpd-textarea",ar);const Tk=me`:host{display:inline-flex}button{display:flex;align-items:center;justify-content:center;width:30px;height:30px;padding:0;border:none;border-radius:5px;background:transparent;color:var( --wpd-btn-color,currentColor );cursor:pointer;transition:background-color 0.15s ease,color 0.15s ease}button:hover{color:var( --wpd-btn-color-hover,currentColor );background:var( --wpd-btn-bg-hover,rgba( 0,0,0,0.06 ) )}button:focus-visible{color:var( --wpd-btn-color-hover,currentColor );background:var( --wpd-btn-bg-hover,rgba( 0,0,0,0.06 ) );outline:2px solid var( --wpd-btn-outline,currentColor );outline-offset:1px}:host( [ active ] ) button{color:var( --wpd-btn-color-hover,currentColor );background:var( --wpd-btn-bg-active,rgba( 0,0,0,0.08 ) )}:host( [ danger ] ) button:hover{color:#fff;background:var( --wpd-btn-danger-hover,#d63638 )}svg{display:block;pointer-events:none;flex-shrink:0}svg:empty{display:none}::slotted( span ){line-height:1}::slotted( svg ){display:block}`,Nk={minimize:'<path d="M3 6h6" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>',maximize:'<rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="1.25" fill="none"/>',fullscreen:'<path d="M4.5 2H2v2.5M10 4.5V2H7.5M4.5 10H2V7.5M10 7.5V10H7.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',"fullscreen-exit":'<path d="M2 4.5H4.5V2M7.5 2V4.5H10M2 7.5H4.5V10M7.5 10V7.5H10" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',detach:'<path d="M5 2H2.5v7.5H10V7M6.5 2H10v3.5M10 2L5.5 6.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',reload:'<g transform="translate(0.6 0.6) scale(0.021)" fill="currentColor"><path d="m504.554 233.704-76.447 91.467c-6.329 7.572-15.417 11.479-24.571 11.479a31.872 31.872 0 0 1-20.504-7.447l-91.467-76.447c-13.561-11.334-15.366-31.515-4.032-45.075s31.515-15.366 45.075-4.032l37.506 31.347c-10.274-74.891-74.668-132.774-152.337-132.774C132.984 102.223 64 171.207 64 256s68.984 153.777 153.777 153.777c17.673 0 32 14.327 32 32s-14.327 32-32 32c-58.17 0-112.859-22.653-153.991-63.785C22.653 368.859 0 314.17 0 256s22.653-112.859 63.786-153.992c41.132-41.132 95.821-63.785 153.991-63.785s112.859 22.653 153.992 63.785c32.517 32.516 53.471 73.508 60.829 117.991l22.849-27.339c11.334-13.56 31.515-15.364 45.075-4.032 13.56 11.335 15.365 31.516 4.032 45.076z"/></g>',close:'<path d="M3.25 3.25l5.5 5.5M3.25 8.75l5.5-5.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>',menu:'<circle cx="3" cy="6" r="1.2" fill="currentColor"/><circle cx="6" cy="6" r="1.2" fill="currentColor"/><circle cx="9" cy="6" r="1.2" fill="currentColor"/>'},to=class to extends ue{constructor(){super(...arguments),this._activateWired=!1}render(){const e=this.icon||"",n=Nk[e]||"";return B` |
| 200 |
<button type="button"> |
| 201 |
<svg |
| 202 |
width="14" |
| 203 |
height="14" |
| 204 |
viewBox="0 0 12 12" |
| 205 |
aria-hidden="true" |
| 206 |
focusable="false" |
| 207 |
></svg> |
| 208 |
<slot></slot> |
| 209 |
</button> |
| 210 |
<span data-svg-buffer style="display:none">${n}</span> |
| 211 |
`}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paintSvg()),queueMicrotask(()=>this._wireActivateEvent())}attributeChangedCallback(e,n,o){super.attributeChangedCallback(e,n,o),queueMicrotask(()=>this._paintSvg())}_paintSvg(){const e=this.shadowRoot;if(!e)return;const n=e.querySelector("svg"),o=e.querySelector("[data-svg-buffer]");if(n&&o){const s=o.textContent||"";n.innerHTML!==s&&(n.innerHTML=s)}}_wireActivateEvent(){if(this._activateWired)return;const e=this.shadowRoot;if(!e)return;const n=e.querySelector("button");n&&(this._activateWired=!0,n.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("wpd-button-activate",{bubbles:!0,composed:!0,cancelable:!0}))}))}};to.props=["icon","active","danger"],to.styles=[Tk],to.help=void 0;let dr=to;fe("wpd-window-button",dr);const rt="Sticky Note",Dk="<!-- wpworkspace-sticky:",lr="-->",Ok=64,Rk=48,Mk=180;function cr(t){const e=Pk(t.title),n=Hk($k(t.content,{stripHtmlForRendered:!0})),o=Fk(t);return{localId:`guideline:${t.id}`,guidelineId:t.id,title:e,body:Uk(e,n),modified:t.modified,...o>0?{modifiedMs:o}:{},link:t.link,termIds:Array.isArray(t.wp_guideline_type)?t.wp_guideline_type.filter(zk):[]}}function Pk(t){const e=[];typeof t=="string"?e.push(t):t&&typeof t=="object"&&(typeof t.raw=="string"&&e.push(t.raw),typeof t.rendered=="string"&&e.push(ur(t.rendered)));for(const n of e){const o=ur(n).trim();if(o)return o}return rt}function $k(t,e={}){return typeof t=="string"?t:!t||typeof t!="object"?"":typeof t.raw=="string"&&t.raw.length>0?t.raw:typeof t.rendered=="string"?e.stripHtmlForRendered?ur(t.rendered):t.rendered:""}function Eu(t){const e=t.split(/\r?\n/).find(o=>o.trim().length>0)?.trim(),n=e&&e.length>0?e:rt;return pr(n,Ok)}function Wk(t){const n=t.replace(/\s+/g," ").trim()||rt;return pr(n,Rk)}function Uk(t,e){const n=t.trim();return!n||e.split(/\r?\n/)[0]?.trim()===n?e:e?`${n} |
| 212 |
${e}`:n}function Bk(t,e=rt){const n=e.trim()||rt,o=Eu(t),s=t.search(/\r?\n/);if(s===-1){const r=o===rt?n:o;return{title:r,content:"",excerpt:Su(r)}}let i=t.slice(s);return i=i.replace(/^\r?\n/,""),i.startsWith(` |
| 213 |
`)&&(i=i.slice(1)),{title:o,content:i,excerpt:Su(i.trim()?i:o)}}function Su(t){const e=t.replace(/[\n\t]+/g," ").trim();return pr(e,Mk)}function Hk(t){if(!t.startsWith(Dk)||!t.includes(lr))return t;const e=t.indexOf(lr);let n=t.slice(e+lr.length);return n.startsWith(`\r |
| 214 |
`)?n=n.slice(2):n.startsWith(` |
| 215 |
`)&&(n=n.slice(1)),n}function ur(t){if(typeof document<"u"){const e=document.createElement("template");return e.innerHTML=t,(e.content.textContent??"").trim()}return t.replace(/<[^>]*>/g,"").trim()}function pr(t,e){return t.length>e?`${t.slice(0,e)}...`:t}function Fk(t){if(typeof t.desktop_mode_modified_ms=="number"&&Number.isFinite(t.desktop_mode_modified_ms))return t.desktop_mode_modified_ms;if(!t.modified)return 0;const e=Date.parse(t.modified);return Number.isFinite(e)?e:0}function zk(t){return typeof t=="number"&&Number.isFinite(t)}class Cu extends Error{constructor(e,n){super(e),this.name="StickyNotesRestError",this.status=n}}async function jk(t){const e=await Gk(t),n=qk([...e.artifactTerms,...e.artifactsTerms],e.noteTerms,e.stickyTerms);if(n)return n;const o=await fr(t,{slug:"artifact",name:"Artifact",parent:0}),s=await fr(t,{slug:"note",name:"Note",parent:o.id}),i=await fr(t,{slug:"sticky",name:"Sticky",parent:o.id});return{stickyTermId:i.id,termIds:Iu([o.id,s.id,i.id])}}async function Gk(t){const[e,n,o,s]=await Promise.all([Ft(t,"artifact"),Ft(t,"artifacts"),Ft(t,"note"),Ft(t,"sticky")]);return{artifactTerms:e,artifactsTerms:n,noteTerms:o,stickyTerms:s}}function qk(t,e,n){if(n.length===0)return null;const o=t.find(r=>["artifact","artifacts"].includes(r.slug))??t[0]??null,s=o?n.find(r=>Number(r.parent)===o.id)??n[0]:n[0];if(!s)return null;const i=o?e.find(r=>Number(r.parent)===o.id)??null:null;return{stickyTermId:s.id,termIds:Iu([o?.id,i?.id,s.id])}}async function xu(t,e){return(await Zo(t,Au("wp/v2/guidelines",{context:"edit",status:"private",per_page:"100",orderby:"modified",order:"desc",wp_guideline_type:String(e)}),void 0,!0)).filter(o=>Array.isArray(o.wp_guideline_type)?o.wp_guideline_type.includes(e):!0).map(cr)}async function Vk(t,e,n){const o=Bk(e.body,e.title),s={status:"private",title:o.title,content:o.content,excerpt:o.excerpt};e.guidelineId===null&&(s.wp_guideline_type=n.termIds);const i=e.guidelineId===null?"wp/v2/guidelines":`wp/v2/guidelines/${e.guidelineId}`,r=await Zo(t,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},!1);return cr(r)}function Kk(t,e){const n=new URL("post.php",t);return n.searchParams.set("post",String(e)),n.searchParams.set("action","edit"),n.toString()}async function Ft(t,e){try{return await Zo(t,Au("wp/v2/wp_guideline_type",{context:"edit",slug:e,per_page:"100"}),void 0,!0)}catch(n){if(n instanceof Cu&&(n.status===404||n.status===400))return[];throw n}}async function fr(t,e){const n=await Ft(t,e.slug),o=n.find(s=>Number(s.parent??0)===e.parent);if(o)return o;if(n[0])return n[0];try{return await Zo(t,"wp/v2/wp_guideline_type",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}catch(s){const i=await Ft(t,e.slug);if(i[0])return i[0];throw s}}async function Zo(t,e,n,o=!0){const s=await je(sn(Yk(t),e),n,{source:"desktop-mode/sticky-notes",silent:o});if(!s.ok)throw new Cu(s.statusText||`${rt} request failed`,s.status);return await s.json()}function Yk(t){return t.restUrl?t.restUrl:`${window.location.origin}/wp-json/`}function Au(t,e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,s])=>{n.set(o,s)}),`${t}?${n.toString()}`}function Iu(t){const e=[];return t.forEach(n=>{typeof n=="number"&&Number.isFinite(n)&&!e.includes(n)&&e.push(n)}),e}const Xk="desktop_mode_sticky_notes_subscribe",Zk="desktop_mode_sticky_notes";let Lu=!1,mr=null;function Jk(t){mr=t,!Lu&&(Lu=!0,Ve.contribute(Xk,()=>mr?.getHeartbeatSubscription()),Ve.subscribe(Zk,e=>{mr?.applyHeartbeatPayload(e)}))}const Tu="desktop-mode-sticky-notes-geometry",Qk=264,e_=176,hr=180,wr=128,re=16,t_=1e3;class n_{constructor(e){this.root=null,this.terms=null,this.controllers=new Map,this.contextMenuInstalled=!1,this.desktopHooksInstalled=!1,this.highWaterMs=0,this.zIndexCounter=0,this.host=e.host,this.config=e.config,this.openArtifact=e.openArtifact,this.getActiveDesktopId=e.getActiveDesktopId??(()=>"desktop-1"),this.onError=e.onError}async boot(){try{if(this.terms=await jk(this.config),!this.terms)return;this.installContextMenu(),this.installDesktopHooks();const e=await xu(this.config,this.terms.stickyTermId);if(this.bumpHighWaterFromNotes(e),Jk(this),e.length===0)return;this.ensureRoot(),Nu(e).forEach((n,o)=>this.upsert(n,o))}catch(e){e instanceof Error&&console.debug("[desktop-mode] Sticky notes unavailable:",e.message)}}createNote(e=""){if(!this.terms)return;const n={localId:`local:${Date.now()}:${Math.random().toString(36).slice(2)}`,guidelineId:null,title:e.trim()?Wk(e):rt,body:e,termIds:this.terms.termIds};this.upsert(n,this.controllers.size,{activate:!0}).focus()}upsert(e,n,o={}){this.ensureRoot();const s=Ne(e),i=this.controllers.get(s);if(i)return i.replace(e),o.activate&&this.bringToFront(i),i;const r=new o_({layer:this,note:e,index:n});return this.controllers.set(s,r),this.root?.appendChild(r.element),this.assignZIndex(r),this.applyDesktopVisibility(r),o.activate&&this.bringToFront(r),r}ensureRoot(){if(this.root)return this.root;const e=document.createElement("section");return e.className="desktop-mode-sticky-notes",e.setAttribute("aria-label",N("Sticky notes")),this.host.appendChild(e),this.root=e,e}installContextMenu(){this.contextMenuInstalled||(this.contextMenuInstalled=!0,Tr("desktop-mode.wallpaper-context-menu","desktop-mode/sticky-notes",e=>!Array.isArray(e)||!this.terms||e.some(n=>n.id==="new-sticky-note")?e:[...e,{id:"new-sticky-note",label:N("New sticky note"),icon:"dashicons-edit-page",sort:14,onClick:()=>this.createNote()}]))}installDesktopHooks(){this.desktopHooksInstalled||(this.desktopHooksInstalled=!0,j(v.DESKTOP_SWITCHED,"desktop-mode/sticky-notes",()=>this.refreshDesktopVisibility()),j(v.DESKTOP_CLOSED,"desktop-mode/sticky-notes",e=>{this.migrateDesktopAssignments(e?.desktopId,e?.migratedTo),this.refreshDesktopVisibility()}))}save(e){return this.terms?Vk(this.config,e,this.terms):Promise.reject(new Error(N("Sticky term is unavailable.")))}getHeartbeatSubscription(){if(this.terms)return{stickyTermId:this.terms.stickyTermId,knownIds:this.knownGuidelineIds(),version:this.highWaterMs}}applyHeartbeatPayload(e){for(const n of e.notes??[]){const o=cr(n);this.upsertRemote(o)}for(const n of e.removed??[])this.forgetGuidelineId(n);typeof e.serverTimeMs=="number"&&Number.isFinite(e.serverTimeMs)&&e.serverTimeMs>this.highWaterMs&&(this.highWaterMs=e.serverTimeMs),e.truncated&&this.reloadFromServer()}openNoteArtifact(e){e.guidelineId!==null&&this.openArtifact(Kk(this.config.adminUrl,e.guidelineId),e.title,e.guidelineId)}notifyError(e){this.onError?.(e)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}defaultGeometry(e){const{width:n,height:o}=this.hostSize(),s=Math.min(Qk,Math.max(hr,n-re*2)),i=Math.min(e_,Math.max(wr,o-re*2)),r=e%8*28,a=ze(n-s-32-r,re,Math.max(re,n-s-re)),d=ze(32+r,re,Math.max(re,o-i-re));return{x:a/n,y:d/o,width:s,height:i}}forget(e){this.controllers.delete(Ne(e.note)),e.dispose(),e.element.remove(),this.controllers.size===0&&(this.root?.remove(),this.root=null)}replaceControllerKey(e,n){const o=Ne(n.note);this.controllers.delete(e),this.controllers.set(o,n),i_(e,o),this.applyDesktopVisibility(n)}bumpHighWaterFromNote(e){const n=Mn(e);n>this.highWaterMs&&(this.highWaterMs=n)}bringToFront(e){e.setZIndex(this.nextZIndex())}geometryForNote(e,n){const o=Ne(e),s=gr(o),i=this.normalizeDesktopId(s?.desktopId),r=s?{...s,desktopId:i}:{...this.defaultGeometry(n),desktopId:i};return(!s||s.desktopId!==r.desktopId)&&yr(o,r),r}upsertRemote(e){const n=Ne(e),o=this.controllers.get(n);if(o)return o.shouldReplaceFromRemote(e)?(o.replace(e),this.bumpHighWaterFromNote(e),o):(this.bumpHighWaterFromNote(e),o);const s=this.upsert(e,this.controllers.size);return this.bumpHighWaterFromNote(e),s}forgetGuidelineId(e){for(const n of this.controllers.values())if(n.note.guidelineId===e){this.forget(n);return}}knownGuidelineIds(){const e=[];for(const n of this.controllers.values())n.note.guidelineId!==null&&e.push(n.note.guidelineId);return e}bumpHighWaterFromNotes(e){e.forEach(n=>this.bumpHighWaterFromNote(n))}assignZIndex(e){e.setZIndex(this.nextZIndex())}nextZIndex(){return this.zIndexCounter+=1,this.zIndexCounter}applyDesktopVisibility(e){e.setVisible(this.isNoteOnActiveDesktop(e.note))}refreshDesktopVisibility(){for(const e of this.controllers.values())this.applyDesktopVisibility(e)}isNoteOnActiveDesktop(e){const n=Ne(e),o=gr(n),s=this.normalizeDesktopId(o?.desktopId);return o&&o.desktopId!==s&&yr(n,{...o,desktopId:s}),s===this.activeDesktopId()}migrateDesktopAssignments(e,n){if(!e||!n||e===n)return;const o=Jo();let s=!1;Object.entries(o).forEach(([i,r])=>{r.desktopId===e&&(o[i]={...r,desktopId:this.normalizeDesktopId(n)},s=!0)}),s&&br(o)}activeDesktopId(){try{const e=this.getActiveDesktopId();return typeof e=="string"&&e?e:"desktop-1"}catch{return"desktop-1"}}normalizeDesktopId(e){return e||this.activeDesktopId()}async reloadFromServer(){if(this.terms)try{const e=await xu(this.config,this.terms.stickyTermId),n=new Set;Nu(e).forEach(o=>{o.guidelineId!==null&&n.add(o.guidelineId),this.upsertRemote(o)}),this.knownGuidelineIds().forEach(o=>{n.has(o)||this.forgetGuidelineId(o)})}catch{}}}class o_{constructor(e){this.saveTimer=null,this.geometryTimer=null,this.saving=!1,this.saveAgain=!1,this.resizeObserver=null,this.disposed=!1,this.layer=e.layer,this.note=e.note,this.index=e.index,this.element=document.createElement("article"),this.element.className="desktop-mode-sticky-note",this.element.dataset.stickyNoteId=Ne(this.note),this.titleEl=document.createElement("span"),this.editor=document.createElement("wpd-textarea"),this.statusEl=document.createElement("wpd-save-status"),this.openButton=document.createElement("wpd-window-button"),this.paint(),this.applyGeometry(this.layer.geometryForNote(this.note,this.index)),this.element.addEventListener("pointerdown",()=>this.layer.bringToFront(this),{capture:!0}),this.element.addEventListener("focusin",()=>this.layer.bringToFront(this)),this.watchResize()}focus(){window.setTimeout(()=>this.editor.focusInput?.(),0)}replace(e){this.note=e,this.element.dataset.stickyNoteId=Ne(this.note),this.titleEl.textContent=this.note.title,this.editor.setAttribute("value",this.note.body),this.refreshOpenButton()}shouldReplaceFromRemote(e){if(this.hasLocalChanges())return!1;const n=Mn(this.note),o=Mn(e);return!(n>0&&o>0&&o<=n&&this.note.title===e.title&&this.note.body===e.body)}setZIndex(e){this.element.style.zIndex=String(e)}setVisible(e){this.element.style.display=e?"":"none"}dispose(){this.disposed=!0,this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.geometryTimer!==null&&(window.clearTimeout(this.geometryTimer),this.geometryTimer=null),this.resizeObserver?.disconnect(),this.resizeObserver=null}paint(){this.element.innerHTML="",this.element.style.minWidth=`${hr}px`,this.element.style.minHeight=`${wr}px`;const e=document.createElement("div");e.className="desktop-mode-sticky-note__header";const n=document.createElement("span");n.className="desktop-mode-sticky-note__grip",n.setAttribute("aria-hidden","true"),this.titleEl.className="desktop-mode-sticky-note__title",this.titleEl.textContent=this.note.title,this.statusEl.setAttribute("mode","icon"),this.statusEl.setAttribute("phase","idle"),this.statusEl.className="desktop-mode-sticky-note__status",this.openButton.setAttribute("icon","detach"),this.openButton.setAttribute("title",N("Open artifact")),this.openButton.className="desktop-mode-sticky-note__open",this.openButton.addEventListener("wpd-button-activate",()=>{this.layer.openNoteArtifact(this.note)});const o=document.createElement("wpd-window-button");o.setAttribute("icon","close"),o.setAttribute("danger",""),o.setAttribute("title",N("Hide sticky note")),o.className="desktop-mode-sticky-note__close",o.addEventListener("wpd-button-activate",()=>this.close()),e.append(n,this.titleEl,this.statusEl,this.openButton,o),e.addEventListener("pointerdown",s=>this.startDrag(s)),this.editor.className="desktop-mode-sticky-note__editor",this.editor.setAttribute("aria-label",N("Sticky note text")),this.editor.setAttribute("rows","8"),this.editor.setAttribute("value",this.note.body),this.installEditorKeyboardGuard(),this.editor.addEventListener("wpd-input-change",s=>{const i=s.detail;this.note.body=i.value,this.note.title=Eu(i.value),this.titleEl.textContent=this.note.title,this.setPhase("pending"),this.scheduleSave()}),this.editor.addEventListener("wpd-input-commit",()=>this.flushSave()),this.element.append(e,this.editor),this.refreshOpenButton()}installEditorKeyboardGuard(){["keydown","keypress","keyup"].forEach(e=>{this.editor.addEventListener(e,n=>{n.stopPropagation()})})}refreshOpenButton(){const e=this.note.guidelineId===null;this.openButton.classList.toggle("is-disabled",e),this.openButton.setAttribute("aria-disabled",e?"true":"false")}close(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.layer.forget(this);return}this.flushSave(),this.layer.forget(this)}scheduleSave(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.setPhase("idle");return}this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},t_)}flushSave(){this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),(this.note.guidelineId!==null||this.note.body.trim().length>0)&&this.save()}async save(){if(this.saving){this.saveAgain=!0,this.setPhase("pending");return}this.saving=!0,this.setPhase("saving");const e=this.note.body;try{const n=await this.layer.save({...this.note,body:e});if(this.disposed)return;const o=Ne(this.note);this.note.guidelineId=n.guidelineId,this.note.modified=n.modified,this.note.link=n.link,this.note.termIds=n.termIds.length>0?n.termIds:this.note.termIds,this.note.body===e&&(this.note.title=n.title,this.titleEl.textContent=n.title),o!==Ne(this.note)&&(this.element.dataset.stickyNoteId=Ne(this.note),this.layer.replaceControllerKey(o,this)),this.layer.bumpHighWaterFromNote(this.note),this.refreshOpenButton(),this.setPhase("saved")}catch(n){if(this.disposed)return;const o=n instanceof Error?n.message:N("Could not save sticky note.");this.setPhase("failed",o),this.layer.notifyError(o)}finally{this.saving=!1,!this.disposed&&this.saveAgain&&(this.saveAgain=!1,this.scheduleSave())}}setPhase(e,n){this.statusEl.setAttribute("phase",e),n?(this.statusEl.setAttribute("error",n),this.statusEl.setAttribute("title",n)):(this.statusEl.removeAttribute("error"),this.statusEl.removeAttribute("title"))}hasLocalChanges(){const e=this.statusEl.getAttribute("phase");return this.saveTimer!==null||this.saving||this.saveAgain||e==="pending"||e==="failed"}startDrag(e){if(e.button!==0||e.target?.closest("wpd-window-button, wpd-save-status"))return;e.preventDefault();const o=this.element.getBoundingClientRect(),s=this.layerHostRect(),i=o.left-s.left,r=o.top-s.top,a=e.clientX,d=e.clientY;this.element.classList.add("desktop-mode-sticky-note--dragging"),this.element.setPointerCapture?.(e.pointerId);const l=u=>{const p=this.element.offsetWidth,f=this.element.offsetHeight,{width:g,height:m}=this.layer.hostSize(),h=ze(i+u.clientX-a,re,Math.max(re,g-p-re)),w=ze(r+u.clientY-d,re,Math.max(re,m-f-re));this.element.style.left=`${h}px`,this.element.style.top=`${w}px`},c=u=>{this.element.classList.remove("desktop-mode-sticky-note--dragging"),this.element.releasePointerCapture?.(u.pointerId),document.removeEventListener("pointermove",l),document.removeEventListener("pointerup",c),this.persistGeometry()};document.addEventListener("pointermove",l),document.addEventListener("pointerup",c)}applyGeometry(e){const{width:n,height:o}=this.layer.hostSize(),s=ze(e.width,hr,n-re*2),i=ze(e.height,wr,o-re*2),r=ze(e.x*n,re,Math.max(re,n-s-re)),a=ze(e.y*o,re,Math.max(re,o-i-re));this.element.style.left=`${r}px`,this.element.style.top=`${a}px`,this.element.style.width=`${s}px`,this.element.style.height=`${i}px`}watchResize(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.geometryTimer!==null&&window.clearTimeout(this.geometryTimer),this.geometryTimer=window.setTimeout(()=>{this.geometryTimer=null,this.persistGeometry()},150)}),this.resizeObserver.observe(this.element))}persistGeometry(){const{width:e,height:n}=this.layer.hostSize(),o=parseFloat(this.element.style.left)||0,s=parseFloat(this.element.style.top)||0,i=gr(Ne(this.note));yr(Ne(this.note),{...i??{},x:ze(o/e,0,1),y:ze(s/n,0,1),width:this.element.offsetWidth,height:this.element.offsetHeight})}layerHostRect(){return(this.element.parentElement?.parentElement??document.body).getBoundingClientRect()}}function s_(t){const e=new n_(t);return e.boot(),e}function Ne(t){return t.guidelineId===null?t.localId:`guideline:${t.guidelineId}`}function Mn(t){if(typeof t.modifiedMs=="number"&&Number.isFinite(t.modifiedMs))return t.modifiedMs;if(!t.modified)return 0;const e=Date.parse(t.modified);return Number.isFinite(e)?e:0}function Nu(t){return[...t].sort((e,n)=>Mn(e)-Mn(n))}function gr(t){const n=Jo()[t];return!n||!Number.isFinite(n.x)||!Number.isFinite(n.y)||!Number.isFinite(n.width)||!Number.isFinite(n.height)?null:n}function yr(t,e){const n=Jo();n[t]=e,br(n)}function i_(t,e){if(t===e)return;const n=Jo();n[t]&&(n[e]=n[t],delete n[t],br(n))}function Jo(){try{const t=window.localStorage.getItem(Tu);return t?JSON.parse(t):{}}catch{return{}}}function br(t){try{window.localStorage.setItem(Tu,JSON.stringify(t))}catch{}}function ze(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}const r_={id:"clock",get label(){return N("Clock")},get description(){return N("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:t=>{t.classList.add("desktop-mode-widget-clock");const e=document.createElement("div");e.className="desktop-mode-widget-clock__time",t.appendChild(e);const n=document.createElement("div");n.className="desktop-mode-widget-clock__date",t.appendChild(n);const o=()=>{const a=new Date;e.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 a_(){Ks(r_)}function d_(t){const{layer:e}=t,n=new Set,o=new Set,s=async d=>{if(!(!d.scriptUrl||o.has(d.scriptUrl))){try{await Ae(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(l){C(v.SHELL_ERROR,{scope:"widget-script-load",id:d.id,error:l})}o.add(d.scriptUrl)}},i=d=>{const c=(window.desktopModeWidgets||{})[d.id];return c?{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:c}:(C(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 l=i(d);if(l){try{Ks(l)}catch(c){C(v.SHELL_ERROR,{scope:"widget-register",id:d.id,error:c});return}n.add(d.id),xo(),e&&e.mountIfEnabled(d.id)}},a=d=>{n.has(d)&&(e?.unmount(d),Gh(d),n.delete(d),xo())};return async d=>{const l=new Set;for(const c of d)l.add(c.id);for(const c of Array.from(n))l.has(c)||a(c);for(const c of d)n.has(c.id)||await r(c)}}const Du=["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"],Ou=new Set(Du),l_=2e3,vr=new Set,Ru=new WeakSet;let Mu=!1;function c_(t,e){const n=t.length,o=e.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]=t[i-1]===e[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=d}}return s[o]}function u_(t){let e=null,n=1/0;for(const o of Ou){const s=c_(t,o);s<n&&(n=s,e=o)}return n>0&&n<=3?e:null}function p_(t){return t.startsWith("wpd-")?t.slice(4):t}function f_(t,e){if(vr.has(t))return;if(vr.add(t),Ou.has(t)){const s=p_(t);console.error(`[wp.desktop] <${t}> is in the DOM but its module was never imported, so the tag will not upgrade and the component will render as inert HTML. |
| 216 |
|
| 217 |
Fix — side-effect-import the component module from wherever you render it: |
| 218 |
|
| 219 |
import '<rel>/ui/components/${s}/${s}'; |
| 220 |
|
| 221 |
Or pull every wpd-* component in one go (heavier — only do this from an entry bundle): |
| 222 |
|
| 223 |
import '<rel>/ui/components'; |
| 224 |
|
| 225 |
See docs/components-reference.md for the full list.`,` |
| 226 |
First offending element:`,e);return}const o=u_(t);if(o){console.error(`[wp.desktop] <${t}> is not a registered wpd-* component. Did you mean <${o}>? |
| 227 |
|
| 228 |
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'.`,` |
| 229 |
First offending element:`,e);return}console.error(`[wp.desktop] <${t}> looks like a wpd-* tag but no component by that name exists. |
| 230 |
|
| 231 |
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.`,` |
| 232 |
First offending element:`,e)}function Pu(t){const e=t.tagName.toLowerCase();if(!e.startsWith("wpd-")||vr.has(e)||customElements.get(e))return;let n=!1;customElements.whenDefined(e).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(e)||f_(e,t)},l_)}function $u(t){t instanceof Element&&(Pu(t),t.shadowRoot&&Qo(t.shadowRoot));const e=t.querySelectorAll("*");for(let n=0;n<e.length;n++){const o=e[n];Pu(o),o.shadowRoot&&Qo(o.shadowRoot)}}function Qo(t){if(Ru.has(t))return;Ru.add(t),$u(t),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&&$u(r)}}}).observe(t,{childList:!0,subtree:!0})}function m_(){const t=Element.prototype,e=t.attachShadow;if(e.__wpdPatched)return;const n=function(o){const s=e.call(this,o);return s.mode==="open"&&Qo(s),s};n.__wpdPatched=!0,t.attachShadow=n}function h_(){Mu||typeof document>"u"||(Mu=!0,m_(),Qo(document))}const kr="data-desktop-mode-trash-drop-active",zt="desktop-mode-recycle-bin",w_=[`.desktop-mode-file-tile[data-file-ref="${zt}"]`,`[data-icon-id="${zt}"]`,`[data-system-id="${zt}"]`];function g_(){for(const t of w_){const e=document.querySelector(t);if(e instanceof HTMLElement)return e}return null}let Wu=!1,Pn=null,$n=null,Uu=null;function y_(t){return t.payload.type==="desktop-file"}function Bu(t,e,n){return t.registerDropTarget({id:e,element:n,accept:o=>{if(o.type!=="desktop-file")return!1;const i=o.data?.placement;return!i||i.file?.ref===zt?!1:i.canTrash!==!1},onEnter:()=>{n.setAttribute(kr,"")},onLeave:()=>{n.removeAttribute(kr)},onDrop:o=>{if(n.removeAttribute(kr),!y_(o))return;const s=o.payload.data.placement;rv(s)}})}function b_(t){if(Wu)return;Wu=!0;const e=()=>{const n=g_();if(!n){Pn?.(),Pn=null;return}Pn&&v_(t)===n||(Pn?.(),Pn=Bu(t,"recycle-bin-dock",n))};if(e(),document.addEventListener("desktop-mode-files-changed",e),document.addEventListener("desktop-mode-desktop-icons-rendered",e),j(v.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",e),typeof MutationObserver<"u"){Uu=new MutationObserver(()=>{e()});const n=document.getElementById("desktop-mode-area")??document.body;Uu.observe(n,{childList:!0,subtree:!0})}j(v.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==zt)return;$n?.(),$n=null;const o=document.querySelector("[data-desktop-mode-recycle-bin-root]");o instanceof HTMLElement&&($n=Bu(t,"recycle-bin-window",o))}),j(v.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===zt&&($n?.(),$n=null)})}function v_(t){const e=t.debug().listTargets().find(n=>n.id==="recycle-bin-dock");return e?e.element:null}let Hu=!1,vt=0;function k_(){Hu||(Hu=!0,Ve.contribute("desktop_mode_files_subscribe",()=>{const t=wt(),e={};for(const[n,o]of t.folders)e[String(n)]=o.updatedAtMs;return{folderVersions:e,placementsVersion:vt,sharesVersion:Je().state.sharesVersion}}),Ve.subscribe("desktop_mode_files",t=>{__(t)}))}function __(t){const e=t.folders??[];for(const i of e)Oi(i,"remote"),i.updatedAtMs>vt&&(vt=i.updatedAtMs);const n=t.placements??[];for(const i of n)Di(i,"remote"),i.updatedAtMs>vt&&(vt=i.updatedAtMs);const o=t.removed??{};for(const i of o.folders??[])Ri(i,"remote");for(const i of o.placements??[])Fo(i,"remote");typeof t.serverTimeMs=="number"&&t.serverTimeMs>vt&&(vt=t.serverTimeMs);const s=t.shares?.pending;if(Array.isArray(s)&&s.length>0&&cu(s),t.truncated){const i=Array.from(wt().hydratedFolders);for(const r of i)Oe(r).then(a=>{Wt(r,a.placements)}).catch(()=>{})}}let Fu=!1;const E_=[];function S_(){if(Fu)return;Fu=!0;const t=e=>{const n=e;!n||n.action!=="untrashed"||C_()};E_.push(Re("desktop-mode.placement.changed",t),Re("desktop-mode.shortcut.changed",t),Re("desktop-mode.folder.changed",t))}function C_(){Ac().then(e=>{Wc(e.folders)}).catch(e=>{console.error("[desktop-mode] files restore-sync: listFolders failed",e)});const t=Array.from(wt().hydratedFolders);for(const e of t)Oe(e).then(n=>{Wt(e,n.placements)}).catch(n=>{console.error("[desktop-mode] files restore-sync: listPlacements failed for",e,n)})}const Wn="desktop-mode-wallpaper-menu";let jt=null;function zu(){return jt!==null}let ju=0;function x_(t,e,n,o={}){Un();const s=++ju;Yt(()=>s===ju,()=>A_(t,e,n,o))}function A_(t,e,n,o={}){if(n.length===0)return;n=n.slice().sort((f,g)=>{const m=typeof f.sort=="number"?f.sort:100,h=typeof g.sort=="number"?g.sort:100;return m!==h?m-h:f.label.localeCompare(g.label)});const s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(Wn),s.style.left=`${e.x}px`,s.style.top=`${e.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 g=document.createElement("wpd-context-menu-option");g.dataset.menuItemId=f.id,g.setAttribute("value",f.id),f.heading&&g.setAttribute("heading",""),f.disabled&&g.setAttribute("disabled",""),f.icon&&g.setAttribute("icon",Gu(f.icon));const m=Array.isArray(f.children)&&f.children.length>0;m&&g.setAttribute("has-children",""),g.textContent=f.label,g.addEventListener("mouseenter",()=>{if(m){l(f,g);return}d()}),s.appendChild(g)}s.addEventListener("wpd-context-menu-pick",f=>{const g=f.detail,m=i.get(g.id)??null;if(m){if(Array.isArray(m.children)&&m.children.length>0){if(f.stopPropagation(),a&&a.id===m.id){d();return}const h=s.querySelector(`[data-menu-item-id="${m.id}"]`);h&&l(m,h);return}Un(),m.onClick(new MouseEvent("click"))}});function l(f,g){d();const m=document.createElement("wpd-context-menu");m.setAttribute("open",""),m.classList.add(Wn,`${Wn}--flyout`),m.dataset.parentId=f.id;const h=(f.children??[]).slice().sort((w,x)=>{const D=typeof w.sort=="number"?w.sort:100,y=typeof x.sort=="number"?x.sort:100;return D!==y?D-y:w.label.localeCompare(x.label)});for(const w of h){const x=document.createElement("wpd-context-menu-option");x.dataset.menuItemId=w.id,x.setAttribute("value",w.id),w.icon&&x.setAttribute("icon",Gu(w.icon)),w.disabled&&x.setAttribute("disabled",""),w.checked&&x.setAttribute("checked",""),x.textContent=w.label,x.addEventListener("wpd-context-menu-pick",D=>{D.stopPropagation(),Un(),w.onClick(new MouseEvent("click"))}),m.appendChild(x)}document.body.appendChild(m),r=m,a=f,c(m,g)}function c(f,g){const m=g.getBoundingClientRect();f.style.position="fixed",f.style.left=`${m.right}px`,f.style.top=`${m.top}px`;const h=f.getBoundingClientRect();h.right>window.innerWidth&&(f.style.left=`${Math.max(0,m.left-h.width)}px`),h.bottom>window.innerHeight&&(f.style.top=`${Math.max(0,window.innerHeight-h.height-8)}px`)}t.appendChild(s),jt=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=Bc(s,{close:()=>Un(),siblingSelectors:[`.${Wn}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",p),C("desktop-mode.wallpaper-menu.opened",{items:n.map(f=>f.id)})}function Un(){jt&&(document.querySelectorAll(`.${Wn}--flyout`).forEach(t=>t.remove()),jt.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),jt.remove(),jt=null,C("desktop-mode.wallpaper-menu.closed",{}))}function I_(t){const e=[{id:"create-folder",label:t.labels.createFolder,icon:"dashicons-portfolio",sort:10,onClick:()=>t.createFolder()},{id:"new-url",label:t.labels.newUrl,icon:"dashicons-admin-links",sort:12,onClick:()=>t.createUrl()},{id:"sort-by",label:t.labels.sortHeading,icon:"dashicons-sort",sort:16,onClick:()=>{},children:[{id:"sort-name-asc",label:t.labels.sortNameAsc,sort:10,checked:t.currentSortMode==="name-asc",onClick:()=>t.sortIcons("name-asc")},{id:"sort-name-desc",label:t.labels.sortNameDesc,sort:20,checked:t.currentSortMode==="name-desc",onClick:()=>t.sortIcons("name-desc")},{id:"sort-date-desc",label:t.labels.sortDateDesc,sort:30,checked:t.currentSortMode==="date-desc",onClick:()=>t.sortIcons("date-desc")},{id:"sort-date-asc",label:t.labels.sortDateAsc,sort:40,checked:t.currentSortMode==="date-asc",onClick:()=>t.sortIcons("date-asc")}]},...t.includeShowDesktop===!1?[]:[{id:"show-desktop",label:t.labels.showDesktop,icon:"dashicons-desktop",sort:20,onClick:()=>t.toggleShowDesktop()}],{id:"os-settings",label:t.labels.osSettings,icon:"dashicons-admin-generic",sort:30,onClick:()=>t.openOsSettings()}],n=(t.serverItems??[]).map(i=>L_(i,t)),o=[...e,...n],s=q("desktop-mode.wallpaper-context-menu",o);return Array.isArray(s)?s:o}function L_(t,e){return{id:t.id,label:t.label,icon:t.icon,sort:t.sort,disabled:t.disabled,onClick:()=>{if(t.callbackId){const n=e.serverCallbacks?.[t.callbackId];if(typeof n=="function")return n()}C("desktop-mode.wallpaper-context-menu.activated",{id:t.id,callbackId:t.callbackId??""})}}}function Gu(t){return t.replace(/[^a-zA-Z0-9_-]/g,"")}const Bn="desktop-mode-url-dialog";let Hn=null;function _r(){Hn&&(Hn.dispatchEvent(new CustomEvent("url-dialog-closed")),Hn.remove(),Hn=null,C("desktop-mode.files.url-dialog.closed",{}))}function T_(t){if(_r(),q("desktop-mode.files.url-dialog",null,t)===!1)return;const n=document.createElement("div");n.className=`${Bn}__overlay desktop-mode-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${Bn} desktop-mode-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${Bn}-title`);const s=document.createElement("h2");if(s.id=`${Bn}-title`,s.className="desktop-mode-create-folder-dialog__title",s.textContent=t.title,o.appendChild(s),t.description){const w=document.createElement("p");w.className=`${Bn}__description`,w.textContent=t.description,o.appendChild(w)}const i=document.createElement("wpd-text-field");i.setAttribute("label",t.nameLabel??"Name"),i.setAttribute("value",t.initialName??""),i.setAttribute("placeholder","My web app"),i.setAttribute("autocomplete","off"),o.appendChild(i);const r=document.createElement("wpd-text-field");r.setAttribute("label",t.urlLabel??"URL"),r.setAttribute("value",t.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 l=document.createElement("button");l.type="button",l.className="desktop-mode-create-folder-dialog__btn desktop-mode-create-folder-dialog__btn--secondary",l.textContent="Cancel";const c=document.createElement("button");c.type="button",c.className="desktop-mode-create-folder-dialog__btn desktop-mode-create-folder-dialog__btn--primary",c.textContent=t.submitLabel??"Create",d.appendChild(l),d.appendChild(c),o.appendChild(d),n.appendChild(o),document.body.appendChild(n),Hn=n,queueMicrotask(()=>{const w=i.shadowRoot?.querySelector("input");w?.focus(),w?.select()}),C("desktop-mode.files.url-dialog.opened",{});const u=w=>{const x=w.value;return typeof x=="string"?x:w.shadowRoot?.querySelector("input")?.value??""},p=w=>{i.disabled=w,r.disabled=w,l.disabled=w,c.disabled=w,o.classList.toggle("desktop-mode-create-folder-dialog--busy",w)},f=w=>{a.textContent=w,a.hidden=!1},g=()=>{_r(),t.onCancel?.()},m=async()=>{const w=u(r).trim();if(!w){f("Please enter a URL.");return}const x=/^[a-z][a-z0-9+\-.]*:/i.test(w)?w:`https://${w}`;try{new URL(x)}catch{f("That doesn't look like a valid URL.");return}const D=u(i).trim();a.hidden=!0,p(!0);try{await t.onSubmit({name:D,url:x}),_r()}catch(y){p(!1),f(y instanceof Error?y.message:"Could not save.")}};l.addEventListener("click",()=>g()),c.addEventListener("click",()=>void m()),n.addEventListener("click",w=>{w.target===n&&g()});const h=w=>{w.key==="Escape"?(w.preventDefault(),g()):w.key==="Enter"&&!w.isComposing&&(w.preventDefault(),m())};o.addEventListener("keydown",h),n.addEventListener("url-dialog-closed",()=>{o.removeEventListener("keydown",h)})}const qu=[];let Er=!1;(function(){const e=window;if(e.wp||(e.wp={}),e.wp.desktop)return;const n={whenReady(o){if(typeof o=="function"){if(Er){Promise.resolve().then(o);return}qu.push(o)}},ready(o){n.whenReady(o)},isReady(){return Er}};e.wp.desktop=n})();const Fn="desktop-mode-os-settings";function Vu(){const t=window.desktopModeConfig;if(!t)return;const e=document.getElementById("desktop-mode-area");if(!e)return;const n=new Rp(e),o=document.getElementById("desktop-mode-wallpaper"),s=t.pluginUrl||"";let i=null;o&&(i=new ad(o,s));const r=document.getElementById("desktop-mode-widgets");let a=null;a_(),Tm(),r&&(a=new yw(r,s)),sd({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const d=new Rm({mediaUrl:t.mediaUrl,restNonce:t.restNonce,canUpload:!!t.canUpload,isAdmin:!!t.currentUserIsAdmin,aiPlatformSettings:t.aiPlatformSettings??null,aiPlatformSettingsUrl:t.aiPlatformSettingsUrl??"",extendedOptions:t.extendedOptions??null,extendedOptionsUrl:t.extendedOptionsUrl??"",osSettingsPanelBundleUrl:t.osSettingsPanelBundleUrl??""},i??new ad(document.createElement("div"),s));d.apply();const l=new Fw({aiSearchUrl:t.aiSearchUrl??"",aiSearchStreamUrl:t.aiSearchStreamUrl??"",restNonce:t.restNonce,getTransport:()=>d.getOsSettingsSnapshot().ai.transport},t.aiAssistantBundleUrl??"");l.attachAsk(Vw({config:()=>t,fallbackContext:()=>({close:()=>l.close(),openInWindow:(S,W,U)=>{n.open({url:S,title:W,icon:U??"dashicons-admin-generic"})},confirm:S=>hc({message:S})})}));const c=new qg,u=new dy;document.addEventListener(Ie.START,S=>{const U=S.detail?.payload;if(!U||U.type!=="shortcut"&&U.type!=="desktop-file")return;const K=U.data?.bridgePayload;K&&c.start(K)}),document.addEventListener(Ie.END,()=>{c.end()}),yy(u),window.addEventListener("message",S=>{if(S.origin!==window.location.origin)return;const W=S.data;!W||W.type!=="desktop-mode-drop-failed"||J({message:"Could not insert into the editor."})}),Ql({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>l.open(),close:()=>l.close(),isOpen:()=>l.isOpen}),Sy(),Pp(n),Hp(n),new Ph({manager:n,adminUrl:t.adminUrl}).install(),new jh({manager:n,adminUrl:t.adminUrl}).install(),document.addEventListener("desktop-mode-open-ai",()=>{tc("desktop-mode-ai-assistant")});const p=document.getElementById("desktop-mode-dock"),f=document.getElementById("desktop-mode-shell"),g=f?.querySelector(".desktop-mode-shell__body");let m=null;const h=Iw({manager:n,appendSystemTile:S=>m?.appendSystemTile(S),removeSystemTile:S=>m?.removeSystemTile(S)}),w=h.sync;rf({getSnapshot:()=>d.getOsSettingsSnapshot(),openById:S=>h.openById(S),adminUrl:t.adminUrl});const x=S=>{const W=le(S,t.adminUrl),U=m?m.getMenuItems():t.dockItems??[];for(const K of U){if(le(K.url,t.adminUrl)===W)return{title:K.title,icon:K.icon,url:K.url,submenu:K.submenu,multi:K.multi};for(const de of K.submenu??[])if(le(de.url,t.adminUrl)===W)return{title:de.title,icon:K.icon,url:K.url,multi:K.multi}}return null};if(gf({adminUrl:t.adminUrl,deriveSlug:S=>le(S,t.adminUrl),openWindow:S=>{n.open(S)},findDockEntry:x}),Ct({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(S,W)=>{if(!W.pathname.endsWith("/edit.php"))return!1;const U=W.searchParams.get("post_type");return!U||U==="post"},enabled:S=>S.nativePostsEnabled===!0}),Ct({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(S,W)=>W.pathname.endsWith("/edit.php")?W.searchParams.get("post_type")==="page":!1,enabled:S=>S.nativePagesEnabled===!0}),Ct({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(S,W)=>W.pathname.endsWith("/users.php"),enabled:S=>S.nativeUsersEnabled===!0}),Ct({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(S,W)=>{const U=W.pathname;return U.endsWith("/profile.php")?!0:U.endsWith("/user-edit.php")?W.searchParams.has("user_id"):!1},enabled:S=>S.nativeUsersEnabled===!0,onMatch:(S,W)=>{const U=parseInt(W.searchParams.get("user_id")??"0",10);U>0&&Bm(U)}}),Ct({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(S,W)=>W.pathname.endsWith("/edit-comments.php"),enabled:S=>S.nativeCommentsEnabled===!0}),Ct({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(S,W)=>{const U=W.pathname;return U.endsWith("/plugins.php")||U.endsWith("/plugin-install.php")},enabled:S=>S.nativePluginsEnabled===!0,onMatch:(S,W)=>{const U=W.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>M_).then(K=>{K.setPluginsWindowTab(U)})}}),p&&f&&g&&t.dockItems){e.classList.add("desktop-mode-area--with-dock");const S=d.getOsSettingsSnapshot().desktopLayout,W=U=>{ll(e,U,{openWindow:h.openById,manager:n})};m=Bw({shellRoot:f,shellBody:g,bottomDockEl:p,desktopArea:e,windowManager:n,adminUrl:t.adminUrl,renderIcons:W,getSettings:()=>{const U=d.getOsSettingsSnapshot();return{itemVisibility:U.itemVisibility,dockOrder:U.dockOrder}}},S,t.dockItems,t.desktopIcons),m.appendSystemTile({id:Fn,title:"OS Settings",icon:"dashicons-desktop",isOpen:()=>{const U=n.getById(Fn);return U?(U.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:D},"core"),Tl()||m.appendSystemTile(Rg(t.pwa?.appName||"WordPress",J),"core"),window.matchMedia("(display-mode: standalone)").addEventListener("change",U=>{U.matches&&m?.removeSystemTile("desktop-mode-pwa-install")}),Nl().then(U=>{U&&m?.removeSystemTile("desktop-mode-pwa-install")})}function D(){n.open({id:Fn,baseId:Fn,url:"#os-settings",title:"OS Settings",icon:"dashicons-desktop",native:!0,render:S=>d.renderPanel(S),width:820,height:720,minWidth:560,minHeight:480})}function y(){n.open({id:vn,baseId:vn,url:`#${vn}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:S=>hg(S),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("desktop-mode-open-bug-report",()=>{y()}),m&&(m.appendSystemTile({id:vn,title:"Report a bug",icon:"dashicons-buddicons-replies",isOpen:()=>{const S=n.getById(vn);return S?(S.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:y},"core"),m.appendSystemTile(Pm(),"core"));const E=m?.getPrimary()??null;w(Array.isArray(t.nativeWindows)?t.nativeWindows:[]);const L=Vy(t.session),b=L?Ky(n,t,e).catch(S=>{typeof console<"u"&&console.error("[desktop-mode] session restore failed:",S)}):Promise.resolve(),A=t.defaultWindow?.enabled!==!1,I=t.defaultWindow?.url??"",_=typeof I=="string"&&I.startsWith("native:");Xy({fromPortal:t.fromPortal,fromPortalIntent:t.fromPortalIntent,hasSession:L,defaultEnabled:A,isNativeDefault:_})&&b.then(()=>Yy(n,t).catch(S=>{typeof console<"u"&&console.error("[desktop-mode] openCurrentPage failed:",S)}));const k=Jy(n,t);eb(k);const O=async S=>{try{const W=await wi(n,t.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({url:S})},{source:"desktop-mode/default-window"});if(!W.ok)throw new Error(`HTTP ${W.status}`);const U=await W.json();t.defaultWindow=U,document.dispatchEvent(new CustomEvent("desktop-mode-default-window-changed",{detail:U}))}catch(W){C(v.SHELL_ERROR,{scope:"default-window-save",error:W}),typeof console<"u"&&console.error("[desktop-mode] Failed to save default window:",W)}};if(n.onToggleStartupRequested=S=>{const W=t.defaultWindow,U=!!S.config.native,K=U?`native:${S.id}`:S.getCurrentUrl(),de=U?W?.url===K:ua(W?.url??"")===ua(K),Vt=!!W?.enabled&&de;O(Vt?null:K)},t.defaultWindow?.enabled&&t.fromPortal&&!t.fromPortalIntent&&!L&&_){const S=I.slice(7);queueMicrotask(()=>{if(S===Fn){D();return}h.openById(S)})}const M=S=>{m?.appendSystemTile(S)},X=d_({layer:a});X(Array.isArray(t.serverWidgets)?t.serverWidgets:[]);const Z=Gm({osSettings:d});Z(Array.isArray(t.serverWallpapers)?t.serverWallpapers:[]);const te=Ym();te(Array.isArray(t.serverCommandScripts)?t.serverCommandScripts:[],Array.isArray(t.serverCommands)?t.serverCommands:[]);const T=Jm();T(Array.isArray(t.serverSettingsTabScripts)?t.serverSettingsTabScripts:[],Array.isArray(t.serverSettingsTabs)?t.serverSettingsTabs:[]);const F=oh();F(Array.isArray(t.serverTitleBarButtonScripts)?t.serverTitleBarButtonScripts:[]);const H=sh();H(Array.isArray(t.serverDockRailRendererScripts)?t.serverDockRailRendererScripts:[]),ah()(Array.isArray(t.serverWindowThemeScripts)?t.serverWindowThemeScripts:[],Array.isArray(t.serverWindowThemes)?t.serverWindowThemes:[]),ch(),uh()(Array.isArray(t.serverWindowControlScripts)?t.serverWindowControlScripts:[],Array.isArray(t.serverWindowControls)?t.serverWindowControls:[]),mh()(Array.isArray(t.serverWindowSlotScripts)?t.serverWindowSlotScripts:[],Array.isArray(t.serverWindowSlots)?t.serverWindowSlots:[]),Bd(Array.isArray(t.serverWindowNotices)?t.serverWindowNotices:[]),Ah()(Array.isArray(t.serverWindowChromeScripts)?t.serverWindowChromeScripts:[],Array.isArray(t.serverWindowChromes)?t.serverWindowChromes:[]);const G=Nh(n);Kw(n),Yw(),nf(),j("desktop-mode.shell.toast","desktop-mode/shell-toast",S=>{!S||typeof S.message!="string"||J({message:S.message,action:S.action,duration:S.duration})});const ne=t,z=ne.recycleBinCount;Qw(Number(z)||0,typeof ne.recycleBinCountUrl=="string"?ne.recycleBinCountUrl:""),lg({getRecycleBinCount:Zw}),window.__desktopModeConnectionBridge=G,j(v.WINDOW_CLOSED,"desktop-mode/connection-cleanup",S=>{S?.windowId&&G.onWindowClosed(S.windowId)}),j(v.IFRAME_READY,"desktop-mode/connection-rearm",S=>{S?.windowId&&G.onIframeReady(S.windowId)});const se=Cw(n),ke=qy({layoutDispatcher:m,config:t,syncNativeWindows:w,syncServerWidgets:X,syncServerWallpapers:Z,syncServerCommands:te,syncServerSettingsTabs:T,syncServerTitleBarButtons:F,syncServerDockRailRenderers:H,renderIcons:S=>{if(m){m.applyDesktopIcons(S);return}ll(e,S,{openWindow:h.openById,manager:n})}});d.subscribeOsSettings(S=>{if(!m)return;const W=m.getLayout();m.setLayout(S.desktopLayout),ae.dock=m.getPrimary(),ae.sideDock=m.getSide(),ae.desktopLayout=S.desktopLayout,W===S.desktopLayout&&m.refresh(),ir(S.itemVisibility,S.dockPromotedPositions),yc(S.desktopLayout)}),Ek(()=>d.getOsSettingsSnapshot().itemVisibility,()=>d.getOsSettingsSnapshot().dockPromotedPositions),yc(d.getOsSettingsSnapshot().desktopLayout);const ae=Db({manager:n,dock:E,layoutDispatcher:m,osSettings:d,iconsApi:Ow,filesApi:Te,saveSession:k,widgetLayer:a,registerWindow:se,openWindowById:h.openById,openNewWindowById:h.openNewById,placeSystemTile:M,setDefaultWindow:O,refreshMenu:ke,openOsSettings:D,aiAssistant:l,dragBridge:c,dragManager:u,connect:G.connect,getConnection:G.getConnection,config:t});if(Ob(ae),b_(u),Cy(),$y(),s_({host:e,config:t,getActiveDesktopId:()=>n.getActiveDesktopId(),openArtifact:(S,W)=>{const U=le(S,t.adminUrl);n.open({id:U,baseId:U,url:S,title:W,icon:"dashicons-edit-page"})},onError:S=>{J({message:S})}}),Hb({openUrl:({id:S,url:W,title:U,icon:K})=>(xt(W)||n.open({id:S,baseId:S,url:W,title:U,icon:K}),!0),openNativeWindow:S=>h.openById(S),deriveWindowId:S=>le(S,t.adminUrl)}),_c(t.userFileAssociations??{}),typeof t.filesUrl=="string"&&t.filesUrl){Sc({baseUrl:t.filesUrl,nonce:t.restNonce});const S=document.getElementById("desktop-mode-area");if(S){const W=Xc(S,0),U=()=>{e.classList.contains("desktop-mode-area--booting")&&requestAnimationFrame(()=>{e.classList.remove("desktop-mode-area--booting")})},K=setTimeout(U,2e3);W.hydrated.then(()=>{clearTimeout(K),U()})}}k_(),S_(),Iy(),C(v.COMPONENTS_REGISTERED,{tags:[...Du]}),vy(),Hg(t,J);const qt=()=>{dp(t.shellOverlaysBundleUrl??""),ip(t.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(qt,{timeout:1500}):window.setTimeout(qt,0),C(v.INIT,{config:t}),Er=!0;const so=qu.splice(0);for(const S of so)try{S()}catch(W){C(v.SHELL_ERROR,{scope:"when-ready-cb",error:W}),typeof console<"u"&&console.error("[desktop-mode] whenReady cb threw:",W)}d.apply(),a?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),a?.disposeAll()}),tb(),Hy(n,t);const rs=(S,W=!0)=>{const U=Te.store.getState().placementsByFolder.get(0)??[],K=S(U),de=Math.max(1,Math.floor((e.clientHeight-16)/110)),Vt=new Set;let kt=0;for(const xe of K){const Ee=gt(16+Math.floor(kt/de)*96,16+kt%de*110,Vt,e);Vt.add(`${Ee.col},${Ee.row}`),kt++,!(xe.x===Ee.x&&xe.y===Ee.y)&&(Te.store.upsertPlacement({...xe,x:Ee.x,y:Ee.y,sortOrder:kt}),W&&Pt(xe.id,{x:Ee.x,y:Ee.y,sortOrder:kt}).catch(et=>{console.error("[desktop-mode] relayout persist failed",et)}))}},io=S=>W=>{const U=W.slice();switch(S){case"name-asc":U.sort((K,de)=>K.file.title.localeCompare(de.file.title));break;case"name-desc":U.sort((K,de)=>de.file.title.localeCompare(K.file.title));break;case"date-asc":U.sort((K,de)=>K.updatedAtMs-de.updatedAtMs);break;case"date-desc":U.sort((K,de)=>de.updatedAtMs-K.updatedAtMs);break}return U},Lr="desktop-mode:root-sort-mode",gE=S=>S==="name-asc"||S==="name-desc"||S==="date-asc"||S==="date-desc";let as=(()=>{try{const S=window.localStorage.getItem(Lr);return gE(S)?S:null}catch{return null}})();const Ju=S=>{as=S;try{S?window.localStorage.setItem(Lr,S):window.localStorage.removeItem(Lr)}catch{}};if(j("desktop-mode.files.tile-manually-placed","desktop-mode/root-sort-clear",S=>{S?.folderId===0&&Ju(null)}),typeof ResizeObserver<"u"){let S=e.clientWidth,W=e.clientHeight;new ResizeObserver(()=>{if(!as)return;const K=e.clientWidth,de=e.clientHeight;K===S&&de===W||(S=K,W=de,rs(io(as),!1))}).observe(e)}e.addEventListener("click",S=>{d.state.showDesktopOnWallpaperClick&&S.target===e&&(e.classList.contains("desktop-mode-area--overview")||zu()||u.recentlyEndedDrag()||n.toggleShowDesktop())}),e.addEventListener("contextmenu",S=>{if(S.target!==e)return;S.preventDefault();const W=S.clientX,U=S.clientY;(()=>{if(e.classList.contains("desktop-mode-area--overview"))return;if(zu()){Un();return}const K={x:W,y:U},de=()=>{const xe=e.getBoundingClientRect(),Ee=Math.max(0,K.x-xe.left),et=Math.max(0,K.y-xe.top),ro=zc(Te.store.getState().placementsByFolder.get(0)??[]);return gt(Ee,et,ro,e)},Vt=(xe,Ee)=>{T_({title:xe,description:Ee,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:et,url:ro})=>{const Qu=de(),yE=await Mt({type:"link",ref:ro,parentId:0,x:Qu.x,y:Qu.y,meta:et?{name:et}:void 0});Te.store.upsertPlacement(yE)}})},kt=I_({createFolder:()=>{Bi({onSubmit:async xe=>{const Ee=await Ni({name:xe}),et=de(),ro=await Mt({type:"folder",ref:String(Ee.id),parentId:0,x:et.x,y:et.y});Te.store.upsertFolder(Ee),Te.store.upsertPlacement(ro)}})},createUrl:()=>Vt("New URL","Opens the URL in a new browser tab."),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>D(),sortIcons:xe=>{Ju(xe),rs(io(xe))},currentSortMode:as,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:t.serverWallpaperMenuItems??[]});x_(document.body,{x:W,y:U},kt)})()}),Promise.resolve().then(()=>rE).then(S=>{S.bootOsFileDrop({config:t.dropConfig,mediaUrl:t.mediaUrl,restNonce:t.restNonce})}),document.dispatchEvent(new CustomEvent("desktop-mode-init",{detail:{config:t,restored:L}}))}h_(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Vu):Vu();const N_={tab:null,requestedAt:0};let es=null;function Sr(){if(es)return es;const e=window.wp?.desktop?.createSharedStore;return typeof e!="function"?null:(es=e("desktop-mode/plugins-window/tab-target",()=>({...N_})),es)}function D_(t){const e=Sr();if(e){e.state.tab=t,e.state.requestedAt=Date.now(),e.notify();return}const n=window;n._wpdPluginsWindowTab={tab:t,requestedAt:Date.now()}}function O_(){const t=Sr();if(t){const o=t.state.tab;return o!==null&&(t.state.tab=null,t.state.requestedAt=0,t.notify()),o}const e=window,n=e._wpdPluginsWindowTab;return n?(e._wpdPluginsWindowTab={tab:null,requestedAt:0},n.tab):null}function R_(t){const e=Sr();return e?e.subscribe(n=>t({...n})):()=>{}}const M_=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:O_,setPluginsWindowTab:D_,subscribePluginsWindowTab:R_},Symbol.toStringTag,{value:"Module"})),pe={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"},P_=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function ts(t){const e=t.dataTransfer?.types;if(!e)return!1;const n=e;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 $_(t){if(!t)return;const e=document.querySelectorAll("iframe");for(const n of Array.from(e))if(n.contentWindow===t)return n.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0}function W_(t){const e=window;if(e.__desktopModeOsFileDropMounted)return e.__desktopModeOsFileDropMounted;if(!t.config.enabled)return B_();const n=U_();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=>{ts(m)&&(m.preventDefault(),o++,n.classList.add("is-active"),r())},d=m=>{if(ts(m)){if(m.defaultPrevented){i();return}m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="copy"),r()}},l=()=>{o=Math.max(0,o-1),o===0&&n.classList.remove("is-active")},c=m=>{if(!ts(m))return;if(m.defaultPrevented){i();return}m.preventDefault(),i();const h=m.dataTransfer?.files?Array.from(m.dataTransfer.files):[];if(h.length===0)return;const w=H_(m);Ku(h,w,t)},u=()=>i(),p=()=>{document.visibilityState==="hidden"&&i()},f=m=>{if(m.origin!==window.location.origin)return;const h=m.data;if(!h||h.type!=="desktop-mode-os-file-drop"||!Array.isArray(h.files)||h.files.length===0)return;const w=h.files.filter(y=>y instanceof File);if(w.length===0)return;const x=$_(m.source);if(!x)return;const D={surface:"iframe",windowId:x,x:typeof h.x=="number"?h.x:0,y:typeof h.y=="number"?h.y:0};o=0,n.classList.remove("is-active"),Ku(w,D,t)};window.addEventListener("dragenter",a),window.addEventListener("dragover",d),window.addEventListener("dragleave",l),window.addEventListener("drop",c),window.addEventListener("dragend",u),document.addEventListener("visibilitychange",p),window.addEventListener("blur",u),window.addEventListener("message",f);const g={dispose:()=>{window.removeEventListener("dragenter",a),window.removeEventListener("dragover",d),window.removeEventListener("dragleave",l),window.removeEventListener("drop",c),window.removeEventListener("dragend",u),document.removeEventListener("visibilitychange",p),window.removeEventListener("blur",u),window.removeEventListener("message",f),n.remove(),delete window.__desktopModeOsFileDropMounted}};return e.__desktopModeOsFileDropMounted=g,g}function U_(){const t=document.querySelector(".desktop-mode-os-drop-overlay");if(t)return t;const e=document.createElement("div");e.className="desktop-mode-os-drop-overlay",e.setAttribute("aria-hidden","true"),e.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",e.appendChild(n),document.body.appendChild(e);const o=document.createElement("style");return o.textContent=".desktop-mode-os-drop-overlay.is-active{opacity:1!important;}",document.head.appendChild(o),e}function B_(){const t=o=>{if(!ts(o))return;const s=o.target;s?.closest&&P_.some(i=>s.closest(i))||o.preventDefault()};window.addEventListener("dragover",t),window.addEventListener("drop",t);const e=window,n={dispose:()=>{window.removeEventListener("dragover",t),window.removeEventListener("drop",t),delete e.__desktopModeOsFileDropMounted}};return e.__desktopModeOsFileDropMounted=n,n}function H_(t){const e=t.clientX,n=t.clientY;let o=t.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:e,y:n};if(o.hasAttribute("data-window-id"))return{surface:"window",windowId:o.getAttribute("data-window-id")||void 0,x:e,y:n};if(o.classList.contains("desktop-mode-folder-grid"))return{surface:"folder",x:e,y:n};if(o.id==="desktop-mode-wallpaper"||o.classList.contains("desktop-mode-wallpaper")||o.classList.contains("desktop-mode-desktop"))return{surface:"wallpaper",x:e,y:n};o=o.parentElement}return{surface:"unknown",x:e,y:n}}async function Ku(t,e,n){const o=q(pe.FILES_DETECTED,t,e);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=F_(o,n.config);if(i.length>0&&(C(pe.FILES_REJECTED,{rejections:i,context:e}),J({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 l={file:a,mime:d,fields:G_(a,d)},c=q(pe.DIALOG_FIELDS,l,e);return!c||typeof c!="object"||!("fields"in c)||typeof c.fields!="object"?l:c});await n.openDialog(r,e)}function F_(t,e){const n=[],o=[];for(const s of t){if(s.size===0){o.push({file:s,reason:"empty",message:`“${s.name}” is empty.`});continue}if(e.maxSize>0&&s.size>e.maxSize){o.push({file:s,reason:"size",message:`“${s.name}” exceeds the ${K_(e.maxSize)} upload limit.`});continue}const i=z_(s,e.allowedMimes,e.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 z_(t,e,n){if(e.length===0)return null;const o=t.type.toLowerCase();if(o&&e.includes(o))return o;const s=Yu(t.name);if(!s)return null;if(n){for(const[r,a]of Object.entries(n))if(r.split("|").includes(s)&&e.includes(a))return a;return null}const i=j_[s];return i&&e.includes(i)?i:null}const j_={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 Yu(t){const e=t.lastIndexOf(".");return e<0?"":t.slice(e+1).toLowerCase()}function G_(t,e){const n=q_(t.name),o=Yu(n),s=o?n.slice(0,n.length-o.length-1):n,i=V_(s);return{title:i,altText:e.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function q_(t){return t.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function V_(t){const e=t.replace(/[-_]+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):"Upload"}function K_(t){return t>=1048576?`${(t/1048576).toFixed(0)} MB`:t>=1024?`${(t/1024).toFixed(0)} KB`:`${t} B`}function ns(t){if(!Number.isFinite(t)||t<=0)return"0 B";const e=["B","KB","MB","GB","TB"];let n=t,o=0;for(;n>=1024&&o<e.length-1;)n/=1024,o++;const s=n>=100||o===0?0:1;return`${n.toFixed(s)} ${e[o]}`}const Y_=me`: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}}`,no=class no extends ue{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return B`<div class="root" part="root"> |
| 233 |
<div class="header" part="header" hidden> |
| 234 |
<span class="label" part="label"></span> |
| 235 |
<span class="percent" part="percent"></span> |
| 236 |
</div> |
| 237 |
<div class="track" part="track"> |
| 238 |
<div class="fill" part="fill"></div> |
| 239 |
</div> |
| 240 |
</div>`}requestUpdate(){super.requestUpdate(),queueMicrotask(()=>this._paint())}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paint())}_paint(){const e=this.shadowRoot;if(!e)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"),l=e.querySelector(".fill");l&&!o?l.style.width=`${(i*100).toFixed(2)}%`:l&&o&&l.style.removeProperty("width");const c=e.querySelector(".header"),u=e.querySelector(".label"),p=e.querySelector(".percent");if(c&&u&&p){const g=a||d&&!o;c.hidden=!g,u.textContent=a,p.hidden=!(d&&!o),p.textContent=`${r}%`}this._syncAria(n,s,o,a);const f=e.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(e,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(e)),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 e=this.getAttribute("max");if(e===null)return 100;const n=parseFloat(e);return Number.isFinite(n)?n:100}_readValue(e){const n=parseFloat(this.getAttribute("value")??"0");return!Number.isFinite(n)||n<0?0:n>e?e:n}};no.props=["value","max","indeterminate","tone","label","showPercent"],no.styles=[Y_],no.help=void 0;let Cr=no;fe("wpd-progress-bar",Cr);const Ue=new Map;let Qe=null;function X_(){if(document.body.hasAttribute("data-desktop-mode-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const t="desktop-mode/os-file-drop-hud";j(pe.UPLOAD_STARTED,t,e=>Z_(e.file,e.fields,e.abort)),j(pe.UPLOAD_PROGRESS,t,e=>J_(e.file,e.loaded,e.total,e.indeterminate)),j(pe.AFTER_UPLOAD,t,e=>Q_(e.file,e.fields,e.result)),j(pe.UPLOAD_FAILED,t,e=>eE(e.file,e.error))}function Z_(t,e,n){const o=tE(),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=e.filename||t.name,r.title=e.filename||t.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 l=document.createElement("div");l.className="desktop-mode-upload-hud__actions";const c=document.createElement("wpd-button");c.setAttribute("variant","tertiary"),c.setAttribute("size","small"),c.textContent="Cancel",c.addEventListener("click",()=>{const u=Ue.get(t);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):xr(u))}),l.appendChild(c),s.append(i,d,l),o.querySelector(".desktop-mode-upload-hud__list").appendChild(s),Ue.set(t,{file:t,abort:n,root:s,bar:d,statusEl:a,cancelBtn:c,state:"running",lingerTimer:null}),os()}function J_(t,e,n,o){const s=Ue.get(t);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${ns(e)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(e)),s.statusEl.textContent=`${ns(e)} / ${ns(n)}`))}function Q_(t,e,n){const o=Ue.get(t);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(()=>xr(o),2500),os(),ge.publish("desktop-mode/upload-hud-complete",{filename:e.filename||n.filename,attachmentId:n.id}))}function eE(t,e){const n=Ue.get(t);n&&(n.bar.removeAttribute("indeterminate"),n.bar.setAttribute("tone","danger"),n.cancelBtn.textContent="Dismiss",n.cancelBtn.disabled=!1,e.name==="UploadAbortedError"?(n.state="aborted",n.statusEl.textContent="Cancelled"):(n.state="failed",n.statusEl.textContent=e.message||"Upload failed"),os())}function xr(t){t.lingerTimer&&clearTimeout(t.lingerTimer),Ue.delete(t.file),t.root.remove(),os(),Ue.size===0&&Qe&&(Qe.hidden=!0)}function tE(){if(Qe&&Qe.isConnected)return Qe.hidden=!1,Qe;const t=document.createElement("div");t.className="desktop-mode-upload-hud",t.setAttribute("role","region"),t.setAttribute("aria-label","Uploads");const e=document.createElement("div");e.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[...Ue.values()])i.state!=="running"&&xr(i);Ue.size===0&&(t.hidden=!0)}),e.append(n,o);const s=document.createElement("div");return s.className="desktop-mode-upload-hud__list",t.append(e,s),document.body.appendChild(t),Qe=t,t}function os(){if(!Qe)return;const t=Qe.querySelector(".desktop-mode-upload-hud__title");if(!t)return;const e=Ue.size,n=[...Ue.values()].filter(o=>o.state==="running").length;n>0?t.textContent=n===e?`Uploading ${n} file${n===1?"":"s"}…`:`${n} of ${e} uploading…`:e>0?t.textContent=`Uploads (${e})`:t.textContent="Uploads"}function nE(){if(document.body.hasAttribute("data-desktop-mode-suppress-media-library-refresh"))return;const t=window;t.__wpdMediaLibraryRefresher||(t.__wpdMediaLibraryRefresher=!0,j(pe.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>oE()))}function oE(){const t=document.querySelectorAll("iframe");for(const e of Array.from(t))if(sE(Xu(e)))try{e.contentWindow?.location.reload()}catch{const n=Xu(e);n&&e.setAttribute("src",n)}}function Xu(t){try{return t.contentWindow?.location.href??t.src??""}catch{return t.src??""}}function sE(t){return t?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(t):!1}function iE(t){const e=t.config||{enabled:!1,allowedMimes:[],maxSize:0};X_(),nE(),W_({config:e,mediaUrl:t.mediaUrl,restNonce:t.restNonce,openDialog:async(n,o)=>{const{openUploadDialog:s}=await Promise.resolve().then(()=>wE);await s({entries:n,context:o,mediaUrl:t.mediaUrl,restNonce:t.restNonce})}})}const rE=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:pe,bootOsFileDrop:iE},Symbol.toStringTag,{value:"Module"})),aE=me`: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}`,oo=class oo extends ue{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),Ya(this)}render(){const e=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 l=r||"off";d&&(!r||l==="off")&&(l="new-password");const c=this.maxlength,u=this.minlength,p=this.pattern||"",f=this.name||"",g=this.suffix||"",m=this.invalid!==null,h=this.reveal!==null,w=a==="password",x=w&&!(h&&this._revealed);let D;w||h&&this._revealed?D="text":D=a;const y=h?"wpd-text-field__row wpd-text-field__row--has-reveal":"wpd-text-field__row",E=x?"wpd-text-field__input wpd-text-field__input--masked":"wpd-text-field__input",b=`${this.id||"wpd-unnamed"}__input`;return B` |
| 241 |
${e?B`<label |
| 242 |
class="wpd-text-field__label" |
| 243 |
for=${b} |
| 244 |
>${e}</label>`:B``} |
| 245 |
<span class=${y}> |
| 246 |
<input |
| 247 |
id=${b} |
| 248 |
class=${E} |
| 249 |
type=${D} |
| 250 |
.value=${n} |
| 251 |
placeholder=${o} |
| 252 |
?disabled=${s} |
| 253 |
?readonly=${i} |
| 254 |
autocomplete=${l} |
| 255 |
maxlength=${c??""} |
| 256 |
minlength=${u??""} |
| 257 |
pattern=${p} |
| 258 |
name=${f} |
| 259 |
aria-invalid=${m?"true":"false"} |
| 260 |
aria-label=${e||""} |
| 261 |
@input=${A=>this._onInput(A)} |
| 262 |
@change=${A=>this._onChange(A)} |
| 263 |
@keydown=${A=>this._onKeyDown(A)} |
| 264 |
/> |
| 265 |
${g?B`<span class="wpd-text-field__suffix">${g}</span>`:B``} |
| 266 |
${h?this._renderRevealButton(s):B``} |
| 267 |
</span> |
| 268 |
`}_renderRevealButton(e){const n=this._revealed?"Hide":"Show";return B` |
| 269 |
<button |
| 270 |
type="button" |
| 271 |
class="wpd-text-field__reveal" |
| 272 |
aria-label=${n} |
| 273 |
aria-pressed=${this._revealed?"true":"false"} |
| 274 |
?disabled=${e} |
| 275 |
tabindex="0" |
| 276 |
@click=${()=>this._onToggleReveal()} |
| 277 |
> |
| 278 |
${this._revealed?lE():dE()} |
| 279 |
</button> |
| 280 |
`}_onToggleReveal(){this._revealed=!this._revealed,this.requestUpdate()}_onInput(e){const n=e.target;this.value=n.value,this.emit("wpd-input-change",{value:n.value})}_onChange(e){const n=e.target;this.emit("wpd-input-commit",{value:n.value})}_onKeyDown(e){if(e.key==="Enter"&&!e.shiftKey&&!e.altKey&&!e.metaKey){const n=e.target;this.emit("wpd-submit",{value:n.value})}}};oo.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],oo.styles=[aE],oo.help=void 0;let Ar=oo;fe("wpd-text-field",Ar);function dE(){return B` |
| 281 |
<svg |
| 282 |
viewBox="0 0 16 16" |
| 283 |
width="14" |
| 284 |
height="14" |
| 285 |
fill="none" |
| 286 |
stroke="currentColor" |
| 287 |
stroke-width="1.5" |
| 288 |
stroke-linecap="round" |
| 289 |
stroke-linejoin="round" |
| 290 |
aria-hidden="true" |
| 291 |
focusable="false" |
| 292 |
> |
| 293 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 294 |
<circle cx="8" cy="8" r="2" /> |
| 295 |
</svg> |
| 296 |
`}function lE(){return B` |
| 297 |
<svg |
| 298 |
viewBox="0 0 16 16" |
| 299 |
width="14" |
| 300 |
height="14" |
| 301 |
fill="none" |
| 302 |
stroke="currentColor" |
| 303 |
stroke-width="1.5" |
| 304 |
stroke-linecap="round" |
| 305 |
stroke-linejoin="round" |
| 306 |
aria-hidden="true" |
| 307 |
focusable="false" |
| 308 |
> |
| 309 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 310 |
<circle cx="8" cy="8" r="2" /> |
| 311 |
<line x1="2" y1="2" x2="14" y2="14" /> |
| 312 |
</svg> |
| 313 |
`}async function cE(t){const e={file:t.file,mime:t.mime,fields:t.fields},n=q(pe.BEFORE_UPLOAD,e,t.context);if(!n)throw new Zu;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",t.mediaUrl,!0),a.withCredentials=!0,a.setRequestHeader("X-WP-Nonce",t.restNonce),a.responseType="text";let d=!1,l=!1,c=!1;const u=()=>{if(c=!0,!l){d=!0;try{a.abort()}catch{}}};C(pe.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:t.context,abort:u}),a.upload.addEventListener("progress",p=>{C(pe.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:t.context,loaded:p.loaded,total:p.lengthComputable?p.total:0,indeterminate:!p.lengthComputable})}),a.upload.addEventListener("load",()=>{l=!0,C(pe.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:t.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.");C(pe.UPLOAD_FAILED,{file:n.file,error:p,context:t.context}),r(p)}),a.addEventListener("abort",()=>{const p=new Ir;C(pe.UPLOAD_FAILED,{file:n.file,error:p,context:t.context}),r(p)}),a.addEventListener("load",()=>{if(d)return;if(a.status<200||a.status>=300){const g=pE(a),m=new Error(g);C(pe.UPLOAD_FAILED,{file:n.file,error:m,context:t.context}),r(m);return}let p;try{p=JSON.parse(a.responseText)}catch(g){const m=g instanceof Error?g:new Error("Could not parse server response.");C(pe.UPLOAD_FAILED,{file:n.file,error:m,context:t.context}),r(m);return}if(c&&p.id){uE(t.mediaUrl,t.restNonce,p.id);const g=new Ir;C(pe.UPLOAD_FAILED,{file:n.file,error:g,context:t.context}),r(g);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};C(pe.AFTER_UPLOAD,{file:n.file,result:f,fields:n.fields,context:t.context}),i(f)}),a.send(o)})}class Zu extends Error{constructor(){super("Upload cancelled by desktop-mode.drop.before-upload filter."),this.name="UploadCancelledError"}}class Ir extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function uE(t,e,n){const o=`${t.replace(/\/$/,"")}/${n}?force=true`,s=new XMLHttpRequest;return s.open("DELETE",o,!0),s.withCredentials=!0,s.setRequestHeader("X-WP-Nonce",e),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 pE(t){const e=`Upload failed (HTTP ${t.status}).`,n=t.responseText;if(!n)return e;try{const o=JSON.parse(n);if(o&&typeof o.message=="string")return o.message}catch{}return e}async function fE(t){if(t.entries.length===0)return;const e=document.createElement("wpd-modal");e.setAttribute("open",""),e.setAttribute("size","md"),e.setAttribute("title",t.entries.length===1?"Upload to Media Library":`Upload ${t.entries.length} files to Media Library`),document.body.appendChild(e);const n=t.entries.map(r=>({...r.fields})),o=()=>{e.innerHTML="";const r=document.createElement("div");r.style.cssText="display:flex;flex-direction:column;gap:18px;max-height:60vh;overflow:auto;padding-right:6px;",t.entries.forEach((c,u)=>{r.appendChild(s(c,n[u],u+1))}),e.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",()=>{e.remove()});const l=document.createElement("wpd-button");l.setAttribute("variant","primary"),l.textContent=t.entries.length===1?"Upload":`Upload ${t.entries.length} files`,l.addEventListener("click",()=>{i(l,d)}),a.appendChild(d),a.appendChild(l),e.appendChild(a)},s=(r,a,d)=>{const l=document.createElement("div");l.style.cssText="display:flex;flex-direction:column;gap:8px;border:1px solid rgba(255,255,255,0.08);border-radius:10px;padding:14px;";const c=document.createElement("div");c.style.cssText="display:flex;gap:10px;align-items:center;font-weight:600;";const u=document.createElement("span");u.textContent=t.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"} · ${ns(r.file.size)}`,f.style.cssText="opacity:0.6;font-size:12px;",c.appendChild(u),c.appendChild(p),c.appendChild(f),l.appendChild(c),l.appendChild(ss("Title",a.title,g=>a.title=g)),l.appendChild(ss("Filename",a.filename,g=>a.filename=g)),r.mime.startsWith("image/")&&l.appendChild(ss("Alt text",a.altText,g=>a.altText=g)),l.appendChild(ss("Caption",a.caption,g=>a.caption=g)),l.appendChild(mE("Description",a.description,g=>a.description=g)),l},i=async(r,a)=>{r.disabled=!0,a.disabled=!0,r.textContent="Uploading…";const d=t.entries.length;let l=0,c=0,u=0;const p=[];for(let f=0;f<d;f++){const g=t.entries[f];try{await cE({file:g.file,mime:g.mime,fields:n[f],context:t.context,mediaUrl:t.mediaUrl,restNonce:t.restNonce}),l++}catch(m){if(m instanceof Zu){u++;continue}if(m instanceof Ir){u++;continue}c++;const h=m instanceof Error?m.message:"Upload failed.";p.push(`“${g.file.name}” — ${h}`)}}e.remove(),hE({total:d,successes:l,failures:c,cancelled:u,failureDetails:p})};o(),await new Promise(r=>{e.addEventListener("wpd-modal-cancel",()=>{e.remove(),r()});const a=new MutationObserver(()=>{e.isConnected||(a.disconnect(),r())});a.observe(document.body,{childList:!0,subtree:!0})})}function ss(t,e,n){const o=document.createElement("wpd-text-field");return o.setAttribute("label",t),o.setAttribute("value",e),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function mE(t,e,n){const o=document.createElement("wpd-textarea");return o.setAttribute("label",t),o.setAttribute("value",e),o.setAttribute("rows","3"),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function hE(t){const{total:e,successes:n,failures:o,cancelled:s,failureDetails:i}=t;if(e===0)return;if(e===1){n===1?J({message:"Uploaded to Media Library."}):o===1&&i[0]?J({message:i[0]}):s===1&&J({message:"Upload cancelled."});return}if(n===e){J({message:`Uploaded ${n} files to Media Library.`});return}if(s===e){J({message:"All uploads cancelled."});return}if(o===e){J({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}.`),J({message:r.join(" ")})}const wE=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:fE},Symbol.toStringTag,{value:"Module"}));return ds.clampGeometryToViewport=lc,Object.defineProperty(ds,Symbol.toStringTag,{value:"Module"}),ds}({}); |
| 314 |
|