| 1 |
var desktopMode=function(di){"use strict";var li=typeof document<"u"?document.currentScript:null;function Uh(){const e=window;e.wp=e.wp??{};const t=e.wp;t.desktop||(t.desktop={});const n=t.desktop;if(n.myWordpress)return;const o=[],s={registerEntityKind:(i,r)=>{const a={unregister:null},d={kind:i,renderer:r,slot:a};return o.push(d),()=>{if(a.unregister){a.unregister(),a.unregister=null;return}const l=o.indexOf(d);l!==-1&&o.splice(l,1)}},__pendingKinds:o};n.myWordpress=s}Uh();function gt(){const e=window.wp?.hooks;if(!e)throw new Error("[desktop-mode] `window.wp.hooks` is not available. The plugin declares `wp-hooks` as a script dependency; if you are seeing this error, verify the enqueue order.");return e}function gn(e,t,n,o){gt().addFilter(e,t,n,o)}function G(e,t,n,o){gt().addAction(e,t,n,o)}function wd(e,t){return gt().removeAction(e,t)}function j(e,t,...n){return gt().applyFilters(e,t,...n)}function T(e,...t){gt().doAction(e,...t)}function gd(e){return gt().didAction(e)}function Fh(){return gt()}const y={INIT:"desktop-mode.init",WALLPAPERS:"desktop-mode.wallpapers",GAMES:"desktop-mode.games",UNFOCUS_EFFECTS:"desktop-mode.unfocus-effects",WALLPAPER_MOUNTING:"desktop-mode.wallpaper.mounting",WALLPAPER_MOUNTED:"desktop-mode.wallpaper.mounted",WALLPAPER_UNMOUNTING:"desktop-mode.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"desktop-mode.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"desktop-mode.wallpaper.visibility",WALLPAPER_SUSPEND:"desktop-mode.wallpaper.suspend",WALLPAPER_PREVIEW_PARAMS:"desktop-mode.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"desktop-mode.wallpaper.settings-changed",IFRAME_READY:"desktop-mode.iframe.ready",IFRAME_ERROR:"desktop-mode.iframe.error",IFRAME_NETWORK_COMPLETED:"desktop-mode.iframe.network-completed",SHELL_ERROR:"desktop-mode.shell.error",BROADCAST:"desktop-mode.broadcast",MONITOR_ENTRY:"desktop-mode.monitor.entry",WALLPAPER_SURFACES:"desktop-mode.wallpaper.surfaces",WINDOW_GEOMETRY:"desktop-mode.window.geometry",WINDOW_OPENED:"desktop-mode.window.opened",WINDOW_CONTENT_LOADING:"desktop-mode.window.content-loading",WINDOW_CONTENT_LOADED:"desktop-mode.window.content-loaded",WINDOW_LOADING_OVERLAY:"desktop-mode.window.loading-overlay",WINDOW_REOPENED:"desktop-mode.window.reopened",WINDOW_CLOSING:"desktop-mode.window.closing",WINDOW_CLOSED:"desktop-mode.window.closed",WINDOW_FOCUSED:"desktop-mode.window.focused",WINDOW_BLURRED:"desktop-mode.window.blurred",WINDOW_MINIMIZED:"desktop-mode.window.minimized",WINDOW_RESTORED:"desktop-mode.window.restored",WINDOW_MAXIMIZED:"desktop-mode.window.maximized",WINDOW_UNMAXIMIZED:"desktop-mode.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"desktop-mode.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"desktop-mode.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"desktop-mode.window.auto-exit-fullscreen",WINDOW_FOCUS_ON_DRAG_HOVER:"desktop-mode.window.focus-on-drag-hover",WINDOW_BOUNDS_CHANGED:"desktop-mode.window.bounds-changed",WINDOW_MOVED:"desktop-mode.window.moved",WINDOW_RESIZED:"desktop-mode.window.resized",WINDOW_DRAG_START:"desktop-mode.window.drag-start",WINDOW_DRAG_END:"desktop-mode.window.drag-end",WINDOW_RESIZE_START:"desktop-mode.window.resize-start",WINDOW_RESIZE_END:"desktop-mode.window.resize-end",WINDOW_DETACHED:"desktop-mode.window.detached",WINDOW_RELOADED:"desktop-mode.window.reloaded",WINDOW_TITLE_CHANGED:"desktop-mode.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"desktop-mode.window.highlight-changed",WINDOW_BODY_RESIZED:"desktop-mode.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"desktop-mode.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"desktop-mode.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"desktop-mode.native-window.before-close",WINDOW_CHROME_THEME:"desktop-mode.window.chrome.theme",WINDOW_CHROME_CONTROLS:"desktop-mode.window.chrome.controls",WINDOW_CHROME_SLOT:"desktop-mode.window.chrome.slot",WINDOW_CHROME_RENDER:"desktop-mode.window.chrome.render",WINDOW_CHROME_APPLIED:"desktop-mode.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"desktop-mode.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"desktop-mode.desktop-icon.clicked",DESKTOP_ICONS_RENDERED:"desktop-mode.desktop-icons.rendered",ICON_BADGE_CHANGED:"desktop-mode.icon.badge-changed",COMPONENTS_REGISTERED:"desktop-mode.components.registered",DOCK_ITEM_APPENDED:"desktop-mode.dock.item-appended",DOCK_ITEM_REMOVED:"desktop-mode.dock.item-removed",DOCK_BEFORE_RENDER:"desktop-mode.dock.before-render",DOCK_AFTER_RENDER:"desktop-mode.dock.after-render",DOCK_TILE_CLASS:"desktop-mode.dock.tile-class",DOCK_TILE_ELEMENT:"desktop-mode.dock.tile-element",DOCK_TILE_RENDERED:"desktop-mode.dock.tile-rendered",DOCK_TILE_TOOLTIP:"desktop-mode.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"desktop-mode.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"desktop-mode.dock.peek-card-element",OVERVIEW_ENTERING:"desktop-mode.overview.entering",OVERVIEW_ENTERED:"desktop-mode.overview.entered",OVERVIEW_EXITING:"desktop-mode.overview.exiting",OVERVIEW_EXITED:"desktop-mode.overview.exited",OVERVIEW_WINDOW_HOVER:"desktop-mode.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"desktop-mode.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"desktop-mode.overview.window-click",ARRANGE_CASCADE_STARTING:"desktop-mode.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"desktop-mode.arrange.cascade.applied",ARRANGE_TILE_STARTING:"desktop-mode.arrange.tile.starting",ARRANGE_TILE_APPLIED:"desktop-mode.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"desktop-mode.arrange.tile.dimensions",ARRANGE_SNAP_CHANGED:"desktop-mode.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"desktop-mode.arrange.snap.cell-size",ARRANGE_CUSTOM_ACTION:"desktop-mode.arrange.custom-action",SNAP_ZONE_PENDING:"desktop-mode.snap.zone-pending",SNAP_ZONE_CANCELED:"desktop-mode.snap.zone-canceled",SNAP_ZONE_COMMITTED:"desktop-mode.snap.zone-committed",SNAP_SPLIT_FILLED:"desktop-mode.snap.split-filled",WIDGETS:"desktop-mode.widgets",WIDGET_MOUNTING:"desktop-mode.widget.mounting",WIDGET_MOUNTED:"desktop-mode.widget.mounted",WIDGET_UNMOUNTING:"desktop-mode.widget.unmounting",WIDGET_MOUNT_FAILED:"desktop-mode.widget.mount-failed",WIDGET_ADDED:"desktop-mode.widget.added",WIDGET_REMOVED:"desktop-mode.widget.removed",DESKTOP_CREATED:"desktop-mode.desktop.created",DESKTOP_CLOSED:"desktop-mode.desktop.closed",DESKTOP_SWITCHED:"desktop-mode.desktop.switched",PRIMARY_DESKTOP_ID:"desktop-mode.primary-desktop-id",WINDOWS_BEFORE_CLOSE_ALL:"desktop-mode.windows.before-close-all",WINDOWS_CLOSE_ALL:"desktop-mode.windows.close-all",WINDOWS_AFTER_CLOSE_ALL:"desktop-mode.windows.after-close-all",COMMAND_BEFORE_RUN:"desktop-mode.command.before-run",COMMAND_AFTER_RUN:"desktop-mode.command.after-run",COMMAND_ERROR:"desktop-mode.command.error",SHELL_RESIZED:"desktop-mode.shell.resized",SHELL_VISIBILITY:"desktop-mode.shell.visibility",CONNECTION_OPENED:"desktop-mode.connection.opened",CONNECTION_CLOSED:"desktop-mode.connection.closed",CONNECTION_MESSAGE:"desktop-mode.connection.message",IFRAME_CONNECTION_REQUEST:"desktop-mode.iframe.connection-request",WINDOW_CONTENT_CHANGED:"desktop-mode.window-links.content-changed",WINDOW_LINK_GROUPS_CHANGED:"desktop-mode.window-links.groups-changed",WINDOW_LINKS_CONTENT:"desktop-mode.window-links.content",WINDOW_LINK_GROUPS:"desktop-mode.window-links.groups",WINDOW_LINK_EDGES:"desktop-mode.window-links.edges",RELATED_ENTITIES_ITEMS:"desktop-mode.related-entities.items",WINDOW_LINK_RENDERERS:"desktop-mode.window-links.renderers",WINDOW_LINK_RENDERER:"desktop-mode.window-links.renderer",FILE_DROP_FILES_DETECTED:"desktop-mode.drop.files-detected",FILE_DROP_FILES_REJECTED:"desktop-mode.drop.files-rejected",FILE_DROP_DIALOG_FIELDS:"desktop-mode.drop.dialog-fields",FILE_DROP_BEFORE_UPLOAD:"desktop-mode.drop.before-upload",FILE_DROP_UPLOAD_STARTED:"desktop-mode.drop.upload-started",FILE_DROP_UPLOAD_PROGRESS:"desktop-mode.drop.upload-progress",FILE_DROP_AFTER_UPLOAD:"desktop-mode.drop.after-upload",FILE_DROP_UPLOAD_FAILED:"desktop-mode.drop.upload-failed",AUTH_LOST:"desktop-mode.auth.lost",AUTH_RESTORED:"desktop-mode.auth.restored"};let Hh=0;function yd(e){if(gd(y.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++Hh}`;G(y.INIT,t,e)}function Bh(){return gd(y.INIT)>0}const zh=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"];function bd(e){let t=e;try{t=decodeURIComponent(e)}catch{t=e}return t.replace(/\.php/g,"-php").replace(/[?&=/]/g,"-").replace(/[^a-zA-Z0-9_-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")||"index"}function oe(e,t){let n=null;try{n=new URL(e,t)}catch{n=null}if(n){const s=new URL(t).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams;for(const d of zh){const l=n.searchParams.get(d);l&&r.set(d,l)}const a=r.toString();return bd(a?`${i}?${a}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),bd(o)}function Gh(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function jh(e){e.style.setProperty("--desktop-mode-file-tile-enter-delay",`${(Math.random()*.25).toFixed(3)}s`),e.style.setProperty("--desktop-mode-file-tile-enter-duration",`${(.3+Math.random()*.25).toFixed(3)}s`)}function vd(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("desktop_mode_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function Qo(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("desktop_mode_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.searchParams.delete("_wp_http_referer"),t.searchParams.sort(),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function kd(e){if(typeof e!="string"||e===""||typeof DOMParser>"u")return"";let t;try{t=new DOMParser().parseFromString(e,"image/svg+xml")}catch{return""}const n=t.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||t.getElementsByTagName("parsererror").length>0)return"";const o=new Set(["script","style","foreignobject","iframe","object","embed"]),s=i=>{const r=Array.from(i.children);for(const a of r){if(o.has(a.nodeName.toLowerCase())){a.remove();continue}for(const d of Array.from(a.attributes)){const 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}let Mt=null;function es(){return!!window.desktopModeWindowSystem}function _d(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-window-system="1"]'),s=()=>{if(es()){t();return}n(new Error("[desktop-mode] window-system bundle loaded but did not register `window.desktopModeWindowSystem`."))};if(o){es()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeWindowSystem="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))),document.head.appendChild(i)})}function qh(){return window.desktopModeConfig?.windowSystemBundleUrl??""}function Vh(e){!e||es()||Mt||(Mt=_d(e).catch(t=>{Mt=null,typeof console<"u"&&console.warn("[desktop-mode] window-system preload failed; will retry on first open():",t)}))}async function Kh(e){if(es())return window.desktopModeWindowSystem;if(!e){const t=window.desktopModeWindowSystem;if(t)return t;throw new Error("[desktop-mode] ensureWindowSystemLoaded(): no bundle URL configured and `window.desktopModeWindowSystem` is not pre-registered.")}return Mt||(Mt=_d(e)),await Mt,window.desktopModeWindowSystem}const Xh="wpd-confirm-dialog";let Pt=null;function yn(){return typeof window.customElements<"u"&&!!window.customElements.get(Xh)}function Ed(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-shell-overlays="1"]'),s=()=>{if(yn()){t();return}n(new Error("[desktop-mode] shell-overlays bundle loaded but did not register the overlay components."))};if(o){yn()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeShellOverlays="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(i)})}function Yh(e){!e||yn()||Pt||(Pt=Ed(e).catch(t=>{Pt=null,typeof console<"u"&&console.warn("[desktop-mode] shell-overlays preload failed; will retry on first overlay use:",t)}))}function ci(e){return yn()||!e?Promise.resolve():(Pt||(Pt=Ed(e)),Pt)}function ui(){return window.desktopModeConfig?.shellOverlaysBundleUrl??""}function bn(e,t){const n=ui();if(yn()||!n){t();return}ci(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[desktop-mode] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Sd="desktop-mode";function pi(){return window.wp?.i18n}function S(e,t=Sd){return pi()?.__(e,t)??e}function vn(e,t,n,o=Sd){return pi()?._n(e,t,n,o)??(n===1?e:t)}function ne(e,...t){const n=pi()?.sprintf;if(n)return n(e,...t);let o=0;return e.replace(/%(?:(\d+)\$)?[sd]/g,(s,i)=>{const r=i?Number.parseInt(i,10)-1:o++;return String(t[r]??"")})}function Zh(e,t){if(!e||typeof e!="object")return!1;const n=e.cols,o=e.rows;return typeof n!="number"||typeof o!="number"||!Number.isFinite(n)||!Number.isFinite(o)||n<1||o<1?!1:Math.floor(n)*Math.floor(o)>=t}function Jh(e){if(!e||typeof e!="object")return!1;const t=e.cellWidth,n=e.cellHeight;return typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)?!1:t>0&&n>0}function Qh(e,t,n){if(e<=1)return{cols:1,rows:1};const o=t/Math.max(1,n),s=6;let i={cols:e,rows:1,score:1/0};for(let r=1;r<=Math.min(s,e);r++){const a=Math.min(s,Math.ceil(e/r));if(r*a<e)continue;const d=t/r/Math.max(1,n/a),l=Math.abs(d-o),c=r*a-e,u=l+c*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function fi(e,t,n=0){const o=e.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,d=34,l=(t.width-r*2-a*(s-1))/s,c=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,c-d);return e.map((p,f)=>{const h=f%s,m=Math.floor(f/s),w=t.left+r+h*(l+a),g=t.top+n+r+m*(c+a)+d,k=p.element.offsetWidth,D=p.element.offsetHeight,b=Math.min(l/k,u/D),E=k*b,I=D*b;return{win:p,x:w+(l-E)/2,y:g+(u-I)/2,scale:b}})}const xd=120,Id=["adminmenumain","adminmenuback","desktop-mode-dock","desktop-mode-side-dock","desktop-mode-widgets"];function Cd(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function Ad(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function ew(e){if(e._overviewActive)return;const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);if(t.length>0&&t.every(c=>c.state==="minimized"))for(const c of t)try{c.restore()}catch(u){typeof console<"u"&&console.error("[desktop-mode] enterOverview: window.restore() threw for",c.id,u)}const n=e._stack.filter(c=>c.state!=="minimized"&&c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,T(y.OVERVIEW_ENTERING,{});for(const c of Id){const u=document.getElementById(c);u&&(u.inert=!0)}Cd(!0),Ad(e,!0),e._overviewSnapshot.clear();for(const c of n)e._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=e._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);e._desktop.classList.add("desktop-mode-area--overview"),document.getElementById("desktop-mode-shell")?.classList.add("desktop-mode-shell--overview"),e._overviewTopBar=Ld(e),e._desktop.appendChild(e._overviewTopBar);const d=fi(n,r,xd);e._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 h=hi(c);u.insertAdjacentElement("afterend",h),e._overviewLabels.set(c.win.id,h)}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===e._desktop?{id:"backdrop",element:e._desktop}:null};e._overviewPointerDownHandler=c=>{if(c.button!==0){e._overviewPressTarget=null;return}e._overviewPressTarget=l(c),e._overviewPressTarget&&(c.preventDefault(),c.stopPropagation())},e._overviewPointerUpHandler=c=>{if(c.button!==0)return;const u=e._overviewPressTarget;if(e._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"){yt(e);return}const h=e.getById(u.id);T(y.OVERVIEW_WINDOW_CLICK,{windowId:u.id}),yt(e,h)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){yt(e);return}if(c.key==="Enter"){const p=c.target?.ownerDocument||document;if(p.activeElement&&p.activeElement.tagName==="BUTTON")return;if(c.preventDefault(),e._overviewAddTileFocused){Td(e);return}yt(e)}},e._desktop.addEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._desktop.addEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewClickBlocker=c=>{c.target?.closest(".desktop-mode-overview-top-bar")||(c.stopPropagation(),c.preventDefault())},e._desktop.addEventListener("click",e._overviewClickBlocker,!0),document.addEventListener("keydown",e._overviewKeyHandler),e._lastOverviewHoverId=null,e._overviewMouseHandler=c=>{const p=c.target?.closest(".desktop-mode-window--overview"),f=p?p.id.replace(/^wp-window-/,""):null;f!==e._lastOverviewHoverId&&(e._lastOverviewHoverId&&T(y.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&T(y.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&T(y.OVERVIEW_ENTERED,{})},300)}function tw(e){e._overviewEnterTimeoutId!==null&&(window.clearTimeout(e._overviewEnterTimeoutId),e._overviewEnterTimeoutId=null),e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null)}function Ld(e){const t=document.createElement("div");t.className="desktop-mode-overview-top-bar";const n=document.createElement("div");n.className="desktop-mode-overview-top-bar__list",t.appendChild(n);for(const s of e._desktops)n.appendChild(nw(e,s));const o=document.createElement("button");return o.type="button",o.className="desktop-mode-overview-top-bar__tile desktop-mode-overview-top-bar__tile--add",e._overviewAddTileFocused&&o.classList.add("desktop-mode-overview-top-bar__tile--cursor"),o.setAttribute("aria-label",S("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(),Td(e)}),n.appendChild(o),t}function Td(e){const t=Rd(e);e._overviewAddTileFocused=!1,Nd(e,t.id)}function nw(e,t){const n=document.createElement("div");n.className="desktop-mode-overview-top-bar__tile-wrapper";const o=document.createElement("button");o.type="button",o.className="desktop-mode-overview-top-bar__tile",o.dataset.desktopId=t.id,t.id===e._activeDesktopId&&!e._overviewAddTileFocused&&o.classList.add("desktop-mode-overview-top-bar__tile--active"),o.setAttribute("aria-label",ne(S("Switch to %s"),t.label));const s=document.createElement("span");s.className="desktop-mode-overview-top-bar__tile-preview";const i=e._stack.filter(d=>d.config.desktopId===t.id).length;if(i>0){const d=document.createElement("span");d.className="desktop-mode-overview-top-bar__tile-count",d.textContent=String(i),s.appendChild(d)}o.appendChild(s);const r=document.createElement("span");r.className="desktop-mode-overview-top-bar__tile-label",r.textContent=t.label,o.appendChild(r),o.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),Nd(e,t.id)});const a=document.createElement("button");return a.type="button",a.className="desktop-mode-overview-top-bar__tile-close",a.setAttribute("aria-label",ne(S("Close %s"),t.label)),a.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2.5 2.5l7 7M9.5 2.5l-7 7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),Pd(e,t.id),mi(e)}),n.appendChild(o),n.appendChild(a),n}function mi(e){if(!e._overviewTopBar)return;const t=Ld(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Nd(e,t){Md(e,t),yt(e)}function hi(e){const t=document.createElement("div");t.className="desktop-mode-overview-label",t.dataset.windowId=e.win.id;const n=e.win.element.offsetWidth*e.scale;t.style.left=`${e.x}px`,t.style.top=`${e.y-34}px`,t.style.width=`${n}px`;const o=e.win.config.icon||"dashicons-admin-generic",s=document.createElement("span");s.className=`desktop-mode-overview-label__icon dashicons ${o}`,s.setAttribute("aria-hidden","true"),t.appendChild(s);const i=document.createElement("span");i.className="desktop-mode-overview-label__title",i.textContent=e.win.config.title,t.appendChild(i);const r=e.win.getExternalTabCount();if(r>0){const a=document.createElement("span");a.className="desktop-mode-overview-label__meta",a.textContent=ne(vn("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function yt(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,T(y.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),e._desktop.classList.remove("desktop-mode-area--overview"),document.getElementById("desktop-mode-shell")?.classList.remove("desktop-mode-shell--overview");for(const i of Id){const r=document.getElementById(i);r&&(r.inert=!1)}Cd(!1),Ad(e,!1);for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform)}t&&(e.focus(t),n&&t.maximize());for(const i of e._overviewLabels.values())i.classList.add("desktop-mode-overview-label--out");e._overviewTopBar&&e._overviewTopBar.classList.add("desktop-mode-overview-top-bar--out");const s=280;e._overviewExitTimeoutId=window.setTimeout(()=>{e._overviewExitTimeoutId=null;for(const i of e._stack)i.element.classList.remove("desktop-mode-window--overview");for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),e._overviewTopBar&&(e._overviewTopBar.remove(),e._overviewTopBar=null),e._overviewClickBlocker&&(e._desktop.removeEventListener("click",e._overviewClickBlocker,!0),e._overviewClickBlocker=null),T(y.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},s),e._overviewPointerDownHandler&&(e._desktop.removeEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._overviewPointerDownHandler=null),e._overviewPointerUpHandler&&(e._desktop.removeEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewPointerUpHandler=null),e._overviewPressTarget=null,e._overviewKeyHandler&&(document.removeEventListener("keydown",e._overviewKeyHandler),e._overviewKeyHandler=null),e._overviewMouseHandler&&(e._desktop.removeEventListener("mouseover",e._overviewMouseHandler),e._overviewMouseHandler=null),e._lastOverviewHoverId&&(T(y.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function ow(e){return[...e._desktops]}function Dd(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function sw(e){return Dd(e).id}function Od(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none"}function wi(e){for(const t of e._stack)Od(e,t)}function Rd(e){e._desktopSeq++;const t={id:`desktop-${e._desktopSeq}`,label:ne(S("Desktop %d"),e._desktopSeq)};return e._desktops.push(t),T(y.DESKTOP_CREATED,{desktopId:t.id}),t}function Md(e,t,n){if(t===e._activeDesktopId||!e._desktops.some(s=>s.id===t))return;const o=e._activeDesktopId;if(e._activeDesktopId=t,e._overviewActive)$d(e),mi(e);else{wi(e),n?.direction&&iw(e,n.direction);const s=[...e._stack].reverse().find(i=>i.config.desktopId===t&&i.state!=="minimized");s&&e.focus(s)}T(y.DESKTOP_SWITCHED,{from:o,to:t})}function iw(e,t){const n=e._desktop,o=t==="next"?"desktop-mode-area--sliding-from-right":"desktop-mode-area--sliding-from-left";n.classList.remove("desktop-mode-area--sliding-from-right","desktop-mode-area--sliding-from-left"),n.offsetWidth,n.classList.add(o);const s=i=>{i.animationName.startsWith("desktop-mode-area-slide-from-")&&(n.classList.remove(o),n.removeEventListener("animationend",s))};n.addEventListener("animationend",s)}function Pd(e,t){if(e._desktops.length<=1)return;const n=e._desktops.findIndex(r=>r.id===t);if(n===-1)return;const o=n>0?n-1:1,s=e._desktops[o];for(const r of e._stack)r.config.desktopId===t&&(r.config.desktopId=s.id);e._desktops.splice(n,1),e._activeDesktopId===t&&(e._activeDesktopId=s.id),e._overviewActive?$d(e):wi(e),T(y.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function $d(e){for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform,a.element.style.transition=r.transition,a.element.classList.remove("desktop-mode-window--overview"))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),wi(e);const t=e._stack.filter(i=>i.state!=="minimized"&&i.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const i of t)e._overviewSnapshot.set(i.id,{transform:i.element.style.transform||"",transition:i.element.style.transition||""});const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=fi(t,o,xd);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=hi(i);r.insertAdjacentElement("afterend",l),e._overviewLabels.set(i.win.id,l)}}function rw(e,t,n){if(t.length===0)return;e._desktops=t.map(s=>({...s})),e._activeDesktopId=t.some(s=>s.id===n)?n:t[0].id;let o=0;for(const s of t){const i=s.id.match(/^desktop-(\d+)$/);if(i){const r=parseInt(i[1],10);Number.isFinite(r)&&r>o&&(o=r)}}e._desktopSeq=Math.max(e._desktopSeq,o)}function aw(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;T(y.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=e._desktop.getBoundingClientRect(),o=30,s=30,i=Math.min(Math.round(n.width*.7),1100),r=Math.min(Math.round(n.height*.75),750),a=Math.max(1,Math.floor((n.width-i-o)/s)),d=Math.max(1,Math.floor((n.height-r-o)/s)),l=Math.min(a,d);t.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=e.getFocused();c&&e.focus(c),document.dispatchEvent(new CustomEvent("desktop-mode-window-changed",{detail:{reason:"cascade"}})),T(y.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function dw(e){const t=e._stack.filter(p=>p.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const p of t)p.state==="minimized"&&p.restore(),p.state==="fullscreen"&&p.toggleFullscreen(),p.state==="maximized"&&p.toggleMaximize();const n=e._desktop.getBoundingClientRect(),o=Qh(t.length,n.width,n.height),s=j(y.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=Zh(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;T(y.ARRANGE_TILE_STARTING,{windowCount:t.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);t.forEach((p,f)=>{const h=f%i,m=Math.floor(f/i);p.element.style.left=`${a+h*(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=e.getFocused();u&&e.focus(u),document.dispatchEvent(new CustomEvent("desktop-mode-window-changed",{detail:{reason:"tile"}})),T(y.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}const Wd="desktop-mode-snap-to-grid";function lw(){try{return window.localStorage.getItem(Wd)==="1"}catch{return!1}}function cw(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(Wd,t?"1":"0")}catch{}T(y.ARRANGE_SNAP_CHANGED,{enabled:t})}}function uw(e){if(!e._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const t=e._desktop.getBoundingClientRect(),n=t.width>=t.height?12:8,o={cellWidth:Math.max(40,Math.round(t.width/n)),cellHeight:Math.max(40,Math.round(t.height/Math.round(n*.66)))},s=j(y.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=Jh(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function pw(e,t,n){if(e._splitOverviewActive)return;e._splitOverviewActive=!0,e._splitOverviewAnchor=t,e._splitOverviewZone=n;const o=e._stack.filter(a=>a!==t&&a.state!=="minimized"&&a.config.desktopId===e._activeDesktopId);if(o.length===0){Ud(e);return}e._splitOverviewSnapshot.clear();for(const a of o)e._splitOverviewSnapshot.set(a.id,{transform:a.element.style.transform||"",transition:a.element.style.transition||""});e._desktop.classList.add("desktop-mode-area--split-overview");const s=gw(e,n),i=fi(o,s,0);e._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=hi(a);d.insertAdjacentElement("afterend",u),e._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:e._desktop}:null};e._splitOverviewPointerDown=a=>{if(a.button!==0){e._splitOverviewPressTarget=null;return}e._splitOverviewPressTarget=r(a),e._splitOverviewPressTarget&&(a.preventDefault(),a.stopPropagation())},e._splitOverviewPointerUp=a=>{if(a.button!==0)return;const d=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!d)return;const 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"){kn(e);return}const u=e.getById(d.id);if(!u){kn(e);return}fw(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&kn(e)},e._splitOverviewClickBlocker=a=>{a.stopPropagation(),a.preventDefault()},e._desktop.addEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._desktop.addEventListener("pointerup",e._splitOverviewPointerUp,!0),e._desktop.addEventListener("click",e._splitOverviewClickBlocker,!0),document.addEventListener("keydown",e._splitOverviewKey)}function fw(e,t){const n=e._splitOverviewZone;if(!n){kn(e);return}const o=n==="left"?"right":"left";t.element.style.transform="",t.element.classList.remove("desktop-mode-window--overview"),t.applySnap(o),e._splitOverviewSnapshot.delete(t.id),e.focus(t),T(y.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),kn(e)}function kn(e){if(!e._splitOverviewActive)return;e._splitOverviewActive=!1;for(const[n,o]of e._splitOverviewSnapshot){const s=e.getById(n);s&&(s.element.style.transform=o.transform)}for(const n of e._splitOverviewLabels.values())n.classList.add("desktop-mode-overview-label--out");e._desktop.classList.remove("desktop-mode-area--split-overview"),window.setTimeout(()=>{for(const n of e._stack)e._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("desktop-mode-window--overview");for(const n of e._splitOverviewLabels.values())n.remove();Ud(e)},260),e._splitOverviewPointerDown&&(e._desktop.removeEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._splitOverviewPointerDown=null),e._splitOverviewPointerUp&&(e._desktop.removeEventListener("pointerup",e._splitOverviewPointerUp,!0),e._splitOverviewPointerUp=null),e._splitOverviewClickBlocker&&(e._desktop.removeEventListener("click",e._splitOverviewClickBlocker,!0),e._splitOverviewClickBlocker=null),e._splitOverviewKey&&(document.removeEventListener("keydown",e._splitOverviewKey),e._splitOverviewKey=null),e._splitOverviewPressTarget=null}function Ud(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const Fd=30,mw=260;function hw(e,t){return e<=t.left+Fd?"left":e>=t.right-Fd?"right":null}function ww(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?0:n.width-o,y:0,width:o,height:s}}function gw(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return t==="left"?new DOMRect(o,0,o,s):new DOMRect(0,0,o,s)}function yw(e,t){if(e._snapPendingZone===t&&e._snapPreviewEl)return;if(e._snapPendingZone=t,!e._snapPreviewEl){const o=document.createElement("div");o.className="desktop-mode-snap-preview",o.setAttribute("aria-hidden","true"),e._desktop.appendChild(o),e._snapPreviewEl=o,Promise.resolve().then(()=>{o.classList.add("desktop-mode-snap-preview--visible")})}const n=ww(e,t);e._snapPreviewEl.style.left=`${n.x}px`,e._snapPreviewEl.style.top=`${n.y}px`,e._snapPreviewEl.style.width=`${n.width}px`,e._snapPreviewEl.style.height=`${n.height}px`,e._snapPreviewEl.dataset.zone=t}function gi(e){if(!e._snapPreviewEl){e._snapPendingZone=null;return}const t=e._snapPreviewEl;e._snapPreviewEl=null,e._snapPendingZone=null,t.classList.remove("desktop-mode-snap-preview--visible"),window.setTimeout(()=>{t.remove()},mw)}function bw(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=hw(n,o),i=e._snapPendingZone;s?(yw(e,s),i!==s&&T(y.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(gi(e),T(y.SNAP_ZONE_CANCELED,{windowId:t.id}))}function vw(e,t){const n=e._snapPendingZone;return n?(gi(e),t.state==="normal"&&(t._savedGeometry={x:t.element.offsetLeft,y:t.element.offsetTop,width:t.element.offsetWidth,height:t.element.offsetHeight}),t.applySnap(n),T(y.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{pw(e,t,n)}),!0):!1}function kw(e){e._snapPendingZone&&gi(e)}const Hd="desktop-mode-native-window-geometry",Bd=64,qe=8192;function ts(){try{const e=window.localStorage.getItem(Hd);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function zd(e){try{window.localStorage.setItem(Hd,JSON.stringify(e))}catch{}}function Gd(e){if(!e)return null;const n=ts()[e];if(!n)return null;const o=Number(n.width),s=Number(n.height);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0||s<=0||o>qe||s>qe)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<=qe&&a<=qe;return{width:Math.round(o),height:Math.round(s),...d?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function jd(e,t){if(!e)return;const n=Math.round(Number(t.width)),o=Math.round(Number(t.height));if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0||n>qe||o>qe)return;const s=ts(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,d=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===d||(_n(s,e,{width:n,height:o,...typeof a=="number"&&typeof d=="number"?{x:a,y:d}:{},...r?{state:r}:{}}),En(s))}function qd(e,t){if(!e)return;const n=Math.round(Number(t.x)),o=Math.round(Number(t.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>qe||o>qe)return;const s=ts(),i=s[e];i&&(i.x===n&&i.y===o||(_n(s,e,{...i,x:n,y:o}),En(s)))}function Vd(e,t,n){if(!e)return;const o=ts(),s=o[e];if(!s){if(t===null||!n)return;const i=Math.round(Number(n.width)),r=Math.round(Number(n.height));if(!Number.isFinite(i)||!Number.isFinite(r)||i<=0||r<=0||i>qe||r>qe)return;_n(o,e,{width:i,height:r,state:t}),En(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;_n(o,e,r),En(o);return}s.state!==t&&(_n(o,e,{...s,state:t}),En(o))}function _n(e,t,n){delete e[t],e[t]=n}function En(e){const t=Object.keys(e);if(t.length>Bd){const n={};for(const o of t.slice(-Bd))n[o]=e[o];zd(n);return}zd(e)}const Kd=100,ns=30;class _w{constructor(t){this._stack=[],this.cascadeIndex=0,this._desktops=[{id:"desktop-1",label:"Desktop 1"}],this._activeDesktopId="desktop-1",this._desktopSeq=1,this.onToggleStartupRequested=null,this.desktopResizeObserver=null,this._reflowRestoreTimer=null,this._snapEnabled=lw(),this._overviewActive=!1,this._overviewSnapshot=new Map,this._overviewLabels=new Map,this._overviewPointerDownHandler=null,this._overviewPointerUpHandler=null,this._overviewKeyHandler=null,this._overviewPressTarget=null,this._overviewClickBlocker=null,this._overviewTopBar=null,this._overviewMouseHandler=null,this._lastOverviewHoverId=null,this._overviewAddTileFocused=!1,this._overviewEnterTimeoutId=null,this._overviewExitTimeoutId=null,this._snapPendingZone=null,this._snapPreviewEl=null,this._splitOverviewActive=!1,this._splitOverviewAnchor=null,this._splitOverviewZone=null,this._splitOverviewSnapshot=new Map,this._splitOverviewLabels=new Map,this._splitOverviewPointerDown=null,this._splitOverviewPointerUp=null,this._splitOverviewPressTarget=null,this._splitOverviewClickBlocker=null,this._splitOverviewKey=null,this._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const t=this._desktop.ownerDocument?.activeElement??null;if(!t||t.tagName!=="IFRAME")return;const n=t.closest(".desktop-mode-window");if(!n)return;const o=n.id.replace(/^wp-window-/,""),s=this.getById(o);s&&(this._overviewActive||this.getFocused()!==s&&this.focus(s))},0)})}reflowStatefulWindows(){if(!this._overviewActive){for(const t of this._stack){const n=t.element.parentElement;if(n){if(t.state==="maximized")t.element.classList.add("desktop-mode-window--reflowing"),t.element.style.width=`${n.clientWidth}px`,t.element.style.height=`${n.clientHeight}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("desktop-mode-window--reflowing");const o=Math.floor(n.clientWidth/2),s=n.clientHeight,i=t.state==="snapped-left"?0:o;t.element.style.left=`${i}px`,t.element.style.top="0px",t.element.style.width=`${o}px`,t.element.style.height=`${s}px`}}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const t of this._stack)t.element.classList.remove("desktop-mode-window--reflowing")},140)}}async open(t){if(!t||typeof t!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(t===null?"null":typeof t));if(typeof t.id!="string"||t.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof t.url!="string"||t.url==="")throw new TypeError('windowManager.open(): config.url must be a non-empty string. Pass an admin URL (e.g. "/wp-admin/edit.php") or a hash fragment (e.g. "#my-window") for native windows.');if(typeof t.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=t.baseId||t.id,o=this.getByBaseIdOnActiveDesktop(n);if(o){const i=o.state==="minimized";this.focus(o),i&&o.restore();let r=!1;if(!o.config.native){const d=Qo(t.url);d===Qo(o.getCurrentUrl())||d===Qo(o.config.url||"")||d===Qo(o.config.parentUrl??o.config.url??"")||(r=o.navigateTo(t.url))}const a={windowId:o.id,baseId:n,wasMinimized:i,navigated:r};return document.dispatchEvent(new CustomEvent("desktop-mode-window-reopened",{detail:a})),T(y.WINDOW_REOPENED,a),o}const s=this.getByBaseId(n)?this.nextInstanceId(n):t.id;return this.createWindow({...t,id:s,baseId:n})}async openNew(t){const n=t.baseId||t.id,o=this.nextInstanceId(n),s=40+this.cascadeIndex%8*ns,i=40+this.cascadeIndex%8*ns;return this.createWindow({initialState:"normal",x:s,y:i,...t,id:o,baseId:n})}async createWindow(t){const n=this._desktop.getBoundingClientRect(),o=Math.min(Math.round(n.width*.8),1200),s=Math.min(Math.round(n.height*.8),800),i=40+this.cascadeIndex%8*ns,r=40+this.cascadeIndex%8*ns,a=t.baseId||t.id,d=t.minWidth??320,l=t.minHeight??200,c=typeof t.width=="number",u=typeof t.height=="number",p=typeof t.x=="number",f=typeof t.y=="number",h=typeof t.initialState=="string",m=!c||!u||!h||!p||!f?Gd(a):null,w=t.width??(m?Math.max(m.width,d):o),g=t.height??(m?Math.max(m.height,l):s),k=t.initialState??(m?.state==="maximized"?"maximized":void 0);let D,b;if(m&&typeof m.x=="number"&&typeof m.y=="number"){const U=Math.max(0,n.width-w-12),ee=Math.max(0,n.height-g-12);D=Math.max(12,Math.min(m.x,U)),b=Math.max(12,Math.min(m.y,ee))}const E=t.x??D??i,I=t.y??b??r,O=c||u||p||f||h,v=!!m,N={x:E,y:I,width:w,height:g,state:k};let C;try{C=j(y.WINDOW_GEOMETRY,N,{windowId:t.id,baseId:a,hasSavedGeometry:v,callerPinned:O,desktopRect:{width:n.width,height:n.height}})}catch(M){T(y.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:M}),typeof console<"u"&&console.error(`[desktop-mode] WINDOW_GEOMETRY filter threw for "${t.id}":`,M),C=N}const L=(M,U)=>typeof M=="number"&&Number.isFinite(M)?M:U,A=C&&typeof C=="object"?C:N,R=Math.max(L(A.width,w),d),F=Math.max(L(A.height,g),l),K=L(A.x,E),Y=L(A.y,I),x=A.state??k,$={icon:t.icon||"dashicons-admin-generic",...t,x:K,y:Y,width:R,height:F,minWidth:d,minHeight:l,...x?{initialState:x}:{},baseId:a,desktopId:t.desktopId||this._activeDesktopId};this.cascadeIndex++;const[B]=await Promise.all([Kh(qh()),ci(ui())]),P=B.createWindow($);P.onFocusRequest=M=>this.focus(M),P.onClose=M=>this.remove(M),P.onMinimize=()=>{const M=this._stack.filter(U=>U.state!=="minimized");M.length>0&&this.focus(M[M.length-1])},P.onOpenAnother=M=>{const U=M.config.baseId||M.id;M.config.native&&window.wp?.desktop?.openNewWindow?.(U,{source:"open-another"})||this.openNew({id:U,baseId:U,url:M.config.url||"",title:M.config.title,icon:M.config.icon,submenu:M.config.submenu,multi:!0})},P.onOpenInNewWindow=M=>{const U=M.config.baseId||M.id;if(M.config.native&&window.wp?.desktop?.openNewWindow?.(U,{source:"open-in-new-window"}))return;const ee=M.getCurrentUrl();this.openNew({id:U,baseId:U,url:ee||M.config.url||"",title:M.config.title,icon:M.config.icon,submenu:M.config.submenu,multi:!0})},P.onToggleStartup=M=>{this.onToggleStartupRequested?.(M)},P.snapConfigProvider=()=>this.getSnapConfig(),P.onDragMove=(M,U)=>{bw(this,M,U)},P.onDragEnd=M=>this._snapPendingZone?vw(this,M):(kw(this),!1),this._stack.push(P),this._desktop.appendChild(P.element),Od(this,P),P.hydrateNative(),this.focus(P);const X={windowId:P.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("desktop-mode-window-opened",{detail:X})),T(y.WINDOW_OPENED,X),P}nextInstanceId(t){const n=new Set(this._stack.map(s=>s.id));if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=this._stack.length>0?this._stack[this._stack.length-1]:null,o=this._stack.find(r=>r!==t&&r.isFocused()&&r.isFullscreen());o&&j(y.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:o.id,focusedTo:t.id})&&o.toggleFullscreen();const s=this._stack.indexOf(t);if(s>-1&&this._stack.splice(s,1),this._stack.push(t),this._stack.forEach((r,a)=>{r.setZIndex(Kd+a),r.setFocused(a===this._stack.length-1)}),n&&n!==t&&n.id!==t.id){const r={windowId:n.id,focusedTo:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-blurred",{detail:r})),T(y.WINDOW_BLURRED,r)}const i={windowId:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-focused",{detail:i})),T(y.WINDOW_FOCUSED,i)}raise(t){const n=this.getById(t);if(!n||this._stack.length<2)return;const o=this._stack.indexOf(n);o===-1||o===this._stack.length-1||(this._stack.splice(o,1),this._stack.splice(this._stack.length-1,0,n),this._stack.forEach((s,i)=>{s.setZIndex(Kd+i)}))}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);for(let i=this._stack.length-1;i>=0;i--){const r=this._stack[i];if(!(r.state==="minimized"||(r.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(r);break}}const o={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("desktop-mode-window-closing",{detail:o})),T(y.WINDOW_CLOSING,o);const s={windowId:t.id};document.dispatchEvent(new CustomEvent("desktop-mode-window-closed",{detail:s})),T(y.WINDOW_CLOSED,s)}getById(t){return this._stack.find(n=>n.id===t)}getByBaseId(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===t)return o}}getByBaseIdOnActiveDesktop(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==t)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(t){const n=o=>{if(o===t)return 1;const s=`${t}-`;if(o.startsWith(s)){const i=parseInt(o.slice(s.length),10);return Number.isFinite(i)?i:999}return 999};return this._stack.filter(o=>(o.config.baseId||o.id)===t).sort((o,s)=>n(o.id)-n(s.id))}getAllByBaseIdOnActiveDesktop(t){return this.getAllByBaseId(t).filter(n=>(n.config.desktopId||this._activeDesktopId)===this._activeDesktopId)}getAll(){return[...this._stack]}findByIframeSource(t){if(t)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===t)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(t){const n=this.getById(t);if(!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)return!1;const s=this.getFocused();return!!s&&s.id===t}isActiveByBaseId(t){const n=this.getFocused();return!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId?!1:(n.config.baseId||n.id)===t}getDesktops(){return ow(this)}getActiveDesktop(){return Dd(this)}getActiveDesktopId(){return sw(this)}createDesktop(){return Rd(this)}switchDesktop(t,n){Md(this,t,n)}closeDesktop(t){Pd(this,t)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=j(y.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(d=>!n.has(d.id));T(y.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=j(y.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 T(y.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r}),a}minimizeAll(){const t=[];for(const n of this._stack.slice())if((n.config.desktopId||this._activeDesktopId)===this._activeDesktopId&&n.state!=="minimized")try{n.minimize(),t.push(n)}catch(s){typeof console<"u"&&console.error("[desktop-mode] minimizeAll: window.minimize() threw for",n.id,s)}return t}restoreFrom(t){if(!Array.isArray(t))return;const n=new Set(this._stack);for(const o of t)if(!(!n.has(o)||(o.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)&&o.state==="minimized")try{o.restore()}catch(i){typeof console<"u"&&console.error("[desktop-mode] restoreFrom: window.restore() threw for",o.id,i)}}toggleShowDesktop(){const t=this._stack.filter(o=>(o.config.desktopId||this._activeDesktopId)===this._activeDesktopId);if(t.length===0)return!1;if(t.every(o=>o.state==="minimized")){for(const o of t)try{o.restore()}catch{}return!1}return this.minimizeAll(),!0}cascade(){aw(this)}tile(){dw(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){cw(this,t)}getSnapConfig(){return uw(this)}enterOverview(){ew(this)}exitOverview(t,n=!1){yt(this,t,n)}destroy(){this._overviewActive&&yt(this),tw(this)}getVisibleRects(){return this._stack.map(t=>{const n=t.getSnapshot();return{windowId:t.id,rect:{x:n.x,y:n.y,width:n.width,height:n.height},state:n.state,element:t.element}})}snapshot(){const t=this.getFocused(),o=this._stack.filter(i=>!i.config.native).map(i=>{const r=i.getSnapshot(),a=i.getExternalTabsSnapshot();return{id:i.id,baseId:i.config.baseId||i.id,desktopId:i.config.desktopId||this._activeDesktopId,url:i.getCurrentUrl(),title:i.config.title,icon:i.config.icon,state:r.state,x:r.x,y:r.y,width:r.width,height:r.height,...a.length>0?{externalTabs:a}:{}}}),s=t&&!t.config.native?t.id:"";return{windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Math.floor(Date.now()/1e3)}}seedDesktops(t,n){rw(this,t,n)}}function Ew(e){const t=e.getActiveDesktopId(),n=Array.from(e._desktop.children);return e.getAll().filter(o=>(o.config.desktopId||t)===t).sort((o,s)=>n.indexOf(o.element)-n.indexOf(s.element))}function Xd(e,t){if(e._overviewActive)return;const n=Ew(e);if(n.length<2)return;const o=e.getFocused(),r=((o?n.indexOf(o):-1)+(t==="next"?1:-1)+n.length)%n.length,a=n[r];a.state==="minimized"?a.restore():e.focus(a)}let Yd=!1;function Zd(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;if(!t)return!1;if(t instanceof HTMLIFrameElement||t instanceof HTMLTextAreaElement)return!0;if(t instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(t.type);if(t instanceof HTMLElement&&t.isContentEditable===!0)return!0;const n=t.getAttribute("contenteditable");return n!==null&&n!=="false"}function Sw(e){if(Yd)return;Yd=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(Zd(document)||(n.preventDefault(),Xd(e,n.shiftKey?"prev":"next")))},!0);const t=window.location.origin;window.addEventListener("message",n=>{if(n.origin!==t)return;const o=n.data;!o||o.type!=="desktop-mode-window-switch"||Xd(e,o.direction==="prev"?"prev":"next")})}function Jd(e,t){const n=e.getDesktops();if(n.length<2)return!1;const o=e.getActiveDesktopId(),s=n.findIndex(a=>a.id===o);if(s===-1)return!1;const r=(s+(t==="next"?1:-1)+n.length)%n.length;return r===s?!1:(e.switchDesktop(n[r].id,{direction:t}),!0)}function Qd(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(d=>d.id===e.getActiveDesktopId());if(i===-1)return!1;const a=(i+(t==="next"?1:-1)+o)%o;return a===i?!1:a===s?(e._overviewAddTileFocused=!0,mi(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function xw(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function Iw(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function el(e){return e._overviewActive?(e.exitOverview(),!0):!1}function Cw(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function Aw(e){return Cw(e)?(e.toggleShowDesktop(),!0):!1}let tl=!1;function Lw(e){tl||(tl=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||Zd(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Qd(e,"prev"):Jd(e,"prev");break;case"ArrowRight":n=e._overviewActive?Qd(e,"next"):Jd(e,"next");break;case"ArrowUp":n=el(e)||Aw(e)||xw(e);break;case"ArrowDown":n=el(e)||Iw(e);break}n&&t.preventDefault()},!0))}function os(e){if(!e)return 214;let t=5381;for(let n=0;n<e.length;n++)t=Math.imul(t,33)+e.charCodeAt(n);return(t%360+360)%360}function yi(e,t){const n=t.className??"",o=t.title??"";if(typeof e=="string"&&e.startsWith("dashicons-")){const a=document.createElement("span");return a.className=`dashicons ${e} ${n}`.trim(),a.setAttribute("aria-hidden","true"),a}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const a=e.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(a)){const d=document.createElement("span");return d.className=n,d.setAttribute("aria-hidden","true"),d.style.backgroundImage=`url("${e}")`,d.style.backgroundRepeat="no-repeat",d.style.backgroundPosition="center",d.style.backgroundSize="contain",d.style.display="inline-block",d}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const a=e.indexOf(","),d=a>=0?e.slice(a+1):"";if(/^[A-Za-z0-9+/=]+$/.test(d))return nl(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return nl(e,n);const s=document.createElement("span");s.className=`${n} desktop-mode-icon-letter`.trim(),s.setAttribute("aria-hidden","true");const i=Tw(o);s.textContent=i;const r=os(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 nl(e,t){const n=document.createElement("img");return n.className=t,n.src=e,n.alt="",n.setAttribute("aria-hidden","true"),n.draggable=!1,n}function Tw(e){const t=(e??"").trim();if(t==="")return"?";const n=t.split(/\s+/);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();const o=n[0];return o.length>=2?o.slice(0,2).toUpperCase():o.toUpperCase()}const ol=new Map,Nw=new Map;function bi(e,t,n,o){let s=e.get(t);if(!s){if(!o)return;s=new Map,e.set(t,s)}let i=s.get(n);if(!i){if(!o)return;i=new Set,s.set(n,i)}return i}function sl(e,t,n,o){const s={channel:n,windowId:t},i=bi(e,t,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(d){typeof console<"u"&&console.error(`[desktop-mode] window-channel subscriber for "${n}" threw:`,d)}const r=bi(e,t,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(d){typeof console<"u"&&console.error(`[desktop-mode] window-channel wildcard subscriber for "${t}" threw:`,d)}}function Dw(e,t,n){const o=bi(ol,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function Ow(e,t,n){sl(ol,e,t,n)}function Rw(e,t,n){sl(Nw,e,t,n)}const il=new Set,Mw=new Set,rl=new Map;function Pw(e){if(!il.has(e)){il.add(e);const t=rl.get(e);if(t){rl.delete(e);for(const n of t)try{n.flush()}catch(o){typeof console<"u"&&console.error(`[desktop-mode] flushing queued window-send for "${n.channel}" threw:`,o)}}}Mw.delete(e)&&(T(y.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("desktop-mode-window-content-loaded",{detail:{windowId:e}})))}const $w=Symbol.for("desktop-mode/window-config");function Ww(e){return e[$w]}function al(){const e=document.createElement("div");e.className="desktop-mode-window__loading",e.setAttribute("aria-hidden","true");const t=document.createElement("wpd-spinner");return t.setAttribute("preset","classic"),t.setAttribute("size","clamp(96px, 14vw, 192px)"),t.setAttribute("label",S("Loading window content")),e.appendChild(t),e}function Uw(e){let t=al();const n={windowId:e.id,config:e};if(typeof e.loading?.render=="function")try{e.loading.render(t,n)}catch(o){typeof console<"u"&&console.error(`[desktop-mode] loading.render threw for "${e.id}":`,o)}try{const o=j(y.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[desktop-mode] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains("desktop-mode-window__loading")&&t.classList.add("desktop-mode-window__loading"),t}function Fw(e){e.querySelector(":scope .desktop-mode-window__loading")?.remove()}function dl(e){const t=e.querySelector(":scope .desktop-mode-window__body");if(!t||t.querySelector(":scope .desktop-mode-window__loading"))return;const o=Ww(e);t.appendChild(o?Uw(o):al())}const Hw=250;let ll=!1;function cl(e){return e?document.getElementById(`wp-window-${e}`):null}function Bw(){ll||(ll=!0,zw())}function zw(){G(y.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=cl(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .desktop-mode-window__body");n&&(n.classList.add("desktop-mode-window__body--loading"),dl(t))}),G(y.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=cl(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .desktop-mode-window__body");n&&(n.classList.remove("desktop-mode-window__body--loading"),window.setTimeout(()=>{n.classList.contains("desktop-mode-window__body--loading")||Fw(t)},Hw))}),G(y.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>ul())})}function ul(){document.querySelectorAll(".desktop-mode-window__body--loading").forEach(t=>{const n=t.closest(".desktop-mode-window");n&&(t.querySelector(":scope .desktop-mode-window__loading")?.remove(),dl(n))})}const pl="__desktopModeSharedStores";function Gw(){const e=window;let t=e[pl];return t||(t=new Map,e[pl]=t),t}function re(e,t){const n=Gw();let o=n.get(e);o||(o={state:t(),listeners:new Set,rebuild:t},n.set(e,o));const s={get state(){return o.state},set state(i){o.state=i},getState(){return o.state},notify(){for(const i of Array.from(o.listeners))try{i(o.state)}catch(r){console.error(`[desktop-mode/shared-store:${e}] subscriber threw:`,r)}},subscribe(i){return o.listeners.add(i),()=>{o.listeners.delete(i)}},setState(i){const r=o.state;if(typeof r!="object"||r===null){console.warn(`[desktop-mode/shared-store:${e}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(r,i),s.notify()},reset(){const i=o.rebuild(),r=o.state;if(typeof r=="object"&&r!==null&&typeof i=="object"&&i!==null){const a=r;for(const d of Object.keys(a))delete a[d];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}const Sn=re("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function jw(e){Sn.state.deps=e}function $t(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.nativeWindowId!="string"||e.nativeWindowId==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=Sn.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>qw(e.id)}function qw(e){const t=Sn.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function vi(e){const{deps:t,remaps:n}=Sn.state;if(!t||!e)return null;let o;try{o=new URL(e,t.adminUrl)}catch{return null}const s=t.getSnapshot();for(const i of n)if(i.matches(e,o)&&!(i.enabled&&!i.enabled(s)))return i.nativeWindowId;return null}function dt(e){const{deps:t,remaps:n}=Sn.state;if(!t||!e)return!1;let o;try{o=new URL(e,t.adminUrl)}catch{return!1}const s=t.getSnapshot();for(const i of n)if(i.matches(e,o)&&!(i.enabled&&!i.enabled(s))){if(i.onMatch)try{i.onMatch(e,o)}catch(r){console.warn(`[desktop-mode] URL remap onMatch hook threw for "${i.id}":`,r)}if(t.openById(i.nativeWindowId))return!0}return!1}const Vw="desktop-mode.activity.";function ki(e){return`${Vw}${String(e)}`}let Kw=0;const ve={publish(e,t){T(ki(e),t)},subscribe(e,t){const n=`desktop-mode/activity-sub/${++Kw}`,o=ki(e);G(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,wd(o,n))}},filter(e,t,...n){return j(ki(e),t,...n)}},Xw=4e3,Yw=200;function q(e){const t=ve.filter("desktop-mode/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return bn(()=>!n,()=>{o=Zw(t)}),()=>{n=!0,o&&o()}}function Zw(e){const t=Jw(),n=document.createElement("wpd-toast");n.textContent=e.message,e.action&&(n.setAttribute("action",e.action.label),n.addEventListener("wpd-toast-action",()=>{e.action?.onClick(),i()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("wpd-toast-dismiss",()=>{e.onDismiss?.(),i()})),t.appendChild(n);let o=!1,s=null;const i=()=>{o||(o=!0,s!==null&&(window.clearTimeout(s),s=null),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove()},Yw))};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),e.persistent||(s=window.setTimeout(i,e.duration??Xw)),ve.publish("desktop-mode/toast-shown",{...e}),i}function Jw(){const e=document.querySelector("wpd-toast-container");if(e)return e;const t=document.createElement("wpd-toast-container");return document.body.appendChild(t),t}const _i=re("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function Qw(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=_i.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>fl(e.id)}function fl(e){const t=_i.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function eg(){return _i.state.entries.slice()}function bt(e,t){if(!e||typeof e!="object")return["def (not an object)"];const n=e,o=[];for(const s of t)s.valid(n)||o.push(`${s.field} (${s.message})`);return o}class tg extends Error{constructor(t,n,o){super(`[desktop-mode] ${t} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=t,this.errors=n,this.def=o}}function De(e,t,n){if(t.length!==0)throw new tg(e,t,n)}function ml(e,t,n){typeof console>"u"||console.warn(`[desktop-mode] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const ng=32,og=64,sg=/^[a-z0-9_/-]+$/,de=re("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function vt(e){return`${e.type}:${e.id}`}function hl(e){return e.root?vt(e.root):vt(e)}function wl(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&sg.test(o.trim().toLowerCase());return bt(e,[{field:"type",valid:o=>n(o.type),message:"must match /^[a-z0-9_/-]+$/ — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-type"},{field:"id",valid:o=>t(o.id),message:"must be a finite number or non-empty string"},{field:"root",valid:o=>o.root===void 0||!!o.root&&typeof o.root=="object"&&n(o.root.type)&&t(o.root.id),message:"when present, must be { type, id } with the same shapes as the ref itself"},{field:"related",valid:o=>o.related===void 0||Array.isArray(o.related)&&o.related.every(s=>!!s&&typeof s=="object"&&typeof s.id=="string"&&s.id.trim()!==""&&typeof s.group=="string"&&s.group.trim()!==""&&typeof s.label=="string"&&s.label.trim()!==""&&typeof s.url=="string"&&s.url.trim()!==""&&(s.groupLabel===void 0||typeof s.groupLabel=="string")&&(s.icon===void 0||typeof s.icon=="string")&&(s.count===void 0||typeof s.count=="number"&&Number.isFinite(s.count))),message:"when present, must be an array of { id, group, label, url, groupLabel?, icon?, count? } entries with non-empty strings"},{field:"links",valid:o=>o.links===void 0||Array.isArray(o.links)&&o.links.every(s=>!!s&&typeof s=="object"&&n(s.type)&&t(s.id)&&(s.rel===void 0||s.rel==="references"||s.rel==="child")),message:"when present, must be an array of { type, id, rel?: 'references'|'child' } entries"}])}function ig(e,t){const n={type:e.type.trim().toLowerCase(),id:e.id,source:t};return e.root&&(n.root={type:e.root.type.trim().toLowerCase(),id:e.root.id}),Array.isArray(e.links)&&e.links.length>0&&(n.links=e.links.slice(0,ng).map(o=>{const s={type:o.type.trim().toLowerCase(),id:o.id};return o.rel==="child"&&(s.rel="child"),s})),typeof e.label=="string"&&e.label!==""&&(n.label=e.label),Array.isArray(e.related)&&e.related.length>0&&(n.related=e.related.slice(0,og).map(o=>{const s={id:o.id,group:o.group,label:o.label,url:o.url};return typeof o.groupLabel=="string"&&o.groupLabel!==""&&(s.groupLabel=o.groupLabel),typeof o.icon=="string"&&o.icon!==""&&(s.icon=o.icon),typeof o.count=="number"&&(s.count=o.count),s})),n}function gl(e){return!e||!e.related?"":e.related.map(t=>`${t.id}\0${t.group}\0${t.label}\0${t.url}\0${t.groupLabel??""}\0${t.icon??""}\0${t.count??""}`).join("|")}function Ei(e){return e?[vt(e),hl(e),...(e.links??[]).map(t=>vt(t)+(t.rel==="child"?"!child":""))].join("|"):""}function ss(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){De("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=wl(t);if(a.length>0){o==="api"&&De("WindowContentRef",a,t),ml("WindowContentRef",a,t);return}s=ig(t,o)}if(s=j(y.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||wl(s).length>0)){ml("WindowContentRef",["filter (desktop-mode.window-links.content returned an invalid ref)"],s);return}const i=de.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&Ei(s)===Ei(i)&&s.label===i.label&&gl(s)===gl(i))return;s===null?de.state.contentByWindow.delete(e):de.state.contentByWindow.set(e,s);const r={windowId:e,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("desktop-mode-window-content-changed",{detail:r})),T(y.WINDOW_CONTENT_CHANGED,r),lg(),ag()}function Si(e){return de.state.contentByWindow.get(e)}function is(){const e=new Map;for(const[s,i]of de.state.contentByWindow){const r=hl(i);let a=e.get(r);a||(a={key:r,root:i.root?{...i.root}:{type:i.type,id:i.id},rootWindowIds:[],children:[]},e.set(r,a)),i.root?a.children.push({windowId:s,content:i}):a.rootWindowIds.push(s)}const t=de.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=j(y.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function yl(e){return is().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function bl(e){const t=new Set,n=yl(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of xn())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function rg(e){const t=new Set;for(const n of xn())n.fromWindowId===e?t.add(n.toWindowId):n.toWindowId===e&&t.add(n.fromWindowId);return t.delete(e),Array.from(t)}function xn(){const e=de.state.focusSeq,t=new Map;for(const[a,d]of de.state.contentByWindow){const l=vt(d),c=t.get(l);(!c||(e.get(a)??0)>(e.get(c)??0))&&t.set(l,a)}const n=new Map,o=(a,d)=>`${a}→${d}`;for(const[a,d]of de.state.contentByWindow){if(d.root){const l=t.get(vt(d.root));l&&l!==a&&n.set(o(a,l),{fromWindowId:a,toWindowId:l,kind:"child-root",bidirectional:!1})}for(const l of d.links??[]){const c=t.get(vt(l));if(!c||c===a)continue;if(l.rel==="child"){const p=o(c,a),f=n.get(p);(!f||f.kind!=="child-root")&&n.set(p,{fromWindowId:c,toWindowId:a,kind:"child-root",bidirectional:!1});continue}const u=o(a,c);n.has(u)||n.set(u,{fromWindowId:a,toWindowId:c,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[a,d]of n){if(i.has(a))continue;const l=o(d.toWindowId,d.fromWindowId),c=n.get(l);if(c&&d.kind==="reference"){if(c.kind==="reference"){i.add(l),s.push({...d,bidirectional:!0});continue}continue}s.push(d)}const r=j(y.WINDOW_LINK_EDGES,s);return Array.isArray(r)?r:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.window-links.edges` filter returned a non-array; falling back to derived edges."),s)}function vl(e){return de.state.listeners.add(e),()=>{de.state.listeners.delete(e)}}function ag(){for(const e of Array.from(de.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[desktop-mode] window-links listener threw:",t)}}function dg(){return Array.from(de.state.contentByWindow).map(([e,t])=>`${e}=${Ei(t)}`).sort().join(";")}function lg(){const e=dg();if(e===de.state.lastGroupsSignature)return;de.state.lastGroupsSignature=e;const n={groups:is()};document.dispatchEvent(new CustomEvent("desktop-mode-window-link-groups-changed",{detail:n})),T(y.WINDOW_LINK_GROUPS_CHANGED,n)}const cg={get:Si,set:(e,t)=>ss(e,t,{source:"api"}),groups:is,edges:xn,groupOf:yl,related:bl,subscribe:vl};function ug({manager:e}){de.state.manager=e,!de.state.started&&(de.state.started=!0,G(y.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=de.state.manager?.getById(t.windowId)?.config?.content;o&&ss(t.windowId,o,{source:"config"})}),G(y.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(de.state.focusSeq.delete(t.windowId),ss(t.windowId,null,{source:"config"}))}),G(y.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(de.state.seq+=1,de.state.focusSeq.set(t.windowId,de.state.seq))}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t.data;if(!n||n.type!=="desktop-mode-content-identity")return;const o=de.state.manager?.findByIframeSource?.(t.source);o&&ss(o.id,n.identity??null,{source:"bridge"})}))}const pg=re("desktop-mode/admin-link-deps",()=>({deps:null}));function fg(e){pg.state.deps=e}const kl=re("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),Wt=kl.state.seed,mg=kl.state.listeners;function In(e){De("Wallpaper",bt(e,xl),e);const t=Wt.findIndex(n=>n.id===e.id);t>=0?Wt[t]=e:Wt.push(e),El()}function _l(e){const t=Wt.findIndex(n=>n.id===e);t>=0&&(Wt.splice(t,1),El())}function El(){const e=Array.from(mg);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] wallpaper registry listener threw:",n)}}function Sl(){const e=Wt.slice(),t=j(y.WALLPAPERS,e);return Array.isArray(t)?t.filter(hg):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.wallpapers` filter returned a non-array; falling back to seed list."),e)}function xi(e){return Sl().find(t=>t.id===e)}const xl=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"preview",message:"missing or not a non-empty string",valid:e=>typeof e.preview=="string"&&e.preview!==""},{field:"type",message:'must be "css" or "canvas"',valid:e=>e.type==="css"||e.type==="canvas"},{field:"value/resolveValue/mount",message:"css types need `value` or `resolveValue`; canvas types need `mount`",valid:e=>e.type==="css"?typeof e.value=="string"||typeof e.resolveValue=="function":e.type==="canvas"?typeof e.mount=="function":!0}];function hg(e){return bt(e,xl).length===0}const Il=re("desktop-mode/wallpaper-settings",()=>({values:{}}));function wg(e){return{...Il.state.values[e]??{}}}function gg(e){const t=Il.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const Cl="desktop-mode-os-settings",yg="custom-gradient",Al="custom-image",Ii="dark",Ll=[{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 Tl(){const t=window.wp?.desktop?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return Ll;const n=[];for(const o of t)o&&typeof o=="object"&&typeof o.id=="string"&&typeof o.label=="string"&&typeof o.value=="string"&&o.id!==""&&o.label!==""&&/^#[0-9a-f]{3,8}$/i.test(o.value)&&n.push({id:o.id,label:o.label,value:o.value});return n.length>0?n:Ll}function Nl(){const t=window.wp?.desktop?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:Ii}const Ci=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],bg=[{id:"classic",label:"Classic"},{id:"unified",label:"Unified"},{id:"spatial",label:"Spatial"}],Q={wallpaper:Ii,accent:"wp-blue",dockSize:"default",desktopLayout:"classic",dockRailRenderer:"default",unfocusEffect:"darken",windowLinkRenderer:"svg-splines",windowLinkVisibility:"always",windowLinksEnabled:!0,windowLinkRaiseOnFocus:!0,windowLinkHighlight:!0,customGradient:{from:"#2271b1",to:"#7c3aed",angle:135},customImage:null,wallpaperSettings:{},libraryHdOnly:!0,ai:{enabled:!1},heartbeatRate:60,nativePostsEnabled:!1,nativePostsHiddenColumns:[],nativePagesEnabled:!1,nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,showDesktopOnWallpaperClick:!1,showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,itemVisibility:{},dockOrder:[],dockPromotedPositions:{}};function Dl(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const Ol="X-WP-Nonce";function Rl(e,t){const n=vg();if(!n)return t;const o=kg(e);if(!o||!_g(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Ol)?t:(i.set(Ol,n),{...t??{},headers:i})}function vg(){if(typeof window>"u")return;const t=window.desktopModeConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function kg(e){try{const t=typeof window<"u"&&window.location?window.location.href:void 0;return typeof e=="string"?new URL(e,t):e instanceof URL?e:typeof Request<"u"&&e instanceof Request?new URL(e.url,t):null}catch{return null}}function _g(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Pe(e,t,n={}){const o=window.wp?.desktop?.fetch;if(typeof o=="function")return o(e,t,n);const s=Rl(e,t);return fetch(e,s)}function Eg(){const e=Sg();if(e){const t=Ml(e);return Li(t),t}try{const t=window.localStorage.getItem(Cl);if(t)return Ml(JSON.parse(t))}catch{}return Rg()}function Sg(){const t=window.desktopModeConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}function Ml(e){const t=Tl();return{wallpaper:typeof e.wallpaper=="string"&&e.wallpaper!==""?e.wallpaper:Nl(),accent:t.some(n=>n.id===e.accent)?e.accent:Q.accent,dockSize:Ci.some(n=>n.id===e.dockSize)?e.dockSize:Q.dockSize,desktopLayout:bg.some(n=>n.id===e.desktopLayout)?e.desktopLayout:Q.desktopLayout,dockRailRenderer:typeof e.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(e.dockRailRenderer)?e.dockRailRenderer:Q.dockRailRenderer,unfocusEffect:typeof e.unfocusEffect=="string"&&/^[a-z0-9_/-]+$/.test(e.unfocusEffect)?e.unfocusEffect:Q.unfocusEffect,windowLinkRenderer:typeof e.windowLinkRenderer=="string"&&/^[a-z0-9_/-]+$/.test(e.windowLinkRenderer)?e.windowLinkRenderer:Q.windowLinkRenderer,windowLinkVisibility:e.windowLinkVisibility==="focus"||e.windowLinkVisibility==="always"||e.windowLinkVisibility==="off"?e.windowLinkVisibility:Q.windowLinkVisibility,windowLinksEnabled:typeof e.windowLinksEnabled=="boolean"?e.windowLinksEnabled:Q.windowLinksEnabled,windowLinkRaiseOnFocus:typeof e.windowLinkRaiseOnFocus=="boolean"?e.windowLinkRaiseOnFocus:Q.windowLinkRaiseOnFocus,windowLinkHighlight:typeof e.windowLinkHighlight=="boolean"?e.windowLinkHighlight:Q.windowLinkHighlight,customGradient:Pg(e.customGradient),customImage:$g(e.customImage),wallpaperSettings:xg(e.wallpaperSettings),libraryHdOnly:typeof e.libraryHdOnly=="boolean"?e.libraryHdOnly:Q.libraryHdOnly,ai:Mg(e.ai),heartbeatRate:e.heartbeatRate===15||e.heartbeatRate===30||e.heartbeatRate===45||e.heartbeatRate===60?e.heartbeatRate:Q.heartbeatRate,nativePostsEnabled:typeof e.nativePostsEnabled=="boolean"?e.nativePostsEnabled:Q.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(e.nativePostsHiddenColumns)?e.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):Q.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof e.nativePagesEnabled=="boolean"?e.nativePagesEnabled:Q.nativePagesEnabled,nativeUsersEnabled:typeof e.nativeUsersEnabled=="boolean"?e.nativeUsersEnabled:Q.nativeUsersEnabled,nativePluginsEnabled:typeof e.nativePluginsEnabled=="boolean"?e.nativePluginsEnabled:Q.nativePluginsEnabled,nativeCommentsEnabled:typeof e.nativeCommentsEnabled=="boolean"?e.nativeCommentsEnabled:Q.nativeCommentsEnabled,showDesktopOnWallpaperClick:typeof e.showDesktopOnWallpaperClick=="boolean"?e.showDesktopOnWallpaperClick:Q.showDesktopOnWallpaperClick,showPostStatusRibbons:typeof e.showPostStatusRibbons=="boolean"?e.showPostStatusRibbons:Q.showPostStatusRibbons,developerModeEnabled:typeof e.developerModeEnabled=="boolean"?e.developerModeEnabled:Q.developerModeEnabled,foldersSharingEnabled:typeof e.foldersSharingEnabled=="boolean"?e.foldersSharingEnabled:Q.foldersSharingEnabled,itemVisibility:Ig(e.itemVisibility),dockOrder:Cg(e.dockOrder),dockPromotedPositions:Ag(e.dockPromotedPositions)}}function xg(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(typeof o!="string"||o===""||!/^[a-z0-9_/-]+$/.test(o)||!s||typeof s!="object"||Array.isArray(s))continue;const i={};let r=0;for(const[a,d]of Object.entries(s)){if(r>=32)break;if(!(typeof a!="string"||a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof d=="boolean")i[a]=d;else if(typeof d=="number"&&Number.isFinite(d))i[a]=d;else if(typeof d=="string")i[a]=d.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function Ig(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=["both","dock","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(e)){if(o>=256)break;if(typeof s!="string"||s===""||typeof i!="string")continue;const r=i;t.includes(r)&&(n[s]=r,o++)}return n}function Cg(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const o of e)if(!(typeof o!="string"||o===""||n.has(o))&&(n.add(o),t.push(o),t.length>=256))break;return t}function Ag(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(typeof s!="string"||s===""||!i||typeof i!="object"||Array.isArray(i))continue;const r=i;typeof r.x!="number"||typeof r.y!="number"||!Number.isFinite(r.x)||!Number.isFinite(r.y)||Math.abs(r.x)>o||Math.abs(r.y)>o||(t[s]={x:r.x,y:r.y},n++)}return t}let rs=null;const Lg=250;let Cn=null;function Tg(e){Cn=Ai(e)}function Ai(e){return{...e,customGradient:{...e.customGradient},customImage:e.customImage?{...e.customImage}:null,wallpaperSettings:Object.fromEntries(Object.entries(e.wallpaperSettings).map(([t,n])=>[t,{...n}])),ai:{...e.ai},nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),itemVisibility:{...e.itemVisibility},dockOrder:e.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function Ng(e,t={}){Li(e),Dg(e,t.windowId)}function Li(e){try{window.localStorage.setItem(Cl,JSON.stringify(e))}catch{}}function Dg(e,t){rs!==null&&clearTimeout(rs),t&&(Ti=t),Ut("pending"),rs=setTimeout(()=>{rs=null;const n=Ti;Ti=null,Og(e,n)},Lg)}let Ti=null;function Og(e,t){const n=window.desktopModeConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Ut("saved");return}Ut("saving");const i=t||"desktop-mode-os-settings";Pe(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:e})},{windowId:i}).then(r=>{if(!r.ok)throw new Error(`${r.status} ${r.statusText}`);Cn=Ai(e),Ut("saved")}).catch(r=>{Cn?(Li(Cn),Ut("failed",r instanceof Error?r.message:String(r),Ai(Cn))):Ut("failed",r instanceof Error?r.message:String(r))})}function Ut(e,t,n){const o={phase:e};t&&(o.error=t),n&&(o.rolledBackTo=n),document.dispatchEvent(new CustomEvent("desktop-mode-os-settings-save-lifecycle",{detail:o}))}function Rg(){return{...Q,customGradient:{...Q.customGradient},customImage:null,wallpaperSettings:{...Q.wallpaperSettings},ai:{...Q.ai},itemVisibility:{...Q.itemVisibility},dockOrder:[...Q.dockOrder],dockPromotedPositions:{...Q.dockPromotedPositions}}}function Mg(e){if(!e||typeof e!="object")return{...Q.ai};const{enabled:t}=e;return{enabled:typeof t=="boolean"?t:Q.ai.enabled}}function Pg(e){if(!e||typeof e!="object")return{...Q.customGradient};const{from:t,to:n,angle:o}=e;return{from:Dl(t)?t:Q.customGradient.from,to:Dl(n)?n:Q.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:Q.customGradient.angle}}function $g(e){if(!e||typeof e!="object")return null;const{id:t,url:n}=e;return typeof t!="number"||!Number.isFinite(t)||t<=0||typeof n!="string"||!/^https?:\/\//i.test(n)?null:{id:t,url:n}}const An=re("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),lt=An.state.registry,Ni=An.state.listeners,Wg=/^[a-z0-9_-]+$/;function Pl(e){if(!e||typeof e!="object")throw new TypeError("[desktop-mode] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!Wg.test(e.id))throw new TypeError(`[desktop-mode] registerDockRailRenderer: id must match /^[a-z0-9_-]+$/, got: ${String(e.id)}`);if(typeof e.label!="string"||e.label==="")throw new TypeError("[desktop-mode] registerDockRailRenderer: label must be a non-empty string.");if(typeof e.mount!="function")throw new TypeError("[desktop-mode] registerDockRailRenderer: mount must be a function.");if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new TypeError(`[desktop-mode] registerDockRailRenderer: unsupported apiVersion ${e.apiVersion} (this shell speaks v1).`);lt.set(e.id,e),as()}function Ug(e){lt.delete(e)&&as()}function Fg(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(lt.entries()))o.owner===e&&(lt.delete(n),t++);return t>0&&as(),t}function Hg(){return Array.from(lt.values())}function Bg(e){return Ni.add(e),()=>{Ni.delete(e)}}function zg(e){An.state.activeId!==e&&(An.state.activeId=e,as())}function Di(){return lt.get(An.state.activeId)??lt.get("default")??lt.values().next().value}function as(){const e=Array.from(Ni);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] dock-rail-renderer listener threw:",n)}}const Gg=180,jg=220,$l=32;function Wl(e){const{tile:t}=e;let n=null,o=null,s=null,i=!1;const r=()=>{o!==null&&(window.clearTimeout(o),o=null)},a=()=>{s!==null&&(window.clearTimeout(s),s=null)},d=()=>{r(),a(),t.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),e.suppressTooltip(!1)},l=f=>{f.pointerType==="mouse"&&qg(e)&&(i=!0,a(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},Gg)))},c=f=>{n&&f.relatedTarget instanceof Node&&n.contains(f.relatedTarget)||(i=!1,r(),u())},u=()=>{a(),s=window.setTimeout(()=>{s=null,!i&&d()},jg)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),n=Vg(e,()=>d()),document.body.appendChild(n),ey(n),ty(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("desktop-mode-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,a()}),n.addEventListener("pointerleave",f=>{f.relatedTarget instanceof Node&&t.contains(f.relatedTarget)||(i=!1,u())})};return t.addEventListener("pointerenter",l),t.addEventListener("pointerleave",c),()=>{t.removeEventListener("pointerenter",l),t.removeEventListener("pointerleave",c),d()}}function qg(e){return e.getInstances().length>=1}function Vg(e,t){const n=document.createElement("div");n.className="desktop-mode-dock-peek",n.setAttribute("role","menu"),n.setAttribute("aria-label",ne(S("%s — open windows"),e.item.title));const o=document.createElement("div");o.className="desktop-mode-dock-peek__cards",n.appendChild(o);const s=e.getInstances();let i=0;for(const r of s){const a=Kg(r,e,i++,t);o.appendChild(a)}if(e.enableGhost!==!1){const r=Yg(e,i,t);o.appendChild(r)}return n}function Ul(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function Kg(e,t,n,o){const s=document.createElement("button");s.type="button",s.setAttribute("role","menuitem"),s.className="desktop-mode-dock-peek__card desktop-mode-dock-peek__card--instance",s.style.setProperty("--peek-card-index",String(n)),s.style.setProperty("--peek-card-delay",`${n*$l}ms`);const i=e.config.title||t.item.title;s.style.setProperty("--peek-card-hue",`${os(e.id||i)}`),s.style.setProperty("--peek-card-vt-name",`desktop-mode-peek-card-${e.id}`);const r=document.createElement("span");r.className="desktop-mode-dock-peek__card-titlebar";const a=document.createElement("span");a.className="desktop-mode-dock-peek__card-dots",a.setAttribute("aria-hidden","true");for(let m=0;m<3;m++)a.appendChild(document.createElement("i"));r.appendChild(a);const d=document.createElement("span");d.className="desktop-mode-dock-peek__card-icon",d.setAttribute("aria-hidden","true");const l=e.config.icon||t.item.icon;l.startsWith("dashicons-")?d.classList.add("dashicons",Gh(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 w=document.createElement("span");w.className="desktop-mode-dock-peek__card-line",u.appendChild(w)}const p={window:e,item:t.item},f=j(y.DOCK_PEEK_CARD_CONTENT,u,p);return f!==u&&f.classList.add("desktop-mode-dock-peek__card-body--custom"),s.appendChild(f),e.state==="minimized"&&(s.dataset.state="minimized"),s.addEventListener("click",()=>{Xg(t,e,s,o)}),s.addEventListener("pointerenter",()=>{e.state==="minimized"?Ul(e,s):t.windowManager.getFocused()!==e&&t.windowManager.focus(e)}),j(y.DOCK_PEEK_CARD_ELEMENT,s,p)}function Xg(e,t,n,o){const s=document,i=`desktop-mode-peek-card-${t.id}`,r=()=>{o(),Ul(t,n),e.windowManager.focus(t)};if(typeof s.startViewTransition!="function"){r();return}const a=t.element;n.style.setProperty("view-transition-name",i),a.style.setProperty("view-transition-name",i);const d=s.startViewTransition(r),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 Yg(e,t,n){const o=document.createElement("button");o.type="button",o.setAttribute("role","menuitem"),o.className="desktop-mode-dock-peek__card desktop-mode-dock-peek__card--ghost",o.style.setProperty("--peek-card-index",String(t)),o.style.setProperty("--peek-card-delay",`${t*$l}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=ne(S("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{Zg(e,n)}),o}function Zg(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const Jg=12,Qg=["--wp-admin-theme-color","--desktop-mode-titlebar-bg","--desktop-mode-titlebar-bg-focused","--desktop-mode-titlebar-color","--desktop-mode-titlebar-color-focused"];function ey(e){const t=document.querySelector(".desktop-mode-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of Qg){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function ty(e,t,n){const o=t.getBoundingClientRect();e.dataset.orientation=n,n==="bottom"?(e.style.left=`${o.left+o.width/2}px`,e.style.top=`${o.top-12}px`):n==="right"?(e.style.top=`${o.top+o.height/2}px`,e.style.left=`${o.left-12}px`):(e.style.top=`${o.top+o.height/2}px`,e.style.left=`${o.right+12}px`),requestAnimationFrame(()=>ny(e))}function ny(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=Jg;let r=0,a=0;n.top<i?r=i-n.top:n.bottom>o-i&&(r=o-i-n.bottom),n.left<i?a=i-n.left:n.right>s-i&&(a=s-i-n.right),!(a===0&&r===0)&&(e.style.setProperty("--peek-clamp-x",`${a}px`),e.style.setProperty("--peek-clamp-y",`${r}px`),e.classList.add("desktop-mode-dock-peek--clamped"))}function ds(e){try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin?!1:(window.open(t.toString(),"_blank","noopener,noreferrer"),!0)}catch{return!1}}function oy(e){return`desktop:${e}`}function sy(e){return`dock:${e}`}function iy(e){return e.startsWith("dock:")?e.slice(5):e.startsWith("desktop:")?e.slice(8):e}function kt(e,t,n){const o=n[e];return o||t}function Fl(e){return e==="dock"||e==="both"}function Hl(e){return e==="desktop"||e==="both"}function ry(e,t,n,o){const s=n.itemVisibility,i=n.dockOrder,r=[];for(const a of e){const d=kt(a.id,"dock",s);Fl(d)&&r.push(a)}for(const a of t){const d=kt(a.id,"desktop",s);Fl(d)&&(a.window&&o&&o.has(a.window)||r.push({id:sy(a.id),title:a.title,icon:a.icon,url:a.url||"",windowId:a.window||void 0,badge:0,submenu:[],isCore:!1}))}return dy(r,i)}function ay(e,t,n){const o=[];for(const i of e){const r=kt(i.id,"desktop",n);Hl(r)&&o.push(i)}let s=0;for(const i of t){const r=kt(i.id,"dock",n);Hl(r)&&o.push({id:oy(i.id),title:i.title,icon:i.icon,window:"",url:i.url||"",position:2e3+s++})}return o}function dy(e,t){if(t.length===0||e.length<=1)return e;const n=new Map;for(const i of e)n.set(i.id,i);const o=[],s=new Set;for(const i of t){const r=n.get(i);r&&(o.push(r),s.add(i))}for(const i of e)s.has(i.id)||o.push(i);return o}function z(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function ly(e){return!!e&&e.__wpdHtml===!0}const cy="$$wpd$$",xe=/\$\$wpd\$\$(\d+)\$\$/g;function uy(e){let t=e[0];for(let n=1;n<e.length;n++)t+=`${cy}${n-1}$$`+e[n];return t}const Bl=new WeakMap;function zl(e){const t=Bl.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=uy(e);const o=[],s=(a,d)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const p of Array.from(u.attributes)){const f=p.name,h=p.value,m=f[0];if(xe.test(h))if(xe.lastIndex=0,m==="@"){const w=xe.exec(h);xe.lastIndex=0,o.push({path:d,kind:"event",name:f.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(f)}else if(m==="."){const w=xe.exec(h);xe.lastIndex=0,o.push({path:d,kind:"prop",name:f.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(f)}else if(m==="?"){const w=xe.exec(h);xe.lastIndex=0,o.push({path:d,kind:"bool",name:f.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(f)}else{const w=[],g=[];let k=0,D;for(xe.lastIndex=0;(D=xe.exec(h))!==null;)w.push(h.slice(k,D.index)),g.push(Number(D[1])),k=D.index+D[0].length;w.push(h.slice(k)),o.push({path:d,kind:"attr",name:f,template:w,valueIndices:g}),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 h=p.textContent||"";if(!xe.test(h)){xe.lastIndex=0;continue}xe.lastIndex=0;const m=p.parentNode;let w=0,g;const k=[],D=[];for(xe.lastIndex=0;(g=xe.exec(h))!==null;){g.index>w&&k.push(document.createTextNode(h.slice(w,g.index)));const b=document.createTextNode("");k.push(b),D.push({path:[...d,f+k.length-1],kind:"node",valueIndex:Number(g[1])}),w=g.index+g[0].length}w<h.length&&k.push(document.createTextNode(h.slice(w)));for(const b of k)m.insertBefore(b,p);m.removeChild(p),c+=k.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 Bl.set(e,r),r}const Gl=new WeakMap;function py(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function fy(e,t){const n=Gl.get(t);if(n&&n.strings===e.strings&&py(n,t)){ls(n.parts,e.values);return}const o=zl(e.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s),ls(i,e.values),Gl.set(t,{strings:e.strings,parts:i,nodes:r})}function ls(e,t){for(const n of e)if(n.kind==="node")Oi(n.child,t[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;s<n.valueIndices.length;s++)o+=jl(t[n.valueIndices[s]]),o+=n.template[s+1];o!==n.last&&(n.last=o,o===""?n.element.removeAttribute(n.name):n.element.setAttribute(n.name,o))}else if(n.kind==="event"){const o=t[n.valueIndex];o!==n.current&&(n.current&&n.element.removeEventListener(n.name,n.current),o&&n.element.addEventListener(n.name,o),n.current=o)}else if(n.kind==="prop"){const o=t[n.valueIndex];o!==n.last&&(n.last=o,n.element[n.name]=o)}else if(n.kind==="bool"){const o=!!t[n.valueIndex];o!==n.last&&(n.last=o,o?n.element.setAttribute(n.name,""):n.element.removeAttribute(n.name))}}function Oi(e,t){if(t==null||t===!1){e.state&&(Ft(e.state),e.state=null);return}if(Array.isArray(t)){gy(e,t);return}if(ly(t)){wy(e,t);return}if(t instanceof Node){my(e,t);return}hy(e,jl(t))}function my(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Ft(n),cs(e,[t]),e.state={shape:"node",node:t})}function hy(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Ft(n);const o=document.createTextNode(t);cs(e,[o]),e.state={shape:"text",node:o,text:t}}function wy(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){ls(n.parts,t.values);return}n&&Ft(n);const o=zl(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);cs(e,[s]),ls(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function gy(e,t){const n=e.state;if(n?.shape==="array"&&n.entries.length===t.length){for(let s=0;s<t.length;s++)Oi(n.entries[s],t[s]);return}n&&Ft(n);const o=[];for(const s of t){const i=document.createTextNode("");cs(e,[i]);const r={anchor:i,state:null};Oi(r,s),o.push(r)}e.state={shape:"array",entries:o}}function cs(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Ft(e){if(e.shape==="text"){e.node.remove();return}if(e.shape==="template"){for(const t of e.nodes)t.parentNode&&t.parentNode.removeChild(t);return}if(e.shape==="node"){e.node.parentNode&&e.node.parentNode.removeChild(e.node);return}for(const t of e.entries)t.state&&Ft(t.state),t.anchor.remove()}function jl(e){return e==null||e===!1?"":String(e)}const wt=class wt 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(ql)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=yy(t);this._propValues[s]=o,this.requestUpdate()}get classNames(){return Array.from(this.classList)}set classNames(t){if(t==null){this.removeAttribute("class");return}const o=(Array.isArray(t)?t:String(t).split(/\s+/)).map(s=>String(s).trim()).filter(s=>s!=="");this.className=o.join(" ")}requestUpdate(){this._scheduleRender()}emit(t,n){return this.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,composed:!0}))}_installPropAccessors(){const t=this.constructor;for(const n of t.props){if(Object.getOwnPropertyDescriptor(this,n))continue;const o=ql(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&&fy(this.render(),this._renderRoot)}))}_adoptStyles(){const t=this.constructor;if(t.styles.length!==0)if(t.shadow&&this.shadowRoot){const n=t.styles.map(o=>o.sheet).filter(o=>o!==null);if(this.shadowRoot.adoptedStyleSheets=n,n.length!==t.styles.length){for(const o of t.styles)if(!o.sheet){const s=document.createElement("style");s.textContent=o.cssText,this.shadowRoot.appendChild(s)}}}else this._adoptLightStyles(t)}_adoptLightStyles(t){if(!wt._lightStylesAdopted.has(t)){wt._lightStylesAdopted.add(t);for(const n of t.styles){const o=document.createElement("style");o.dataset.wpdUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};wt.props=[],wt.styles=[],wt.shadow=!0,wt._lightStylesAdopted=new WeakSet;let me=wt;function we(e,t){customElements.get(e)||customElements.define(e,t)}function ql(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function yy(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const by=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function ge(e,...t){let n=e[0];for(let o=1;o<e.length;o++){const s=t[o-1];if(typeof s=="string"||typeof s=="number")n+=String(s);else if(s&&s.__wpdCss)n+=s.cssText;else throw new TypeError("[wpd-ui] css`` interpolations must be strings, numbers, or other css`` results. Got: "+typeof s);n+=e[o]}if(by){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function vy(e){const t=[],n=[];let o=null,s=e.parentElement;for(;s&&!(s===document.body||s===document.documentElement);){const r=s.id||"";if(r.startsWith("wp-window-")){o=r.slice(10);break}if(s.tagName.toLowerCase()==="wpd-tabpanel"){const a=s.getAttribute("for");a&&n.unshift(a)}s=s.parentElement}o&&t.push(Ri(o));for(const r of n)t.push("tab-"+Ri(r));const i=e.getAttribute("label");return i&&t.push(Ri(i)),t.length===0?"wpd-unnamed":"wpd-"+t.filter(r=>r!=="").join("-")}function Ri(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Vl(e){if(e.id)return e.id;const t=vy(e);return e.id=t,t}const ky=ge`:host{display:none;position:fixed;inset:0;align-items:center;justify-content:center;background:rgba( 0,0,0,0.45 );backdrop-filter:blur( 2px );z-index:10000}:host( [ open ] ){display:flex}.dialog{width:min( 420px,92vw );background:var( --wpd-confirm-dialog-bg,var( --desktop-mode-bg,#1d2327 ) );color:var( --wpd-confirm-dialog-fg,var( --desktop-mode-fg,#fff ) );border:1px solid rgba( 255,255,255,0.08 );border-radius:10px;box-shadow:0 20px 50px rgba( 0,0,0,0.6 );padding:20px 22px 18px;display:flex;flex-direction:column;gap:10px;position:relative}.close{position:absolute;top:8px;right:10px;width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;background:transparent;border:0;border-radius:6px;color:var( --wpd-confirm-dialog-fg-muted,rgba( 255,255,255,0.7 ) );cursor:pointer;font-size:22px;line-height:1;padding:0}.close:hover{background:rgba( 255,255,255,0.08 );color:inherit}.title{margin:0 0 4px;font-size:16px;font-weight:600}.message{margin:0;color:var( --wpd-confirm-dialog-fg-muted,rgba( 255,255,255,0.7 ) );line-height:1.45;white-space:pre-line}.actions{display:flex;justify-content:flex-end;gap:8px;margin-top:6px}.btn{border:0;border-radius:6px;padding:8px 14px;font-size:13px;cursor:pointer;font-weight:500}.btn--secondary{background:rgba( 255,255,255,0.08 );color:inherit}.btn--secondary:hover{background:rgba( 255,255,255,0.14 )}.btn--primary{background:var( --wp-admin-theme-color,#2271b1 );color:#fff}.btn--primary:hover{filter:brightness( 1.08 )}.btn--danger{background:#d63638;color:#fff}.btn--danger:hover{filter:brightness( 1.08 )}`,Ro=class Ro extends me{constructor(){super(...arguments),this._onKey=t=>{t.key==="Escape"&&(t.preventDefault(),this._cancel()),t.key==="Enter"&&!t.isComposing&&(t.preventDefault(),this._confirm())},this._onBackdrop=t=>{const n=t.composedPath();(n.length>0?n[0]:t.target)===this&&this._cancel()},this._confirm=()=>{this.emit("wpd-confirm",{confirmed:!0}),this.removeAttribute("open")},this._cancel=()=>{this.emit("wpd-cancel",{confirmed:!1}),this.removeAttribute("open")}}connectedCallback(){super.connectedCallback(),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","true"),this.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop)}render(){const t=this.title??"",n=this.message??"",o=this["confirm-label"]||"Confirm",s=this["cancel-label"]||"Cancel",i=this.hasAttribute("danger"),r=this.hasAttribute("hide-cancel"),a=this.hasAttribute("dismissable");return z` |
| 2 |
<div class="dialog" tabindex="-1"> |
| 3 |
${a?z`<button |
| 4 |
type="button" |
| 5 |
class="close" |
| 6 |
aria-label="Close" |
| 7 |
@click=${()=>this._cancel()} |
| 8 |
>×</button>`:z``} |
| 9 |
${t?z`<h2 class="title">${t}</h2>`:z``} |
| 10 |
${n?z`<p class="message">${n}</p>`:z``} |
| 11 |
<div class="actions"> |
| 12 |
${r?z``:z`<button |
| 13 |
type="button" |
| 14 |
class="btn btn--secondary" |
| 15 |
@click=${()=>this._cancel()} |
| 16 |
> |
| 17 |
${s} |
| 18 |
</button>`} |
| 19 |
<button |
| 20 |
type="button" |
| 21 |
class="btn ${i?"btn--danger":"btn--primary"}" |
| 22 |
@click=${()=>this._confirm()} |
| 23 |
> |
| 24 |
${o} |
| 25 |
</button> |
| 26 |
</div> |
| 27 |
</div> |
| 28 |
`}};Ro.props=["open","title","message","confirm-label","cancel-label","danger","hide-cancel","dismissable"],Ro.styles=[ky],Ro.help=void 0;let Mi=Ro;we("wpd-confirm-dialog",Mi);function Pi(e){return new Promise(t=>{const n=document.createElement("wpd-confirm-dialog");n.setAttribute("open",""),e.title&&n.setAttribute("title",e.title),n.setAttribute("message",e.message),e.confirmLabel&&n.setAttribute("confirm-label",e.confirmLabel),e.cancelLabel&&n.setAttribute("cancel-label",e.cancelLabel),e.danger&&n.setAttribute("danger",""),e.hideCancel&&n.setAttribute("hide-cancel",""),e.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),t(i)};n.addEventListener("wpd-confirm",()=>o(!0)),n.addEventListener("wpd-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}const _y="http://localhost/";function Ze(e,t){const n=typeof window<"u"&&window.location?window.location.href:_y,o=new URL(e,n),s=t.replace(/^\/+/,""),i=s.indexOf("?"),r=i===-1?s:s.slice(0,i),a=i===-1?"":s.slice(i+1);if(o.searchParams.has("rest_route")){const d=o.searchParams.get("rest_route")??"/",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 Ln(){return window.wp?.desktop??null}let _t=null;function Tn(){_t&&(_t.remove(),_t=null)}function Nn(e,t){const n=Ln();if(!n?.getOsSettings||!n?.updateOsSettings)return;const s={...n.getOsSettings().itemVisibility};s[e]=t,n.updateOsSettings({itemVisibility:s})}function Ey(e,t){return e.startsWith("dock:")?"dock":e.startsWith("desktop:")?"desktop":t}function Kl(e,t,n,o){return kt(e,t,o)==="both"?n==="dock"?"desktop":"dock":"hidden"}let Xl=0;function Yl(e){Tn();const t=++Xl;bn(()=>t===Xl,()=>Sy(e))}function Sy(e){Tn();const t=iy(e.id),n=Ey(e.id,e.surface),o=kt(t,n,Ln()?.getOsSettings?.().itemVisibility??{}),s=[];if(e.surface==="dock"?(s.push({id:"hide-from-dock",label:S("Hide from dock"),icon:"dashicons-hidden",onPick:()=>Nn(t,Kl(t,n,"dock",Ln()?.getOsSettings?.().itemVisibility??{}))}),o!=="both"&&s.push({id:"show-on-desktop-too",label:S("Also show on desktop"),icon:"dashicons-desktop",onPick:()=>Nn(t,"both")})):(s.push({id:"hide-from-desktop",label:S("Hide from desktop"),icon:"dashicons-hidden",onPick:()=>Nn(t,Kl(t,n,"desktop",Ln()?.getOsSettings?.().itemVisibility??{}))}),o!=="both"&&s.push({id:"show-on-dock-too",label:S("Also show on dock"),icon:"dashicons-menu",onPick:()=>Nn(t,"both")})),s.push({id:"hide-everywhere",label:S("Hide everywhere"),icon:"dashicons-no",danger:!0,onPick:()=>Nn(t,"hidden")}),s.push({id:"open-settings",label:S("Apps & Icons settings…"),icon:"dashicons-admin-generic",onPick:()=>{Ln()?.openOsSettings?.({tabId:"apps-icons"})}}),e.pluginFile){const c=e.pluginFile,u=e.pluginName||e.title;s.push({kind:"separator"}),s.push({id:"deactivate-plugin",label:ne(S("Deactivate %s…"),u),icon:"dashicons-trash",danger:!0,onPick:()=>{xy(c,u)}})}const i=document.createElement("wpd-context-menu");i.setAttribute("open",""),i.classList.add("desktop-mode-item-visibility-menu"),i.dataset.itemId=e.id,i.style.position="fixed",i.style.left="-9999px",i.style.top="-9999px",i.style.visibility="hidden",i.style.zIndex="1000000";const r=new Map;for(const c of s){if(c.kind==="separator"){const p=document.createElement("hr");p.style.cssText="border: 0; border-top: 1px solid var( --wpd-context-menu-separator-color, rgba(255,255,255,0.12) ); margin: 4px 6px;",i.appendChild(p);continue}r.set(c.id,c);const u=document.createElement("wpd-context-menu-option");u.dataset.menuItemId=c.id,u.setAttribute("value",c.id),c.icon&&u.setAttribute("icon",c.icon),c.danger&&u.setAttribute("danger",""),u.textContent=c.label,i.appendChild(u)}i.addEventListener("wpd-context-menu-pick",c=>{const u=c.detail,p=u?.id||u?.value||"",f=r.get(p);Tn();try{f?.onPick()}catch{}}),document.body.appendChild(i),_t=i,requestAnimationFrame(()=>{if(i!==_t)return;const c=i.getBoundingClientRect(),u=8;let p=e.x,f;e.surface==="dock"?f=Math.max(u,e.y-c.height-u):(f=e.y,f+c.height+u>window.innerHeight&&(f=Math.max(u,e.y-c.height))),p+c.width+u>window.innerWidth&&(p=Math.max(u,e.x-c.width)),i.style.left=`${p}px`,i.style.top=`${f}px`,i.style.visibility=""});const d=c=>{_t&&(_t.contains(c.target)||(Tn(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",l,!0)))},l=c=>{c.key==="Escape"&&(Tn(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",l,!0))};document.addEventListener("mousedown",d,!0),document.addEventListener("keydown",l,!0)}async function xy(e,t){if(!await Pi({title:ne(S("Deactivate %s?"),t),message:S("This plugin will stop running on the site. You can re-activate it later from the Plugins screen."),confirmLabel:S("Deactivate"),cancelLabel:S("Cancel"),danger:!0}))return;const o=window.desktopModeConfig??{},s=typeof o.restRoot=="string"&&o.restRoot?o.restRoot:`${window.location.origin}/wp-json/`,i=typeof o.restNonce=="string"&&o.restNonce?o.restNonce:"",a=(e.endsWith(".php")?e.slice(0,-4):e).split("/").map(encodeURIComponent).join("/"),d=Ze(s,`wp/v2/plugins/${a}`);try{const p=await Pe(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){q({message:ne(S("Could not deactivate %s."),t),duration:4e3}),console.error("[desktop-mode] deactivate plugin failed",p);return}const l=Iy(e),c=l.length>0?ne(S("%1$s deactivated. Closed %2$d window(s)."),t,l.length):ne(S("%s deactivated."),t);q({message:c,duration:3e3}),window.wp?.desktop?.refreshMenu?.()}function Iy(e){const t=window.wp?.desktop;if(!t?.windowManager?.getAll)return[];const o=(t.getMenuItems?.()??[]).filter(l=>l.pluginFile===e);if(o.length===0)return[];const s=new Set;for(const l of o)s.add(l.id),t.deriveWindowId&&s.add(t.deriveWindowId(l.url));const i=new Map,r=t.windowManager.getAll()??[],a=t.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 Ne=class Ne{constructor(t,n,o,s,i="left"){this.itemElements=new Map,this.systemItems=[],this.systemItemElements=new Map,this.systemSeparator=null,this.badgeOverrides=new Map,this.attentionTimers=new Map,this.peekTeardowns=new Map,this.boundRefresh=()=>{},this.container=t,this.windowManager=n,this.items=o,this.adminUrl=s,this.orientation=i,this.rail=i==="bottom"?"taskbar":"dock",this.hooksNamespace=`desktop-mode/dock/${++Ne.instanceCounter}`,this.container.setAttribute("data-desktop-mode-dock-placement",i);const r=document.createElement("div");r.className="desktop-mode-dock__scroll";const a=document.createElement("div");a.className="desktop-mode-dock__pinned",t.appendChild(r),t.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="desktop-mode-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("desktop-mode-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("desktop-mode-dock__tooltip--before"):this.tooltip.classList.add("desktop-mode-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.render(),this.bindWindowEvents()}buildHookContextBase(){return{rail:this.rail,orientation:this.orientation,dockId:this.container.id,container:this.container}}setOrientation(t){this.orientation!==t&&(this.orientation=t,this.container.setAttribute("data-desktop-mode-dock-placement",t),this.tooltip.classList.remove("desktop-mode-dock__tooltip--above","desktop-mode-dock__tooltip--before","desktop-mode-dock__tooltip--after"),t==="bottom"?this.tooltip.classList.add("desktop-mode-dock__tooltip--above"):t==="right"?this.tooltip.classList.add("desktop-mode-dock__tooltip--before"):this.tooltip.classList.add("desktop-mode-dock__tooltip--after"))}replaceItems(t){for(const i of this.itemElements.keys()){const r=this.peekTeardowns.get(i);r&&(r(),this.peekTeardowns.delete(i))}for(const i of this.itemElements.values())i.remove();this.itemHost.querySelectorAll(".desktop-mode-dock__separator--group").forEach(i=>i.remove()),this.itemElements.clear(),this.items=t;const n=this.buildHookContextBase();T(y.DOCK_BEFORE_RENDER,{...n,items:t,tileElements:this.itemElements});let o=!1,s=0;for(const i of t){if(!o&&i.isCore===!1){if(s>0){const d=document.createElement("div");d.className="desktop-mode-dock__separator desktop-mode-dock__separator--group",d.setAttribute("aria-hidden","true"),this.itemHost.appendChild(d)}o=!0}const r=this.createItemButton(i);this.itemElements.set(i.id,r),this.itemHost.appendChild(r),s++;const a=this.badgeOverrides.get(i.id);if(a!==void 0){const d=r.querySelector(".desktop-mode-dock__item-primary");Zl(d??r,a)}T(y.DOCK_TILE_RENDERED,{...n,item:i,isSystem:!1,el:r})}this.updateActiveStates(),T(y.DOCK_AFTER_RENDER,{...n,items:t,tileElements:this.itemElements})}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(t){const n=this.systemItemElements.get(t);n&&(n.remove(),this.systemItemElements.delete(t),this.systemItems=this.systemItems.filter(o=>o.id!==t),this.badgeOverrides.delete(t),this.systemItemElements.size===0&&this.systemSeparator&&(this.systemSeparator.remove(),this.systemSeparator=null),T(y.DOCK_ITEM_REMOVED,{id:t,placement:this.rail}))}setBadge(t,n){const o=this._resolveTileElement(t);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(t):this.badgeOverrides.set(t,s);const i=o.querySelector(".desktop-mode-dock__item-primary");Zl(i??o,s),ve.publish("desktop-mode/badge-changed",{itemId:t,count:s,rail:this.rail})}clearBadge(t){this.setBadge(t,0)}setAttention(t,n,o={}){const s=this._resolveTileElement(t);if(!s)return;const i=this.attentionTimers.get(t);if(i!==void 0&&(window.clearTimeout(i),this.attentionTimers.delete(t)),s.classList.remove("desktop-mode-dock__item--attention-pulse","desktop-mode-dock__item--attention-shake","desktop-mode-dock__item--attention-bounce","desktop-mode-dock__item--intensity-subtle","desktop-mode-dock__item--intensity-normal","desktop-mode-dock__item--intensity-strong"),n===null)return;s.classList.add(`desktop-mode-dock__item--attention-${n}`);const r=o.intensity??"normal";s.classList.add(`desktop-mode-dock__item--intensity-${r}`);const a=o.durationMs??4e3;if(a>0){const d=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},a);this.attentionTimers.set(t,d)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}appendSystemItem(t){this.systemItems.push(t),this.systemSeparator||(this.systemSeparator=document.createElement("div"),this.systemSeparator.className="desktop-mode-dock__separator",this.systemSeparator.setAttribute("aria-hidden","true"),this.systemHost.appendChild(this.systemSeparator));const n=this.createSystemItemButton(t);this.systemItemElements.set(t.id,n),this.systemHost.appendChild(n),this.updateActiveStates(),T(y.DOCK_TILE_RENDERED,{...this.buildHookContextBase(),item:t,isSystem:!0,el:n})}render(){if(Ne.activeDragReset){const o=Ne.activeDragReset;Ne.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="";const t=this.buildHookContextBase();T(y.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of this.items){if(!n&&o.isCore===!1){if(this.itemHost.childElementCount>0){const i=document.createElement("div");i.className="desktop-mode-dock__separator desktop-mode-dock__separator--group",i.setAttribute("aria-hidden","true"),this.itemHost.appendChild(i)}n=!0}const s=this.createItemButton(o);this.itemElements.set(o.id,s),this.itemHost.appendChild(s),T(y.DOCK_TILE_RENDERED,{...t,item:o,isSystem:!1,el:s})}T(y.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["desktop-mode-dock__item","desktop-mode-dock__item--system"],i=j(y.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id;const r=document.createElement("button");r.className="desktop-mode-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title)),r.addEventListener("click",()=>t.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=Wl({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:""},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(t.id),enableGhost:!!t.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(t.onOpenNew??t.onOpen)()},suppressTooltip:d=>{d&&this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),j(y.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["desktop-mode-dock__item"];t.multi&&s.push("desktop-mode-dock__item--multi");const i=j(y.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="desktop-mode-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const a=this.resolveIcon(t.icon,t.title,t.url);if(r.appendChild(a),t.badge>0){const c=t.badge>99?"99+":String(t.badge),u=document.createElement("span");u.className="desktop-mode-dock__badge",u.textContent=c,u.setAttribute("aria-label",ne(vn("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.addEventListener("contextmenu",c=>{c.preventDefault(),Yl({x:c.clientX,y:c.clientY,id:t.id,title:t.title,surface:"dock",pluginFile:t.pluginFile??null,pluginName:t.pluginName??null})}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const d=this.resolveItemBaseId(t),l=Wl({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(d),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(t),suppressTooltip:c=>{c&&this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}});return this.peekTeardowns.set(t.id,l),this.attachDragReorder(o,t.id),j(y.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n){let i=!1,r=0,a=0,d=[],l=null,c=-1,u=null,p=!1;const f=()=>{i=!1,t.classList.remove("desktop-mode-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",k),document.removeEventListener("pointerup",I),document.removeEventListener("pointercancel",O),document.removeEventListener("keydown",v,!0),window.removeEventListener("blur",N),document.removeEventListener("visibilitychange",C),c=-1,u=null},h=L=>!!L&&L instanceof HTMLElement&&L.classList.contains("desktop-mode-dock__item")&&!L.classList.contains("desktop-mode-dock__item--system")&&!!L.dataset.menuSlug,m=L=>{for(const A of Array.from(this.itemHost.children))A instanceof HTMLElement&&A!==t&&h(A)&&L(A)},w=()=>{const L=[];for(const A of Array.from(this.itemHost.children))h(A)&&L.push(A.dataset.menuSlug);return L},g=L=>{m(A=>{const R=L.get(A);if(!R)return;const F=A.getBoundingClientRect(),K=R.left-F.left,Y=R.top-F.top;if(Math.abs(K)<.5&&Math.abs(Y)<.5)return;A.style.transition="none",A.style.transform=`translate(${K}px, ${Y}px)`,A.offsetHeight,A.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",A.style.transform="";const x=()=>{A.style.transition="",A.style.transform="",A.removeEventListener("transitionend",x)};A.addEventListener("transitionend",x)})},k=L=>{if(c!==-1&&L.pointerId!==c)return;if(!i){const P=L.clientX-r,X=L.clientY-a;if(P*P+X*X<5*5)return;i=!0,d=w(),l=t.nextSibling,u=t.getBoundingClientRect(),t.classList.add("desktop-mode-dock__item--dragging"),this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}if(!u)return;const A=L.clientX-r,R=L.clientY-a;t.style.transform=`translate(${A}px, ${R}px)`;const K=document.elementFromPoint(L.clientX,L.clientY)?.closest(".desktop-mode-dock__item");if(!K||K===t||!h(K))return;const Y=K.getBoundingClientRect();let x;this.orientation==="bottom"?x=L.clientX<Y.left+Y.width/2:x=L.clientY<Y.top+Y.height/2;const $=new Map;m(P=>{$.set(P,P.getBoundingClientRect())});let B=!1;if(x?K!==t.nextSibling&&(this.itemHost.insertBefore(t,K),B=!0):K.nextSibling!==t&&(this.itemHost.insertBefore(t,K.nextSibling),B=!0),B){t.style.transform="";const P=t.getBoundingClientRect();r=P.left+P.width/2,a=P.top+P.height/2,t.style.transform=`translate(${L.clientX-r}px, ${L.clientY-a}px)`,g($)}},D=()=>{t.classList.remove("desktop-mode-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",k),document.removeEventListener("pointerup",I),document.removeEventListener("pointercancel",O),document.removeEventListener("keydown",v,!0),window.removeEventListener("blur",N),document.removeEventListener("visibilitychange",C),c=-1,u=null,i=!1,Ne.activeDragReset===f&&(Ne.activeDragReset=null)},b=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const L=()=>{t.style.transition="",t.removeEventListener("transitionend",L)};t.addEventListener("transitionend",L)},E=L=>{const A=window.wp?.desktop;if(!A?.getOsSettings||!A?.updateOsSettings)return;const R=A.getOsSettings().dockOrder,F=new Set(L),K=[];let Y=!1;for(const x of R){if(F.has(x)){Y||(K.push(...L),Y=!0);continue}K.push(x)}Y||K.push(...L),A.updateOsSettings({dockOrder:K})},I=L=>{if(c!==-1&&L.pointerId!==c)return;if(!i){D();return}p=!0;const A=w();b(),D(),A.length===d.length&&A.every((F,K)=>F===d[K])||E(A),setTimeout(()=>{p=!1},200)},O=L=>{if(!(L&&c!==-1&&L.pointerId!==c)){if(i&&l!==void 0){const A=new Map;m(R=>{A.set(R,R.getBoundingClientRect())}),this.itemHost.insertBefore(t,l),g(A)}b(),D()}},v=L=>{L.key==="Escape"&&O()},N=()=>O(),C=()=>{document.visibilityState!=="visible"&&O()};t.addEventListener("pointerdown",L=>{if(L.button===0){if(Ne.activeDragReset){const A=Ne.activeDragReset;Ne.activeDragReset=null,A()}(i||c!==-1)&&f(),r=L.clientX,a=L.clientY,c=L.pointerId,i=!1,Ne.activeDragReset=f,document.addEventListener("pointermove",k),document.addEventListener("pointerup",I),document.addEventListener("pointercancel",O),document.addEventListener("keydown",v,!0),window.addEventListener("blur",N),document.addEventListener("visibilitychange",C)}}),t.addEventListener("click",L=>{p&&(L.preventDefault(),L.stopImmediatePropagation())},!0)}resolveIcon(t,n,o){if(t.startsWith("dashicons-")&&t!=="dashicons-admin-generic"){const s=document.createElement("span");return s.className=`dashicons ${t}`,s.setAttribute("aria-hidden","true"),s}if(t.startsWith("data:image/svg+xml;base64,")){const s=t.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(s))return this._makeSvgIcon(t)}if(t.startsWith("url("))return this._makeSvgIcon(t);if(t.startsWith("http://")||t.startsWith("https://")){const s=document.createElement("img");return s.className="desktop-mode-dock__item-img",s.src=t,s.alt="",s.setAttribute("aria-hidden","true"),s}if(o){const s=this._extractNativeMenuIcon(o);if(s)return s}if(t==="dashicons-admin-generic"){const s=document.createElement("span");return s.className="dashicons dashicons-admin-generic",s.setAttribute("aria-hidden","true"),s}return this.createLetterBadge(n)}_makeSvgIcon(t){const n=document.createElement("span");return n.className="desktop-mode-dock__item-svg",n.style.backgroundImage=t.startsWith("url(")?t:`url("${t}")`,n.style.backgroundSize="contain",n.style.backgroundRepeat="no-repeat",n.style.backgroundPosition="center",n.setAttribute("aria-hidden","true"),n}_extractNativeMenuIcon(t){const n=document.getElementById("adminmenu");if(!n)return null;let o;try{const p=new URL(t,window.location.href);o=(p.pathname.split("/").pop()||"")+p.search}catch{return null}if(!o)return null;const s=n.querySelectorAll("li.menu-top > a");let i=null;for(const p of Array.from(s))if(p.href.endsWith(o)){i=p.closest("li.menu-top");break}if(!i)return null;const r=i.querySelector(".wp-menu-image");if(!r)return null;const a=r.querySelector("img");if(a&&a.src){const p=document.createElement("img");return p.className="desktop-mode-dock__item-img",p.src=a.src,p.alt="",p.setAttribute("aria-hidden","true"),p}const d=r.className.match(/\bdashicons-[\w-]+\b/);if(d&&d[0]!=="dashicons-before"){const p=document.createElement("span");return p.className=`dashicons ${d[0]}`,p.setAttribute("aria-hidden","true"),p}const 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(t){const n=document.createElement("span");n.className="desktop-mode-dock__item-letter",n.setAttribute("aria-hidden","true");const o=t.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=os(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(t,n,o){const s=j(y.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("desktop-mode-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("desktop-mode-dock__tooltip--visible")}))}positionTooltip(t,n){const o=t.getBoundingClientRect();this.tooltip.textContent=n,this.orientation==="bottom"?(this.tooltip.style.left=`${o.left+o.width/2}px`,this.tooltip.style.top=`${o.top-14}px`):this.orientation==="right"?(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.left}px`):(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.right+8}px`)}openPage(t){if(t.id.startsWith("dock:")){const o=t.id.slice(5),i=window.desktopModeConfig?.desktopIcons?.find(r=>r.id===o);if(i?.window){window.wp?.desktop?.openWindow?.(i.window);return}if(i?.url){if(ds(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(ds(t.url)||dt(t.url))return;const n=this.deriveWindowId(t.url);this.windowManager.open({id:n,baseId:n,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,multi:!!t.multi})}openNewInstance(t){if(ds(t.url))return;const n=window.wp?.desktop?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=vi(t.url);if(o&&n?.(o,{source:"dock-peek"}))return;const s=this.deriveWindowId(t.url);this.windowManager.openNew({id:s,baseId:s,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,multi:!0})}deriveWindowId(t){return oe(t,this.adminUrl)}resolveItemBaseId(t){if(t.windowId)return t.windowId;if(t.id.startsWith("dock:")){const o=t.id.slice(5),i=window.desktopModeConfig?.desktopIcons?.find(r=>r.id===o);if(i?.window)return i.window;if(i?.url)return vi(i.url)??this.deriveWindowId(i.url)}return vi(t.url)??this.deriveWindowId(t.url)}bindWindowEvents(){const t=()=>this.updateActiveStates();this.boundRefresh=t,document.addEventListener("desktop-mode-window-opened",t),document.addEventListener("desktop-mode-window-closed",t),document.addEventListener("desktop-mode-window-focused",t),window.wp?.hooks?.addAction?.("desktop-mode.desktop.switched",this.hooksNamespace,t),window.wp?.hooks?.addAction?.("desktop-mode.desktop.closed",this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.WINDOW_RESTORED,this.hooksNamespace,t)}destroy(){document.removeEventListener("desktop-mode-window-opened",this.boundRefresh),document.removeEventListener("desktop-mode-window-closed",this.boundRefresh),document.removeEventListener("desktop-mode-window-focused",this.boundRefresh),window.wp?.hooks?.removeAction?.("desktop-mode.desktop.switched",this.hooksNamespace),window.wp?.hooks?.removeAction?.("desktop-mode.desktop.closed",this.hooksNamespace),window.wp?.hooks?.removeAction?.(y.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(y.WINDOW_RESTORED,this.hooksNamespace);for(const t of this.attentionTimers.values())window.clearTimeout(t);this.attentionTimers.clear();for(const t of this.peekTeardowns.values())t();for(this.peekTeardowns.clear(),this.tooltip.remove();this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.itemElements.clear(),this.systemItemElements.clear(),this.systemItems=[],this.systemSeparator=null,this.container.removeAttribute("data-desktop-mode-dock-placement")}updateActiveStates(){const t=this.windowManager.getFocused(),n=this.windowManager.getActiveDesktopId(),o=i=>(i.config.desktopId||n)===n,s=i=>i.state==="minimized";for(const i of this.items){const r=this.itemElements.get(i.id);if(!r)continue;const a=this.resolveItemBaseId(i);let d=this.windowManager.getAllByBaseId(a).filter(o);if(d.length===0&&i.url){const p=this.deriveWindowId(i.url);d=this.windowManager.getAll().filter(f=>{const h=f.config.baseId||f.id;if(h===a||h===p||h===i.id)return!0;if(f.config.url){const m=this.deriveWindowId(f.config.url);return m===a||m===p}return!1}).filter(o)}const l=d.length>0,c=l&&d.every(s),u=!!t&&o(t)&&!s(t)&&d.some(p=>p.id===t.id||(t.config.baseId||t.id)===a);r.classList.toggle("desktop-mode-dock__item--active",l),r.classList.toggle("desktop-mode-dock__item--focused",u),r.classList.toggle("desktop-mode-dock__item--all-minimized",c),r.classList.toggle("desktop-mode-dock__item--stacked",l&&d.length>1)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const a=this.windowManager.getById(i.id),d=i.isOpen?i.isOpen():!!a,l=!!a&&s(a),c=!!t&&t.id===i.id&&!s(t);r.classList.toggle("desktop-mode-dock__item--active",d),r.classList.toggle("desktop-mode-dock__item--focused",c),r.classList.toggle("desktop-mode-dock__item--all-minimized",l)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("desktop-mode-show-desktop-active",o)}};Ne.instanceCounter=0,Ne.activeDragReset=null;let us=Ne;function Zl(e,t){const n=e.querySelector(":scope > .desktop-mode-dock__badge");if(t<=0){n?.remove();return}const o=t>99?"99+":String(t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",ne(vn("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="desktop-mode-dock__badge",s.textContent=o,s.setAttribute("aria-label",ne(vn("%d notification","%d notifications",t),t)),e.appendChild(s)}const Jl=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),$i={id:"default",label:"Icon strip",description:"The shipped baseline — icon tiles with badges, tooltips, multi-instance chips, and attention animations.",icon:"dashicons-menu-alt",apiVersion:1,mount(e){const t=new us(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[Jl]:t,replaceItems:o=>t.replaceItems(o),appendSystemItem:o=>t.appendSystemItem(o),removeSystemItem:o=>t.removeSystemItem(o),setBadge:(o,s)=>t.setBadge(o,s),setAttention:(o,s,i)=>t.setAttention(o,s,i),setOrientation:o=>t.setOrientation(o),destroy:()=>t.destroy()}}};function ps(e){if(!e)return null;const n=e[Jl];return n instanceof us?n:null}function Cy(){Pl($i)}const Ay=ge`:host{display:none;position:fixed;inset:0;align-items:center;justify-content:center;background:rgba( 0,0,0,0.45 );backdrop-filter:blur( 2px );z-index:10000;--desktop-mode-text:#f0f0f1;--desktop-mode-text-muted:#bbc1c7;--desktop-mode-muted:#a7aaad;--desktop-mode-muted-fg:#a7aaad;--desktop-mode-border:rgba( 255,255,255,0.25 );--desktop-mode-window-bg:#2c3338;--wpd-button-bg-hover:rgba( 255,255,255,0.08 )}:host( [ open ] ){display:flex}.dialog{max-width:92vw;max-height:90vh;background:var( --wpd-modal-bg,var( --desktop-mode-bg,#1d2327 ) );color:var( --wpd-modal-fg,var( --desktop-mode-fg,#fff ) );border:1px solid rgba( 255,255,255,0.08 );border-radius:10px;box-shadow:0 20px 50px rgba( 0,0,0,0.6 );display:flex;flex-direction:column;overflow:hidden}:host( [ size='sm' ] ) .dialog{width:min( 360px,92vw )}:host(:not( [ size ] ) ) .dialog,:host( [ size='md' ] ) .dialog{width:min( 540px,92vw )}:host( [ size='lg' ] ) .dialog{width:min( 760px,94vw )}.header{display:flex;align-items:center;gap:10px;padding:16px 20px 12px;border-bottom:1px solid rgba( 255,255,255,0.06 )}.title{margin:0;flex:1;font-size:15px;font-weight:600}.header-actions{display:flex;gap:6px}.header-actions::slotted( * ){margin-inline-start:6px}.close{background:transparent;border:0;color:inherit;font-size:18px;line-height:1;padding:4px 8px;border-radius:4px;cursor:pointer;opacity:0.7}.close:hover{opacity:1;background:rgba( 255,255,255,0.08 )}.body{padding:16px 20px;overflow:auto;flex:1 1 auto;font-size:13px;line-height:1.5}.footer{padding:12px 20px 16px;border-top:1px solid rgba( 255,255,255,0.06 )}.footer slot{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap}:host( [ mandatory ] ) .close{display:none}`,Ql='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',Mo=class Mo extends me{constructor(){super(...arguments),this._prevFocus=null,this._onKey=t=>{if(t.key==="Escape"&&!this.hasAttribute("mandatory")){t.preventDefault(),this._cancel();return}if(t.key==="Tab"){const n=this._focusables();if(n.length===0)return;const o=n[0],s=n[n.length-1],i=this.ownerDocument,r=i?i.activeElement:null,a=t.composedPath()[0]||r;t.shiftKey&&a===o?(t.preventDefault(),s.focus()):!t.shiftKey&&a===s&&(t.preventDefault(),o.focus())}},this._onBackdrop=t=>{if(this.hasAttribute("mandatory"))return;const n=t.composedPath();(n.length>0?n[0]:t.target)===this&&this._cancel()}}connectedCallback(){super.connectedCallback(),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","true"),this.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback?.(t,n,o),t==="open"){if(o!==null){const s=this.ownerDocument;this._prevFocus=s?s.activeElement:null,queueMicrotask(()=>this._focusFirst())}else if(this._prevFocus){try{this._prevFocus.focus()}catch{}this._prevFocus=null}}}showModal(){this.setAttribute("open","")}hideModal(){this.removeAttribute("open")}_focusables(){const t=this.shadowRoot;if(!t)return[];const n=Array.from(this.querySelectorAll(Ql)),o=Array.from(t.querySelectorAll(Ql));return[...n,...o].filter(s=>s.offsetParent!==null||s.tagName==="BUTTON")}_focusFirst(){const t=this._focusables();t.length>0?t[0].focus():this.shadowRoot?.querySelector(".dialog")?.focus?.()}_cancel(){const t=new CustomEvent("wpd-modal-cancel",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(t)&&this.hideModal()}render(){const t=this.getAttribute("title")??"",n=this.hasAttribute("mandatory");return z` |
| 29 |
<div class="dialog" tabindex="-1"> |
| 30 |
${t?z` |
| 31 |
<div class="header"> |
| 32 |
<h2 class="title">${t}</h2> |
| 33 |
<div class="header-actions"> |
| 34 |
<slot name="header-actions"></slot> |
| 35 |
${n?z``:z`<button |
| 36 |
type="button" |
| 37 |
class="close" |
| 38 |
aria-label="Close" |
| 39 |
@click=${()=>this._cancel()} |
| 40 |
>×</button>`} |
| 41 |
</div> |
| 42 |
</div> |
| 43 |
`:z``} |
| 44 |
<div class="body"> |
| 45 |
<slot></slot> |
| 46 |
</div> |
| 47 |
<div class="footer"> |
| 48 |
<slot name="footer"></slot> |
| 49 |
</div> |
| 50 |
</div> |
| 51 |
`}};Mo.props=["open","title","size","mandatory"],Mo.styles=[Ay],Mo.help=void 0;let Wi=Mo;we("wpd-modal",Wi);const Ly=ge`:host{display:inline-flex}:host( [ fill-cell ] ){display:flex;width:100%}button{appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:var( --wpd-button-padding,6px 12px );border-radius:var( --wpd-button-border-radius,6px );font:inherit;font-weight:500;cursor:pointer;transition:background-color 0.12s ease,color 0.12s ease,border-color 0.12s ease;background:var( --wpd-button-bg,transparent );color:var( --wpd-button-fg,var( --desktop-mode-text,#1d2327 ) );border:var( --wpd-button-border,1px solid var( --desktop-mode-border,#c3c4c7 ) )}:host( [ fill-cell ] ) button{width:100%;min-height:var( --wpd-button-min-height,44px )}button:disabled{opacity:0.5;cursor:not-allowed}button:hover:not(:disabled ){background:var( --wpd-button-bg-hover,rgba( 0,0,0,0.04 ) )}:host( [ variant='primary' ] ) button{background:var( --wpd-button-bg,var( --wp-admin-theme-color,#2271b1 ) );color:var( --wpd-button-fg,#fff );border:var( --wpd-button-border,1px solid transparent )}:host( [ variant='primary' ] ) button:hover:not(:disabled ){filter:brightness( 1.06 );background:var( --wpd-button-bg,var( --wp-admin-theme-color,#2271b1 ) )}:host( [ variant='secondary' ] ) button{background:var( --wpd-button-bg,rgba( 0,0,0,0.06 ) );color:var( --wpd-button-fg,var( --desktop-mode-text,#1d2327 ) );border:var( --wpd-button-border,1px solid transparent )}:host( [ variant='secondary' ] ) button:hover:not(:disabled ){background:var( --wpd-button-bg-hover,rgba( 0,0,0,0.1 ) )}:host( [ variant='danger' ] ) button{background:var( --wpd-button-bg,transparent );color:var( --wpd-button-fg,#d63638 );border:var( --wpd-button-border,1px solid currentColor )}:host( [ variant='danger' ] ) button:hover:not(:disabled ){background:#d63638;color:#fff}:host( [ variant='link' ] ) button{background:transparent;color:var( --wpd-button-fg,var( --wp-admin-theme-color,#2271b1 ) );border:0;padding:0;text-decoration:underline}:host( [ busy ] ) button{pointer-events:none;opacity:0.75}.wpd-button__spinner{box-sizing:border-box;display:inline-block;width:12px;height:12px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:wpd-button-spin 0.6s linear infinite;flex-shrink:0}@keyframes wpd-button-spin{to{transform:rotate( 360deg )}}`,Po=class Po extends me{render(){const t=this.disabled!==null,n=this.busy!==null,o=this.type||"button";return z` |
| 52 |
<button |
| 53 |
part="button" |
| 54 |
type=${o} |
| 55 |
?disabled=${t||n} |
| 56 |
aria-busy=${n?"true":"false"} |
| 57 |
> |
| 58 |
${n?z`<span class="wpd-button__spinner" aria-hidden="true"></span>`:""} |
| 59 |
<slot></slot> |
| 60 |
</button> |
| 61 |
`}};Po.props=["variant","disabled","type","busy","fill-cell"],Po.styles=[Ly],Po.help=void 0;let Ui=Po;we("wpd-button",Ui);function ec(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}const Ty=()=>S("Mix your own two-colour gradient and set the angle — your desk, your palette.");function Ny(e){In({id:yg,label:S("Custom gradient"),type:"css",preview:ec(e.state),description:Ty(),resolveValue:()=>ec(e.state)})}function Dy(e){if(!e.customImage){_l(Al);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`;In({id:Al,label:S("Custom image"),type:"css",value:n,preview:n,description:S("Any image from your media library or an upload, sized to cover the whole desk.")})}let fs=null;function Oy(e){return window.desktopModeRenderOsSettingsPanel?Promise.resolve(window.desktopModeRenderOsSettingsPanel):fs||(fs=new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-os-settings-panel="1"]'),s=()=>{const r=window.desktopModeRenderOsSettingsPanel;if(!r){n(new Error("[desktop-mode] os-settings-panel bundle loaded but did not register desktopModeRenderOsSettingsPanel"));return}t(r)};if(o){window.desktopModeRenderOsSettingsPanel?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeOsSettingsPanel="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))),document.head.appendChild(i)}),fs)}class Ry{constructor(t,n){this.activeEditorTeardown=null,this.tabRegistryUnsubscribe=null,this.activeTabId=null,this.osSettingsListeners=new Set,this._lastRenderedBody=null,this.config=t,this.layer=n,this.state=Eg(),Tg(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))}),Ny(this),Dy(this.state)}getOsSettingsSnapshot(){return{wallpaper:this.state.wallpaper,accent:this.state.accent,dockSize:this.state.dockSize,desktopLayout:this.state.desktopLayout,dockRailRenderer:this.state.dockRailRenderer,unfocusEffect:this.state.unfocusEffect,windowLinkRenderer:this.state.windowLinkRenderer,windowLinkVisibility:this.state.windowLinkVisibility,windowLinksEnabled:this.state.windowLinksEnabled,windowLinkRaiseOnFocus:this.state.windowLinkRaiseOnFocus,windowLinkHighlight:this.state.windowLinkHighlight,ai:{...this.state.ai},nativePostsEnabled:this.state.nativePostsEnabled,nativePostsHiddenColumns:this.state.nativePostsHiddenColumns.slice(),nativePagesEnabled:this.state.nativePagesEnabled,nativeUsersEnabled:this.state.nativeUsersEnabled,nativePluginsEnabled:this.state.nativePluginsEnabled,nativeCommentsEnabled:this.state.nativeCommentsEnabled,developerModeEnabled:this.state.developerModeEnabled,foldersSharingEnabled:this.state.foldersSharingEnabled,itemVisibility:{...this.state.itemVisibility},dockOrder:this.state.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(this.state.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}subscribeOsSettings(t){return this.osSettingsListeners.add(t),()=>{this.osSettingsListeners.delete(t)}}apply(){const t=document.getElementById("desktop-mode-shell");if(!t)return;gg(this.state.wallpaperSettings);const n=xi(this.state.wallpaper)||xi(Nl())||xi(Ii)||Sl()[0];n&&this.layer.apply(n);const o=Tl(),s=o.find(a=>a.id===this.state.accent)??o[0],i=Ci.find(a=>a.id===this.state.dockSize)??Ci[1],r=document.documentElement;r.style.setProperty("--wp-admin-theme-color",s.value),r.style.setProperty("--desktop-mode-dock-width",`${i.width}px`),r.style.setProperty("--desktop-mode-dock-icon-size",`${i.icon}px`),t.setAttribute("data-desktop-mode-layout",this.state.desktopLayout),zg(this.state.dockRailRenderer)}save(t={}){if(Ng(this.state,t),this.osSettingsListeners.size>0){const n=this.getOsSettingsSnapshot(),o=Array.from(this.osSettingsListeners);for(const s of o)try{s(n)}catch(i){typeof console<"u"&&console.error("[desktop-mode] os-settings listener threw:",i)}}}focusTab(t){this.activeTabId=t;const n=this._lastRenderedBody;if(!n?.isConnected)return;const o=n.querySelector("wpd-tabs");o&&(o.value=t)}renderPanel(t){this._lastRenderedBody=t;const n=window.desktopModeRenderOsSettingsPanel;if(n){n(this,t);return}Oy(this.config.osSettingsPanelBundleUrl??"").then(o=>{t.isConnected&&o(this,t)}).catch(o=>{typeof console<"u"&&console.error("[desktop-mode] OS Settings panel failed to load:",o)})}}const My="desktop-mode-exit";function Py(){return{id:My,title:S("Exit Desktop Mode"),icon:"dashicons-exit",onOpen:()=>{$y()}}}async function $y(){const e=window.desktopModeAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){tc(t);return}const n=new URLSearchParams;n.set("action","save-desktop-mode"),n.set("nonce",e.nonce),n.set("enabled","");let o=t;try{const s=await fetch(e.ajaxUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),credentials:"same-origin"});if(s.ok){const i=await s.json();i?.success&&i.data?.redirect&&(o=i.data.redirect)}}catch{}tc(o)}function tc(e){try{window.top.location.href=e}catch{window.location.href=e}}const Wy={userId:null,requestedAt:0,tabRequested:!1};let ms=null;function Uy(){if(ms)return ms;const t=window.wp?.desktop?.createSharedStore;return typeof t!="function"?null:(ms=t("desktop-mode/user-edit/target",()=>({...Wy})),ms)}function Fy(e){const t=Uy();if(t){t.state.userId=e,t.state.requestedAt=Date.now(),t.state.tabRequested=!0,t.notify();return}const n=window;n._wpdUserEditTarget={userId:e,requestedAt:Date.now(),tabRequested:!0}}const Fi=new Map;function Ie(e,t){const n=Fi.get(e);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-desktop-mode-vendor="${Hy(e)}"]`,a=document.querySelector(r);if(a){if(a.dataset.loaded==="1"){s();return}a.addEventListener("load",()=>s(),{once:!0}),a.addEventListener("error",()=>i(new Error(`Failed to load ${e}`)),{once:!0});return}t?.translations&&hs(t.translations);for(const l of t?.l10n??[])hs(l);for(const l of t?.before??[])hs(l);const d=document.createElement("script");d.src=e,d.async=!0,d.dataset.desktopModeVendor=e,d.addEventListener("load",()=>{d.dataset.loaded="1";for(const l of t?.after??[])hs(l);s()},{once:!0}),d.addEventListener("error",()=>{Fi.delete(e),d.remove(),i(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(d)});return Fi.set(e,o),o}function hs(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.desktopModeVendorInline="1",document.head.appendChild(t)}function Hy(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}const ws=new Map;function nc(e){if(!e||typeof e.id!="string"||e.id===""){typeof console<"u"&&console.warn("[desktop-mode] Ignored invalid module registration:",e);return}if(typeof e.url!="string"||e.url===""){typeof console<"u"&&console.warn(`[desktop-mode] Module "${e.id}" has no url; ignored.`);return}ws.set(e.id,e)}function By(){return Array.from(ws.keys())}async function oc(e){if(!e||e.length===0)return;const t=e.filter(n=>!ws.has(n));if(t.length>0)throw new Error(`[desktop-mode] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${By().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=ws.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():Ie(o.url)}))}function sc(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:zy(),visible:!document.hidden,settings:wg(e)}}function zy(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class ic{constructor(t,n){this.generation=0,this.active=null,this.suspendReasons=new Map,this.freezeOverlay=null,this.frozenCanvas=null,this.boundVisibilityChange=()=>{this.emitEffectiveVisibility()},this.element=t,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(t){const n=++this.generation;if(this.teardownActive(),t.type==="css"){this.applyCss(t);return}this.applyCanvas(t,n)}suspend(t){const n=this.isSuspended();this.suspendReasons.set(t,(this.suspendReasons.get(t)??0)+1),!n&&(this.installFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}resume(t){const n=this.suspendReasons.get(t);if(n!==void 0){if(n>1){this.suspendReasons.set(t,n-1);return}this.suspendReasons.delete(t),!this.isSuspended()&&(this.removeFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}}isSuspended(){return this.suspendReasons.size>0}teardownActive(){if(this.removeFreezeOverlay(),!this.active)return;const{id:t,teardown:n}=this.active;this.active=null,T(y.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){T(y.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[desktop-mode] Wallpaper "${t}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(t){const n=t.resolveValue?t.resolveValue(sc(t.id,this.pluginUrl)):t.value;typeof n=="string"&&(this.element.style.setProperty("--desktop-mode-bg",n),document.getElementById("desktop-mode-shell")?.style.setProperty("--desktop-mode-bg",n))}applyCanvas(t,n){const o=sc(t.id,this.pluginUrl);T(y.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?oc(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},T(y.WALLPAPER_MOUNTED,{id:t.id,container:this.element,ctx:o}),this.isEffectivelyHidden()&&this.emitEffectiveVisibility()};s.then(()=>{if(n!==this.generation)return;let r;try{r=t.mount(this.element,o)}catch(a){this.handleMountFailure(t.id,a);return}if(Gy(r)){r.then(i,a=>{n===this.generation&&this.handleMountFailure(t.id,a)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(t.id,r)})}isEffectivelyHidden(){return document.hidden||this.isSuspended()}emitEffectiveVisibility(){this.active&&T(y.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){T(y.WALLPAPER_SUSPEND,{id:this.active?.id??null,suspended:this.isSuspended(),reasons:Array.from(this.suspendReasons.keys())})}installFreezeOverlay(){if(this.freezeOverlay||!this.active)return;const t=this.element.querySelector("canvas");if(!(!t||t.width===0||t.height===0))try{const n=document.createElement("canvas");n.width=t.width,n.height=t.height;const o=n.getContext("2d");if(!o)return;o.drawImage(t,0,0),n.className="desktop-mode-wallpaper-freeze",n.style.position="absolute",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.setAttribute("aria-hidden","true"),this.element.appendChild(n),t.style.visibility="hidden",this.freezeOverlay=n,this.frozenCanvas=t}catch{}}removeFreezeOverlay(){this.freezeOverlay?.remove(),this.freezeOverlay=null,this.frozenCanvas&&(this.frozenCanvas.style.visibility="",this.frozenCanvas=null)}handleMountFailure(t,n){this.element.innerHTML="",T(y.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),T(y.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[desktop-mode] Wallpaper "${t}" failed to mount:`,n)}}function Gy(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}function jy(e){const{osSettings:t}=e,n=new Set,o=new Set,s=async l=>{if(!(!l.scriptUrl||o.has(l.scriptUrl))){try{await Ie(l.scriptUrl,{translations:l.scriptTranslations,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){T(y.SHELL_ERROR,{scope:"wallpaper-script-load",id:l.id,error:c});return}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,description:l.description||void 0},a=async l=>{if(n.has(l.id))return;const c=r(l);if(c){In(c),n.add(l.id),t.apply();return}await s(l);let u=i(l.id);if(u&&!u.description&&l.description&&(u={...u,description:l.description}),!u){T(y.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{In(u)}catch(p){T(y.SHELL_ERROR,{scope:"wallpaper-register",id:l.id,error:p});return}n.add(l.id),t.apply()},d=l=>{n.has(l)&&(_l(l),n.delete(l),t.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 rc=re("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),Ht=rc.state.seed,Hi=rc.state.listeners;function Bi(e){De("Game",bt(e,cc),e);const t=Ht.findIndex(n=>n.id===e.id);t>=0?Ht[t]=e:Ht.push(e),dc()}function ac(e){const t=Ht.findIndex(n=>n.id===e);t>=0&&(Ht.splice(t,1),dc())}function qy(e){return Hi.add(e),()=>{Hi.delete(e)}}function dc(){const e=Array.from(Hi);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] games registry listener threw:",n)}}function lc(){const e=Ht.slice(),t=j(y.GAMES,e);return Array.isArray(t)?t.filter(Vy):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.games` filter returned a non-array; falling back to seed list."),e)}function gs(e){return lc().find(t=>t.id===e)}const cc=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"title",message:"missing or not a non-empty string",valid:e=>typeof e.title=="string"&&e.title!==""},{field:"scoreColumns",message:"must be an array",valid:e=>Array.isArray(e.scoreColumns)},{field:"render/scriptUrl",message:"needs a `render` callback or a `scriptUrl` to lazily load one",valid:e=>typeof e.render=="function"||typeof e.scriptUrl=="string"&&e.scriptUrl!==""}];function Vy(e){return bt(e,cc).length===0}function Ky(e){return{id:e.id,title:e.title,icon:e.icon,description:e.description||void 0,scoreColumns:Array.isArray(e.scoreColumns)?e.scoreColumns:[],config:e.config??{},scriptUrl:e.scriptUrl,scriptTranslations:e.scriptTranslations,scriptL10n:e.scriptL10n,scriptBefore:e.scriptBefore,scriptAfter:e.scriptAfter}}function Xy(){const e=new Set,t=o=>{try{const s=gs(o.id),i=Ky(o);Bi(s&&typeof s.render=="function"?{...i,render:s.render,window:s.window}:i)}catch(s){typeof console<"u"&&console.error(`[desktop-mode] Server game "${o.id}" failed to register:`,s);return}e.add(o.id)},n=o=>{e.has(o)&&(ac(o),e.delete(o))};return async o=>{const s=new Set;for(const i of o)i&&typeof i.id=="string"&&i.id!==""&&s.add(i.id);for(const i of Array.from(e))s.has(i)||n(i);for(const i of o)s.has(i.id)&&t(i)}}const ys=new Map,zi=new Map;let uc=!1;const ye={contribute(e,t){return ys.set(e,t),()=>{ys.get(e)===t&&ys.delete(e)}},subscribe(e,t){let n=zi.get(e);return n||(n=new Set,zi.set(e,n)),n.add(t),()=>{n.delete(t)}}};function Yy(){if(uc)return;uc=!0;const e=window.jQuery;if(!e){console.warn("[desktop-mode/heartbeat] jQuery missing — Heartbeat bus disabled.");return}e(document).on("heartbeat-send",(...t)=>{const n=t[1];if(n)for(const[o,s]of ys)try{n[o]=s()}catch(i){console.error(`[desktop-mode/heartbeat] supplier for "${o}" threw:`,i)}}),e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n)for(const[o,s]of zi){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)}}})}let bs=null,vs={installHintDismissed:!1,notificationsEnabled:!1};const Gi=new Set;function pc(e){if(!e){bs=null;return}bs=e,vs={...e.state},mc()}function Dn(){return{...vs}}function ji(e){if(vs={...vs,...e},mc(),!bs)return Dn();const t=JSON.stringify(e),n=Zy();return fetch(bs.stateUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",...n?{"X-WP-Nonce":n}:{}},body:t}).catch(o=>{typeof console<"u"&&console.warn("[desktop-mode] pwa-state write failed:",o)}),Dn()}function fc(e){return Gi.add(e),()=>{Gi.delete(e)}}function mc(){const e=Dn();for(const t of Array.from(Gi))try{t(e)}catch(n){typeof console<"u"&&console.error("[desktop-mode] pwa-state listener threw:",n)}}function Zy(){return window.desktopModeConfig?.restNonce??""}const Jy=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:Dn,initPwaState:pc,subscribePwaState:fc,updatePwaState:ji},Symbol.toStringTag,{value:"Module"}));function qi(e){const t=ve.filter("desktop-mode/notification-requested",{...e});if(!t||t.cancel===!0||!t.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=q({message:t.body?t.title+" — "+t.body:t.title}),ve.publish("desktop-mode/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=hc(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(d=>{if(!n){if(d==="granted"){ji({notificationsEnabled:!0}),o=hc(t),o||r();return}r()}}),i)}function hc(e){let t=null;try{t=new Notification(e.title,{body:e.body,icon:e.icon,tag:e.tag,requireInteraction:e.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[desktop-mode] Notification ctor threw:",n),null}if(e.onClick){const n=e.onClick;t.onclick=()=>{try{n(t)}catch(o){typeof console<"u"&&console.error("[desktop-mode] notification onClick threw:",o)}}}return ve.publish("desktop-mode/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function Qy(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&ji({notificationsEnabled:!0}),e}function eb(){return typeof Notification>"u"?"unsupported":Notification.permission}const Bt=re("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function tb(){return Bt.state}function wc(e){const t=Bt.state;let n=!1;for(const o of e){if(!o||typeof o.id!="number")continue;const s=t.rows.get(o.id);(!s||s.updatedAtMs!==o.updatedAtMs)&&(t.rows.set(o.id,o),n=!0),o.updatedAtMs>t.version&&(t.version=o.updatedAtMs)}n&&ob()}function nb(e){return Bt.state.listeners.add(e),()=>{Bt.state.listeners.delete(e)}}function ob(){for(const e of Array.from(Bt.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[desktop-mode] challenges store listener threw:",t)}}function sb(){return Array.from(Bt.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}const ib="desktop-mode/games";function rb(){const t=window.wp?.desktop?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function On(e,t={},n={}){const{restUrl:o,restNonce:s}=rb(),i=new Headers(t.headers??{});i.set("X-WP-Nonce",s),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Pe(Ze(o,e),{...t,headers:i,credentials:"same-origin"},{source:ib,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok){const d=a?.message||`Games request failed (${r.status})`,l=new Error(d);throw l.status=r.status,l}return a}function ab(e,t,n={}){return On(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function db(){return On("desktop-mode/v1/games/playtime")}function lb(e,t,n={}){return On(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function cb(e){return On(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function ub(e,t,n={}){return On(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const pb=6e4;function fb(e,t={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const d=Date.now();o+=Math.max(0,d-n),n=d},r=()=>{i();const d=Math.floor(o/1e3);d<1||(o-=d*1e3,lb(e,d,{windowId:t.windowId,silent:!0}).catch(()=>{o+=d*1e3}))},a=setInterval(r,pb);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}function gc(){return window.wp?.desktop??{}}const mb=760,hb=560,wb=480,gb=380;async function yb(e){if(typeof e.render=="function")return e;const t=gc().loadVendorScript;if(!e.scriptUrl||typeof t!="function")throw new Error(`[desktop-mode] Game "${e.id}" has no render callback and no loadable script.`);await t(e.scriptUrl,{translations:e.scriptTranslations,l10n:e.scriptL10n,before:e.scriptBefore,after:e.scriptAfter});const o=window.desktopModeGames?.[e.id];if(!o||typeof o.render!="function")throw new Error(`[desktop-mode] No game def on window.desktopModeGames["${e.id}"]. Script loaded but didn't publish a def — check the plugin's global assignment.`);const s={...e,render:o.render,window:o.window??e.window};return Bi(s),s}async function yc(e,t={}){const n=gc();let o=gs(e);if(!o)throw new Error(`[desktop-mode] Unknown game "${e}".`);o=await yb(o);const s=o.render;if(typeof s!="function")throw new Error(`[desktop-mode] Game "${e}" did not provide a render callback.`);if(typeof n.registerWindow!="function")throw new Error("[desktop-mode] wp.desktop.registerWindow is missing — the shell must boot before launching games.");const i=`desktop-mode-game-${e}`,r=`game:${i}`,a=n.windowManager,d=a?.getByBaseId?.(i)??a?.getById(i);if(d){const h=d.config?.desktopId;h&&a?.switchDesktop&&h!==a?.getActiveDesktopId?.()&&a.switchDesktop(h),n.registerWindow({id:i,title:o.title,icon:o.icon,render:()=>{}});return}n.wallpaper?.suspend(r);let l=!1;const c=()=>{l||(l=!0,n.wallpaper?.resume(r))};let u=null;const p=()=>{u?.stop(),u=null};n.onWindow?.(i,{closed:()=>{p(),c()},minimized:()=>u?.pause(),restored:()=>u?.resume()});const f=h=>t.challenge?ub(t.challenge.id,h,{windowId:i}).then(()=>{}):ab(e,h,{windowId:i}).then(()=>{});try{await n.registerWindow({id:i,title:o.title,icon:o.icon,width:o.window?.width??mb,height:o.window?.height??hb,minWidth:o.window?.minWidth??wb,minHeight:o.window?.minHeight??gb,render:h=>{const m={windowId:i,container:h,config:o.config??{},challenge:t.challenge,submitScore:f,close:()=>{n.windowManager?.getById(i)?.close()}};u=fb(e,{windowId:i});const w=s(m);return()=>{try{w?.()}finally{p(),c()}}}})}catch(h){throw p(),c(),h}}function bb(e){return gs(e)?.title||e}const bc=new Set,vc=new Set;async function vb(e){const{challenge:t}=await cb(e.id);wc([t]),await yc(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function kb(e){const t=ne(S("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,bb(e.game),String(e.scoreToBeat));qi({title:S("Game challenge"),body:t,tag:`desktop-mode-game-challenge-${e.id}`}),q({message:t,persistent:!0,dismissible:!0,action:{label:S("Accept & Play"),onClick:()=>{vb(e).catch(n=>{q({message:n instanceof Error?n.message:S("Could not accept the challenge.")})})}}})}function _b(e){let t;e.result==="beaten"?t=S("%1$s beat your score: %2$s vs your %3$s."):t=S("%1$s did not beat your score: %2$s vs your %3$s.");const n=ne(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));qi({title:S("Challenge finished"),body:n,tag:`desktop-mode-game-challenge-${e.id}`}),q({message:n})}function Eb(e){const{currentUserId:t}=e;if(!t)return;ye.contribute("desktop_mode_games_subscribe",()=>({challengesVersion:tb().version})),ye.subscribe("desktop_mode_games",o=>{Array.isArray(o?.challenges)&&wc(o.challenges)});const n=()=>{for(const o of sb())o.state==="pending"&&o.recipientId===t&&!bc.has(o.id)&&(bc.add(o.id),kb(o)),o.state==="completed"&&o.challengerId===t&&!vc.has(o.id)&&(vc.add(o.id),_b(o))};nb(n),n()}const kc=/^[a-z0-9_/-]+$/,_c=re("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),Et=_c.state.registry,Sb=_c.state.listeners;function ks(e){const t=[],n=typeof e?.slug=="string"?e.slug.trim().toLowerCase():"";!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.slug!="string"||e.slug.trim()===""?t.push("slug (missing)"):kc.test(n)||t.push(`slug (must match ${kc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.run!="function"&&t.push("run (must be a function)")),De("Command",t,e),Et.set(n,{...e,slug:n}),Vi()}function Ec(e){Et.delete(e.toLowerCase())&&Vi()}function _s(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Et.entries()))o.owner===e&&(Et.delete(n),t++);return t>0&&Vi(),t}function Sc(){return Array.from(Et.values())}function xb(){const e=[];for(const t of Et.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function Ib(e){return Et.get(e.toLowerCase())??null}function Vi(){const e=Array.from(Sb);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] command-registry listener threw:",n)}}function Cb(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ie(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(y.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.slug)continue;let 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 Sc())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(e))if(!d.has(l)){for(const c of i(l))Ec(c);e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const xc=re("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),Rn=xc.state.registry,Ab=xc.state.listeners;function Ic(e){if(!e||typeof e.id!="string"||e.id.trim()===""||typeof e.label!="string"||e.label.trim()===""||typeof e.render!="function")return;const t=e.id.trim().toLowerCase();if(!/^[a-z0-9_\-]+$/.test(t)){typeof console<"u"&&console.warn("[desktop-mode] registerSettingsTab: id must be [a-z0-9_-]+, got",e.id);return}Rn.set(t,{...e,id:t}),Ki()}function Cc(e){Rn.delete(e.toLowerCase())&&Ki()}function Lb(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Rn.entries()))o.owner===e&&(Rn.delete(n),t++);return t>0&&Ki(),t}function Ac(){return Array.from(Rn.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Ki(){const e=Array.from(Ab);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] settings-tab-registry listener threw:",n)}}function Tb(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ie(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(y.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let l=a.get(d.scriptHandle);l||(l=new Set,a.set(d.scriptHandle,l)),l.add(d.id)}return a},i=r=>{Lb(r);const a=n.get(r);if(a){const d=new Set(Ac().map(l=>l.id));for(const l of a)d.has(l)&&Cc(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(e))d.has(l)||(i(l),e.delete(l));for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const Lc=re("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),Mn=Lc.state.registry,Nb=Lc.state.listeners,Tc=/^[a-z0-9_/-]+$/;function Xi(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Tc.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Tc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (missing)"),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)")),De("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();Mn.set(n,{...e,id:n}),Yi()}function Db(e){Mn.delete(e.toLowerCase())&&Yi()}function Ob(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Mn.entries()))o.owner===e&&(Mn.delete(n),t++);return t>0&&Yi(),t}function Rb(){return Array.from(Mn.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Yi(){const e=Array.from(Nb);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] title-bar-button registry listener threw:",n)}}function Mb(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ie(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(y.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(Ob(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const zt="none",Zi="svg-splines",Nc=re("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),Pn=Nc.state.registry,Ji=Nc.state.listeners,Dc=/^[a-z0-9_/-]+$/;function Oc(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Dc.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===zt&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Dc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.mount!="function"&&t.push("mount (not a function)")),De("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();Pn.set(n,{...e,id:n}),er()}function Pb(e){Pn.delete(e.toLowerCase())&&er()}function $b(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Pn.entries()))o.owner===e&&(Pn.delete(n),t++);return t>0&&er(),t}function Rc(){const e=Array.from(Pn.values()),t=j(y.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function Qi(e){return Rc().find(t=>t.id===e)}function Wb(e){return Ji.add(e),()=>{Ji.delete(e)}}function er(){const e=Array.from(Ji);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-link-renderer registry listener threw:",n)}}const Ub=16;function Fb(e,t){const n=t.map(i=>({start:Math.max(e.start,i.start),end:Math.min(e.end,i.end)})).filter(i=>i.end>i.start).sort((i,r)=>i.start-r.start),o=[];let s=e.start;for(const i of n)i.start>s&&o.push({start:s,end:i.start}),s=Math.max(s,i.end);return s<e.end&&o.push({start:s,end:e.end}),o}function Hb(e,t){const n=e.x+e.width/2,o=e.y+e.height/2,s=t.x-n,i=t.y-o;if(s===0&&i===0)return{x:n,y:o,side:"right"};const r=s!==0?e.width/2/Math.abs(s):1/0,a=i!==0?e.height/2/Math.abs(i):1/0,d=Math.min(r,a),l=n+s*d,c=o+i*d;let u;return r<=a?u=s>0?"right":"left":u=i>0?"bottom":"top",{x:l,y:c,side:u}}function Mc(e,t,n,o){for(const s of n)if(!(s.windowId===o||s.zIndex<=t)&&e.x>=s.rect.x&&e.x<=s.rect.x+s.rect.width&&e.y>=s.rect.y&&e.y<=s.rect.y+s.rect.height)return!1;return!0}function Bb(e,t,n,o,s){const i=n.filter(l=>l.windowId!==o&&l.zIndex>t),r=[{side:"top",base:{start:e.x,end:e.x+e.width},at:e.y,horizontal:!0},{side:"bottom",base:{start:e.x,end:e.x+e.width},at:e.y+e.height,horizontal:!0},{side:"left",base:{start:e.y,end:e.y+e.height},at:e.x,horizontal:!1},{side:"right",base:{start:e.y,end:e.y+e.height},at:e.x+e.width,horizontal:!1}];let a=null,d=1/0;for(const{side:l,base:c,at:u,horizontal:p}of r){const f=[];for(const{rect:h}of i)(p?h.y<=u&&u<=h.y+h.height:h.x<=u&&u<=h.x+h.width)&&f.push(p?{start:h.x,end:h.x+h.width}:{start:h.y,end:h.y+h.height});for(const h of Fb(c,f)){if(h.end-h.start<Ub)continue;const m=(h.start+h.end)/2,w=p?m:u,g=p?u:m,k=Math.hypot(s.x-w,s.y-g);k<d&&(d=k,a={x:w,y:g,side:l})}}return a}function zb(e,t){const n=Math.max(t.x-(e.x+e.width),e.x-(t.x+t.width)),o=Math.max(t.y-(e.y+e.height),e.y-(t.y+t.height));if(n<0&&o<0)return null;const s=Math.max(e.x,t.x),i=Math.min(e.x+e.width,t.x+t.width),r=Math.max(e.y,t.y),a=Math.min(e.y+e.height,t.y+t.height);let d,l;i>=s?d=l=(s+i)/2:t.x>e.x?(d=e.x+e.width,l=t.x):(d=e.x,l=t.x+t.width);let c,u;a>=r?c=u=(r+a)/2:t.y>e.y?(c=e.y+e.height,u=t.y):(c=e.y,u=t.y+t.height);const p=n>=o,f=(h,m,w)=>p?m<=h.x?"left":"right":w<=h.y?"top":"bottom";return{from:{x:d,y:c,side:f(e,d,c)},to:{x:l,y:u,side:f(t,l,u)}}}function Pc(e,t){const n=Math.min(160,Math.max(24,.4*t));switch(e.side){case"left":return{x:e.x-n,y:e.y};case"right":return{x:e.x+n,y:e.y};case"top":return{x:e.x,y:e.y-n};default:return{x:e.x,y:e.y+n}}}function Gb(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}const Gt="http://www.w3.org/2000/svg";let jb=0;function $c(e,t,n,o,s){const i=Hb(e,s);return t===null||Mc(i,t,o,n)?i:Bb(e,t,o,n,s)??i}function qb(e,t){const n=document.createElementNS(Gt,"defs"),o=(a,d,l)=>{const c=`${t}-${a}`,u=document.createElementNS(Gt,"marker");u.setAttribute("id",c),u.setAttribute("viewBox","0 0 10 10"),u.setAttribute("refX","5"),u.setAttribute("refY","5"),u.setAttribute("markerWidth",l),u.setAttribute("markerHeight",l),u.setAttribute("markerUnits","strokeWidth");const p=document.createElementNS(Gt,"circle");return p.setAttribute("cx","5"),p.setAttribute("cy","5"),p.setAttribute("r","4"),p.classList.add(d),u.appendChild(p),n.appendChild(u),c},s="desktop-mode-window-link__endpoint",i=`${s}--active`,r={dot:{normal:o("dot",s,"7"),active:o("dot-active",i,"7")},port:{normal:o("port",s,"4.5"),active:o("port-active",i,"4.5")}};return e.appendChild(n),r}Oc({id:"svg-splines",label:S("Splines"),description:S("Curved connectors between related windows, ending in circular dots — the larger dot sits on the window the content belongs to; windows that reference each other get large dots on both ends."),mount:e=>{const t=++jb,n=(a,d)=>{const l=document.createElementNS(Gt,"svg");return l.classList.add("desktop-mode-window-links__svg"),a.appendChild(l),{svg:l,markers:qb(l,`desktop-mode-window-link-${t}${d}`)}},o={base:n(e.container,""),elevated:n(e.elevatedContainer,"-elevated")},s=new Map,i=a=>{for(const{svg:l}of[o.base,o.elevated])l.setAttribute("width",String(a.container.width)),l.setAttribute("height",String(a.container.height)),l.setAttribute("viewBox",`0 0 ${a.container.width} ${a.container.height}`);const d=new Set;for(const l of a.edges){if(!l.from||!l.to)continue;const c=`${l.fromWindowId}→${l.toWindowId}:${l.kind}`;d.add(c);const u=l.elevated?"elevated":"base";let p=s.get(c);if(p&&p.surface!==u&&(p.group.remove(),s.delete(c),p=void 0),!p){const O=document.createElementNS(Gt,"g");O.classList.add("desktop-mode-window-link");const v=document.createElementNS(Gt,"path");v.classList.add("desktop-mode-window-link__path"),O.appendChild(v),o[u].svg.appendChild(O),p={group:O,path:v,surface:u},s.set(c,p)}const f=a.obstacles??[],h=zb(l.from,l.to),m=(O,v,N)=>v===null||Mc(O,v,f,N);let w=null;h&&m(h.from,l.fromZIndex,l.fromWindowId)&&(w=h.from),w||(w=$c(l.from,l.fromZIndex,l.fromWindowId,f,h?{x:h.to.x,y:h.to.y}:Gb(l.to)));let g=null;h&&m(h.to,l.toZIndex,l.toWindowId)&&(g=h.to),g||(g=$c(l.to,l.toZIndex,l.toWindowId,f,{x:w.x,y:w.y}));const k=Math.hypot(g.x-w.x,g.y-w.y),D=Pc(w,k),b=Pc(g,k);p.path.setAttribute("d",`M ${w.x} ${w.y} C ${D.x} ${D.y}, ${b.x} ${b.y}, ${g.x} ${g.y}`);const E=o[p.surface].markers,I=l.focused?"active":"normal";p.path.setAttribute("marker-end",`url(#${E.dot[I]})`),p.path.setAttribute("marker-start",`url(#${l.bidirectional?E.dot[I]:E.port[I]})`),p.group.classList.toggle("desktop-mode-window-link--active",l.focused)}for(const[l,c]of Array.from(s))d.has(l)||(c.group.remove(),s.delete(l))},r=e.onFrame(i);return i(e.getFrame()),()=>{r(),s.clear(),o.base.svg.remove(),o.elevated.svg.remove()}}});const Wc="desktop-mode-window-links",Uc="desktop-mode-window--linked",Fc="desktop-mode-window-links--visible";let Hc=!1;function Vb({manager:e,osSettings:t}){if(Hc)return;Hc=!0;let n=t.getOsSettingsSnapshot(),o=null,s=null,i=null,r=null,a=0;const d=new Set;let l=!1;const c=new Set;let u=!1;const p=A=>{const R=A.element;return!R||!R.isConnected||A.state==="minimized"||R.offsetParent===null?null:{x:R.offsetLeft,y:R.offsetTop,width:R.offsetWidth,height:R.offsetHeight}},f=A=>A.state==="snapped-left"||A.state==="snapped-right"?null:p(A),h=()=>{const A=[];for(const x of is()){if(x.rootWindowIds.length===0||x.children.length===0)continue;const $=[],B=(P,X,M)=>{const U=e.getById(P);!U||!M||$.push({windowId:P,role:X,content:M,rect:f(U),focused:U.isFocused(),state:U.state})};for(const P of x.rootWindowIds)B(P,"root",Si(P));for(const P of x.children)B(P.windowId,"child",P.content);$.length>0&&A.push({key:x.key,root:x.root,members:$})}const R=x=>{const $=Number.parseInt(x.element?.style.zIndex||"",10);return Number.isFinite($)?$:null},F=e.getFocused()?.id??null,K=[];for(const x of xn()){const $=e.getById(x.fromWindowId),B=e.getById(x.toWindowId);if(!$||!B)continue;const P=$.isFocused()||B.isFocused();K.push({fromWindowId:x.fromWindowId,toWindowId:x.toWindowId,kind:x.kind,bidirectional:x.bidirectional,focused:P,from:f($),to:f(B),fromZIndex:R($),toZIndex:R(B),elevated:F!==null&&(x.fromWindowId===F||x.toWindowId===F)})}const Y=[];for(const x of e.getAll()){const $=p(x);$&&Y.push({windowId:x.id,rect:$,zIndex:R(x)??0})}return{groups:A,edges:K,obstacles:Y,container:{width:o?.offsetWidth??0,height:o?.offsetHeight??0}}},m=()=>{l||d.size===0||(l=!0,requestAnimationFrame(()=>{if(l=!1,!i)return;const A=h();for(const R of Array.from(d))try{R(A)}catch(F){typeof console<"u"&&console.error("[desktop-mode] window-link frame subscriber threw:",F)}}))},w=()=>{if(o&&o.isConnected&&s?.isConnected)return o;const A=document.getElementById("desktop-mode-area");if(!A)return null;o=document.createElement("div"),o.id=Wc,o.className="desktop-mode-window-links",o.setAttribute("aria-hidden","true"),s=document.createElement("div"),s.id=`${Wc}-elevated`,s.className="desktop-mode-window-links desktop-mode-window-links--elevated",s.setAttribute("aria-hidden","true");const R=document.getElementById("desktop-mode-widgets");return R&&R.parentElement===A?(R.insertAdjacentElement("afterend",s),R.insertAdjacentElement("afterend",o)):A.prepend(o,s),o},g=()=>xn().length>0,k=()=>{let A=n.windowLinkRenderer||Zi;return A=j(y.WINDOW_LINK_RENDERER,A),A===zt?zt:Qi(A)?A:Qi(Zi)?Zi:zt},D=()=>{if(a++,d.clear(),l=!1,r){try{r()}catch(A){T(y.SHELL_ERROR,{scope:"window-link-renderer-teardown",error:A})}r=null}i=null,o?.replaceChildren(),s?.replaceChildren()},b=A=>{const R=Qi(A),F=w();if(!R||!F||!s)return;i=A;const K=++a,Y={container:F,elevatedContainer:s,getFrame:h,onFrame:x=>(d.add(x),()=>{d.delete(x)})};try{const x=R.mount(Y);x instanceof Promise?x.then($=>{if(K!==a){typeof $=="function"&&$();return}typeof $=="function"&&(r=$)}).catch($=>{T(y.SHELL_ERROR,{scope:"window-link-renderer-mount",error:$}),K===a&&(i=null)}):typeof x=="function"&&(r=x)}catch(x){T(y.SHELL_ERROR,{scope:"window-link-renderer-mount",error:x}),i=null}m()},E=()=>{const A=e.getFocused();return A?new Set(bl(A.id)):new Set},I=()=>n.windowLinksEnabled!==!1,O=()=>{if(!o)return;const A=!u&&I()&&(n.windowLinkVisibility==="always"||n.windowLinkVisibility==="focus"&&E().size>0);o.classList.toggle(Fc,A),s?.classList.toggle(Fc,A)},v=()=>{if(!I()||n.windowLinkRaiseOnFocus===!1||n.windowLinkVisibility==="off")return;const A=e.getFocused();if(A)for(const R of rg(A.id)){const F=e.getById(R);F&&F.state!=="minimized"&&e.raise(R)}},N=()=>{if(!s)return;const A=e.getFocused(),R=E();if(!A||R.size===0||!I()||n.windowLinkVisibility==="off"){s.style.zIndex="";return}let F=-1/0;for(const K of[A.id,...R]){const Y=e.getById(K),x=Y?.element;if(!x||Y.state==="minimized")continue;const $=Number.parseInt(x.style.zIndex||"",10);Number.isFinite($)&&(F=Math.max(F,$))}s.style.zIndex=Number.isFinite(F)?String(F):""},C=()=>{const A=I()&&n.windowLinkHighlight!==!1&&n.windowLinkVisibility!=="off"?E():new Set;for(const R of c)A.has(R)||e.getById(R)?.element?.classList.remove(Uc);for(const R of A)e.getById(R)?.element?.classList.add(Uc);c.clear();for(const R of A)c.add(R)},L=()=>{const A=I()&&n.windowLinkVisibility!=="off"&&g()?k():zt;A===zt?i&&D():A!==i&&(D(),b(A)),O(),C(),N(),m()};G(y.WINDOW_BOUNDS_CHANGED,"desktop-mode/window-links-frame",()=>m());for(const A of[y.WINDOW_MOVED,y.WINDOW_RESIZED,y.WINDOW_MINIMIZED,y.WINDOW_RESTORED,y.WINDOW_MAXIMIZED,y.WINDOW_UNMAXIMIZED,y.WINDOW_FULLSCREEN_ENTERED,y.WINDOW_FULLSCREEN_EXITED,y.SNAP_ZONE_COMMITTED,y.SNAP_SPLIT_FILLED,y.DESKTOP_SWITCHED,y.SHELL_RESIZED])G(A,"desktop-mode/window-links-frame",()=>m());G(y.WINDOW_FOCUSED,"desktop-mode/window-links-focus",()=>{v(),O(),C(),N(),m()}),G(y.WINDOW_BLURRED,"desktop-mode/window-links-blur",()=>{O(),C(),N(),m()}),G(y.OVERVIEW_ENTERING,"desktop-mode/window-links-overview",()=>{u=!0,O()}),G(y.OVERVIEW_EXITED,"desktop-mode/window-links-overview",()=>{u=!1,O(),m()}),vl(L),Wb(L),t.subscribeOsSettings(A=>{const R=A.windowLinkRenderer!==n.windowLinkRenderer,F=R||A.windowLinkVisibility!==n.windowLinkVisibility||A.windowLinksEnabled!==n.windowLinksEnabled||A.windowLinkRaiseOnFocus!==n.windowLinkRaiseOnFocus||A.windowLinkHighlight!==n.windowLinkHighlight;n=A,F&&(R&&i&&D(),L())}),L()}function Bc(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function Kb({items:e,onPick:t}){const n=document.createElement("wpd-menu");n.classList.add("desktop-mode-window__menu-panel"),n.classList.add("desktop-mode-window__related-panel");const o=new Map;for(const r of e){const a=o.get(r.group);a?a.push(r):o.set(r.group,[r])}const s=Array.from(o.entries()).sort((r,a)=>Bc(r[0])-Bc(a[0])),i=[];for(const[,r]of s){const a=r.find(d=>typeof d.groupLabel=="string"&&d.groupLabel!=="")?.groupLabel;if(a){const d=document.createElement("div");d.className="desktop-mode-window__related-group",d.setAttribute("role","presentation"),d.textContent=a,n.appendChild(d)}for(const d of r){const l=document.createElement("wpd-menu-item");l.setAttribute("role","menuitem"),l.setAttribute("value",d.id),l.tabIndex=-1,d.icon&&l.setAttribute("icon",d.icon),l.classList.add("desktop-mode-window__related-item"),l.textContent=typeof d.count=="number"?`${d.label} (${d.count})`:d.label,l.addEventListener("wpd-menu-item-click",c=>{c.stopPropagation(),t(d)}),i.push(l),n.appendChild(l)}}return n.addEventListener("keydown",r=>{const a=r,d=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const l=a.key==="ArrowDown";let c=i[l?0:i.length-1];d!==-1&&(c=i[(d+(l?1:-1)+i.length)%i.length]),c?.focus()}else if(a.key==="Home"||a.key==="End")a.preventDefault(),a.stopPropagation(),i[a.key==="Home"?0:i.length-1]?.focus();else if(a.key==="Enter"||a.key===" "){const l=i[d];l&&(a.preventDefault(),a.stopPropagation(),l.dispatchEvent(new CustomEvent("wpd-menu-item-click",{bubbles:!0})))}}),n}function zc(e){if(!e||typeof e!="object")return!1;const t=e,n=o=>typeof o=="string"&&o.trim()!=="";return n(t.id)&&n(t.group)&&n(t.label)&&n(t.url)&&(t.groupLabel===void 0||typeof t.groupLabel=="string")&&(t.icon===void 0||typeof t.icon=="string")&&(t.count===void 0||typeof t.count=="number"&&Number.isFinite(t.count))}function Gc(e){const t=Si(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=j(y.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(zc):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(zc))}function tr(e){e?.querySelectorAll(".desktop-mode-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function Xb(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function Yb(e,t,n){const o=e.closest(".desktop-mode-window__titlebar");if(!o)return;const s=Gc(t.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",a),d.remove(),e.setAttribute("aria-expanded","false")},a=l=>{l.key==="Escape"&&(l.stopPropagation(),r(),e.focus())},d=Kb({items:s,onPick:l=>{r(),Xb(o),n(l)}});d._wpdRelatedClose=r,o.appendChild(d),o.addEventListener("keydown",a),e.setAttribute("aria-expanded","true"),i=l=>{const c=l.target;!c||d.contains(c)||e.contains(c)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),d.querySelector('[role="menuitem"]')?.focus()}function Zb({manager:e,openUrl:t}){Xi({id:"desktop-mode/related-entities",label:S("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>Gc(n.id).length>0,render:(n,o)=>{tr(o.element),n.setAttribute("aria-haspopup","menu"),n.setAttribute("aria-expanded","false"),n.addEventListener("click",s=>{if(s.stopPropagation(),o.element?.querySelector(".desktop-mode-window__related-panel")){tr(o.element);return}Yb(n,o,t)})}}),G(y.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(tr(o.element),o.renderCustomTitleBarButtons?.())})}const jc="none",qc=re("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),$n=qc.state.registry,nr=qc.state.listeners,Vc=/^[a-z0-9_/-]+$/;function Es(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Vc.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===jc&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Vc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.className!="string"&&typeof e.apply!="function"&&t.push("className|apply (at least one must be provided — a CSS class to toggle or an apply callback)")),De("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();$n.set(n,{...e,id:n}),sr()}function Jb(e){$n.delete(e.toLowerCase())&&sr()}function Qb(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from($n.entries()))o.owner===e&&($n.delete(n),t++);return t>0&&sr(),t}function or(){const e=Array.from($n.values()),t=j(y.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function Kc(e){return or().find(t=>t.id===e)}function ev(e){return nr.add(e),()=>{nr.delete(e)}}function sr(){const e=Array.from(nr);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] unfocus-effect registry listener threw:",n)}}Es({id:"darken",label:S("Darken"),description:S("Dim unfocused windows so the focused one stands out."),className:"desktop-mode-window--fx-darken"}),Es({id:"frost",label:S("Frost"),description:S("Throw unfocused windows out of focus — a soft, frosted-glass blur, as if you were looking at them through an iced-over pane."),className:"desktop-mode-window--fx-frost"}),Es({id:"grayscale",label:S("Grayscale"),description:S("Drain the colour from unfocused windows so the focused one is the only thing still in colour — your eye snaps right to it."),className:"desktop-mode-window--fx-grayscale"});function tv(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ie(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(y.SHELL_ERROR,{scope:"unfocus-effect-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(Qb(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function nv(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ie(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(y.SHELL_ERROR,{scope:"window-link-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||($b(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const ir="data-desktop-unfocus-effect",rr="data-desktop-unfocus-effect-class";let Xc=!1;function ov(e){return e.querySelector("canvas")!==null}function sv({manager:e,osSettings:t}){if(Xc)return;Xc=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const d=r.getAttribute(rr);d&&(r.classList.remove(d),r.removeAttribute(rr));const l=r.getAttribute(ir);l&&Kc(l)?.clear?.(r);for(const c of a)c.className&&r.classList.remove(c.className);r.removeAttribute(ir)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(rr,a.className)),r.setAttribute(ir,a.id),a.apply?.(r)},i=()=>{const r=n===jc?void 0:Kc(n),a=or();for(const d of e.getAll()){const l=d.element;l&&(o(l,a),!(!r||d.isFocused()||d.state==="minimized")&&(ov(l)||s(l,r)))}};for(const r of["desktop-mode-window-opened","desktop-mode-window-reopened","desktop-mode-window-closed","desktop-mode-window-focused","desktop-mode-window-blurred"])document.addEventListener(r,()=>i());t.subscribeOsSettings(r=>{n=r.unfocusEffect,i()}),ev(()=>i()),i()}function iv(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Ie(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(y.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(Fg(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Yc=re("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),Wn=Yc.state.registry,rv=Yc.state.listeners,Zc=/^[a-z0-9_/-]+$/;function Jc(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{if(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Zc.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Zc} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!e.tokens||typeof e.tokens!="object")t.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(e.tokens))if(!o.startsWith("--")){t.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof e.match!="function"&&t.push("match (must be a function)")}De("WindowTheme",t,e);const n=e.id.trim().toLowerCase();Wn.set(n,{...e,id:n}),ar()}function Qc(e){Wn.delete(e.toLowerCase())&&ar()}function av(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Wn.entries()))o.owner===e&&(Wn.delete(n),t++);return t>0&&ar(),t}function eu(){return Array.from(Wn.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function ar(){const e=Array.from(rv);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-theme registry listener threw:",n)}}function dv(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async d=>{if(!d.scriptUrl||t.has(d.scriptUrl)){e.add(d.handle);return}try{await Ie(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(l){T(y.SHELL_ERROR,{scope:"window-theme-script-load",handle:d.handle,url:d.scriptUrl,error:l});return}t.add(d.scriptUrl),e.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 eu())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{Jc({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){T(y.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(e)){if(c.has(u))continue;const p=r(u);for(const f of p)Qc(f),o.delete(f);av(u),e.delete(u)}a(l);for(const u of d)!u.handle||e.has(u.handle)||await s(u);n=i(l)}}const tu=re("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),Un=tu.state.registry,lv=tu.state.listeners,nu=/^[a-z0-9_/-]+$/;function Fn(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):nu.test(e.id.trim().toLowerCase())||t.push(`id (must match ${nu} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)"),typeof e.render!="function"&&(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (required when render is omitted)"),typeof e.match!="function"&&t.push("match (must be a function)"),e.placement!==void 0&&e.placement!=="left"&&e.placement!=="right"&&e.placement!=="controls"&&t.push('placement (must be "left", "right", or "controls")')),De("WindowControl",t,e);const n=e.id.trim().toLowerCase();Un.set(n,{...e,id:n}),dr()}function ou(e){Un.delete(e.toLowerCase())&&dr()}function cv(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Un.entries()))o.owner===e&&(Un.delete(n),t++);return t>0&&dr(),t}function su(){return Array.from(Un.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function dr(){const e=Array.from(lv);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-control registry listener threw:",n)}}function uv(){Fn({id:"core/minimize",label:S("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),Fn({id:"core/maximize",label:S("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),Fn({id:"core/focus-tab",label:S("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),Fn({id:"core/close",label:S("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function pv(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ie(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(y.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let 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 su())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(e))if(!d.has(l)){for(const c of i(l))ou(c);cv(l),e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const iu=re("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),Hn=iu.state.registry,fv=iu.state.listeners,ru=/^[a-z0-9_/-]+$/,au=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function du(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):ru.test(e.id.trim().toLowerCase())||t.push(`id (must match ${ru} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):au.has(e.slot)||t.push(`slot (must be one of ${Array.from(au).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),De("WindowSlot",t,e);const n=e.id.trim().toLowerCase();Hn.set(n,{...e,id:n}),cr()}function lr(e){Hn.delete(e.toLowerCase())&&cr()}function mv(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Hn.entries()))o.owner===e&&(Hn.delete(n),t++);return t>0&&cr(),t}function lu(){return Array.from(Hn.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function cr(){const e=Array.from(fv);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-slot registry listener threw:",n)}}function hv(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ie(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(y.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let 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 lu())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(e))if(!d.has(l)){for(const c of i(l))lr(c);mv(l),e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const wv="desktop-mode-notice-dismissed";function gv(){const t=window.wp?.desktop?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function cu(){return`${wv}:${gv()}`}function ur(){try{const e=window.localStorage.getItem(cu());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function uu(e){try{window.localStorage.setItem(cu(),JSON.stringify(e))}catch{}}function pr(e){return e?ur()[e]===!0:!1}function Bn(e){if(!e)return;const t=ur();t[e]=!0,uu(t)}function pu(e){if(!e)return;const t=ur();t[e]&&(delete t[e],uu(t))}const yv=ge`:host{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:10px 14px;font:var( --wpd-notice-font,13px/1.5 var( --desktop-mode-font,system-ui ) );color:var( --wpd-notice-color,var( --desktop-mode-text,#1d2327 ) );background:var( --wpd-notice-bg,rgba( 0,0,0,0.04 ) );border-block-end:1px solid var( --wpd-notice-border,rgba( 0,0,0,0.08 ) );border-inline-start:4px solid var( --wpd-notice-accent,#646970 )}:host( [ hidden ] ){display:none}.wpd-notice__icon{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:var( --wpd-notice-accent,#646970 )}.wpd-notice__icon[ hidden ]{display:none}.wpd-notice__label{flex:1;min-width:0;word-wrap:break-word}::slotted( a ){color:var( --wpd-notice-link,var( --wp-admin-theme-color,#2271b1 ) )}::slotted( p:first-child ){margin-block-start:0}::slotted( p:last-child ){margin-block-end:0}.wpd-notice__close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;background:transparent;color:inherit;opacity:0.6;cursor:pointer;border-radius:4px;transition:opacity 0.12s ease,background-color 0.12s ease}.wpd-notice__close:hover{opacity:1;background:rgba( 0,0,0,0.06 )}.wpd-notice__close:focus-visible{opacity:1;outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:1px}.wpd-notice__close[ hidden ]{display:none}.wpd-notice__close svg{width:14px;height:14px}:host( [ tone='info' ] ){--wpd-notice-accent:var( --wpd-notice-info,#0969da );--wpd-notice-bg:var( --wpd-notice-info-bg,rgba( 9,105,218,0.08 ) );--wpd-notice-border:var( --wpd-notice-info-border,rgba( 9,105,218,0.16 ) )}:host( [ tone='success' ] ){--wpd-notice-accent:var( --wpd-notice-success,#1a7f37 );--wpd-notice-bg:var( --wpd-notice-success-bg,rgba( 26,127,55,0.08 ) );--wpd-notice-border:var( --wpd-notice-success-border,rgba( 26,127,55,0.16 ) )}:host( [ tone='warning' ] ){--wpd-notice-accent:var( --wpd-notice-warning,#9a6700 );--wpd-notice-bg:var( --wpd-notice-warning-bg,rgba( 154,103,0,0.08 ) );--wpd-notice-border:var( --wpd-notice-warning-border,rgba( 154,103,0,0.16 ) )}:host( [ tone='error' ] ),:host( [ tone='danger' ] ){--wpd-notice-accent:var( --wpd-notice-error,#cf222e );--wpd-notice-bg:var( --wpd-notice-error-bg,rgba( 207,34,46,0.08 ) );--wpd-notice-border:var( --wpd-notice-error-border,rgba( 207,34,46,0.16 ) )}:host( [ tone='neutral' ] ){--wpd-notice-accent:var( --wpd-notice-neutral,#57606a );--wpd-notice-bg:var( --wpd-notice-neutral-bg,rgba( 87,96,106,0.08 ) );--wpd-notice-border:var( --wpd-notice-neutral-border,rgba( 87,96,106,0.16 ) )}`,$o=class $o extends me{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&pr(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&Bn(t),this.emit("wpd-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&pu(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return z` |
| 62 |
<span |
| 63 |
class="wpd-notice__icon dashicons ${t??""}" |
| 64 |
?hidden=${!t} |
| 65 |
aria-hidden="true" |
| 66 |
></span> |
| 67 |
<span class="wpd-notice__label"><slot></slot></span> |
| 68 |
<button |
| 69 |
type="button" |
| 70 |
class="wpd-notice__close" |
| 71 |
?hidden=${!n} |
| 72 |
aria-label=${S("Dismiss notice")} |
| 73 |
@click=${o=>this._onDismiss(o)} |
| 74 |
> |
| 75 |
<svg viewBox="0 0 14 14" aria-hidden="true"> |
| 76 |
<path |
| 77 |
d="M3 3 L11 11 M11 3 L3 11" |
| 78 |
stroke="currentColor" |
| 79 |
stroke-width="1.6" |
| 80 |
stroke-linecap="round" |
| 81 |
fill="none" |
| 82 |
></path> |
| 83 |
</svg> |
| 84 |
</button> |
| 85 |
`}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};$o.props=["tone","notDismissible","icon","noticeId"],$o.styles=[yv],$o.help=void 0;let fr=$o;we("wpd-notice",fr);const zn=re("desktop-mode/window-notices",()=>({entries:new Map})),bv=/^[a-z0-9_/-]+$/;function fu(e){return`desktop-mode-notice/${e.toLowerCase()}`}function vv(e){const t=document.createElement("wpd-notice");return t.setAttribute("tone",e.tone??"info"),t.setAttribute("notice-id",e.id),e.dismissible===!1&&t.setAttribute("not-dismissible",""),e.icon&&t.setAttribute("icon",e.icon),t.innerHTML=e.message,t}function mu(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!bv.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};zn.state.entries.set(t,n);const o=fu(t);return du({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=zn.state.entries.get(t);if(!i)return!1;if(typeof i.match!="function")return!0;try{return i.match(s)===!0}catch{return!1}},render:s=>{const i=zn.state.entries.get(t);i&&s.appendChild(vv(i))}}),()=>mr(t)}function mr(e){const t=String(e??"").trim().toLowerCase();t&&zn.state.entries.delete(t)&&lr(fu(t))}function hu(){return Array.from(zn.state.entries.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function kv(e){const t=String(e??"").trim().toLowerCase();t&&Bn(t)}function _v(e){const t=String(e??"").trim().toLowerCase();t&&pu(t)}function Ev(e){if(!e)return;const t=new Set;if(typeof e.window=="string"&&e.window!==""&&t.add(e.window),Array.isArray(e.windows))for(const o of e.windows)typeof o=="string"&&o!==""&&t.add(o);const n=typeof e.urlContains=="string"&&e.urlContains!==""?e.urlContains.toLowerCase():null;if(!(t.size===0&&n===null))return o=>!(t.size>0&&!t.has(o.id)||n!==null&&!(typeof o.config.url=="string"?o.config.url.toLowerCase():"").includes(n))}function wu(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),mu({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:Ev(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of hu())n.owner==="__server__"&&(t.has(n.id)||mr(n.id))}const gu=re("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),Gn=gu.state.registry,Sv=gu.state.listeners,yu=/^[a-z0-9_/-]+$/;function xv(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):yu.test(e.id.trim().toLowerCase())||t.push(`id (must match ${yu} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),De("WindowChrome",t,e);const n=e.id.trim().toLowerCase();Gn.set(n,{...e,id:n}),hr()}function bu(e){Gn.delete(e.toLowerCase())&&hr()}function Iv(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Gn.entries()))o.owner===e&&(Gn.delete(n),t++);return t>0&&hr(),t}function vu(){return Array.from(Gn.values()).sort((e,t)=>e.id.localeCompare(t.id))}function hr(){const e=Array.from(Sv);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[desktop-mode] window-chrome registry listener threw:",n)}}function Cv(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await Ie(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(y.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const d of r){if(!d.scriptHandle||!d.id)continue;let 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 vu())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(e))if(!d.has(l)){for(const c of i(l))bu(c);Iv(l),e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const wr=window.location.origin;let Av=0;const jt=new Map,qt=new Map,jn=new Map;function Lv(e,t){return jn.set(e,t),()=>{jn.get(e)===t&&jn.delete(e)}}function Tv(){return`desktop-mode-conn-${++Av}`}function Nv(e){const t=(d,l)=>{try{d.contentWindow?.postMessage(l,wr)}catch(c){typeof console<"u"&&console.error("[desktop-mode] connection: postMessage failed",c)}},n=(d,l={})=>{const c=Tv(),u=Array.isArray(l.topics)?[...l.topics]:[],p=new Map,f=[];let h=!1,m=!1;const w=()=>{const O=jn.get(d);return O||(e.getById(d)?.iframe??null)},g=()=>{if(w())return!1;const O=e.getById(d);return!!O&&O.config?.native===!0},k=[],D=()=>{const O=w();if(O)for(;f.length;){const v=f.shift();t(O,{type:"desktop-mode-bridge-publish",connectionId:c,topic:v.topic,payload:v.payload})}},b={id:c,target:d,isOpen:()=>h,subscribe(O,v){const N=v;if(g()){const L=Dw(d,O,(A,R)=>{T(y.CONNECTION_MESSAGE,{connectionId:c,topic:R.channel,direction:"in"});try{N(A,{topic:R.channel})}catch(F){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",F)}});return k.push(L),L}let C=p.get(O);return C||(C=new Set,p.set(O,C)),C.add(N),()=>{C?.delete(N)}},send(O,v){if(m)return;if(T(y.CONNECTION_MESSAGE,{connectionId:c,topic:O,direction:"out"}),g()){Rw(d,O,v);return}if(!h){f.push({topic:O,payload:v});return}const N=w();N&&t(N,{type:"desktop-mode-bridge-publish",connectionId:c,topic:O,payload:v})},disconnect(){b._destroy("disconnect")},_targetWindow:w,_handleIframeMessage(O){if(!O||typeof O!="object")return;const v=O;if(v.type==="desktop-mode-bridge-handshake-ack"){if(h)return;h=!0,T(y.CONNECTION_OPENED,{connectionId:c,targetWindowId:d,topics:u,connection:b});try{l.onOpen?.()}catch(N){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",N)}D();return}if(v.type==="desktop-mode-bridge-publish"){const N=O,C=typeof N.topic=="string"?N.topic:"";if(!C)return;T(y.CONNECTION_MESSAGE,{connectionId:c,topic:C,direction:"in"});const L=p.get(C);if(L)for(const R of Array.from(L))try{R(N.payload,{topic:C})}catch(F){typeof console<"u"&&console.error("[desktop-mode] connection subscriber threw:",F)}const A=p.get("*");if(A)for(const R of Array.from(A))try{R(N.payload,{topic:C})}catch(F){typeof console<"u"&&console.error("[desktop-mode] connection wildcard subscriber threw:",F)}return}v.type==="desktop-mode-bridge-disconnect"&&b._destroy("disconnect")},_destroy(O){if(m)return;m=!0;const v=h;h=!1,jt.delete(c);const N=qt.get(d);N&&(N.delete(c),N.size===0&&qt.delete(d));for(const C of k.splice(0))try{C()}catch{}if(v){const C=w();C&&t(C,{type:"desktop-mode-bridge-disconnect",connectionId:c})}T(y.CONNECTION_CLOSED,{connectionId:c,reason:O});try{l.onClose?.(O)}catch(C){typeof console<"u"&&console.error("[desktop-mode] connection.onClose threw:",C)}}};jt.set(c,b);let E=qt.get(d);if(E||(E=new Set,qt.set(d,E)),E.add(c),g())return Promise.resolve().then(()=>{if(!(m||h)){h=!0,T(y.CONNECTION_OPENED,{connectionId:c,targetWindowId:d,topics:u});try{l.onOpen?.()}catch(O){typeof console<"u"&&console.error("[desktop-mode] connection.onOpen threw:",O)}}}),b;const I=w();return I&&t(I,{type:"desktop-mode-bridge-handshake",connectionId:c,targetWindowId:d,topics:u}),b},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;jt.get(c.connectionId)?._handleIframeMessage(d)},s=(d,l,c)=>{const p=jn.get(d)??e.getById(d)?.iframe??null;if(!p)return;const f=j(y.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"},wr)}catch{}return}const h=f&&typeof f=="object"&&Array.isArray(f.topics)?f.topics:c,m=n(d,{topics:h});try{p.contentWindow?.postMessage({type:"desktop-mode-bridge-connection-ack",requestId:l,accepted:!0,connectionId:m.id},wr)}catch{}};return{connect:n,getConnection:d=>jt.get(d)??null,routeIncomingFromIframe:o,onIframeReady:d=>{const l=qt.get(d);if(l)for(const c of Array.from(l)){const u=jt.get(c);if(!u||u.isOpen())continue;const p=u._targetWindow();p&&t(p,{type:"desktop-mode-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:d=>{const l=qt.get(d);if(l)for(const c of Array.from(l))jt.get(c)?._destroy("window-closed")}}}const Dv={};function Ov(...e){(typeof{url:li&&li.tagName.toUpperCase()==="SCRIPT"&&li.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&Dv?"production":void 0)!=="production"&&console.log(...e)}const Rv="iframe:";function gr(e){return Rv+e}function ku(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function Mv(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}class Pv{constructor(t){this.subscribedWindowId=null,this.manager=t.manager,this.adminUrl=t.adminUrl}install(){document.addEventListener("desktop-mode-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&this.onFocused(o.windowId)}),document.addEventListener("desktop-mode-window-closed",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&(_s(gr(o.windowId)),this.subscribedWindowId===o.windowId&&(this.subscribedWindowId=null))}),document.addEventListener("desktop-mode-window-changed",n=>{const o=n.detail;!o||typeof o.windowId!="string"||o.reason==="state"&&o.state==="minimized"&&this.subscribedWindowId===o.windowId&&(this.subscribedWindowId=null)}),window.addEventListener("message",n=>{if(n.origin!==window.location.origin)return;const o=n.data;if(!o||typeof o.type!="string")return;if(o.type==="desktop-mode-bridge-ready"){const i=this.manager.findByIframeSource(n.source);i&&i.id===this.subscribedWindowId&&this.sendSubscribe(i.id);return}if(o.type!=="desktop-mode-commands-list"||!Array.isArray(o.commands))return;const s=this.manager.findByIframeSource(n.source);s&&s.id===this.subscribedWindowId&&this.applyList(s.id,o.commands)});const t=this.manager.getFocused();t&&this.onFocused(t.id)}onFocused(t){if(this.subscribedWindowId!==t){if(this.subscribedWindowId){const n=this.manager.getById(this.subscribedWindowId);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"desktop-mode-commands-unsubscribe"},window.location.origin)}catch{}_s(gr(this.subscribedWindowId))}this.subscribedWindowId=t,this.sendSubscribe(t)}}sendSubscribe(t){const n=this.manager.getById(t);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"desktop-mode-commands-subscribe"},window.location.origin)}catch(o){Ov("[wpd-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=gr(t);_s(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=Mv(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?kd(s.iconSvg):"",a={slug:i,label:s.label,icon:ku(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,ku(s)):this.runProxy(t,s.name)};try{ks(a)}catch(d){console.error("[desktop-mode] iframe-bridge: dropping bad command",a,d)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),dt(t))return;const r=oe(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runProxy(t,n){return(o,s)=>{s.close();const i=this.manager.getById(t);if(!(!i||!i.iframe||!i.iframe.contentWindow)){try{i.iframe.contentWindow.postMessage({type:"desktop-mode-commands-invoke",name:n},window.location.origin)}catch{}this.manager.focus(i)}}}}const _u="global",$v=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,Wv=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,Uv=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,Fv=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,Hv=/getSiteEditorPage\s*\(|site-editor\.php/,Bv=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function zv(e){const t=window.__desktopModeMenuCommands;if(!Array.isArray(t))return null;for(const n of t)if(n&&typeof n=="object"&&n.name===e&&typeof n.url=="string"&&n.url!=="")return{label:typeof n.label=="string"?n.label:"",url:n.url};return null}class Gv{constructor(t){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=t.manager,this.adminUrl=t.adminUrl}install(){this.tryMount(0)}tryMount(t){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){t<40&&window.setTimeout(()=>this.tryMount(t+1),150);return}this.mount()}mount(){const t=window.wp,n=t.element,o=t.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,d=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof d!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const 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 w=new Array(m.length);for(let g=0;g<m.length;g++){const k=m[g];w[g]=k&&k.name?k.name:""}return w.join("|")},p=()=>{let m=[];for(const w of c.loadersList){const g=c.perLoader[w];Array.isArray(g)&&(m=m.concat(g))}Array.isArray(c.statics)&&(m=m.concat(c.statics)),this.callbackCache=Object.create(null);for(const w of m)w&&w.name&&typeof w.callback=="function"&&(this.callbackCache[w.name]=w.callback);this.publish(m)},f=m=>{const w=m.loader;let g=null;try{g=w.hook({search:""})}catch{}const k=g&&Array.isArray(g.commands)?g.commands:[],D=a(()=>u(k),[k]);return i(()=>{c.perLoader[w.name]=k,p()},[D]),i(()=>()=>{delete c.perLoader[w.name],p()},[]),null},h=()=>{const m=d(E=>{const I=E("core/commands");return!I||typeof I.getCommandLoaders!="function"?[]:[...I.getCommandLoaders(!1)||[],...I.getCommandLoaders(!0)||[]]},[]),w=d(E=>{const I=E("core/commands");return!I||typeof I.getCommands!="function"?[]:[...I.getCommands(!1)||[],...I.getCommands(!0)||[]]},[]),g=a(()=>Array.isArray(m)?m.map(E=>E&&E.name||""):[],[m]),k=g.join("|");i(()=>{c.loadersList=g,p()},[k]);const D=a(()=>u(Array.isArray(w)?w:[]),[w]);if(i(()=>{c.statics=Array.isArray(w)?w:[],p()},[D]),!Array.isArray(m)||m.length===0)return null;const b=[];for(const E of m)!E||typeof E.hook!="function"||b.push(s(f,{key:E.name,loader:E}));return s(n.Fragment||"div",null,b)};try{this.root=n.createRoot(l),this.root.render(s(h))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(t){const n=Object.create(null),o=[];for(const i of t)!i||!i.name||!i.label||i.disabled||n[i.name]||(n[i.name]=!0,o.push(this.classify(i)));let s="";for(const i of o)s+=`${i.name}|${i.kind}|${i.url||""} |
| 86 |
`;if(s!==this.lastFingerprint){this.lastFingerprint=s,_s(_u);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!==""?kd(i.iconSvg):void 0,owner:_u,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{ks(d)}catch(l){console.error("[desktop-mode] shell-harvester: dropping bad command",d,l)}}}}classify(t){const n={name:String(t.name),label:String(t.label),icon:typeof t.icon=="string"?t.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof t.callback=="function"?t.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=zv(n.name);if(s){try{n.url=new URL(s.url,this.adminUrl).toString(),n.kind="navigate",s.label!==""&&(n.windowTitle=s.label)}catch{n.kind="skip"}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}if(typeof t.callback=="function"){let i="";try{i=Function.prototype.toString.call(t.callback)}catch{i=""}const r=i.match($v)||i.match(Wv)||i.match(Uv);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(Fv.test(i)){const d=Hv.test(i)?n.name.match(Bv):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(t){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(t);if(typeof o=="string"&&o.toLowerCase().startsWith("<svg"))return o}catch{}return""}iconFor(t){return t.icon&&t.icon.startsWith("dashicons-")?t.icon:t.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}runNavigate(t,n,o){return(s,i)=>{if(i.close(),dt(t))return;const r=oe(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runInvoke(t,n,o){return(s,i)=>{const r=this.callbackCache[t];if(typeof r!="function"){i.close();return}const a=this.runWithNavCapture(r);if(a){i.close();const d=oe(a,this.adminUrl);this.manager.open({id:d,baseId:d,url:a,title:n,icon:o})}}}runWithNavCapture(t){let n=null;const o=d=>{n===null&&typeof d=="string"&&d!==""&&(n=d)},s=window.location,i=new Proxy(s,{get(d,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{t({close:()=>{}})}catch{}finally{for(const d of r)try{delete d.obj[d.key]}catch{}}return n}}const Vt=[];function yr(e){De("Widget",bt(e,Su),e);const t=Vt.findIndex(n=>n.id===e.id);t>=0?Vt[t]=e:Vt.push(e)}function jv(e){const t=Vt.findIndex(n=>n.id===e);t>=0&&Vt.splice(t,1)}function Eu(){const e=Vt.slice(),t=j(y.WIDGETS,e);return Array.isArray(t)?t.filter(qv):(typeof console<"u"&&console.warn("[desktop-mode] `desktop-mode.widgets` filter returned a non-array; falling back to seed list."),e)}function qn(e){return Eu().find(t=>t.id===e)}const Su=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"description",message:"not a string",valid:e=>typeof e.description=="string"},{field:"icon",message:"missing or not a non-empty string",valid:e=>typeof e.icon=="string"&&e.icon!==""},{field:"mount",message:"not a function",valid:e=>typeof e.mount=="function"}];function qv(e){return bt(e,Su).length===0}let Ve=null;function Vv(e){if(Ve)return;const t=document.createElement("div");t.className="desktop-mode-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",S("Add widget"));const n=document.createElement("div");n.className="desktop-mode-widget-picker__title",n.textContent=S("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="desktop-mode-widget-picker__list",t.appendChild(o),Iu(o,e),document.body.appendChild(t),Kv(t,e.anchor);const s=a=>{const d=a.target;d&&(t.contains(d)||e.anchor.contains(d)||xu())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&xu()};document.addEventListener("keydown",i),Ve={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function Vn(){if(!Ve)return;const e=Ve.panel.querySelector(".desktop-mode-widget-picker__list");e&&Iu(e,Ve.options)}function xu(){Ve&&(document.removeEventListener("pointerdown",Ve.onOutsidePointerDown,!0),document.removeEventListener("keydown",Ve.onKeyDown),Ve.panel.remove(),Ve=null)}function Iu(e,t){e.innerHTML="";const n=new Set(t.enabledIds()),o=t.registry();if(o.length===0){const s=document.createElement("div");s.className="desktop-mode-widget-picker__empty",s.textContent=S("No widgets available. Activate a plugin that registers one, or see the docs for the registerWidget API."),e.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="desktop-mode-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("desktop-mode-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=ne(S("%s (already added)"),s.label):a=ne(S("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=S("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function Kv(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.style.visibility="hidden";const o=e.getBoundingClientRect(),s=o.width||320,i=o.height||200,r=6;let a=n.right-s,d=n.top-i-r;a<8&&(a=8),d<8&&(d=n.bottom+r),e.style.left=`${Math.round(a)}px`,e.style.top=`${Math.round(d)}px`,e.style.visibility=""}const Ss="desktop-mode-widgets__card--floating",Xv="desktop-mode-widgets__card--movable",Yv="desktop-mode-widgets__card--resizable",Cu="desktop-mode-widgets__card--dragging",Au="desktop-mode-widgets__card--resizing",Zv=160,Lu=80,Jv=280,Qv=180,xs=20,Tu=5,ek=Tu*Tu,tk='input, textarea, select, button, a, [contenteditable="true"]';function nk(e,t,n){const o=document.createElement("div");o.className="desktop-mode-widgets__card",o.dataset.widgetId=e.id;const s=e.movable===!0,i=e.resizable===!0;s&&o.classList.add(Xv),i&&o.classList.add(Yv),s?o.appendChild(ok(e,n.onRemove,n.onRedock)):o.appendChild(ik(e,n.onRemove));const r=document.createElement("div");r.className="desktop-mode-widgets__card-body",o.appendChild(r),t.geometry?(br(o,uk(t.geometry,t.floatingParent)),o.classList.add(Ss)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${ck(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(Ss),d=[];if(i)for(const c of dk()){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(ak(o,u,c,e,t,n,a))}let l=null;if(s){const c=o.querySelector(".desktop-mode-widgets__chrome");c&&(l=rk(o,c,e,t,n))}return{card:o,body:r,dispose:()=>{for(const c of d)try{c()}catch{}if(l)try{l()}catch{}o.remove()}}}function ok(e,t,n){const o=document.createElement("header");o.className="desktop-mode-widgets__chrome";const s=document.createElement("span");s.className="desktop-mode-widgets__grip",s.setAttribute("aria-hidden","true"),o.appendChild(s);const i=document.createElement("span");i.className="desktop-mode-widgets__title",i.textContent=e.label,o.appendChild(i),o.appendChild(sk(e,n));const r=Nu(e,t);return o.appendChild(r),o}function sk(e,t){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-redock",n.setAttribute("aria-label",ne(S("Dock %s back to widget column"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2 6h6M5.5 3.5L8 6l-2.5 2.5M10 2.5v7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n.dataset.noDrag="true",n}function ik(e,t){const n=Nu(e,t);return n.classList.add("desktop-mode-widgets__card-close--corner"),n}function Nu(e,t){const n=document.createElement("button");return n.type="button",n.className="desktop-mode-widgets__card-close",n.setAttribute("aria-label",ne(S("Remove %s"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2.5 2.5l7 7M9.5 2.5l-7 7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function rk(e,t,n,o,s){let i=null,r=0,a=0,d=0,l=0,c=!1;const u=m=>{if(m.button!==0)return;const w=m.target;w&&w.closest(tk)||(m.preventDefault(),i=m.pointerId,r=m.clientX,a=m.clientY,c=!1,d=parseFloat(e.style.left)||0,l=parseFloat(e.style.top)||0,t.setPointerCapture(i))},p=()=>{if(!e.classList.contains(Ss)){const m=o.floatingParent.getBoundingClientRect(),w=e.getBoundingClientRect(),g={x:w.left-m.left,y:w.top-m.top,width:w.width||n.defaultWidth||Jv,height:w.height||n.defaultHeight||Qv};br(e,g),e.classList.add(Ss),s.onLiberate(g),d=parseFloat(e.style.left)||0,l=parseFloat(e.style.top)||0}e.classList.add(Cu)},f=m=>{if(i===null||m.pointerId!==i)return;const w=m.clientX-r,g=m.clientY-a;if(!c){if(w*w+g*g<ek)return;c=!0,p()}const k=Ou(d+w,l+g,e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${k.x}px`,e.style.top=`${k.y}px`},h=m=>{if(!(i===null||m.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,c&&(c=!1,e.classList.remove(Cu),s.onGeometryChanged(Du(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",f),t.addEventListener("pointerup",h),t.addEventListener("pointercancel",h),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",f),t.removeEventListener("pointerup",h),t.removeEventListener("pointercancel",h)}}function ak(e,t,n,o,s,i,r){let a=null,d=0,l=0,c=0,u=0,p=0,f=0;const h=g=>{if(g.button!==0||!r()&&!lk(n))return;g.preventDefault(),g.stopPropagation(),a=g.pointerId,d=g.clientX,l=g.clientY;const k=e.getBoundingClientRect(),D=s.floatingParent.getBoundingClientRect();c=k.left-D.left,u=k.top-D.top,p=k.width,f=k.height,t.setPointerCapture(a),e.classList.add(Au)},m=g=>{if(a===null||g.pointerId!==a)return;const k=g.clientX-d,D=g.clientY-l,b=pk(n,k,D,c,u,p,f,o,s.floatingParent,r());r()&&(e.style.left=`${b.x}px`,e.style.top=`${b.y}px`,e.style.width=`${b.width}px`),e.style.height=`${b.height}px`},w=g=>{if(!(a===null||g.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(Au),r()?i.onGeometryChanged(Du(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",h),t.addEventListener("pointermove",m),t.addEventListener("pointerup",w),t.addEventListener("pointercancel",w),()=>{t.removeEventListener("pointerdown",h),t.removeEventListener("pointermove",m),t.removeEventListener("pointerup",w),t.removeEventListener("pointercancel",w)}}function dk(){return["n","e","s","w","ne","nw","se","sw"]}function lk(e){return e==="s"}function br(e,t){e.style.left=`${t.x}px`,e.style.top=`${t.y}px`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`}function Du(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function ck(e,t){return Kn(e,t.minHeight??Lu,t.maxHeight??1/0)}function uk(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Ou(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function Ou(e,t,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,a=Math.max(0,i-n-xs),d=Math.max(0,r-o-xs);return{x:Math.min(Math.max(xs,e),a),y:Math.min(Math.max(xs,t),d)}}function pk(e,t,n,o,s,i,r,a,d,l){const c=a.minWidth??Zv,u=a.minHeight??Lu,p=a.maxWidth??1/0,f=a.maxHeight??1/0,h=d.clientWidth||d.getBoundingClientRect().width,m=d.clientHeight||d.getBoundingClientRect().height;let w=o,g=s,k=i,D=r;if((e==="e"||e==="ne"||e==="se")&&(k=Kn(i+t,c,Math.min(p,h-o))),e==="w"||e==="nw"||e==="sw"){const b=Kn(i-t,c,Math.min(p,o+i));w=o+(i-b),k=b}if((e==="s"||e==="se"||e==="sw")&&(D=Kn(r+n,u,Math.min(f,m-s))),e==="n"||e==="ne"||e==="nw"){const b=Kn(r-n,u,Math.min(f,s+r));g=s+(r-b),D=b}return l||(k=i,w=o),{x:w,y:g,width:k,height:D}}function Kn(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const Ru="desktop-mode-widgets",Mu="desktop-mode-widgets-geometry",Pu="desktop-mode-widgets-docked-heights";function $u(){try{return window.localStorage.getItem(Ru)}catch{return null}}function fk(){const e=$u();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function vr(e){try{window.localStorage.setItem(Ru,JSON.stringify(e))}catch{}}function mk(){try{const e=window.localStorage.getItem(Mu);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t)){const i=wk(s);i&&(n[o]=i)}return n}catch{return{}}}function kr(e){try{window.localStorage.setItem(Mu,JSON.stringify(e))}catch{}}function hk(){try{const e=window.localStorage.getItem(Pu);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t))typeof s=="number"&&Number.isFinite(s)&&s>0&&(n[o]=s);return n}catch{return{}}}function Wu(e){try{window.localStorage.setItem(Pu,JSON.stringify(e))}catch{}}function wk(e){if(!e||typeof e!="object")return null;const{x:t,y:n,width:o,height:s}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)||typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||s<=0?null:{x:t,y:n,width:o,height:s}}function gk(e){const t=`desktop-mode.widget.${e}.`,n=o=>{try{return localStorage.getItem(t+o)}catch{return null}};return{get(o){const s=n(o);if(s===null)return null;try{return JSON.parse(s)}catch{return null}},set(o,s){try{localStorage.setItem(t+o,JSON.stringify(s))}catch{}},remove(o){try{localStorage.removeItem(t+o)}catch{}},clear(){try{for(let o=localStorage.length-1;o>=0;o--){const s=localStorage.key(o);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}}}}const yk=["clock"];class bk{constructor(t,n,o){this.mounted=new Map,this.generation=0,this.root=t,this.pluginUrl=n,this.enabledIds=fk(),this.geometry=mk(),this.dockedHeights=hk(),this.floatingHost=o??t.parentElement??t,this.listEl=document.createElement("div"),this.listEl.className="desktop-mode-widgets__list",this.root.appendChild(this.listEl),this.addTile=this.buildAddTile(),this.root.appendChild(this.addTile),this.paintEmptyState()}hydrate(){$u()===null&&(this.enabledIds=yk.filter(t=>!!qn(t)),vr(this.enabledIds));for(const t of this.enabledIds)this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){this.enabledIds.includes(t)||qn(t)&&(this.enabledIds.push(t),vr(this.enabledIds),this.mountById(t),this.paintEmptyState(),T(y.WIDGET_ADDED,{id:t}),Vn())}remove(t){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(vr(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],kr(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],Wu(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),T(y.WIDGET_REMOVED,{id:t}),Vn())}getEnabledIds(){return[...this.enabledIds]}mountIfEnabled(t){qn(t)&&this.enabledIds.includes(t)&&(this.mounted.has(t)||(this.mountById(t),this.paintEmptyState()))}unmount(t){this.mounted.has(t)&&(this.unmountById(t),this.paintEmptyState())}ensureMounted(t){return qn(t)?(this.enabledIds.includes(t)||this.add(t),!0):!1}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t)}mountById(t){const n=qn(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=nk(n,{floatingParent:this.floatingHost,geometry:s,dockedHeight:this.dockedHeights[t]},{onRemove:()=>this.remove(t),onGeometryChanged:u=>this.persistGeometry(t,u),onDockedHeightChanged:u=>this.persistDockedHeight(t,u),onLiberate:u=>this.liberate(t,u),onRedock:()=>this.redock(t)}),r=!!s,a={id:t,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(t,a),this.placeCard(i.card,r);const d={id:t,pluginUrl:this.pluginUrl,storage:gk(t)};T(y.WIDGET_MOUNTING,{id:t,container:i.body,ctx:d});const l=u=>{const p=this.mounted.get(t);if(!p||p.generation!==o){try{u()}catch{}return}p.teardown=u,T(y.WIDGET_MOUNTED,{id:t,container:i.body,ctx:d})};let c;try{c=n.mount(i.body,d)}catch(u){this.handleMountFailure(t,u);return}if(vk(c)){c.then(l,u=>{this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,u)});return}l(c)}unmountById(t){const n=this.mounted.get(t);if(n){T(y.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){T(y.SHELL_ERROR,{scope:"widget-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[desktop-mode] Widget "${t}" teardown threw:`,o)}this.generation++,n.frame.dispose(),this.mounted.delete(t)}}handleMountFailure(t,n){const o=this.mounted.get(t);o&&(o.frame.dispose(),this.mounted.delete(t)),T(y.WIDGET_MOUNT_FAILED,{id:t,error:n}),T(y.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[desktop-mode] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="desktop-mode-widgets__add",t.setAttribute("aria-label",S("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=S("Add widget"),t.appendChild(n),t.appendChild(o),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Vv({anchor:t,registry:()=>Eu(),enabledIds:()=>[...this.enabledIds],onAdd:i=>this.add(i)})}),t}placeCard(t,n){n?this.floatingHost.appendChild(t):this.listEl.appendChild(t)}liberate(t,n){const o=this.mounted.get(t);!o||o.floating||(o.floating=!0,this.floatingHost.appendChild(o.frame.card),br(o.frame.card,n),this.persistGeometry(t,n),this.paintEmptyState())}redock(t){const n=this.mounted.get(t);if(!n||!n.floating)return;n.floating=!1,this.geometry[t]&&(delete this.geometry[t],kr(this.geometry));const o=n.frame.card;o.classList.remove("desktop-mode-widgets__card--floating"),o.style.left="",o.style.top="",o.style.width="";const s=this.dockedHeights[t];o.style.height=s!==void 0?`${s}px`:"",this.listEl.appendChild(o),this.paintEmptyState()}persistGeometry(t,n){this.geometry[t]=n,kr(this.geometry)}persistDockedHeight(t,n){!Number.isFinite(n)||n<=0||(this.dockedHeights[t]=n,Wu(this.dockedHeights))}paintEmptyState(){let t=0;for(const n of this.mounted.values())n.floating||t++;this.root.classList.toggle("desktop-mode-widgets--has-widgets",t>0)}}function vk(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const kk=280,_k=220,Ek=520,Sk=400;function xk(e,t,n){return o=>{const s=document.createElement("iframe");s.style.width="100%",s.style.height="100%",s.style.border="0",s.setAttribute("src",e.url),typeof e.sandbox=="string"&&e.sandbox!==""&&s.setAttribute("sandbox",e.sandbox),o.style.padding="0",o.appendChild(s);const i=Lv(n,s);t.push(i);let r;try{r=new URL(e.url,window.location.origin).origin}catch{r=window.location.origin}let a=null;const d=new Promise(u=>{a=u}),l=()=>{if(e.bridge)try{const u=s.contentDocument;if(u&&!u.querySelector("script[data-desktop-mode-iframe-bridge]")){const p=window.desktopModeConfig?.iframeBridgeUrl;if(p){const f=u.createElement("script");f.src=p,f.setAttribute("data-desktop-mode-iframe-bridge","1"),u.head?.appendChild(f)}}}catch{}Pw(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!==""&&Ow(n,p.channel,p.payload);try{e.onMessage?.(u.data)}catch(f){typeof console<"u"&&console.error("[desktop-mode] iframeContent.onMessage threw:",f)}};return window.addEventListener("message",c),t.push(()=>{window.removeEventListener("message",c),s.removeEventListener("load",l)}),d}}function Ik(e){return async t=>{const n=t.render;let o=n;const s=[];t.iframeContent&&(n&&typeof console<"u"&&console.warn("[desktop-mode] registerWindow: both `render` and `iframeContent` provided — ignoring `render` and using the iframe shorthand. Drop one."),o=xk(t.iframeContent,s,t.id));const i=t.onClose,r=s.length?()=>{for(const d of s)try{d()}catch{}i?.()}:i;return await e.open({id:t.id,baseId:t.baseId||t.id,native:!0,url:t.url||`#${t.id}`,title:t.title,icon:t.icon,x:t.x??0,y:t.y??0,width:t.width??Ek,height:t.height??Sk,minWidth:t.minWidth??kk,minHeight:t.minHeight??_k,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let Ck=0;function Ak(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++Ck}`,s=n.persistent===!0,i=[["opened",y.WINDOW_OPENED],["reopened",y.WINDOW_REOPENED],["focused",y.WINDOW_FOCUSED],["blurred",y.WINDOW_BLURRED],["closing",y.WINDOW_CLOSING],["closed",y.WINDOW_CLOSED],["minimized",y.WINDOW_MINIMIZED],["restored",y.WINDOW_RESTORED],["maximized",y.WINDOW_MAXIMIZED],["unmaximized",y.WINDOW_UNMAXIMIZED],["fullscreenEntered",y.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",y.WINDOW_FULLSCREEN_EXITED],["resized",y.WINDOW_RESIZED],["bodyResized",y.WINDOW_BODY_RESIZED],["boundsChanged",y.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const d=()=>{if(!a){a=!0;for(const l of r)wd(l,o)}};for(const[l,c]of i){const u=t[l];u&&(r.push(c),G(c,o,p=>{const f=p;if(f.windowId!==e)return;const{windowId:h,...m}=f;u(m),l==="closed"&&!s&&d()}))}return d}function Uu(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.desktopModeNativeWindows||{}}}function Lk(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,a=new Set,d=new Map,l=b=>{const E=Gd(b.id);return E?{width:Math.max(E.width,b.minWidth),height:Math.max(E.height,b.minHeight)}:{width:b.width,height:b.height}},c=b=>{if(i.has(b.templateId))return;if(document.getElementById(b.templateId)){i.add(b.templateId);return}if(!b.templateHtml)return;const E=document.createElement("template");E.id=b.templateId,E.innerHTML=b.templateHtml,document.body.appendChild(E),i.add(b.templateId)},u=b=>{const E=b.styleUrl;if(!E||a.has(E))return;const I=E.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${I}"]`)){const v=document.createElement("link");v.rel="stylesheet",v.href=E,b.styleHandle&&(v.dataset.desktopModeStyleHandle=b.styleHandle),document.head.appendChild(v)}if(Array.isArray(b.styleInline))for(const v of b.styleInline){if(typeof v!="string"||v==="")continue;const N=document.createElement("style");b.styleHandle&&(N.dataset.desktopModeStyleHandle=b.styleHandle),N.textContent=v,document.head.appendChild(N)}a.add(E)},p=async b=>{if(!(!b.scriptUrl||r.has(b.scriptUrl))){try{await Ie(b.scriptUrl,{translations:b.scriptTranslations,l10n:b.scriptL10n,before:b.scriptBefore,after:b.scriptAfter})}catch(E){T(y.SHELL_ERROR,{scope:"native-window-script-load",id:b.id,error:E})}r.add(b.scriptUrl)}},f=b=>{const E=Uu()[b.id],I=(v,N)=>(v.appendChild(_r(b.templateId)),E?.(v,N)),O=l(b);t.open({id:b.id,baseId:b.id,native:!0,url:`#${b.id}`,title:b.title,icon:b.icon,width:O.width,height:O.height,minWidth:b.minWidth,minHeight:b.minHeight,render:I,autofocus:b.autofocus,ownerHandle:b.ownerHandle||b.scriptHandle})},h=b=>{const E=Uu()[b.id],I=(v,N)=>(v.appendChild(_r(b.templateId)),E?.(v,N)),O=l(b);t.openNew({id:b.id,baseId:b.id,native:!0,url:`#${b.id}`,title:b.title,icon:b.icon,width:O.width,height:O.height,minWidth:b.minWidth,minHeight:b.minHeight,initialState:"normal",render:I,autofocus:b.autofocus,ownerHandle:b.ownerHandle||b.scriptHandle})},m=async b=>{if(!s.has(b.id)){if(b.placement==="none"){c(b),u(b),await p(b),s.add(b.id);return}c(b),u(b),await p(b),n({id:b.id,title:b.title,icon:b.icon,isOpen:()=>!!t.getById(b.id),onOpen:()=>f(b)}),T(y.DOCK_ITEM_APPENDED,{id:b.id}),s.add(b.id)}},w=b=>{s.has(b)&&(o(b),s.delete(b),d.delete(b))},g=async b=>{const E=new Set;for(const I of b)E.add(I.id),d.set(I.id,I);for(const I of Array.from(s))E.has(I)||w(I);for(const I of b)s.has(I.id)||await m(I)},k=(b,E={})=>{const I=d.get(b);return I?(ve.publish("desktop-mode/open-requested",{windowId:b,source:E.source??"api"}),f(I),!0):!1},D=(b,E={})=>{const I=d.get(b);return I?(ve.publish("desktop-mode/open-requested",{windowId:b,source:E.source??"api"}),h(I),!0):!1};return G(y.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",b=>{const E=b,I=E?.windowId,O=E?.width,v=E?.height;if(!I||typeof O!="number"||typeof v!="number")return;const N=t.getById(I);if(!N||N.state!=="normal")return;const C=N.config.baseId||N.id;jd(C,{width:O,height:v}),N.element&&qd(C,{x:N.element.offsetLeft,y:N.element.offsetTop})}),G(y.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",b=>{const E=b?.windowId;if(!E)return;const I=t.getById(E);if(!I||I.state!=="normal"||!I.element)return;const O=I.config.baseId||I.id;jd(O,{width:I.element.offsetWidth,height:I.element.offsetHeight}),qd(O,{x:I.element.offsetLeft,y:I.element.offsetTop})}),G(y.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",b=>{const E=b?.windowId;if(!E)return;const I=t.getById(E);if(!I)return;const O=I.config.baseId||I.id,v=d.get(O),N=v?{width:v.width,height:v.height}:{width:I.config.width,height:I.config.height};Vd(O,"maximized",N)}),G(y.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",b=>{const E=b?.windowId;if(!E)return;const I=t.getById(E);if(!I)return;const O=I.config.baseId||I.id;Vd(O,null)}),{sync:g,openById:k,openNewById:D}}function _r(e){let t=null;if(typeof e=="string"){const n=document.getElementById(e);n instanceof HTMLTemplateElement&&(t=n)}else t=e;if(!t)throw new Error(`[desktop-mode] cloneTemplate: no <template> found for ${typeof e=="string"?`#${e}`:"<reference>"}`);return t.content.cloneNode(!0)}function Fu(e){const t=window.wp?.desktop,n=window.desktopModeConfig,o=t?.config?.adminUrl??n?.adminUrl;if(!o)return null;const s=t?.getMenuItems?.()??n?.dockItems??[],i=oe(e,o);return s.find(r=>oe(r.url,o)===i||(r.submenu??[]).some(a=>oe(a.url,o)===i))??null}const Hu="desktop-mode-icon__badge",Xn=new Map;function Tk(e){return Math.max(0,Math.floor(Number(e)||0))}function Bu(e,t){if(!e)return;const n=Mk(e);if(!n)return;const o=Tk(t),s=Xn.get(e)??0;o!==s&&(o===0?Xn.delete(e):Xn.set(e,o),ju(n,o),ve.publish("desktop-mode/badge-changed",{itemId:e,count:o,rail:"icon"}),T(y.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function Nk(e){Bu(e,0)}function Dk(e){return Xn.get(e)??0}const Ok={setBadge:Bu,clearBadge:Nk,getBadge:Dk};function Rk(e){return!e||e.length===0?"":e.map(t=>`${t.id}|${t.title}|${t.icon}|${t.window??""}|${t.url??""}|${t.position??0}|${t.pinned?1:0}`).join(";")}let zu="";function Gu(e,t,n){const o=Rk(t);if(o===zu&&e.querySelector(":scope > .desktop-mode-icons"))return;zu=o;const s=e.querySelector(":scope > .desktop-mode-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="desktop-mode-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",S("Desktop icons"));const r=[...t].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=$k(d,n),c=Xn.get(d.id)??0;c>0&&ju(l,c),i.appendChild(l),a.set(d.id,l)}e.appendChild(i),T(y.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(d=>d.id),container:i,tiles:a})}function Mk(e){if(!e)return null;const t=document.querySelector(".desktop-mode-icons");return t?t.querySelector(`[data-icon-id="${Pk(e)}"]`):null}function ju(e,t){const n=e.querySelector(`:scope > .${Hu}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=ne(vn("%d notification","%d notifications",t),t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",s);return}const i=document.createElement("span");i.className=Hu,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function Pk(e){const t=window.CSS;return t?.escape?t.escape(e):e}function $k(e,t){const n=document.createElement("button");n.type="button",n.className=e.pinned?"desktop-mode-icon desktop-mode-icon--pinned":"desktop-mode-icon",n.dataset.iconId=e.id,e.pinned&&(n.dataset.pinned="1"),n.setAttribute("role","listitem"),n.setAttribute("aria-label",e.title);const o=yi(e.icon,{title:e.title,className:"desktop-mode-icon__image"});n.appendChild(o);const s=document.createElement("span");return s.className="desktop-mode-icon__label",s.textContent=e.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),T(y.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),Wk(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),Yl({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function Wk(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(ds(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=Fu(n.toString());t.manager.open({id:o,baseId:o,url:n.toString(),parentUrl:s?.url??n.toString(),title:e.title,icon:e.icon,submenu:s?.submenu,multi:!!s?.multi})}catch{}}}const qu="desktop-mode-side-dock";function Uk(e,t){return{id:`dock-core:${e.id}`,title:e.title,icon:e.icon,window:"",url:e.url,position:1e3+t}}function Fk(e,t,n,o){let s=t,i=n,r=o??[],a=null,d=null,l=null,c=null,u=null;const p=new Map,f=C=>C==="core"&&d?d:a,h=()=>{const C=document.getElementById(qu);if(C)return C;const L=document.createElement("nav");return L.id=qu,L.className="desktop-mode-dock",L.setAttribute("role","toolbar"),L.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(L,e.shellBody.firstChild),L},m=()=>{u&&u.parentNode&&u.parentNode.removeChild(u),u=null},w=()=>e.getSettings?.()??{itemVisibility:{},dockOrder:[]},g=()=>{const C=new Set;for(const L of p.values())C.add(L.item.id);return ry(i,r,w(),C)},k=()=>{const C=g(),L=[],A=[];for(const R of C)R.isCore?L.push(R):A.push(R);return{core:L,plugin:A}},D=()=>{const C=w();if(s!=="spatial"){e.renderIcons(ay(r,i,C.itemVisibility));return}const{core:L}=k(),A=L.map(Uk),R=r.filter(Y=>{const x=C.itemVisibility[Y.id];return x?x==="desktop"||x==="both":!!Y.pinned}),F=[];let K=0;for(const Y of i){const x=C.itemVisibility[Y.id];(x==="desktop"||x==="both")&&F.push({id:`dock:${Y.id}`,title:Y.title,icon:Y.icon,window:"",url:Y.url||"",position:2e3+K++})}e.renderIcons([...A,...R,...F])},b=()=>{if(a){try{a.destroy()}catch(C){T(y.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:C})}a=null,l=null}if(d){try{d.destroy()}catch(C){T(y.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:C})}d=null,c=null}},E=C=>{const L=Di();if(!L)return T(y.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return L.mount(C)}catch(A){if(T(y.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:L.id,error:A}),L===$i)return null;try{return $i.mount(C)}catch{return null}}},I=(C,L,A)=>({container:C,items:L,fullMenu:i.slice(),fullSystemTiles:Array.from(p.values()).map(R=>R.item),orientation:A,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:R=>{const F=oe(R.url,e.adminUrl);e.windowManager.open({id:F,baseId:F,url:R.url,parentUrl:R.url,title:R.title,icon:R.icon.startsWith("dashicons-")?R.icon:"dashicons-admin-generic",submenu:R.submenu,multi:!!R.multi})},openSubmenuPick:(R,F)=>{e.windowManager.open({id:oe(F.url,e.adminUrl),baseId:oe(R.url,e.adminUrl),url:F.url,parentUrl:R.url,title:R.title,icon:R.icon.startsWith("dashicons-")?R.icon:"dashicons-admin-generic",submenu:R.submenu,multi:!!R.multi})},openSystemItem:R=>R.onOpen()}),O=()=>{b();const{core:C,plugin:L}=k();s==="classic"?(u=h(),d=E(I(u,C,"left")),c=ps(d),a=E(I(e.bottomDockEl,L,"bottom")),l=ps(a)):s==="unified"?(m(),a=E(I(e.bottomDockEl,g(),"bottom")),l=ps(a)):(m(),a=E(I(e.bottomDockEl,L,"bottom")),l=ps(a));for(const A of p.values())f(A.affinity)?.appendSystemItem(A.item)},v={getLayout:()=>s,getPrimary:()=>l,getSide:()=>c,setLayout:C=>{C!==s&&(s=C,e.shellRoot.setAttribute("data-desktop-mode-layout",C),O(),D(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:C,primary:l,side:c}})))},applyDockItems:C=>{i=C;const{core:L,plugin:A}=k();s==="classic"?(d?.replaceItems(L),a?.replaceItems(A)):s==="unified"?a?.replaceItems(g()):a?.replaceItems(A),D()},applyDesktopIcons:C=>{r=C??[],D()},appendSystemTile:(C,L="plugin")=>{p.set(C.id,{item:C,affinity:L}),f(L)?.appendSystemItem(C)},removeSystemTile:C=>{const L=p.get(C);L&&(p.delete(C),f(L.affinity)?.removeSystemItem(C))},listSystemTiles:()=>Array.from(p.values()).map(C=>({id:C.item.id,title:C.item.title,icon:C.item.icon,affinity:C.affinity})),getSystemTile:C=>p.get(C)?.item??null,getMenuItems:()=>i.slice(),refresh:()=>{const{core:C,plugin:L}=k();s==="classic"?(d?.replaceItems(C),a?.replaceItems(L)):s==="unified"?a?.replaceItems(g()):a?.replaceItems(L),D()},destroy:()=>{b(),m()}};e.shellRoot.setAttribute("data-desktop-mode-layout",s),O(),D();let N=Di()?.id??null;return Bg(()=>{const C=Di()?.id??null;C!==N&&(N=C,O(),D(),document.dispatchEvent(new CustomEvent("desktop-mode-layout-changed",{detail:{layout:s,primary:l,side:c}})))}),v}function Hk(e){return window.desktopModeCreateAiAssistant?Promise.resolve(window.desktopModeCreateAiAssistant):new Promise((t,n)=>{const o=document.querySelector('script[data-desktop-mode-ai="1"]'),s=()=>{const r=window.desktopModeCreateAiAssistant;if(!r){n(new Error("[desktop-mode] ai-assistant bundle loaded but did not register desktopModeCreateAiAssistant"));return}t(r)};if(o){window.desktopModeCreateAiAssistant?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.desktopModeAi="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))),document.head.appendChild(i)})}class Bk{constructor(t,n){this._real=null,this._loadPromise=null,this._pendingAsk=null,this._intendOpen=!1,this.ask=(...o)=>this._ensure().then(s=>s.ask(...o)),this._config=t,this._scriptUrl=n}_ensure(){return this._loadPromise?this._loadPromise:(this._loadPromise=Hk(this._scriptUrl).then(t=>{const n=t(this._config);return this._pendingAsk&&n.attachAsk(this._pendingAsk),this._real=n,n}),this._loadPromise)}open(){this._intendOpen=!0,this._ensure().then(t=>t.open())}close(){this._intendOpen=!1,this._real&&this._real.close()}toggle(){this.isOpen?this.close():this.open()}get isOpen(){return this._real?this._real.isOpen:this._intendOpen}attachAsk(t){this._pendingAsk=t,this._real&&this._real.attachAsk(t)}}const Vu=e=>!e||typeof e!="object"?!1:e.name==="AbortError",zk=e=>{if(!e)return[];const t=xb();if(e===!0||e==="aiCallable")return t;if(Array.isArray(e)){const n=new Set(e.map(o=>o.toLowerCase()));return t.filter(o=>n.has(o.slug))}return typeof e=="function"?t.filter(n=>{try{return e(n.slug)===!0}catch{return!1}}):[]},Gk=e=>e?typeof e=="string"?{text:e,mode:"append"}:typeof e=="object"&&typeof e.text=="string"&&e.text!==""?{text:e.text,mode:e.mode==="replace"?"replace":"append"}:null:null;function jk(e,t){const n=e??"";return n!==""?n:typeof t=="string"&&t!==""?t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"?t.message:""}function qk(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function Vk(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",d=r.restNonce??"";if(!a||!d)throw new Error("[desktop-mode] wp.desktop.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Pe(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 Vu(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=Ib(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??e.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:qk(a)}};d&&(c.system_prompt_text=d.text,c.system_prompt_mode=d.mode);let u;try{u=await t(c,l)}catch(h){if(Vu(h))throw h;return null}if(!u.ok)return null;const p=await u.json().catch(()=>({}));return(typeof p.message=="string"?p.message.trim():"")!==""?p.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[desktop-mode] wp.desktop.ai.ask: empty query passed with non-default options — likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const d=zk(r.tools),l=Gk(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 t(c,r.signal);if(!u.ok){const k=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[desktop-mode] wp.desktop.ai.ask: HTTP ${u.status} — ${k.message??u.statusText}`)}const p=await u.json();if(p.answer_type!=="tool_call"||!p.tool)return{answer_type:p.answer_type,message:p.message??"",entity:p.entity??null,admin_links:p.admin_links??null,request_id:p.request_id,continue:p.continue??null};const f=await n(p,r);if(!f.ok)return f.response;const{slug:h,args:m,result:w}=f;let g=jk(p.message,w);if(r.followUp===!0){const k=await o(a,h,m,w,l,r.signal);k!==null&&(g=k)}return{answer_type:"tool_call",message:g,entity:null,admin_links:null,toolCall:{slug:h,args:m,result:w},request_id:p.request_id}}}const Er="desktop-mode-broadcast",Ku="desktop-mode-broadcast",Xu=window.location.origin;let Sr=null;function Kk(e){Sr=e}function xr(e,t){const n=String(j("desktop-mode.broadcast.topic",e,{payload:t})??e),o=j("desktop-mode.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Er,{detail:s})),T(y.BROADCAST,s),ve.publish(n,o),!Sr)return;const i={type:Ku,topic:n,payload:o};for(const r of Sr._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Xu)}catch{}}}function Fe(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){T(y.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Er,n),()=>document.removeEventListener(Er,n)}function Xk(){window.addEventListener("message",e=>{if(e.origin!==Xu)return;const t=e.data;!t||t.type!==Ku||t._fromParent||typeof t.topic=="string"&&xr(t.topic,t.payload)})}const Yu="[desktop-mode-bin badge]";function Ke(...e){try{window.localStorage?.getItem("desktopModeBinDebug")&&console.info(Yu,...e)}catch{}}function Is(...e){console.warn(Yu,...e)}const Je="desktop-mode-recycle-bin",Yk="desktop_mode_recycle_bin_seen_ts";function Zu(){return window.wp?.desktop}const ue=re("desktop-mode/recycle-bin/badge",()=>({current:0,seenTs:0,started:!1,countUrl:""}));function Yn(e){const t=Math.max(0,Math.floor(e)),n=ue.state.current;ue.state.current=t,Ke("setRecycleBinBadge",{prev:n,next:t}),Cs(t)}function Ju(e){Yn(ue.state.current+e)}function Zk(){return ue.state.current}function Cs(e){const t=Zu(),n=Jk(),o=n?0:e;Ke("paintBadge",{count:e,visible:o,active:n}),t?.dock?.setBadge?.(Je,o),t?.taskbar?.setBadge?.(Je,o),t?.icons?.setBadge?.(Je,o)}function Jk(){const e=Zu()?.windowManager;return e?.isActiveByBaseId?e.isActiveByBaseId(Je):!!e?.isActive?.(Je)}function Qk(e,t=""){const n=Number(e)||0,o=window.desktopModeConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl,r=o?.desktopModeBinDebug;Ke("startRecycleBinBadge entry",{initial:n,countUrl:t,alreadyStarted:ue.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)||Is("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}),ue.state.started){Yn(n);return}ue.state.started=!0,ue.state.countUrl=t,ue.state.seenTs=Date.now(),Yn(n),t_(),n_(),o_(),s_(),i_(),e_()}function e_(){const e="desktop-mode/recycle-bin/badge-lifecycle",t=n=>{const s=n?.windowId;!s||!(s===Je||s.startsWith(Je+"-"))||Cs(ue.state.current)};G(y.WINDOW_OPENED,e,t),G(y.WINDOW_FOCUSED,e,t),G(y.WINDOW_BLURRED,e,t),G(y.WINDOW_MINIMIZED,e,t),G(y.WINDOW_RESTORED,e,t),G(y.WINDOW_CLOSED,e,t),G(y.WINDOW_REOPENED,e,t)}function t_(){G(y.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/badge",e=>{e?.id===Je&&Cs(ue.state.current)})}function n_(){G(y.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/badge",e=>{e?.ids?.includes(Je)&&Cs(ue.state.current)})}function o_(){const e=t=>{const n=t;if(!n)return;const o=Array.isArray(n.ids)?n.ids.length:0;switch(n.action){case"trashed":Ju(+o);break;case"untrashed":case"deleted":Ju(-o);break}};Fe("desktop-mode.post.changed",e),Fe("desktop-mode.page.changed",e),Fe("desktop-mode.attachment.changed",e),Fe("desktop-mode.comment.changed",e),Fe("desktop-mode.placement.changed",e),Fe("desktop-mode.shortcut.changed",e),Fe("desktop-mode.folder.changed",e)}function s_(){const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;if(!n||n.type!=="desktop-mode-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=ue.state.seenTs){Ke("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:ue.state.seenTs});return}Ke("postMessage triggers refetch",{ts:o,prevSeenTs:ue.state.seenTs}),ue.state.seenTs=o,r_()})}function i_(){const e=window.jQuery;if(!e){Is("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}Ke("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[Yk]=ue.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.desktop_mode_recycle_bin;Ke("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>ue.state.seenTs&&(ue.state.seenTs=o.ts),typeof o.count=="number"&&Yn(o.count))})}async function r_(){if(!ue.state.countUrl){Ke("refetchCount: no countUrl, skip");return}Ke("refetchCount: hitting",ue.state.countUrl);try{const e=await fetch(ue.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){Is("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();Ke("refetchCount: response",t),typeof t.count=="number"&&Yn(t.count)}catch(e){Is("refetchCount: fetch failed",e)}}const a_="desktop-mode-os-settings",d_="desktop-mode-recycle-bin";function l_(e){const t=p_();t&&t.addFilter("desktop-mode.dock.peek-card-content","desktop-mode/built-in-peek-renderers",(n,o)=>{const s=o,i=s.window.id;return i===a_?c_():i===d_?u_(s,e.getRecycleBinCount):n})}function c_(e){const t=document.createElement("span");t.className="desktop-mode-dock-peek__card-body desktop-mode-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="desktop-mode-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="desktop-mode-dock-peek__os-subtitle",o.textContent=S("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="desktop-mode-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`desktop-mode-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function u_(e,t){const n=document.createElement("span");n.className="desktop-mode-dock-peek__card-body desktop-mode-dock-peek__card-body--recycle-bin",n.setAttribute("aria-hidden","true");const o=Math.max(0,Math.floor(t()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="desktop-mode-dock-peek__bin-stage";const i=document.createElement("span");i.className="desktop-mode-dock-peek__bin-stack";for(let d=0;d<3;d++){const 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=S("Recycle Bin — empty"):o===1?a.textContent=S("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function p_(){return window.wp?.hooks??null}const Zn="desktop-mode-bug-report",f_="WordPress",m_="desktop-mode",Qu=6e3;function h_(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="desktop-mode-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="desktop-mode-bug-report__intro",n.textContent=S("Found a bug or have a feature idea? Fill this in and we will open a pre-filled GitHub issue for you to review and submit."),t.appendChild(n),t.appendChild(w_()),t.appendChild(g_("title",S("Title"),{placeholder:S("A short summary"),required:!0})),t.appendChild(ep("description",S("What happened? What did you expect?"),{placeholder:S("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(ep("steps",S("Steps to reproduce (bug only)"),{placeholder:S("One step per line"),rows:4}));const o=y_();t.appendChild(o);const s=document.createElement("div");s.className="desktop-mode-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="desktop-mode-bug-report__submit",i.textContent=S("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="desktop-mode-bug-report__hint",r.textContent=S("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const d=v_(t);if(!d.title.trim()||!d.description.trim()){b_(t,S("Title and description are both required."));return}const l=k_(d);window.open(l,"_blank","noopener")}),e.appendChild(t)}function w_(){const e=document.createElement("div");e.className="desktop-mode-bug-report__field desktop-mode-bug-report__field--type";const t=document.createElement("span");t.className="desktop-mode-bug-report__label",t.textContent=S("Type"),e.appendChild(t);const n=document.createElement("div");n.className="desktop-mode-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:S("Bug"),checked:!0},{value:"feature",label:S("Feature request")},{value:"question",label:S("Question")}];for(const s of o){const i=document.createElement("label");i.className="desktop-mode-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const a=document.createElement("span");a.textContent=s.label,i.appendChild(a),n.appendChild(i)}return e.appendChild(n),e}function g_(e,t,n={}){const o=document.createElement("div");o.className="desktop-mode-bug-report__field";const s=document.createElement("label");s.className="desktop-mode-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("input");return i.type="text",i.name=e,i.className="desktop-mode-bug-report__input",n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function ep(e,t,n={}){const o=document.createElement("div");o.className="desktop-mode-bug-report__field";const s=document.createElement("label");s.className="desktop-mode-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("textarea");return i.name=e,i.className="desktop-mode-bug-report__textarea",i.rows=n.rows??4,n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function y_(){const e=document.createElement("details");e.className="desktop-mode-bug-report__metadata";const t=document.createElement("summary");t.textContent=S("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="desktop-mode-bug-report__metadata-body",n.textContent=np(tp()),e.appendChild(n),e}function b_(e,t){let n=e.querySelector(".desktop-mode-bug-report__error");n||(n=document.createElement("div"),n.className="desktop-mode-bug-report__error",n.setAttribute("role","alert"),e.prepend(n)),n.textContent=t}function v_(e){const t=new FormData(e);return{type:t.get("type")??"bug",title:t.get("title")??"",description:t.get("description")??"",steps:t.get("steps")??""}}function k_(e){const t=__(e.type),n=E_(e),o=new URLSearchParams;return o.set("title",e.title.trim()),o.set("body",n),t.length&&o.set("labels",t.join(",")),`https://github.com/${f_}/${m_}/issues/new?${o.toString()}`}function __(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function E_(e){const t=[];t.push(e.description.trim()),e.type==="bug"&&e.steps.trim()&&(t.push(""),t.push("## Steps to reproduce"),t.push(""),t.push(e.steps.trim())),t.push(""),t.push("<details><summary>Environment</summary>"),t.push(""),t.push("```"),t.push(np(tp())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(` |
| 87 |
`);return n.length>Qu&&(n=n.slice(0,Qu)+` |
| 88 |
|
| 89 |
…(truncated to fit GitHub URL length limit)`),n}function tp(){const e=window.wp?.desktop?.config;return{pluginVersion:e?.pluginVersion??"unknown",wordpressVersion:e?.wordpressVersion??"unknown",userAgent:navigator.userAgent,viewport:`${window.innerWidth}x${window.innerHeight}`,platform:navigator.platform||"unknown",currentUrl:window.location.href}}function np(e){return[`Plugin version: ${e.pluginVersion}`,`WordPress version: ${e.wordpressVersion}`,`User agent: ${e.userAgent}`,`Viewport: ${e.viewport}`,`Platform: ${e.platform}`,`Current URL: ${e.currentUrl}`].join(` |
| 90 |
`)}let As=null,op=!1,sp=!1,ip=!1,St="pending";function S_(){if(sp)return;sp=!0;const e=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{e&&(ip||I_()||(C_(),ip=!0,setTimeout(()=>window.location.reload(),0)))})}const rp="wpd-sw-reload-ts",x_=3e4;function I_(){try{const e=sessionStorage.getItem(rp),t=e?Number.parseInt(e,10):0;return!Number.isFinite(t)||t<=0?!1:Date.now()-t<x_}catch{return!1}}function C_(){try{sessionStorage.setItem(rp,String(Date.now()))}catch{}}async function A_(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return St="unsupported",null;if(As||op)return As;if(!t.forceReplace){const o=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(s=>{const i=s.active?.scriptURL??s.installing?.scriptURL??"";return i!==""&&i!==e.swUrl});if(o)return St="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 As=await navigator.serviceWorker.register(e.swUrl,{scope:"/",updateViaCache:"none"}),St="registered",S_(),As}catch(n){return op=!0,St="failed",typeof console<"u"&&console.warn("[desktop-mode] SW registration failed:",n),null}}function L_(){return St}const T_="desktop-mode-pwa-install";function ap(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function dp(){if(ap())return!0;const e=window.navigator;if(typeof e.getInstalledRelatedApps!="function")return!1;try{const t=await e.getInstalledRelatedApps();return Array.isArray(t)&&t.length>0}catch{return!1}}let ct=null;function N_(e,t){if(typeof window>"u")return;window.removeEventListener("beforeinstallprompt",n),window.addEventListener("beforeinstallprompt",n),window.removeEventListener("appinstalled",o),window.addEventListener("appinstalled",o);function n(s){s.preventDefault(),ct=s}function o(){ct=null,t({message:ne(S("Installed %s as an app."),e)})}}function D_(e,t){return{id:T_,title:ne(S("Install %s as an app"),e),icon:"dashicons-download",onOpen:()=>{O_(e,t)}}}async function O_(e,t){if(ct){const n=ct;ct=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:S("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[desktop-mode] install prompt failed:",o)}return}if(await dp()){t({message:ne(S("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(L_()==="foreign-sw"){t({message:S("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the desktop_mode_pwa_force_replace_sw filter to true.")});return}t({message:S("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 R_(){if(!ct)return"unavailable";const e=ct;ct=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function M_(){Promise.resolve().then(()=>Jy).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function P_(e,t){e.pwa&&(pc(e.pwa),N_(e.pwa.appName||"WordPress",t),A_(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw}))}const Kt={START:"desktop-mode-cross-frame-drag-start",END:"desktop-mode-cross-frame-drag-end"};function $_(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-start"&&!!e.payload&&typeof e.payload=="object"}function W_(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-end"}function U_(e){return!!e&&typeof e=="object"&&e.type==="desktop-mode-drag-payload-request"}function F_(e){const t=e;return t.kind!==void 0&&t.kind!==null?e:typeof t.id=="number"&&typeof t.url=="string"&&typeof t.mime=="string"?{kind:"attachment",id:t.id,url:t.url,title:typeof t.title=="string"?t.title:"",alt:typeof t.alt=="string"?t.alt:"",mime:t.mime,thumbnailUrl:typeof t.thumbnailUrl=="string"?t.thumbnailUrl:void 0,sizes:t.sizes&&typeof t.sizes=="object"?t.sizes:void 0}:e}class H_{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if($_(n)){this._startDrag(n.payload);return}if(W_(n)){this._endDrag();return}if(U_(n)&&this._payload&&t.source)try{t.source.postMessage({type:"desktop-mode-drag-payload",payload:this._payload},this._origin)}catch{}},this._origin=window.location.origin,window.addEventListener("message",this._onMessage)}getPayload(){return this._payload}isDragging(){return this._payload!==null}start(t){this._payload!==t&&this._startDrag(t)}end(){this._endDrag()}_startDrag(t){const n=F_(t);this._payload=n,document.dispatchEvent(new CustomEvent(Kt.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(Kt.END,{detail:{payload:t}}))}}class B_{constructor(){this._targets=new Map,this._byElement=new Map}register(t){const n=this._targets.get(t.id);return n&&this._byElement.delete(n.element),this._targets.set(t.id,t),this._byElement.set(t.element,t),()=>{this._targets.get(t.id)===t&&(this._targets.delete(t.id),this._byElement.delete(t.element))}}list(){return Array.from(this._targets.values())}clear(){this._targets.clear(),this._byElement.clear()}hitTest(t){let n=t;for(;n;){if(n instanceof HTMLElement){const o=this._byElement.get(n);if(o)return o;if(n.classList.contains("desktop-mode-window"))return null}n=n.parentElement}return null}hitTestPoint(t,n){const o=document.elementFromPoint(t,n);return{target:this.hitTest(o),element:o,accepted:!1}}}const z_="desktop-mode-drag-ghost",lp="desktop-mode-drag-ghost--accept",cp="desktop-mode-drag-ghost--reject",G_="desktop-mode-drag-hint",up="desktop-mode-drag-hint--accept",pp="desktop-mode-drag-hint--reject",fp="desktop-mode-drag-hint--neutral",j_=16,q_=18;function V_(e,t,n){const o=Q_(e),s=e.ghost?.offsetX??eE(e.source),i=e.ghost?.offsetY??tE(e.source);o.classList.add(z_),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=X_(e),a=r?K_():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+j_}px, ${c+q_}px, 0)`)},setMode(l,c){o.classList.remove(lp,cp),l==="accept"?o.classList.add(lp):l==="reject"&&o.classList.add(cp),a&&r&&(a.classList.remove(up,pp,fp),l==="accept"?(a.classList.add(up),a.textContent=c?.acceptLabel??r.accept):l==="reject"?(a.classList.add(pp),a.textContent=r.reject):(a.classList.add(fp),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(t,n),d.setMode("neutral"),d}function K_(){const e=document.createElement("div");return e.className=G_,e.setAttribute("aria-hidden","true"),e.setAttribute("role","presentation"),e.style.position="fixed",e.style.left="0",e.style.top="0",e.style.margin="0",e.style.pointerEvents="none",e.style.zIndex="2147483647",e.style.willChange="transform",e}function X_(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??Y_(e),reject:t?.reject??Z_(),neutral:t?.neutral??J_(e)}}function Y_(e){return e.type==="shortcut"?S("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?S("Drop here to move","desktop-mode"):S("Drop here","desktop-mode")}function Z_(e){return S("Can’t drop here","desktop-mode")}function J_(e){return e.type==="shortcut"?S("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?S("Drop in a folder","desktop-mode"):""}function Q_(e){if(e.ghost?.element)return e.ghost.element;const t=e.source.cloneNode(!0);t.removeAttribute("id");const n=e.source.getBoundingClientRect();return t.style.width=`${n.width}px`,t.style.height=`${n.height}px`,t}function eE(e){return e.offsetWidth/2}function tE(e){return e.offsetHeight/2}let mp=!1;function nE(e){mp||(mp=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const hp=4,le={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"},Ls="desktop-mode-file-tile--dragging",wp="desktop-mode-file-tile--drop-target",gp="data-desktop-mode-trash-drop-active",yp="data-files-drop-active",bp="data-desktop-mode-dragging",vp="data-desktop-mode-drag-type",Ir="data-desktop-mode-drag-mode";class oE{constructor(){this._registry=new B_,this._active=null,this._docListenersAttached=!1,this._lastLiftedEndAt=0,this._onPointerMove=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;const o=t.clientX-n._origin.clientX,s=t.clientY-n._origin.clientY;if(!n._lifted){if(Math.abs(o)<hp&&Math.abs(s)<hp)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),Qe(le.MOVE,{payload:n.payload,clientX:t.clientX,clientY:t.clientY}))},this._onPointerUp=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;if(!n._lifted){n._finished=!0,this._active=null;try{n._callbacks.onClickOnly?.()}catch(s){console.error("[desktop-mode] drag onClickOnly threw:",s)}return}const o=this._hitTestNow(n,t.clientX,t.clientY);if(o&&o.accepted&&o.target){this._commit(n,o.target,t.clientX,t.clientY);return}this._cancel(n,o&&o.target?"rejected":"no-target")},this._onPointerCancel=t=>{const n=this._active;!n||n._pointerId!==t.pointerId||this._cancel(n,"pointercancel")}}start(t){if(this._active||t.origin.button!==0)return null;const n={payload:t.payload,isFinished:()=>n._finished,cancel:o=>this._cancel(n,o??"caller"),_origin:t.origin,_pointerId:t.origin.pointerId,_lifted:!1,_finished:!1,_callbacks:{onClickOnly:t.onClickOnly,onCancel:t.onCancel,onCommit:t.onCommit},_ghost:null,_currentTarget:null,_currentAccepted:!1};return this._active=n,this._ensureDocListeners(),nE(o=>{this._active&&this._cancel(this._active,o)}),n}registerDropTarget(t){return this._registry.register(t)}isDragging(){return this._active!==null&&this._active._lifted}recentlyEndedDrag(t=500){return this._lastLiftedEndAt===0?!1:Date.now()-this._lastLiftedEndAt<t}getActive(){return this._active}debug(){return{findOrphans:()=>kp(),listTargets:()=>this._registry.list()}}_ensureDocListeners(){this._docListenersAttached||(this._docListenersAttached=!0,document.addEventListener("pointermove",this._onPointerMove,!0),document.addEventListener("pointerup",this._onPointerUp,!0),document.addEventListener("pointercancel",this._onPointerCancel,!0))}_lift(t,n){t._lifted=!0,t.payload.source.classList.add(Ls),t._ghost=V_(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(bp,""),document.body.setAttribute(vp,String(t.payload.type)),document.body.setAttribute(Ir,"neutral")),Qe(le.START,{payload:t.payload})}_hitTestNow(t,n,o){const s=()=>{const i=document.elementFromPoint(n,o),r=this._registry.hitTest(i);if(!r)return{target:null,accepted:!1};let a=!1;try{a=r.accept(t.payload)}catch(d){console.error("[desktop-mode] drop target accept() threw:",r.id,d)}return{target:r,accepted:a}};return t._ghost?t._ghost.withHidden(s):s()}_updateHover(t,n,o){const s=this._hitTestNow(t,n,o),i=t._currentTarget;if(s.target===i&&s.accepted===t._currentAccepted)return;i&&Cr(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(sE(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),Qe(le.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Ir,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),Cr(n,t),this._cleanupDom(t);const i=this._active;this._active=null;try{n.onDrop(t,{clientX:o,clientY:s})}catch(r){console.error("[desktop-mode] drop target onDrop threw:",n.id,r)}try{t._callbacks.onCommit?.(n)}catch(r){console.error("[desktop-mode] drag onCommit threw:",r)}Qe(le.COMMIT,{payload:t.payload,targetId:n.id}),Qe(le.END,{payload:t.payload,reason:"commit"}),this._active===i&&(this._active=null)}_cancel(t,n){if(!t._finished){t._finished=!0,t._lifted&&(this._lastLiftedEndAt=Date.now()),t._currentTarget&&Cr(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[desktop-mode] drag onCancel threw:",o)}Qe(le.CANCEL,{payload:t.payload,reason:n}),Qe(le.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(Ls)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(bp),document.body.removeAttribute(vp),document.body.removeAttribute(Ir)),iE()}}function Qe(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function sE(e,t){try{e.onEnter?.(t)}catch(n){console.error("[desktop-mode] drop target onEnter threw:",e.id,n)}Qe(le.ENTER,{payload:t.payload,targetId:e.id})}function Cr(e,t){try{e.onLeave?.(t)}catch(n){console.error("[desktop-mode] drop target onLeave threw:",e.id,n)}Qe(le.LEAVE,{payload:t.payload,targetId:e.id})}function kp(){if(typeof document>"u")return[];const e=[];for(const t of[`.${Ls}`,`.${wp}`,`[${gp}]`,`[${yp}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function iE(){for(const e of kp())e.classList.remove(Ls,wp),e.removeAttribute(gp),e.removeAttribute(yp)}const rE=".desktop-mode-window",_p="wp-window-";function Ep(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(rE);return o instanceof HTMLElement?o:null}function aE(e){if(!e.id.startsWith(_p))return null;const t=e.id.slice(_p.length);return t.length>0?t:null}const dE="desktop-mode-iframe-drop-",Ts="iframe.desktop-mode-window__iframe",Ar="data-desktop-mode-iframe-drop-active";let Lr=!1,Sp=null;const $e=new Map,xt=new Map;let et=null,It=null;function lE(){document.querySelectorAll(Ts).forEach(t=>{$e.has(t)||($e.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function cE(){$e.forEach((e,t)=>{t.style.pointerEvents=e}),$e.clear()}function xp(e,t){const n=Ep(e,t);if(!n)return null;const o=n.querySelector(Ts);return o instanceof HTMLIFrameElement?o:null}const Ip=e=>{if(!et)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=xp(e.clientX,e.clientY);t!==It&&(It&&Ct(It,{type:"desktop-mode-drag-leave"}),It=t,t&&Ct(t,{type:"desktop-mode-drag-over",payload:et}))},Cp=e=>{if(!et)return;e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const t=xp(e.clientX,e.clientY),n=et;if(Tr(),!t)return;const o=t.getBoundingClientRect();Ct(t,{type:"desktop-mode-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},Ap=()=>{Tr()};function uE(e){if(et){et=e;return}et=e,lE(),document.addEventListener("dragover",Ip,!0),document.addEventListener("drop",Cp,!0),document.addEventListener("dragend",Ap,!0)}function Tr(){et&&(et=null,It&&(Ct(It,{type:"desktop-mode-drag-leave"}),It=null),document.removeEventListener("dragover",Ip,!0),document.removeEventListener("drop",Cp,!0),document.removeEventListener("dragend",Ap,!0),cE())}function Ns(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function Ct(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function pE(e,t,n,o){return e.registerDropTarget({id:`${dE}${o}`,element:n,accept:s=>!!Ns(s),onEnter:s=>{const i=Ns(s.payload);i&&(n.setAttribute(Ar,""),Ct(t,{type:"desktop-mode-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(Ar),Ct(t,{type:"desktop-mode-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(Ar);const r=Ns(s.payload);if(!r)return;const a=t.getBoundingClientRect();Ct(t,{type:"desktop-mode-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function Lp(e){let t=e.parentElement;for(;t;){if(t.id.startsWith("wp-window-"))return t.id.slice(10);t=t.parentElement}return`unknown-${Math.random().toString(36).slice(2,10)}`}function fE(e){const t=Sp;if(!t)return;const n=document.querySelectorAll(Ts),o=!!Ns(e);console.info("[desktop-mode] drag-start: suppressing %d iframe(s); bridgeable=%s",n.length,o,e),n.forEach(s=>{if($e.has(s)||($e.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||xt.has(s))return;const i=s.parentElement;if(!i)return;const r=Lp(s),a=pE(t,s,i,r);xt.set(s,a)})}function mE(){$e.forEach((e,t)=>{t.style.pointerEvents=e}),$e.clear(),xt.forEach(e=>{try{e()}catch{}}),xt.clear()}function hE(e){Lr||(Lr=!0,Sp=e,document.addEventListener(le.START,t=>{const n=t.detail;fE(n?.payload)}),document.addEventListener(le.END,()=>{mE()}),document.addEventListener(Kt.START,t=>{const n=t.detail;n?.payload&&uE(n.payload)}),document.addEventListener(Kt.END,()=>{Tr()}),G(y.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from($e))t.isConnected||$e.delete(t);for(const[t,n]of Array.from(xt))if(!t.isConnected){try{n()}catch{}xt.delete(t)}}),window.__desktopModeIframeDropDebug=()=>({installed:Lr,iframesInDom:document.querySelectorAll(Ts).length,suppressedCount:$e.size,registeredCount:xt.size,suppressedIframeIds:Array.from($e.keys()).map(Lp)}))}const wE=250,gE=1e3,yE="desktop-mode-drag-hover";let Tp=!1,Nr=null,Dr=null,Jn=null,Qn=null,Or=null;function Np(){Jn!==null&&(clearTimeout(Jn),Jn=null)}function Dp(){Qn!==null&&(clearTimeout(Qn),Qn=null)}function eo(){Np(),Dp(),Dr=null}function Op(){Dp(),Qn=setTimeout(()=>{Qn=null,eo()},gE)}function bE(e,t){const n=Nr?.getById(e);if(!(!n||n.isFocused()||!j(y.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{Nr?.focus(n)}catch(s){console.error("[desktop-mode] focus-on-drag-hover focus() threw:",e,s)}}function Rp(e,t){e!==Dr&&(Np(),Dr=e,e!==null&&(Jn=setTimeout(()=>{Jn=null,bE(e,t)},wE)))}function Mp(e,t,n){const o=Ep(e,t);Rp(o?aE(o):null,n)}const vE=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||Mp(t.clientX,t.clientY,t.payload?.type??"")},kE=()=>{eo()};function _E(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;return typeof n.includes=="function"?n.includes("Files"):typeof n.contains=="function"&&n.contains("Files")}const EE=e=>{Op();const t=Or??(_E(e)?"os-file":"external");Mp(e.clientX,e.clientY,t)},Pp=()=>{eo()},SE=e=>{e.relatedTarget===null&&eo()};function xE(e){if(!e)return null;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e)return n.closest("[data-window-id]")?.getAttribute("data-window-id")||null;return null}const IE=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==yE)return;const n=xE(e.source);n&&(Op(),Rp(n,typeof t.payloadType=="string"?t.payloadType:"external"))},CE=e=>{const t=e.detail;t?.payload&&(Or=t.payload.kind??"")},AE=()=>{Or=null,eo()};function LE(e){Tp||(Tp=!0,Nr=e,document.addEventListener(le.MOVE,vE),document.addEventListener(le.END,kE),document.addEventListener(Kt.START,CE),document.addEventListener(Kt.END,AE),document.addEventListener("dragover",EE,!0),document.addEventListener("drop",Pp,!0),document.addEventListener("dragend",Pp,!0),document.addEventListener("dragleave",SE,!0),window.addEventListener("message",IE))}function $p(){const e=window.wp?.desktop;if(!e)return[];const t=e.windowManager,n=e.config;if(!t||!n)return[];const o=[],s=(r,a)=>({id:r.id,label:r.title,description:a,icon:r.icon,open:()=>t.open({id:r.id,baseId:r.id,url:r.url,title:r.title,icon:r.icon})});for(const r of n.dockItems??[])o.push(s(r,"Admin menu"));const i=j("desktop-mode.open-command.items",o);return Array.isArray(i)?i:o}const TE={slug:"open",label:"Open",description:"Open an admin page or registered window.",hint:"[window]",icon:"dashicons-external",suggest(e){const t=e.trim().toLowerCase(),n=$p();return(t===""?n:n.filter(s=>s.label.toLowerCase().includes(t)||s.id.toLowerCase().includes(t))).slice(0,12).map(s=>({value:s.label,label:s.label,description:s.description,icon:s.icon??"dashicons-external"}))},run(e,t){const n=e.trim();if(!n)return"Type the name of a window to open, for example `/open Posts`.";const o=$p(),s=n.toLowerCase(),i=o.find(r=>r.label.toLowerCase()===s||r.id.toLowerCase()===s)??o.find(r=>r.label.toLowerCase().includes(s)||r.id.toLowerCase().includes(s));if(!i)return`No window matching **${n}** — try \`/open\` alone to see available options.`;i.open(),t.close()}};function NE(){ks(TE)}const ke=[],DE=new Set;function Wp(e){if(!e||typeof e.id!="string"||e.id==="")return()=>{};if(typeof e.open!="function"||typeof e.close!="function"||typeof e.isOpen!="function")return()=>{};const t=ke.findIndex(n=>n.id===e.id);return t>=0?ke[t]=e:ke.push(e),Rr(),()=>{const n=ke.findIndex(o=>o.id===e.id);n>=0&&(ke.splice(n,1),Rr())}}function OE(e){const t=ke.findIndex(n=>n.id===e);t>=0&&(ke.splice(t,1),Rr())}function RE(){return ke.slice()}function Rr(){for(const e of Array.from(DE))try{e()}catch(t){typeof console<"u"&&console.error("[desktop-mode] palette-registry listener threw:",t)}}function Up(){if(ke.length===0)return;const e=ke.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{ke[0].open()}catch{}return}try{ke[e].close()}catch{}const t=e+1;if(t<ke.length)try{ke[t].open()}catch{}}function Mr(e){const t=ke.find(n=>n.id===e);if(t){for(const n of ke)if(n.id!==e)try{n.isOpen()&&n.close()}catch{}try{t.open()}catch{}}}let Fp=!1;function ME(){if(Fp)return;Fp=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),Up())},!0);const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;n&&n.type==="desktop-mode-palette-cycle"&&Up()})}const He=re("desktop-mode/presence",()=>({byUser:new Map,serverTimeMs:0})),PE=5*60*1e3;let Hp=Date.now(),Bp=!1;function Ds(){Hp=Date.now()}function $E(e){if(!e||!e.snapshot)return;const t=He.state.byUser,n=new Map(t),o=[];for(const[s,i]of Object.entries(e.snapshot)){const r=Number(s);if(!Number.isFinite(r)||r<=0)continue;const d={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},l=t.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})}He.state.byUser=n,typeof e.serverTimeMs=="number"&&(He.state.serverTimeMs=e.serverTimeMs),He.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})),ve.publish("desktop-mode/presence-changed",i)}ve.publish("desktop-mode/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function WE(){Bp||(Bp=!0,document.addEventListener("pointerdown",Ds,{capture:!0,passive:!0}),document.addEventListener("keydown",Ds,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||Ds()}),ye.contribute("desktop_mode_presence_active",()=>!0),ye.contribute("desktop_mode_user_active",()=>Date.now()-Hp<PE),ye.subscribe("desktop_mode_presence",e=>{$E(e)}))}function UE(e){const t=He.state.byUser.get(e);return t?t.status:"offline"}function FE(){return new Map(He.state.byUser)}function HE(e){return He.state.byUser.get(e)??null}function BE(e){return He.subscribe(t=>e(t))}function zE(){Ds()}function GE(e){if(!Array.isArray(e)||e.length===0)return;const t=He.state.byUser,n=new Map(t),o=[];for(const s of e){const i=Number(s.userId);if(!Number.isFinite(i)||i<=0)continue;const r=t.get(i),a={status:s.status,lastSeenMs:typeof s.lastSeenMs=="number"?s.lastSeenMs:r?.lastSeenMs??0,lastActiveMs:typeof s.lastActiveMs=="number"?s.lastActiveMs:r?.lastActiveMs??0};n.set(i,a),(!r||r.status!==a.status)&&o.push({userId:i,oldStatus:r?r.status:null,newStatus:a.status,entry:a})}if(!(o.length===0&&n.size===t.size)){He.state.byUser=n,He.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})),ve.publish("desktop-mode/presence-changed",i)}ve.publish("desktop-mode/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const jE=Object.freeze({getStatus:UE,getAll:FE,getEntry:HE,subscribe:BE,markActive:zE,applyBatch:GE});let to=null;function qE(){ye.contribute("desktop_mode_content_changes_seen_ts",()=>to===null?0:to),ye.subscribe("desktop_mode_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=to===null,n=to??0;let o=Math.max(n,e.ts);if(!t&&Array.isArray(e.entries))for(const s of e.entries)!s||typeof s.ts!="number"||s.ts<=n||typeof s.type!="string"||s.type===""||(xr(`desktop-mode.${s.type}.changed`,{source:"heartbeat",action:typeof s.action=="string"&&s.action!==""?s.action:"updated",ids:Array.isArray(s.ids)?s.ids.map(Number).filter(i=>i>0):[]}),s.ts>o&&(o=s.ts));to=o})}const VE="desktop_mode_nonces",Pr=new Map;let zp=!1;function $r(e,t){if(typeof e!="string"||e==="")return()=>{};let n=Pr.get(e);return n||(n=new Set,Pr.set(e,n)),n.add(t),()=>{n.delete(t)}}function KE(){zp||(zp=!0,ye.subscribe(VE,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=Pr.get(t);if(o)for(const s of o)try{s(n)}catch(i){console.error(`[desktop-mode/nonce-refresh] updater for "${t}" threw:`,i)}}}),XE())}function XE(){$r("wp_rest",YE),$r("desktop-mode-plugins",e=>{Gp("desktop-mode-plugins","ajaxNonce",e)}),$r("updates",e=>{Gp("desktop-mode-plugins","updatesNonce",e)})}function YE(e){const t=ZE();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=jp();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Gp(e,t,n){const s=jp()?.[e];s&&typeof s=="object"&&(s[t]=n)}function ZE(){if(!(typeof window>"u"))return window.desktopModeConfig}function jp(){if(!(typeof window>"u"))return window.desktopModeWindowConfig}const JE="desktop_mode_auth",QE=5e3,qp=1e3,e0=1e4;let Vp=!1,Os=!1,Wr=!1,Rs=0,Kp=0,no=0,Xt=null,Xp=0,Yp=null,Zp=null,Jp=()=>{try{window.location.reload()}catch{}};function Ur(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function Fr(e=qp){const t=Date.now();if(t<no){Xt===null&&(Xt=window.setTimeout(()=>{Xt=null,no=Date.now()+qp,Ur()},no-t));return}no=t+e,Ur()}function t0(){Os=!0,!Wr&&(Wr=!0,T(y.AUTH_LOST),document.dispatchEvent(new CustomEvent("desktop-mode-auth-lost")))}function n0(){for(const e of o0())try{e.contentWindow?.location.reload()}catch{}}function o0(){let e;try{e=document.querySelectorAll("iframe")}catch{return[]}return Array.from(e).filter(t=>t.id!=="wp-auth-check-frame"&&!t.closest("#wp-auth-check-wrap"))}function Hr(){const e=Date.now();e-Xp<e0||(Xp=e,Os=!1,Wr=!1,Xt!==null&&(window.clearTimeout(Xt),Xt=null),no=0,Fr(),n0(),T(y.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("desktop-mode-auth-restored")))}function s0(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(Rs<=0){Rs=t;return}t!==Rs&&Jp()}}function i0(e,t){if(e!==401&&e!==403)return;let n;try{n=new URL(String(t||""),window.location.href)}catch{return}if(n.origin!==window.location.origin||n.pathname.indexOf("/wp-admin/admin-ajax.php")!==-1&&/(?:^|&|\?)action=heartbeat(?:&|$)/.test(n.search)||n.pathname.indexOf("/wp-login.php")!==-1)return;const o=Date.now();o<Kp||(Kp=o+QE,Ur())}function r0(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");Zp=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&Fr(),t=n}),Zp.observe(e,{attributes:!0,attributeFilter:["class"]})}function a0(e={}){Vp||(Vp=!0,Rs=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(Jp=e.reloadShell),ye.subscribe("wp-auth-check",t=>{if(t===!1){t0();return}t===!0&&Os&&Hr()}),ye.subscribe("nonces_expired",()=>{if(Os){Hr();return}Fr()}),ye.subscribe(JE,s0),Yp=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="desktop-mode-reauth-detected"&&Hr()},window.addEventListener("message",Yp),r0())}const Yt=12;function Br(e,t){const n=oe(e,t.adminUrl);return(t.dockItems||[]).find(o=>oe(o.url,t.adminUrl)===n||(o.submenu||[]).some(s=>oe(s.url,t.adminUrl)===n))}function Qp(e,t){const n=Math.max(200,t.width-Yt*2),o=Math.max(200,t.height-Yt*2),s=Math.min(e.width,n),i=Math.min(e.height,o),r=Math.max(0,t.width-s-Yt),a=Math.max(0,t.height-i-Yt),d=Math.max(Yt,Math.min(e.x,r)),l=Math.max(Yt,Math.min(e.y,a));return{x:d,y:l,width:s,height:i}}const ef=window.location.origin;function d0(e,t){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let d;try{d=new URL(a,window.location.href)}catch(m){typeof console<"u"&&console.warn("[desktop-mode] Couldn’t parse href; letting the browser handle the click:",a,m);return}if(d.origin!==ef)return;let l;try{l=new URL(t.adminUrl).pathname}catch(m){typeof console<"u"&&console.error("[desktop-mode] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,m),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(),dt(d.href)))return;const c=oe(d.href,t.adminUrl),u=Br(d.href,t),p=(i.textContent||"").trim()||u?.title||"",f=!!i.closest("#wp-admin-bar-new-content"),h={id:c,baseId:c,multi:!!u?.multi||f,url:d.href,parentUrl:u?.url??d.href,title:u?.title||p,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu};if(f){e.openNew(h);return}e.open(h)},!0)}const l0="desktop-mode-registry-changed";function c0(e,t){const n=new Set;if(Array.isArray(e))for(const r of e)r&&typeof r.id=="string"&&n.add(r.id);const o=new Set;for(const r of t)r&&typeof r.id=="string"&&o.add(r.id);const s=[];for(const r of o)n.has(r)||s.push(r);const i=[];for(const r of n)o.has(r)||i.push(r);return{added:s,removed:i}}function zr(e,t,n){const{added:o,removed:s}=c0(t,n);if(o.length===0&&s.length===0||typeof document>"u")return;const i={registry:e,added:o,removed:s};document.dispatchEvent(new CustomEvent(l0,{detail:i}))}function u0(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:d,syncServerUnfocusEffects:l,syncServerWindowLinkRenderers:c,syncServerDockRailRenderers:u,syncServerGames:p,renderIcons:f,syncShortcuts:h}=e;return function(w){const g=w.dockItems,k=w.nativeWindows,D=w.serverWidgets,b=w.serverWallpapers,E=w.serverCommandScripts,I=w.serverCommands,O=w.serverSettingsTabScripts,v=w.serverSettingsTabs,N=w.serverDockRailRendererScripts,C=w.serverTitleBarButtonScripts,L=w.serverUnfocusEffectScripts,A=w.serverWindowLinkRendererScripts,R=w.serverWindowNotices,F=w.serverGames,K=w.desktopIcons;if(!Array.isArray(g)||g.length===0)return;const Y=n.dockItems;if(t(g),n.dockItems=g,zr("dock-items",Y,g),h?.(),Array.isArray(k)){const x=n.nativeWindows;o(k),n.nativeWindows=k,zr("native-windows",x,k)}if(Array.isArray(D)&&(s(D),n.serverWidgets=D),Array.isArray(b)&&(i(b),n.serverWallpapers=b),Array.isArray(F)&&(p(F),n.serverGames=F),Array.isArray(E)&&(r(E,Array.isArray(I)?I:void 0),n.serverCommandScripts=E,Array.isArray(I)&&(n.serverCommands=I)),Array.isArray(O)&&(a(O,Array.isArray(v)?v:void 0),n.serverSettingsTabScripts=O,Array.isArray(v)&&(n.serverSettingsTabs=v)),Array.isArray(C)&&(d(C),n.serverTitleBarButtonScripts=C),Array.isArray(L)&&(l(L),n.serverUnfocusEffectScripts=L),Array.isArray(A)&&(c(A),n.serverWindowLinkRendererScripts=A),Array.isArray(N)&&(u(N),n.serverDockRailRendererScripts=N),Array.isArray(R)&&(wu(R),n.serverWindowNotices=R),Array.isArray(K)){const x=n.desktopIcons;f(K),n.desktopIcons=K,zr("desktop-icons",x,K)}}}const p0=8e3;function f0(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:d,syncServerTitleBarButtons:l,syncServerUnfocusEffects:c,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:p,syncServerGames:f,renderIcons:h,syncShortcuts:m}=e,w=u0({applyDockItems:b=>t?.applyDockItems(b),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:d,syncServerTitleBarButtons:l,syncServerUnfocusEffects:c,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:p,syncServerGames:f,renderIcons:h,syncShortcuts:m});let g=typeof o.menuSig=="string"?o.menuSig:"",k=!1;const D=()=>{if(!o.adminUrl)return Promise.resolve();const b=(()=>{try{const E=new URL("admin.php",o.adminUrl);return E.searchParams.set("desktop_mode_chromeless","1"),E.searchParams.set("desktop_mode_menu_refresh","1"),E.toString()}catch{return null}})();return b?new Promise(E=>{const I=document.createElement("iframe");I.setAttribute("aria-hidden","true"),I.tabIndex=-1,I.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",I.src=b;let O=!1;const v=()=>{O||(O=!0,window.clearTimeout(C),window.removeEventListener("message",N),I.parentNode&&I.parentNode.removeChild(I),E())},N=L=>{if(L.source!==I.contentWindow)return;const A=L.data;!A||A.type!=="desktop-mode-plugins-changed"||v()},C=window.setTimeout(()=>{T(y.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),v()},p0);window.addEventListener("message",N),document.body.appendChild(I)}):Promise.resolve()};return window.addEventListener("message",b=>{if(b.origin!==ef)return;const E=b.data;if(E){if(E.type==="desktop-mode-plugins-changed"){E.payload&&(w(E.payload),typeof E.payload.menuSig=="string"&&(g=E.payload.menuSig));return}if(E.type==="desktop-mode-menu-signature"){const I=E.sig;typeof I=="string"&&I!==""&&I!==g&&!k&&(k=!0,D().finally(()=>{k=!1}))}}}),D}function m0(e){if(!e)return!1;if(Array.isArray(e.windows)&&e.windows.length>0)return!0;if(typeof e.updated!="number"||e.updated<=0||!Array.isArray(e.desktops)||e.desktops.length===0)return!1;if(e.desktops.length>1)return!0;const t=e.desktops[0];return t?.id&&t.id!=="desktop-1"?!0:!!e.activeDesktop&&e.activeDesktop!=="desktop-1"}async function h0(e,t,n){const o=n.getBoundingClientRect();Array.isArray(t.session.desktops)&&t.session.desktops.length>0&&e.seedDesktops(t.session.desktops,t.session.activeDesktop||t.session.desktops[0].id);for(const s of t.session.windows){const i=Qp(s,o),r=Br(s.url,t),a=await e.open({id:s.id,baseId:s.baseId||s.id,desktopId:s.desktopId,multi:!!r?.multi,url:s.url,parentUrl:r?.url??s.url,title:s.title,icon:s.icon||"dashicons-admin-generic",x:i.x,y:i.y,width:i.width,height:i.height,initialState:s.state,submenu:r?.submenu});if(Array.isArray(s.externalTabs))for(const d of s.externalTabs)d&&typeof d.url=="string"&&d.url!==""&&a.addExternalTab(d.url,typeof d.label=="string"&&d.label!==""?d.label:d.url)}if(t.session.focused){const s=e.getById(t.session.focused);s&&e.focus(s)}}async function w0(e,t){if(dt(t.currentPage))return;const n=oe(t.currentPage,t.adminUrl),o=Br(t.currentPage,t);await e.open({id:n,baseId:n,multi:!!o?.multi,url:t.currentPage,parentUrl:o?.url??t.currentPage,title:t.currentTitle,icon:t.currentIcon,submenu:o?.submenu})}function g0(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function Gr(e,t,n,o){const s=Rl(t,n),i=window.fetch(t,s);if(i.then(a=>{if(a.status===401||a.status===403){let d;typeof t=="string"?d=t:t instanceof URL?d=t.href:d=t.url,i0(a.status,d)}},()=>{}),o?.silent)return i;let r=o?.window;return!r&&o?.windowId&&(r=e.getById(o.windowId)??null),r||(r=e.getFocused()),r&&typeof r.trackActivity=="function"&&r.trackActivity(i).catch(()=>{}),i}const y0=500;function b0(e,t){let n=null,o=!1;const s=async()=>{if(o)return;const a=e.snapshot();o=!0;try{await Gr(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:a}),keepalive:!0},{silent:!0})}catch(d){T(y.SHELL_ERROR,{scope:"session-save",error:d})}finally{o=!1}},i=()=>{n!==null&&(clearTimeout(n),n=null);const a=e.snapshot(),d=new Blob([JSON.stringify({session:a})],{type:"application/json"}),l=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);navigator.sendBeacon&&navigator.sendBeacon(l,d)||s()},r=()=>{n!==null&&clearTimeout(n),n=window.setTimeout(()=>{n=null,s()},y0)};return window.addEventListener("pagehide",i),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&i()}),r}const v0=120;function k0(e){document.addEventListener("desktop-mode-window-opened",e),document.addEventListener("desktop-mode-window-closed",e),document.addEventListener("desktop-mode-window-focused",e),document.addEventListener("desktop-mode-window-changed",e),G(y.DESKTOP_CREATED,"desktop-mode/session-save",e),G(y.DESKTOP_CLOSED,"desktop-mode/session-save",e),G(y.DESKTOP_SWITCHED,"desktop-mode/session-save",e)}function _0(){const e=document.getElementById("desktop-mode-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;T(y.SHELL_RESIZED,{width:o?Math.round(o.width):window.innerWidth,height:o?Math.round(o.height):window.innerHeight})};window.addEventListener("resize",()=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(n,v0)}),document.addEventListener("visibilitychange",()=>{T(y.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function E0(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return j(y.DOCK_TILE_CLASS,e,o)}function S0(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return j(y.DOCK_TILE_ELEMENT,e,o)}function x0(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return j(y.DOCK_TILE_TOOLTIP,e,o)}function I0(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};T(y.DOCK_TILE_RENDERED,{...o,el:e})}const C0=[".desktop-mode-dock","#desktop-mode-dock","#desktop-mode-side-dock",".desktop-mode-dock__tooltip",".desktop-mode-dock-submenu"].join(","),jr=new Set;function A0(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(C0))return!0;for(const n of jr)if(t.closest(n))return!0;return!1}function L0(e){return typeof e!="string"||e.trim()===""?()=>{}:(jr.add(e),()=>{jr.delete(e)})}const tt=new Map,T0=window.location.origin;function tf(e){let t=tt.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},tt.set(e,t)),N0(e,t),t}function N0(e,t){const n=qr(e);if(!n||t.loadHandlerTarget===n&&t.loadHandler||(t.loadHandlerTarget&&t.loadHandler&&typeof t.loadHandlerTarget.removeEventListener=="function"&&t.loadHandlerTarget.removeEventListener("load",t.loadHandler),typeof n.addEventListener!="function"))return;const o=()=>{queueMicrotask(()=>Zt(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function D0(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function qr(e){const t=window.wp?.desktop?.windowManager;if(t&&typeof t.getById=="function"){const o=t.getById(e);if(o?.iframe)return o.iframe;if(o?.element){const s=o.element.querySelector("iframe");if(s)return s}}return document.getElementById(`wp-window-${e}`)?.querySelector("iframe")??null}function O0(e){const t={};for(const[n,o]of e.headers){const s=[];for(const i of o){let r;try{r=typeof i.value=="function"?i.value():i.value}catch{continue}typeof r=="string"&&r!==""&&s.push(r)}s.length>0&&(t[n]=s.join(", "))}return t}function Zt(e){const t=qr(e);if(!t||!t.contentWindow)return;const n=tt.get(e),o=n?O0(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"desktop-mode-instrument-set",headers:o,observe:s},T0)}catch{}}G(y.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&tt.has(t.windowId)&&Zt(t.windowId)}),G(y.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=tt.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const ut=new Map,R0=1e3;function nf(e,t,n){const o=ut.get(e);if(!o||o.inflight)return;o.inflight=!0;const s=new URL(t+"desktop-mode/v1/debug",window.location.origin);s.searchParams.set("sessionId",e),s.searchParams.set("since",String(o.cursor));for(const r of o.channels.keys())s.searchParams.append("channels[]",r);const i=s.toString();fetch(i,{credentials:"same-origin",headers:{"X-WP-Nonce":n}}).then(r=>r.ok?r.json():{events:[],cursor:o.cursor}).then(r=>{if(o.inflight=!1,!!ut.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const d=o.channels.get(a.channel);if(d)for(const l of d)try{l(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=ut.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>nf(e,t,n),R0))})}function M0(){const e=window.desktopModeConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function P0(e,t){const n=ut.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let $0=0;const of={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=tf(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),Zt(e),()=>{const r=tt.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const d=a.indexOf(s);d>=0&&a.splice(d,1),a.length===0&&r.headers.delete(t),Zt(e),sf(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=tf(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,Zt(e)),()=>{const i=tt.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),Zt(e)),sf(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=qr(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=of.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",d=new URL(a,window.location.origin);d.searchParams.set(i,t),o.src=d.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const e=window.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(e,t,n){P0(e,{id:++$0,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=ut.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},ut.set(e,o));let i=o.channels.get(t);if(i||(i=new Set,o.channels.set(t,i)),i.add(n),s){const r=M0();r&&nf(e,r.restUrl,r.restNonce)}return()=>{const r=ut.get(e);if(!r)return;const a=r.channels.get(t);a&&(a.delete(n),a.size===0&&r.channels.delete(t)),r.channels.size===0&&(r.timer&&clearTimeout(r.timer),ut.delete(e))}}}};function sf(e){const t=tt.get(e);t&&t.headers.size===0&&t.observers.size===0&&(D0(t),tt.delete(e))}async function Vr(e){return await ci(ui()),new Promise(t=>{const n=document.createElement("wpd-confirm-dialog");n.setAttribute("open",""),e.title&&n.setAttribute("title",e.title),n.setAttribute("message",e.message),e.confirmLabel&&n.setAttribute("confirm-label",e.confirmLabel),e.cancelLabel&&n.setAttribute("cancel-label",e.cancelLabel),e.danger&&n.setAttribute("danger",""),e.hideCancel&&n.setAttribute("hide-cancel",""),e.dismissable&&n.setAttribute("dismissable","");const o=i=>{n.remove(),t(i)};n.addEventListener("wpd-confirm",()=>o(!0)),n.addEventListener("wpd-cancel",()=>o(!1)),document.body.appendChild(n),(n.shadowRoot?.querySelector(".dialog")??n).focus?.()})}function W0(e){const t=[];for(const d of e.getVisibleRects()){if(d.state==="minimized"||d.element.offsetParent===null)continue;const l=d.element.getBoundingClientRect();t.push({id:`window:${d.windowId}`,kind:"window",rect:rf(l),face:"top",element:d.element})}const n=document.getElementById("desktop-mode-shell");if(n){const d=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:d.left,y:d.bottom-1,width:d.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".desktop-mode-dock");let s=0;for(const d of Array.from(o)){const 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"?t.push({id:u,kind:"dock",rect:{x:l.left,y:l.top,width:l.width,height:1},face:"top",element:d}):c==="right"?t.push({id:u,kind:"dock",rect:{x:l.left,y:l.top,width:1,height:l.height},face:"left",element:d}):t.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++);t.push({id:`widget:${c}`,kind:"widget",rect:rf(l),face:"top",element:d})});const a=j(y.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function rf(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const U0="__desktop_modeKeyedListKey",F0="__desktop_modeKeyedListData";function H0(e){const t=e.__desktop_modeKeyedList;if(t)return t;const n={byKey:new Map};return e.__desktop_modeKeyedList=n,n}function B0(e,t,n){const o=H0(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const d of t){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[U0]=l,u[F0]=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=e.children[d];c!==l&&e.insertBefore(l,c??null)}o.byKey=i}function z0(e){const t=e.__desktop_modeKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__desktop_modeKeyedList}}function G0(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:d=v=>{typeof console<"u"&&console.error("[desktop-mode] createInfiniteList:",v)}}=e;let l=e.sentinel??null;l||(l=document.createElement("div"),l.dataset.wpdInfiniteListSentinel="",l.style.height="1px",t.appendChild(l));const c=new Set;let u=r,p=!0,f=!1,h=null,m=0,w=!1,g=null;const k=v=>{if(f!==v){f=v;try{a(v)}catch(N){d(N)}}},D=()=>{g&&(g.disconnect(),g=null)},b=()=>{g||!l||w||(g=new IntersectionObserver(v=>{for(const N of v)N.isIntersecting&&E()},{rootMargin:i}),g.observe(l))},E=async()=>{if(w||f||!p)return;k(!0),h=new AbortController;const v=h;try{const N=await n(u,v.signal);if(w||v!==h)return;let C=0;const L=document.createDocumentFragment();for(const A of N.items??[]){const R=String(o(A));if(c.has(R))continue;c.add(R);const F=s(A,m+C);L.appendChild(F),C++}C>0&&(l&&l.parentNode===t?t.insertBefore(L,l):t.appendChild(L),m+=C),u=N.nextCursor??null,u||(p=!1,D())}catch(N){if(N?.name==="AbortError")return;d(N)}finally{v===h&&(k(!1),h=null)}},I=()=>{if(w)return;h?.abort(),h=null,c.clear(),u=r,p=!0,m=0;const v=l&&l.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);v&&l&&t.appendChild(l),k(!1),b(),E()},O=()=>{w||(w=!0,D(),h?.abort(),h=null,!e.sentinel&&l&&l.parentNode===t&&t.removeChild(l),l=null,k(!1))};return b(),E(),{reset:I,loadMore:E,hasMore:()=>p,isLoading:()=>f,destroy:O}}const j0=520,q0=720,V0=500;function K0(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[desktop-mode] startOAuth requires a non-empty service slug."));const n=Y0(),o=Z0();return Pe(Ze(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:e})},{source:"desktop-mode/oauth-start"}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`[desktop-mode] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>X0(s,e,t))}function X0(e,t,n){return new Promise((o,s)=>{const i=n.width??j0,r=n.height??q0,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(e.authorize_url,`desktop-mode-oauth-${t}`,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 h=()=>{f||(f=!0,window.removeEventListener("message",m),p!==null&&(window.clearInterval(p),p=null))},m=w=>{if(w.origin!==u)return;const g=w.data;if(!g||g.type!=="desktop-mode-oauth-callback")return;const k=g.payload;if(h(),k&&k.ok)o(k);else{const D=k?.reason??"unknown",b=k?.message??"OAuth flow failed",E=new Error(`[desktop-mode] startOAuth(${t}) failed: ${D} — ${b}`);E.cause=k,s(E)}};window.addEventListener("message",m),p=window.setInterval(()=>{c.closed&&(h(),s(new Error(`[desktop-mode] startOAuth(${t}) cancelled — popup closed before completing.`)))},V0)})}function af(){return window.desktopModeConfig??{}}function Y0(){const e=af().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function Z0(){const e=af().restNonce;return typeof e=="string"&&e!==""?e:null}const J0={register:Bi,unregister:ac,list:lc,get:gs,subscribe:qy,launch:yc,getPlaytime:()=>db().then(e=>e.playtime)},Q0=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","icons","files","confirm","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","openNewWindow","cloneTemplate","onWindow","createInfiniteList","startOAuth","repaintLoadingOverlays","loadVendorScript","getWallpaperSurfaces","wallpaper","games","registerModule","loadModules","whenReady","ready","isReady","setDefaultWindow","refreshMenu","config","ai","dragBridge","dragManager","registerCommand","unregisterCommand","listCommands","registerDestructiveAdminAction","unregisterDestructiveAdminAction","listDestructiveAdminActions","registerSettingsTab","unregisterSettingsTab","listSettingsTabs","registerDockRailRenderer","unregisterDockRailRenderer","listDockRailRenderers","openOsSettings","getOsSettings","subscribeOsSettings","updateOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","renderIcon","applyTileClasses","applyTileElement","applyTileTooltip","dispatchTileRendered","isDockElement","registerDockSelector","registerTitleBarButton","unregisterTitleBarButton","listTitleBarButtons","registerUnfocusEffect","unregisterUnfocusEffect","listUnfocusEffects","relations","registerWindowLinkRenderer","unregisterWindowLinkRenderer","listWindowLinkRenderers","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","getConnection","broadcast","subscribe","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","debug","fetch"]);function eS(e){const{manager:t,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:h,openOsSettings:m,aiAssistant:w,dragBridge:g,dragManager:k,connect:D,getConnection:b,wallpaperSuspend:E,config:I}=e,O={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,icons:i,files:r,confirm:Vr,saveSession:a,hooks:Fh(),HOOKS:y,isActive:()=>!!document.getElementById("desktop-mode-shell"),registerWallpaper:v=>{In(v),s.apply()},registerWidget:v=>{yr(v)},widgetLayer:d,widgets:{redock:v=>{d?.redock(v)}},loadVendorScript:Ie,getWallpaperSurfaces:()=>W0(t),wallpaper:E,games:J0,registerWindow:l,openWindow:c,openNewWindow:u,fetch:(v,N,C)=>Gr(t,v,N,C),repaintLoadingOverlays:ul,cloneTemplate:_r,onWindow:Ak,createInfiniteList:G0,startOAuth:K0,registerSystemTile:v=>{p(v),T(y.DOCK_ITEM_APPENDED,{id:v.id})},registerModule:nc,loadModules:oc,whenReady:yd,ready:yd,isReady:Bh,setDefaultWindow:f,refreshMenu:h,config:I,ai:w,dragBridge:g,dragManager:k,registerCommand:ks,unregisterCommand:Ec,listCommands:Sc,registerDestructiveAdminAction:Qw,unregisterDestructiveAdminAction:fl,listDestructiveAdminActions:eg,registerSettingsTab:Ic,unregisterSettingsTab:Cc,listSettingsTabs:Ac,registerDockRailRenderer:Pl,unregisterDockRailRenderer:Ug,listDockRailRenderers:Hg,openOsSettings:m,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:v=>s.subscribeOsSettings(v),updateOsSettings:(v,N={})=>{if(typeof v.wallpaper=="string"&&(s.state.wallpaper=v.wallpaper),typeof v.accent=="string"&&(s.state.accent=v.accent),typeof v.dockSize=="string"&&(s.state.dockSize=v.dockSize),typeof v.desktopLayout=="string"&&(s.state.desktopLayout=v.desktopLayout),typeof v.dockRailRenderer=="string"&&(s.state.dockRailRenderer=v.dockRailRenderer),typeof v.windowLinkRenderer=="string"&&(s.state.windowLinkRenderer=v.windowLinkRenderer),(v.windowLinkVisibility==="focus"||v.windowLinkVisibility==="always"||v.windowLinkVisibility==="off")&&(s.state.windowLinkVisibility=v.windowLinkVisibility),typeof v.windowLinksEnabled=="boolean"&&(s.state.windowLinksEnabled=v.windowLinksEnabled),typeof v.windowLinkRaiseOnFocus=="boolean"&&(s.state.windowLinkRaiseOnFocus=v.windowLinkRaiseOnFocus),typeof v.windowLinkHighlight=="boolean"&&(s.state.windowLinkHighlight=v.windowLinkHighlight),v.ai&&typeof v.ai=="object"&&(s.state.ai={...s.state.ai,...v.ai}),typeof v.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=v.nativePostsEnabled),typeof v.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=v.nativePagesEnabled),typeof v.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=v.nativeUsersEnabled),typeof v.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=v.nativePluginsEnabled),typeof v.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=v.nativeCommentsEnabled),typeof v.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=v.foldersSharingEnabled),typeof v.developerModeEnabled=="boolean"&&(s.state.developerModeEnabled=v.developerModeEnabled),Array.isArray(v.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=v.nativePostsHiddenColumns.filter(C=>typeof C=="string"&&C!=="").slice(0,32)),v.itemVisibility&&typeof v.itemVisibility=="object"){const C=["both","dock","desktop","hidden"],L={};for(const[A,R]of Object.entries(v.itemVisibility))typeof A!="string"||A===""||typeof R!="string"||!C.includes(R)||(L[A]=R);s.state.itemVisibility=L}if(Array.isArray(v.dockOrder)&&(s.state.dockOrder=v.dockOrder.filter(C=>typeof C=="string"&&C!=="").slice(0,256)),v.dockPromotedPositions&&typeof v.dockPromotedPositions=="object"){const L={};for(const[A,R]of Object.entries(v.dockPromotedPositions)){if(typeof A!="string"||A===""||!R||typeof R!="object")continue;const F=R;if(!(typeof F.x!="number"||typeof F.y!="number"||!Number.isFinite(F.x)||!Number.isFinite(F.y)||Math.abs(F.x)>1e5||Math.abs(F.y)>1e5)&&(L[A]={x:F.x,y:F.y},Object.keys(L).length>=256))break}s.state.dockPromotedPositions=L}s.save(N),(v.itemVisibility||v.dockOrder)&&o?.refresh()},deriveWindowId:(v,N)=>oe(v,N??I.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:v=>o?.getSystemTile(v)??null,getMenuItems:()=>o?.getMenuItems()??[],renderIcon:yi,applyTileClasses:E0,applyTileElement:S0,applyTileTooltip:x0,dispatchTileRendered:I0,isDockElement:A0,registerDockSelector:L0,registerTitleBarButton:Xi,unregisterTitleBarButton:Db,listTitleBarButtons:Rb,registerUnfocusEffect:Es,unregisterUnfocusEffect:Jb,listUnfocusEffects:or,relations:cg,registerWindowLinkRenderer:Oc,unregisterWindowLinkRenderer:Pb,listWindowLinkRenderers:Rc,registerWindowTheme:Jc,unregisterWindowTheme:Qc,listWindowThemes:eu,applyWindowTheme:(v,N)=>{const C=t.getById(v);C&&C.setAppearanceTheme(N)},registerWindowControl:Fn,unregisterWindowControl:ou,listWindowControls:su,applyWindowControls:(v,N)=>{const C=t.getById(v);C&&C.setAppearanceControls(N)},registerWindowSlot:du,unregisterWindowSlot:lr,listWindowSlots:lu,applyWindowSlot:(v,N,C)=>{const L=t.getById(v);L&&L.setAppearanceSlot(N,C)},registerWindowNotice:mu,unregisterWindowNotice:mr,listWindowNotices:hu,dismissWindowNotice:kv,undismissWindowNotice:_v,registerWindowChrome:xv,unregisterWindowChrome:bu,listWindowChromes:vu,applyWindowChrome:(v,N)=>{const C=t.getById(v);C&&C.setAppearanceChrome(N)},connect:D,getConnection:b,broadcast:xr,subscribe:Fe,registerPalette:Wp,unregisterPalette:OE,listPalettes:RE,openPalette:Mr,devtools:of,createSharedStore:re,presence:jE,activity:ve,heartbeat:ye,showToast:q,notify:qi,pwa:{promptInstall:R_,undismissInstallHint:M_,getState:Dn,subscribe:fc,requestNotificationPermission:Qy,getNotificationPermission:eb},renderKeyedList:B0,clearKeyedList:z0,registerNamespace:(v,N)=>{if(typeof v!="string"||v===""){console.warn("[desktop-mode] registerNamespace: name must be a non-empty string");return}if(!N||typeof N!="object"){console.warn(`[desktop-mode] registerNamespace("${v}"): api must be an object`);return}if(Q0.has(v)){console.warn(`[desktop-mode] registerNamespace("${v}"): name is reserved by the shell — pick a plugin-specific key`);return}O[v]=N},getWindowConfig:v=>{const N=window.desktopModeWindowConfig;if(!N||typeof N!="object")return;const C=N[v];return C===void 0?void 0:C},debug:{window:v=>{const N=(I.nativeWindows??[]).find(K=>K.id===v);if(!N)return null;const C=N.scriptUrl||"";let L="unknown",A=!1;C&&(document.querySelector(`script[data-desktop-mode-vendor="${C.replace(/"/g,'\\"')}"]`)?(L="lazy",A=!0):Array.from(document.querySelectorAll("script[src]")).find(x=>x.src===C)&&(L="eager",A=!0));const R=window.desktopModeWindowConfig,F=!!(R&&typeof R=="object"&&Object.prototype.hasOwnProperty.call(R,v));return{id:v,scriptHandle:N.scriptHandle||"",scriptUrl:C,loadPath:L,tagInDom:A,configPresent:F,extras:{hasTranslations:!!N.scriptTranslations,l10nCount:(N.scriptL10n??[]).length,beforeCount:(N.scriptBefore??[]).length,afterCount:(N.scriptAfter??[]).length}}}}};return O}function tS(e){if(window.wp||(window.wp={}),!window.wp.desktop){window.wp.desktop=e;return}Object.assign(window.wp.desktop,e)}const Kr=re("desktop-mode/layout",()=>({layout:"classic"}));function df(e){Kr.state.layout!==e&&(Kr.state.layout=e,Kr.notify())}class lf{constructor(t){this.shape=t}title(){return this.shape.title}icon(){return this.shape.icon}previewUrl(){return this.shape.previewUrl}ref(){return this.shape.ref}exists(){return this.shape.exists}}class nS extends lf{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const oo=new Map,Xr=new Set;function We(e){if(!e.type)throw new Error("[desktop-mode] registerType: `type` is required.");if(!e.label)throw new Error("[desktop-mode] registerType: `label` is required.");oo.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),T("desktop-mode.files.type-registered",e.type,e),uf()}function oS(e){oo.delete(e)&&(T("desktop-mode.files.type-unregistered",e),uf())}function sS(e){const t=oo.get(e);return t||null}function cf(){const e=Array.from(oo.values()).slice(),t=j("desktop-mode.files.types",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>o.sort!==s.sort?o.sort-s.sort:o.label.localeCompare(s.label)),n}function so(e){const t=oo.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new nS(e,e.type)}function iS(e){return Xr.add(e),()=>Xr.delete(e)}function uf(){for(const e of Xr)try{e()}catch(t){console.error("[desktop-mode] files registry subscriber threw:",t)}}const Ms=new Map,Yr=new Set;let Zr={};function pf(e){Zr={...e},ta()}function Jr(){return{...Zr}}function Ue(e){if(!e.id)throw new Error("[desktop-mode] registerOpener: `id` is required.");if(!e.label)throw new Error("[desktop-mode] registerOpener: `label` is required.");if(!Array.isArray(e.types)||e.types.length===0)throw new Error("[desktop-mode] registerOpener: `types` must be a non-empty array.");if(!e.handler||typeof e.handler!="object")throw new Error("[desktop-mode] registerOpener: `handler` is required.");Ms.set(e.id,{id:e.id,label:e.label,types:e.types.slice(),isDefault:!!e.isDefault,sort:typeof e.sort=="number"?e.sort:100,handler:e.handler}),T("desktop-mode.files.opener-registered",e.id,e),ta()}function rS(e){Ms.delete(e)&&(T("desktop-mode.files.opener-unregistered",e),ta())}function aS(e){return Ms.get(e)??null}function ff(){const e=Array.from(Ms.values()).slice(),t=j("desktop-mode.files.openers",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>{const i=typeof o.sort=="number"?o.sort:100,r=typeof s.sort=="number"?s.sort:100;return i!==r?i-r:o.label.localeCompare(s.label)}),n}function Qr(e){return ff().filter(t=>t.types.includes(e))}function ea(e){const t=Qr(e);if(t.length===0)return null;const n=Zr[e];let o=null;return n&&(o=t.find(i=>i.id===n)??null),o||(o=t.find(i=>i.isDefault)??null),o||(o=t[0]),j("desktop-mode.files.resolve-opener",o,e)??null}function dS(e){return Yr.add(e),()=>Yr.delete(e)}function ta(){for(const e of Yr)try{e()}catch(t){console.error("[desktop-mode] openers subscriber threw:",t)}}let io=null;function lS(e){io=e}async function na(e,t){if(!io)return console.warn("[desktop-mode] wp.desktop.files.open() called before the shell installed open deps. The file will not open."),!1;const n=ea(e.type());if(!n)return T("desktop-mode.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;T("desktop-mode.files.opening",{file:e,openerId:n.id});try{const o=n.handler;if(o.kind==="url"){const s=await o.url(e);if(!s)return!1;const i=o.windowId?o.windowId(e):io.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),d=io.openUrl({id:i,url:s,title:r,icon:a});return T("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"url"}),d}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=io.openNativeWindow(o.windowId,s);return T("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),T("desktop-mode.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return T("desktop-mode.files.open-failed",{reason:"handler-threw",type:e.type(),ref:e.ref(),openerId:n.id,error:o}),console.error("[desktop-mode] file opener threw:",o),!1}}function cS(){We({type:"shortcut",label:"Plugin shortcut",sort:1}),We({type:"folder",label:"Folder",sort:5}),We({type:"post",label:"Post",sort:10}),We({type:"attachment",label:"Media",sort:20}),We({type:"upload",label:"Uploaded file",sort:25}),We({type:"user",label:"User",sort:30}),We({type:"term",label:"Taxonomy term",sort:40}),We({type:"comment",label:"Comment",sort:50}),We({type:"bookmark",label:"Bookmark",sort:60}),We({type:"link",label:"Web link",sort:70}),We({type:"embed",label:"Embedded web window",sort:80})}let oa=null;function mf(e){oa=e}function ro(){if(!oa)throw new Error("[desktop-mode] files REST client called before installRestDeps().");return oa}function uS(){return ro()}class sa extends Error{constructor(t){super(`Row was changed by ${t.actor.name||"another session"} (parent="${t.current.parentName}")`),this.name="FilesConflictError",this.status=409,this.detail=t}}async function ae(e,t){const{baseUrl:n,nonce:o}=ro(),s=Ze(n,e),i=new Headers(t.headers??{});i.set("X-WP-Nonce",o),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Pe(s,{...t,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 sa(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 Le(e=0){return ae(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function Jt(e){return ae("/placements",{method:"POST",body:JSON.stringify(e)})}function Qt(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),ae(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function hf(e){return ae(`/placements/${e}`,{method:"DELETE"})}async function ia(e,t){const{baseUrl:n,nonce:o}=ro(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Pe(i,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o},credentials:"same-origin",body:JSON.stringify({items:[{id:e,type:t}]})},{source:"desktop-mode/files"});if(!r.ok)throw new Error(`[desktop-mode] restore ${r.status}`);return await r.json()}function wf(){return ae("/folders",{method:"GET"})}function ra(e){return ae("/folders",{method:"POST",body:JSON.stringify(e)})}function gf(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),ae(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function yf(e){return ae(`/folders/${e}`,{method:"DELETE"})}function bf(e){return ae("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function vf(e){return ae(`/folders/${e}/shares`,{method:"GET"})}function kf(e,t){return ae(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function _f(e,t,n){return ae(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function Ef(e,t){return ae(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function Sf(e,t){return ae(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function xf(e,t){return ae(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function If(e){return ae(`/folders/${e}/leave`,{method:"POST"})}function pS(){return ae("/folder-sharing-tables/purge",{method:"POST"})}function Cf(e){return ae(`/uploads/${e}/shares`,{method:"GET"})}function Af(e,t){return ae(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function Lf(e,t){return ae(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function Tf(e,t){return ae(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function Nf(e,t){return ae(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function Df(e){return ae(`/uploads/${e}/leave`,{method:"POST"})}function fS(e,t){return ae(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function Of(e,t){return ae("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function aa(e){const{baseUrl:t,nonce:n}=ro(),o=Ze(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function Rf(e){const{baseUrl:t,nonce:n}=ro(),o=Ze(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const mS=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:sa,acceptFileShare:Tf,acceptShare:Sf,createFolder:ra,createPlacement:Jt,deleteFolder:yf,deletePlacement:hf,denyFileShare:Nf,denyShare:xf,ensureUploadPath:Of,getFilesRestDeps:uS,getFolderZipUrl:Rf,getUploadDownloadUrl:aa,installRestDeps:mf,inviteFileShare:Af,inviteShare:kf,leaveFileShare:Df,leaveShare:If,listFileShares:Cf,listFolders:wf,listPlacements:Le,listShares:vf,purgeFolderSharingTables:pS,renameUpload:fS,restoreTrashedItem:ia,revokeFileShare:Lf,revokeShare:Ef,saveAssociations:bf,updateFolder:gf,updatePlacement:Qt,updateShareCapability:_f},Symbol.toStringTag,{value:"Module"})),hS="desktop-mode/files";function nt(){return re(hS,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function en(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("desktop-mode-files-changed",{detail:{source:"local",...e}}))}function pt(e,t){const n=nt(),o=new Map(n.state.placementsByFolder);o.set(e,t.slice());const s=new Set(n.state.hydratedFolders);s.add(e),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),en({kind:"placements-set",folderId:e})}function Ps(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[desktop-mode] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=nt(),o=new Map(n.state.placementsByFolder);for(const[a,d]of o)if(d.findIndex(c=>c&&c.id===e.id)>=0&&a!==e.parentId){const c=d.filter(Boolean),u=c.findIndex(p=>p.id===e.id);u>=0&&c.splice(u,1),o.set(a,c)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),en({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function ao(e,t="local"){const n=nt(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(d=>d&&d.id===e)>=0){const d=r.filter(Boolean).filter(l=>l.id!==e);o.set(i,d),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),en({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function Mf(e){const t=nt(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),en({kind:"folders-set"})}function da(e,t="local"){const n=nt(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),en({kind:"folder-upserted",folderRowId:e.id,source:t})}function la(e,t="local"){const n=nt(),o=new Map(n.state.folders);o.delete(e);const s=new Map(n.state.placementsByFolder);s.delete(e),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),en({kind:"folder-removed",folderRowId:e,source:t})}function ca(e){return nt().subscribe(e)}function ft(){return nt().getState()}function Pf(e){const t=ft(),n=t.placementsByFolder.get(e.parentId)?.find(o=>o&&o.id===e.id);if(n)return n;for(const o of t.placementsByFolder.values()){const s=o.find(i=>i&&i.id===e.id);if(s)return s}return e}const J={getState:ft,subscribe:ca,setFolderPlacements:pt,upsertPlacement:Ps,upsertFolder:da,removePlacement:ao,removeFolder:la,currentPlacement:Pf},wS=ge`:host{display:inline-block}`,gS=ge`:host{position:absolute;width:var( --wpd-ribbon-size,90px );height:var( --wpd-ribbon-size,90px );overflow:hidden;pointer-events:none;z-index:var( --wpd-ribbon-z,2 )}:host( [ hidden ] ){display:none}.banner{position:absolute;display:block;width:var( --wpd-ribbon-banner-width,140px );padding:var( --wpd-ribbon-padding,4px 0 );text-align:center;font:var( --wpd-ribbon-font,700 10px/1.4 var( --desktop-mode-font,system-ui ) );letter-spacing:var( --wpd-ribbon-tracking,0.06em );text-transform:uppercase;color:var( --wpd-ribbon-fg,#fff );background:var( --wpd-ribbon-bg,var( --wp-admin-theme-color,#2271b1 ) );box-shadow:var( --wpd-ribbon-shadow,0 2px 4px rgba( 0,0,0,0.2 ) )}:host(:not( [ placement ] ) ),:host( [ placement='top-end' ] ){inset-block-start:0;inset-inline-end:0}:host(:not( [ placement ] ) ) .banner,:host( [ placement='top-end' ] ) .banner{inset-block-start:var( --wpd-ribbon-banner-offset,20px );inset-inline-end:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host( [ placement='top-start' ] ){inset-block-start:0;inset-inline-start:0}:host( [ placement='top-start' ] ) .banner{inset-block-start:var( --wpd-ribbon-banner-offset,20px );inset-inline-start:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-end' ] ){inset-block-end:0;inset-inline-end:0}:host( [ placement='bottom-end' ] ) .banner{inset-block-end:var( --wpd-ribbon-banner-offset,20px );inset-inline-end:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-start' ] ){inset-block-end:0;inset-inline-start:0}:host( [ placement='bottom-start' ] ) .banner{inset-block-end:var( --wpd-ribbon-banner-offset,20px );inset-inline-start:var( --wpd-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host(:not( [ placement ] ) ) .banner,:host-context( [ dir='rtl' ] ):host( [ placement='top-end' ] ) .banner{transform:rotate( -45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='top-start' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-end' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-start' ] ) .banner{transform:rotate( -45deg )}:host( [ tone='success' ] ) .banner{background:var( --wpd-ribbon-success,#1a7f37 )}:host( [ tone='warning' ] ) .banner{background:var( --wpd-ribbon-warning,#9a6700 )}:host( [ tone='danger' ] ) .banner{background:var( --wpd-ribbon-danger,#cf222e )}:host( [ tone='info' ] ) .banner{background:var( --wpd-ribbon-info,#0969da )}:host( [ tone='neutral' ] ) .banner{background:var( --wpd-ribbon-neutral,#57606a )}`,Wo=class Wo extends me{render(){return z`<span class="banner" part="banner"><slot></slot></span>`}};Wo.props=["placement","tone"],Wo.styles=[gS],Wo.help=void 0;let ua=Wo;we("wpd-ribbon",ua);const te="desktop-mode-file-tile",$f={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function yS(){const e=window.wp?.desktop?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function bS(){return window.wp?.desktop?.dragManager??null}const vS=["type","ref","label","icon","thumbnail","kind","status","selected","missing","access-gated","drag-kind","drag-title","drag-icon"],mn=class mn extends me{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this.click())},this.addEventListener("keydown",this._keydownHandler)),this._paint()}disconnectedCallback(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null),this._keydownHandler&&(this.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null)}requestUpdate(){this.isConnected&&this._paint()}render(){return z``}_paint(){const t=this.getAttribute("type")??"",n=this.getAttribute("ref")??"",o=this.getAttribute("label")??"",s=this.getAttribute("icon")??"",i=this.getAttribute("thumbnail")??"",r=this.getAttribute("kind")??"entry",a=this.getAttribute("status")??"",d=this.hasAttribute("selected"),l=this.hasAttribute("missing"),c=this.hasAttribute("access-gated"),u=[te,`${te}--folder`,`${te}--missing`,`${te}--access-gated`,`${te}--selected`];for(const w of u)this.classList.remove(w);this.classList.add(te),r==="folder"&&this.classList.add(`${te}--folder`),l&&this.classList.add(`${te}--missing`),c&&this.classList.add(`${te}--access-gated`),d&&this.classList.add(`${te}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role","listitem"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";c?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const f=[`${te}__visual`,`${te}__label`,`${te}__lock`];for(const w of f)this.querySelectorAll(`:scope > .${w}`).forEach(g=>g.remove());this.querySelectorAll(":scope > wpd-ribbon").forEach(w=>w.remove());const h=document.createElement("span");if(h.className=`${te}__visual`,i){const w=document.createElement("img");w.src=i,w.alt="",w.loading="lazy",w.decoding="async",w.className=`${te}__preview`,w.draggable=!1,h.appendChild(w)}else if(s){const w=yi(s,{title:o,className:`${te}__icon`});h.appendChild(w)}this.appendChild(h);const m=document.createElement("span");if(m.className=`${te}__label`,m.textContent=o,this.appendChild(m),c){const w=document.createElement("span");w.className=`${te}__lock dashicons dashicons-lock`,w.setAttribute("aria-hidden","true"),this.appendChild(w)}if(a&&a!=="publish"&&$f[a]&&yS()){const w=document.createElement("wpd-ribbon");w.setAttribute("placement","top-end"),w.setAttribute("tone",kS(a)),w.textContent=$f[a],this.appendChild(w)}jh(this),T("desktop-mode.tile.rendered",{tile:this}),this._wireDragOut()}_wireDragOut(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null);const t=this.getAttribute("drag-kind");if(!t)return;const n=o=>{if(o.button!==0)return;const s=bS();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,a=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,d=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-d.left,offsetY:o.clientY-d.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};mn.shadow=!1,mn.props=vS,mn.styles=[wS],mn.help=void 0;let pa=mn;function kS(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}we("wpd-tile",pa);function _S(e){const t=document.createElement("wpd-tile");if(t.setAttribute("type",e.type),t.setAttribute("ref",e.ref),t.setAttribute("label",e.label),e.icon&&t.setAttribute("icon",e.icon),e.thumbnail&&t.setAttribute("thumbnail",e.thumbnail),e.role&&t.setAttribute("kind",e.role),e.status&&t.setAttribute("status",e.status),e.missing&&t.setAttribute("missing",""),e.accessGated&&t.setAttribute("access-gated",""),e.dataset)for(const[o,s]of Object.entries(e.dataset))s!=null&&(t.dataset[o]=String(s));if(Array.isArray(e.extraClasses))for(const o of e.extraClasses)o&&t.classList.add(o);const n=j("desktop-mode.tile.class",t.className,e);return n&&n!==t.className&&(t.className=n),typeof e.x=="number"&&typeof e.y=="number"&&(t.style.position="absolute",t.style.left=`${e.x}px`,t.style.top=`${e.y}px`),t}function Wf(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:so(e.file).title()}function ES(e,t){const n=so(e.file),o=n.previewUrl(),s=Wf(e),i=e.meta&&typeof e.meta.iconUrl=="string"?e.meta.iconUrl.trim():"";return{type:e.file.type,ref:e.file.ref,label:s,thumbnail:o||void 0,icon:o?void 0:i||n.icon(),x:e.x,y:e.y,dataset:{placementId:e.id,folderId:t},meta:e.meta,missing:!e.file.exists,accessGated:!!e.accessGated,ariaLabel:s}}function SS(e,t){const n=_S(ES(e,t)),o=j("desktop-mode.files.tile-class",te,e);o&&o!==te&&(n.className=o);const s=j("desktop-mode.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=Pf(e),a=so(r.file);if(r.accessGated){q({message:`You don’t have permission to open "${r.file.title||a.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}na(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),T("desktop-mode.files.tile-rendered",{tile:n,placement:e}),n}function ot(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const tn=new Map;function xS(e,t){return tn.set(e,t),()=>{tn.get(e)===t&&tn.delete(e)}}function IS(e,t){const n=tn.get(e);return n&&n.appliesTo(t)?n.acceptLabel:void 0}function CS(e,t){const n=tn.get(e.type);return n?n.appliesTo(t)&&n.accept(e.data,t):!1}function AS(e,t,n){const o=tn.get(e.payload.type);return!o||!o.appliesTo(n)?!1:(o.onDrop(e,t,n),!0)}function Uf(e,t){const n=s=>{if(!(s.target instanceof Node&&e.contains(s.target))){if(s.target instanceof Node)for(const i of t.siblingSelectors??[]){const r=Array.from(document.querySelectorAll(i));for(const a of r)if(a.contains(s.target))return}t.excludeOutsideTarget&&s.target instanceof Node&&t.excludeOutsideTarget.contains(s.target)||t.close()}},o=s=>{s.key==="Escape"&&t.close()};return document.addEventListener("mousedown",n,{capture:!0}),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",n,{capture:!0}),document.removeEventListener("keydown",o)}}const LS="desktop-mode-wallpaper-menu";let lo=null;function fa(){lo&&(lo.dispatchEvent(new CustomEvent("tile-menu-closed")),lo.remove(),lo=null,T("desktop-mode.files.tile-menu.closed",{}))}let Ff=0;function TS(e,t){fa();const n=++Ff;bn(()=>n===Ff,()=>NS(e,t))}function NS(e,{placement:t,items:n}){const o=j("desktop-mode.files.tile-menu",n.slice(),t),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(LS),i.dataset.placementId=String(t.id),i.style.left=`${e.x}px`,i.style.top=`${e.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",DS(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&&(fa(),u.onClick(new MouseEvent("click")))}),document.body.appendChild(i),lo=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=Uf(i,{close:()=>fa()});i.addEventListener("tile-menu-closed",d),T("desktop-mode.files.tile-menu.opened",{placementId:t.id,items:s.map(l=>l.id)})}function DS(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const _e="desktop-mode-create-folder-dialog";let co=null;function ma(){co&&(co.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),co.remove(),co=null,T("desktop-mode.files.create-folder.closed",{}))}function ha(e){if(ma(),j("desktop-mode.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${_e}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=_e,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${_e}-title`);const i=document.createElement("h2");i.id=`${_e}-title`,i.className=`${_e}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("label");r.className=`${_e}__label`,r.htmlFor=`${_e}-input`,r.textContent=e.label??"Folder name",s.appendChild(r);const a=document.createElement("input");a.type="text",a.id=`${_e}-input`,a.className=`${_e}__input`,a.value=n,a.setAttribute("autocomplete","off"),a.setAttribute("spellcheck","false"),s.appendChild(a);const d=document.createElement("p");d.className=`${_e}__error`,d.hidden=!0,d.setAttribute("role","alert"),s.appendChild(d);const l=document.createElement("div");l.className=`${_e}__actions`;const c=document.createElement("button");c.type="button",c.className=`${_e}__btn ${_e}__btn--secondary`,c.textContent="Cancel";const u=document.createElement("button");u.type="button",u.className=`${_e}__btn ${_e}__btn--primary`,u.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(u),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),co=o,a.focus(),a.select(),T("desktop-mode.files.create-folder.opened",{});const p=g=>{a.disabled=g,c.disabled=g,u.disabled=g,s.classList.toggle(`${_e}--busy`,g)},f=g=>{d.textContent=g,d.hidden=!1},h=()=>{ma(),e.onCancel?.()},m=async()=>{const g=a.value.trim();if(!g){f("Please enter a name."),a.focus();return}d.hidden=!0,p(!0);try{await e.onSubmit(g),ma()}catch(k){p(!1),f(k instanceof Error?k.message:"Could not create the folder."),a.focus(),a.select()}};c.addEventListener("click",()=>h()),u.addEventListener("click",()=>void m()),o.addEventListener("click",g=>{g.target===o&&h()});const w=g=>{g.key==="Escape"?(g.preventDefault(),h()):g.key==="Enter"&&!g.isComposing&&(g.preventDefault(),m())};s.addEventListener("keydown",w),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",w)})}const Oe=16,mt=96,uo=110;function po(e,t){const n=Math.max(0,Math.round((e-Oe)/mt)),o=Math.max(0,Math.round((t-Oe)/uo));return nn(n,o)}function nn(e,t){return{col:e,row:t,x:Oe+e*mt,y:Oe+t*uo}}function At(e,t,n,o){const s=po(e,t);if(!n.has(Ee(s.col,s.row)))return s;const i=o?Math.max(1,Math.floor((o.clientHeight-Oe)/uo)):999;for(let r=0;r<999;r++)for(let a=0;a<i;a++)if(!n.has(Ee(r,a)))return nn(r,a);return s}function Hf(e,t){const n=t?Math.max(1,Math.floor((t.clientWidth-Oe)/mt)):4,o=Math.max(1,n);for(let s=0;s<999;s++)for(let i=0;i<o;i++)if(!e.has(Ee(i,s)))return nn(i,s);return nn(0,0)}function Bf(e,t){const n=new Set;for(const o of e){const s=po(o.x,o.y);n.add(Ee(s.col,s.row))}return n}function Ee(e,t){return`${e},${t}`}function zf(e){return e instanceof sa}function OS(e){const t=e.detail.actor.name||"Someone else",n=e.detail.current.parentName||"another folder";return e.detail.reason==="trashed"?"This item is in the recycle bin.":e.detail.reason==="forbidden"?"You no longer have access.":e.detail.reason==="gone"?"This item was deleted.":`${t} moved this to "${n}".`}function Gf(e){const t=OS(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{const s=`desktop-mode-folder-${n}`,i=window.desktopMode?.windowManager;i?.focus&&i.focus(s)||i?.open&&i.open(s)}}),q({message:t,action:o,duration:7e3})}const fo=new Map;function jf(e,t){return fo.set(e,t),()=>{fo.get(e)===t&&fo.delete(e)}}function RS(e,t){const n=fo.get(e.type);return n?n.accept(e.data,t):!1}function MS(e,t,n){const o=fo.get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function $s(e,t,n){window.wp?.desktop?.broadcast?.(`desktop-mode.${e}.changed`,{source:"desktop-files",action:t,ids:n})}function qf(e){const t=window.wp?.desktop;if(!t?.showToast)return;const o=(e instanceof Error?e.message:String(e)).replace(/^\[desktop-mode\][^:]*:\s*/,"").replace(/^desktop_mode_files_[a-z_]+\s*/,"");t.showToast({message:o||"Could not move this item to the recycle bin.",duration:5e3})}function Vf(e,t){const n=window.wp?.desktop;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function Kf(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";J.removePlacement(t);try{await hf(t),$s(s,"trashed",[t]),Vf(`"${o}" moved to Trash`,async()=>{try{await ia(t,"placement");const i=await Le(n);J.setFolderPlacements(n,i.placements),$s(s,"untrashed",[t])}catch(i){console.error("[desktop-mode] restore failed:",i)}})}catch(i){console.error("[desktop-mode] deletePlacement failed:",i),qf(i),Le(n).then(r=>{J.setFolderPlacements(n,r.placements)})}}async function Xf(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";J.removePlacement(n),J.removeFolder(t);try{await yf(t),$s("folder","trashed",[t]),Vf(`"${s}" moved to Trash`,async()=>{try{await ia(t,"folder");const i=await Le(o);J.setFolderPlacements(o,i.placements),$s("folder","untrashed",[t])}catch(i){console.error("[desktop-mode] restore folder failed:",i)}})}catch(i){console.error("[desktop-mode] deleteFolder failed:",i),qf(i),Le(o).then(r=>{J.setFolderPlacements(o,r.placements)})}}function PS(e){return e.file?.type==="folder"?Xf(e):Kf(e)}function $S(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o}}function mo(){return window.wp?.desktop?.dragManager??null}const WS="desktop-mode-files-layer";function Yf(e,t=0){const n=document.createElement("div");n.className=WS,n.setAttribute("role","list"),n.dataset.folderId=String(t),e.appendChild(n);let o="",s=null;const i=new Set,r=x=>{for(const $ of i)try{$(x)}catch(B){console.error("[desktop-mode] files: selection listener threw:",B)}},a=x=>{const $=x?x.id:null;$!==s&&(n.querySelectorAll(`.${te}--selected`).forEach(B=>B.removeAttribute("selected")),x&&n.querySelector(`[data-placement-id="${x.id}"]`)?.setAttribute("selected",""),s=$,r(x))},d=x=>{const $=new Map,B=new Set;let P=0;for(const M of x){if(!Te(M))continue;const U=nn(0,P);$.set(M.id,{x:U.x,y:U.y}),B.add(Ee(U.col,U.row)),P+=1}const X=new Map;for(const M of x){if($.has(M.id))continue;const U=po(M.x,M.y),ee=Ee(U.col,U.row);if(!B.has(ee)){B.add(ee);continue}const ce=At(M.x,M.y,B,e);B.add(Ee(ce.col,ce.row)),X.set(M.id,{x:ce.x,y:ce.y})}return{pinnedSlots:$,displaced:X}},l=(x,$,B,P)=>{const X=B.get($.id),M=P.get($.id);X?ot(x,X.x,X.y):M?ot(x,M.x,M.y):ot(x,$.x,$.y)},c=(x,$,B)=>{const P=SS(x,t),X=$.get(x.id);if(X){if(ot(P,X.x,X.y),P.classList.add(`${te}--pinned`),tm(P,x),O(P,x),Zf(x)){const U=mo();U&&m.set(x.id,em(U,P,x))}return P}const M=B.get(x.id);if(M&&ot(P,M.x,M.y),jS(P,x,t),tm(P,x),O(P,x),x.file.type==="folder"){const U=parseInt(x.file.ref,10);if(U>0){const ee=mo();if(ee){const ce=GS(ee,P,U);h.set(x.id,ce)}}}else if(Zf(x)){const U=mo();U&&m.set(x.id,em(U,P,x))}return P},u=x=>{const $=new Map;for(const M of n.querySelectorAll("[data-placement-id]")){const U=M.dataset.placementId??"",ee=parseInt(U,10);if(U===""||Number.isNaN(ee)&&U!=="-0")return!1;$.set(ee,M)}const B=new Set;for(const M of x)B.add(M.id);for(const M of x){const U=$.get(M.id);if(!U)continue;if(U.dataset.fileType!==M.file.type||U.dataset.fileRef!==M.file.ref||U.classList.contains(`${te}--pinned`)!==Te(M))return!1}for(const[M,U]of $){if(B.has(M))continue;const ee=h.get(M);if(ee){try{ee()}catch{}h.delete(M)}const ce=m.get(M);if(ce){try{ce()}catch{}m.delete(M)}U.remove()}const{pinnedSlots:P,displaced:X}=d(x);for(const M of x){const U=$.get(M.id);if(U){l(U,M,P,X),Qf(U,M);continue}n.appendChild(c(M,P,X))}return s!==null&&!n.querySelector(`[data-placement-id="${s}"]`)&&(s=null,r(null)),T("desktop-mode.files.grid-rendered",{folderId:t,count:x.length}),!0},p=x=>{const B=(x.placementsByFolder.get(t)??[]).slice().sort((U,ee)=>{const ce=Te(U)?0:1,V=Te(ee)?0:1;return ce-V}),P=US(B);if(P===o||(o=P,BS(B,n,e))||u(B))return;n.replaceChildren();for(const[,U]of h)try{U()}catch{}h.clear();for(const[,U]of m)try{U()}catch{}m.clear();const{pinnedSlots:X,displaced:M}=d(B);for(const U of B)n.appendChild(c(U,X,M));s!==null&&!n.querySelector(`[data-placement-id="${s}"]`)?(s=null,r(null)):s!==null&&n.querySelector(`[data-placement-id="${s}"]`)?.setAttribute("selected",""),T("desktop-mode.files.grid-rendered",{folderId:t,count:B.length})},f=[],h=new Map,m=new Map;let w=null,g=null;const k=x=>{if(w||x.payload.type!=="desktop-file")return;const $=document.createElement("div");$.className="desktop-mode-files-drop-preview",$.setAttribute("aria-hidden","true"),n.appendChild($),w=$;const B=x.payload.ghost,P=B?.offsetX??0,X=B?.offsetY??0,U=x.payload.data?.placement?.id,ee=(se,he)=>{const Se=n.getBoundingClientRect(),be=Math.max(0,se-Se.left-P),ri=Math.max(0,he-Se.top-X),Yo=J.getState().placementsByFolder.get(t)??[],hn=Us(Yo,U),Zo=At(be,ri,hn,e);$.style.transform=`translate3d(${Zo.x}px, ${Zo.y}px, 0)`},ce=x.payload.source.getBoundingClientRect();ee(ce.left+P,ce.top+X);const V=se=>{ee(se.clientX,se.clientY)};document.addEventListener("pointermove",V),g=V},D=()=>{g&&(document.removeEventListener("pointermove",g),g=null),w&&(w.remove(),w=null)},b={id:`desktop-mode-files-canvas-${t}`,element:e,accept:x=>{if(x.type!=="desktop-file"&&x.type!=="shortcut")return RS(x,{folderId:t,host:e});if(t>0&&x.type==="desktop-file"){const $=x.data;if($.placement.file?.type==="folder"){const B=parseInt($.placement.file.ref,10);if(!Number.isNaN(B)&&Jf(B,t))return!1}}return!0},onEnter:x=>{e.setAttribute("data-files-drop-active",""),(x.payload.type==="desktop-file"||x.payload.type==="shortcut")&&k(x)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),D()},onDrop:(x,$)=>{if(e.removeAttribute("data-files-drop-active"),D(),x.payload.type!=="desktop-file"&&x.payload.type!=="shortcut"){MS(x,$,{folderId:t,host:e});return}const B=n.getBoundingClientRect(),P=x.payload.ghost,X=P?.offsetX??0,M=P?.offsetY??0,U=Math.max(0,$.clientX-B.left-X),ee=Math.max(0,$.clientY-B.top-M),ce=J.getState().placementsByFolder.get(t)??[];if(x.payload.type==="desktop-file"){const V=x.payload.data,se=Us(ce,V.placement.id),he=At(U,ee,se,e),Se={...V.placement,x:he.x,y:he.y,parentId:t};if(J.upsertPlacement(Se),T("desktop-mode.files.tile-manually-placed",{folderId:t,placementId:V.placement.id}),Ws(V.placement)){const be=wa(V.placement);be&&HS(be,he.x,he.y);return}Qt(V.placement.id,{x:he.x,y:he.y,parentId:t},V.placement.updatedAtMs).then(be=>{J.upsertPlacement(be,"remote")}).catch(be=>{zf(be)?Gf(be):console.error("[desktop-mode] files: drag persist failed",be),J.upsertPlacement(V.placement)});return}if(x.payload.type==="shortcut"){const V=x.payload.data,se=Us(ce),he=Hf(se,e);Jt({parentId:t,type:V.kind,ref:V.ref,x:he.x,y:he.y}).then(Se=>{J.upsertPlacement(Se),T("desktop-mode.files.shortcut-dropped",{folderId:t,placement:Se})}).catch(Se=>{console.error("[desktop-mode] shortcut drop failed:",Se)})}}},E=mo();E&&f.push(E.registerDropTarget(b));const I=x=>{x.target instanceof Element&&x.target.closest(`.${te}`)||a(null)};e.addEventListener("click",I);function O(x,$){x.addEventListener("click",B=>{B.stopPropagation(),a(J.currentPlacement($))})}p(J.getState());const v=J.subscribe(p);let N=()=>{};const C=new Promise(x=>{N=x});J.getState().hydratedFolders.has(t)?queueMicrotask(N):Le(t).then(x=>{J.setFolderPlacements(t,x.placements)}).catch(x=>{console.error("[desktop-mode] files: failed to hydrate folder",t,x)}).finally(()=>{N()});const L=()=>{const x=e.clientWidth>0?e.clientWidth:4*mt;return Math.max(1,Math.floor((x-Oe)/mt))},A=(x,$)=>{const B=x.slice();switch($){case"name-asc":B.sort((P,X)=>P.file.title.localeCompare(X.file.title));break;case"name-desc":B.sort((P,X)=>X.file.title.localeCompare(P.file.title));break;case"date-asc":B.sort((P,X)=>P.updatedAtMs-X.updatedAtMs);break;case"date-desc":B.sort((P,X)=>X.updatedAtMs-P.updatedAtMs);break}return B},R=x=>{const $=J.getState().placementsByFolder.get(t);if(!$||$.length===0)return;const B=$.filter(V=>Te(V)),P=$.filter(V=>!Te(V)),X=A(P,x),M=L(),U=new Set;for(let V=0;V<B.length;V+=1)U.add(Ee(0,V));let ee=0;const ce=()=>{for(;;){const V=Math.floor(ee/M),se=ee%M;if(ee+=1,!U.has(Ee(se,V)))return{col:se,row:V}}};X.forEach((V,se)=>{const he=ce(),Se=Oe+he.col*mt,be=Oe+he.row*uo,ri={...V,x:Se,y:be,sortOrder:se};J.upsertPlacement(ri),!Ws(V)&&Qt(V.id,{x:Se,y:be,sortOrder:se}).catch(Yo=>{console.error("[desktop-mode] files: sort persist failed",Yo)})})},F=()=>{const x=J.getState().placementsByFolder.get(t);if(!x||x.length===0)return;const $=e.clientWidth>0?e.clientWidth:1/0;if(!x.some(V=>V.x+mt>$))return;const P=L(),X=x.filter(V=>Te(V)),M=x.filter(V=>!Te(V)),U=new Set;for(let V=0;V<X.length;V+=1)U.add(Ee(0,V));let ee=0;const ce=()=>{for(;;){const V=Math.floor(ee/P),se=ee%P;if(ee+=1,!U.has(Ee(se,V)))return{col:se,row:V}}};for(const V of M){const se=ce(),he=Oe+se.col*mt,Se=Oe+se.row*uo,be=n.querySelector(`[data-placement-id="${V.id}"]`);be&&ot(be,he,Se)}};let K=e.clientWidth,Y=null;return typeof ResizeObserver<"u"&&(Y=new ResizeObserver(()=>{const x=e.clientWidth;x!==K&&(K=x,F())}),Y.observe(e)),{host:e,folderId:t,onSelectionChange(x){return i.add(x),()=>{i.delete(x)}},sort:R,reflow:F,hydrated:C,dispose(){v(),Y?.disconnect(),Y=null;for(const x of f)try{x()}catch{}f.length=0;for(const x of h.values())try{x()}catch{}h.clear();for(const x of m.values())try{x()}catch{}m.clear(),e.removeEventListener("click",I),i.clear(),n.remove()}}}function US(e){if(e.length===0)return"0";const t=[];for(const n of e)t.push(`${n.id}:${n.parentId}:${n.x}:${n.y}:${n.sortOrder}:${n.updatedAtMs}:${n.file.type}:${n.file.ref}:${n.file.title}:${n.file.icon}:${Te(n)?1:0}`);return t.join("|")}function Te(e){return!!e.file.pinned}function wa(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function Ws(e){return e.id<=0||wa(e)!==null}const FS="desktop-mode-recycle-bin";function Zf(e){return!(e.file?.type==="folder"||e.file?.ref===FS)}function Us(e,t){const n=e.slice().sort((i,r)=>{const a=Te(i)?0:1,d=Te(r)?0:1;return a-d}),o=new Set;let s=0;for(const i of n)if(!(t!==void 0&&i.id===t))if(Te(i))o.add(Ee(0,s)),s+=1;else{const r=po(i.x,i.y);o.add(Ee(r.col,r.row))}return o}function Jf(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=J.getState();for(const a of o.placementsByFolder.values())for(const d of a){if(d.file?.type!=="folder")continue;const 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=t,r=256;for(;i>0&&r-- >0;){if(i===e||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function HS(e,t,n){const o=window.wp?.desktop;if(!o?.getOsSettings||!o?.updateOsSettings)return;const s=o.getOsSettings().dockPromotedPositions??{};o.updateOsSettings({dockPromotedPositions:{...s,[e]:{x:t,y:n}}})}function BS(e,t,n){const o=Array.from(t.querySelectorAll("[data-placement-id]"));if(o.length!==e.length)return!1;const s=new Map;for(const 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 e){const c=s.get(l.id);if(!c||c.dataset.fileType!==l.file.type||c.dataset.fileRef!==l.file.ref||c.classList.contains(`${te}--pinned`)!==Te(l))return!1}const i=new Map,r=new Set;let a=0;for(const l of e){if(!Te(l))continue;const c=nn(0,a);i.set(l.id,{x:c.x,y:c.y}),r.add(Ee(c.col,c.row)),a+=1}const d=new Map;for(const l of e){if(i.has(l.id))continue;const c=po(l.x,l.y),u=Ee(c.col,c.row);if(!r.has(u)){r.add(u);continue}const p=At(l.x,l.y,r,n);r.add(Ee(p.col,p.row)),d.set(l.id,{x:p.x,y:p.y})}for(const l of e){const c=s.get(l.id);if(!c)continue;const u=i.get(l.id),p=d.get(l.id);u?ot(c,u.x,u.y):p?ot(c,p.x,p.y):ot(c,l.x,l.y),Qf(c,l)}return!0}function Qf(e,t){const n=Wf(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function zS(e){const t=window.wp?.desktop;if(!t?.getOsSettings||!t?.updateOsSettings)return;const o={...t.getOsSettings().itemVisibility??{},[e]:"dock"};t.updateOsSettings({itemVisibility:o})}function em(e,t,n){const o={placement:n};let s=null;return e.registerDropTarget({id:`desktop-mode-files-tile-${n.id}-reject`,element:t,get acceptLabel(){return s?IS(s,o):void 0},accept:i=>(s=i.type,CS(i,o)),onEnter:()=>{t.classList.add(`${te}--drop-target`)},onLeave:()=>{t.classList.remove(`${te}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${te}--drop-target`),AS(i,r,o)}})}function GS(e,t,n,o){const s={id:`desktop-mode-files-folder-${n}-tile-${t.dataset.placementId??"?"}`,element:t,accept:i=>{if(i.type!=="desktop-file"&&i.type!=="shortcut")return!1;if(i.type==="desktop-file"){const r=i.data;if(r.placement.file.type==="folder"&&parseInt(r.placement.file.ref,10)===n||r.placement.parentId===n||Ws(r.placement))return!1;if(r.placement.file.type==="folder"){const a=parseInt(r.placement.file.ref,10);if(!Number.isNaN(a)&&Jf(a,n))return!1}}return!0},onEnter:()=>{t.classList.add(`${te}--drop-target`)},onLeave:()=>{t.classList.remove(`${te}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${te}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a={...r.placement,parentId:n};J.upsertPlacement(a),Qt(r.placement.id,{parentId:n},r.placement.updatedAtMs).then(d=>{J.upsertPlacement(d,"remote")}).catch(d=>{zf(d)?Gf(d):console.error("[desktop-mode] files: move-into-folder persist failed",d),J.upsertPlacement(r.placement)});return}if(i.payload.type==="shortcut"){const r=i.payload.data,a=J.getState().placementsByFolder.get(n)??[],d=Hf(Us(a));Jt({parentId:n,type:r.kind,ref:r.ref,x:d.x,y:d.y}).then(l=>{J.upsertPlacement(l),T("desktop-mode.files.shortcut-dropped",{folderId:n,placement:l})}).catch(l=>{console.error("[desktop-mode] shortcut drop into folder failed:",l)})}}};return e.registerDropTarget(s)}function jS(e,t,n){e.addEventListener("pointerdown",o=>{if(o.button!==0)return;const s=mo();if(!s)return;const r=J.getState().placementsByFolder.get(n)?.find(a=>a.id===t.id)??t;parseFloat(e.style.left)||r.x,parseFloat(e.style.top)||r.y,s.start({payload:{type:"desktop-file",source:e,data:{placement:r,sourceFolderId:n,bridgePayload:$S(r)},ghost:{offsetX:o.clientX-e.getBoundingClientRect().left,offsetY:o.clientY-e.getBoundingClientRect().top}},origin:o})})}function tm(e,t){e.addEventListener("contextmenu",n=>{n.preventDefault(),n.stopPropagation();const o=J.currentPlacement(t),s=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,onClick:()=>{const r=so(o.file);na(r)}}];if(o.file.type==="post"&&s.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>{const r=parseInt(o.file.ref,10);if(!r)return;const a=window.wp?.desktop?.myWordpress,l=(typeof o.file.postType=="string"?o.file.postType:"post")==="page"?"pages":"posts";a?.openDetail({entityId:l,postId:r,postTitle:o.file.title||`#${r}`})}}),o.file.type==="folder")s.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>{const r=parseInt(o.file.ref,10);r&&ha({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:o.file.title,onSubmit:async a=>{const d=a.trim();if(!d||d===o.file.title)return;const l=o.file.title,c={...o,file:{...o.file,title:d}};J.upsertPlacement(c);try{const u=J.getState().folders.get(r)?.updatedAtMs??0,p=await gf(r,{name:d},u);J.upsertFolder(p);const f=await Le(o.parentId);J.setFolderPlacements(o.parentId,f.placements)}catch(u){console.error("[desktop-mode] rename folder failed:",u),J.upsertPlacement({...o,file:{...o.file,title:l}})}}})}}),o.canTrash!==!1&&s.push({id:"delete-folder",label:"Move folder to Trash",icon:"dashicons-trash",sort:90,danger:!0,onClick:()=>Xf(o)});else{const r=wa(o),a=o.file.type==="shortcut";if(r||a){const d=r??o.file.ref;s.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,onClick:()=>zS(d)})}else o.canTrash!==!1&&s.push({id:"remove",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,onClick:()=>Kf(o)})}TS({x:n.clientX,y:n.clientY},{placement:o,items:s})})}function on(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,o=0;for(;n>=1024&&o<t.length-1;)n/=1024,o++;const s=n>=100||o===0?0:1;return`${n.toFixed(s)} ${t[o]}`}const sn="desktop-mode-folder-status-bar";function qS(e,t){const n=document.createElement("div");n.className=sn,n.setAttribute("role","status"),n.dataset.folderId=String(t),e.appendChild(n);const o=()=>{const i=ft().placementsByFolder.get(t)??[],r=i.filter(u=>u.file.type==="folder").length,a=i.length-r;let d=0;for(const u of i)if(u.file.type==="upload"){const p=Number(u.file.sizeBytes??0);Number.isFinite(p)&&p>0&&(d+=p)}const l={folderId:t,totals:{files:a,folders:r,total:i.length,bytes:d}},c=VS(l);KS(n,c)};o();const s=ca(()=>o());return{dispose(){s(),n.remove()}}}function VS(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:om(n,"file","files")+(t>0?`, ${om(t,"folder","folders")}`:"")+(o>0?` (${on(o)})`:""),align:"start",sort:10}],i=j("desktop-mode.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function KS(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,d=typeof r.sort=="number"?r.sort:100;return a!==d?a-d:i.label.localeCompare(r.label)},o=t.filter(i=>(i.align??"start")==="start").sort(n),s=t.filter(i=>i.align==="end").sort(n);e.replaceChildren(),e.appendChild(nm("start",o)),e.appendChild(nm("end",s))}function nm(e,t){const n=document.createElement("div");n.className=`${sn}__cluster ${sn}__cluster--${e}`;for(const o of t)n.appendChild(XS(o));return n}function XS(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${sn}__segment`,n.dataset.segmentId=e.id,t&&(n.type="button",n.addEventListener("click",s=>e.onClick(s))),e.icon){const s=document.createElement("span");s.className=`${sn}__icon dashicons ${e.icon.replace(/[^a-zA-Z0-9_-]/g,"")}`,s.setAttribute("aria-hidden","true"),n.appendChild(s)}const o=document.createElement("span");return o.className=`${sn}__label`,o.textContent=e.label,n.appendChild(o),n}function om(e,t,n){return`${e} ${e===1?t:n}`}const Fs="desktop-mode-icon-canvas-menu";let ho=null,Hs=null,ga=null,wo=null,go=null;function YS(e,t){t.openOnBackgroundClick;const n=i=>{ZS(i.target)||sm(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(ga===e&&ho){Lt();return}const a=JS(t),d=j("desktop-mode.icon-canvas.menu",a,t.scope),l=Array.isArray(d)?d:a,c=++o;bn(()=>c===o,()=>QS(l,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),Lt()}}}function ZS(e){return e instanceof Element?e.closest(".desktop-mode-file-tile")!==null:!1}function sm(e){return e instanceof Element?e.closest(`.${Fs}`)!==null:!1}function JS(e){const n=[{id:"sort-by",label:S("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:S("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:S("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:S("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:S("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function im(e){return e.slice().sort((t,n)=>{const o=typeof t.sort=="number"?t.sort:100,s=typeof n.sort=="number"?n.sort:100;return o!==s?o-s:t.label.localeCompare(n.label)})}function QS(e,t,n){if(Lt(),e.length===0)return;ga=n;const o=im(e),s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(Fs),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;for(const r of o){i.set(r.id,r);const a=rm(s,r);Bs(r)&&a.addEventListener("mouseenter",()=>{am(r,a)})}s.addEventListener("wpd-context-menu-pick",r=>{const a=r.detail,d=i.get(a.id);if(d){if(Bs(d)){r.stopPropagation();const l=s.querySelector(`[data-menu-item-id="${d.id}"]`);l&&am(d,l);return}Lt(),d.onClick?.()}}),document.body.appendChild(s),ho=s,tx(s),queueMicrotask(()=>{wo=r=>{sm(r.target)||Lt()},go=r=>{r.key==="Escape"&&Lt()},document.addEventListener("mousedown",wo),document.addEventListener("keydown",go)})}function rm(e,t){const n=document.createElement("wpd-context-menu-option");return n.dataset.menuItemId=t.id,n.setAttribute("value",t.id),t.heading&&n.setAttribute("heading",""),t.disabled&&n.setAttribute("disabled",""),t.icon&&n.setAttribute("icon",nx(t.icon)),Bs(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function am(e,t){if(dm(),!Bs(e))return;const n=document.createElement("wpd-context-menu");n.setAttribute("open",""),n.classList.add(Fs,`${Fs}--flyout`);const o=new Map;for(const s of im(e.children??[]))o.set(s.id,s),rm(n,s);n.addEventListener("wpd-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),Lt(),r.onClick?.())}),document.body.appendChild(n),Hs=n,ex(n,t)}function ex(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`;const o=e.getBoundingClientRect();o.right>window.innerWidth&&(e.style.left=`${Math.max(0,n.left-o.width)}px`),o.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-o.height-8)}px`)}function tx(e){const t=e.getBoundingClientRect();t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-8)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-8)}px`)}function Bs(e){return Array.isArray(e.children)&&e.children.length>0}function dm(){Hs&&(Hs.remove(),Hs=null)}function Lt(){dm(),ho&&(ho.remove(),ho=null),ga=null,wo&&(document.removeEventListener("mousedown",wo),wo=null),go&&(document.removeEventListener("keydown",go),go=null)}function nx(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const Tt="desktop-mode-breadcrumbs";function ox(e,t,n={}){if(e.replaceChildren(),e.classList.add(Tt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${Tt}__back`,s.setAttribute("aria-label",S("Back","desktop-mode")),s.title=S("Back","desktop-mode");const i=document.createElement("span");i.className="dashicons dashicons-arrow-left-alt2",i.setAttribute("aria-hidden","true"),s.appendChild(i),n.backDisabled&&(s.disabled=!0);const r=n.onBack;s.addEventListener("click",()=>{s.disabled||r()}),e.appendChild(s)}const o=document.createElement("nav");o.className=`${Tt}__crumbs`,o.setAttribute("aria-label",S("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const d=document.createElement("span");d.className=`${Tt}__sep`,d.setAttribute("aria-hidden","true"),d.textContent="›",o.appendChild(d)}if(!s.onClick){const d=document.createElement("span");d.className=`${Tt}__crumb ${Tt}__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=`${Tt}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}async function yo(e,t={}){const n=await Pe(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":sx(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function sx(){return window.wp?.desktop?.config?.restNonce??""}function ix(){const e=window.wp?.desktop?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function bo(e){return Ze(ix(),e)}function rx(e,t){const n=j("desktop-mode.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(ax(e));return}t.replaceChildren(gx()),dx(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(yx(o))})}function ax(e){const t=document.createElement("div");t.className="desktop-mode-files__access-gated";const n=document.createElement("div");n.className="desktop-mode-files__access-gated-ring";const o=document.createElement("span");o.className="dashicons dashicons-lock desktop-mode-files__access-gated-glyph",o.setAttribute("aria-hidden","true"),n.appendChild(o),t.appendChild(n);const s=document.createElement("h2");s.className="desktop-mode-files__access-gated-title",s.textContent="No permission to view",t.appendChild(s);const i=document.createElement("p");i.className="desktop-mode-files__access-gated-sub";const r=e.file.title||e.file.type;i.textContent=`You don’t have access to "${r}". The folder owner shared this folder with you, but your role doesn’t include permission to open this item.`,t.appendChild(i);const a=document.createElement("p");return a.className="desktop-mode-files__access-gated-hint",a.textContent="Ask the owner to grant access on the underlying item, or to remove it from the shared folder.",t.appendChild(a),t}async function dx(e){const t=e.file;switch(t.type){case"post":return lx(t.ref,t);case"folder":return mx(t);case"shortcut":return hx(t);case"attachment":return fx(t.ref,t);case"user":return cx(t.ref,t);case"term":return ux(t);case"comment":return px(t.ref,t);case"bookmark":return wx(t);default:return Be(t)}}async function lx(e,t){const n=parseInt(e,10);if(!n)return Be(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await yo(bo(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return Be(t);const s=st(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=zs(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="desktop-mode-my-wordpress__article-meta";const a=[];if(a.push(lm(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=S("Explore details","desktop-mode"),u.title=S("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),u.addEventListener("click",()=>{const p=typeof t.postType=="string"?t.postType:"post";l.openDetail({entityId:p==="page"?"pages":"posts",postId:n,postTitle:zs(o.title.rendered)||`#${n}`})}),d.appendChild(u)}const c=document.createElement("wpd-button");return c.setAttribute("variant","primary"),c.textContent=S("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 t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";f?.open({id:`${m}-edit-${n}`,url:p,title:zs(o.title.rendered),icon:t.icon})}),d.appendChild(c),s.appendChild(d),s}async function cx(e,t){const n=parseInt(e,10);if(!n)return Be(t);let o=null;try{o=await yo(bo(`desktop-mode/v1/user-stats/${n}`))}catch{return Be(t)}const s=st("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||t.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(rn(o.counts.posts.total.toLocaleString(),S("Posts","desktop-mode"))),d.appendChild(rn(o.counts.pages.total.toLocaleString(),S("Pages","desktop-mode"))),d.appendChild(rn(o.counts.commentsReceived.toLocaleString(),S("Comments received","desktop-mode"))),s.appendChild(d),s}async function ux(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return Be(e);let o=null;try{o=await yo(bo(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return Be(e)}const s=st(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=o.profile.name||e.title||`#${t}`,s.appendChild(i);const r=document.createElement("p");if(r.className="desktop-mode-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const d=document.createElement("div");d.className="desktop-mode-my-wordpress__article-content",d.innerHTML=o.profile.description,s.appendChild(d)}const a=document.createElement("div");return a.className="desktop-mode-my-wordpress__user-stats",a.appendChild(rn(o.counts.posts.total.toLocaleString(),S("Posts","desktop-mode"))),a.appendChild(rn(o.counts.commentsReceived.toLocaleString(),S("Comments","desktop-mode"))),a.appendChild(rn(o.counts.distinctAuthors.toLocaleString(),S("Authors","desktop-mode"))),s.appendChild(a),s}async function px(e,t){const n=parseInt(e,10);if(!n)return Be(t);let o=null;try{o=await yo(bo(`desktop-mode/v1/comment-stats/${n}`))}catch{return Be(t)}const s=st(),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=`${lm(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 fx(e,t){const n=parseInt(e,10);if(!n)return Be(t);let o=null;try{o=await yo(bo(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return Be(t)}const s=st(),i=document.createElement("h2");i.className="desktop-mode-my-wordpress__article-title",i.textContent=zs(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="desktop-mode-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="desktop-mode-my-wordpress__article-hero";const d=o.media_details?.sizes;a.src=d?.large?.source_url??d?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),d=document.createElement("a");d.href=o.source_url,d.textContent=o.source_url,d.target="_blank",d.rel="noopener noreferrer",a.appendChild(d),s.appendChild(a)}return s}function mx(e){const t=st(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||S("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="desktop-mode-my-wordpress__article-meta",o.textContent=S("Double-click to open.","desktop-mode"),t.appendChild(o),t}function hx(e){const t=st(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||S("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="desktop-mode-my-wordpress__article-meta",o.textContent=S("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function wx(e){const t=st(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||S("Bookmark","desktop-mode"),t.appendChild(n);const o=typeof e.url=="string"?e.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",t.appendChild(s)}return t}function Be(e){const t=st(),n=document.createElement("h2");n.className="desktop-mode-my-wordpress__article-title",n.textContent=e.title||e.type,t.appendChild(n);const o=document.createElement("p");if(o.className="desktop-mode-my-wordpress__article-meta",o.textContent=ne(S("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="desktop-mode-my-wordpress__article-meta",s.textContent=S("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function st(e=""){const t=document.createElement("article");return t.className="desktop-mode-my-wordpress__article"+(e?" "+e:""),t}function rn(e,t){const n=document.createElement("div");n.className="desktop-mode-my-wordpress__user-stat";const o=document.createElement("span");o.className="desktop-mode-my-wordpress__user-stat-value",o.textContent=e,n.appendChild(o);const s=document.createElement("span");return s.className="desktop-mode-my-wordpress__user-stat-label",s.textContent=t,n.appendChild(s),n}function gx(){const e=document.createElement("div");e.className="desktop-mode-my-wordpress__preview-loading";const t=document.createElement("wpd-spinner");return e.appendChild(t),e}function yx(e){const t=document.createElement("div");return t.className="desktop-mode-my-wordpress__error",t.textContent=e instanceof Error?e.message:S("Unknown error.","desktop-mode"),t}function zs(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function lm(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function cm(){const e=document.createElement("div");return e.className="desktop-mode-my-wordpress__preview-empty",e.textContent=S("Select an item to preview it here.","desktop-mode"),e}const Gs="desktop-mode-embed-",bx=800,vx=600,ya=360,ba=240,js=16,va=new Map;function kx(e,t){const n=e.ref();if(!n)return;const o=window.wp?.desktop?.windowManager;if(!o)return;const s=t?.placement,i=s?.meta??null,r=s?`${Gs}${s.id}`:`${Gs}anon-${xx(n)}`,a=i?.name?.trim()??"",d=a!==""?a:e.title(),l={id:r,baseId:r,url:n,title:d,icon:e.icon(),minWidth:ya,minHeight:ba},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:h,y:m,width:w,height:g}=Sx(c,p,f);l.x=h,l.y=m,l.width=w,l.height=g}else l.width=Math.min(bx,Math.max(ya,p-js*2)),l.height=Math.min(vx,Math.max(ba,f-js*2));s&&c&&va.set(r,{...c}),o.open(l)}let um=!1;function _x(){if(um)return;um=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(Gs))return;const s=o.slice(Gs.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=va.get(o);c&&c.x===l.x&&c.y===l.y&&c.width===l.width&&c.height===l.height||(va.set(o,l),Ex(i,l))};G(y.WINDOW_DRAG_END,"desktop-mode-embed-persist",e),G(y.WINDOW_RESIZE_END,"desktop-mode-embed-persist",e)}async function Ex(e,t){try{const i={...(await Le(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await Qt(e,{meta:i})}catch(n){console.warn("[desktop-mode] embed window persist failed:",n)}}function Sx(e,t,n){const o=Math.max(ya,Math.min(e.width,t-js)),s=Math.max(ba,Math.min(e.height,n-js)),i=Math.max(0,Math.min(e.x,Math.max(0,t-o))),r=Math.max(0,Math.min(e.y,Math.max(0,n-s)));return{x:i,y:r,width:o,height:s}}function xx(e){let t=0;for(let n=0;n<e.length;n++)t=(Math.imul(t,31)+e.charCodeAt(n))%2147483647;return Math.abs(t).toString(36)}function ka(e){const t=document.createElement("a");t.href=e,t.setAttribute("download",""),t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}function vo(){const t=window.wp?.desktop?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function pm(e){const t=typeof e.shape.url=="string"?e.shape.url:"";if(!t)return"";try{const n=new URL(t,window.location.href);if(n.protocol!=="http:"&&n.protocol!=="https:")return""}catch{return""}return t}function Ix(){Ue({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${vo()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Ue({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${vo()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Ue({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${vo()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),Ue({id:"wp-term-editor",label:"Term editor",types:["term"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>{const[t,n]=e.ref().split(":");return`${vo()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Ue({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${vo()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),Ue({id:"desktop-mode-upload-download",label:"Download",types:["upload"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);t&&ka(aa(t))}}}),Ue({id:"desktop-mode-folder-window",label:"Open folder",types:["folder"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);if(!t)return;const n=window.wp?.desktop?.windowManager;if(!n)return;const o=`desktop-mode-folder-${t}`,s=J.getState().folders.get(t),i=Number(window.desktopModeConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),d=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:d,icon:e.icon(),native:!0,render:l=>{l.replaceChildren(),l.classList.add("desktop-mode-folder-window");const c=[{folderId:t,title:e.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 h=()=>{const w=c.map((g,k)=>k===c.length-1?{label:g.title}:{label:g.title,onClick:()=>{c.length=k+1,m()}});ox(p,w,{onBack:()=>{c.length<=1||(c.pop(),m())},backDisabled:c.length<=1})},m=()=>{u?.(),u=null,f.replaceChildren();const w=document.createElement("div");w.className="desktop-mode-folder-window__split",f.appendChild(w);const g=document.createElement("div");g.className="desktop-mode-folder-window__layer",w.appendChild(g);const k=document.createElement("div");k.className="desktop-mode-folder-window__preview",k.appendChild(cm()),w.appendChild(k);const D=c[c.length-1],b=Yf(g,D.folderId),E=b.onSelectionChange(N=>{if(!N){k.replaceChildren(cm());return}rx(N,k)}),I=N=>{if(!(N.target instanceof Element))return;const C=N.target.closest(".desktop-mode-file-tile");if(!C||C.dataset.fileType!=="folder")return;const L=parseInt(C.dataset.fileRef??"",10);if(!L)return;N.preventDefault(),N.stopPropagation();const A=C.querySelector(".desktop-mode-file-tile__label")?.textContent??`#${L}`;c.push({folderId:L,title:A}),m()};g.addEventListener("dblclick",I,!0);const O=YS(g,{scope:`desktop-mode-folder:${D.folderId}`,onSort:N=>b.sort(N),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{ha({onSubmit:async N=>{const C=await ra({name:N}),L=J.getState().placementsByFolder.get(D.folderId)??[],A=Bf(L),R=At(Oe,Oe,A,g),F=await Jt({type:"folder",ref:String(C.id),parentId:D.folderId,x:R.x,y:R.y});J.upsertFolder(C),J.upsertPlacement(F)}})}}]}),v=qS(f,D.folderId);u=()=>{E(),O.dispose(),v.dispose(),g.removeEventListener("dblclick",I,!0),b.dispose()},h()};m()},width:720,height:480,minWidth:360,minHeight:240})}}}),Ue({id:"desktop-mode-shortcut-opener",label:"Open shortcut",types:["shortcut"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=e.shape,n=window.wp?.desktop;if(n){if(t.shortcutWindow&&n.openWindow){n.openWindow(t.shortcutWindow);return}if(t.shortcutUrl&&n.windowManager)try{const o=new URL(t.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}const s=n.config?.adminUrl,i=s?oe(o.toString(),s):`desktop-icon-${e.ref()}`,r=Fu(o.toString());n.windowManager.open({id:i,baseId:i,url:o.toString(),parentUrl:r?.url??o.toString(),title:e.title(),icon:e.icon(),submenu:r?.submenu,multi:!!r?.multi})}catch{}}}}}),Ue({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=pm(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Ue({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=pm(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Ue({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{kx(e,t)}}})}const Cx="desktop-mode-file-associations";function Ax(){Ic({id:Cx,label:"File Associations",order:50,render(e){Lx(e)}})}function Lx(e){e.replaceChildren();const t=cf();if(t.length===0){const i=document.createElement("p");i.className="desktop-mode-file-associations__empty",i.textContent="No file types are registered.",e.appendChild(i);return}const n=document.createElement("p");n.className="desktop-mode-file-associations__intro",n.textContent="Pick which app opens each kind of file when you double-click it on the desktop.",e.appendChild(n);const o=Jr(),s=document.createElement("div");s.className="desktop-mode-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(Tx(i.type,i.label,o));e.appendChild(s)}function Tx(e,t,n){const o=document.createElement("div");o.className="desktop-mode-file-associations__row",o.setAttribute("role","listitem"),o.dataset.fileType=e;const s=document.createElement("label");s.className="desktop-mode-file-associations__label",s.textContent=t,o.appendChild(s);const i=Qr(e);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=ea(e),a=n[e]??r?.id??"",d=document.createElement("wpd-select");d.setAttribute("value",a),d.setAttribute("aria-label",`Default app for ${t}`),d.className="desktop-mode-file-associations__select",s.htmlFor=`assoc-${e}`,d.id=`assoc-${e}`;for(const 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={...Jr(),[e]:c};pf(u),bf(u).catch(p=>{console.error("[desktop-mode] saveAssociations failed:",p)})}),o.appendChild(d),o}let _a=null;function ze(){return _a||(_a=re("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),_a}function Nx(e,t){const n=ze();n.state.byFolder.set(e,t),n.notify()}function Dx(e){if(!e||typeof e.folderId!="number")return;const t=ze(),o=(t.state.byFolder.get(e.folderId)??[]).filter(s=>s.id!==e.id);o.push(e),t.state.byFolder.set(e.folderId,o),t.notify()}function Ox(e,t){const n=ze(),o=n.state.byFolder.get(e)??[];n.state.byFolder.set(e,o.filter(s=>s.id!==t)),n.notify()}function Rx(e,t){return e.id===t.id&&e.folderId===t.folderId&&e.capability===t.capability&&e.invitedAtMs===t.invitedAtMs&&e.folderName===t.folderName&&e.fileName===t.fileName&&e.ownerName===t.ownerName}function fm(e){const t=ze(),n=new Map(t.state.pending.map(s=>[s.id,s]));let o=!1;for(const s of e){const i=s.targetType==="file"&&typeof s.folderId!="number"?{...s,folderId:0}:s;if(i.targetType==="file"){if(typeof i.fileId=="number"&&t.state.deniedFiles.has(i.fileId))continue}else if(t.state.deniedFolders.has(i.folderId))continue;const r=n.get(i.id);if(r){if(Rx(r,i))continue;t.state.pending=t.state.pending.map(a=>a.id===i.id?i:a)}else t.state.pending.push(i);i.invitedAtMs>t.state.sharesVersion&&(t.state.sharesVersion=i.invitedAtMs),o=!0}o&&t.notify()}function qs(e,t={}){const n=ze();n.state.pending=n.state.pending.filter(o=>o.id!==e),t.denied&&typeof t.folderId=="number"&&n.state.deniedFolders.add(t.folderId),t.denied&&typeof t.fileId=="number"&&n.state.deniedFiles.add(t.fileId),n.notify()}const Mx=ge`:host{display:block;position:relative;font-size:13px}.input{width:100%;padding:8px 10px;background:var( --wpd-input-bg,rgba( 255,255,255,0.06 ) );color:inherit;border:1px solid rgba( 255,255,255,0.12 );border-radius:6px;font:inherit;box-sizing:border-box}.input:focus{outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:-1px}.dropdown{background:var( --desktop-mode-bg,#1d2327 );color:var( --desktop-mode-fg,#fff );border:1px solid rgba( 255,255,255,0.18 );border-radius:6px;overflow:auto;z-index:11000;box-shadow:0 12px 32px rgba( 0,0,0,0.5 )}.empty.error{color:#ff8080}.item{display:flex;align-items:center;gap:10px;padding:8px 10px;cursor:pointer;border:0;background:transparent;color:inherit;width:100%;text-align:start;font:inherit}.item:hover,.item:focus{background:rgba( 255,255,255,0.06 );outline:none}.avatar{width:24px;height:24px;border-radius:50%;flex:0 0 auto;background:rgba( 255,255,255,0.1 )}.name{font-weight:500}.slug{opacity:0.6;font-size:12px}.empty{padding:12px;color:rgba( 255,255,255,0.5 );font-size:12px}`,Uo=class Uo extends me{constructor(){super(...arguments),this._timer=null,this._abort=null,this._results=[],this._query="",this._open=!1,this._phase="idle",this._error="",this._dropdownStyle="",this._onScrollOrResize=()=>{},this._onInput=t=>{const n=t.target.value;this._query=n,this._scheduleSearch(n)},this._onFocus=()=>{if(this._results.length===0&&this._phase==="idle"){this._scheduleSearch(this._query);return}this._open=!0,this._positionDropdown(),this.requestUpdate()},this._onBlur=()=>{setTimeout(()=>{this._open=!1,this.requestUpdate()},150)},this._pick=t=>{this.emit("wpd-user-pick",{user:t}),this._results=[],this._open=!1,this._phase="idle",this._query="";const n=this.shadowRoot?.querySelector(".input");n&&(n.value=""),this.requestUpdate()}}connectedCallback(){super.connectedCallback(),this._onScrollOrResize=()=>{this._open&&(this._positionDropdown(),this.requestUpdate())},window.addEventListener("resize",this._onScrollOrResize),window.addEventListener("scroll",this._onScrollOrResize,!0)}disconnectedCallback(){this._timer&&clearTimeout(this._timer),this._abort&&this._abort.abort(),window.removeEventListener("resize",this._onScrollOrResize),window.removeEventListener("scroll",this._onScrollOrResize,!0)}_endpoint(){const t=this.getAttribute("endpoint");return t||window.desktopModeConfig?.filesUsersSearchUrl||""}_scheduleSearch(t){this._timer&&clearTimeout(this._timer),this._phase="loading",this._open=!0,this._positionDropdown(),this.requestUpdate(),this._timer=setTimeout(()=>this._runSearch(t),200)}async _runSearch(t){const n=this._endpoint();if(!n){this._phase="error",this._error="Search endpoint is not configured.",this._results=[],this._open=!0,this.requestUpdate();return}this._abort&&this._abort.abort();const o=new AbortController;this._abort=o;const s=this.getAttribute("exclude")||"",i=n+"?q="+encodeURIComponent(t)+"&exclude="+encodeURIComponent(s);try{const r={signal:o.signal,credentials:"same-origin"},a=await Pe(i,r,{source:"desktop-mode/files-user-search",silent:!0});if(!a.ok)throw new Error(`HTTP ${a.status}`);const d=await a.json();this._results=d&&Array.isArray(d.users)?d.users:[],this._phase="ready",this._error="",this._open=!0}catch(r){if(r.name==="AbortError")return;this._results=[],this._phase="error",this._error=r.message||"Search failed.",this._open=!0}this._positionDropdown(),this.requestUpdate()}_positionDropdown(){const t=this.shadowRoot?.querySelector(".input");if(!t)return;const n=t.getBoundingClientRect(),o=n.bottom+4,s=n.left,i=n.width,a=window.innerHeight-n.bottom,d=n.top,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 z`<div class="empty">Searching…</div>`;if(this._phase==="error")return z`<div class="empty error">${this._error}</div>`;if(this._results.length===0){const t=this._query?"No matches.":"No users available.";return z`<div class="empty">${t}</div>`}return this._results.map(t=>z` |
| 91 |
<button |
| 92 |
type="button" |
| 93 |
class="item" |
| 94 |
role="option" |
| 95 |
@mousedown=${n=>n.preventDefault()} |
| 96 |
@click=${()=>this._pick(t)} |
| 97 |
> |
| 98 |
<img class="avatar" src=${t.avatarUrl} alt="" /> |
| 99 |
<div> |
| 100 |
<div class="name">${t.name}</div> |
| 101 |
<div class="slug">${t.slug}</div> |
| 102 |
</div> |
| 103 |
</button> |
| 104 |
`)}render(){const t=this.getAttribute("placeholder")||"Search users…";return z` |
| 105 |
<input |
| 106 |
class="input" |
| 107 |
type="search" |
| 108 |
placeholder=${t} |
| 109 |
autocomplete="off" |
| 110 |
@input=${this._onInput} |
| 111 |
@focus=${this._onFocus} |
| 112 |
@blur=${this._onBlur} |
| 113 |
.value=${this._query} |
| 114 |
/> |
| 115 |
${this._open?z` |
| 116 |
<div class="dropdown" role="listbox" style=${this._dropdownStyle}> |
| 117 |
${this._dropdownContent()} |
| 118 |
</div> |
| 119 |
`:z``} |
| 120 |
`}};Uo.props=["placeholder","exclude","endpoint"],Uo.styles=[Mx],Uo.help=void 0;let Ea=Uo;we("wpd-user-search",Ea);const Px=ge`:host{display:flex;flex-wrap:wrap;gap:6px;font-size:13px}.chip{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;background:rgba( 255,255,255,0.06 );color:inherit;border:1px solid rgba( 255,255,255,0.12 );cursor:pointer;font:inherit}.chip:hover{background:rgba( 255,255,255,0.12 )}.chip[ aria-pressed='true' ]{background:var( --wp-admin-theme-color,#2271b1 );border-color:var( --wp-admin-theme-color,#2271b1 );color:#fff}.empty{color:rgba( 255,255,255,0.5 );font-size:12px}`,Fo=class Fo extends me{constructor(){super(...arguments),this._onToggle=t=>{const n=!this._selectedSet().has(t);this.emit("wpd-role-toggle",{slug:t,selected:n})}}_selectedSet(){const t=this.getAttribute("selected")||"";return new Set(t.split(",").map(n=>n.trim()).filter(n=>n!==""))}_roles(){const t=this.getAttribute("roles");if(t)try{const n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return window.desktopModeConfig?.shareEligibleRoles||[]}render(){const t=this._roles();if(t.length===0)return z`<span class="empty">No eligible roles.</span>`;const n=this._selectedSet();return z` |
| 121 |
${t.map(o=>{const s=n.has(o.slug);return z` |
| 122 |
<button |
| 123 |
type="button" |
| 124 |
class="chip" |
| 125 |
aria-pressed=${s?"true":"false"} |
| 126 |
@click=${()=>this._onToggle(o.slug)} |
| 127 |
>${o.name}</button> |
| 128 |
`})} |
| 129 |
`}};Fo.props=["selected","roles"],Fo.styles=[Px],Fo.help=void 0;let Sa=Fo;we("wpd-role-picker",Sa);const $x=ge`:host{display:inline-flex;padding:3px;background:var( --wpd-segmented-bg,rgba( 0,0,0,0.05 ) );border-radius:7px;gap:2px}`,Wx=ge`:host{flex:1 1 auto;min-width:0}button{appearance:none;display:block;width:100%;padding:8px 12px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --desktop-mode-muted,#646970 );cursor:pointer;border-radius:5px;transition:background-color 0.12s ease,color 0.12s ease;white-space:nowrap}:host( [ aria-checked='true' ] ) button{background:var( --desktop-mode-window-bg,#fff );color:var( --desktop-mode-text,#1d2327 );box-shadow:0 1px 3px rgba( 0,0,0,0.12 );font-weight:500}`,Ho=class Ho extends me{render(){return this.setAttribute("role","radio"),z` |
| 130 |
<button type="button" @click=${()=>this._onPick()}> |
| 131 |
<slot></slot> |
| 132 |
</button> |
| 133 |
`}_onPick(){this.emit("wpd-segment-pick",{value:this.value})}};Ho.props=["value"],Ho.styles=[Wx],Ho.help=void 0;let xa=Ho;we("wpd-segment",xa);const Bo=class Bo extends me{connectedCallback(){super.connectedCallback(),this.addEventListener("wpd-segment-pick",t=>{const n=t.detail;t.stopPropagation(),this.value=n.value,this.emit("wpd-pick",{value:n.value})})}set items(t){const n=this.querySelectorAll(":scope > wpd-segment");for(const i of Array.from(n))i.remove();for(const i of t){const r=document.createElement("wpd-segment");r.setAttribute("value",i.value),r.textContent=i.label,this.appendChild(r)}const o=this.value;!(o!==null&&t.some(i=>i.value===o))&&t.length>0?this.value=t[0].value:this.requestUpdate()}render(){const t=this.label||"";t&&this.setAttribute("aria-label",t),this.setAttribute("role","radiogroup");const n=this.value;return queueMicrotask(()=>{const o=this.querySelectorAll("wpd-segment");for(const s of Array.from(o)){const i=s.getAttribute("value");s.setAttribute("aria-checked",i===n?"true":"false")}}),z`<slot></slot>`}};Bo.props=["value","label"],Bo.styles=[$x],Bo.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <wpd-segment> children where exactly one is active.",status:"stable",since:"0.9.0",props:[{name:"value",type:"string",description:"Currently selected segment value. Mirrored onto child aria-checked."},{name:"label",type:"string",description:"aria-label for the radiogroup."}],slots:[{name:"(default)",description:'<wpd-segment value="…"> children.'}],events:[{name:"wpd-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--desktop-mode-window-bg",description:"Pill background."},{name:"--desktop-mode-text",description:"Active label colour."},{name:"--desktop-mode-muted",description:"Inactive label colour."}],example:z` |
| 134 |
<wpd-segmented value="md" label="Dock size"> |
| 135 |
<wpd-segment value="sm">Small</wpd-segment> |
| 136 |
<wpd-segment value="md">Medium</wpd-segment> |
| 137 |
<wpd-segment value="lg">Large</wpd-segment> |
| 138 |
</wpd-segmented> |
| 139 |
`};let Ia=Bo;we("wpd-segmented",Ia);const Ux=ge`:host{position:fixed;top:calc( var( --wp-admin--admin-bar--height,32px ) + 16px );inset-inline-end:16px;display:flex;flex-direction:column;gap:8px;z-index:calc( var( --desktop-mode-z-fullscreen,99999 ) + 10 );pointer-events:none}`,Fx=ge`:host{display:flex;align-items:center;gap:12px;min-width:280px;max-width:420px;padding:10px 14px;background:#1d2327;color:#fff;border-radius:10px;border:1px solid rgba( 255,255,255,0.12 );box-shadow:0 10px 30px rgba( 0,0,0,0.4 ),0 2px 6px rgba( 0,0,0,0.18 ),inset 0 0 0 1px rgba( 255,255,255,0.04 );font-size:13px;line-height:1.4;opacity:0;transform:translateY( -8px );transition:opacity 0.18s ease,transform 0.18s ease;pointer-events:auto}:host( [ state='in' ] ){opacity:1;transform:translateY( 0 )}:host( [ state='out' ] ){opacity:0;transform:translateY( -8px )}.wpd-toast__label{flex:1}button[ hidden ]{display:none}button{flex-shrink:0;padding:4px 10px;border:none;border-radius:4px;background:rgba( 255,255,255,0.12 );color:#fff;font:inherit;font-size:12px;font-weight:500;cursor:pointer;transition:background-color 0.12s ease}button:hover{background:rgba( 255,255,255,0.22 )}button:focus-visible{outline:2px solid rgba( 255,255,255,0.6 );outline-offset:2px}.wpd-toast__close{display:inline-flex;align-items:center;justify-content:center;padding:4px;border-radius:6px;background:transparent;color:rgba( 255,255,255,0.7 )}.wpd-toast__close:hover{background:rgba( 255,255,255,0.14 );color:#fff}@media ( prefers-reduced-motion:reduce ){:host{transition-duration:0.01ms}}`,ii=class ii extends me{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return z`<slot></slot>`}};ii.styles=[Ux],ii.help=void 0;let Ca=ii;we("wpd-toast-container",Ca);const zo=class zo extends me{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status")}render(){const t=this.action||"",n=this.hasAttribute("dismissible");return z` |
| 140 |
<span class="wpd-toast__label"><slot></slot></span> |
| 141 |
<button |
| 142 |
type="button" |
| 143 |
?hidden=${!t} |
| 144 |
@click=${o=>this._onAction(o)} |
| 145 |
> |
| 146 |
${t} |
| 147 |
</button> |
| 148 |
<button |
| 149 |
type="button" |
| 150 |
class="wpd-toast__close" |
| 151 |
aria-label=${S("Dismiss")} |
| 152 |
?hidden=${!n} |
| 153 |
@click=${o=>this._onDismiss(o)} |
| 154 |
> |
| 155 |
<svg viewBox="0 0 14 14" width="12" height="12" aria-hidden="true" focusable="false"> |
| 156 |
<path |
| 157 |
d="M3 3 L11 11 M11 3 L3 11" |
| 158 |
stroke="currentColor" |
| 159 |
stroke-width="1.7" |
| 160 |
stroke-linecap="round" |
| 161 |
fill="none" |
| 162 |
></path> |
| 163 |
</svg> |
| 164 |
</button> |
| 165 |
`}_onAction(t){t.preventDefault(),t.stopPropagation(),this.emit("wpd-toast-action",{})}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.emit("wpd-toast-dismiss",{})}};zo.props=["action","state","dismissible"],zo.styles=[Fx],zo.help={title:"Toast",summary:'Single transient notification. Message is slotted; fade-in / fade-out is CSS-driven by flipping the state attribute between "in" and "out". Usually created via the showToast() helper rather than authored by hand.',status:"stable",since:"0.9.0",props:[{name:"action",type:"string",description:"Optional action button label. When set, a button renders on the right and emits wpd-toast-action on click."},{name:"state",type:"'in' | 'out'",description:'Drives the CSS fade transition. Set to "in" when rendered, flip to "out" before removal.'},{name:"dismissible",type:"boolean",description:"When set, a close (×) button renders on the right and emits wpd-toast-dismiss on click. Use for persistent toasts the user must be able to close."}],slots:[{name:"(default)",description:"Message text."}],events:[{name:"wpd-toast-action",description:"Fires when the action button is clicked.",detail:"{}"},{name:"wpd-toast-dismiss",description:"Fires when the close (×) button is clicked.",detail:"{}"}],example:z` |
| 166 |
<wpd-toast state="in" action="Undo">Post moved to trash.</wpd-toast> |
| 167 |
`};let Aa=zo;we("wpd-toast",Aa);function mm(e,t){const n=document.createElement("wpd-segmented");n.setAttribute("value",e),n.setAttribute("label","Capability"),n.style.setProperty("--wpd-segmented-bg","rgba(255,255,255,0.06)"),n.style.setProperty("--desktop-mode-window-bg","var(--wp-admin-theme-color, #2271b1)"),n.style.setProperty("--desktop-mode-text","#fff"),n.style.setProperty("--desktop-mode-muted","rgba(255,255,255,0.65)");const o=document.createElement("wpd-segment");o.setAttribute("value","read"),o.textContent="Read",n.appendChild(o);const s=document.createElement("wpd-segment");return s.setAttribute("value","write"),s.textContent="Read + Write",n.appendChild(s),n.addEventListener("wpd-pick",i=>{const r=i.detail;t(r.value)}),n}function La(e,t,n={}){const o=document.createElement("wpd-button");o.setAttribute("variant","ghost"),o.setAttribute("aria-label",n.danger?"Remove":"Dismiss"),o.textContent=e;const s=n.danger?"#ff8080":"rgba(255,255,255,0.75)",i=n.danger?"1px solid rgba(255,128,128,0.45)":"1px solid rgba(255,255,255,0.18)";return o.style.setProperty("--wpd-button-fg",s),o.style.setProperty("--wpd-button-border",i),o.style.setProperty("--wpd-button-padding","6px 12px"),o.style.setProperty("--wpd-button-border-radius","7px"),o.style.setProperty("--wpd-button-min-height","34px"),o.style.minWidth="34px",o.style.fontSize="18px",o.style.lineHeight="1",o.addEventListener("click",t),o}async function Ta(e){const t=document.createElement("wpd-modal");t.setAttribute("open",""),t.setAttribute("size","lg"),t.setAttribute("title",`Share "${e.folderName}"`),document.body.appendChild(t);let n=[],o=[];const s=()=>{t.innerHTML="";const d=document.createElement("div");d.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",d.textContent=e.ownerName?`Owner: ${e.ownerName} — cannot be changed`:"Owner cannot be changed",t.appendChild(d);const 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 I=E.detail;o.push({kind:"user",ref:String(I.user.id),label:I.user.name,cap:"read"}),s()}),l.appendChild(u),t.appendChild(l);const f=document.createElement("div");f.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const h=document.createElement("div");h.textContent="Add roles",h.style.cssText="font-weight:600;",f.appendChild(h);const m=document.createElement("wpd-role-picker"),w=n.filter(E=>E.principalType==="role").map(E=>E.principalRef),g=o.filter(E=>E.kind==="role").map(E=>E.ref);if(m.setAttribute("selected",[...w,...g].join(",")),m.addEventListener("wpd-role-toggle",E=>{const I=E.detail,O=n.find(v=>v.principalType==="role"&&v.principalRef===I.slug);if(O){I.selected||r(O);return}if(I.selected){const v=(window.desktopModeConfig?.shareEligibleRoles??[]).find(N=>N.slug===I.slug);o.push({kind:"role",ref:I.slug,label:v?v.name:I.slug,cap:"read"})}else o=o.filter(v=>!(v.kind==="role"&&v.ref===I.slug));s()}),f.appendChild(m),t.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 I=document.createElement("div");I.textContent="New invites (not sent yet)",I.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",E.appendChild(I);for(const v of o){const N=document.createElement("div");N.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const C=document.createElement("span");C.textContent=v.kind==="role"?`Role: ${v.label}`:v.label,C.style.flex="1",N.appendChild(C);const L=mm(v.cap,R=>{v.cap=R});N.appendChild(L);const A=La("×",()=>{o=o.filter(R=>!(R.kind===v.kind&&R.ref===v.ref)),s()});N.appendChild(A),E.appendChild(N)}const O=document.createElement("wpd-button");O.setAttribute("variant","primary"),O.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,O.style.marginTop="8px",O.addEventListener("click",async()=>{if(o.length===0)return;O.setAttribute("busy",""),O.setAttribute("disabled","");const v=o.slice();let N=0,C=null;for(const L of v)try{await kf(e.folderId,{principalType:L.kind,principalRef:L.ref,capability:L.cap}),N++}catch(A){C=A;break}N>0&&(o=o.slice(N));try{await i()}catch{}q(C?{message:`Could not send invites: ${C.message}`}:{message:N===1?"Invite sent.":`${N} invites sent.`}),O.removeAttribute("busy"),O.removeAttribute("disabled"),s()}),E.appendChild(O),t.appendChild(E)}const k=document.createElement("div");if(k.textContent="Who has access",k.style.cssText="font-weight:600;margin:8px 0 6px;",t.appendChild(k),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;",t.appendChild(E)}else for(const E of n){const I=document.createElement("div");I.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const O=document.createElement("div");if(O.style.flex="1",O.textContent=E.principalType==="role"?`Role: ${E.displayName}`:E.displayName,E.state==="pending"){const L=document.createElement("span");L.textContent=" · pending",L.style.cssText="opacity:0.6;font-size:12px;",O.appendChild(L)}else if(E.state==="denied"){const L=document.createElement("span");L.textContent=" · denied",L.style.cssText="color:#d63638;font-size:12px;",O.appendChild(L)}I.appendChild(O);const v=E.capability==="write"?"write":"read",N=mm(v,L=>{a(E,L)});I.appendChild(N);const C=La("×",()=>{r(E)},{danger:!0});I.appendChild(C),t.appendChild(I)}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 b=document.createElement("wpd-button");b.setAttribute("variant","secondary"),b.textContent="Done",b.addEventListener("click",()=>t.remove()),D.appendChild(b),t.appendChild(D)},i=async()=>{try{n=(await vf(e.folderId)).shares,Nx(e.folderId,n)}catch(d){q({message:`Could not load shares: ${d.message}`})}s()},r=async d=>{try{await Ef(e.folderId,d.id),Ox(e.folderId,d.id),await i(),q({message:"Access revoked."})}catch(l){q({message:`Could not revoke: ${l.message}`})}},a=async(d,l)=>{try{const c=await _f(e.folderId,d.id,l);Dx(c),await i()}catch(c){q({message:`Could not update capability: ${c.message}`})}};t.addEventListener("wpd-modal-cancel",()=>t.remove()),s(),await i()}async function Hx(e){const t=document.createElement("wpd-modal");t.setAttribute("open",""),t.setAttribute("size","md"),t.setAttribute("title",`Share "${e.fileName}"`),document.body.appendChild(t);let n=[];const o=async()=>{try{n=(await Cf(e.fileId)).shares}catch(i){q({message:`Could not load shares: ${i.message}`})}s()},s=()=>{t.innerHTML="";const i=document.createElement("div");i.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",i.textContent="People you share with can view and download this file. Only you can move, rename, or delete it.",t.appendChild(i);const r=document.createElement("div");r.textContent="Add people",r.style.cssText="font-weight:600;margin-bottom:6px;",t.appendChild(r);const a=document.createElement("wpd-user-search");a.setAttribute("exclude",n.map(u=>u.principalRef).join(",")),a.setAttribute("placeholder","Search users…"),a.addEventListener("wpd-user-pick",u=>{const p=u.detail;(async()=>{try{await Af(e.fileId,p.user.id),q({message:`Invite sent to ${p.user.name}.`})}catch(f){q({message:`Could not invite: ${f.message}`})}await o()})()}),t.appendChild(a);const d=document.createElement("div");if(d.textContent="Who has access",d.style.cssText="font-weight:600;margin:14px 0 6px;",t.appendChild(d),n.length===0){const u=document.createElement("div");u.textContent="Only you can see this file.",u.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(u)}else for(const u of n){const p=document.createElement("div");p.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const f=document.createElement("div");f.style.flex="1";const h=u.displayName;if(f.textContent=h||`User #${u.principalRef}`,u.state==="pending"){const g=document.createElement("span");g.textContent=" · pending",g.style.cssText="opacity:0.6;font-size:12px;",f.appendChild(g)}else if(u.state==="denied"){const g=document.createElement("span");g.textContent=" · denied",g.style.cssText="color:#d63638;font-size:12px;",f.appendChild(g)}p.appendChild(f);const m=document.createElement("span");m.textContent="Read + download",m.style.cssText="opacity:0.6;font-size:12px;",p.appendChild(m);const w=La("×",()=>{(async()=>{try{await Lf(e.fileId,u.id),q({message:"Access revoked."})}catch(g){q({message:`Could not revoke: ${g.message}`})}await o()})()},{danger:!0});p.appendChild(w),t.appendChild(p)}const l=document.createElement("div");l.setAttribute("slot","footer"),l.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;";const c=document.createElement("wpd-button");c.setAttribute("variant","secondary"),c.textContent="Done",c.addEventListener("click",()=>t.remove()),l.appendChild(c),t.appendChild(l)};t.addEventListener("wpd-modal-cancel",()=>t.remove()),s(),await o()}function hm(e){return new Promise(t=>{const n=document.createElement("wpd-modal");n.setAttribute("open",""),n.setAttribute("title",e.fileName?`${e.ownerName??"Someone"} shared "${e.fileName}" with you`:"File shared with you");const o=document.createElement("div");o.innerHTML=` |
| 168 |
<p style="margin: 0 0 12px;">Accept the invite to add this file to your desktop.</p> |
| 169 |
<p style="margin: 0; opacity: 0.75;">Access level: <strong>Read + download</strong></p> |
| 170 |
`,n.appendChild(o);const s=document.createElement("div");s.setAttribute("slot","footer"),s.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;";const i=document.createElement("wpd-button");i.setAttribute("variant","secondary"),i.textContent="Decide later",i.addEventListener("click",()=>{n.remove(),t("dismissed")});const r=document.createElement("wpd-button");r.setAttribute("variant","danger"),r.textContent="Deny",r.addEventListener("click",async()=>{r.setAttribute("busy",""),r.setAttribute("disabled","");try{await Nf(e.fileId,e.id),ze().state.deniedFiles.add(e.fileId),ze().notify(),n.remove(),t("denied")}catch(d){q({message:`Could not deny: ${d.message}`}),r.removeAttribute("busy"),r.removeAttribute("disabled")}});const a=document.createElement("wpd-button");a.setAttribute("variant","primary"),a.textContent="Accept",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await Tf(e.fileId,e.id);try{const d=await Le(0);pt(0,d.placements)}catch{}n.remove(),t("accepted")}catch(d){q({message:`Could not accept: ${d.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}}),s.appendChild(i),s.appendChild(r),s.appendChild(a),n.appendChild(s),n.addEventListener("wpd-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}function wm(e){return new Promise(t=>{const n=document.createElement("wpd-modal");n.setAttribute("open",""),n.setAttribute("title",e.folderName?`${e.ownerName??"Someone"} shared "${e.folderName}" with you`:"Folder shared with you");const o=document.createElement("div"),s=e.capability==="write"?"Read + Write":"Read";o.innerHTML=` |
| 171 |
<p style="margin: 0 0 12px;">Accept the invite to add this folder to your desktop.</p> |
| 172 |
<p style="margin: 0; opacity: 0.75;">Access level: <strong>${s}</strong></p> |
| 173 |
`,n.appendChild(o);const i=document.createElement("div");i.setAttribute("slot","footer"),i.style.display="flex",i.style.justifyContent="flex-end",i.style.gap="10px",i.style.flexWrap="wrap";const r=document.createElement("wpd-button");r.setAttribute("variant","secondary"),r.textContent="Decide later",r.addEventListener("click",()=>{n.remove(),t("dismissed")});const a=document.createElement("wpd-button");a.setAttribute("variant","danger"),a.textContent="Deny",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await xf(e.folderId,e.id),ze().state.deniedFolders.add(e.folderId),ze().notify(),n.remove(),t("denied")}catch(l){q({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 Sf(e.folderId,e.id);try{const l=await Le(0);pt(0,l.placements)}catch{}n.remove(),t("accepted")}catch(l){q({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(),t("dismissed")}),document.body.appendChild(n)})}const Bx=Object.freeze(Object.defineProperty({__proto__:null,openFileShareModal:Hx,openPendingFileInviteModal:hm,openPendingInviteModal:wm,openShareSettingsModal:Ta},Symbol.toStringTag,{value:"Module"}));function gm(){return Number(window.desktopModeConfig?.currentUserId??0)}function ym(){const e=window.wp?.desktop?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function bm(e){const t=ft().folders.get(e);return t?Number(t.ownerId):0}function vm(e){if(typeof e!="string")return null;const t=/^desktop-mode-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function zx(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function Gx(e){return Number(e.file.ownerId??0)}function jx(){gn("desktop-mode.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!ym())return e;const n=zx(t);if(n===null)return e;const o=bm(n)||Gx(t),s=gm();if(o===s){const r=!!t.file.shareSummary?.shared?"Manage sharing…":"Share folder…";e.push({id:"desktop-mode/folder-share",label:r,icon:"dashicons-share",sort:30,onClick:()=>{Ta({folderId:n,folderName:t.file.title||`Folder ${n}`})}})}else o>0&&e.push({id:"desktop-mode/folder-leave",label:"Leave shared folder",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await Pi({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 If(n),ao(t.id);try{const d=await Le(0);pt(0,d.placements)}catch{}const r=`desktop-mode-folder-${n}`;window.desktopMode?.windowManager?.close?.(r),q({message:"You left the shared folder."})}catch(r){q({message:`Could not leave: ${r.message}`})}}});return e}),Xi({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!ym())return!1;const t=e.config.baseId??e.id,n=vm(t);return n===null?!1:bm(n)===gm()},onClick:e=>{const t=e.config.baseId??e.id,n=vm(t);n!==null&&Ta({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),G("desktop-mode.files.tile-rendered","desktop-mode/folder-share",e=>{const{tile:t,placement:n}=e;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||t.querySelector(".desktop-mode-file-tile__share-badge"))return;const s=document.createElement("span");s.className="desktop-mode-file-tile__share-badge dashicons dashicons-share",s.setAttribute("aria-label","Shared folder"),s.title="Shared folder",s.style.cssText=["position:absolute","top:6px","inset-inline-end:6px","background:rgba(0,0,0,0.55)","color:#fff","border-radius:50%","width:18px","height:18px","font-size:12px","line-height:18px","text-align:center","pointer-events:none"].join(";"),t.appendChild(s)})}const km=new Set;function qx(){const e=window.wp?.desktop?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function Vx(){const e=ze(),t=n=>{if(qx()){for(const o of n.pending)if(!km.has(o.id)){if(km.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;hm({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?qs(o.id):i==="denied"&&qs(o.id,{denied:!0,fileId:s})});continue}wm({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?qs(o.id):s==="denied"&&qs(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function Kx(){return Number(window.desktopModeConfig?.currentUserId??0)}function _m(){return window.desktopModeConfig?.desktopStorage??{}}function Xx(){const e=window.wp?.desktop?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function Yx(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function Zx(){gn("desktop-mode.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&_m().zipAvailable){const i=Number(t.file.ref);return Number.isFinite(i)&&i>0&&e.push({id:"desktop-mode/folder-zip-download",label:"Download as .zip",icon:"dashicons-download",sort:45,onClick:()=>{ka(Rf(i))}}),e}const n=Yx(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{ka(aa(n))}});const o=Number(t.file.ownerId??0),s=Kx();return o===s&&Xx()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{Promise.resolve().then(()=>Bx).then(i=>{i.openFileShareModal({fileId:n,fileName:t.file.title||`File ${n}`})})}}):o>0&&o!==s&&t.parentId===0&&e.push({id:"desktop-mode/upload-leave",label:"Leave shared file",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await Pi({title:"Leave this shared file?",message:"The file will be removed from your desktop. The owner keeps the original.",confirmLabel:"Leave",danger:!0}))try{await Df(n),ao(t.id);try{const r=await Le(0);pt(0,r.placements)}catch{}q({message:"You left the shared file."})}catch(r){q({message:`Could not leave: ${r.message}`})}}}),e}),gn("desktop-mode.wallpaper-context-menu","desktop-mode/uploads",e=>(_m().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>Em(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>Em(!0)})),e))}function Em(e){const t=document.createElement("input");t.type="file",e?t.setAttribute("webkitdirectory",""):t.multiple=!0,t.style.display="none",document.body.appendChild(t),t.addEventListener("change",()=>{const n=t.files?Array.from(t.files):[];t.remove(),n.length!==0&&Jx(n,e)}),t.click()}async function Jx(e,t){const n=window.desktopModeConfig,o=n?.dropConfig??{enabled:!1,allowedMimes:[],maxSize:0},s=await Promise.resolve().then(()=>zA),{accepted:i,rejected:r}=s.partitionByPolicy(e,o);if(r.length>0&&q({message:r.length===1?r[0].message:`${r.length} files can't be uploaded.`}),i.length===0)return;const a=i.map(({file:l,mime:c})=>({file:l,mime:c,fields:s.defaultFields(l,c),relativePath:t?l.webkitRelativePath??"":""}));await(await Promise.resolve().then(()=>Nh)).openUploadDialog({entries:a,context:{surface:"folder",folderId:0,x:0,y:0},mediaUrl:n?.mediaUrl??"",restNonce:n?.restNonce??"",filesUrl:n?.filesUrl,storage:n?.desktopStorage,forceDesktop:t,preferDesktop:!0,mediaMaxBytes:o.maxSize})}cS(),Ix(),_x(),Ax(),jx(),Zx();const Na=window.desktopModeConfig?.serverPendingShares;Array.isArray(Na)&&Na.length>0&&fm(Na),Vx();const Re={DesktopFile:lf,registerType:We,unregisterType:oS,getType:sS,getTypes:cf,resolve:so,subscribe:iS,registerOpener:Ue,unregisterOpener:rS,getOpener:aS,getOpeners:ff,getOpenersForType:Qr,resolveOpener:ea,subscribeOpeners:dS,getUserAssociations:Jr,open:na,rest:mS,store:{get:nt,getState:ft,subscribe:ca,setFolderPlacements:pt,upsertPlacement:Ps,removePlacement:ao,setFolders:Mf,upsertFolder:da,removeFolder:la}},Sm="__synthFromDockItem";function Qx(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function eI(e,t){const n=t[e.id];return{id:Qx(e.id),parentId:0,x:n?n.x:0,y:n?n.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Sm]:e.id},file:{type:"shortcut",ref:`dock-promoted:${e.id}`,title:e.title,icon:e.icon,previewUrl:"",exists:!0,shortcutUrl:e.url}}}function tI(){const e=window.wp?.desktop;return e?.getMenuItems?e.getMenuItems().map(o=>({id:o.id,title:o.title,icon:o.icon,url:o.url,badge:o.badge??0,submenu:o.submenu??[],isCore:o.isCore})):window.desktopModeConfig?.dockItems??[]}function nI(){return window.desktopModeConfig?.desktopIcons??[]}let Da=!1;const Oa=new Map;function oI(e){const t=window.wp?.desktop;if(!t?.getOsSettings||!t?.updateOsSettings)return;const o={...t.getOsSettings().dockPromotedPositions??{}};let s=!1;for(const i of e)i in o&&(delete o[i],s=!0);s&&t.updateOsSettings({dockPromotedPositions:o})}function Vs(e,t={},n){if(!Da){Da=!0;try{const o=tI(),s=nI(),i=new Map(o.map(f=>[f.id,f])),a=Re.store.getState().placementsByFolder.get(0)??[],d=new Map;for(const f of a){const h=(f.meta??null)&&typeof f.meta=="object"?f.meta[Sm]:null;typeof h=="string"&&d.set(h,f)}const l=new Map,c=new Set(s.map(f=>f.id));for(const f of a){const h=f?.file?.ref;typeof h=="string"&&c.has(h)&&l.set(h,f)}const u=new Set;for(const f of o){const h=kt(f.id,"dock",e),m=h==="desktop"||h==="both",w=n==="spatial"&&!!f.isCore&&(h==="dock"||h==="both");(m||w)&&(u.add(f.id),d.has(f.id)||Re.store.upsertPlacement(eI(f,t)))}const p=[];for(const[f,h]of d){if(u.has(f))continue;Re.store.removePlacement(h.id);const w=!!i.get(f)?.isCore&&e[f]===void 0;t[f]&&!w&&p.push(f)}p.length>0&&oI(p);for(const f of s){const h=e[f.id],m=l.get(f.id);if(h==="dock"||h==="hidden"){m&&(Oa.set(f.id,m),Re.store.removePlacement(m.id));continue}if(!m){const w=Oa.get(f.id);w&&(Re.store.upsertPlacement(w),Oa.delete(f.id))}}}finally{Da=!1}}}function sI(e,t=()=>({}),n=()=>{}){return queueMicrotask(()=>Vs(e(),t(),n())),Re.store.subscribe(()=>{Vs(e(),t(),n())})}const iI=ge`: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%}`,xm="desktop-mode-os-settings-save-lifecycle",rI=2200,aI=6e3,Go=class Go extends me{constructor(){super(...arguments),this._autoTimer=null,this._docListener=null}connectedCallback(){super.connectedCallback(),this.auto!==null&&this._installAutoListener()}disconnectedCallback(){this._removeAutoListener(),this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback(t,n,o),(t==="auto"||t==="event")&&(this._removeAutoListener(),this.auto!==null&&this._installAutoListener()),t==="phase"){this._scheduleAutoClear();const s={phase:this.phase??"idle",error:this.error??void 0};this.emit("wpd-save-status-change",s)}}render(){const t=this.phase??"idle",n=this.mode??"dot",s=(this.error??"")||this._labelForPhase(t);return s?this.setAttribute("title",s):this.removeAttribute("title"),this.setAttribute("aria-live",t==="failed"?"assertive":"polite"),this.setAttribute("role",t==="failed"?"alert":"status"),z` |
| 174 |
<span class="wpd-save-status"> |
| 175 |
<span class="wpd-save-status__indicator" aria-hidden="true"> |
| 176 |
<span class="wpd-save-status__glyph">${this._renderGlyph(t)}</span> |
| 177 |
</span> |
| 178 |
${n==="pill"?z`<span class="wpd-save-status__label" |
| 179 |
>${this._labelForPhase(t)}</span |
| 180 |
>`:z``} |
| 181 |
</span> |
| 182 |
`}_renderGlyph(t){return t==="saved"?dI():t==="failed"?lI():""}_labelForPhase(t){switch(t){case"pending":case"saving":return this["saving-label"]??"Saving…";case"saved":return this["saved-label"]??"Saved";case"failed":return(this.error??"")||"Couldn’t save";default:return this["idle-label"]??""}}_installAutoListener(){const t=this.event||xm;this._docListener=n=>{const o=n.detail;!o||typeof o.phase!="string"||(this.phase=o.phase,o.error?this.error=o.error:o.phase!=="failed"&&this.error&&this.removeAttribute("error"))},document.addEventListener(t,this._docListener)}_removeAutoListener(){if(!this._docListener)return;const t=this.event||xm;document.removeEventListener(t,this._docListener),this._docListener=null}_scheduleAutoClear(){this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null);const t=this.phase??"idle",n=this._autoClearMsFor(t);n<=0||(this._autoTimer=window.setTimeout(()=>{this._autoTimer=null,this.phase="idle"},n))}_autoClearMsFor(t){if(t==="saved"){const n=this["auto-clear-saved-ms"];return parseInt(n||"",10)||rI}if(t==="failed"){const n=this["auto-clear-failed-ms"];return parseInt(n||"",10)||aI}return 0}};Go.props=["phase","mode","animation","auto","event","error","saving-label","saved-label","idle-label","auto-clear-saved-ms","auto-clear-failed-ms"],Go.styles=[iI],Go.help=void 0;let Ra=Go;we("wpd-save-status",Ra);function dI(){return z` |
| 183 |
<svg |
| 184 |
viewBox="0 0 12 12" |
| 185 |
aria-hidden="true" |
| 186 |
focusable="false" |
| 187 |
fill="none" |
| 188 |
stroke="currentColor" |
| 189 |
stroke-width="2" |
| 190 |
stroke-linecap="round" |
| 191 |
stroke-linejoin="round" |
| 192 |
> |
| 193 |
<path d="M2.5 6 L5 8.5 L9.5 4" /> |
| 194 |
</svg> |
| 195 |
`}function lI(){return z` |
| 196 |
<svg |
| 197 |
viewBox="0 0 12 12" |
| 198 |
aria-hidden="true" |
| 199 |
focusable="false" |
| 200 |
fill="currentColor" |
| 201 |
> |
| 202 |
<path |
| 203 |
d="M5 2 H7 V7 H5 z M5 8.5 H7 V10.5 H5 z" |
| 204 |
/> |
| 205 |
</svg> |
| 206 |
`}const cI=ge`:host{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var( --desktop-mode-text,#1d2327 );min-width:0}:host( [ hidden ] ){display:none}.wpd-textarea__label{font-size:12px;color:var( --desktop-mode-muted,#646970 )}textarea{appearance:none;-webkit-appearance:none;display:block;width:100%;min-width:0;box-sizing:border-box;padding:8px 10px;background:var( --desktop-mode-window-bg,#fff );border:1px solid var( --desktop-mode-border,#dcdcde );border-radius:6px;font:inherit;font-size:13px;line-height:1.45;color:var( --desktop-mode-text,#1d2327 );resize:vertical;transition:border-color 0.12s ease,box-shadow 0.12s ease}textarea:hover{border-color:var( --desktop-mode-muted,#8c8f94 )}textarea:focus-visible{outline:none;border-color:var( --wp-admin-theme-color,#2271b1 );box-shadow:0 0 0 1px var( --wp-admin-theme-color,#2271b1 )}textarea:disabled{opacity:0.55;cursor:not-allowed;background:rgba( 0,0,0,0.03 )}textarea[ aria-invalid='true' ]{border-color:#d63638}textarea[ aria-invalid='true' ]:focus-visible{box-shadow:0 0 0 1px #d63638}:host( [ auto-grow ] ) textarea{resize:none;overflow:hidden}`,jo=class jo extends me{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),Vl(this)}render(){const t=this._attr("label")||"",n=this._attr("value")??"",o=this._attr("placeholder")||"",s=this._boolAttr("disabled"),i=this._boolAttr("readonly"),r=this._attr("aria-label")||t,a=this._attr("name")||"",d=Number(this._attr("rows"))||3,l=this._attr("maxlength"),c=this._attr("minlength"),u=this._boolAttr("invalid"),f=`${this.id||"wpd-unnamed"}__field`;return z` |
| 207 |
${t?z`<label class="wpd-textarea__label" for=${f}>${t}</label>`:z``} |
| 208 |
<textarea |
| 209 |
id=${f} |
| 210 |
part="textarea" |
| 211 |
.value=${n} |
| 212 |
placeholder=${o} |
| 213 |
?disabled=${s} |
| 214 |
?readonly=${i} |
| 215 |
rows=${d} |
| 216 |
maxlength=${l??""} |
| 217 |
minlength=${c??""} |
| 218 |
name=${a} |
| 219 |
aria-invalid=${u?"true":"false"} |
| 220 |
aria-label=${r||""} |
| 221 |
@input=${h=>this._onInput(h)} |
| 222 |
@change=${h=>this._onChange(h)} |
| 223 |
@keydown=${h=>this._onKeyDown(h)} |
| 224 |
></textarea> |
| 225 |
`}_attr(t){return this.getAttribute(t)}_boolAttr(t){return this.getAttribute(t)!==null}_onInput(t){const n=t.target;this._textareaEl=n,this.setAttribute("value",n.value),this.emit("wpd-input-change",{value:n.value}),this._boolAttr("auto-grow")&&this._autosize(n)}_onChange(t){const n=t.target;this.emit("wpd-input-commit",{value:n.value})}_onKeyDown(t){if(this._boolAttr("submit-on-enter")&&t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey&&!t.ctrlKey){t.preventDefault();const n=t.target;this.emit("wpd-submit",{value:n.value})}}_autosize(t){const n=Number(this._attr("max-rows"))||8,o=window.getComputedStyle(t),s=parseFloat(o.fontSize)||13,i=o.lineHeight,r=i==="normal"?s*1.45:parseFloat(i)||s*1.45,a=parseFloat(o.paddingTop)||0,d=parseFloat(o.paddingBottom)||0,l=r*n+a+d;t.style.height="auto";const c=Math.min(t.scrollHeight,l);t.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))}};jo.props=["label","value","placeholder","disabled","readonly","ariaLabel","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],jo.styles=[cI],jo.help=void 0;let Ma=jo;we("wpd-textarea",Ma);const uI=ge`: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}`,pI={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"/>'},qo=class qo extends me{constructor(){super(...arguments),this._activateWired=!1}render(){const t=this.icon||"",n=pI[t]||"";return z` |
| 226 |
<button type="button"> |
| 227 |
<svg |
| 228 |
width="14" |
| 229 |
height="14" |
| 230 |
viewBox="0 0 12 12" |
| 231 |
aria-hidden="true" |
| 232 |
focusable="false" |
| 233 |
></svg> |
| 234 |
<slot></slot> |
| 235 |
</button> |
| 236 |
<span data-svg-buffer style="display:none">${n}</span> |
| 237 |
`}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paintSvg()),queueMicrotask(()=>this._wireActivateEvent())}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),queueMicrotask(()=>this._paintSvg())}_paintSvg(){const t=this.shadowRoot;if(!t)return;const n=t.querySelector("svg"),o=t.querySelector("[data-svg-buffer]");if(n&&o){const s=o.textContent||"";n.innerHTML!==s&&(n.innerHTML=s)}}_wireActivateEvent(){if(this._activateWired)return;const t=this.shadowRoot;if(!t)return;const n=t.querySelector("button");n&&(this._activateWired=!0,n.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("wpd-button-activate",{bubbles:!0,composed:!0,cancelable:!0}))}))}};qo.props=["icon","active","danger"],qo.styles=[uI],qo.help=void 0;let Pa=qo;we("wpd-window-button",Pa);const ht="Sticky Note",fI="<!-- wpworkspace-sticky:",$a="-->",mI=64,hI=48,wI=180;function Wa(e){const t=gI(e.title),n=_I(yI(e.content,{stripHtmlForRendered:!0})),o=EI(e);return{localId:`guideline:${e.id}`,guidelineId:e.id,title:t,body:vI(t,n),modified:e.modified,...o>0?{modifiedMs:o}:{},link:e.link,termIds:Array.isArray(e.wp_guideline_type)?e.wp_guideline_type.filter(SI):[]}}function gI(e){const t=[];typeof e=="string"?t.push(e):e&&typeof e=="object"&&(typeof e.raw=="string"&&t.push(e.raw),typeof e.rendered=="string"&&t.push(Ua(e.rendered)));for(const n of t){const o=Ua(n).trim();if(o)return o}return ht}function yI(e,t={}){return typeof e=="string"?e:!e||typeof e!="object"?"":typeof e.raw=="string"&&e.raw.length>0?e.raw:typeof e.rendered=="string"?t.stripHtmlForRendered?Ua(e.rendered):e.rendered:""}function Im(e){const t=e.split(/\r?\n/).find(o=>o.trim().length>0)?.trim(),n=t&&t.length>0?t:ht;return Fa(n,mI)}function bI(e){const n=e.replace(/\s+/g," ").trim()||ht;return Fa(n,hI)}function vI(e,t){const n=e.trim();return!n||t.split(/\r?\n/)[0]?.trim()===n?t:t?`${n} |
| 238 |
${t}`:n}function kI(e,t=ht){const n=t.trim()||ht,o=Im(e),s=e.search(/\r?\n/);if(s===-1){const r=o===ht?n:o;return{title:r,content:"",excerpt:Cm(r)}}let i=e.slice(s);return i=i.replace(/^\r?\n/,""),i.startsWith(` |
| 239 |
`)&&(i=i.slice(1)),{title:o,content:i,excerpt:Cm(i.trim()?i:o)}}function Cm(e){const t=e.replace(/[\n\t]+/g," ").trim();return Fa(t,wI)}function _I(e){if(!e.startsWith(fI)||!e.includes($a))return e;const t=e.indexOf($a);let n=e.slice(t+$a.length);return n.startsWith(`\r |
| 240 |
`)?n=n.slice(2):n.startsWith(` |
| 241 |
`)&&(n=n.slice(1)),n}function Ua(e){if(typeof document<"u"){const t=document.createElement("template");return t.innerHTML=e,(t.content.textContent??"").trim()}return e.replace(/<[^>]*>/g,"").trim()}function Fa(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function EI(e){if(typeof e.desktop_mode_modified_ms=="number"&&Number.isFinite(e.desktop_mode_modified_ms))return e.desktop_mode_modified_ms;if(!e.modified)return 0;const t=Date.parse(e.modified);return Number.isFinite(t)?t:0}function SI(e){return typeof e=="number"&&Number.isFinite(e)}class Am extends Error{constructor(t,n){super(t),this.name="StickyNotesRestError",this.status=n}}async function xI(e){const t=await II(e),n=CI([...t.artifactTerms,...t.artifactsTerms],t.noteTerms,t.stickyTerms);if(n)return n;const o=await Ha(e,{slug:"artifact",name:"Artifact",parent:0}),s=await Ha(e,{slug:"note",name:"Note",parent:o.id}),i=await Ha(e,{slug:"sticky",name:"Sticky",parent:o.id});return{stickyTermId:i.id,termIds:Nm([o.id,s.id,i.id])}}async function II(e){const[t,n,o,s]=await Promise.all([an(e,"artifact"),an(e,"artifacts"),an(e,"note"),an(e,"sticky")]);return{artifactTerms:t,artifactsTerms:n,noteTerms:o,stickyTerms:s}}function CI(e,t,n){if(n.length===0)return null;const o=e.find(r=>["artifact","artifacts"].includes(r.slug))??e[0]??null,s=o?n.find(r=>Number(r.parent)===o.id)??n[0]:n[0];if(!s)return null;const i=o?t.find(r=>Number(r.parent)===o.id)??null:null;return{stickyTermId:s.id,termIds:Nm([o?.id,i?.id,s.id])}}async function Lm(e,t){return(await Ks(e,Tm("wp/v2/guidelines",{context:"edit",status:"private",per_page:"100",orderby:"modified",order:"desc",wp_guideline_type:String(t)}),void 0,!0)).filter(o=>Array.isArray(o.wp_guideline_type)?o.wp_guideline_type.includes(t):!0).map(Wa)}async function AI(e,t,n){const o=kI(t.body,t.title),s={status:"private",title:o.title,content:o.content,excerpt:o.excerpt};t.guidelineId===null&&(s.wp_guideline_type=n.termIds);const i=t.guidelineId===null?"wp/v2/guidelines":`wp/v2/guidelines/${t.guidelineId}`,r=await Ks(e,i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},!1);return Wa(r)}function LI(e,t){const n=new URL("post.php",e);return n.searchParams.set("post",String(t)),n.searchParams.set("action","edit"),n.toString()}async function an(e,t){try{return await Ks(e,Tm("wp/v2/wp_guideline_type",{context:"edit",slug:t,per_page:"100"}),void 0,!0)}catch(n){if(n instanceof Am&&(n.status===404||n.status===400))return[];throw n}}async function Ha(e,t){const n=await an(e,t.slug),o=n.find(s=>Number(s.parent??0)===t.parent);if(o)return o;if(n[0])return n[0];try{return await Ks(e,"wp/v2/wp_guideline_type",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},!0)}catch(s){const i=await an(e,t.slug);if(i[0])return i[0];throw s}}async function Ks(e,t,n,o=!0){const s=await Pe(Ze(TI(e),t),n,{source:"desktop-mode/sticky-notes",silent:o});if(!s.ok)throw new Am(s.statusText||`${ht} request failed`,s.status);return await s.json()}function TI(e){return e.restUrl?e.restUrl:`${window.location.origin}/wp-json/`}function Tm(e,t){const n=new URLSearchParams;return Object.entries(t).forEach(([o,s])=>{n.set(o,s)}),`${e}?${n.toString()}`}function Nm(e){const t=[];return e.forEach(n=>{typeof n=="number"&&Number.isFinite(n)&&!t.includes(n)&&t.push(n)}),t}const NI="desktop_mode_sticky_notes_subscribe",DI="desktop_mode_sticky_notes";let Dm=!1,Ba=null;function OI(e){Ba=e,!Dm&&(Dm=!0,ye.contribute(NI,()=>Ba?.getHeartbeatSubscription()),ye.subscribe(DI,t=>{Ba?.applyHeartbeatPayload(t)}))}const Om="desktop-mode-sticky-notes-geometry",RI=264,MI=176,za=180,Ga=128,pe=16,PI=1e3;class $I{constructor(t){this.root=null,this.terms=null,this.controllers=new Map,this.contextMenuInstalled=!1,this.desktopHooksInstalled=!1,this.highWaterMs=0,this.zIndexCounter=0,this.host=t.host,this.config=t.config,this.available=t.available??!0,this.openArtifact=t.openArtifact,this.getActiveDesktopId=t.getActiveDesktopId??(()=>"desktop-1"),this.onError=t.onError}async boot(){if(this.available)try{if(this.terms=await xI(this.config),!this.terms)return;this.installContextMenu(),this.installDesktopHooks();const t=await Lm(this.config,this.terms.stickyTermId);if(this.bumpHighWaterFromNotes(t),OI(this),t.length===0)return;this.ensureRoot(),Rm(t).forEach((n,o)=>this.upsert(n,o))}catch(t){t instanceof Error&&console.debug("[desktop-mode] Sticky notes unavailable:",t.message)}}createNote(t=""){if(!this.terms)return;const n={localId:`local:${Date.now()}:${Math.random().toString(36).slice(2)}`,guidelineId:null,title:t.trim()?bI(t):ht,body:t,termIds:this.terms.termIds};this.upsert(n,this.controllers.size,{activate:!0}).focus()}upsert(t,n,o={}){this.ensureRoot();const s=Me(t),i=this.controllers.get(s);if(i)return i.replace(t),o.activate&&this.bringToFront(i),i;const r=new WI({layer:this,note:t,index:n});return this.controllers.set(s,r),this.root?.appendChild(r.element),this.assignZIndex(r),this.applyDesktopVisibility(r),o.activate&&this.bringToFront(r),r}ensureRoot(){if(this.root)return this.root;const t=document.createElement("section");return t.className="desktop-mode-sticky-notes",t.setAttribute("aria-label",S("Sticky notes")),this.host.appendChild(t),this.root=t,t}installContextMenu(){this.contextMenuInstalled||(this.contextMenuInstalled=!0,gn("desktop-mode.wallpaper-context-menu","desktop-mode/sticky-notes",t=>!Array.isArray(t)||!this.terms||t.some(n=>n.id==="new-sticky-note")?t:[...t,{id:"new-sticky-note",label:S("New sticky note"),icon:"dashicons-edit-page",sort:14,onClick:()=>this.createNote()}]))}installDesktopHooks(){this.desktopHooksInstalled||(this.desktopHooksInstalled=!0,G(y.DESKTOP_SWITCHED,"desktop-mode/sticky-notes",()=>this.refreshDesktopVisibility()),G(y.DESKTOP_CLOSED,"desktop-mode/sticky-notes",t=>{this.migrateDesktopAssignments(t?.desktopId,t?.migratedTo),this.refreshDesktopVisibility()}))}save(t){return this.terms?AI(this.config,t,this.terms):Promise.reject(new Error(S("Sticky term is unavailable.")))}getHeartbeatSubscription(){if(this.terms)return{stickyTermId:this.terms.stickyTermId,knownIds:this.knownGuidelineIds(),version:this.highWaterMs}}applyHeartbeatPayload(t){for(const n of t.notes??[]){const o=Wa(n);this.upsertRemote(o)}for(const n of t.removed??[])this.forgetGuidelineId(n);typeof t.serverTimeMs=="number"&&Number.isFinite(t.serverTimeMs)&&t.serverTimeMs>this.highWaterMs&&(this.highWaterMs=t.serverTimeMs),t.truncated&&this.reloadFromServer()}openNoteArtifact(t){t.guidelineId!==null&&this.openArtifact(LI(this.config.adminUrl,t.guidelineId),t.title,t.guidelineId)}notifyError(t){this.onError?.(t)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}defaultGeometry(t){const{width:n,height:o}=this.hostSize(),s=Math.min(RI,Math.max(za,n-pe*2)),i=Math.min(MI,Math.max(Ga,o-pe*2)),r=t%8*28,a=Xe(n-s-32-r,pe,Math.max(pe,n-s-pe)),d=Xe(32+r,pe,Math.max(pe,o-i-pe));return{x:a/n,y:d/o,width:s,height:i}}forget(t){this.controllers.delete(Me(t.note)),t.dispose(),t.element.remove(),this.controllers.size===0&&(this.root?.remove(),this.root=null)}replaceControllerKey(t,n){const o=Me(n.note);this.controllers.delete(t),this.controllers.set(o,n),FI(t,o),this.applyDesktopVisibility(n)}bumpHighWaterFromNote(t){const n=ko(t);n>this.highWaterMs&&(this.highWaterMs=n)}bringToFront(t){t.setZIndex(this.nextZIndex())}geometryForNote(t,n){const o=Me(t),s=ja(o),i=this.normalizeDesktopId(s?.desktopId),r=s?{...s,desktopId:i}:{...this.defaultGeometry(n),desktopId:i};return(!s||s.desktopId!==r.desktopId)&&qa(o,r),r}upsertRemote(t){const n=Me(t),o=this.controllers.get(n);if(o)return o.shouldReplaceFromRemote(t)?(o.replace(t),this.bumpHighWaterFromNote(t),o):(this.bumpHighWaterFromNote(t),o);const s=this.upsert(t,this.controllers.size);return this.bumpHighWaterFromNote(t),s}forgetGuidelineId(t){for(const n of this.controllers.values())if(n.note.guidelineId===t){this.forget(n);return}}knownGuidelineIds(){const t=[];for(const n of this.controllers.values())n.note.guidelineId!==null&&t.push(n.note.guidelineId);return t}bumpHighWaterFromNotes(t){t.forEach(n=>this.bumpHighWaterFromNote(n))}assignZIndex(t){t.setZIndex(this.nextZIndex())}nextZIndex(){return this.zIndexCounter+=1,this.zIndexCounter}applyDesktopVisibility(t){t.setVisible(this.isNoteOnActiveDesktop(t.note))}refreshDesktopVisibility(){for(const t of this.controllers.values())this.applyDesktopVisibility(t)}isNoteOnActiveDesktop(t){const n=Me(t),o=ja(n),s=this.normalizeDesktopId(o?.desktopId);return o&&o.desktopId!==s&&qa(n,{...o,desktopId:s}),s===this.activeDesktopId()}migrateDesktopAssignments(t,n){if(!t||!n||t===n)return;const o=Xs();let s=!1;Object.entries(o).forEach(([i,r])=>{r.desktopId===t&&(o[i]={...r,desktopId:this.normalizeDesktopId(n)},s=!0)}),s&&Va(o)}activeDesktopId(){try{const t=this.getActiveDesktopId();return typeof t=="string"&&t?t:"desktop-1"}catch{return"desktop-1"}}normalizeDesktopId(t){return t||this.activeDesktopId()}async reloadFromServer(){if(this.terms)try{const t=await Lm(this.config,this.terms.stickyTermId),n=new Set;Rm(t).forEach(o=>{o.guidelineId!==null&&n.add(o.guidelineId),this.upsertRemote(o)}),this.knownGuidelineIds().forEach(o=>{n.has(o)||this.forgetGuidelineId(o)})}catch{}}}class WI{constructor(t){this.saveTimer=null,this.geometryTimer=null,this.saving=!1,this.saveAgain=!1,this.resizeObserver=null,this.disposed=!1,this.layer=t.layer,this.note=t.note,this.index=t.index,this.element=document.createElement("article"),this.element.className="desktop-mode-sticky-note",this.element.dataset.stickyNoteId=Me(this.note),this.titleEl=document.createElement("span"),this.editor=document.createElement("wpd-textarea"),this.statusEl=document.createElement("wpd-save-status"),this.openButton=document.createElement("wpd-window-button"),this.paint(),this.applyGeometry(this.layer.geometryForNote(this.note,this.index)),this.element.addEventListener("pointerdown",()=>this.layer.bringToFront(this),{capture:!0}),this.element.addEventListener("focusin",()=>this.layer.bringToFront(this)),this.watchResize()}focus(){window.setTimeout(()=>this.editor.focusInput?.(),0)}replace(t){this.note=t,this.element.dataset.stickyNoteId=Me(this.note),this.titleEl.textContent=this.note.title,this.editor.setAttribute("value",this.note.body),this.refreshOpenButton()}shouldReplaceFromRemote(t){if(this.hasLocalChanges())return!1;const n=ko(this.note),o=ko(t);return!(n>0&&o>0&&o<=n&&this.note.title===t.title&&this.note.body===t.body)}setZIndex(t){this.element.style.zIndex=String(t)}setVisible(t){this.element.style.display=t?"":"none"}dispose(){this.disposed=!0,this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.geometryTimer!==null&&(window.clearTimeout(this.geometryTimer),this.geometryTimer=null),this.resizeObserver?.disconnect(),this.resizeObserver=null}paint(){this.element.innerHTML="",this.element.style.minWidth=`${za}px`,this.element.style.minHeight=`${Ga}px`;const t=document.createElement("div");t.className="desktop-mode-sticky-note__header";const n=document.createElement("span");n.className="desktop-mode-sticky-note__grip",n.setAttribute("aria-hidden","true"),this.titleEl.className="desktop-mode-sticky-note__title",this.titleEl.textContent=this.note.title,this.statusEl.setAttribute("mode","icon"),this.statusEl.setAttribute("phase","idle"),this.statusEl.className="desktop-mode-sticky-note__status",this.openButton.setAttribute("icon","detach"),this.openButton.setAttribute("title",S("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",S("Hide sticky note")),o.className="desktop-mode-sticky-note__close",o.addEventListener("wpd-button-activate",()=>this.close()),t.append(n,this.titleEl,this.statusEl,this.openButton,o),t.addEventListener("pointerdown",s=>this.startDrag(s)),this.editor.className="desktop-mode-sticky-note__editor",this.editor.setAttribute("aria-label",S("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=Im(i.value),this.titleEl.textContent=this.note.title,this.setPhase("pending"),this.scheduleSave()}),this.editor.addEventListener("wpd-input-commit",()=>this.flushSave()),this.element.append(t,this.editor),this.refreshOpenButton()}installEditorKeyboardGuard(){["keydown","keypress","keyup"].forEach(t=>{this.editor.addEventListener(t,n=>{n.stopPropagation()})})}refreshOpenButton(){const t=this.note.guidelineId===null;this.openButton.classList.toggle("is-disabled",t),this.openButton.setAttribute("aria-disabled",t?"true":"false")}close(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.layer.forget(this);return}this.flushSave(),this.layer.forget(this)}scheduleSave(){if(this.note.guidelineId===null&&this.note.body.trim().length===0){this.setPhase("idle");return}this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},PI)}flushSave(){this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),(this.note.guidelineId!==null||this.note.body.trim().length>0)&&this.save()}async save(){if(this.saving){this.saveAgain=!0,this.setPhase("pending");return}this.saving=!0,this.setPhase("saving");const t=this.note.body;try{const n=await this.layer.save({...this.note,body:t});if(this.disposed)return;const o=Me(this.note);this.note.guidelineId=n.guidelineId,this.note.modified=n.modified,this.note.link=n.link,this.note.termIds=n.termIds.length>0?n.termIds:this.note.termIds,this.note.body===t&&(this.note.title=n.title,this.titleEl.textContent=n.title),o!==Me(this.note)&&(this.element.dataset.stickyNoteId=Me(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:S("Could not save sticky note.");this.setPhase("failed",o),this.layer.notifyError(o)}finally{this.saving=!1,!this.disposed&&this.saveAgain&&(this.saveAgain=!1,this.scheduleSave())}}setPhase(t,n){this.statusEl.setAttribute("phase",t),n?(this.statusEl.setAttribute("error",n),this.statusEl.setAttribute("title",n)):(this.statusEl.removeAttribute("error"),this.statusEl.removeAttribute("title"))}hasLocalChanges(){const t=this.statusEl.getAttribute("phase");return this.saveTimer!==null||this.saving||this.saveAgain||t==="pending"||t==="failed"}startDrag(t){if(t.button!==0||t.target?.closest("wpd-window-button, wpd-save-status"))return;t.preventDefault();const o=this.element.getBoundingClientRect(),s=this.layerHostRect(),i=o.left-s.left,r=o.top-s.top,a=t.clientX,d=t.clientY;this.element.classList.add("desktop-mode-sticky-note--dragging"),this.element.setPointerCapture?.(t.pointerId);const l=u=>{const p=this.element.offsetWidth,f=this.element.offsetHeight,{width:h,height:m}=this.layer.hostSize(),w=Xe(i+u.clientX-a,pe,Math.max(pe,h-p-pe)),g=Xe(r+u.clientY-d,pe,Math.max(pe,m-f-pe));this.element.style.left=`${w}px`,this.element.style.top=`${g}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(t){const{width:n,height:o}=this.layer.hostSize(),s=Xe(t.width,za,n-pe*2),i=Xe(t.height,Ga,o-pe*2),r=Xe(t.x*n,pe,Math.max(pe,n-s-pe)),a=Xe(t.y*o,pe,Math.max(pe,o-i-pe));this.element.style.left=`${r}px`,this.element.style.top=`${a}px`,this.element.style.width=`${s}px`,this.element.style.height=`${i}px`}watchResize(){typeof ResizeObserver>"u"||(this.resizeObserver=new ResizeObserver(()=>{this.geometryTimer!==null&&window.clearTimeout(this.geometryTimer),this.geometryTimer=window.setTimeout(()=>{this.geometryTimer=null,this.persistGeometry()},150)}),this.resizeObserver.observe(this.element))}persistGeometry(){const{width:t,height:n}=this.layer.hostSize(),o=parseFloat(this.element.style.left)||0,s=parseFloat(this.element.style.top)||0,i=ja(Me(this.note));qa(Me(this.note),{...i??{},x:Xe(o/t,0,1),y:Xe(s/n,0,1),width:this.element.offsetWidth,height:this.element.offsetHeight})}layerHostRect(){return(this.element.parentElement?.parentElement??document.body).getBoundingClientRect()}}function UI(e){const t=new $I(e);return t.boot(),t}function Me(e){return e.guidelineId===null?e.localId:`guideline:${e.guidelineId}`}function ko(e){if(typeof e.modifiedMs=="number"&&Number.isFinite(e.modifiedMs))return e.modifiedMs;if(!e.modified)return 0;const t=Date.parse(e.modified);return Number.isFinite(t)?t:0}function Rm(e){return[...e].sort((t,n)=>ko(t)-ko(n))}function ja(e){const n=Xs()[e];return!n||!Number.isFinite(n.x)||!Number.isFinite(n.y)||!Number.isFinite(n.width)||!Number.isFinite(n.height)?null:n}function qa(e,t){const n=Xs();n[e]=t,Va(n)}function FI(e,t){if(e===t)return;const n=Xs();n[e]&&(n[t]=n[e],delete n[e],Va(n))}function Xs(){try{const e=window.localStorage.getItem(Om);return e?JSON.parse(e):{}}catch{return{}}}function Va(e){try{window.localStorage.setItem(Om,JSON.stringify(e))}catch{}}function Xe(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}const HI=ge`:host{display:inline-flex;position:relative;width:var( --wpd-avatar-size,32px );height:var( --wpd-avatar-size,32px );flex:0 0 auto;vertical-align:middle;line-height:0;perspective:calc( var( --wpd-avatar-size,32px ) * 8 );--wpd-avatar-tilt-x:0deg;--wpd-avatar-tilt-y:0deg;--wpd-avatar-hover:0;--wpd-avatar-glare-x:50%;--wpd-avatar-glare-y:50%}:host( [ hidden ] ){display:none}.wpd-avatar__tile{position:relative;width:100%;height:100%;border-radius:50%;overflow:hidden;background:var( --desktop-mode-window-bg,#f0f0f1 );color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:calc( var( --wpd-avatar-size,32px ) * 0.48 );line-height:1;letter-spacing:0;font-feature-settings:'tnum' 1;user-select:none;transform-style:preserve-3d;transform:rotateX( var( --wpd-avatar-tilt-x ) ) rotateY( var( --wpd-avatar-tilt-y ) ) scale( calc( 1 + var( --wpd-avatar-hover ) * 0.07 ) );transition:transform 220ms cubic-bezier( 0.2,0.8,0.2,1 ),box-shadow 220ms cubic-bezier( 0.2,0.8,0.2,1 );box-shadow:inset 0 0 0 1px rgba( 255,255,255,calc( 0.18 + 0.22 * var( --wpd-avatar-hover ) ) ),inset 0 0 0 calc( 1px + var( --wpd-avatar-hover ) * 1px ) rgba( 0,0,0,calc( 0.08 + 0.04 * var( --wpd-avatar-hover ) ) ),0 calc( 1px + var( --wpd-avatar-hover ) * 8px ) calc( 6px + var( --wpd-avatar-hover ) * 18px ) rgba( 0,0,0,calc( 0.08 + 0.18 * var( --wpd-avatar-hover ) ) )}.wpd-avatar__tile::after{content:'';position:absolute;inset:0;border-radius:50%;background:radial-gradient( circle at var( --wpd-avatar-glare-x ) var( --wpd-avatar-glare-y ),rgba( 255,255,255,0.55 ) 0%,rgba( 255,255,255,0 ) 55% );opacity:var( --wpd-avatar-hover );mix-blend-mode:overlay;pointer-events:none;transition:opacity 220ms cubic-bezier( 0.2,0.8,0.2,1 )}.wpd-avatar__tile::before{content:'';position:absolute;inset:calc( var( --wpd-avatar-hover ) * -3px );border-radius:50%;background:radial-gradient( circle at var( --wpd-avatar-glare-x ) var( --wpd-avatar-glare-y ),rgba( 99,102,241,calc( 0.35 * var( --wpd-avatar-hover ) ) ) 0%,rgba( 99,102,241,0 ) 70% );filter:blur( 4px );pointer-events:none;z-index:-1;transition:inset 220ms cubic-bezier( 0.2,0.8,0.2,1 ),background 220ms}.wpd-avatar__tile img{width:100%;height:100%;object-fit:cover;display:block;transform:translateZ( 1px )}.wpd-avatar__dot{position:absolute;bottom:0;inset-inline-end:0;width:calc( var( --wpd-avatar-size,32px ) * 0.32 );height:calc( var( --wpd-avatar-size,32px ) * 0.32 );min-width:8px;min-height:8px;border-radius:50%;box-sizing:border-box;border:2px solid var( --wpd-avatar-dot-ring,var( --desktop-mode-window-bg,#fff ) );background:var( --wpd-avatar-dot-color,transparent );z-index:2}.wpd-avatar__dot--online{background:var( --desktop-mode-success,#00a32a )}.wpd-avatar__dot--inactive{background:var( --desktop-mode-warning,#dba617 )}.wpd-avatar__dot--offline{background:var( --desktop-mode-muted,#8c8f94 )}@media ( prefers-reduced-motion:reduce ){.wpd-avatar__tile{transform:none;transition:box-shadow 200ms}.wpd-avatar__tile::after,.wpd-avatar__tile::before{display:none}}`,Mm={xs:20,sm:24,md:40,lg:64,xl:96},Pm=new Set(["online","inactive","offline"]),Vo=class Vo extends me{constructor(){super(...arguments),this._presenceHandler=null,this._imgFailed=!1,this._onPointerMove=null,this._onPointerEnter=null,this._onPointerLeave=null,this._tiltRaf=0,this._pendingTiltX="0deg",this._pendingTiltY="0deg",this._pendingGlareX="50%",this._pendingGlareY="50%"}connectedCallback(){super.connectedCallback(),this._maybeAttachPresenceListener(),this._attachHoverEffect()}disconnectedCallback(){this._presenceHandler&&(document.removeEventListener("desktop-mode-presence-changed",this._presenceHandler),this._presenceHandler=null),this._detachHoverEffect()}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),t==="src"&&(this._imgFailed=!1),(t==="user-id"||t==="presence")&&this._maybeAttachPresenceListener()}render(){const t=this._attr("src"),n=this._attr("name")||"",o=this._attr("alt"),s=o!==null?o:n,i=this._attr("size"),r=this._resolveSize(i),a=this._presenceForRender(),d=this._attr("clickable")!==null;this.style.setProperty("--wpd-avatar-size",`${r}px`);const l=t&&!this._imgFailed?"":this._initialsBg(n),c=t&&!this._imgFailed?z`<img |
| 242 |
src=${t} |
| 243 |
alt=${s} |
| 244 |
@error=${()=>this._onImgError()} |
| 245 |
loading="lazy" |
| 246 |
/>`:this._initials(n),u=a?z`<span |
| 247 |
class=${`wpd-avatar__dot wpd-avatar__dot--${a}`} |
| 248 |
aria-label=${this._presenceLabel(a)} |
| 249 |
></span>`:z``;return d?z` |
| 250 |
<button |
| 251 |
type="button" |
| 252 |
class="wpd-avatar__tile" |
| 253 |
aria-label=${s||"User"} |
| 254 |
style=${l?`background:${l};`:""} |
| 255 |
@click=${p=>this._onClick(p)} |
| 256 |
>${c}</button> |
| 257 |
${u} |
| 258 |
`:z` |
| 259 |
<div |
| 260 |
class="wpd-avatar__tile" |
| 261 |
role="img" |
| 262 |
aria-label=${s||"User"} |
| 263 |
style=${l?`background:${l};`:""} |
| 264 |
>${c}</div> |
| 265 |
${u} |
| 266 |
`}_attr(t){return this.getAttribute(t)}_resolveSize(t){if(!t)return 32;if(t in Mm)return Mm[t];const n=Number(t);return Number.isFinite(n)&&n>0?n:32}_initials(t){const n=t.trim();return n?Array.from(n)[0]?.toUpperCase()??"?":"?"}_initialsBg(t){const n=os(t);return`linear-gradient(135deg, hsl(${n} 62% 55%), hsl(${(n+24)%360} 58% 42%))`}_presenceForRender(){const t=this._attr("presence");return t&&Pm.has(t)?t:null}_presenceLabel(t){switch(t){case"online":return"Online";case"inactive":return"Inactive";case"offline":return"Offline"}}_onImgError(){this._imgFailed=!0,this.requestUpdate()}_onClick(t){const n=this._attr("user-id"),o={userId:n!==null&&Number(n)||null,originalEvent:t};this.emit("wpd-avatar-click",o)}_attachHoverEffect(){typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(this._onPointerEnter=()=>{this.style.setProperty("--wpd-avatar-hover","1")},this._onPointerLeave=()=>{this.style.setProperty("--wpd-avatar-hover","0"),this._pendingTiltX="0deg",this._pendingTiltY="0deg",this._pendingGlareX="50%",this._pendingGlareY="50%",this._flushTilt()},this._onPointerMove=n=>{const o=this.getBoundingClientRect();if(o.width===0||o.height===0)return;const s=(n.clientX-o.left)/o.width-.5,i=(n.clientY-o.top)/o.height-.5,r=14;this._pendingTiltY=`${(s*r).toFixed(2)}deg`,this._pendingTiltX=`${(-i*r).toFixed(2)}deg`;const a=Math.max(0,Math.min(100,(s+.5)*100)),d=Math.max(0,Math.min(100,(i+.5)*100));this._pendingGlareX=`${a.toFixed(1)}%`,this._pendingGlareY=`${d.toFixed(1)}%`,this._tiltRaf||(this._tiltRaf=requestAnimationFrame(()=>this._flushTilt()))},this.addEventListener("pointerenter",this._onPointerEnter),this.addEventListener("pointerleave",this._onPointerLeave),this.addEventListener("pointermove",this._onPointerMove))}_flushTilt(){this._tiltRaf=0,this.style.setProperty("--wpd-avatar-tilt-x",this._pendingTiltX),this.style.setProperty("--wpd-avatar-tilt-y",this._pendingTiltY),this.style.setProperty("--wpd-avatar-glare-x",this._pendingGlareX),this.style.setProperty("--wpd-avatar-glare-y",this._pendingGlareY)}_detachHoverEffect(){this._onPointerMove&&(this.removeEventListener("pointermove",this._onPointerMove),this._onPointerMove=null),this._onPointerEnter&&(this.removeEventListener("pointerenter",this._onPointerEnter),this._onPointerEnter=null),this._onPointerLeave&&(this.removeEventListener("pointerleave",this._onPointerLeave),this._onPointerLeave=null),this._tiltRaf&&(cancelAnimationFrame(this._tiltRaf),this._tiltRaf=0)}_maybeAttachPresenceListener(){const t=this._attr("user-id"),n=this._attr("presence"),o=!!t&&!n;o&&!this._presenceHandler?(this._presenceHandler=s=>{const i=s.detail;i&&String(i.userId)===String(t)&&i.newStatus&&Pm.has(i.newStatus)&&this.setAttribute("presence",i.newStatus)},document.addEventListener("desktop-mode-presence-changed",this._presenceHandler)):!o&&this._presenceHandler&&(document.removeEventListener("desktop-mode-presence-changed",this._presenceHandler),this._presenceHandler=null)}};Vo.props=["src","alt","name","size","presence","userId","clickable"],Vo.styles=[HI],Vo.help=void 0;let Ka=Vo;we("wpd-avatar",Ka);const dn=["butter","blush","sky","mint","lilac","peach"];function BI(e){return dn.includes(e)?e:dn[0]}function Xa(e){return e.toLowerCase().replace(/[^a-z0-9_-]/g,"")||dn[0]}function $m(e){const t=dn.indexOf(BI(e));return dn[(t+1)%dn.length]}const Wm="cubic-bezier(0.2, 0.7, 0.2, 1)",Um="cubic-bezier(0.5, 0, 0.9, 0.4)",zI="cubic-bezier(0.2, 0.7, 0.3, 1.15)";function ln(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ye(e,t,n){return typeof e.animate!="function"?Promise.resolve():e.animate(t,n).finished.then(()=>{}).catch(()=>{})}async function GI(e){const t=e.restRotation??0;if(ln()){Fm(e.rippleHost,400);return}const n=e.tempo??1,o=e.fallDistance??30;await Ye(e.pin,[{opacity:0,transform:`translate(8px, ${-o}px) rotate(${t-16}deg) scale(1.9)`},{opacity:1,offset:.35},{opacity:1,transform:`translate(0, 0) rotate(${t}deg) scale(0.92)`}],{duration:170*n,easing:Um,fill:"forwards"}),Fm(e.rippleHost,420*n);const s=Ye(e.paper,[{transform:"scale(1) translateY(0) skewX(0)"},{transform:"scale(0.982) translateY(2px) skewX(0)",offset:.08},{transform:"scale(1.01) translateY(0) skewX(0.6deg)",offset:.32},{transform:"scale(0.996) translateY(0) skewX(-0.4deg)",offset:.55},{transform:"scale(1) translateY(0) skewX(0)"}],{duration:370*n,easing:"linear"}),i=Ye(e.pin,[{transform:`rotate(${t}deg) scale(0.92)`},{transform:`rotate(${t+1.5}deg) scale(1.07)`,offset:.25},{transform:`rotate(${t-1}deg) scale(0.98)`,offset:.5},{transform:`rotate(${t}deg) scale(1)`}],{duration:370*n,easing:Wm,fill:"forwards"});await Promise.all([s,i])}function Fm(e,t){const n=document.createElement("span");n.className="desktop-mode-pinned-note__ripple",n.setAttribute("aria-hidden","true"),e.appendChild(n),Ye(n,[{boxShadow:"0 0 0 0 rgba(0, 0, 0, 0.28)",opacity:.35},{boxShadow:"0 0 0 26px rgba(0, 0, 0, 0)",opacity:0}],{duration:t,easing:"ease-out"}).then(()=>n.remove()),window.setTimeout(()=>n.remove(),t+100)}function jI(e){if(ln())return{onPointerMove:()=>{},setBias:()=>{},stop:()=>{}};const t=14;let n=0,o=0,s=0,i=0,r=null,a=0,d=0,l=0,c=0,u=!0;const p=f=>{if(!u)return;const h=Math.min(.05,c?(f-c)/1e3:.016);c=f,f-a>80&&(d*=.85),s=Math.max(-14,Math.min(14,-d*.055))+i,o+=(-120*(n-s)-t*o)*h,n+=o*h,e.style.transform=`rotate(${n.toFixed(2)}deg)`,l=window.requestAnimationFrame(p)};return l=window.requestAnimationFrame(p),{onPointerMove(f){const h=performance.now();if(r!==null&&h>a){const m=(f-r)/(h-a)*16.7;d=d*.7+m*.3}r=f,a=h},setBias(f){i=f},stop(){u=!1,window.cancelAnimationFrame(l),e.style.transform=""}}}async function qI(e){if(ln()){await Ye(e.flyback,[{opacity:1},{opacity:0}],{duration:120,easing:"linear",fill:"forwards"});return}const t=e.swing?Ye(e.swing,[{transform:"rotate(0deg)"},{transform:"rotate(9deg)",offset:.35},{transform:"rotate(-4deg)",offset:.7},{transform:"rotate(0deg)"}],{duration:330,easing:"linear",fill:"forwards"}):Promise.resolve(),n=Ye(e.flyback,[{left:`${e.flyback.offsetLeft}px`,top:`${e.flyback.offsetTop}px`},{left:`${e.homeX}px`,top:`${e.homeY}px`}],{duration:330,easing:zI,fill:"forwards"});await Promise.all([n,t])}async function VI(e){if(ln()){await Ye(e.clone,[{opacity:1},{opacity:0}],{duration:150,easing:"linear",fill:"forwards"});return}e.pin&&Ye(e.pin,[{transform:"translate(0, 0) rotate(0deg)",opacity:1},{transform:"translate(2px, -16px) rotate(-30deg)",opacity:0}],{duration:200,easing:Wm,fill:"forwards"});const t=e.clone.getBoundingClientRect(),n=e.binX-(t.left+t.width/2),o=e.binY-(t.top+t.height/2),s="polygon(4% 8%, 38% 2%, 68% 7%, 96% 3%, 98% 42%, 92% 71%, 97% 94%, 60% 98%, 30% 93%, 3% 97%, 6% 62%, 2% 34%)",i="polygon(10% 14%, 42% 6%, 64% 12%, 90% 8%, 94% 38%, 86% 66%, 92% 88%, 58% 94%, 34% 86%, 10% 92%, 14% 58%, 8% 36%)";await Ye(e.paper,[{transform:"translate(0, 0) scale(0.88) rotate(0deg)",borderRadius:"2px",opacity:1},{transform:`translate(${n*.3}px, ${o*.3}px) scale(0.6) rotate(12deg)`,clipPath:s,offset:.3},{transform:`translate(${n*.6}px, ${o*.6}px) scale(0.34) rotate(24deg)`,clipPath:i,offset:.6,opacity:1},{transform:`translate(${n}px, ${o}px) scale(0.12) rotate(38deg)`,borderRadius:"50%",clipPath:i,opacity:0}],{duration:400,easing:Um,delay:60,fill:"forwards"})}function KI(e){let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t>>>1||1}function Hm(e){let t=2166136261;const n=`wpd-note-${e}`;for(let i=0;i<n.length;i++)t^=n.charCodeAt(i),t=Math.imul(t,16777619)>>>0;const o=t>>>3,s=t>>>5;return{rotation:(t%45-22)/10,pinOffsetX:o%21-10,pinRotation:s%17-8}}const XI=.57,YI=.525,ZI=56,JI=52;function QI(e){return`${e.replace(/\/$/,"")}/assets/images/pushpin.svg`}function eC(e){const t=document.createElement("img");return t.src=QI(e),t.alt="",t.width=ZI,t.height=JI,t.draggable=!1,t.className="desktop-mode-pinned-note__pin-img",t}let Ya=null;function tC(e){Ya=e}function nC(){if(!Ya)throw new Error("[desktop-mode] notes REST client called before installNotesRestDeps().");return Ya}function oC(e){const t=window.desktopModeConfig;return typeof t?.restNonce=="string"&&t.restNonce?t.restNonce:e}class Bm extends Error{constructor(t){super("Note was changed by another session."),this.status=409,this.name="NotesConflictError",this.current=t}}function sC(e){return e instanceof Bm}async function cn(e,t){const{baseUrl:n,nonce:o}=nC(),s=e?Ze(n,e):n,i=new Headers(t.headers??{});i.set("X-WP-Nonce",oC(o)),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Pe(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/notes"}),a=await r.text();let d=null;if(a)try{d=JSON.parse(a)}catch{d=null}if(!r.ok){if(r.status===409){const c=d?.data?.current;throw new Bm(c??null)}const l=d;throw new Error(`[desktop-mode] notes REST ${r.status}: ${l?.code??""} ${l?.message??""}`.trim())}if(d===null)throw new Error(`[desktop-mode] notes REST ${r.status}: empty or unparseable body.`);return d}function zm(){return cn("",{method:"GET"})}function iC(e){return cn("",{method:"POST",body:JSON.stringify(e)})}function rC(e,t){return cn(`/${e}`,{method:"PATCH",body:JSON.stringify(t)})}function aC(e){return cn(`/${e}`,{method:"DELETE"})}function Gm(e){return cn(`/${e}/restore`,{method:"POST"})}function dC(e){return cn(`/${e}/convert`,{method:"POST"})}const lC="desktop_mode_notes_subscribe",cC="desktop_mode_notes";let jm=!1,Za=null;function uC(e){Za=e,!jm&&(jm=!0,ye.contribute(lC,()=>Za?.getHeartbeatSubscription()),ye.subscribe(cC,t=>{Za?.applyHeartbeatPayload(t)}))}function qm(){const e=window.wp?.desktop;return e&&typeof e.showToast=="function"?e:null}async function pC(e,t){t.onEvict(e.id);try{await aC(e.id),qm()?.showToast?.({message:S("Note moved to Trash","desktop-mode"),duration:6e3,action:{label:S("Undo","desktop-mode"),onClick:()=>{Gm(e.id).then(n=>t.onRestore(n)).catch(n=>{console.error("[desktop-mode] notes: restore failed:",n)})}}})}catch(n){console.error("[desktop-mode] notes: trash failed:",n),t.onRestore(e),qm()?.showToast?.({message:S("Could not move the note to the Trash.","desktop-mode"),duration:5e3})}}function Ys(){return window.wp?.desktop??null}function fC(e){const t=Ys();if(!t?.windowManager?.open||!t.deriveWindowId)return window.location.href=e,null;const n=t.deriveWindowId(e);return t.windowManager.open({id:n,baseId:n,url:e,title:S("Edit draft","desktop-mode"),icon:"dashicons-admin-post"}),n}async function mC(e,t){t.onEvict(e.id);try{const n=await dC(e.id),o=fC(n.editUrl);Ys()?.showToast?.({message:S("Note converted to a draft post","desktop-mode"),duration:6e3,action:{label:S("Undo","desktop-mode"),onClick:()=>{o&&Ys()?.windowManager?.getById?.(o)?.close?.(),Gm(e.id).then(s=>t.onRestore(s)).catch(s=>{console.error("[desktop-mode] notes: convert undo failed:",s)})}}})}catch(n){console.error("[desktop-mode] notes: convert failed:",n),t.onRestore(e),Ys()?.showToast?.({message:S("Could not convert the note to a post.","desktop-mode"),duration:5e3})}}const hC="note-draft",un="note",wC="desktop-mode-note-created",gC=208,yC=1e3,bC=800,vC=10,kC=1;function _C(){return window.wp?.desktop?.dragManager??null}function Zs(e){return e.seed||Math.abs(e.id)||1}const EC='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="currentColor" aria-hidden="true" focusable="false"><path d="m7.3 9.7 1.4 1.4c.2-.2.3-.3.4-.5 0 0 0-.1.1-.1.3-.5.4-1.1.3-1.6L12 7 9 4 7.2 6.5c-.6-.1-1.1 0-1.6.3 0 0-.1 0-.1.1-.3.1-.4.2-.6.4l1.4 1.4L4 11v1h1l2.3-2.3zM4 20h9v-1.5H4V20zm0-5.5V16h16v-1.5H4z" /></svg>';class SC{constructor(t){this.root=null,this.liveRegion=null,this.controllers=new Map,this.zCounter=1,this.highWaterMs=0,this.tempIdCounter=0,this.host=t.host,this.pluginUrl=t.pluginUrl,this.canCreatePosts=t.canCreatePosts??!1,this.onError=t.onError}async boot(){try{const{notes:t}=await zm();t.forEach(n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"none"})}),uC(this)}catch(t){t instanceof Error&&console.debug("[desktop-mode] Pinned notes unavailable:",t.message)}}upsertNote(t,n={animate:"none"}){this.ensureRoot(),this.zCounter=Math.max(this.zCounter,t.z);const o=this.controllers.get(t.id);if(o)return o.replace(t),o;const s=new xC({layer:this,note:t});return this.controllers.set(t.id,s),this.root?.appendChild(s.element),n.animate!=="none"&&s.playInsertion(n.animate==="thunk"?1:.7),s}removeNote(t){const n=this.controllers.get(t);n&&(this.controllers.delete(t),n.dispose(),n.element.remove())}rekeyNote(t,n){this.controllers.delete(t),this.controllers.set(n.note.id,n)}has(t){return this.controllers.has(t)}get(t){return this.controllers.get(t)}nextTempId(){return this.tempIdCounter-=1,this.tempIdCounter}bringToFront(t){this.zCounter+=1,t.setZ(this.zCounter)}bumpHighWater(t){Number.isFinite(t)&&t>this.highWaterMs&&(this.highWaterMs=t)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}clampPosition(t,n){const{width:o,height:s}=this.hostSize(),i=Math.max(0,1-gC/o),r=Math.max(0,1-120/s);return{x:Math.min(i,Math.max(0,t)),y:Math.min(r,Math.max(0,n))}}announce(t){this.ensureRoot(),this.liveRegion&&(this.liveRegion.textContent=t)}notifyError(t){this.onError?.(t)}trashNote(t){pC(t,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}convertNote(t){!this.canCreatePosts||!t.canEdit||mC(t,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}getHeartbeatSubscription(){return{knownIds:Array.from(this.controllers.keys()).filter(t=>t>0),sinceMs:this.highWaterMs}}applyHeartbeatPayload(t){for(const n of t.notes??[]){this.bumpHighWater(n.updatedAtMs);const o=this.controllers.get(n.id);o?o.shouldReplaceFromRemote(n)&&o.replace(n):this.upsertNote(n,{animate:"move"})}for(const n of t.removed??[])this.removeNote(n);typeof t.serverTimeMs=="number"&&Number.isFinite(t.serverTimeMs)&&this.bumpHighWater(t.serverTimeMs),t.truncated&&this.reloadFromServer()}async reloadFromServer(){try{const{notes:t}=await zm(),n=new Set;for(const o of t){n.add(o.id),this.bumpHighWater(o.updatedAtMs);const s=this.controllers.get(o.id);s?s.shouldReplaceFromRemote(o)&&s.replace(o):this.upsertNote(o,{animate:"move"})}for(const o of Array.from(this.controllers.keys()))o>0&&!n.has(o)&&this.removeNote(o)}catch{}}ensureRoot(){if(this.root)return this.root;const t=document.createElement("section");t.className="desktop-mode-notes",t.setAttribute("aria-label",S("Pinned notes","desktop-mode"));const n=document.createElement("div");return n.className="desktop-mode-notes__live screen-reader-text",n.setAttribute("aria-live","polite"),t.appendChild(n),this.host.appendChild(t),this.root=t,this.liveRegion=n,t}}class xC{constructor(t){this.editor=null,this.statusEl=null,this.colorDot=null,this.visibilityBtn=null,this.saveTimer=null,this.zTimer=null,this.patchChain=Promise.resolve(),this.pendingText=null,this.disposed=!1,this.moveMode=!1,this.moveOrigin=null,this.dragCleanup=null,this.lastPointer=null,this.layer=t.layer,this.note=t.note,this.jitter=Hm(Zs(t.note)),this.element=document.createElement("article"),this.paperEl=document.createElement("div"),this.pinEl=document.createElement(this.note.canEdit?"button":"span"),this.paint(),this.applyPosition(),this.setZ(this.note.z),this.element.addEventListener("pointerdown",()=>this.layer.bringToFront(this),{capture:!0})}paint(){const t=this.note;this.element.className="desktop-mode-pinned-note",this.element.dataset.noteId=String(t.id),this.element.dataset.noteColor=Xa(t.color),this.element.dataset.owner=t.canEdit?"me":"other",this.element.setAttribute("role",t.canEdit?"group":"note"),this.element.setAttribute("aria-label",t.canEdit?S("Pinned note","desktop-mode"):ne(S("Note by %s","desktop-mode"),t.ownerName)),this.element.style.setProperty("--dm-note-rot",`${this.jitter.rotation}deg`),this.element.style.setProperty("--dm-pin-dx",`${this.jitter.pinOffsetX}px`),this.element.style.setProperty("--dm-pin-rot",`${this.jitter.pinRotation}deg`),this.pinEl.className="desktop-mode-pinned-note__pin",this.pinEl.appendChild(eC(this.layer.pluginUrl)),t.canEdit?(this.pinEl.setAttribute("type","button"),this.pinEl.setAttribute("aria-pressed","false"),this.pinEl.setAttribute("aria-label",S("Move note. Drag the pin, or press Enter then use the arrow keys.","desktop-mode")),this.pinEl.addEventListener("pointerdown",n=>this.startDrag(n)),this.pinEl.addEventListener("click",n=>{n.detail===0&&!this.moveMode&&this.toggleMoveMode()}),this.pinEl.addEventListener("keydown",n=>this.onPinKeydown(n)),this.pinEl.addEventListener("blur",()=>this.exitMoveMode(!1))):this.pinEl.setAttribute("aria-hidden","true"),this.paperEl.className="desktop-mode-pinned-note__paper",t.canEdit?this.paintOwnerPaper():this.paintViewerPaper(),this.element.append(this.pinEl,this.paperEl)}paintOwnerPaper(){const t=document.createElement("div");t.className="desktop-mode-pinned-note__meta";const n=document.createElement("button");n.type="button",n.className="desktop-mode-pinned-note__color-dot",this.colorDot=n,this.refreshColorDot(),n.addEventListener("click",()=>this.cycleColor());const o=document.createElement("wpd-window-button");if(o.className="desktop-mode-pinned-note__visibility",this.visibilityBtn=o,this.refreshVisibility(),o.addEventListener("wpd-button-activate",()=>this.togglePublic()),t.append(n,o),this.layer.canCreatePosts){const a=document.createElement("wpd-window-button");a.className="desktop-mode-pinned-note__convert",a.innerHTML=EC;const d=S("Convert to a draft post","desktop-mode");a.setAttribute("title",d),a.setAttribute("aria-label",d),a.addEventListener("wpd-button-activate",()=>this.layer.convertNote(this.note)),t.append(a)}const s=document.createElement("wpd-textarea");s.className="desktop-mode-pinned-note__editor",s.setAttribute("aria-label",S("Note text","desktop-mode")),s.setAttribute("rows","5"),s.setAttribute("auto-grow",""),s.setAttribute("max-rows","10"),s.setAttribute("value",this.note.text),["keydown","keypress","keyup"].forEach(a=>{s.addEventListener(a,d=>d.stopPropagation())}),s.addEventListener("wpd-input-change",a=>{const d=a.detail;this.pendingText=d.value,this.setPhase("pending"),this.scheduleSave()}),s.addEventListener("wpd-input-commit",()=>this.flushSave()),this.editor=s;const i=document.createElement("div");i.className="desktop-mode-pinned-note__footer";const r=document.createElement("wpd-save-status");r.setAttribute("mode","icon"),r.setAttribute("phase","idle"),r.className="desktop-mode-pinned-note__status",this.statusEl=r,i.appendChild(r),this.paperEl.append(t,s,i)}paintViewerPaper(){const t=document.createElement("div");t.className="desktop-mode-pinned-note__body",t.textContent=this.note.text;const n=document.createElement("div");n.className="desktop-mode-pinned-note__attribution",n.title=ne(S("Pinned by %s","desktop-mode"),this.note.ownerName);const o=document.createElement("wpd-avatar");o.setAttribute("size","20"),o.setAttribute("name",this.note.ownerName),this.note.ownerAvatar&&o.setAttribute("src",this.note.ownerAvatar);const s=document.createElement("span");s.className="desktop-mode-pinned-note__attribution-name",s.textContent=this.note.ownerName,n.append(o,s),this.paperEl.append(t,n)}refreshColorDot(){if(!this.colorDot)return;const t=$m(this.note.color);this.colorDot.style.setProperty("--dm-note-next-paper",`var(--dm-note-${t})`),this.colorDot.setAttribute("aria-label",ne(S("Change paper color (next: %s)","desktop-mode"),t))}refreshVisibility(){if(!this.visibilityBtn)return;const t=this.note.public;this.visibilityBtn.innerHTML="";const n=document.createElement("span");n.className=`dashicons ${t?"dashicons-admin-site-alt3":"dashicons-lock"}`,n.setAttribute("aria-hidden","true"),this.visibilityBtn.appendChild(n),this.visibilityBtn.setAttribute("title",S(t?"Public note — everyone can see it. Click to make private.":"Private note. Click to share with every desktop user.","desktop-mode")),this.visibilityBtn.classList.toggle("is-public",t)}replace(t){const n=t.id!==this.note.id,o=Zs(t)!==Zs(this.note),s=t.color!==this.note.color,i=t.x!==this.note.x||t.y!==this.note.y,r=t.z!==this.note.z;if(this.note=t,r&&(this.element.style.zIndex=String(t.z)),n&&(this.element.dataset.noteId=String(t.id)),o&&(this.jitter=Hm(Zs(t)),this.element.style.setProperty("--dm-note-rot",`${this.jitter.rotation}deg`),this.element.style.setProperty("--dm-pin-dx",`${this.jitter.pinOffsetX}px`),this.element.style.setProperty("--dm-pin-rot",`${this.jitter.pinRotation}deg`)),s&&(this.element.dataset.noteColor=Xa(t.color),this.refreshColorDot()),i&&this.applyPosition(),this.note.canEdit)this.pendingText===null&&this.editor?.setAttribute("value",t.text),this.refreshVisibility();else{const a=this.paperEl.querySelector(".desktop-mode-pinned-note__body");a&&(a.textContent=t.text)}}shouldReplaceFromRemote(t){return this.pendingText!==null||this.saveTimer!==null?!1:t.updatedAtMs>=this.note.updatedAtMs}setZ(t){this.element.style.zIndex=String(t),!(t===this.note.z||!this.note.canEdit)&&(this.note={...this.note,z:t},!(this.note.id<=0)&&(this.zTimer!==null&&window.clearTimeout(this.zTimer),this.zTimer=window.setTimeout(()=>{this.zTimer=null,this.queuePatch({z:this.note.z})},bC)))}applyPosition(){this.element.style.left=`${(this.note.x*100).toFixed(3)}%`,this.element.style.top=`${(this.note.y*100).toFixed(3)}%`}moveTo(t,n){const o=this.layer.clampPosition(t,n);this.note={...this.note,x:o.x,y:o.y},this.applyPosition(),this.note.id>0&&this.queuePatch({x:o.x,y:o.y})}playInsertion(t=1){return GI({pin:this.pinEl,paper:this.paperEl,rippleHost:this.element,restRotation:this.jitter.pinRotation,fallDistance:t>=1?30:12,tempo:t})}focusEditor(){window.setTimeout(()=>this.editor?.focusInput?.(),0)}dispose(){this.disposed=!0,this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.zTimer!==null&&(window.clearTimeout(this.zTimer),this.zTimer=null),this.dragCleanup?.(),this.dragCleanup=null}setPhase(t){this.statusEl?.setAttribute("phase",t)}scheduleSave(){this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.flushSave()},yC)}flushPendingEdits(){this.flushSave()}flushSave(){if(this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.pendingText===null||this.note.id<=0)return;const t=this.pendingText;this.pendingText=null,this.note={...this.note,text:t},this.setPhase("saving"),this.queuePatch({text:t})}cycleColor(){const t=$m(this.note.color);this.note={...this.note,color:t},this.element.dataset.noteColor=t,this.refreshColorDot(),this.note.id>0&&this.queuePatch({color:t})}togglePublic(){const t=!this.note.public;this.note={...this.note,public:t},this.refreshVisibility(),t&&!ln()&&this.visibilityBtn&&this.visibilityBtn.animate?.([{transform:"scale(1)"},{transform:"scale(1.25)"},{transform:"scale(1)"}],{duration:300,easing:"ease-out"}),this.layer.announce(S(t?"Note is now public.":"Note is now private.","desktop-mode")),this.note.id>0&&this.queuePatch({public:t})}queuePatch(t){this.patchChain=this.patchChain.then(async()=>{if(!(this.disposed||this.note.id<=0))try{const n=await rC(this.note.id,{...t,updatedAtMs:this.note.updatedAtMs});if(this.disposed)return;this.note={...this.note,updatedAtMs:n.updatedAtMs,public:n.public},this.setPhase("saved")}catch(n){if(this.disposed)return;if(sC(n)&&n.current){this.pendingText=null,this.replace(n.current),this.setPhase("idle"),this.layer.notifyError(S("This note was changed in another session — showing the latest version.","desktop-mode"));return}this.setPhase("failed"),console.error("[desktop-mode] notes: save failed:",n)}})}startDrag(t){if(!this.note.canEdit||this.note.id<=0)return;const n=_C();if(!n)return;t.preventDefault(),this.element.ownerDocument.defaultView?.getSelection()?.removeAllRanges();const o=this.buildGhost(),s=this.element.getBoundingClientRect(),i={noteId:this.note.id,canEdit:this.note.canEdit,updatedAtMs:this.note.updatedAtMs};n.start({payload:{type:un,source:this.element,data:i,ghost:{element:o.root,offsetX:o.tipX,offsetY:o.tipY,hint:{neutral:S("Drop on the desktop to pin","desktop-mode"),accept:S("Pin here","desktop-mode"),reject:S("Can’t pin here","desktop-mode")}}},origin:t,onClickOnly:()=>{this.teardownDragListeners(),this.toggleMoveMode()},onCancel:()=>{this.teardownDragListeners(),this.snapBack(s)},onCommit:()=>{this.teardownDragListeners(),this.layer.has(this.note.id)&&this.playInsertion(.7)}})&&this.installDragListeners(o)}buildGhost(){const t=this.element.getBoundingClientRect(),o=(this.pinEl.querySelector("img")??this.pinEl).getBoundingClientRect(),s=o.left-t.left+o.width*XI,i=o.top-t.top+o.height*YI,r=document.createElement("div");r.className="desktop-mode-pinned-note-ghost",r.style.width=`${t.width}px`,r.style.height=`${t.height}px`;const a=document.createElement("div");a.className="desktop-mode-pinned-note-ghost__swing",a.style.transformOrigin=`${s}px ${i}px`;const d=this.pinEl.cloneNode(!0);d.removeAttribute("aria-pressed"),d.setAttribute("aria-hidden","true");const l=this.paperEl.cloneNode(!0);return l.classList.add("desktop-mode-pinned-note-ghost__paper"),a.dataset.noteColor=this.element.dataset.noteColor??"",a.append(d,l),r.appendChild(a),{root:r,swing:a,pin:d,paper:l,tipX:s,tipY:i}}installDragListeners(t){this.teardownDragListeners();let n=null;const o=a=>{a.detail?.payload?.data?.noteId===this.note.id&&(n=jI(t.swing))},s=a=>{const d=a.detail;this.lastPointer={x:d.clientX,y:d.clientY},n?.onPointerMove(d.clientX)},i=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.add("desktop-mode-pinned-note-ghost--doom"),n?.setBias(6))},r=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.remove("desktop-mode-pinned-note-ghost--doom"),n?.setBias(0))};document.addEventListener(le.START,o),document.addEventListener(le.MOVE,s),document.addEventListener(le.ENTER,i),document.addEventListener(le.LEAVE,r),this.dragCleanup=()=>{n?.stop(),n=null,document.removeEventListener(le.START,o),document.removeEventListener(le.MOVE,s),document.removeEventListener(le.ENTER,i),document.removeEventListener(le.LEAVE,r)}}teardownDragListeners(){this.dragCleanup?.(),this.dragCleanup=null}async snapBack(t){if(!this.lastPointer||ln()){this.playInsertion(.63);return}const n=this.buildGhost();n.root.classList.add("desktop-mode-pinned-note-ghost--flyback"),n.root.style.position="fixed",n.root.style.left=`${this.lastPointer.x-n.tipX}px`,n.root.style.top=`${this.lastPointer.y-n.tipY}px`,n.root.style.zIndex="2147483647",n.root.style.pointerEvents="none",document.body.appendChild(n.root);try{await qI({flyback:n.root,swing:n.swing,homeX:t.left,homeY:t.top})}finally{n.root.remove()}this.playInsertion(.63)}async playCrumpleAt(t,n){const o=this.buildGhost();o.root.classList.add("desktop-mode-pinned-note-ghost--flyback"),o.root.style.position="fixed",o.root.style.left=`${t-o.tipX}px`,o.root.style.top=`${n-o.tipY}px`,o.root.style.zIndex="2147483647",o.root.style.pointerEvents="none",document.body.appendChild(o.root);try{await VI({clone:o.root,pin:o.pin,paper:o.paper,binX:t,binY:n+24})}finally{o.root.remove()}}toggleMoveMode(){this.moveMode?this.exitMoveMode(!0):this.enterMoveMode()}enterMoveMode(){this.note.canEdit&&(this.moveMode=!0,this.moveOrigin={x:this.note.x,y:this.note.y},this.element.classList.add("desktop-mode-pinned-note--move-mode"),this.pinEl.setAttribute("aria-pressed","true"),this.layer.announce(S("Moving note. Arrow keys to move, Enter to place, Escape to cancel, Delete to move to the Recycle Bin.","desktop-mode")))}exitMoveMode(t){this.moveMode&&(this.moveMode=!1,this.element.classList.remove("desktop-mode-pinned-note--move-mode"),this.pinEl.setAttribute("aria-pressed","false"),t?(this.moveTo(this.note.x,this.note.y),this.layer.announce(S("Note placed.","desktop-mode")),this.playInsertion(.7)):this.moveOrigin&&(this.note={...this.note,...this.moveOrigin},this.applyPosition()),this.moveOrigin=null)}onPinKeydown(t){if(!this.moveMode)return;const{width:n,height:o}=this.layer.hostSize(),s=t.shiftKey?kC:vC,i=s/n,r=s/o;switch(t.key){case"ArrowLeft":this.nudge(-i,0);break;case"ArrowRight":this.nudge(i,0);break;case"ArrowUp":this.nudge(0,-r);break;case"ArrowDown":this.nudge(0,r);break;case"Enter":case" ":this.exitMoveMode(!0);break;case"Escape":this.exitMoveMode(!1),this.layer.announce(S("Move cancelled.","desktop-mode"));break;case"Delete":case"Backspace":this.exitMoveMode(!1),Vr({title:S("Move note to the Recycle Bin?","desktop-mode"),message:S("You can restore it from the Recycle Bin later.","desktop-mode"),confirmLabel:S("Move to Trash","desktop-mode"),danger:!0}).then(a=>{a&&this.layer.trashNote(this.note)});break;default:return}t.preventDefault(),t.stopPropagation()}nudge(t,n){const o=this.layer.clampPosition(this.note.x+t,this.note.y+n);this.note={...this.note,...o},this.applyPosition()}}const _o=new Map;function IC(e,t){return _o.set(e,t),()=>{_o.get(e)===t&&_o.delete(e)}}function CC(e){const t=_o.get(e.type);return t?t.accept(e.data):!1}function AC(e,t){const n=_o.get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}function Vm(e,t,n){const o=e.host.getBoundingClientRect(),s=t.payload.ghost?.offsetX??0,i=t.payload.ghost?.offsetY??0,{width:r,height:a}=e.hostSize();return e.clampPosition((n.clientX-s-o.left)/r,(n.clientY-i-o.top)/a)}function LC(e,t,n){const o=t.payload.data,s=String(o.text??"");if(!s.trim())return;const{x:i,y:r}=Vm(e,t,n),a=Xa(String(o.color??"")),d=o.isPublic===!0,l=KI(s),c=e.nextTempId(),u={id:c,text:s,color:a,x:i,y:r,z:1,public:d,seed:l,ownerId:0,ownerName:"",ownerAvatar:"",canEdit:!0,updatedAtMs:0},p=e.upsertNote(u,{animate:"thunk"});e.bringToFront(p),iC({text:s,color:a,x:i,y:r,public:d,seed:l}).then(f=>{e.bumpHighWater(f.updatedAtMs),p.replace(f),e.rekeyNote(c,p),p.flushPendingEdits()}).catch(f=>{e.removeNote(c),e.notifyError(S("Could not pin the note. Please try again.","desktop-mode")),console.error("[desktop-mode] notes: create failed:",f)})}function TC(e,t,n){const o=t.payload.data,s=e.get(o.noteId);if(!s)return;const{x:i,y:r}=Vm(e,t,n);s.moveTo(i,r)}function NC(e){const t=[],n=o=>o.folderId===0;return t.push(jf(hC,{accept:(o,s)=>n(s)&&!!String(o.text??"").trim(),onDrop:(o,s)=>LC(e,o,s)})),t.push(jf(un,{accept:(o,s)=>n(s)&&o.canEdit===!0,onDrop:(o,s)=>TC(e,o,s)})),t.push(IC(un,{accept:o=>o.canEdit===!0,onDrop:(o,s)=>{const i=o.payload.data,r=e.get(i.noteId);if(!r)return;const a=r.note;r.playCrumpleAt(s.clientX,s.clientY),e.trashNote(a)}})),()=>{t.forEach(o=>o())}}const Ja="data-desktop-mode-posts-drop-active",Km="desktop-mode-posts",DC='.desktop-mode-dock__item[data-menu-slug="menu-posts"],.desktop-mode-dock__item[data-menu-slug="editphp"]',OC="[data-desktop-mode-posts-root]";function RC(){return window.wp?.desktop?.dragManager??null}function MC(e){return e.type!==un?!1:e.data.canEdit===!0}function PC(e){if(!e)return!1;let t=e,n="";try{const i=new URL(e,window.location.origin);t=i.pathname,n=i.search}catch{}if(!(/(?:^|\/)(?:edit\.php|post-new\.php)$/.test(t)||!t.includes("/")&&(t==="edit.php"||t==="post-new.php")))return!1;const s=new URLSearchParams(n).get("post_type");return!s||s==="post"}function $C(e){const t=e.placement.file;if(!t||t.type!=="shortcut")return!1;const n=typeof t.shortcutUrl=="string"?t.shortcutUrl:"";return PC(n)}function Xm(e,t){if(t.payload.type!==un)return;const n=t.payload.data;if(typeof n.noteId!="number")return;const o=e.get(n.noteId);o&&e.convertNote(o.note)}let Ym=!1,Eo=null,So=null,Zm=null;function Jm(e,t,n,o){return e.registerDropTarget({id:n,element:o,acceptLabel:S("Convert to post","desktop-mode"),accept:s=>MC(s),onEnter:()=>{o.setAttribute(Ja,"")},onLeave:()=>{o.removeAttribute(Ja)},onDrop:s=>{o.removeAttribute(Ja),Xm(t,s)}})}function WC(e,t){const n=e.debug().listTargets().find(o=>o.id===t);return n?n.element:null}function UC(e){if(Ym||!e.canCreatePosts)return;const t=RC();if(!t)return;Ym=!0,xS(un,{appliesTo:o=>$C(o),acceptLabel:S("Convert to post","desktop-mode"),accept:o=>o.canEdit===!0,onDrop:o=>Xm(e,o)});const n=()=>{const o=document.querySelector(DC);if(!(o instanceof HTMLElement)){Eo?.(),Eo=null;return}Eo&&WC(t,"notes-convert-dock")===o||(Eo?.(),Eo=Jm(t,e,"notes-convert-dock",o))};n(),G(y.DOCK_AFTER_RENDER,"desktop-mode/notes/convert-dock-target",n),typeof MutationObserver<"u"&&(Zm=new MutationObserver(()=>{n()}),Zm.observe(document.body,{childList:!0,subtree:!0})),G(y.WINDOW_OPENED,"desktop-mode/notes/convert-window-target",o=>{if(o.windowId!==Km)return;So?.(),So=null;const s=document.querySelector(OC);s instanceof HTMLElement&&(So=Jm(t,e,"notes-convert-window",s))}),G(y.WINDOW_CLOSED,"desktop-mode/notes/convert-window-cleanup",o=>{o.windowId===Km&&(So?.(),So=null)})}function FC(e){const t=e.config.notesUrl;if(typeof t!="string"||!t)return null;tC({baseUrl:t,nonce:e.config.restNonce??""});const n=new SC({host:e.host,pluginUrl:e.config.pluginUrl??"",canCreatePosts:e.config.canCreatePosts??!1,onError:e.onError});return NC(n),UC(n),document.addEventListener(wC,o=>{const s=o.detail?.note;if(s&&typeof s.id=="number"){n.bumpHighWater(s.updatedAtMs);const i=n.upsertNote(s,{animate:"thunk"});n.bringToFront(i),i.focusEditor()}}),n.boot(),n}const HC={id:"clock",get label(){return S("Clock")},get description(){return S("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("desktop-mode-widget-clock");const t=document.createElement("div");t.className="desktop-mode-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="desktop-mode-widget-clock__date",e.appendChild(n);const o=()=>{const a=new Date;t.textContent=a.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=a.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})};o();const s=1e3-Date.now()%1e3;let i=null;const r=window.setTimeout(()=>{o(),i=window.setInterval(o,1e3)},s);return()=>{window.clearTimeout(r),i!==null&&window.clearInterval(i)}}};function BC(){yr(HC)}const Qm="desktop-mode-release-card-styles",eh="desktop-mode-release-host",zC='<svg viewBox="0 0 122.52 122.523" aria-hidden="true"><path fill="currentColor" d="M8.708 61.26c0 20.802 12.089 38.779 29.619 47.298L13.258 39.872a52.352 52.352 0 0 0-4.55 21.388zm87.892-2.652c0-6.495-2.333-10.993-4.334-14.494-2.664-4.329-5.161-7.995-5.161-12.324 0-4.831 3.664-9.328 8.825-9.328.233 0 .454.029.681.042-9.35-8.566-21.807-13.796-35.489-13.796-18.36 0-34.513 9.42-43.91 23.688 1.233.037 2.395.063 3.382.063 5.497 0 14.006-.667 14.006-.667 2.833-.167 3.167 3.994.337 4.329 0 0-2.847.335-6.015.501l19.138 56.925 11.502-34.493-8.187-22.432c-2.831-.166-5.51-.501-5.51-.501-2.831-.167-2.499-4.496.332-4.329 0 0 8.679.667 13.843.667 5.496 0 14.006-.667 14.006-.667 2.835-.167 3.168 3.994.337 4.329 0 0-2.852.335-6.015.501l18.992 56.494 5.242-17.517c2.272-7.269 4.001-12.49 4.001-16.989zm-34.404 7.223l-15.768 45.819a52.552 52.552 0 0 0 14.807 2.136c6.309 0 12.36-1.091 17.996-3.075a4.617 4.617 0 0 1-.374-.724L62.196 65.831zm45.192-29.81c.226 1.674.354 3.471.354 5.404 0 5.333-.996 11.328-3.996 18.824l-16.053 46.413c15.624-9.111 26.133-26.038 26.133-45.426.001-9.137-2.333-17.729-6.438-25.215zM61.262 0C27.483 0 0 27.481 0 61.26c0 33.783 27.483 61.263 61.262 61.263 33.778 0 61.265-27.48 61.265-61.263C122.526 27.481 95.04 0 61.262 0zm0 119.715c-32.23 0-58.453-26.223-58.453-58.455 0-32.23 26.222-58.451 58.453-58.451 32.229 0 58.45 26.221 58.45 58.451 0 32.232-26.221 58.455-58.45 58.455z"/></svg>',GC='<svg viewBox="0 0 14 14" aria-hidden="true"><path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" fill="none"></path></svg>',jC=` |
| 267 |
.dm-release-card { |
| 268 |
position: relative; box-sizing: border-box; width: 268px; padding: 11px; |
| 269 |
border-radius: 14px; color: #fff; |
| 270 |
font-family: var( --desktop-mode-font, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif ); |
| 271 |
background: #34373f; border: 1px solid rgba( 255, 255, 255, 0.14 ); |
| 272 |
box-shadow: 0 16px 40px rgba( 0, 0, 0, 0.55 ), 0 3px 8px rgba( 0, 0, 0, 0.3 ), inset 0 0 0 1px rgba( 255, 255, 255, 0.04 ); |
| 273 |
--accent: #2271b1; --accent-ink: #ffffff; |
| 274 |
animation: dmRcCardIn 0.5s cubic-bezier( 0.2, 1.2, 0.35, 1 ) both; |
| 275 |
} |
| 276 |
.dm-release-card, .dm-release-card * { box-sizing: border-box; } |
| 277 |
@keyframes dmRcCardIn { |
| 278 |
from { opacity: 0; transform: translateY( -16px ) scale( 0.96 ); } |
| 279 |
to { opacity: 1; transform: none; } |
| 280 |
} |
| 281 |
.dm-rc__close { |
| 282 |
position: absolute; top: 9px; right: 9px; z-index: 10; |
| 283 |
width: 22px; height: 22px; padding: 0; border: none; border-radius: 50%; |
| 284 |
display: inline-flex; align-items: center; justify-content: center; |
| 285 |
background: rgba( 0, 0, 0, 0.5 ); color: #fff; opacity: 0.72; cursor: pointer; |
| 286 |
transition: opacity 0.12s ease, background-color 0.12s ease; |
| 287 |
} |
| 288 |
.dm-rc__close:hover { opacity: 1; background: rgba( 0, 0, 0, 0.7 ); } |
| 289 |
.dm-rc__close:focus-visible { opacity: 1; outline: 2px solid #fff; outline-offset: 2px; } |
| 290 |
.dm-rc__close svg { width: 11px; height: 11px; } |
| 291 |
.dm-rc__art { position: relative; height: 150px; } |
| 292 |
.dm-rc__cover { |
| 293 |
position: absolute; left: 2px; top: 0; width: 150px; height: 150px; |
| 294 |
border-radius: 2px; overflow: hidden; z-index: 3; |
| 295 |
box-shadow: 0 8px 20px rgba( 0, 0, 0, 0.5 ), inset 0 0 0 1px rgba( 255, 255, 255, 0.08 ); |
| 296 |
} |
| 297 |
.dm-rc__canvas { width: 100%; height: 100%; display: block; } |
| 298 |
.dm-rc__disc-wrap { |
| 299 |
position: absolute; left: 94px; top: 2px; width: 148px; height: 148px; z-index: 2; |
| 300 |
border-radius: 50%; box-shadow: 0 14px 26px rgba( 0, 0, 0, 0.6 ); |
| 301 |
animation: dmRcEmerge 0.8s cubic-bezier( 0.2, 1, 0.28, 1 ) 0.45s both; |
| 302 |
} |
| 303 |
@keyframes dmRcEmerge { |
| 304 |
from { transform: translateX( -84px ); } |
| 305 |
to { transform: translateX( 0 ); } |
| 306 |
} |
| 307 |
.dm-rc__disc { |
| 308 |
position: absolute; inset: 0; border-radius: 50%; |
| 309 |
background: |
| 310 |
repeating-radial-gradient( circle at 50% 50%, rgba( 255, 255, 255, 0.05 ) 0 1px, rgba( 0, 0, 0, 0 ) 1px 2.4px ), |
| 311 |
radial-gradient( circle at 50% 50%, #1a1a1e 0 11%, #0a0a0c 12% 62%, #050506 100% ); |
| 312 |
box-shadow: inset 0 0 26px rgba( 0, 0, 0, 0.9 ), inset 0 0 0 1px rgba( 255, 255, 255, 0.05 ); |
| 313 |
animation: dmRcSettle 2.5s cubic-bezier( 0.12, 0.72, 0.16, 1 ) 0.45s both; |
| 314 |
} |
| 315 |
@keyframes dmRcSettle { |
| 316 |
from { transform: rotate( 0 ); } |
| 317 |
to { transform: rotate( 720deg ); } |
| 318 |
} |
| 319 |
.dm-rc__label { |
| 320 |
position: absolute; inset: 34%; border-radius: 50%; display: grid; place-items: center; |
| 321 |
background: var( --accent ); color: var( --accent-ink ); |
| 322 |
box-shadow: inset 0 0 0 2px rgba( 0, 0, 0, 0.18 ), 0 1px 2px rgba( 0, 0, 0, 0.4 ); |
| 323 |
} |
| 324 |
.dm-rc__label svg { width: 59%; height: 59%; display: block; } |
| 325 |
.dm-rc__sheen { |
| 326 |
position: absolute; inset: 0; border-radius: 50%; pointer-events: none; z-index: 3; |
| 327 |
background: linear-gradient( 118deg, rgba( 255, 255, 255, 0.18 ) 0%, transparent 24%, transparent 74%, rgba( 255, 255, 255, 0.1 ) 100% ); |
| 328 |
mix-blend-mode: screen; |
| 329 |
} |
| 330 |
.dm-rc__meta { |
| 331 |
display: flex; align-items: center; gap: 10px; margin-top: 11px; |
| 332 |
opacity: 0; animation: dmRcFade 0.5s ease 1.05s forwards; |
| 333 |
} |
| 334 |
@keyframes dmRcFade { to { opacity: 1; } } |
| 335 |
.dm-rc__text { flex: 1; font-size: 13px; line-height: 1.35; color: #fff; } |
| 336 |
.dm-rc__text b { font-weight: 650; } |
| 337 |
.dm-rc__btn { |
| 338 |
flex-shrink: 0; padding: 7px 12px; border: none; border-radius: 7px; |
| 339 |
color: var( --accent-ink ); background: var( --accent ); font: inherit; font-size: 12px; font-weight: 600; |
| 340 |
cursor: pointer; box-shadow: 0 2px 8px rgba( 0, 0, 0, 0.3 ); transition: filter 0.12s; |
| 341 |
} |
| 342 |
.dm-rc__btn:hover { filter: brightness( 1.12 ); } |
| 343 |
.dm-rc__btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; } |
| 344 |
@media ( prefers-reduced-motion: reduce ) { |
| 345 |
.dm-release-card, .dm-rc__disc-wrap, .dm-rc__disc, .dm-rc__meta { animation: none !important; } |
| 346 |
.dm-rc__disc-wrap { transform: translateX( 0 ); } |
| 347 |
.dm-rc__meta { opacity: 1; } |
| 348 |
} |
| 349 |
`;function qC(){if(document.getElementById(Qm))return;const e=document.createElement("style");e.id=Qm,e.textContent=jC,document.head.appendChild(e)}function VC(){const e=document.querySelector("."+eh);if(e)return e;const t=document.createElement("div");return t.className=eh,t.style.cssText="position:fixed;top:calc(var(--wp-admin--admin-bar--height,32px) + 16px);inset-inline-end:16px;z-index:calc(var(--desktop-mode-z-fullscreen,99999) + 10);pointer-events:none;",document.body.appendChild(t),t}function KC(e,t,n,o){const s=new Image;s.crossOrigin="anonymous",s.addEventListener("load",()=>{const i=s.naturalWidth||0,r=s.naturalHeight||0;if(!i||!r)return;const a=320;t.width=a,t.height=a;const d=t.getContext("2d");if(!d)return;const l=Math.min(i,r);d.drawImage(s,0,0,l,l,0,0,a,a);try{const c=document.createElement("canvas");c.width=i,c.height=r;const u=c.getContext("2d");if(!u)return;u.drawImage(s,0,0);const p=u.getImageData(0,0,i,r).data,f=(E,I)=>{const O=(I*i+E)*4;return p[O]>248&&p[O+1]>248&&p[O+2]>248&&p[O+3]>200},h=E=>{for(let I=0;I<i;I+=2)if(!f(I,E))return!1;return!0},m=E=>{for(let I=0;I<r;I+=2)if(!f(E,I))return!1;return!0};let w=0;for(;w<r-1&&h(w);)w++;let g=r-1;for(;g>w&&h(g);)g--;let k=0;for(;k<i-1&&m(k);)k++;let D=i-1;for(;D>k&&m(D);)D--;const b=Math.max(1,Math.min(D-k+1,g-w+1));d.clearRect(0,0,a,a),d.drawImage(s,k,w,b,b,0,0,a,a),o||XC(e,d,a)}catch{}},{once:!0}),s.src=n}function XC(e,t,n){const{data:o}=t.getImageData(0,0,n,n),s=new Map;let i=null,r=-1;for(let u=0;u<o.length;u+=4){const p=o[u],f=o[u+1],h=o[u+2];if(o[u+3]<200)continue;const m=Math.max(p,f,h),w=Math.min(p,f,h),g=m/255,k=m===0?0:(m-w)/m;if(g<.2||k<.25)continue;const D=`${Math.floor(p/16)},${Math.floor(f/16)},${Math.floor(h/16)}`;let b=s.get(D);b||(b={r:0,g:0,b:0,n:0,score:0},s.set(D,b)),b.r+=p,b.g+=f,b.b+=h,b.n+=1,b.score+=k*g,b.score>r&&(r=b.score,i=b)}if(!i)return;const a=Math.round(i.r/i.n),d=Math.round(i.g/i.n),l=Math.round(i.b/i.n),c=(.299*a+.587*d+.114*l)/255;e.style.setProperty("--accent",`rgb(${a}, ${d}, ${l})`),e.style.setProperty("--accent-ink",c>.6?"#1a1a1a":"#ffffff")}function YC(e){qC();const t=VC();t.textContent="";const n=document.createElement("div");n.className="dm-release-card",n.setAttribute("role","status"),n.style.pointerEvents="auto",e.accent&&n.style.setProperty("--accent",e.accent),e.accentInk&&n.style.setProperty("--accent-ink",e.accentInk),n.innerHTML=`<button type="button" class="dm-rc__close">${GC}</button><div class="dm-rc__art"><div class="dm-rc__disc-wrap"><div class="dm-rc__disc"><div class="dm-rc__label">${zC}</div></div><div class="dm-rc__sheen"></div></div><div class="dm-rc__cover"><canvas class="dm-rc__canvas"></canvas></div></div><div class="dm-rc__meta"><span class="dm-rc__text"></span><button type="button" class="dm-rc__btn"></button></div>`,n.querySelector(".dm-rc__text").textContent=e.message;const o=n.querySelector(".dm-rc__close");o.setAttribute("aria-label",S("Dismiss"));const s=n.querySelector(".dm-rc__btn");s.textContent=S("Update now"),t.appendChild(n),KC(n,n.querySelector(".dm-rc__canvas"),e.artUrl,!!e.accent);let i=!1,r=null;const a=()=>{i=!0,r!==null&&(clearTimeout(r),r=null),n.remove()};return o.addEventListener("click",d=>{if(d.preventDefault(),d.stopPropagation(),i)return;if(Bn(e.dismissKey),typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches){a();return}i=!0,n.style.animation="none",n.style.transition="opacity 0.2s ease",requestAnimationFrame(()=>{n.style.opacity="0"}),r=window.setTimeout(()=>n.remove(),240)}),s.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),e.onUpdate(),a()}),a}const th="desktop-mode/release-art:v1:",ZC=6*60*60*1e3;function Nt(e){return typeof e=="string"?e:""}function it(e,t){return e&&typeof e=="object"?e[t]:void 0}function JC(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}function QC(e){const t=it(it(e,"_embedded"),"wp:featuredmedia"),n=Array.isArray(t)?t[0]:void 0,o=it(it(n,"media_details"),"sizes");for(const s of["medium_large","large","1536x1536","medium"]){const i=Nt(it(it(o,s),"source_url"));if(i)return i}return Nt(it(n,"source_url"))}function eA(e,t){if(!Array.isArray(e))return null;const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp("^WordPress "+n+'\\s*[“"]([^”"]+)[”"]');for(const s of e){const i=JC(Nt(it(it(s,"title"),"rendered"))),r=o.exec(i);if(!r)continue;const a=QC(s);if(a)return{name:r[1].trim(),artUrl:a}}return null}function tA(e){try{const t=localStorage.getItem(th+e);if(!t)return null;const n=JSON.parse(t);return n.ok===!0&&Nt(n.name)&&Nt(n.artUrl)?{name:Nt(n.name),artUrl:Nt(n.artUrl)}:n.ok===!1&&typeof n.ts=="number"&&Date.now()-n.ts<ZC?"miss":null}catch{return null}}function Js(e,t){try{localStorage.setItem(th+e,JSON.stringify(t))}catch{}}async function nA(e){if(!e)return null;const t=tA(e);if(t==="miss")return null;if(t)return t;try{const n="https://wordpress.org/news/wp-json/wp/v2/posts?search="+encodeURIComponent(e)+"&per_page=100&_fields=title,_links,_embedded&_embed=wp:featuredmedia",o=await Pe(n,{credentials:"omit"},{silent:!0,source:"desktop-mode/release-art"});if(!o.ok)return Js(e,{ok:!1,ts:Date.now()}),null;const s=eA(await o.json(),e);return s?(Js(e,{ok:!0,name:s.name,artUrl:s.artUrl}),s):(Js(e,{ok:!1,ts:Date.now()}),null)}catch{return Js(e,{ok:!1,ts:Date.now()}),null}}function oA(e,t=5e3){return new Promise(n=>{const o=new Image;o.crossOrigin="anonymous";let s=!1;const i=r=>{s||(s=!0,n(r))};o.addEventListener("load",()=>i(!0),{once:!0}),o.addEventListener("error",()=>i(!1),{once:!0}),window.setTimeout(()=>i(!1),t),o.src=e})}function nh(e,t){if(t){const o=S('WordPress %1$s "%2$s" is available.');return ne(o,e,t)}const n=S("WordPress %s is available.");return ne(n,e)}async function sA(e){const{update:t,openUrl:n}=e;if(!t||typeof t.version!="string"||!t.version||typeof t.url!="string"||!t.url)return;const o=t.version,s=typeof t.branch=="string"&&t.branch?t.branch:o,i=t.crossing===!0,a=`desktop-mode/core-update:${typeof t.available=="string"&&t.available?t.available:o}`;if(pr(a))return;const d=()=>n({url:t.url,title:S("WordPress Updates")}),l=e.resolveArt??nA,c=e.loadImage??oA,u=await l(s);if(u&&u.artUrl&&await c(u.artUrl)){YC({message:nh(o,i?u.name:""),artUrl:u.artUrl,dismissKey:a,onUpdate:d});return}q({message:nh(o,""),persistent:!0,dismissible:!0,onDismiss:()=>Bn(a),action:{label:S("Update now"),onClick:d}})}function oh(e){const{notices:t,openUrl:n,keyPrefix:o="core-notice"}=e;if(Array.isArray(t))for(const s of t){if(!s||typeof s.id!="string"||!s.id||typeof s.message!="string"||!s.message)continue;const i=`desktop-mode/${o}:${s.id}`;if(pr(i))continue;const r=s.actionLabel,a=s.actionUrl,d=s.title||r||"";let l;r&&a&&(l={label:r,onClick:()=>n({url:a,title:d})}),q({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>Bn(i),action:l})}}const Qa="desktop-mode/starter",iA="desktop-mode/dev-mode-gate";let sh=!1;function rA({osSettings:e,layer:t}){if(sh)return;sh=!0,gn(y.WIDGETS,iA,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==Qa));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(Qa):t.unmount(Qa),Vn())})}function aA(e){const{layer:t}=e,n=new Set,o=new Set,s=async d=>{if(!(!d.scriptUrl||o.has(d.scriptUrl))){try{await Ie(d.scriptUrl,{translations:d.scriptTranslations,l10n:d.scriptL10n,before:d.scriptBefore,after:d.scriptAfter})}catch(l){T(y.SHELL_ERROR,{scope:"widget-script-load",id:d.id,error:l});return}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}:(T(y.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{yr(l)}catch(c){T(y.SHELL_ERROR,{scope:"widget-register",id:d.id,error:c});return}n.add(d.id),Vn(),t&&t.mountIfEnabled(d.id)}},a=d=>{n.has(d)&&(t?.unmount(d),jv(d),n.delete(d),Vn())};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 ih=["wpd-section","wpd-button","wpd-swatch","wpd-swatch-grid","wpd-segmented","wpd-segment","wpd-select","wpd-option","wpd-multiselect","wpd-color-field","wpd-range-field","wpd-text-field","wpd-number-field","wpd-checkbox","wpd-checkbox-label","wpd-toast","wpd-toast-container","wpd-tabs","wpd-tab","wpd-tabpanel","wpd-window-button","wpd-menu","wpd-menu-item","wpd-context-menu","wpd-context-menu-option","wpd-confirm-dialog","wpd-modal","wpd-user-search","wpd-role-picker","wpd-flyout","wpd-tab-chip","wpd-stack","wpd-cluster","wpd-icon","wpd-body","wpd-panel","wpd-row","wpd-grid","wpd-display","wpd-empty-state","wpd-key","wpd-code","wpd-badge","wpd-ribbon","wpd-tile","wpd-log","wpd-steps","wpd-step","wpd-table","wpd-spinner","wpd-relative-time","wpd-avatar","wpd-textarea","wpd-chip","wpd-tag-input","wpd-form","wpd-save-status","wpd-category-picker","wpd-crumb-chain","wpd-card","wpd-rating-summary","wpd-notice","wpd-progress-bar"],rh=new Set(ih),dA=2e3,ed=new Set,ah=new WeakSet;let dh=!1;function lA(e,t){const n=e.length,o=t.length;if(n===0)return o;if(o===0)return n;const s=new Array(o+1);for(let i=0;i<=o;i++)s[i]=i;for(let i=1;i<=n;i++){let r=s[0];s[0]=i;for(let a=1;a<=o;a++){const d=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=d}}return s[o]}function cA(e){let t=null,n=1/0;for(const o of rh){const s=lA(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function uA(e){return e.startsWith("wpd-")?e.slice(4):e}function pA(e,t){if(ed.has(e))return;if(ed.add(e),rh.has(e)){const s=uA(e);console.error(`[wp.desktop] <${e}> is in the DOM but its module was never imported, so the tag will not upgrade and the component will render as inert HTML. |
| 350 |
|
| 351 |
Fix — side-effect-import the component module from wherever you render it: |
| 352 |
|
| 353 |
import '<rel>/ui/components/${s}/${s}'; |
| 354 |
|
| 355 |
Or pull every wpd-* component in one go (heavier — only do this from an entry bundle): |
| 356 |
|
| 357 |
import '<rel>/ui/components'; |
| 358 |
|
| 359 |
See docs/components-reference.md for the full list.`,` |
| 360 |
First offending element:`,t);return}const o=cA(e);if(o){console.error(`[wp.desktop] <${e}> is not a registered wpd-* component. Did you mean <${o}>? |
| 361 |
|
| 362 |
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'.`,` |
| 363 |
First offending element:`,t);return}console.error(`[wp.desktop] <${e}> looks like a wpd-* tag but no component by that name exists. |
| 364 |
|
| 365 |
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.`,` |
| 366 |
First offending element:`,t)}function lh(e){const t=e.tagName.toLowerCase();if(!t.startsWith("wpd-")||ed.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||pA(t,e)},dA)}function ch(e){e instanceof Element&&(lh(e),e.shadowRoot&&Qs(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];lh(o),o.shadowRoot&&Qs(o.shadowRoot)}}function Qs(e){if(ah.has(e))return;ah.add(e),ch(e),new MutationObserver(n=>{for(let o=0;o<n.length;o++){const s=n[o].addedNodes;for(let i=0;i<s.length;i++){const r=s[i];r.nodeType===1&&ch(r)}}}).observe(e,{childList:!0,subtree:!0})}function fA(){const e=Element.prototype,t=e.attachShadow;if(t.__wpdPatched)return;const n=function(o){const s=t.call(this,o);return s.mode==="open"&&Qs(s),s};n.__wpdPatched=!0,e.attachShadow=n}function mA(){dh||typeof document>"u"||(dh=!0,fA(),Qs(document))}const hA=new Set(["post"]);function uh(){const e=window.wp?.desktop?.myWordpress;return e&&typeof e.trashEntity=="function"?e:null}const td="data-desktop-mode-trash-drop-active",pn="desktop-mode-recycle-bin",wA=[`.desktop-mode-file-tile[data-file-ref="${pn}"]`,`[data-icon-id="${pn}"]`,`[data-system-id="${pn}"]`];function gA(){for(const e of wA){const t=document.querySelector(e);if(t instanceof HTMLElement)return t}return null}let ph=!1,xo=null,Io=null,fh=null;function yA(e){return e.payload.type==="desktop-file"}function bA(e){return e.payload.type==="shortcut"}function vA(e){if(!e.kind||!e.ref||!e.entityId||!hA.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return!Number.isFinite(t)||t<=0?!1:uh()!==null}function mh(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:S("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const i=o.data?.placement;return!i||i.file?.ref===pn?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data;return vA(s)}return CC(o)},onEnter:()=>{n.setAttribute(td,"")},onLeave:()=>{n.removeAttribute(td)},onDrop:(o,s)=>{if(n.removeAttribute(td),yA(o)){const i=o.payload.data.placement;PS(i);return}if(!(o.payload.type!=="shortcut"&&AC(o,s))&&bA(o)){const i=o.payload.data,r=uh();if(!r?.trashEntity||!i.entityId)return;const a=Number.parseInt(i.ref,10);if(!Number.isFinite(a)||a<=0)return;r.trashEntity(i.entityId,a).catch(d=>{console.error("[desktop-mode] recycle-bin: shortcut trash failed:",d)})}}})}function kA(e){if(ph)return;ph=!0;const t=()=>{const n=gA();if(!n){xo?.(),xo=null;return}xo&&_A(e)===n||(xo?.(),xo=mh(e,"recycle-bin-dock",n))};if(t(),document.addEventListener("desktop-mode-files-changed",t),G(y.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),G(y.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){fh=new MutationObserver(()=>{t()});const n=document.getElementById("desktop-mode-area")??document.body;fh.observe(n,{childList:!0,subtree:!0})}G(y.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==pn)return;Io?.(),Io=null;const o=document.querySelector("[data-desktop-mode-recycle-bin-root]");o instanceof HTMLElement&&(Io=mh(e,"recycle-bin-window",o))}),G(y.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===pn&&(Io?.(),Io=null)})}function _A(e){const t=e.debug().listTargets().find(n=>n.id==="recycle-bin-dock");return t?t.element:null}let hh=!1,Dt=0;function EA(){hh||(hh=!0,ye.contribute("desktop_mode_files_subscribe",()=>{const e=ft(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:Dt,sharesVersion:ze().state.sharesVersion}}),ye.subscribe("desktop_mode_files",e=>{SA(e)}))}function SA(e){const t=e.folders??[];for(const i of t)da(i,"remote"),i.updatedAtMs>Dt&&(Dt=i.updatedAtMs);const n=e.placements??[];for(const i of n)Ps(i,"remote"),i.updatedAtMs>Dt&&(Dt=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])la(i,"remote");for(const i of o.placements??[])ao(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>Dt&&(Dt=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&fm(s),e.truncated){const i=Array.from(ft().hydratedFolders);for(const r of i)Le(r).then(a=>{pt(r,a.placements)}).catch(()=>{})}}let wh=!1;const xA=[];function IA(){if(wh)return;wh=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||CA()};xA.push(Fe("desktop-mode.placement.changed",e),Fe("desktop-mode.shortcut.changed",e),Fe("desktop-mode.folder.changed",e))}function CA(){wf().then(t=>{Mf(t.folders)}).catch(t=>{console.error("[desktop-mode] files restore-sync: listFolders failed",t)});const e=Array.from(ft().hydratedFolders);for(const t of e)Le(t).then(n=>{pt(t,n.placements)}).catch(n=>{console.error("[desktop-mode] files restore-sync: listPlacements failed for",t,n)})}const Co="desktop-mode-wallpaper-menu";let fn=null;function gh(){return fn!==null}let yh=0;function AA(e,t,n,o={}){Ao();const s=++yh;bn(()=>s===yh,()=>LA(e,t,n,o))}function LA(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((f,h)=>{const m=typeof f.sort=="number"?f.sort:100,w=typeof h.sort=="number"?h.sort:100;return m!==w?m-w:f.label.localeCompare(h.label)});const s=document.createElement("wpd-context-menu");s.setAttribute("open",""),s.classList.add(Co),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const d=()=>{r&&(r.remove(),r=null,a=null)};for(const f of n){i.set(f.id,f);const h=document.createElement("wpd-context-menu-option");h.dataset.menuItemId=f.id,h.setAttribute("value",f.id),f.heading&&h.setAttribute("heading",""),f.disabled&&h.setAttribute("disabled",""),f.icon&&h.setAttribute("icon",bh(f.icon));const m=Array.isArray(f.children)&&f.children.length>0;m&&h.setAttribute("has-children",""),h.textContent=f.label,h.addEventListener("mouseenter",()=>{if(m){l(f,h);return}d()}),s.appendChild(h)}s.addEventListener("wpd-context-menu-pick",f=>{const h=f.detail,m=i.get(h.id)??null;if(m){if(Array.isArray(m.children)&&m.children.length>0){if(f.stopPropagation(),a&&a.id===m.id){d();return}const w=s.querySelector(`[data-menu-item-id="${m.id}"]`);w&&l(m,w);return}Ao(),m.onClick(new MouseEvent("click"))}});function l(f,h){d();const m=document.createElement("wpd-context-menu");m.setAttribute("open",""),m.classList.add(Co,`${Co}--flyout`),m.dataset.parentId=f.id;const w=(f.children??[]).slice().sort((g,k)=>{const D=typeof g.sort=="number"?g.sort:100,b=typeof k.sort=="number"?k.sort:100;return D!==b?D-b:g.label.localeCompare(k.label)});for(const g of w){const k=document.createElement("wpd-context-menu-option");k.dataset.menuItemId=g.id,k.setAttribute("value",g.id),g.icon&&k.setAttribute("icon",bh(g.icon)),g.disabled&&k.setAttribute("disabled",""),g.checked&&k.setAttribute("checked",""),k.textContent=g.label,k.addEventListener("wpd-context-menu-pick",D=>{D.stopPropagation(),Ao(),g.onClick(new MouseEvent("click"))}),m.appendChild(k)}document.body.appendChild(m),r=m,a=f,c(m,h)}function c(f,h){const m=h.getBoundingClientRect();f.style.position="fixed",f.style.left=`${m.right}px`,f.style.top=`${m.top}px`;const w=f.getBoundingClientRect();w.right>window.innerWidth&&(f.style.left=`${Math.max(0,m.left-w.width)}px`),w.bottom>window.innerHeight&&(f.style.top=`${Math.max(0,window.innerHeight-w.height-8)}px`)}e.appendChild(s),fn=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=Uf(s,{close:()=>Ao(),siblingSelectors:[`.${Co}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",p),T("desktop-mode.wallpaper-menu.opened",{items:n.map(f=>f.id)})}function Ao(){fn&&(document.querySelectorAll(`.${Co}--flyout`).forEach(e=>e.remove()),fn.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),fn.remove(),fn=null,T("desktop-mode.wallpaper-menu.closed",{}))}function TA(e){const t=[{id:"create-folder",label:e.labels.createFolder,icon:"dashicons-portfolio",sort:10,onClick:()=>e.createFolder()},{id:"new-url",label:e.labels.newUrl,icon:"dashicons-admin-links",sort:12,onClick:()=>e.createUrl()},{id:"sort-by",label:e.labels.sortHeading,icon:"dashicons-sort",sort:16,onClick:()=>{},children:[{id:"sort-name-asc",label:e.labels.sortNameAsc,sort:10,checked:e.currentSortMode==="name-asc",onClick:()=>e.sortIcons("name-asc")},{id:"sort-name-desc",label:e.labels.sortNameDesc,sort:20,checked:e.currentSortMode==="name-desc",onClick:()=>e.sortIcons("name-desc")},{id:"sort-date-desc",label:e.labels.sortDateDesc,sort:30,checked:e.currentSortMode==="date-desc",onClick:()=>e.sortIcons("date-desc")},{id:"sort-date-asc",label:e.labels.sortDateAsc,sort:40,checked:e.currentSortMode==="date-asc",onClick:()=>e.sortIcons("date-asc")}]},...e.includeShowDesktop===!1?[]:[{id:"show-desktop",label:e.labels.showDesktop,icon:"dashicons-desktop",sort:20,onClick:()=>e.toggleShowDesktop()}],{id:"os-settings",label:e.labels.osSettings,icon:"dashicons-admin-generic",sort:30,onClick:()=>e.openOsSettings()}],n=(e.serverItems??[]).map(i=>NA(i,e)),o=[...t,...n],s=j("desktop-mode.wallpaper-context-menu",o);return Array.isArray(s)?s:o}function NA(e,t){return{id:e.id,label:e.label,icon:e.icon,sort:e.sort,disabled:e.disabled,onClick:()=>{if(e.callbackId){const n=t.serverCallbacks?.[e.callbackId];if(typeof n=="function")return n()}T("desktop-mode.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function bh(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const Lo="desktop-mode-url-dialog";let To=null;function nd(){To&&(To.dispatchEvent(new CustomEvent("url-dialog-closed")),To.remove(),To=null,T("desktop-mode.files.url-dialog.closed",{}))}function DA(e){if(nd(),j("desktop-mode.files.url-dialog",null,e)===!1)return;const n=document.createElement("div");n.className=`${Lo}__overlay desktop-mode-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${Lo} desktop-mode-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${Lo}-title`);const s=document.createElement("h2");if(s.id=`${Lo}-title`,s.className="desktop-mode-create-folder-dialog__title",s.textContent=e.title,o.appendChild(s),e.description){const g=document.createElement("p");g.className=`${Lo}__description`,g.textContent=e.description,o.appendChild(g)}const i=document.createElement("wpd-text-field");i.setAttribute("label",e.nameLabel??"Name"),i.setAttribute("value",e.initialName??""),i.setAttribute("placeholder","My web app"),i.setAttribute("autocomplete","off"),o.appendChild(i);const r=document.createElement("wpd-text-field");r.setAttribute("label",e.urlLabel??"URL"),r.setAttribute("value",e.initialUrl??"https://"),r.setAttribute("placeholder","https://example.com"),r.setAttribute("type","url"),r.setAttribute("autocomplete","off"),o.appendChild(r);const a=document.createElement("p");a.className="desktop-mode-create-folder-dialog__error",a.hidden=!0,a.setAttribute("role","alert"),o.appendChild(a);const d=document.createElement("div");d.className="desktop-mode-create-folder-dialog__actions";const 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=e.submitLabel??"Create",d.appendChild(l),d.appendChild(c),o.appendChild(d),n.appendChild(o),document.body.appendChild(n),To=n,queueMicrotask(()=>{const g=i.shadowRoot?.querySelector("input");g?.focus(),g?.select()}),T("desktop-mode.files.url-dialog.opened",{});const u=g=>{const k=g.value;return typeof k=="string"?k:g.shadowRoot?.querySelector("input")?.value??""},p=g=>{i.disabled=g,r.disabled=g,l.disabled=g,c.disabled=g,o.classList.toggle("desktop-mode-create-folder-dialog--busy",g)},f=g=>{a.textContent=g,a.hidden=!1},h=()=>{nd(),e.onCancel?.()},m=async()=>{const g=u(r).trim();if(!g){f("Please enter a URL.");return}const k=/^[a-z][a-z0-9+\-.]*:/i.test(g)?g:`https://${g}`;try{new URL(k)}catch{f("That doesn't look like a valid URL.");return}const D=u(i).trim();a.hidden=!0,p(!0);try{await e.onSubmit({name:D,url:k}),nd()}catch(b){p(!1),f(b instanceof Error?b.message:"Could not save.")}};l.addEventListener("click",()=>h()),c.addEventListener("click",()=>void m()),n.addEventListener("click",g=>{g.target===n&&h()});const w=g=>{g.key==="Escape"?(g.preventDefault(),h()):g.key==="Enter"&&!g.isComposing&&(g.preventDefault(),m())};o.addEventListener("keydown",w),n.addEventListener("url-dialog-closed",()=>{o.removeEventListener("keydown",w)})}const vh=[];let od=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.desktop)return;const n={whenReady(o){if(typeof o=="function"){if(od){Promise.resolve().then(o);return}vh.push(o)}},ready(o){n.whenReady(o)},isReady(){return od}};t.wp.desktop=n})();const No="desktop-mode-os-settings";let sd=[],ei=Number.POSITIVE_INFINITY,id=!1;function Ge(e,t=1500){if(sd.push(e),t<ei&&(ei=t),id)return;id=!0;const n=()=>{const o=sd;sd=[],ei=Number.POSITIVE_INFINITY,id=!1;for(const s of o)try{s()}catch(i){typeof console<"u"&&console.error("[desktop-mode] scheduleIdleBoot callback threw:",i)}};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(n,{timeout:ei}):window.setTimeout(n,0)}function kh(){const e=window.desktopModeConfig;if(!e)return;const t=document.getElementById("desktop-mode-area");if(!t)return;const n=new _w(t),o=document.getElementById("desktop-mode-wallpaper"),s=e.pluginUrl||"";let i=null;o&&(i=new ic(o,s));const r=document.getElementById("desktop-mode-widgets");let a=null;BC(),Cy(),r&&(a=new bk(r,s)),nc({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const d=new Ry({mediaUrl:e.mediaUrl,restNonce:e.restNonce,canUpload:!!e.canUpload,isAdmin:!!e.currentUserIsAdmin,extendedOptions:e.extendedOptions??null,extendedOptionsUrl:e.extendedOptionsUrl??"",osSettingsPanelBundleUrl:e.osSettingsPanelBundleUrl??""},i??new ic(document.createElement("div"),s));d.apply(),a&&rA({osSettings:d,layer:a});const l=new Bk({aiSearchUrl:e.aiSearchUrl??"",aiSearchStreamUrl:e.aiSearchStreamUrl??"",restNonce:e.restNonce,getTransport:()=>"sse",isAiAvailable:()=>e.aiAssistant?.available===!0&&e.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>d.getOsSettingsSnapshot().ai.enabled!==!1},e.aiAssistantBundleUrl??"");l.attachAsk(Vk({config:()=>e,fallbackContext:()=>({close:()=>l.close(),openInWindow:(_,W,H)=>{n.open({url:_,title:W,icon:H??"dashicons-admin-generic"})},confirm:_=>Vr({message:_})})}));const c=new H_,u=new oE;document.addEventListener(le.START,_=>{const H=_.detail?.payload;if(!H||H.type!=="shortcut"&&H.type!=="desktop-file")return;const Z=H.data?.bridgePayload;Z&&c.start(Z)}),document.addEventListener(le.END,()=>{c.end()}),Ge(()=>hE(u)),Ge(()=>LE(n)),window.addEventListener("message",_=>{if(_.origin!==window.location.origin)return;const W=_.data;!W||W.type!=="desktop-mode-drop-failed"||q({message:"Could not insert into the editor."})}),Wp({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>l.open(),close:()=>l.close(),isOpen:()=>l.isOpen}),ME(),Sw(n),Lw(n),Ge(()=>{new Pv({manager:n,adminUrl:e.adminUrl}).install(),new Gv({manager:n,adminUrl:e.adminUrl}).install()}),document.addEventListener("desktop-mode-open-ai",()=>{Mr("desktop-mode-ai-assistant")}),document.addEventListener("click",_=>{const W=_.target;!(W instanceof Element)||!W.closest("#wp-admin-bar-command-palette")||(_.preventDefault(),_.stopImmediatePropagation(),Mr("desktop-mode-ai-assistant"))},!0);const p=document.getElementById("desktop-mode-dock"),f=document.getElementById("desktop-mode-shell"),h=f?.querySelector(".desktop-mode-shell__body");let m=null;const w=Lk({manager:n,appendSystemTile:_=>m?.appendSystemTile(_),removeSystemTile:_=>m?.removeSystemTile(_)}),g=w.sync;jw({getSnapshot:()=>d.getOsSettingsSnapshot(),openById:_=>w.openById(_),adminUrl:e.adminUrl});const k=_=>{const W=oe(_,e.adminUrl),H=m?m.getMenuItems():e.dockItems??[];for(const Z of H){if(oe(Z.url,e.adminUrl)===W)return{title:Z.title,icon:Z.icon,url:Z.url,submenu:Z.submenu,multi:Z.multi};for(const fe of Z.submenu??[])if(oe(fe.url,e.adminUrl)===W)return{title:fe.title,icon:Z.icon,url:Z.url,multi:Z.multi}}return null};if(fg({adminUrl:e.adminUrl,deriveSlug:_=>oe(_,e.adminUrl),openWindow:_=>{n.open(_)},findDockEntry:k}),$t({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(_,W)=>{if(!W.pathname.endsWith("/edit.php"))return!1;const H=W.searchParams.get("post_type");return!H||H==="post"},enabled:_=>_.nativePostsEnabled===!0}),$t({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(_,W)=>W.pathname.endsWith("/edit.php")?W.searchParams.get("post_type")==="page":!1,enabled:_=>_.nativePagesEnabled===!0}),$t({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(_,W)=>W.pathname.endsWith("/users.php"),enabled:_=>_.nativeUsersEnabled===!0}),$t({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(_,W)=>{const H=W.pathname;return H.endsWith("/profile.php")?!0:H.endsWith("/user-edit.php")?W.searchParams.has("user_id"):!1},enabled:_=>_.nativeUsersEnabled===!0,onMatch:(_,W)=>{const H=parseInt(W.searchParams.get("user_id")??"0",10);H>0&&Fy(H)}}),$t({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(_,W)=>W.pathname.endsWith("/edit-comments.php"),enabled:_=>_.nativeCommentsEnabled===!0}),$t({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(_,W)=>{const H=W.pathname;return H.endsWith("/plugins.php")||H.endsWith("/plugin-install.php")},enabled:_=>_.nativePluginsEnabled===!0,onMatch:(_,W)=>{const H=W.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>aL).then(Z=>{Z.setPluginsWindowTab(H)})}}),p&&f&&h&&e.dockItems){t.classList.add("desktop-mode-area--with-dock");const _=d.getOsSettingsSnapshot().desktopLayout,W=H=>{Gu(t,H,{openWindow:w.openById,manager:n,deriveWindowId:Z=>oe(Z,e.adminUrl)})};m=Fk({shellRoot:f,shellBody:h,bottomDockEl:p,desktopArea:t,windowManager:n,adminUrl:e.adminUrl,renderIcons:W,getSettings:()=>{const H=d.getOsSettingsSnapshot();return{itemVisibility:H.itemVisibility,dockOrder:H.dockOrder}}},_,e.dockItems,e.desktopIcons),m.appendSystemTile({id:No,title:"OS Settings",icon:"dashicons-desktop",isOpen:()=>{const H=n.getById(No);return H?(H.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:D},"core"),ap()||m.appendSystemTile(D_(e.pwa?.appName||"WordPress",q),"core"),window.matchMedia("(display-mode: standalone)").addEventListener("change",H=>{H.matches&&m?.removeSystemTile("desktop-mode-pwa-install")}),dp().then(H=>{H&&m?.removeSystemTile("desktop-mode-pwa-install")})}function D(_={}){_.tabId==="extended"&&(_={..._,tabId:"features"}),_.tabId&&(d.activeTabId=_.tabId),n.open({id:No,baseId:No,url:"#os-settings",title:"OS Settings",icon:"dashicons-desktop",native:!0,render:W=>d.renderPanel(W),width:820,height:720,minWidth:560,minHeight:480}),_.tabId&&d.focusTab(_.tabId)}function b(){n.open({id:Zn,baseId:Zn,url:`#${Zn}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:_=>h_(_),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("desktop-mode-open-bug-report",()=>{b()}),m&&(m.appendSystemTile({id:Zn,title:"Report a bug",icon:"dashicons-buddicons-replies",isOpen:()=>{const _=n.getById(Zn);return _?(_.config.desktopId||n.getActiveDesktopId())===n.getActiveDesktopId():!1},onOpen:b},"core"),m.appendSystemTile(Py(),"core"));const E=m?.getPrimary()??null;g(Array.isArray(e.nativeWindows)?e.nativeWindows:[]);const I=m0(e.session),O=I?h0(n,e,t).catch(_=>{typeof console<"u"&&console.error("[desktop-mode] session restore failed:",_)}):Promise.resolve(),v=e.defaultWindow?.enabled!==!1,N=e.defaultWindow?.url??"",C=typeof N=="string"&&N.startsWith("native:");g0({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:I,defaultEnabled:v,isNativeDefault:C})&&O.then(()=>w0(n,e).catch(_=>{typeof console<"u"&&console.error("[desktop-mode] openCurrentPage failed:",_)}));const L=b0(n,e);k0(L);const A=async _=>{try{const W=await Gr(n,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:_})},{source:"desktop-mode/default-window"});if(!W.ok)throw new Error(`HTTP ${W.status}`);const H=await W.json();e.defaultWindow=H,document.dispatchEvent(new CustomEvent("desktop-mode-default-window-changed",{detail:H}))}catch(W){T(y.SHELL_ERROR,{scope:"default-window-save",error:W}),typeof console<"u"&&console.error("[desktop-mode] Failed to save default window:",W)}};if(n.onToggleStartupRequested=_=>{const W=e.defaultWindow,H=!!_.config.native,Z=H?`native:${_.id}`:_.getCurrentUrl(),fe=H?W?.url===Z:vd(W?.url??"")===vd(Z),wn=!!W?.enabled&&fe;A(wn?null:Z)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!I&&C){const _=N.slice(7);queueMicrotask(()=>{if(_===No){D();return}w.openById(_)})}const R=_=>{m?.appendSystemTile(_)},F=aA({layer:a});F(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const K=jy({osSettings:d});K(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]);const Y=Xy();Y(Array.isArray(e.serverGames)?e.serverGames:[]);const x=Cb();x(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const $=Tb();$(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const B=Mb();B(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const P=tv();P(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const X=nv();X(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),sv({manager:n,osSettings:d}),ug({manager:n}),Vb({manager:n,osSettings:d}),Zb({manager:n,openUrl:_=>{const W=oe(_.url,e.adminUrl);n.open({id:W,baseId:W,url:_.url,title:_.label,icon:_.icon||"dashicons-admin-links"})}});const M=iv();M(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),dv()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),uv(),pv()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),hv()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),wu(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),Cv()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const se=Nv(n);Kk(n),Ge(()=>Xk()),Bw(),G("desktop-mode.shell.toast","desktop-mode/shell-toast",_=>{!_||typeof _.message!="string"||q({message:_.message,action:_.action,duration:_.duration})});const he=e,Se=he.recycleBinCount;Qk(Number(Se)||0,typeof he.recycleBinCountUrl=="string"?he.recycleBinCountUrl:""),l_({getRecycleBinCount:Zk}),window.__desktopModeConnectionBridge=se,G(y.WINDOW_CLOSED,"desktop-mode/connection-cleanup",_=>{_?.windowId&&se.onWindowClosed(_.windowId)}),G(y.IFRAME_READY,"desktop-mode/connection-rearm",_=>{_?.windowId&&se.onIframeReady(_.windowId)});const be=Ik(n),Yo=f0({layoutDispatcher:m,desktopArea:t,config:e,syncNativeWindows:g,syncServerWidgets:F,syncServerWallpapers:K,syncServerCommands:x,syncServerSettingsTabs:$,syncServerTitleBarButtons:B,syncServerUnfocusEffects:P,syncServerWindowLinkRenderers:X,syncServerDockRailRenderers:M,syncServerGames:Y,renderIcons:_=>{if(m){m.applyDesktopIcons(_);return}Gu(t,_,{openWindow:w.openById,manager:n,deriveWindowId:W=>oe(W,e.adminUrl)})},syncShortcuts:()=>{const _=d.getOsSettingsSnapshot();Vs(_.itemVisibility,_.dockPromotedPositions,_.desktopLayout)}});d.subscribeOsSettings(_=>{if(!m)return;const W=m.getLayout();m.setLayout(_.desktopLayout),hn.dock=m.getPrimary(),hn.sideDock=m.getSide(),hn.desktopLayout=_.desktopLayout,W===_.desktopLayout&&m.refresh(),Vs(_.itemVisibility,_.dockPromotedPositions,_.desktopLayout),df(_.desktopLayout)}),sI(()=>d.getOsSettingsSnapshot().itemVisibility,()=>d.getOsSettingsSnapshot().dockPromotedPositions,()=>d.getOsSettingsSnapshot().desktopLayout),df(d.getOsSettingsSnapshot().desktopLayout);const hn=eS({manager:n,dock:E,layoutDispatcher:m,osSettings:d,iconsApi:Ok,filesApi:Re,saveSession:L,widgetLayer:a,registerWindow:be,openWindowById:w.openById,openNewWindowById:w.openNewById,placeSystemTile:R,setDefaultWindow:A,refreshMenu:Yo,openOsSettings:D,aiAssistant:l,dragBridge:c,dragManager:u,connect:se.connect,getConnection:se.getConnection,wallpaperSuspend:{suspend:_=>i?.suspend(_),resume:_=>i?.resume(_),isSuspended:()=>i?.isSuspended()??!1},config:e});tS(hn),Ge(()=>kA(u)),Yy(),Eb({currentUserId:Number(e.currentUserId)||0}),Ge(()=>qE()),Ge(()=>KE()),Ge(()=>a0({currentUserId:Number(e.currentUserId)||0})),UI({host:t,config:e,available:e.stickyNotes?.available,getActiveDesktopId:()=>n.getActiveDesktopId(),openArtifact:(_,W)=>{const H=oe(_,e.adminUrl);n.open({id:H,baseId:H,url:_,title:W,icon:"dashicons-edit-page"})},onError:_=>{q({message:_})}}),FC({host:t,config:e,onError:_=>{q({message:_})}}),lS({openUrl:({id:_,url:W,title:H,icon:Z})=>(dt(W)||n.open({id:_,baseId:_,url:W,title:H,icon:Z}),!0),openNativeWindow:_=>w.openById(_),deriveWindowId:_=>oe(_,e.adminUrl)}),pf(e.userFileAssociations??{}),sA({update:e.coreUpdate,openUrl:({url:_,title:W})=>{dt(_)||n.open({id:"update-core",baseId:"update-core",url:_,title:W,icon:"dashicons-update"})}});const Zo=({url:_,title:W})=>{if(dt(_))return;const H=oe(_,e.adminUrl);n.open({id:H,baseId:H,url:_,title:W,icon:"dashicons-info"})};if(oh({notices:e.coreNotices,openUrl:Zo}),oh({notices:e.pluginNotices,openUrl:Zo,keyPrefix:"plugin-notice"}),typeof e.filesUrl=="string"&&e.filesUrl){mf({baseUrl:e.filesUrl,nonce:e.restNonce});const _=document.getElementById("desktop-mode-area");if(_){const W=Yf(_,0),H=()=>{t.classList.contains("desktop-mode-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("desktop-mode-area--booting")})},Z=setTimeout(H,2e3);W.hydrated.then(()=>{clearTimeout(Z),H()})}}Ge(()=>EA()),Ge(()=>IA()),Ge(()=>WE()),T(y.COMPONENTS_REGISTERED,{tags:[...ih]}),NE(),P_(e,q);const Oh=()=>{Yh(e.shellOverlaysBundleUrl??""),Vh(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(Oh,{timeout:1500}):window.setTimeout(Oh,0),T(y.INIT,{config:e}),od=!0;const vL=vh.splice(0);for(const _ of vL)try{_()}catch(W){T(y.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()}),_0(),d0(n,e);const Rh=(_,W=!0)=>{const H=Re.store.getState().placementsByFolder.get(0)??[],Z=_(H),fe=Math.max(1,Math.floor((t.clientHeight-16)/110)),wn=new Set;let Rt=0;for(const Ce of Z){const Ae=At(16+Math.floor(Rt/fe)*96,16+Rt%fe*110,wn,t);wn.add(`${Ae.col},${Ae.row}`),Rt++,!(Ce.x===Ae.x&&Ce.y===Ae.y)&&(Re.store.upsertPlacement({...Ce,x:Ae.x,y:Ae.y,sortOrder:Rt}),!(!W||Ws(Ce))&&Qt(Ce.id,{x:Ae.x,y:Ae.y,sortOrder:Rt}).catch(at=>{console.error("[desktop-mode] relayout persist failed",at)}))}},Mh=_=>W=>{const H=W.slice();switch(_){case"name-asc":H.sort((Z,fe)=>Z.file.title.localeCompare(fe.file.title));break;case"name-desc":H.sort((Z,fe)=>fe.file.title.localeCompare(Z.file.title));break;case"date-asc":H.sort((Z,fe)=>Z.updatedAtMs-fe.updatedAtMs);break;case"date-desc":H.sort((Z,fe)=>fe.updatedAtMs-Z.updatedAtMs);break}return H},hd="desktop-mode:root-sort-mode",kL=_=>_==="name-asc"||_==="name-desc"||_==="date-asc"||_==="date-desc";let ai=(()=>{try{const _=window.localStorage.getItem(hd);return kL(_)?_:null}catch{return null}})();const Ph=_=>{ai=_;try{_?window.localStorage.setItem(hd,_):window.localStorage.removeItem(hd)}catch{}};if(G("desktop-mode.files.tile-manually-placed","desktop-mode/root-sort-clear",_=>{_?.folderId===0&&Ph(null)}),typeof ResizeObserver<"u"){let _=t.clientWidth,W=t.clientHeight;new ResizeObserver(()=>{if(!ai)return;const Z=t.clientWidth,fe=t.clientHeight;Z===_&&fe===W||(_=Z,W=fe,Rh(Mh(ai),!1))}).observe(t)}let $h=!1;t.addEventListener("pointerdown",_=>{_.isPrimary&&($h=_.target===t)}),t.addEventListener("click",_=>{d.state.showDesktopOnWallpaperClick&&_.target===t&&$h&&(t.classList.contains("desktop-mode-area--overview")||gh()||u.recentlyEndedDrag()||n.toggleShowDesktop())}),t.addEventListener("contextmenu",_=>{if(_.target!==t)return;_.preventDefault();const W=_.clientX,H=_.clientY;(()=>{if(t.classList.contains("desktop-mode-area--overview"))return;if(gh()){Ao();return}const Z={x:W,y:H},fe=()=>{const Ce=t.getBoundingClientRect(),Ae=Math.max(0,Z.x-Ce.left),at=Math.max(0,Z.y-Ce.top),Jo=Bf(Re.store.getState().placementsByFolder.get(0)??[]);return At(Ae,at,Jo,t)},wn=(Ce,Ae)=>{DA({title:Ce,description:Ae,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:at,url:Jo})=>{const Wh=fe(),_L=await Jt({type:"link",ref:Jo,parentId:0,x:Wh.x,y:Wh.y,meta:at?{name:at}:void 0});Re.store.upsertPlacement(_L)}})},Rt=TA({createFolder:()=>{ha({onSubmit:async Ce=>{const Ae=await ra({name:Ce}),at=fe(),Jo=await Jt({type:"folder",ref:String(Ae.id),parentId:0,x:at.x,y:at.y});Re.store.upsertFolder(Ae),Re.store.upsertPlacement(Jo)}})},createUrl:()=>wn("New URL","Opens the URL in a new browser tab."),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>D(),sortIcons:Ce=>{Ph(Ce),Rh(Mh(Ce))},currentSortMode:ai,includeShowDesktop:!d.state.showDesktopOnWallpaperClick,labels:{createFolder:"New folder",showDesktop:"Show desktop",osSettings:"OS Settings",sortHeading:"Sort by",sortNameAsc:"Name (A → Z)",sortNameDesc:"Name (Z → A)",sortDateAsc:"Date (oldest first)",sortDateDesc:"Date (newest first)",newUrl:"New URL"},serverItems:e.serverWallpaperMenuItems??[]});AA(document.body,{x:W,y:H},Rt)})()}),Promise.resolve().then(()=>bL).then(_=>{_.bootOsFileDrop({config:e.dropConfig,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.desktopStorage})}),document.dispatchEvent(new CustomEvent("desktop-mode-init",{detail:{config:e,restored:I}}))}mA(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",kh):kh();const ie={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"},OA=32;function RA(e){if(!e)return[];const t=[];for(let n=0;n<e.length;n++){const o=e[n];if(o.kind!=="file")continue;const s=typeof o.webkitGetAsEntry=="function"?o.webkitGetAsEntry():null;s&&t.push(s)}return t}function MA(e){const t=e.createReader();return new Promise((n,o)=>{const s=[],i=()=>{t.readEntries(r=>{if(r.length===0){n(s);return}s.push(...r),i()},o)};i()})}function PA(e){return new Promise((t,n)=>{e.file(t,n)})}async function $A(e){const t={files:[],emptyDirs:[],hadDirectory:!1};for(const n of e)await _h(n,"",t,0);return t}async function _h(e,t,n,o){if(o>OA)return;if(e.isFile){try{const r=await PA(e);n.files.push({file:r,relativePath:t?`${t}${r.name}`:""})}catch{}return}if(!e.isDirectory)return;n.hadDirectory=!0;const s=`${t}${e.name}`;let i=[];try{i=await MA(e)}catch{i=[]}if(i.length===0){n.emptyDirs.push(s);return}for(const r of i)await _h(r,`${s}/`,n,o+1)}const Eh=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function Do(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;if(typeof n.includes=="function")return n.includes("Files");if(typeof n.contains=="function")return n.contains("Files");for(let o=0;o<n.length;o++)if(n[o]==="Files")return!0;return!1}function ti(e){const t=e?.closest?.(".desktop-mode-window");if(!t)return;const n=/^wp-window-(.+)$/.exec(t.id||"");return n?n[1]:void 0}function WA(e){if(!e)return;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e){const o=ti(n);return o||n.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0}}function Sh(e){const t=window;if(t.__desktopModeOsFileDropMounted)return t.__desktopModeOsFileDropMounted;if(!e.config.enabled)return FA();const n=UA();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=>{Do(m)&&(m.preventDefault(),o++,n.classList.add("is-active"),r())},d=m=>{if(Do(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(!Do(m))return;if(m.defaultPrevented){i();return}m.preventDefault(),i();const w=RA(m.dataTransfer?.items),g=xh(m);if(w.some(D=>D.isDirectory)){Ih(w,g,e);return}const k=m.dataTransfer?.files?Array.from(m.dataTransfer.files):[];k.length!==0&&rd(k,g,e)},u=()=>i(),p=()=>{document.visibilityState==="hidden"&&i()},f=m=>{if(m.origin!==window.location.origin)return;const w=m.data;if(!w||w.type!=="desktop-mode-os-file-drop"||!Array.isArray(w.files)||w.files.length===0)return;const g=w.files.filter(b=>b instanceof File);if(g.length===0)return;const k=WA(m.source);if(!k)return;const D={surface:"iframe",windowId:k,x:typeof w.x=="number"?w.x:0,y:typeof w.y=="number"?w.y:0};o=0,n.classList.remove("is-active"),rd(g,D,e)};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 h={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 t.__desktopModeOsFileDropMounted=h,h}function UA(){const e=document.querySelector(".desktop-mode-os-drop-overlay");if(e)return e;const t=document.createElement("div");t.className="desktop-mode-os-drop-overlay",t.setAttribute("aria-hidden","true"),t.style.cssText=["position:fixed","inset:0","pointer-events:none","z-index:200","opacity:0","transition:opacity 120ms ease","background:radial-gradient(circle at center, rgba(34,113,177,0.18) 0%, rgba(34,113,177,0.06) 60%, transparent 100%)","box-shadow:inset 0 0 0 3px rgba(34,113,177,0.55)"].join(";");const n=document.createElement("div");n.style.cssText=["position:absolute","top:50%","left:50%","transform:translate(-50%,-50%)","padding:14px 22px","border-radius:12px","background:rgba(20,20,24,0.78)","color:#fff","font:600 14px/1.2 -apple-system,BlinkMacSystemFont,sans-serif","letter-spacing:0.02em"].join(";"),n.textContent="Drop to upload",t.appendChild(n),document.body.appendChild(t);const o=document.createElement("style");return o.textContent=".desktop-mode-os-drop-overlay.is-active{opacity:1!important;}",document.head.appendChild(o),t}function FA(){const e=o=>{if(!Do(o))return;const s=o.target;s?.closest&&Eh.some(i=>s.closest(i))||o.preventDefault()};window.addEventListener("dragover",e),window.addEventListener("drop",e);const t=window,n={dispose:()=>{window.removeEventListener("dragover",e),window.removeEventListener("drop",e),delete t.__desktopModeOsFileDropMounted}};return t.__desktopModeOsFileDropMounted=n,n}function xh(e){const t=e.clientX,n=e.clientY;let o=e.target;for(;o&&o!==document.body;){if(o.classList.contains("desktop-mode-file-tile")&&o.dataset.fileType==="folder"){const s=Number(o.dataset.fileRef??0);if(Number.isFinite(s)&&s>0)return{surface:"folder",folderId:s,x:t,y:n}}if(o.tagName==="IFRAME")return{surface:"iframe",windowId:ti(o),x:t,y:n};if(o.classList.contains("desktop-mode-window")||o.hasAttribute("data-window-id")){const s=ti(o)??(o.getAttribute("data-window-id")||void 0),i=s?/^desktop-mode-folder-(\d+)/.exec(s):null;return i?{surface:"folder",folderId:Number(i[1]),windowId:s,x:t,y:n}:{surface:"window",windowId:s,x:t,y:n}}if(o.dataset?.folderId!==void 0){const s=Number(o.dataset.folderId);return Number.isFinite(s)&&s>0?{surface:"folder",folderId:s,x:t,y:n}:{surface:"wallpaper",x:t,y:n}}if(o.id==="desktop-mode-wallpaper"||o.classList.contains("desktop-mode-wallpaper")||o.classList.contains("desktop-mode-desktop"))return{surface:"wallpaper",x:t,y:n};o=o.parentElement}return{surface:"unknown",x:t,y:n}}async function rd(e,t,n){const o=j(ie.FILES_DETECTED,e,t);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=ad(o,n.config);if(i.length>0&&(T(ie.FILES_REJECTED,{rejections:i,context:t}),q({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:dd(a,d)},c=j(ie.DIALOG_FIELDS,l,t);return!c||typeof c!="object"||!("fields"in c)||typeof c.fields!="object"?l:c});await n.openDialog(r,t)}async function Ih(e,t,n){if(!n.storage?.canUpload||!n.filesUrl){q({message:"Folder uploads need desktop storage, which is not available for your account."});return}const o=await $A(e),s=j(ie.FILES_DETECTED,o.files.map(u=>u.file),t);if(!Array.isArray(s))return;const i=new Set(s),r=o.files.filter(u=>i.has(u.file));if(r.length===0&&o.emptyDirs.length===0)return;const{accepted:a,rejected:d}=ad(r.map(u=>u.file),n.config);d.length>0&&(T(ie.FILES_REJECTED,{rejections:d,context:t}),q({message:d.length===1?d[0].message:`${d.length} files couldn't be uploaded.`}));const l=new Map(r.map(u=>[u.file,u.relativePath])),c=a.map(({file:u,mime:p})=>({file:u,mime:p,fields:dd(u,p),relativePath:l.get(u)??""}));c.length===0&&o.emptyDirs.length===0||await n.openDialog(c,t,{forceDesktop:!0,emptyDirs:o.emptyDirs})}function ad(e,t){const n=[],o=[];for(const s of e){if(s.size===0){o.push({file:s,reason:"empty",message:`“${s.name}” is empty.`});continue}if(t.maxSize>0&&s.size>t.maxSize){o.push({file:s,reason:"size",message:`“${s.name}” exceeds the ${BA(t.maxSize)} upload limit.`});continue}const i=Ch(s,t.allowedMimes,t.extToMime);if(!i){o.push({file:s,reason:"mime",message:`“${s.name}” is not an allowed file type.`});continue}n.push({file:s,mime:i})}return{accepted:n,rejected:o}}function Ch(e,t,n){if(t.length===0)return null;const o=e.type.toLowerCase();if(o&&t.includes(o))return o;const s=Ah(e.name);if(!s)return null;if(n){for(const[r,a]of Object.entries(n))if(r.split("|").includes(s)&&t.includes(a))return a;return null}const i=HA[s];return i&&t.includes(i)?i:null}const HA={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 Ah(e){const t=e.lastIndexOf(".");return t<0?"":e.slice(t+1).toLowerCase()}function dd(e,t){const n=Lh(e.name),o=Ah(n),s=o?n.slice(0,n.length-o.length-1):n,i=Th(s);return{title:i,altText:t.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function Lh(e){return e.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function Th(e){const t=e.replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Upload"}function BA(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}const zA=Object.freeze(Object.defineProperty({__proto__:null,IFRAME_PASSTHROUGH_SELECTORS:Eh,classifyDropTarget:xh,defaultFields:dd,dragHasFiles:Do,handleFiles:rd,handleTreeDrop:Ih,humanize:Th,mountOsFileDropManager:Sh,partitionByPolicy:ad,resolveAllowedMime:Ch,sanitizeFilename:Lh,windowIdFromElement:ti},Symbol.toStringTag,{value:"Module"})),GA=ge`:host{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var( --desktop-mode-text,#1d2327 );min-width:0}:host( [ hidden ] ){display:none}.wpd-text-field__label{font-size:12px;color:var( --desktop-mode-muted,#646970 )}.wpd-text-field__row{position:relative;display:flex;align-items:center;width:100%}input{appearance:none;-webkit-appearance:none;display:block;width:100%;min-width:0;box-sizing:border-box;padding:7px 10px;background:var( --desktop-mode-window-bg,#fff );border:1px solid var( --desktop-mode-border,#dcdcde );border-radius:6px;font:inherit;font-size:13px;color:var( --desktop-mode-text,#1d2327 );transition:border-color 0.12s ease,box-shadow 0.12s ease}.wpd-text-field__suffix{position:absolute;inset-inline-end:10px;top:50%;transform:translateY( -50% );pointer-events:none;font-size:12px;color:var( --desktop-mode-muted,#646970 )}.wpd-text-field__row--has-reveal input{padding-inline-end:36px}.wpd-text-field__reveal{position:absolute;inset-inline-end:0;top:0;bottom:0;width:34px;display:flex;align-items:center;justify-content:center;padding:0;border:none;background:transparent;color:var( --desktop-mode-muted,#646970 );cursor:pointer;border-radius:0 6px 6px 0;transition:color 0.12s ease}.wpd-text-field__reveal:hover{color:var( --wp-admin-theme-color,#2271b1 )}.wpd-text-field__reveal:focus-visible{outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:-2px;border-radius:0 6px 6px 0}.wpd-text-field__reveal:disabled{opacity:0.45;cursor:not-allowed}.wpd-text-field__input--masked{-webkit-text-security:disc;text-security:disc}@supports not ( ( -webkit-text-security:disc ) or ( text-security:disc ) ){.wpd-text-field__input--masked{font-family:text-security-disc,"password",monospace;letter-spacing:0.2em}}input:hover{border-color:var( --desktop-mode-muted,#8c8f94 )}input:focus-visible{outline:none;border-color:var( --wp-admin-theme-color,#2271b1 );box-shadow:0 0 0 1px var( --wp-admin-theme-color,#2271b1 )}input:disabled{opacity:0.55;cursor:not-allowed;background:rgba( 0,0,0,0.03 )}input[ aria-invalid='true' ]{border-color:#d63638}input[ aria-invalid='true' ]:focus-visible{box-shadow:0 0 0 1px #d63638}input[ type='number' ]::-webkit-inner-spin-button,input[ type='number' ]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}input[ type='number' ]{-moz-appearance:textfield}`,Ko=class Ko extends me{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),Vl(this)}render(){const t=this.label||"",n=this.value??"",o=this.placeholder||"",s=this.disabled!==null,i=this.readonly!==null,r=this.autocomplete,a=this.type||"text",d=a==="password";let l=r||"off";d&&(!r||l==="off")&&(l="new-password");const c=this.maxlength,u=this.minlength,p=this.pattern||"",f=this.name||"",h=this.suffix||"",m=this.invalid!==null,w=this.reveal!==null,g=a==="password",k=g&&!(w&&this._revealed);let D;g||w&&this._revealed?D="text":D=a;const b=w?"wpd-text-field__row wpd-text-field__row--has-reveal":"wpd-text-field__row",E=k?"wpd-text-field__input wpd-text-field__input--masked":"wpd-text-field__input",O=`${this.id||"wpd-unnamed"}__input`;return z` |
| 367 |
${t?z`<label |
| 368 |
class="wpd-text-field__label" |
| 369 |
for=${O} |
| 370 |
>${t}</label>`:z``} |
| 371 |
<span class=${b}> |
| 372 |
<input |
| 373 |
id=${O} |
| 374 |
class=${E} |
| 375 |
type=${D} |
| 376 |
.value=${n} |
| 377 |
placeholder=${o} |
| 378 |
?disabled=${s} |
| 379 |
?readonly=${i} |
| 380 |
autocomplete=${l} |
| 381 |
maxlength=${c??""} |
| 382 |
minlength=${u??""} |
| 383 |
pattern=${p} |
| 384 |
name=${f} |
| 385 |
aria-invalid=${m?"true":"false"} |
| 386 |
aria-label=${t||""} |
| 387 |
@input=${v=>this._onInput(v)} |
| 388 |
@change=${v=>this._onChange(v)} |
| 389 |
@keydown=${v=>this._onKeyDown(v)} |
| 390 |
/> |
| 391 |
${h?z`<span class="wpd-text-field__suffix">${h}</span>`:z``} |
| 392 |
${w?this._renderRevealButton(s):z``} |
| 393 |
</span> |
| 394 |
`}_renderRevealButton(t){const n=this._revealed?"Hide":"Show";return z` |
| 395 |
<button |
| 396 |
type="button" |
| 397 |
class="wpd-text-field__reveal" |
| 398 |
aria-label=${n} |
| 399 |
aria-pressed=${this._revealed?"true":"false"} |
| 400 |
?disabled=${t} |
| 401 |
tabindex="0" |
| 402 |
@click=${()=>this._onToggleReveal()} |
| 403 |
> |
| 404 |
${this._revealed?qA():jA()} |
| 405 |
</button> |
| 406 |
`}_onToggleReveal(){this._revealed=!this._revealed,this.requestUpdate()}_onInput(t){const n=t.target;this.value=n.value,this.emit("wpd-input-change",{value:n.value})}_onChange(t){const n=t.target;this.emit("wpd-input-commit",{value:n.value})}_onKeyDown(t){if(t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey){const n=t.target;this.emit("wpd-submit",{value:n.value})}}};Ko.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],Ko.styles=[GA],Ko.help=void 0;let ld=Ko;we("wpd-text-field",ld);function jA(){return z` |
| 407 |
<svg |
| 408 |
viewBox="0 0 16 16" |
| 409 |
width="14" |
| 410 |
height="14" |
| 411 |
fill="none" |
| 412 |
stroke="currentColor" |
| 413 |
stroke-width="1.5" |
| 414 |
stroke-linecap="round" |
| 415 |
stroke-linejoin="round" |
| 416 |
aria-hidden="true" |
| 417 |
focusable="false" |
| 418 |
> |
| 419 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 420 |
<circle cx="8" cy="8" r="2" /> |
| 421 |
</svg> |
| 422 |
`}function qA(){return z` |
| 423 |
<svg |
| 424 |
viewBox="0 0 16 16" |
| 425 |
width="14" |
| 426 |
height="14" |
| 427 |
fill="none" |
| 428 |
stroke="currentColor" |
| 429 |
stroke-width="1.5" |
| 430 |
stroke-linecap="round" |
| 431 |
stroke-linejoin="round" |
| 432 |
aria-hidden="true" |
| 433 |
focusable="false" |
| 434 |
> |
| 435 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 436 |
<circle cx="8" cy="8" r="2" /> |
| 437 |
<line x1="2" y1="2" x2="14" y2="14" /> |
| 438 |
</svg> |
| 439 |
`}async function VA(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=j(ie.BEFORE_UPLOAD,t,e.context);if(!n)throw new cd;const o=new FormData,s=n.fields.filename!==n.file.name?new File([n.file],n.fields.filename,{type:n.mime||n.file.type}):n.file;return o.append("file",s),o.append("title",n.fields.title),o.append("alt_text",n.fields.altText),o.append("caption",n.fields.caption),o.append("description",n.fields.description),new Promise((i,r)=>{const a=new XMLHttpRequest;a.open("POST",e.mediaUrl,!0),a.withCredentials=!0,a.setRequestHeader("X-WP-Nonce",e.restNonce),a.responseType="text";let d=!1,l=!1,c=!1;const u=()=>{if(c=!0,!l){d=!0;try{a.abort()}catch{}}};T(ie.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:u}),a.upload.addEventListener("progress",p=>{T(ie.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:p.loaded,total:p.lengthComputable?p.total:0,indeterminate:!p.lengthComputable})}),a.upload.addEventListener("load",()=>{l=!0,T(ie.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:n.file.size,total:n.file.size,indeterminate:!1})}),a.addEventListener("error",()=>{if(d)return;const p=new Error("Network error during upload.");T(ie.UPLOAD_FAILED,{file:n.file,error:p,context:e.context}),r(p)}),a.addEventListener("abort",()=>{const p=new ni;T(ie.UPLOAD_FAILED,{file:n.file,error:p,context:e.context}),r(p)}),a.addEventListener("load",()=>{if(d)return;if(a.status<200||a.status>=300){const h=XA(a),m=new Error(h);T(ie.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}let p;try{p=JSON.parse(a.responseText)}catch(h){const m=h instanceof Error?h:new Error("Could not parse server response.");T(ie.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}if(c&&p.id){KA(e.mediaUrl,e.restNonce,p.id);const h=new ni;T(ie.UPLOAD_FAILED,{file:n.file,error:h,context:e.context}),r(h);return}const f={id:p.id,url:p.source_url,mime:p.mime_type||n.mime,title:p.title?.rendered||n.fields.title,filename:p.media_details?.file||n.fields.filename};T(ie.AFTER_UPLOAD,{file:n.file,result:f,fields:n.fields,context:e.context}),i(f)}),a.send(o)})}class cd extends Error{constructor(){super("Upload cancelled by desktop-mode.drop.before-upload filter."),this.name="UploadCancelledError"}}class ni extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function KA(e,t,n){const o=`${e.replace(/\/$/,"")}/${n}?force=true`,s=new XMLHttpRequest;return s.open("DELETE",o,!0),s.withCredentials=!0,s.setRequestHeader("X-WP-Nonce",t),new Promise(i=>{s.addEventListener("loadend",()=>{(s.status<200||s.status>=300)&&console.warn(`[os-file-drop] late-cancel cleanup failed for attachment ${n} (HTTP ${s.status}). The attachment remains in the Media Library; delete it manually.`),i()}),s.addEventListener("error",()=>{console.warn(`[os-file-drop] late-cancel cleanup network error for attachment ${n}. The attachment remains in the Media Library; delete it manually.`),i()});try{s.send()}catch(r){console.warn(`[os-file-drop] late-cancel cleanup could not be dispatched for attachment ${n}:`,r),i()}})}function XA(e){const t=`Upload failed (HTTP ${e.status}).`,n=e.responseText;if(!n)return t;try{const o=JSON.parse(n);if(o&&typeof o.message=="string")return o.message}catch{}return t}async function YA(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=j(ie.BEFORE_UPLOAD,t,e.context);if(!n)throw new cd;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;o.append("file",s),o.append("parentId",String(e.parentId)),e.relativePath&&o.append("relativePath",e.relativePath),e.coords&&(o.append("x",String(e.coords.x)),o.append("y",String(e.coords.y)));const i=`${e.filesUrl.replace(/\/$/,"")}/uploads`;return new Promise((r,a)=>{const d=new XMLHttpRequest;d.open("POST",i,!0),d.withCredentials=!0,d.setRequestHeader("X-WP-Nonce",e.restNonce),d.responseType="text";let l=!1;const c=()=>{l=!0;try{d.abort()}catch{}};T(ie.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:c}),d.upload.addEventListener("progress",p=>{T(ie.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:p.loaded,total:p.lengthComputable?p.total:0,indeterminate:!p.lengthComputable})});const u=p=>{T(ie.UPLOAD_FAILED,{file:n.file,error:p,context:e.context}),a(p)};d.addEventListener("error",()=>{l||u(new Error("Network error during upload."))}),d.addEventListener("abort",()=>u(new ni)),d.addEventListener("load",()=>{if(l)return;if(d.status<200||d.status>=300){u(new Error(ZA(d,n.file.name)));return}let p;try{p=JSON.parse(d.responseText)}catch{u(new Error("Could not parse server response."));return}if(!p.placement||typeof p.storedFileId!="number"){u(new Error("Unexpected server response."));return}Ps(p.placement,"local");const f={placement:p.placement,storedFileId:p.storedFileId};T(ie.AFTER_UPLOAD,{file:n.file,result:f,fields:n.fields,context:e.context}),r(f)}),d.send(o)})}function ZA(e,t){if(e.status===413)return`“${t}” is larger than this server accepts.`;const n=`Upload failed (HTTP ${e.status}).`,o=e.responseText;if(!o)return n;try{const s=JSON.parse(o);if(s&&typeof s.message=="string"&&s.message)return s.message}catch{}return n}function JA(e,t){const n=Math.max(0,Math.round((e-16)/96)),o=Math.max(0,Math.round((t-16)/110));return{x:16+n*96,y:16+o*110}}const QA=/^(image|video|audio)\//;function ud(e){return e.desktopAllowed?e.forceDesktop||e.preferDesktop?"desktop":e.surface==="window"||e.surface==="iframe"?"media":(e.folderId??0)>0?"desktop":e.mimes.length>0&&e.mimes.every(n=>QA.test(n))?"media":"desktop":"media"}let Ot=null;async function eL(e){if(e.entries.length===0&&!e.emptyDirs?.length)return;if(Ot){Ot.replace(e);return}const t=!!(e.storage?.canUpload&&e.filesUrl);let n=ud({desktopAllowed:t,surface:e.context.surface,folderId:e.context.folderId,forceDesktop:e.forceDesktop,preferDesktop:e.preferDesktop,mimes:e.entries.map(c=>c.mime)});const o=document.createElement("wpd-modal");o.setAttribute("open",""),o.setAttribute("size","md"),document.body.appendChild(o);const s=()=>{const c=e.entries.length;let u="Media Library";n==="desktop"&&(u=(e.context.folderId??0)>0?"this folder":"Desktop");let p=`Upload ${c} files to ${u}`;c===0?p=(e.context.folderId??0)>0?"Create folders in this folder":"Create folders on Desktop":c===1&&(p=`Upload to ${u}`),o.setAttribute("title",p)};s();const i=e.entries.map(c=>({...c.fields})),r=()=>{if(o.innerHTML="",t&&!e.forceDesktop){const m=document.createElement("div");m.style.cssText="display:flex;align-items:center;gap:10px;margin-bottom:14px;";const w=document.createElement("span");w.textContent="Upload to",w.style.cssText="font-weight:600;",m.appendChild(w);const g=document.createElement("wpd-segmented");g.setAttribute("value",n),g.setAttribute("label","Destination"),g.style.setProperty("--wpd-segmented-bg","rgba(255,255,255,0.06)");const k=document.createElement("wpd-segment");k.setAttribute("value","desktop"),k.textContent="Desktop",g.appendChild(k);const D=document.createElement("wpd-segment");D.setAttribute("value","media"),D.textContent="Media Library",g.appendChild(D),g.addEventListener("wpd-pick",b=>{n=b.detail.value,s(),r()}),m.appendChild(g),o.appendChild(m)}else if(e.forceDesktop){const m=document.createElement("div");m.style.cssText="opacity:0.7;font-size:12px;margin-bottom:14px;",m.textContent="Folder uploads land in your desktop storage, preserving the folder structure.",o.appendChild(m)}const c=n==="desktop"?e.storage?.maxBytes??0:e.mediaMaxBytes??0;if(c>0){const m=document.createElement("div");m.className="desktop-mode-upload-dialog__max-size",m.style.cssText="opacity:0.6;font-size:12px;margin-bottom:14px;",m.textContent=`Maximum file size: ${on(c)}`,o.appendChild(m)}const u=document.createElement("div");u.style.cssText="display:flex;flex-direction:column;gap:18px;max-height:60vh;overflow:auto;padding-right:6px;",e.entries.forEach((m,w)=>{u.appendChild(a(m,i[w],w+1))}),o.appendChild(u);const p=document.createElement("div");p.setAttribute("slot","footer"),p.style.cssText="display:flex;gap:8px;justify-content:flex-end;";const f=document.createElement("wpd-button");f.setAttribute("variant","secondary"),f.textContent="Cancel",f.addEventListener("click",()=>{o.remove()});const h=document.createElement("wpd-button");h.setAttribute("variant","primary"),e.entries.length===0?h.textContent="Create folders":h.textContent=e.entries.length===1?"Upload":`Upload ${e.entries.length} files`,h.addEventListener("click",()=>{d(h,f)}),p.appendChild(f),p.appendChild(h),o.appendChild(p)},a=(c,u,p)=>{const f=document.createElement("div");f.style.cssText="display:flex;flex-direction:column;gap:8px;border:1px solid rgba(255,255,255,0.08);border-radius:10px;padding:14px;";const h=document.createElement("div");h.style.cssText="display:flex;gap:10px;align-items:center;font-weight:600;";const m=document.createElement("span");m.textContent=e.entries.length===1?"":`#${p} · `,m.style.opacity="0.6";const w=document.createElement("span");w.textContent=c.file.name,w.style.cssText="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const g=document.createElement("span");if(g.textContent=`${c.mime||"unknown"} · ${on(c.file.size)}`,g.style.cssText="opacity:0.6;font-size:12px;",h.appendChild(m),h.appendChild(w),h.appendChild(g),f.appendChild(h),n==="desktop"){if(c.relativePath){const k=document.createElement("div");k.textContent=c.relativePath,k.style.cssText="opacity:0.55;font-size:12px;",f.appendChild(k)}return f.appendChild(Oo("Filename",u.filename,k=>u.filename=k)),f}return f.appendChild(Oo("Title",u.title,k=>u.title=k)),f.appendChild(Oo("Filename",u.filename,k=>u.filename=k)),c.mime.startsWith("image/")&&f.appendChild(Oo("Alt text",u.altText,k=>u.altText=k)),f.appendChild(Oo("Caption",u.caption,k=>u.caption=k)),f.appendChild(tL("Description",u.description,k=>u.description=k)),f},d=async(c,u)=>{Ot===l&&(Ot=null),c.disabled=!0,u.disabled=!0,c.textContent="Uploading…";const p=e.entries.length;let f=0,h=0,m=0;const w=[],g=e.context.folderId??0;let k=!1;for(let D=0;D<p;D++){const b=e.entries[D];try{if(n==="desktop"&&e.filesUrl){const I=!b.relativePath&&!k&&e.context.surface==="wallpaper"?JA(e.context.x,e.context.y):void 0;I&&(k=!0),await YA({file:b.file,mime:b.mime,fields:i[D],context:e.context,filesUrl:e.filesUrl,restNonce:e.restNonce,parentId:g,relativePath:b.relativePath??"",coords:I})}else await VA({file:b.file,mime:b.mime,fields:i[D],context:e.context,mediaUrl:e.mediaUrl,restNonce:e.restNonce});f++}catch(E){if(E instanceof cd){m++;continue}if(E instanceof ni){m++;continue}h++;const I=E instanceof Error?E.message:"Upload failed.";w.push(`“${b.file.name}” — ${I}`)}}if(n==="desktop"&&e.emptyDirs?.length)for(const D of e.emptyDirs)try{await Of(g,D)}catch{}o.remove(),nL({total:p,successes:f,failures:h,cancelled:m,failureDetails:w,destination:n})},l={replace:c=>{e.entries=c.entries,e.emptyDirs=c.emptyDirs,e.forceDesktop=c.forceDesktop,e.preferDesktop=c.preferDesktop,e.context=c.context,e.mediaMaxBytes=c.mediaMaxBytes??e.mediaMaxBytes,i.length=0;for(const u of c.entries)i.push({...u.fields});n=ud({desktopAllowed:t,surface:c.context.surface,folderId:c.context.folderId,forceDesktop:c.forceDesktop,preferDesktop:c.preferDesktop,mimes:c.entries.map(u=>u.mime)}),s(),r()}};Ot=l,r(),await new Promise(c=>{const u=()=>{Ot===l&&(Ot=null),c()};o.addEventListener("wpd-modal-cancel",()=>{o.remove(),u()});const p=new MutationObserver(()=>{o.isConnected||(p.disconnect(),u())});p.observe(document.body,{childList:!0,subtree:!0})})}function Oo(e,t,n){const o=document.createElement("wpd-text-field");return o.setAttribute("label",e),o.setAttribute("value",t),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function tL(e,t,n){const o=document.createElement("wpd-textarea");return o.setAttribute("label",e),o.setAttribute("value",t),o.setAttribute("rows","3"),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function nL(e){const{total:t,successes:n,failures:o,cancelled:s,failureDetails:i}=e,r=e.destination==="desktop"?"your desktop":"Media Library";if(t===0){e.destination==="desktop"&&q({message:"Folder created on your desktop."});return}if(t===1){n===1?q({message:`Uploaded to ${r}.`}):o===1&&i[0]?q({message:i[0]}):s===1&&q({message:"Upload cancelled."});return}if(n===t){q({message:`Uploaded ${n} files to ${r}.`});return}if(s===t){q({message:"All uploads cancelled."});return}if(o===t){q({message:o===1&&i[0]?i[0]:`${o} uploads failed.`});return}const a=[];n>0&&a.push(`Uploaded ${n} file${n===1?"":"s"}.`),s>0&&a.push(`Cancelled ${s}.`),o>0&&a.push(`Failed ${o}.`),q({message:a.join(" ")})}const Nh=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:eL,resolveDefaultDestination:ud},Symbol.toStringTag,{value:"Module"})),oL={tab:null,requestedAt:0};let oi=null;function pd(){if(oi)return oi;const t=window.wp?.desktop?.createSharedStore;return typeof t!="function"?null:(oi=t("desktop-mode/plugins-window/tab-target",()=>({...oL})),oi)}function sL(e){const t=pd();if(t){t.state.tab=e,t.state.requestedAt=Date.now(),t.notify();return}const n=window;n._wpdPluginsWindowTab={tab:e,requestedAt:Date.now()}}function iL(){const e=pd();if(e){const o=e.state.tab;return o!==null&&(e.state.tab=null,e.state.requestedAt=0,e.notify()),o}const t=window,n=t._wpdPluginsWindowTab;return n?(t._wpdPluginsWindowTab={tab:null,requestedAt:0},n.tab):null}function rL(e){const t=pd();return t?t.subscribe(n=>e({...n})):()=>{}}const aL=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:iL,setPluginsWindowTab:sL,subscribePluginsWindowTab:rL},Symbol.toStringTag,{value:"Module"})),dL=ge`:host{display:block;--wpd-progress-track-bg:var( --desktop-mode-control-bg,rgba( 0,0,0,0.08 ) );--wpd-progress-fill:var( --wp-admin-theme-color,#2271b1 );--wpd-progress-height:6px;--wpd-progress-radius:999px;--wpd-progress-label-color:inherit;--wpd-progress-label-size:12px;--wpd-progress-label-gap:4px;width:100%;font:inherit;color:var( --wpd-progress-label-color )}:host( [ hidden ] ){display:none}.header{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:var( --wpd-progress-label-gap );font-size:var( --wpd-progress-label-size );line-height:1.3}.label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.percent{font-variant-numeric:tabular-nums;opacity:0.75;flex-shrink:0}.track{position:relative;width:100%;height:var( --wpd-progress-height );background:var( --wpd-progress-track-bg );border-radius:var( --wpd-progress-radius );overflow:hidden}.fill{position:absolute;inset-block:0;inset-inline-start:0;width:0;background:var( --wpd-progress-fill );border-radius:inherit;transition:width 0.18s ease-out}:host( [ tone='success' ] ){--wpd-progress-fill:var( --desktop-mode-status-success,#3a8a3a )}:host( [ tone='warning' ] ){--wpd-progress-fill:var( --desktop-mode-status-warning,#dba617 )}:host( [ tone='danger' ] ){--wpd-progress-fill:var( --desktop-mode-status-danger,#d63638 )}:host( [ indeterminate ] ) .fill{width:33%;animation:wpd-progress-sweep 1.1s linear infinite;transition:none}@keyframes wpd-progress-sweep{0%{transform:translateX( -120% )}100%{transform:translateX( 320% )}}@media ( prefers-reduced-motion:reduce ){.fill{transition:none}:host( [ indeterminate ] ) .fill{animation:none;width:100%;opacity:0.6}}`,Xo=class Xo extends me{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return z`<div class="root" part="root"> |
| 440 |
<div class="header" part="header" hidden> |
| 441 |
<span class="label" part="label"></span> |
| 442 |
<span class="percent" part="percent"></span> |
| 443 |
</div> |
| 444 |
<div class="track" part="track"> |
| 445 |
<div class="fill" part="fill"></div> |
| 446 |
</div> |
| 447 |
</div>`}requestUpdate(){super.requestUpdate(),queueMicrotask(()=>this._paint())}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paint())}_paint(){const t=this.shadowRoot;if(!t)return;const n=this._readMax(),o=this.hasAttribute("indeterminate")||n<=0,s=o?0:this._readValue(n),i=o?0:s/n,r=Math.round(i*100),a=this.getAttribute("label")??"",d=this.hasAttribute("show-percent"),l=t.querySelector(".fill");l&&!o?l.style.width=`${(i*100).toFixed(2)}%`:l&&o&&l.style.removeProperty("width");const c=t.querySelector(".header"),u=t.querySelector(".label"),p=t.querySelector(".percent");if(c&&u&&p){const h=a||d&&!o;c.hidden=!h,u.textContent=a,p.hidden=!(d&&!o),p.textContent=`${r}%`}this._syncAria(n,s,o,a);const f=t.querySelector(".track");f&&(f.setAttribute("role","progressbar"),f.setAttribute("aria-valuemin","0"),o?(f.removeAttribute("aria-valuenow"),f.removeAttribute("aria-valuemax")):(f.setAttribute("aria-valuemax",String(n)),f.setAttribute("aria-valuenow",String(s))),a?f.setAttribute("aria-label",a):f.removeAttribute("aria-label"))}_syncAria(t,n,o,s){this.setAttribute("role","progressbar"),this.setAttribute("aria-valuemin","0"),o?(this.removeAttribute("aria-valuenow"),this.removeAttribute("aria-valuemax")):(this.setAttribute("aria-valuemax",String(t)),this.setAttribute("aria-valuenow",String(n)));const i=this.getAttribute("aria-label");s?(i===null||i===this._ownedAriaLabel)&&(this.setAttribute("aria-label",s),this._ownedAriaLabel=s):i!==null&&i===this._ownedAriaLabel&&(this.removeAttribute("aria-label"),this._ownedAriaLabel=null)}_readMax(){const t=this.getAttribute("max");if(t===null)return 100;const n=parseFloat(t);return Number.isFinite(n)?n:100}_readValue(t){const n=parseFloat(this.getAttribute("value")??"0");return!Number.isFinite(n)||n<0?0:n>t?t:n}};Xo.props=["value","max","indeterminate","tone","label","showPercent"],Xo.styles=[dL],Xo.help=void 0;let fd=Xo;we("wpd-progress-bar",fd);const je=new Map;let rt=null;function lL(){if(document.body.hasAttribute("data-desktop-mode-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const e="desktop-mode/os-file-drop-hud";G(ie.UPLOAD_STARTED,e,t=>cL(t.file,t.fields,t.abort)),G(ie.UPLOAD_PROGRESS,e,t=>uL(t.file,t.loaded,t.total,t.indeterminate)),G(ie.AFTER_UPLOAD,e,t=>pL(t.file,t.fields,t.result)),G(ie.UPLOAD_FAILED,e,t=>fL(t.file,t.error))}function cL(e,t,n){const o=mL(),s=document.createElement("div");s.className="desktop-mode-upload-hud__row";const i=document.createElement("div");i.className="desktop-mode-upload-hud__meta";const r=document.createElement("div");r.className="desktop-mode-upload-hud__name",r.textContent=t.filename||e.name,r.title=t.filename||e.name;const a=document.createElement("div");a.className="desktop-mode-upload-hud__status",a.textContent="Uploading…",i.append(r,a);const d=document.createElement("wpd-progress-bar");d.setAttribute("indeterminate",""),d.setAttribute("show-percent","");const 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=je.get(e);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):md(u))}),l.appendChild(c),s.append(i,d,l),o.querySelector(".desktop-mode-upload-hud__list").appendChild(s),je.set(e,{file:e,abort:n,root:s,bar:d,statusEl:a,cancelBtn:c,state:"running",lingerTimer:null}),si()}function uL(e,t,n,o){const s=je.get(e);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${on(t)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(t)),s.statusEl.textContent=`${on(t)} / ${on(n)}`))}function pL(e,t,n){const o=je.get(e);o&&(o.state="success",o.bar.removeAttribute("indeterminate"),o.bar.setAttribute("value","100"),o.bar.setAttribute("max","100"),o.bar.setAttribute("tone","success"),o.statusEl.textContent="Uploaded",o.cancelBtn.textContent="Dismiss",o.lingerTimer=setTimeout(()=>md(o),2500),si(),ve.publish("desktop-mode/upload-hud-complete",{filename:t.filename||n.filename,attachmentId:n.id}))}function fL(e,t){const n=je.get(e);n&&(n.bar.removeAttribute("indeterminate"),n.bar.setAttribute("tone","danger"),n.cancelBtn.textContent="Dismiss",n.cancelBtn.disabled=!1,t.name==="UploadAbortedError"?(n.state="aborted",n.statusEl.textContent="Cancelled"):(n.state="failed",n.statusEl.textContent=t.message||"Upload failed"),si())}function md(e){e.lingerTimer&&clearTimeout(e.lingerTimer),je.delete(e.file),e.root.remove(),si(),je.size===0&&rt&&(rt.hidden=!0)}function mL(){if(rt&&rt.isConnected)return rt.hidden=!1,rt;const e=document.createElement("div");e.className="desktop-mode-upload-hud",e.setAttribute("role","region"),e.setAttribute("aria-label","Uploads");const t=document.createElement("div");t.className="desktop-mode-upload-hud__header";const n=document.createElement("div");n.className="desktop-mode-upload-hud__title",n.textContent="Uploads";const o=document.createElement("button");o.type="button",o.className="desktop-mode-upload-hud__close",o.setAttribute("aria-label","Hide upload panel"),o.textContent="×",o.addEventListener("click",()=>{for(const i of[...je.values()])i.state!=="running"&&md(i);je.size===0&&(e.hidden=!0)}),t.append(n,o);const s=document.createElement("div");return s.className="desktop-mode-upload-hud__list",e.append(t,s),document.body.appendChild(e),rt=e,e}function si(){if(!rt)return;const e=rt.querySelector(".desktop-mode-upload-hud__title");if(!e)return;const t=je.size,n=[...je.values()].filter(o=>o.state==="running").length;n>0?e.textContent=n===t?`Uploading ${n} file${n===1?"":"s"}…`:`${n} of ${t} uploading…`:t>0?e.textContent=`Uploads (${t})`:e.textContent="Uploads"}function hL(){if(document.body.hasAttribute("data-desktop-mode-suppress-media-library-refresh"))return;const e=window;e.__wpdMediaLibraryRefresher||(e.__wpdMediaLibraryRefresher=!0,G(ie.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>wL()))}function wL(){const e=document.querySelectorAll("iframe");for(const t of Array.from(e))if(gL(Dh(t)))try{t.contentWindow?.location.reload()}catch{const n=Dh(t);n&&t.setAttribute("src",n)}}function Dh(e){try{return e.contentWindow?.location.href??e.src??""}catch{return e.src??""}}function gL(e){return e?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(e):!1}function yL(e){const t=e.config||{enabled:!1,allowedMimes:[],maxSize:0};lL(),hL(),Sh({config:t,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.storage,openDialog:async(n,o,s)=>{const{openUploadDialog:i}=await Promise.resolve().then(()=>Nh);await i({entries:n,context:o,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.storage,forceDesktop:s?.forceDesktop,emptyDirs:s?.emptyDirs,mediaMaxBytes:t.maxSize})}})}const bL=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:ie,bootOsFileDrop:yL},Symbol.toStringTag,{value:"Module"}));return di.clampGeometryToViewport=Qp,Object.defineProperty(di,Symbol.toStringTag,{value:"Module"}),di}({}); |
| 448 |
|