PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.13
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.13
1.1.13 1.1.12 1.1.11 1.1.10 1.1.9 1.1.8 1.1.7 1.1.6 1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.1 1.0.0 0.9.8 0.9.7 0.9.6 0.9.4 0.9.5 0.9.3 0.9.2 0.9.1 0.9.0 All 37 releases
desktop-mode / assets / js / desktop.min.js

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

72 lines 696.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var openStation=function(wa){"use strict";var ya=typeof document<"u"?document.currentScript:null;function At(){const e=window.wp?.hooks;if(!e)throw new Error("[openstation] `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 lt(e,t,n,o){At().addFilter(e,t,n,o)}function ee(e,t,n,o){At().addAction(e,t,n,o)}function Ct(e,t){return At().removeAction(e,t)}function LE(e,t){return At().removeFilter(e,t)}function Q(e,t,...n){return At().applyFilters(e,t,...n)}function L(e,...t){At().doAction(e,...t)}function Lu(e){return At().didAction(e)}function TE(){return At()}const y={INIT:"os.init",WALLPAPERS:"os.wallpapers",GAMES:"os.games",UNFOCUS_EFFECTS:"os.unfocus-effects",WINDOW_REVEALS:"os.window-reveals",WALLPAPER_MOUNTING:"os.wallpaper.mounting",WALLPAPER_MOUNTED:"os.wallpaper.mounted",WALLPAPER_UNMOUNTING:"os.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"os.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"os.wallpaper.visibility",WALLPAPER_SUSPEND:"os.wallpaper.suspend",WALLPAPER_PREVIEW_PARAMS:"os.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"os.wallpaper.settings-changed",IFRAME_READY:"os.iframe.ready",IFRAME_ERROR:"os.iframe.error",IFRAME_NETWORK_COMPLETED:"os.iframe.network-completed",SHELL_ERROR:"os.shell.error",BROADCAST:"os.broadcast",MONITOR_ENTRY:"os.monitor.entry",WALLPAPER_SURFACES:"os.wallpaper.surfaces",DESKTOP_THEME_CHANGED:"os.os-theme.changed",DESKTOP_THEME_ICON:"os.os-theme.icon",DESKTOP_THEME_ICON_COLOR:"os.os-theme.icon-color",WALLPAPERS_SERVER_CHANGED:"os.wallpapers.server-changed",EXTENDED_OPTIONS_CHANGED:"os.extended-options.changed",WINDOW_GEOMETRY:"os.window.geometry",WINDOW_OPENED:"os.window.opened",WINDOW_CONTENT_LOADING:"os.window.content-loading",WINDOW_CONTENT_LOADED:"os.window.content-loaded",WINDOW_LOADING_OVERLAY:"os.window.loading-overlay",WINDOW_REOPENED:"os.window.reopened",WINDOW_MENU_OPENED:"os.window.menu-opened",WINDOW_CLOSING:"os.window.closing",WINDOW_CLOSED:"os.window.closed",WINDOW_FOCUSED:"os.window.focused",WINDOW_BLURRED:"os.window.blurred",WINDOW_MINIMIZED:"os.window.minimized",WINDOW_RESTORED:"os.window.restored",WINDOW_CHILD_BLOCKED:"os.window.child-blocked",WINDOW_MAXIMIZED:"os.window.maximized",WINDOW_UNMAXIMIZED:"os.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"os.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"os.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"os.window.auto-exit-fullscreen",WINDOW_FOCUS_ON_DRAG_HOVER:"os.window.focus-on-drag-hover",WINDOW_BOUNDS_CHANGED:"os.window.bounds-changed",WINDOW_MOVED:"os.window.moved",WINDOW_RESIZED:"os.window.resized",WINDOW_DRAG_START:"os.window.drag-start",WINDOW_DRAG_END:"os.window.drag-end",WINDOW_RESIZE_START:"os.window.resize-start",WINDOW_RESIZE_END:"os.window.resize-end",WINDOW_DETACHED:"os.window.detached",WINDOW_RELOADED:"os.window.reloaded",WINDOW_TITLE_CHANGED:"os.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"os.window.highlight-changed",WINDOW_BODY_RESIZED:"os.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"os.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"os.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"os.native-window.before-close",WINDOW_CHROME_THEME:"os.window.chrome.theme",WINDOW_CHROME_CONTROLS:"os.window.chrome.controls",WINDOW_CHROME_SLOT:"os.window.chrome.slot",WINDOW_CHROME_RENDER:"os.window.chrome.render",WINDOW_CHROME_APPLIED:"os.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"os.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"os.os-icon.clicked",DESKTOP_ICONS_RENDERED:"os.os-icons.rendered",ICON_BADGE_CHANGED:"os.icon.badge-changed",COMPONENTS_REGISTERED:"os.components.registered",DOCK_ITEM_APPENDED:"os.dock.item-appended",DOCK_ITEM_REMOVED:"os.dock.item-removed",DOCK_BEFORE_RENDER:"os.dock.before-render",DOCK_AFTER_RENDER:"os.dock.after-render",DOCK_REFRESH_ACTIVE:"os.dock.refresh-active",DOCK_TILE_CLASS:"os.dock.tile-class",DOCK_TILE_ELEMENT:"os.dock.tile-element",DOCK_TILE_RENDERED:"os.dock.tile-rendered",DOCK_TILE_TOOLTIP:"os.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"os.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"os.dock.peek-card-element",CONSTELLATION_PANEL:"os.constellation.panel",CONSTELLATION_OPENED:"os.constellation.opened",CONSTELLATION_CLOSED:"os.constellation.closed",OVERVIEW_ENTERING:"os.overview.entering",OVERVIEW_ENTERED:"os.overview.entered",OVERVIEW_EXITING:"os.overview.exiting",OVERVIEW_EXITED:"os.overview.exited",OVERVIEW_WINDOW_HOVER:"os.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"os.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"os.overview.window-click",WORK_AREA_CHANGED:"os.work-area.changed",ARRANGE_CASCADE_STARTING:"os.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"os.arrange.cascade.applied",ARRANGE_TILE_STARTING:"os.arrange.tile.starting",ARRANGE_TILE_APPLIED:"os.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"os.arrange.tile.dimensions",ARRANGE_COLUMNS_STARTING:"os.arrange.columns.starting",ARRANGE_COLUMNS_APPLIED:"os.arrange.columns.applied",ARRANGE_FOCUS_SPLIT:"os.arrange.focus.split",ARRANGE_FOCUS_STARTING:"os.arrange.focus.starting",ARRANGE_FOCUS_APPLIED:"os.arrange.focus.applied",ARRANGE_SNAP_CHANGED:"os.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"os.arrange.snap.cell-size",POINTER_SHAKE:"os.pointer.shake",GRID_SNAP_DIMENSIONS:"os.grid-snap.dimensions",GRID_SNAP_ARMED:"os.grid-snap.armed",GRID_SNAP_CHANGED:"os.grid-snap.changed",GRID_SNAP_ANCHOR_RESET:"os.grid-snap.anchor-reset",GRID_SNAP_CANCELED:"os.grid-snap.canceled",GRID_SNAP_COMMITTED:"os.grid-snap.committed",GRID_SNAP_REFLOWED:"os.grid-snap.reflowed",SNAP_ZONE_PENDING:"os.snap.zone-pending",SNAP_ZONE_CANCELED:"os.snap.zone-canceled",SNAP_ZONE_COMMITTED:"os.snap.zone-committed",SNAP_SPLIT_FILLED:"os.snap.split-filled",WIDGETS:"os.widgets",WIDGET_MOUNTING:"os.widget.mounting",WIDGET_MOUNTED:"os.widget.mounted",WIDGET_UNMOUNTING:"os.widget.unmounting",WIDGET_MOUNT_FAILED:"os.widget.mount-failed",WIDGET_ADDED:"os.widget.added",WIDGET_REMOVED:"os.widget.removed",DESKTOP_CREATED:"os.os.created",DESKTOP_CLOSED:"os.os.closed",DESKTOP_SWITCHED:"os.os.switched",DESKTOP_RENAMED:"os.os.renamed",WINDOW_DESKTOP_CHANGED:"os.os.window-moved",PRIMARY_DESKTOP_ID:"os.primary-desktop-id",WORKSPACE_PRESETS:"os.workspaces.presets",WORKSPACE_PROFILE:"os.workspaces.profile",WORKSPACE_UPDATED:"os.workspaces.updated",WORKSPACE_PROVISIONED:"os.workspaces.provisioned",WINDOWS_BEFORE_CLOSE_ALL:"os.windows.before-close-all",WINDOWS_CLOSE_ALL:"os.windows.close-all",WINDOWS_AFTER_CLOSE_ALL:"os.windows.after-close-all",COMMAND_BEFORE_RUN:"os.command.before-run",COMMAND_AFTER_RUN:"os.command.after-run",COMMAND_ERROR:"os.command.error",SHELL_RESIZED:"os.shell.resized",SHELL_VISIBILITY:"os.shell.visibility",CONNECTION_OPENED:"os.connection.opened",CONNECTION_CLOSED:"os.connection.closed",CONNECTION_MESSAGE:"os.connection.message",IFRAME_CONNECTION_REQUEST:"os.iframe.connection-request",WINDOW_CONTENT_CHANGED:"os.window-links.content-changed",WINDOW_LINK_GROUPS_CHANGED:"os.window-links.groups-changed",WINDOW_LINKS_CONTENT:"os.window-links.content",WINDOW_LINK_GROUPS:"os.window-links.groups",WINDOW_LINK_EDGES:"os.window-links.edges",RELATED_ENTITIES_ITEMS:"os.related-entities.items",WINDOW_LINK_RENDERERS:"os.window-links.renderers",WINDOW_LINK_RENDERER:"os.window-links.renderer",EDITOR_PREVIEW_WINDOW_CONFIG:"os.editor-preview.window-config",EDITOR_PREVIEW_LIVE:"os.editor-preview.live",EDITOR_PREVIEW_OPENED:"os.editor-preview.opened",EDITOR_PREVIEW_CLOSED:"os.editor-preview.closed",REVISIONS_WINDOW_CONFIG:"os.revisions.window-config",REVISIONS_OPENED:"os.revisions.opened",FILE_DROP_FILES_DETECTED:"os.drop.files-detected",FILE_DROP_FILES_REJECTED:"os.drop.files-rejected",FILE_DROP_DIALOG_FIELDS:"os.drop.dialog-fields",FILE_DROP_BEFORE_UPLOAD:"os.drop.before-upload",FILE_DROP_UPLOAD_STARTED:"os.drop.upload-started",FILE_DROP_UPLOAD_PROGRESS:"os.drop.upload-progress",FILE_DROP_AFTER_UPLOAD:"os.drop.after-upload",FILE_DROP_UPLOAD_FAILED:"os.drop.upload-failed",AUTH_LOST:"os.auth.lost",AUTH_RESTORED:"os.auth.restored",MODE_CHANGED:"os.mode.changed",SESSION_SNAPSHOT:"os.session.snapshot"};let NE=0;function Tu(e){if(Lu(y.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++NE}`;ee(y.INIT,t,e)}function OE(){return Lu(y.INIT)>0}const ba="data-os-mode";function Nu(e,t){e.getAttribute(ba)!==t&&e.setAttribute(ba,t)}function Jt(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(ba)==="mobile"}const va="data-os-display";function Ou(e,t){e.getAttribute(va)!==t&&e.setAttribute(va,t)}function DE(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(va)==="standalone"}const Du=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"],xu=Du.filter(e=>e!=="p"),_a=[];function Ru(e){if(!e.pathname.endsWith("/admin.php")||!e.searchParams.get("page"))return _a;const t=e.searchParams.get("action");return t==="edit"&&e.searchParams.get("id")?["id"]:t==="new"?["action"]:_a}function Mu(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 fe(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,a=[...Du,...Ru(n)];for(const c of a){const d=n.searchParams.get(c);d&&r.set(c,d)}const l=r.toString();return Mu(l?`${i}?${l}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),Mu(o)}function xE(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function RE(e){e.style.setProperty("--os-file-tile-enter-delay",`${(Math.random()*.25).toFixed(3)}s`),e.style.setProperty("--os-file-tile-enter-duration",`${(.3+Math.random()*.25).toFixed(3)}s`)}function Wu(e){try{const t=new URL(e,window.location.origin),n=new URLSearchParams,o=[...xu,...Ru(t)];for(const i of o){const r=t.searchParams.get(i);r?n.set(i,r):i==="post_type"&&(t.pathname.endsWith("/edit.php")||t.pathname.endsWith("/post-new.php"))&&n.set(i,"post")}n.sort();const s=n.toString();return t.pathname.replace(/\/+$/,"")+(s?`?${s}`:"")}catch{return e}}function Lt(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("openstation_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function On(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("openstation_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 Pu(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 l of Array.from(a.attributes)){const c=l.name.toLowerCase(),d=l.value.trim().toLowerCase();if(c.startsWith("on")){a.removeAttribute(l.name);continue}d.startsWith("javascript:")&&a.removeAttribute(l.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 Dn=null;function mi(){return!!window.openStationWindowSystem}function $u(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(mi()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){mi()?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.osWindowSystem="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))),document.head.appendChild(i)})}function ME(){return window.openStationConfig?.windowSystemBundleUrl??""}function WE(e){!e||mi()||Dn||(Dn=$u(e).catch(t=>{Dn=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function PE(e){if(mi())return window.openStationWindowSystem;if(!e){const t=window.openStationWindowSystem;if(t)return t;throw new Error("[openstation] ensureWindowSystemLoaded(): no bundle URL configured and `window.openStationWindowSystem` is not pre-registered.")}return Dn||(Dn=$u(e)),await Dn,window.openStationWindowSystem}let xn=null;function Po(){return!!window.openStationShellOverlays}function Uu(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(Po()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){Po()?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.osShellOverlays="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(i)})}function $E(e){!e||Po()||xn||(xn=Uu(e).catch(t=>{xn=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function Ea(e){return Po()||!e?Promise.resolve():(xn||(xn=Uu(e)),xn)}function ka(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function gi(e,t){const n=ka();if(Po()||!n){t();return}Ea(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Bu="desktop-mode";function Sa(){return window.wp?.i18n}function b(e,t=Bu){return Sa()?.__(e,t)??e}function Qt(e,t,n,o=Bu){return Sa()?._n(e,t,n,o)??(n===1?e:t)}function le(e,...t){const n=Sa()?.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]??"")})}const UE=900,BE=260,Ia="os-desktop-name-hud";let tt=null,Tt=null;function FE(e,t){t.trim()&&(Tt!==null&&window.clearTimeout(Tt),tt||(tt=document.createElement("div"),tt.className=Ia,tt.setAttribute("role","status")),tt.textContent=t,tt.classList.remove(`${Ia}--out`),e.appendChild(tt),Tt=window.setTimeout(()=>{tt?.classList.add(`${Ia}--out`),Tt=window.setTimeout(()=>{tt?.remove(),Tt=null},BE)},UE))}function HE(){Tt!==null&&(window.clearTimeout(Tt),Tt=null),tt?.remove(),tt=null}function GE(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 zE(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 jE(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 l=t/r/Math.max(1,n/a),c=Math.abs(l-o),d=r*a-e,u=c+d*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function Aa(e,t,n,o,s){let i=n,r=e-t-i;return r<s&&(r=s,i=e-t-r),i<o&&(i=o,r=Math.max(s,e-t-i)),i=Math.max(0,Math.min(i,e)),r=Math.max(0,Math.min(r,e)),{first:{x:0,width:i},second:{x:e-r,width:r}}}function Ca(e,t,n,o){const s=Math.floor(e.width/2),i=t==="left"?Aa(e.width,0,s,n,o):Aa(e.width,0,s,o,n),r=t==="left"?i.first:i.second;return{x:e.x+r.x,y:e.y,width:r.width,height:e.height}}function Fu(e,t,n){const o=n.length;if(o===0)return[];const s=new Array(o).fill(0),i=new Array(o).fill(!1);let r=e-t*(o-1),a=o,l=!0;for(;l&&a>0;){l=!1;const u=Math.floor(r/a);for(let f=0;f<o;f++)!i[f]&&n[f]>u&&(i[f]=!0,s[f]=Math.min(n[f],e),r-=s[f],a--,l=!0)}const c=a>0?Math.floor(r/a):0;for(let u=0;u<o;u++)i[u]||(s[u]=c);if(r>=0){let u=0;return s.map(f=>{const p={x:u,width:f};return u+=f+t,p})}const d=e-s[o-1];return s.map((u,f)=>{const p=o>1?Math.round(d*f/(o-1)):0;return{x:Math.max(0,Math.min(p,e-u)),width:u}})}function La(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,l=34,c=(t.width-r*2-a*(s-1))/s,d=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-l);return e.map((f,p)=>{const g=p%s,h=Math.floor(p/s),m=t.left+r+g*(c+a),E=t.top+n+r+h*(d+a)+l,k=f.element.offsetWidth,N=f.element.offsetHeight,M=Math.min(c/k,u/N),S=k*M,$=N*M;return{win:f,x:m+(c-S)/2,y:E+(u-$)/2,scale:M}})}const VE=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],Hu=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],KE=[...VE,...Hu],Gu={close:{a:'fill="currentColor"',b:'<path d="m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z" />'},check:{a:'fill="currentColor"',b:'<path d="M16.5 7.5 10 13.9l-2.5-2.4-1 1 3.5 3.6 7.5-7.6z" />'},"chevron-right":{a:'fill="currentColor"',b:'<path d="M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z" />'},"arrow-up-right":{a:'fill="currentColor"',b:'<path d="M10 6H18V14H16.5V8.5L7 18L6 17L15.5 7.5H10V6Z" />'},plus:{a:'fill="currentColor"',b:'<path d="M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z" />'},search:{a:'fill="currentColor"',b:'<path d="M13 5c-3.3 0-6 2.7-6 6 0 1.4.5 2.7 1.3 3.7l-3.8 3.8 1.1 1.1 3.8-3.8c1 .8 2.3 1.3 3.7 1.3 3.3 0 6-2.7 6-6S16.3 5 13 5zm0 10.5c-2.5 0-4.5-2-4.5-4.5s2-4.5 4.5-4.5 4.5 2 4.5 4.5-2 4.5-4.5 4.5z" />'},pin:{a:'fill="currentColor"',b:'<path d="m21.5 9.1-6.6-6.6-4.2 5.6c-1.2-.1-2.4.1-3.6.7-.1 0-.1.1-.2.1-.5.3-.9.6-1.2.9l3.7 3.7-5.7 5.7v1.1h1.1l5.7-5.7 3.7 3.7c.4-.4.7-.8.9-1.2.1-.1.1-.2.2-.3.6-1.1.8-2.4.6-3.6l5.6-4.1zm-7.3 3.5.1.9c.1.9 0 1.8-.4 2.6l-6-6c.8-.4 1.7-.5 2.6-.4l.9.1L15 4.9 19.1 9l-4.9 3.6z" />'},trash:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M12 5.5A2.25 2.25 0 0 0 9.878 7h4.244A2.251 2.251 0 0 0 12 5.5ZM12 4a3.751 3.751 0 0 0-3.675 3H5v1.5h1.27l.818 8.997a2.75 2.75 0 0 0 2.739 2.501h4.347a2.75 2.75 0 0 0 2.738-2.5L17.73 8.5H19V7h-3.325A3.751 3.751 0 0 0 12 4Zm4.224 4.5H7.776l.806 8.861a1.25 1.25 0 0 0 1.245 1.137h4.347a1.25 1.25 0 0 0 1.245-1.137l.805-8.861Z" />'},download:{a:'fill="currentColor"',b:'<path d="M18 11.3l-1-1.1-4 4V3h-1.5v11.3L7 10.2l-1 1.1 6.2 5.8 5.8-5.8zm.5 3.7v3.5h-13V15H4v5h16v-5h-1.5z" />'},settings:{a:'fill="currentColor"',b:'<path d="m19 7.5h-7.628c-.3089-.87389-1.1423-1.5-2.122-1.5-.97966 0-1.81309.62611-2.12197 1.5h-2.12803v1.5h2.12803c.30888.87389 1.14231 1.5 2.12197 1.5.9797 0 1.8131-.62611 2.122-1.5h7.628z" /><path d="m19 15h-2.128c-.3089-.8739-1.1423-1.5-2.122-1.5s-1.8131.6261-2.122 1.5h-7.628v1.5h7.628c.3089.8739 1.1423 1.5 2.122 1.5s1.8131-.6261 2.122-1.5h2.128z" />'},info:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm.75 4v1.5h-1.5V8h1.5Zm0 8v-5h-1.5v5h1.5Z" />'},bell:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M17 11.5c0 1.353.17 2.368.976 3 .266.209.602.376 1.024.5v1H5v-1c.422-.124.757-.291 1.024-.5.806-.632.976-1.647.976-3V9c0-2.8 2.2-5 5-5s5 2.2 5 5v2.5ZM15.5 9v2.5c0 .93.066 1.98.515 2.897l.053.103H7.932a4.018 4.018 0 0 0 .053-.103c.449-.917.515-1.967.515-2.897V9c0-1.972 1.528-3.5 3.5-3.5s3.5 1.528 3.5 3.5Zm-5.492 9.008c0-.176.023-.346.065-.508h3.854A1.996 1.996 0 0 1 12 20c-1.1 0-1.992-.892-1.992-1.992Z" />'},more:{a:'fill="currentColor"',b:'<path d="M11 13h2v-2h-2v2zm-6 0h2v-2H5v2zm12-2v2h2v-2h-2z" />'},maximize:{a:'fill="currentColor"',b:'<path d="M6 4a2 2 0 0 0-2 2v3h1.5V6a.5.5 0 0 1 .5-.5h3V4H6Zm3 14.5H6a.5.5 0 0 1-.5-.5v-3H4v3a2 2 0 0 0 2 2h3v-1.5Zm6 1.5v-1.5h3a.5.5 0 0 0 .5-.5v-3H20v3a2 2 0 0 1-2 2h-3Zm3-16a2 2 0 0 1 2 2v3h-1.5V6a.5.5 0 0 0-.5-.5h-3V4h3Z" />'},edit:{a:'fill="currentColor"',b:'<path d="m19 7-3-3-8.5 8.5-1 4 4-1L19 7Zm-7 11.5H5V20h7v-1.5Z" />'},color:{a:'fill="currentColor"',b:'<path d="M17.2 10.9c-.5-1-1.2-2.1-2.1-3.2-.6-.9-1.3-1.7-2.1-2.6L12 4l-1 1.1c-.6.9-1.3 1.7-2 2.6-.8 1.2-1.5 2.3-2 3.2-.6 1.2-1 2.2-1 3 0 3.4 2.7 6.1 6.1 6.1s6.1-2.7 6.1-6.1c0-.8-.3-1.8-1-3zm-5.1 7.6c-2.5 0-4.6-2.1-4.6-4.6 0-.3.1-1 .8-2.3.5-.9 1.1-1.9 2-3.1.7-.9 1.3-1.7 1.8-2.3.7.8 1.3 1.6 1.8 2.3.8 1.1 1.5 2.2 2 3.1.7 1.3.8 2 .8 2.3 0 2.5-2.1 4.6-4.6 4.6z" />'},wallpaper:{a:'fill="currentColor"',b:'<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.5h14c.3 0 .5.2.5.5v8.4l-3-2.9c-.3-.3-.8-.3-1 0L11.9 14 9 12c-.3-.2-.6-.2-.8 0l-3.6 2.6V5c-.1-.3.1-.5.4-.5zm14 15H5c-.3 0-.5-.2-.5-.5v-2.4l4.1-3 3 1.9c.3.2.7.2.9-.1L16 12l3.5 3.4V19c0 .3-.2.5-.5.5z" />'},warning:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm-.75 12v-1.5h1.5V16h-1.5Zm0-8v5h1.5V8h-1.5Z" />'},minimize:{a:'fill="currentColor"',b:'<path d="M5 11.25h14v1.5H5z" />'},window:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="4.125" y="5.4375" width="15.75" height="13.125" rx="1.75"/><path d="M4.125 9.8125h15.75"/><circle cx="7.275" cy="7.625" r="0.7438" fill="currentColor" stroke="none"/>'},windows:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="8.5" width="11.375" height="10.0625" rx="1.75"/><path d="M3.6875 12h11.375"/><path d="M8.5 8.5V7.1875a1.75 1.75 0 0 1 1.75-1.75h7.875A1.75 1.75 0 0 1 19.875 7.1875v7a1.75 1.75 0 0 1-1.75 1.75h-3.0625"/>'},dock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.25" y="8.5" width="17.5" height="7" rx="3.5"/><circle cx="7.625" cy="12" r="1.0062" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.0062" fill="currentColor" stroke="none"/><circle cx="16.375" cy="12" r="1.0062" fill="currentColor" stroke="none"/>'},spaces:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="5.4375" width="7.4375" height="7.875" rx="1.75"/><rect x="12.875" y="5.4375" width="7.4375" height="7.875" rx="1.75"/><circle cx="9.375" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/><circle cx="12" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/><circle cx="14.625" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/>'},copilot:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<path d="M10 2.5Q10.9 8.5 17.5 10Q10.9 11.5 10 17.5Q9.1 11.5 2.5 10Q9.1 8.5 10 2.5Z" fill="currentColor" stroke="none"/><path d="M17.9 14Q18.35 17.1 21.5 17.6Q18.35 18.1 17.9 21.2Q17.45 18.1 14.3 17.6Q17.45 17.1 17.9 14Z" fill="currentColor" stroke="none"/>'},snap:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="5.4375" width="16.625" height="13.125" rx="1.75"/><path d="M12 5.4375v13.125"/><path d="M12 12h8.3125"/>'},command:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<path d="M14.625 6.75v10.5a2.625 2.625 0 1 0 2.625-2.625H6.75a2.625 2.625 0 1 0 2.625 2.625V6.75a2.625 2.625 0 1 0-2.625 2.625h10.5a2.625 2.625 0 1 0-2.625-2.625"/>'},apps:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="4.125" y="4.125" width="6.5625" height="6.5625" rx="1.75"/><rect x="13.3125" y="4.125" width="6.5625" height="6.5625" rx="1.75"/><rect x="4.125" y="13.3125" width="6.5625" height="6.5625" rx="1.75"/><rect x="13.3125" y="13.3125" width="6.5625" height="6.5625" rx="1.75"/>'},widgets:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="3.6875" width="9.625" height="9.625" rx="1.75"/><rect x="15.0625" y="3.6875" width="5.25" height="5.25" rx="1.75"/><rect x="15.0625" y="10.6875" width="5.25" height="9.625" rx="1.75"/><rect x="3.6875" y="15.0625" width="9.625" height="5.25" rx="1.75"/>'},user:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<circle cx="12" cy="8.9375" r="3.5"/><path d="M5.4375 19.4375a6.5625 6.5625 0 0 1 13.125 0"/>'},lock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="5.4375" y="10.6875" width="13.125" height="8.75" rx="1.75"/><path d="M8.5 10.6875V8.0625a3.5 3.5 0 0 1 7 0v2.625"/>'}};function zu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ju(e){return Object.prototype.hasOwnProperty.call(Gu,e)?Gu[e]:null}function qE(e){return ju(e)!==null}function en(e,t={}){const n=ju(e);if(!n)return"";const{size:o=24,className:s,title:i,rotate:r}=t,a=['xmlns="http://www.w3.org/2000/svg"','viewBox="0 0 24 24"'];o!=null&&a.push(`width="${o}"`,`height="${o}"`),a.push(n.a),s&&a.push(`class="${zu(s)}"`),i?a.push('role="img"',`aria-label="${zu(i)}"`):a.push('aria-hidden="true"','focusable="false"');const l=r?`<g transform="rotate(${r} 12 12)">${n.b}</g>`:n.b;return`<svg ${a.join(" ")}>${l}</svg>`}function Vu(e,t={}){const n=en(e,t),o=document.createElement("div");o.innerHTML=n;const s=o.firstElementChild;return s instanceof SVGSVGElement?s:document.createElementNS("http://www.w3.org/2000/svg","svg")}function YE(e,t={}){const n=en(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const XE=Object.freeze({svg:en,node:Vu,dataUri:YE,names:Object.freeze([...KE]),ours:Object.freeze([...Hu]),has:qE}),ZE=120,JE=56;function Ku(e){return ZE+(e?.querySelector(".os-overview-top-bar__header")?JE:0)}const QE="openstation";function Rn(e,t){let n;if(typeof e=="string")try{n=new URL(e,t??(typeof window<"u"?window.location.href:void 0))}catch{return!1}else n=e;return n.pathname.slice(n.pathname.lastIndexOf("/")+1)==="admin.php"&&n.searchParams.get("page")===QE}const qu=["target","intent","openstation_overview","openstation_hop","openstation_hop_from"];function ek(e,t){let n;try{n=new URL(typeof e=="string"?e:e.href,t??(typeof window<"u"?window.location.href:void 0))}catch{return null}return!Rn(n)||!qu.some(o=>n.searchParams.has(o))?null:(qu.forEach(o=>n.searchParams.delete(o)),n.href)}const Yu="__openStationSharedStores";function tk(){const e=window;let t=e[Yu];return t||(t=new Map,e[Yu]=t),t}function se(e,t){const n=tk();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 l of Object.keys(a))delete a[l];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}const Xu="os_tab",nk="os_person_view";function ok(e){return e.searchParams.has(nk)}const Mn=se("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function sk(e){Mn.state.deps=e}function yt(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=Mn.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Ta(e.id)}function Ta(e){const t=Mn.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function $o(e){const{deps:t,remaps:n}=Mn.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 Zu(e,t,n){let o;const s=n.searchParams.get(Xu);if(e.params)try{o=e.params(t,n)??void 0}catch(i){console.warn(`[openstation] URL remap params hook threw for "${e.id}":`,i)}return s&&/^[a-z0-9_-]+$/.test(s)&&(o={...o??{},tab:s}),o}function ik(e){const{deps:t,remaps:n}=Mn.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{id:i.nativeWindowId,params:Zu(i,e,o)};return null}function Be(e,t={}){const{deps:n,remaps:o}=Mn.state;if(!n||!e)return!1;let s;try{s=new URL(e,n.adminUrl)}catch{return!1}const i=n.getSnapshot();for(const r of o){if(!r.matches(e,s)||r.enabled&&!r.enabled(i))continue;if(r.onMatch)try{r.onMatch(e,s)}catch(d){console.warn(`[openstation] URL remap onMatch hook threw for "${r.id}":`,d)}const a=Zu(r,e,s),l=t.newInstance&&n.openNewById?n.openNewById:n.openById;if(a?l(r.nativeWindowId,{params:a}):l(r.nativeWindowId))return!0}return!1}const Ju="X-WP-Nonce";function Qu(e,t){const n=rk();if(!n)return t;const o=ak(e);if(!o||!ck(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Ju)?t:(i.set(Ju,n),{...t??{},headers:i})}function rk(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function ak(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 ck(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Ae(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=Qu(e,t);return fetch(e,s)}class Uo extends Error{constructor(t,n){super(t||n.serverMessage||`HTTP ${n.status}`),this.name="RestError",this.status=n.status,this.code=n.code,this.data=n.data,this.serverMessage=n.serverMessage??""}}function ef(e){return e instanceof Uo}function tf(e){const t=typeof e=="object"&&e!==null?e:void 0;return{code:typeof t?.code=="string"?t.code:void 0,data:t?.data,serverMessage:typeof t?.message=="string"?t.message:""}}function bt(e,t,n=""){return new Uo(n,{status:e,...tf(t)})}async function Wn(e,t=""){let n=null;try{n=await e.json()}catch{n=null}return bt(e.status,n,t)}function nf(e,t){return new Uo(t,{status:e,code:"openstation_bad_response"})}function lk(e){const{prefix:t,source:n,conflict:o}=e;return async(s,i={})=>{const r=new Headers(i.headers??{});r.set("X-WP-Nonce",e.nonce()),i.body&&!r.has("Content-Type")&&r.set("Content-Type","application/json");const a=await Ae(e.url(s),{...i,headers:r,credentials:"same-origin"},{source:n}),l=await a.text();let c=null,d=null;if(l)try{c=JSON.parse(l)}catch(u){d=u}if(!a.ok){if(a.status===409&&o){const p=o(c);if(p)throw p}const{code:u,serverMessage:f}=tf(c);throw bt(a.status,c,`${t} ${a.status}: ${u??""} ${f}`.trim())}if(c===null){if(d&&l){const u=l.slice(0,120).replace(/\s+/g," ");throw nf(a.status,`${t} ${a.status} returned non-JSON body — ${d.message}. First 120 chars: ${u}`)}throw nf(a.status,`${t} ${a.status}: empty or unparseable body.`)}return c}}const Bo=se("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),vt=Bo.state.registry,Na=Bo.state.listeners,dk=/^[a-z0-9_-]+$/;function Oa(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!dk.test(e.id))throw new TypeError(`[openstation] registerDockRailRenderer: id must match /^[a-z0-9_-]+$/, got: ${String(e.id)}`);if(typeof e.label!="string"||e.label==="")throw new TypeError("[openstation] registerDockRailRenderer: label must be a non-empty string.");if(typeof e.mount!="function")throw new TypeError("[openstation] registerDockRailRenderer: mount must be a function.");if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new TypeError(`[openstation] registerDockRailRenderer: unsupported apiVersion ${e.apiVersion} (this shell speaks v1).`);vt.set(e.id,e),wi()}function uk(e){vt.delete(e)&&wi()}function fk(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(vt.entries()))o.owner===e&&(vt.delete(n),t++);return t>0&&wi(),t}function pk(e){return vt.get(e)}function hk(){return Array.from(vt.values())}function mk(e){return Na.add(e),()=>{Na.delete(e)}}function gk(e){Bo.state.activeId!==e&&(Bo.state.activeId=e,wi())}function Da(){return vt.get(Bo.state.activeId)??vt.get("default")??vt.values().next().value}function wi(){const e=Array.from(Na);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function tn(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 wk extends Error{constructor(t,n,o){super(`[openstation] ${t} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=t,this.errors=n,this.def=o}}function Me(e,t,n){if(t.length!==0)throw new wk(e,t,n)}function of(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const Nt=[[0,0],[100,0],[100,100],[0,100]],yk=48,bk=80,xa=6,Ra=8,sf=4,rf=3,af=64,Ma=105,Ot=2;function cf(e){return`${Math.round(e*1e3)/1e3}%`}function Dt(e){return e.slice().reverse()}function Fo(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function vk(e,t,n,o){const s=[];for(let i=0;i<o;i++){const r=i/o*Math.PI*2;s.push([e+Math.cos(r)*n,t+Math.sin(r)*n])}return s}function dt(e,t=[]){const n=[],o=s=>{n.push(`${cf(s[0])} ${cf(s[1])}`)};for(const s of e)o(s);if(t.length>0){o(e[0]);for(const s of t){for(const i of s)o(i);o(s[0]),o(e[0])}}return`polygon( ${n.join(", ")} )`}function lf(e){return dt(Nt,[Dt(vk(50,50,e,yk))])}function df(e){return dt(Nt,[Dt(Fo(50-e,-Ot,50+e,100+Ot))])}function uf(e){const t=100/xa,n=[];for(let o=0;o<xa;o++){const s=o*t;n.push(Dt(Fo(-Ot,s,100+Ot,s+e)))}return dt(Nt,n)}function ff(e){return dt(Nt,[Dt(Fo(-Ot,50-e,100+Ot,50+e))])}function pf(e){const t=100/Ra,n=[];for(let o=0;o<Ra;o++){const s=o*t;n.push(Dt(Fo(s,-Ot,s+e,100+Ot)))}return dt(Nt,n)}function hf(e){return dt(Nt,[Dt([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function mf(e){const t=100/sf,n=100/rf,o=[];for(let s=0;s<rf;s++)for(let i=0;i<sf;i++){const r=i*t+t/2,a=s*n+n/2,l=t/2*e,c=n/2*e;o.push(Dt(Fo(r-l,a-c,r+l,a+c)))}return dt(Nt,o)}function gf(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<af;s++){const i=t+s/(af-1)*n;o.push([50+Math.cos(i)*Ma,50+Math.sin(i)*Ma])}return dt(Nt,[Dt(o)])}function _k(){return{from:lf(0),to:lf(bk)}}function Ek(){return{from:df(0),to:df(52)}}function kk(){return{from:uf(0),to:uf(100/xa+.5)}}function Sk(){return{from:ff(0),to:ff(52)}}function Ik(){return{from:pf(0),to:pf(100/Ra+.5)}}function Ak(){return{from:hf(0),to:hf(Ma)}}function Ck(){return{from:mf(0),to:mf(1.04)}}function Lk(){return{from:gf(0),to:gf(360)}}function Tk(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function Nk(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function Ok(){return{from:dt([[-60,0],[100,0],[100,100],[0,100]]),to:dt([[100,0],[260,0],[260,100],[160,100]])}}const Wa=6,Pa=100,Pn=Pa/2,yi=200,wf=90,yf=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],Dk="#101014",xk=1.25,$n="http://www.w3.org/2000/svg";let Rk=0;function bi(e){return Math.round(e*1e3)/1e3}function $a(e){return e/Wa*Math.PI*2-Math.PI/2}function Mk(e){const n=$a(e)+Math.PI/Wa+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function Wk(e){const t=$a(e),n=$a(e+1);return[[Pn,Pn],[Pn+Math.cos(t)*yi,Pn+Math.sin(t)*yi],[Pn+Math.cos(n)*yi,Pn+Math.sin(n)*yi]]}function bf(e,t){const n=Wk(e),o=document.createElementNS($n,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${bi(s)} ${bi(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",yf[e%yf.length]),o.setAttribute("stroke",Dk),o.setAttribute("stroke-width",String(xk)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function Pk(){const e=`os-iris-${++Rk}`,t=document.createElementNS($n,"svg");t.setAttribute("viewBox",`0 0 ${Pa} ${Pa}`),t.setAttribute("preserveAspectRatio","none"),t.setAttribute("aria-hidden","true"),t.style.width="100%",t.style.height="100%",t.style.display="block";const n=document.createElementNS($n,"defs"),o=document.createElementNS($n,"mask");o.setAttribute("id",e);const s=document.createElementNS($n,"g"),i=document.createElementNS($n,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let l=0;l<Wa;l++){const c=bf(l,!0),d=bf(l,!1);s.appendChild(c),i.appendChild(d),r.push({el:c,index:l},{el:d,index:l})}o.appendChild(s),n.appendChild(o),t.appendChild(n),t.appendChild(i);const a=document.createElement("div");return a.appendChild(t),{element:a,play:l=>r.map(({el:c,index:d})=>{const u=Mk(d),f=bi(u.x*wf),p=bi(u.y*wf);return c.animate([{transform:"translate( 0px, 0px )"},{transform:`translate( ${f}px, ${p}px )`}],{duration:l.duration,easing:l.easing,delay:l.delay,fill:"both"})})}}const Ho="none",$k=460,Uk="cubic-bezier( 0.33, 0, 0.2, 1 )",vf=80,_f=4e3,Bk=70,Fk=600,Ef=se("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),vi=Ef.state.registry,Hk=Ef.state.listeners,kf=/^[a-z0-9_/-]+$/;function Sf(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function Gk(e){return typeof e!="number"||!Number.isFinite(e)?$k:Math.min(_f,Math.max(vf,e))}const Ua=0;function If(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?Ua:Math.min(_f,Math.max(vf,e))}function Un(e){return typeof e!="number"||!Number.isFinite(e)?Bk:Math.min(Fk,Math.max(0,e))}function Af(e){return typeof e.render=="function"?[]:Array.isArray(e.layers)&&e.layers.length>0?e.layers:typeof e.from=="string"&&typeof e.to=="string"?[{from:e.from,to:e.to}]:[]}function Cf(e,t){const n=[],o=typeof e.from=="string"&&e.from.trim()!=="",s=typeof e.to=="string"&&e.to.trim()!=="";if(o||n.push(`${t}.from (missing — the clip-path covering the window)`),s||n.push(`${t}.to (missing — the clip-path uncovering the window)`),o&&s){const i=Sf(e.from),r=Sf(e.to);i===""||r===""?n.push(`${t}.from|to (must be shape functions, e.g. \`inset( … )\` or \`polygon( … )\` — bare keywords like \`none\` cannot be animated)`):i!==r&&n.push(`${t}.from|to (must use the same shape function to interpolate — got \`${i}()\` and \`${r}()\`)`)}return n}function zk(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function ze(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):kf.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Ho&&t.push('id ("none" is reserved)'):t.push(`id (must match ${kf} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)");const o=e.render!==void 0,s=Array.isArray(e.layers),i=e.from!==void 0||e.to!==void 0;o&&typeof e.render!="function"?t.push("render (not a function)"):o&&(s||i)?t.push("render|layers|from|to (supply exactly one of: a from/to pair, a layers array, or a render function)"):o||(s&&i?t.push("layers|from|to (supply EITHER a single from/to pair OR a layers array, not both)"):s?(e.layers.length===0&&t.push("layers (empty — supply at least one matched pair)"),e.layers.forEach((r,a)=>{if(!r||typeof r!="object"){t.push(`layers[ ${a} ] (not an object)`);return}t.push(...Cf(r,`layers[ ${a} ]`))})):t.push(...Cf(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):zk(e.easing)||t.push("easing (not an easing the browser can parse — `Element.animate()` would throw at play time, with the covering surface already over the window)"))}Me("WindowReveal",t,e);const n=e.id.trim().toLowerCase();vi.set(n,{...e,id:n}),Nf()}function jk(e){vi.delete(e.toLowerCase())&&Nf()}function Lf(){const e=Array.from(vi.values()),t=Q(y.WINDOW_REVEALS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-reveals` filter returned a non-array; falling back to registry list."),e)}function Tf(e){return Lf().find(t=>t.id===e)}function Vk(e){return vi.has(e)}function Nf(){const e=Array.from(Hk);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}ze({id:"sweep",label:b("Sweep"),description:b("A straight edge travels across the window, uncovering the page behind it."),...Nk(),duration:420}),ze({id:"iris",label:b("Iris"),description:b("The page opens out from the centre of the window, like a camera shutter."),..._k(),duration:520}),ze({id:"curtain",label:b("Curtain"),description:b("Two panels part from the middle of the window and slide off the sides."),...Ek(),duration:480}),ze({id:"blinds",label:b("Blinds"),description:b("Six horizontal slats retract at once, letting the page through between them."),...kk(),duration:560}),ze({id:"diagonal",label:b("Diagonal"),description:b("A slanted edge sweeps off the trailing corner of the window."),...Ok(),duration:460}),ze({id:"rise",label:b("Rise"),description:b("The page rises into the window from the bottom edge upward."),...Tk(),duration:440}),ze({id:"shutter",label:b("Shutter"),description:b("Two panels part from the middle of the window and slide off the top and bottom."),...Sk(),duration:480}),ze({id:"slats",label:b("Slats"),description:b("Eight vertical slats retract at once, letting the page through between them."),...Ik(),duration:560}),ze({id:"diamond",label:b("Diamond"),description:b("The page opens out from the centre of the window through a growing rhombus."),...Ak(),duration:520}),ze({id:"mosaic",label:b("Mosaic"),description:b("The page arrives as a grid of tiles, each opening out from its own centre."),...Ck(),duration:600}),ze({id:"obturator",label:b("Camera shutter"),description:b("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:Pk,duration:720,edgeLag:0}),ze({id:"radar",label:b("Radar"),description:b("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...Lk(),duration:760});const Of="desktop-mode-os-settings",xt="desktop-mode-os-settings",Df="custom-gradient",Go="custom-image",Ba="galaxy",Fa="custom",xf=[{id:"pulse",label:"Pulse",value:"#f252fc"},{id:"nebula",label:"Nebula",value:"#ec9bff"},{id:"sirius",label:"Sirius",value:"#9af2ff"},{id:"lagoon",label:"Lagoon",value:"#9f98ff"},{id:"starlight",label:"Starlight",value:"#fffbff"},{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 zo(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return xf;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:xf}function Ha(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:Ba}const Ga=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],za=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],Kk=[{id:"default",label:"Default"},{id:"maximized",label:"Maximized"},{id:"focused",label:"Focused"}],_i=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],Ei=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"}],qk=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],Yk=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],Bn={wallpaper:Ba,accent:"pulse",customAccent:"#f252fc",dockSize:"default",windowRadius:"round",openWindowsAs:"default",adminBarMode:"hidden",desktopLayout:"unified",dockPlacement:"bottom",dockBehavior:"static",sideDockBehavior:"static",dockRailRenderer:"default",desktopTheme:"",appliedThemeRecommendations:[],unfocusEffect:"darken",windowReveal:"none",windowRevealDuration:0,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,nativePagesHiddenColumns:[],nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,stationHomeEnabled:!1,adminAssetCacheEnabled:!0,windowPrewarmEnabled:!0,showDesktopOnWallpaperClick:!1,confirmCloseAllWindows:!0,mioEnabled:!1,mioApiEnabled:!1,mioShowOnWallpaper:!0,mioStyle:{appearance:{},physics:{}},showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,navPlacement:{},navOrder:[],mobileLayout:"auto",mobileTabs:[],dockPromotedPositions:{}},Rf=se("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),Fn=Rf.state.seed,Xk=Rf.state.listeners;function Hn(e){Me("Wallpaper",tn(e,Pf),e);const t=Fn.findIndex(n=>n.id===e.id);t>=0?Fn[t]=e:Fn.push(e),Wf()}function Mf(e){const t=Fn.findIndex(n=>n.id===e);t>=0&&(Fn.splice(t,1),Wf())}function Wf(){const e=Array.from(Xk);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function ja(){const e=Fn.slice(),t=Q(y.WALLPAPERS,e);return Array.isArray(t)?t.filter(Zk):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function Gn(e){return ja().find(t=>t.id===e)}const Pf=[{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 Zk(e){return tn(e,Pf).length===0}const zn=[];function Va(e){Me("Widget",tn(e,$f),e);const t=zn.findIndex(n=>n.id===e.id);t>=0?zn[t]=e:zn.push(e)}function Jk(e){const t=zn.findIndex(n=>n.id===e);t>=0&&zn.splice(t,1)}function Ka(){const e=zn.slice(),t=Q(y.WIDGETS,e);return Array.isArray(t)?t.filter(Qk):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function Rt(e){return Ka().find(t=>t.id===e)}const $f=[{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 Qk(e){return tn(e,$f).length===0}const Uf={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},Bf=["dockRailRenderer","windowReveal","accent","wallpaper"],eS="desktop-theme/",Ff={windowRevealDuration:{min:80,max:4e3}},Hf=/^[a-z0-9_-]+$/,Gf=["accentColor"],tS=/^#[0-9a-fA-F]{6}$/,zf={navPlacement:["rail","desktop","both","hidden"]},jf=["widgets"],nS=/^[A-Za-z0-9_/-]{1,128}$/;[...Object.keys(Uf),...Bf,...Gf,...Object.keys(Ff),...Object.keys(zf),...jf];function Vf(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[r,a]of Object.entries(Uf)){const l=t[r];typeof l=="string"&&a.includes(l)&&(n[r]=l)}for(const r of Bf){const a=t[r];typeof a=="string"&&Hf.test(a)&&(n[r]=a)}for(const r of Gf){const a=t[r];typeof a=="string"&&tS.test(a)&&(n[r]=a.toLowerCase())}for(const[r,a]of Object.entries(Ff)){const l=t[r];typeof l=="number"&&Number.isFinite(l)&&(o[r]=Math.min(a.max,Math.max(a.min,Math.round(l))))}const s={};for(const[r,a]of Object.entries(zf)){const l=t[r];if(!l||typeof l!="object"||Array.isArray(l))continue;const c={};for(const[d,u]of Object.entries(l))Hf.test(d)&&typeof u=="string"&&a.includes(u)&&(c[d]=u);Object.keys(c).length>0&&(s[r]=c)}const i={};for(const r of jf){const a=t[r];Array.isArray(a)&&(i[r]=[...new Set(a.filter(l=>typeof l=="string"&&nS.test(l)))])}return{...n,...o,...s,...i}}function oS(e,t){const n=Vf(e);if(typeof n.wallpaper=="string"){const s=(t?[`${eS}${t}/${n.wallpaper}`,n.wallpaper]:[n.wallpaper]).find(i=>Gn(i)!==void 0);s?n.wallpaper=s:delete n.wallpaper}if(typeof n.dockRailRenderer=="string"&&pk(n.dockRailRenderer)===void 0&&delete n.dockRailRenderer,typeof n.windowReveal=="string"&&n.windowReveal!==Ho&&!Vk(n.windowReveal)&&delete n.windowReveal,typeof n.accent=="string"&&!zo().some(o=>o.id===n.accent)&&delete n.accent,n.widgets&&n.widgets.length>0){const o=n.widgets.filter(s=>Rt(s)!==void 0);o.length>0?n.widgets=o:delete n.widgets}if(typeof n.accentColor=="string"){if(typeof n.accent!="string"){const o=n.accentColor,s=zo().find(i=>i.value.toLowerCase()===o);s?n.accent=s.id:(n.accent=Fa,n.customAccent=o)}delete n.accentColor}return n}const sS=/^[a-z0-9_-]+$/,Kf=128;function iS(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function qa(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!sS.test(n))return null;const o={};if(t.icons&&typeof t.icons=="object"){let l=0;for(const[c,d]of Object.entries(t.icons)){if(l>=Kf)break;c===""||!iS(d)||(o[c]=d,l+=1)}}const s={};if(t.tokens&&typeof t.tokens=="object")for(const[l,c]of Object.entries(t.tokens))typeof c=="string"&&(s[l]=c);const i=[];if(Array.isArray(t.fonts))for(const l of t.fonts)typeof l=="string"&&l!==""&&i.push(l);const r={};if(t.iconColors&&typeof t.iconColors=="object"){let l=0;for(const[c,d]of Object.entries(t.iconColors)){if(l>=Kf)break;c===""||typeof d!="string"||d===""||(r[c]=d,l+=1)}}const a=l=>typeof t[l]=="string"?t[l]:"";return{id:a("id")||n,slug:n,name:a("name")||n,version:a("version"),author:a("author"),description:a("description"),previewUrl:a("previewUrl"),cssUrl:a("cssUrl"),cssText:a("cssText"),tokens:s,fonts:i,icons:o,iconColors:r,recommendedOsSettings:Vf(t.recommendedOsSettings),drawsToolbar:t.drawsToolbar===!0,installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload",cssDeferred:t.cssDeferred===!0}}function rS(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=qa(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const Mt=se("desktop-mode/desktop-themes",rS);function jn(){return Mt}function aS(){return Mt.getState().themes.slice()}function ki(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return Mt.getState().themes.find(n=>n.slug===t||n.id===e)??null}function Si(){return Mt.getState().activeId}function cS(e){const t=qa(e);if(!t)return null;const n=Mt.state.themes.slice(),o=n.findIndex(s=>s.slug===t.slug);return o>=0?n[o]=t:n.push(t),n.sort((s,i)=>s.name.localeCompare(i.name)),Mt.setState({themes:n}),t}let jo=null;function qf(){if(jo)return jo;const e=window.openStationConfig?.desktopThemesUrl;return e?(jo=Ae(e,{method:"GET",credentials:"same-origin"},{source:"desktop-mode/desktop-themes"}).then(async t=>{if(!t.ok)throw await Wn(t);return t.json()}).then(t=>{for(const n of t?.themes??[])cS(n)}).catch(()=>{jo=null}),jo):Promise.resolve()}function lS(e){const t=[];for(const n of e){const o=qa(n);o&&t.push(o)}Mt.setState({themes:t})}function dS(e){return Mt.subscribe(e)}function Vo(e){const t=jn().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=Q(y.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function Ya(e){const t=jn().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=Q(y.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?uS(o):null}function uS(e){const t=e.trim();if(t===""||t.length>64||/[;{}<>"'\\]/.test(t))return null;let n=0;for(const o of t)if(o==="(")n+=1;else if(o===")"&&(n-=1,n<0))return null;return n===0?t:null}const nn={WINDOW_CONTROL_MINIMIZE:"WINDOW_CONTROL_MINIMIZE",WINDOW_CONTROL_MAXIMIZE:"WINDOW_CONTROL_MAXIMIZE",WINDOW_CONTROL_FULLSCREEN:"WINDOW_CONTROL_FULLSCREEN",WINDOW_CONTROL_FULLSCREEN_EXIT:"WINDOW_CONTROL_FULLSCREEN_EXIT",WINDOW_CONTROL_CLOSE:"WINDOW_CONTROL_CLOSE",WINDOW_CONTROL_MENU:"WINDOW_CONTROL_MENU",WINDOW_CONTROL_RELOAD:"WINDOW_CONTROL_RELOAD",WINDOW_CONTROL_DETACH:"WINDOW_CONTROL_DETACH",OS_SETTINGS:"OS_SETTINGS",RECYCLE_BIN:"RECYCLE_BIN",BUG_REPORT:"BUG_REPORT",EXIT_OPENSTATION:"EXIT_OPENSTATION",PWA_INSTALL:"PWA_INSTALL",DEFAULT_APP_ICON:"DEFAULT_APP_ICON",FOLDER:"FOLDER",FILE_SHORTCUT:"FILE_SHORTCUT",FILE_POST:"FILE_POST",FILE_ATTACHMENT:"FILE_ATTACHMENT",FILE_UPLOAD:"FILE_UPLOAD",FILE_USER:"FILE_USER",FILE_TERM:"FILE_TERM",FILE_COMMENT:"FILE_COMMENT",FILE_BOOKMARK:"FILE_BOOKMARK",FILE_LINK:"FILE_LINK",FILE_EMBED:"FILE_EMBED",RECYCLE_RESTORE:"RECYCLE_RESTORE",RECYCLE_DELETE:"RECYCLE_DELETE"},fS={"desktop-mode-os-settings":nn.OS_SETTINGS,"desktop-mode-recycle-bin":nn.RECYCLE_BIN,"desktop-mode-bug-report":nn.BUG_REPORT,"os-exit":nn.EXIT_OPENSTATION,"os-pwa-install":nn.PWA_INSTALL};function Vn(e){if(typeof e!="string"||e==="")return"";const t=fS[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function pS(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return nn.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in nn?n:""}const Ii=se("desktop-mode/window-channels",()=>({parentSubs:new Map,nativeSubs:new Map,readyWindows:new Set,loadingWindows:new Set,pendingSends:new Map}));function Xa(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 Yf(e,t,n,o){const s={channel:n,windowId:t},i=Xa(e,t,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel subscriber for "${n}" threw:`,l)}const r=Xa(e,t,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel wildcard subscriber for "${t}" threw:`,l)}}function hS(e,t,n){const o=Xa(Ii.state.parentSubs,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function mS(e,t,n){Yf(Ii.state.parentSubs,e,t,n)}function gS(e,t,n){Yf(Ii.state.nativeSubs,e,t,n)}function wS(e){const{readyWindows:t,loadingWindows:n,pendingSends:o}=Ii.state;if(!t.has(e)){t.add(e);const s=o.get(e);if(s){o.delete(e);for(const i of s)try{i.flush()}catch(r){typeof console<"u"&&console.error(`[openstation] flushing queued window-send for "${i.channel}" threw:`,r)}}}n.delete(e)&&(L(y.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const yS="os.activity.";function Za(e){return yS+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let bS=0;const Se={publish(e,t){L(Za(e),t)},subscribe(e,t){const n=`os/activity-sub/${++bS}`,o=Za(e);ee(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,Ct(o,n))}},filter(e,t,...n){return Q(Za(e),t,...n)}},vS=4e3,_S=200,ES=1200;function ue(e){const t=Se.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return gi(()=>!n,()=>{o=IS(t)}),()=>{n=!0,o&&o()}}const kS={success:"positive",warning:"warning",error:"critical","shell-error":"critical"};function SS(e){return e?window.openStationConfig?.toastTypes?.find(o=>o.id===e)?.tone??kS[e]??null:null}function IS(e){const t=TS(),n=document.createElement("os-toast");n.textContent=e.message;const o=SS(e.type);o&&n.setAttribute("tone",o),e.action&&(n.setAttribute("action",e.action.label),n.addEventListener("os-toast-action",()=>{e.action?.onClick(),c()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{e.onDismiss?.(),c()})),t.appendChild(n);let s=!1,i=null,r=e.duration??vS,a=0;const l=()=>{i!==null&&(window.clearTimeout(i),i=null)},c=()=>{s||(s=!0,l(),LS(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),CS()},_S))},d=()=>{s||e.persistent||i!==null||(a=Date.now(),i=window.setTimeout(c,r))},u=()=>{i!==null&&(r=Math.max(0,r-(Date.now()-a)),l())};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),n.addEventListener("os-toast-hold",f=>{if(f.detail?.held){u();return}r=Math.max(r,ES),d()}),AS(n),d(),Se.publish("os/toast-shown",{...e}),c}let Ai=null,Ko=0;function Xf(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(Ai=t))}function AS(e){Ko===0&&document.addEventListener("focusin",Xf,!0),Ko+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(Ai=n)}function CS(){Ko=Math.max(0,Ko-1),Ko===0&&document.removeEventListener("focusin",Xf,!0)}function LS(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||Ai?.isConnected===!0&&Ai.focus()}function TS(){const e=document.querySelector("os-toast-container");if(e)return e;const t=document.createElement("os-toast-container");return document.body.appendChild(t),t}const NS="http://localhost/";function nt(e,t){const n=typeof window<"u"&&window.location?window.location.href:NS,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 l=o.searchParams.get("rest_route")??"/",c=l.endsWith("/")?l:l+"/";o.searchParams.set("rest_route",c+r)}else{const l=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=l+r}return a&&new URLSearchParams(a).forEach((c,d)=>{o.searchParams.append(d,c)}),o.toString()}const OS="os-site-assistant",DS="os-overview",Zf="os-system",qo={assistant:5,mio:10,overview:20,system:30,exit:35},xS=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round"><rect x="6" y="6" width="27" height="27" rx="5"/><rect x="43" y="6" width="15" height="15" rx="5"/><rect x="43" y="31" width="15" height="27" rx="5"/><rect x="6" y="43" width="27" height="15" rx="5"/></svg>')}`,RS=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round"><path d="M10 22h44M10 42h44"/><circle cx="24" cy="22" r="7" fill="currentColor" stroke="none"/><circle cx="42" cy="42" r="7" fill="currentColor" stroke="none"/></svg>')}`,MS=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M10 2.5Q10.9 8.5 17.5 10Q10.9 11.5 10 17.5Q9.1 11.5 2.5 10Q9.1 8.5 10 2.5Z"/><path d="M17.9 14Q18.35 17.1 21.5 17.6Q18.35 18.1 17.9 21.2Q17.45 18.1 14.3 17.6Q17.45 17.1 17.9 14Z"/></svg>')}`,WS="os-exit";function PS(){return{id:WS,title:b("Exit OpenStation"),navKind:"control",locked:!0,order:qo.exit,icon:"dashicons-exit",onOpen:()=>{$S()}}}async function $S(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Ja(t);return}const n=new URLSearchParams;n.set("action","save-openstation"),n.set("nonce",e.nonce),n.set("enabled",""),e.network&&n.set("network","1");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{}Ja(o)}function Ja(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const Jf=800;function US(e,t=Jf){window.setTimeout(()=>{if(e){Ja(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const BS="desktop_mode_nonces",FS="desktop-mode/v1",HS=3e4,GS=3,Kn=se("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function Qf(){return window.wp?.os?.config??{}}function zS(){const e=Qf().restUrl;return e?nt(e,FS):null}function jS(){Kn.state.negativeConfirms=0}async function VS(){const e=Kn.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=GS)return;const t=zS();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<HS)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await Ae(t,{credentials:"same-origin"},{silent:!0,source:"desktop-mode/plugin-presence"});if(o.status!==404){e.negativeConfirms+=1;return}if((await o.json())?.code!=="rest_no_route"){e.negativeConfirms+=1;return}KS()}catch{}finally{e.confirmInFlight=!1}}}function KS(){if(!Kn.state.exiting){Kn.state.exiting=!0,US(Qf().adminUrl||"");try{ue({message:b("OpenStation is no longer active. Returning to the WordPress dashboard…"),duration:Jf})}catch{}}}function qS(){if(Kn.state.booted)return;Kn.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[BS]!==void 0){jS();return}VS()}})}const YS=0,Qa=40,ep=250,XS=120,ZS=250,Yo="os-window__loading",Ci="os-window__loading--visible",tp="classic",np="clamp(96px, 14vw, 192px)",Li=se("desktop-mode/window-reveal-active",()=>({id:Ho,duration:Ua}));function op(e){Li.state.id=typeof e=="string"&&e!==""?e:Ho}function JS(){const e=Li.state.id;return!e||e===Ho?null:Tf(e)??null}function sp(e){Li.state.duration=If(e)}function QS(){return Li.state.duration}function eI({osSettings:e}){const t=e.getOsSettingsSnapshot();op(t.windowReveal),sp(t.windowRevealDuration),e.subscribeOsSettings(n=>{op(n.windowReveal),sp(n.windowRevealDuration)})}const qn="os-window__reveal",Xo="os-window__reveal--edge",tI="os-window__reveal--custom",on="os-window__body--revealing",ec="data-os-reveal",tc="data-os-reveal-layer",Wt=new WeakMap,ip=se("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function rp(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const nI="--os-window-reveal-duration",oI="--os-window-reveal-edge-thickness";function ap(e){const t=e.trim();if(t==="")return 0;const n=/^(-?\d*\.?\d+)\s*(ms|s)?$/i.exec(t);if(!n)return 0;const o=Number(n[1]);return Number.isFinite(o)?n[2]?.toLowerCase()==="s"?o*1e3:o:0}function sI(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return If(ap(window.getComputedStyle(e).getPropertyValue(nI)))}catch{return 0}}function iI(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function rI(e,t){const n=iI(e,oI);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return Un(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return Un(t*Number(s[1]));const i=ap(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?Un(i):null}function cp(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return!1;try{const t=window.getComputedStyle(e),n=t.backgroundImage;if(n&&n!=="none")return!1;const o=/^rgba?\(([^)]+)\)$/.exec(t.backgroundColor.trim());if(!o)return!1;const s=o[1].split(/[,\s/]+/).filter(Boolean);return s.length>=4&&Number(s[3])===0}catch{return!1}}function aI(e,t){const n=Gk(t.duration),o=QS(),s=o!==Ua?o:sI(e)||n,i=rI(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=Un(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:Un(r*s/n)}}function lp(e){return e.querySelector(":scope .os-window__body")}function cI(e){return e.querySelector(`:scope .${qn}:not( .${Xo} )`)}function lI(e){return e.querySelector(`:scope .${Xo}`)}function dp(e){return Array.from(e.querySelectorAll(`:scope .${qn}:not( .${Xo} )`))}function up(e){return Array.from(e.querySelectorAll(`:scope .${Xo}`))}function nc(e){return Array.from(e.querySelectorAll(`:scope .${qn}`))}function fp(e,t,n,o){const s=document.createElement("div");s.className=o?`${qn} ${Xo}`:qn;const i=o?e.edgeColor:t.color??e.surfaceColor;return typeof i=="string"&&i!==""&&(s.style.background=i),s.setAttribute("aria-hidden","true"),s.setAttribute(ec,e.id),s.setAttribute(tc,String(n)),s.style.clipPath=t.from,s}function dI(){const e=JS();if(!e)return[];if(typeof e.render=="function"){let o;try{o=e.render()}catch(i){return typeof console<"u"&&console.error(`[openstation] window reveal "${e.id}" render threw:`,i),[]}if(!o?.element||typeof o.play!="function")return[];const s=o.element;return s.classList.add(qn),s.classList.add(tI),s.setAttribute("aria-hidden","true"),s.setAttribute(ec,e.id),s.setAttribute(tc,"0"),ip.set(s,o.play),[s]}const t=Af(e);if(t.length===0)return[];const n=[];return Un(e.edgeLag)>0&&t.forEach((o,s)=>n.push(fp(e,o,s,!0))),t.forEach((o,s)=>n.push(fp(e,o,s,!1))),n}function uI(e){const t=lp(e);if(t){t.classList.remove(on);for(const n of nc(t))Wt.get(n)?.cancel(),Wt.delete(n),n.remove();for(const n of dI())t.appendChild(n)}}function pp(e){const t=lp(e);if(!t)return;const n=cI(t);if(!n)return;let o;try{o=Tf(n.getAttribute(ec)??"")}catch(S){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",S)}if(!o){nc(t).forEach(S=>S.remove());return}const i=!!t.querySelector(`:scope .${Yo}`)?.classList.contains(Ci)?ep:0,{duration:r,edgeLag:a}=aI(t,o),l=o.easing??Uk,c=ip.get(n);if(c){t.classList.add(on);const S=()=>{Wt.delete(n),n.remove(),t.classList.remove(on)};if(rp()||typeof n.animate!="function"){window.setTimeout(S,i);return}let $=[];try{$=c({duration:r,easing:l,delay:i})}catch(W){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,W)}if($.length===0){S();return}$[0].addEventListener("finish",S),$[0].addEventListener("cancel",()=>{Wt.delete(n),t.classList.remove(on)}),Wt.set(n,$[0]);return}const d=lI(t);d&&(a<=0||cp(d))&&up(t).forEach(S=>S.remove()),cp(n)&&dp(t).forEach(S=>S.remove());const u=nc(t);if(u.length===0)return;t.classList.add(on);const f=()=>{for(const S of u)Wt.delete(S),S.remove();t.classList.remove(on)};if(rp()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,g=Af(o),h=(S,$)=>{const W=g[Number(S.getAttribute(tc))];if(!W)return S.remove(),null;S.style.willChange="clip-path";let F;try{F=S.animate([{clipPath:W.from},{clipPath:W.to}],{duration:$,easing:p,delay:i,fill:"both"})}catch(x){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,x),S.remove(),null}return Wt.set(S,F),F},m=dp(t).map(S=>h(S,r)).filter(S=>S!==null),E=up(t).map(S=>h(S,r+a)).filter(S=>S!==null),k=m[0]??null,N=E[0]??null;if(!k&&!N){f();return}(N??k)?.addEventListener("finish",f);const M=()=>{for(const S of u)Wt.delete(S);t.classList.remove(on)};k?.addEventListener("cancel",M),N?.addEventListener("cancel",M)}const fI="os-window-tab-change";function hp(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function mp(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function gp(e,t){return`${e.id||"os-window"}-tab-${mp(t)}`}function wp(e,t){return`${e.id||"os-window"}-panel-${mp(t)}`}function pI(e){const t=e.querySelector(".os-window__tab-plate");if(!t)return;const n=e.querySelector(".os-window__tab--active");if(!n){t.dataset.empty="",e.dataset.tabPlateEmpty="";return}delete t.dataset.empty,delete e.dataset.tabPlateEmpty,e.style.setProperty("--_tab-plate-x",`${n.offsetLeft}px`),e.style.setProperty("--_tab-plate-w",`${n.offsetWidth}px`),e.style.setProperty("--_tab-strip-w",`${e.clientWidth}px`),n.offsetWidth>0&&(t.dataset.placed="")}function oc(e){if(e){if(e.querySelector(":scope > .os-window__tab")){e.setAttribute("role","tablist");const t=e.dataset.tablistLabel;t&&e.setAttribute("aria-label",t);return}e.setAttribute("role","presentation"),e.removeAttribute("aria-label")}}function hI(e){const t=hp(e);if(t.length===0)return;const n=t.find(o=>o.classList.contains("os-window__tab--active"))??t[0];for(const o of t){const s=o===n?0:-1;o.tabIndex!==s&&(o.tabIndex=s)}}function yp(e){const t=new Map;for(const n of hp(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function bp(e){const t=e.querySelector(".os-window__body");return t?Array.from(t.querySelectorAll("os-tabpanel[ for ]")).filter(n=>!n.parentElement?.closest("os-tabpanel, os-tabs")):[]}function mI(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of yp(n)){const r=s===t;o=o||r,i.classList.toggle("os-window__tab--active",r),i.setAttribute("aria-selected",r?"true":"false")}if(o){for(const s of bp(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}hI(n),pI(n),e.dispatchEvent(new CustomEvent(fI,{bubbles:!0,detail:{value:t}}))}}function gI(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=yp(o),i=Array.from(s.entries()).find(([,d])=>d.classList.contains("os-window__tab--active"))?.[0];let r=o.querySelector(".os-window__tab-plate");for(const d of t){let u=s.get(d.value);if(u)s.delete(d.value);else{const f=document.createElement("button");f.type="button",u=f,u.className="os-window__tab",u.dataset.kind="panel",u.dataset.panel=d.value,u.setAttribute("role","tab"),u.setAttribute("aria-selected","false"),u.tabIndex=-1}u.textContent!==d.label&&(u.textContent=d.label),u.id=gp(e,d.value),u.setAttribute("aria-controls",wp(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();oc(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of bp(e)){const u=d.getAttribute("for");u&&(d.id=wp(e,u),a?d.setAttribute("aria-labelledby",gp(e,u)):d.removeAttribute("aria-labelledby"))}const l=d=>d!==void 0&&t.some(u=>u.value===d),c=[n,i,t[0]?.value].find(l);c!==void 0&&mI(e,c)}const Zo="os-window__body--loading",sc="os-window__body--loading-out",ic="data-os-loading-at",vp="data-os-loading-cycle";function Ti(e){return e.getAttribute(vp)??"0"}function wI(e){e.setAttribute(ic,String(Date.now())),e.setAttribute(vp,String(Number(Ti(e))+1))}function yI(e,t){const n=Number(e.getAttribute(ic)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=XS-o;if(s<=0){t.classList.add(Ci);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(Zo)&&t.classList.add(Ci)},s)}const bI=Symbol.for("desktop-mode/window-config");function vI(e){return e[bI]}const rc=window.location.origin;function _I(e){try{return new URL(e,rc).searchParams.has(Xu)}catch{return!1}}function EI(e){const t=new URL(e,rc);return t.origin!==rc||Rn(t)?null:(t.searchParams.set("openstation_chromeless","1"),t.toString())}function ac(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function _p(){const e=document.createElement("div");e.className=Yo,e.setAttribute("role","status"),e.setAttribute("aria-live","polite");const t=document.createElement("os-spinner");return t.setAttribute("preset",tp),t.setAttribute("size",np),t.setAttribute("label",b("Loading window content")),e.appendChild(t),e}function kI(e){let t=_p();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(`[openstation] loading.render threw for "${e.id}":`,o)}try{const o=Q(y.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[openstation] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains(Yo)&&t.classList.add(Yo),t}function Ep(e){e.querySelector(":scope .os-window__loading")?.remove()}function kp(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=vI(e),s=o?kI(o):_p();t.appendChild(s),yI(t,s)}function SI(e){const t=[],n=(e.submenu??[]).filter(l=>!l.offSite&&!_I(l.url));if(n.length===0||!e.url)return[];const o=Lt(e.url),s=e.parentUrl??e.url,i=Lt(s),a=n.some(l=>Lt(l.url)===i)?[...n]:[{title:e.selfLabel||e.title,url:s},...n];for(const l of a){const c=document.createElement("button");c.className="os-window__tab",c.dataset.kind="submenu",c.setAttribute("type","button"),c.setAttribute("role","tab"),c.dataset.url=l.url,c.textContent=l.title,Lt(l.url)===o?(c.classList.add("os-window__tab--active"),c.setAttribute("aria-selected","true")):c.setAttribute("aria-selected","false"),t.push(c)}return t}const Sp=8,Ip=Object.freeze({top:0,right:0,bottom:0,left:0});function Ap(e,t,n,o){return{left:e,top:t,width:n,height:o,right:e+n,bottom:t+o}}function II(e,t){const n=t.left+t.width/2,o=t.top+t.height/2,s={top:Math.abs(o-e.top),bottom:Math.abs(e.bottom-o),left:Math.abs(n-e.left),right:Math.abs(e.right-n)},r=t.height>t.width?["left","right","top","bottom"]:["top","bottom","left","right"];let a=r[0];for(const l of r)s[l]<s[a]&&(a=l);return a}function AI(e,t,n=Sp){const o={top:0,right:0,bottom:0,left:0};if(e.width<=0||e.height<=0)return o;for(const r of t){if(r.width<=0||r.height<=0)continue;const a=Math.min(e.right,r.right)-Math.max(e.left,r.left),l=Math.min(e.bottom,r.bottom)-Math.max(e.top,r.top);if(!(a<=0||l<=0))switch(II(e,r)){case"bottom":o.bottom=Math.max(o.bottom,e.bottom-r.top+n);break;case"top":o.top=Math.max(o.top,r.bottom-e.top+n);break;case"left":o.left=Math.max(o.left,r.right-e.left+n);break;case"right":o.right=Math.max(o.right,e.right-r.left+n);break}}const s=Math.floor(e.height/2),i=Math.floor(e.width/2);return{top:Math.min(s,Math.ceil(o.top)),bottom:Math.min(s,Math.ceil(o.bottom)),left:Math.min(i,Math.ceil(o.left)),right:Math.min(i,Math.ceil(o.right))}}function Cp(e,t,n){return{x:n.left,y:n.top,width:Math.max(0,e-n.left-n.right),height:Math.max(0,t-n.top-n.bottom)}}function CI(e,t){const n=s=>Math.min(Math.max(0,t.width),Math.max(0,s)),o=s=>Math.min(Math.max(0,t.height),Math.max(0,s));return{top:o(e.top-t.top),bottom:o(t.bottom-e.bottom),left:n(e.left-t.left),right:n(t.right-e.right)}}function LI(e,t){return e.top===t.top&&e.right===t.right&&e.bottom===t.bottom&&e.left===t.left}function Lp(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const TI="os-work-area-changed",NI="data-os-dock-behavior",OI="os/work-area";function DI(){return{insets:{...Ip},rect:{x:0,y:0,width:0,height:0},viewport:{x:0,y:0,width:0,height:0},area:{width:0,height:0}}}const _t=se(OI,()=>({snapshot:DI(),installed:!1,areaEl:null})),Yn={top:"--os-work-area-inset-top",right:"--os-work-area-inset-right",bottom:"--os-work-area-inset-bottom",left:"--os-work-area-inset-left",width:"--os-work-area-width",height:"--os-work-area-height"};function cc(e){return{insets:{...e.insets},rect:{...e.rect},viewport:{...e.viewport},area:{...e.area}}}function Tp(){return cc(_t.state.snapshot)}function he(e){const t=e??_t.state.areaEl;if(!t)return{..._t.state.snapshot.rect};const n=t.clientWidth||t.getBoundingClientRect().width,o=t.clientHeight||t.getBoundingClientRect().height;return Cp(n,o,_t.state.snapshot.insets)}function xI(e){const{installed:t,snapshot:n}=_t.state;if(!t)return{...Ip};const o=n.viewport;return CI(Ap(o.x,o.y,o.width,o.height),e.getBoundingClientRect())}function Jo(e){return _t.subscribe(t=>{e(cc(t.snapshot))})}function RI(e){const t=MI(e),n=[],o=e.shellBody.querySelectorAll(e.chromeSelector??".os-dock");for(const l of Array.from(o))l.hidden||l.getAttribute(NI)==="dynamic"||n.push(l.getBoundingClientRect());const s=AI(t,n),i=e.area.clientWidth||t.width,r=e.area.clientHeight||t.height,a=Cp(i,r,s);return{insets:s,rect:a,viewport:{x:t.left+a.x,y:t.top+a.y,width:a.width,height:a.height},area:{width:i,height:r}}}function MI(e){const{area:t}=e;if(t.offsetWidth>0&&t.offsetParent===e.shellBody){const n=e.shellBody.getBoundingClientRect();return Ap(n.left+t.offsetLeft,n.top+t.offsetTop,t.offsetWidth,t.offsetHeight)}return t.getBoundingClientRect()}function WI(e,t){e.style.setProperty(Yn.top,`${t.insets.top}px`),e.style.setProperty(Yn.right,`${t.insets.right}px`),e.style.setProperty(Yn.bottom,`${t.insets.bottom}px`),e.style.setProperty(Yn.left,`${t.insets.left}px`),e.style.setProperty(Yn.width,`${t.rect.width}px`),e.style.setProperty(Yn.height,`${t.rect.height}px`)}function PI(e,t){return LI(e.insets,t.insets)&&Lp(e.rect,t.rect)&&Lp(e.viewport,t.viewport)&&e.area.width===t.area.width&&e.area.height===t.area.height}function $I(e){const t=new Map;let n=null,o=null,s=!1,i=!1,r=null;const a=()=>{if(s||i)return;const p=RI(e);if(!!_t.state.installed&&PI(_t.state.snapshot,p))return;WI(e.shell,p),_t.setState({snapshot:p,installed:!0,areaEl:e.area});const h=cc(p);L(y.WORK_AREA_CHANGED,h),document.dispatchEvent(new CustomEvent(TI,{detail:h}))},l=typeof ResizeObserver<"u",c=()=>{if(!l)return;const p=new Set(Array.from(e.shellBody.querySelectorAll(e.chromeSelector??".os-dock")));for(const[g,h]of t)p.has(g)||(h.disconnect(),t.delete(g));for(const g of p){if(t.has(g))continue;const h=new ResizeObserver(a);h.observe(g,{box:"border-box"}),t.set(g,h)}};l&&(n=new ResizeObserver(a),n.observe(e.area)),typeof MutationObserver<"u"&&(o=new MutationObserver(()=>{c(),a()}),o.observe(e.shellBody,{childList:!0}));const d=()=>{c(),a()};document.addEventListener("os-layout-changed",d),window.addEventListener("resize",a);const u=()=>{i=!0},f=()=>{i=!1,a()};return ee(y.OVERVIEW_ENTERING,Ni,u),ee(y.OVERVIEW_EXITED,Ni,f),c(),a(),r={refresh:a,destroy:()=>{s=!0,n?.disconnect(),o?.disconnect();for(const p of t.values())p.disconnect();t.clear(),document.removeEventListener("os-layout-changed",d),window.removeEventListener("resize",a),Ct(y.OVERVIEW_ENTERING,Ni),Ct(y.OVERVIEW_EXITED,Ni),Oi===r&&(Oi=null)}},Oi=r,r}const Ni="openstation/work-area";let Oi=null;function UI(){Oi?.refresh()}const BI={get:Tp,rectOf:he,insetsOf:xI,subscribe:Jo};function FI(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){Np(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("os-area--split-overview");const s=qI(e,n),i=La(o,s,0);e._splitOverviewLabels.clear();for(const a of i){const l=a.win.element;l.classList.add("os-window--overview");const c=a.x-l.offsetLeft,d=a.y-l.offsetTop;l.style.transform=`translate(${c}px, ${d}px) scale(${a.scale})`;const u=kc(a);l.insertAdjacentElement("afterend",u),e._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const l=a.target,c=l?.closest(".os-window--overview");return c?{id:c.id.replace(/^wp-window-/,""),element:c}:l?{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 l=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!l)return;const c=l.element.getBoundingClientRect();if(!(a.clientX>=c.left&&a.clientX<=c.right&&a.clientY>=c.top&&a.clientY<=c.bottom))return;if(a.preventDefault(),a.stopPropagation(),l.id==="dismiss"){Qo(e);return}const u=e.getById(l.id);if(!u){Qo(e);return}HI(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&Qo(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 HI(e,t){const n=e._splitOverviewZone;if(!n){Qo(e);return}const o=n==="left"?"right":"left";t.element.style.transform="",t.element.classList.remove("os-window--overview"),t.applySnap(o),e._splitOverviewSnapshot.delete(t.id),e.focus(t),L(y.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),Qo(e)}function Qo(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("os-overview-label--out");e._desktop.classList.remove("os-area--split-overview"),window.setTimeout(()=>{for(const n of e._stack)e._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("os-window--overview");for(const n of e._splitOverviewLabels.values())n.remove();Np(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 Np(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const Op=30,GI=260;function zI(e,t){return e<=t.left+Op?"left":e>=t.right-Op?"right":null}function lc(e){return e.state==="snapped-left"?"left":e.state==="snapped-right"?"right":null}function Di(e,t,n){const o=n==="left"?"right":"left";let s=0;for(const i of e._stack)i!==t&&i.config.desktopId===t.config.desktopId&&lc(i)===o&&(s=Math.max(s,i.config.minWidth||0));return s}function jI(e,t,n){const o=Ca(he(e._desktop),t,n?.config.minWidth||0,n?Di(e,n,t):0);return{...o,height:Math.floor(o.height)}}function VI(e,t){const n=lc(t),o=t.element.parentElement;if(!n||!o)return;const s=Ca(he(o),n,t.config.minWidth||0,Di(e,t,n)),i={left:`${s.x}px`,top:`${s.y}px`,width:`${s.width}px`,height:`${s.height}px`},r=t.element.style;r.left===i.left&&r.top===i.top&&r.width===i.width&&r.height===i.height||(r.left=i.left,r.top=i.top,r.width=i.width,r.height=i.height)}function KI(e){let t=new Map;const n=()=>{if(e._overviewActive)return;const o=new Map;for(const r of e._stack){const a=lc(r);a&&o.set(r.id,{zone:a,desktopId:r.config.desktopId||""})}const s=new Set,i=(r,a)=>{for(const[l,c]of r){const d=a.get(l);(!d||d.zone!==c.zone||d.desktopId!==c.desktopId)&&s.add(c.desktopId)}};if(i(t,o),i(o,t),t=o,s.size!==0)for(const r of e._stack){const a=o.get(r.id);a&&s.has(a.desktopId)&&VI(e,r)}};return document.addEventListener("os-window-changed",n),document.addEventListener("os-window-closed",n),()=>{document.removeEventListener("os-window-changed",n),document.removeEventListener("os-window-closed",n)}}function qI(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 YI(e,t,n){if(e._snapPendingZone===t&&e._snapPreviewEl)return;if(e._snapPendingZone=t,!e._snapPreviewEl){const s=document.createElement("div");s.className="os-snap-preview",s.setAttribute("aria-hidden","true"),e._desktop.appendChild(s),e._snapPreviewEl=s,Promise.resolve().then(()=>{s.classList.add("os-snap-preview--visible")})}const o=jI(e,t,n);e._snapPreviewEl.style.left=`${o.x}px`,e._snapPreviewEl.style.top=`${o.y}px`,e._snapPreviewEl.style.width=`${o.width}px`,e._snapPreviewEl.style.height=`${o.height}px`,e._snapPreviewEl.dataset.zone=t}function dc(e){if(!e._snapPreviewEl){e._snapPendingZone=null;return}const t=e._snapPreviewEl;e._snapPreviewEl=null,e._snapPendingZone=null,t.classList.remove("os-snap-preview--visible"),window.setTimeout(()=>{t.remove()},GI)}function XI(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=zI(n,o),i=e._snapPendingZone;s?(YI(e,s,t),i!==s&&L(y.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(dc(e),L(y.SNAP_ZONE_CANCELED,{windowId:t.id}))}function ZI(e,t){const n=e._snapPendingZone;return n?(dc(e),t.snapTo(n),L(y.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{FI(e,t,n)}),!0):!1}function Dp(e){e._snapPendingZone&&dc(e)}const JI=6,QI=6,eA=8,tA={Shake:"shake"},xp="os-window--grid-snapping",Rp="os-area--grid-snapping";function nA(e){const t={cols:JI,rows:QI},n=Q(y.GRID_SNAP_DIMENSIONS,t,{areaWidth:e.width,areaHeight:e.height});return!!n&&Number.isInteger(n.cols)&&Number.isInteger(n.rows)&&n.cols>=1&&n.rows>=1&&n.cols<=24&&n.rows<=24?{cols:n.cols,rows:n.rows}:t}function uc(e,t,n,o){const s=(e-n.x)/Math.max(1,n.width),i=(t-n.y)/Math.max(1,n.height);return{col:Mp(Math.floor(s*o.cols),o.cols),row:Mp(Math.floor(i*o.rows),o.rows)}}function Mp(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t-1,e)):0}function oA(e,t,n,o){const s=Math.min(e.col,t.col),i=Math.max(e.col,t.col)+1,r=Math.min(e.row,t.row),a=Math.max(e.row,t.row)+1,l=n.x+Math.round(n.width*s/o.cols),c=n.x+Math.round(n.width*i/o.cols),d=n.y+Math.round(n.height*r/o.rows),u=n.y+Math.round(n.height*a/o.rows);return{x:l,y:d,width:c-l,height:u-d}}function xi(e,t,n,o){const s=oA(e,t,n,o),i=Math.round(eA/2);return s.width<=i*4||s.height<=i*4?s:{x:s.x+i,y:s.y+i,width:s.width-i*2,height:s.height-i*2}}function sA(e,t){return e.col===t.col&&e.row===t.row}function fc(e,t,n){const o=e._desktop.getBoundingClientRect();return{x:t-o.left,y:n-o.top}}function pc(e,t){const{overlayEl:n,targetEl:o,dims:s,rect:i}=e;n.style.left=`${t.x}px`,n.style.top=`${t.y}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.setProperty("--os-grid-snap-cols",String(s.cols)),n.style.setProperty("--os-grid-snap-rows",String(s.rows)),o.style.left=`${i.x-t.x}px`,o.style.top=`${i.y-t.y}px`,o.style.width=`${i.width}px`,o.style.height=`${i.height}px`,o.dataset.cols=String(Math.abs(e.cursor.col-e.anchor.col)+1),o.dataset.rows=String(Math.abs(e.cursor.row-e.anchor.row)+1)}function iA(e,t,n,o){if(e._gridSnap)return;Dp(e);const s=he(e._desktop),i=nA(s),r=fc(e,n,o),a=uc(r.x,r.y,s,i),l=document.createElement("div");l.className="os-grid-snap",l.setAttribute("aria-hidden","true");const c=document.createElement("div");c.className="os-grid-snap__target",l.appendChild(c),e._desktop.appendChild(l);const d={windowId:t.id,dims:i,anchor:a,cursor:a,rect:xi(a,a,s,i),overlayEl:l,targetEl:c,windowEl:t.element};e._gridSnap=d,t.element.classList.add(xp),e._desktop.classList.add(Rp),pc(d,s),requestAnimationFrame(()=>{e._gridSnap===d&&l.classList.add("os-grid-snap--visible")}),L(y.GRID_SNAP_ARMED,{windowId:t.id,anchor:{...a},dims:{...i}}),L(y.GRID_SNAP_CHANGED,{windowId:t.id,anchor:{...a},cursor:{...a},rect:{...d.rect}})}function rA(e,t,n){const o=e._gridSnap;if(!o)return;const s=he(e._desktop),i=fc(e,t,n),r=uc(i.x,i.y,s,o.dims),a=xi(o.anchor,r,s,o.dims),l=!sA(r,o.cursor),c=a.x!==o.rect.x||a.y!==o.rect.y||a.width!==o.rect.width||a.height!==o.rect.height;o.cursor=r,o.rect=a,pc(o,s),(l||c)&&L(y.GRID_SNAP_CHANGED,{windowId:o.windowId,anchor:{...o.anchor},cursor:{...r},rect:{...a}})}function aA(e,t,n,o){const s=e._gridSnap;if(!s)return;const i=he(e._desktop),r=fc(e,t,n),a=uc(r.x,r.y,i,s.dims);s.anchor=a,s.cursor=a,s.rect=xi(a,a,i,s.dims),pc(s,i),s.targetEl.classList.remove("os-grid-snap__target--reset"),s.targetEl.offsetWidth,s.targetEl.classList.add("os-grid-snap__target--reset"),L(y.GRID_SNAP_ANCHOR_RESET,{windowId:s.windowId,anchor:{...a},reason:o}),L(y.GRID_SNAP_CHANGED,{windowId:s.windowId,anchor:{...a},cursor:{...a},rect:{...s.rect}})}const cA=200;function Wp(e){const t=e._gridSnap;if(!t)return null;e._gridSnap=null,t.windowEl.classList.remove(xp),e._desktop.classList.remove(Rp);const n=t.overlayEl;return n.classList.remove("os-grid-snap--visible"),window.setTimeout(()=>n.remove(),cA),t}function lA(e){const t=Wp(e);t&&L(y.GRID_SNAP_CANCELED,{windowId:t.windowId})}function dA(e,t){const n=Wp(e);if(!n)return!1;const{rect:o}=n;t.state==="normal"&&(t._savedGeometry=null),t.element.style.left=`${o.x}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${o.width}px`,t.element.style.height=`${o.height}px`,t._emitChange("moved"),t._emitChange("resized"),t._gridSpan={anchor:{...n.anchor},cursor:{...n.cursor},cols:n.dims.cols,rows:n.dims.rows};const s={windowId:t.id,x:o.x,y:o.y,width:o.width,height:o.height};return L(y.GRID_SNAP_COMMITTED,{...s,anchor:{...n.anchor},cursor:{...n.cursor},dims:{...n.dims}}),L(y.WINDOW_DRAG_END,{windowId:t.id,x:o.x,y:o.y}),L(y.WINDOW_MOVED,{windowId:t.id,x:o.x,y:o.y}),L(y.WINDOW_RESIZED,{windowId:t.id,width:o.width,height:o.height}),!0}function Pp(e,t){return xi(e.anchor,e.cursor,t,{cols:e.cols,rows:e.rows})}function $p(e,t){const n=e._gridSpan;if(!n||e.state!=="normal"&&e.state!=="minimized")return!1;const o=Pp(n,t),s=e.element,i={left:`${o.x}px`,top:`${o.y}px`,width:`${o.width}px`,height:`${o.height}px`};return s.style.left===i.left&&s.style.top===i.top&&s.style.width===i.width&&s.style.height===i.height?!1:(s.style.left=i.left,s.style.top=i.top,s.style.width=i.width,s.style.height=i.height,!0)}function uA(e){const t=he(e._desktop),n=[];for(const o of e._stack)$p(o,t)&&(o._emitChange("moved"),n.push(o.id));return n.length>0&&L(y.GRID_SNAP_REFLOWED,{windowIds:n}),n}function fA(e){return Jo(()=>{uA(e)})}function pA(e){return[e.id,e.menu?.url??"",e.entry?.url??"",e.windowId??"",e.title].join(`
2 `).toLowerCase()}function Up(e,t){const n=t.trim().toLowerCase();return n?pA(e).includes(n):!1}function hA(e,t){if(t.length===0)return[];const n=[],o=new Set;for(const s of e)o.has(s.id)||t.some(i=>Up(s,i))&&(o.add(s.id),n.push(s.id));return n}function Bp(e,t){const n=[];for(const o of t){const s=e.find(i=>Up(i,o.match));s&&n.push({item:s,url:o.url??s.menu?.url??s.entry?.url??"",title:o.title??s.title,...o.gridSpan?{gridSpan:o.gridSpan}:{},...o.place?{place:o.place}:{}})}return n}const mA=["index.php","upload.php","options-general.php"];function gA(){return[{id:"commerce",label:b("Commerce"),description:b("A shop floor. WooCommerce orders, products and analytics side by side; everything that is not commerce leaves the rails."),icon:"dashicons-cart",color:"#7f54b3",defaultLabel:b("Commerce"),order:10,apps:["woocommerce","wc-admin","wc-orders","wc-reports","wc-settings","post_type=product","post_type=shop_order","post_type=shop_coupon","edit-tags.php?taxonomy=product_cat","users.php"],widgets:["clock","desktop-mode/site-views"],appearance:{wallpaper:"dark",accent:"indigo"},windows:[{match:"wc-orders"},{match:"post_type=product",url:"edit.php?post_type=product"},{match:"wc-admin"}],layout:"columns"},{id:"learning",label:b("Learning"),description:b("A course studio. Sensei courses, lessons and learners tiled together, so moving between them is a glance rather than a navigation."),icon:"dashicons-welcome-learn-more",color:"#43a047",defaultLabel:b("Learning"),order:20,apps:["sensei","post_type=course","post_type=lesson","post_type=question","post_type=sensei_message","sensei_learner_admin","sensei-settings","users.php"],widgets:["clock","desktop-mode/heartbeat","desktop-mode/recent-comments"],appearance:{wallpaper:"aurora",accent:"emerald"},windows:[{match:"post_type=course",url:"edit.php?post_type=course"},{match:"post_type=lesson",url:"edit.php?post_type=lesson"},{match:"sensei"}],layout:"tile"},{id:"publishing",label:b("Publishing"),description:b("A writing desk. A blank page takes two thirds of the screen, the library sits in the margin, and the rest of the admin is somewhere else."),icon:"dashicons-edit-page",color:"#c8102e",defaultLabel:b("Publishing"),order:30,apps:["edit.php","post-new.php","upload.php","edit-comments.php","edit-tags.php","post_type=page"],widgets:["desktop-mode/drafts","desktop-mode/post-stats","desktop-mode/focus-timer","desktop-mode/notes"],appearance:{wallpaper:"mono",accent:"rose",dockBehavior:"dynamic"},windows:[{match:"edit.php",url:"post-new.php",title:b("New draft")},{match:"edit.php",url:"edit.php"}],layout:"focus"}]}const hc=new Map;function Fp(e){e?.id&&hc.set(e.id,e)}function mc(e){hc.delete(e)}function es(){const e=[...gA(),...hc.values()],t=Q(y.WORKSPACE_PRESETS,e);return(Array.isArray(t)?t.slice():e).map((o,s)=>({preset:o,index:s})).sort((o,s)=>(o.preset.order??0)-(s.preset.order??0)||o.index-s.index).map(o=>o.preset)}function wA(e){return es().find(t=>t.id===e)??null}function Hp(e,t){const n=[...e.apps,...e.apps.length?mA:[]],o=hA(t,n),s=e.widgets??[];return{preset:e.id,icon:e.icon,color:e.color,apps:{mode:e.apps.length>0?"only":"all",ids:o},widgets:{mode:s.length>0?"only":"all",ids:s.slice()},appearance:{...e.appearance??{}},windows:e.windows.map(i=>({...i})),layout:e.layout,provisioned:!1}}const yA=12,bA=["free","cascade","tile","columns","focus"],Gp=["wallpaper","wallpaperSettings","customGradient","customImage","accent","customAccent","desktopTheme","desktopLayout","dockPlacement","dockSize","dockBehavior","sideDockBehavior","windowRadius","windowReveal","unfocusEffect","adminBarMode"];function zp(){return{preset:"",icon:"dashicons-desktop",color:"",apps:{mode:"all",ids:[]},widgets:{mode:"all",ids:[]},appearance:{},windows:[],layout:"free",provisioned:!0}}function vA(e){return e.kind!=="control"&&!e.locked}function _A(e,t,n){if(!n||n.apps.mode!=="only")return e;const o=new Set(n.apps.ids),s={...e};for(const i of t)o.has(i.id)||!vA(i)||(s[i.id]="hidden");return s}function EA(e){const t=e?.widgets;return!t||t.mode!=="only"?null:t.ids}function gc(e){const t=e?.appearance;if(!t)return null;const n={};for(const o of Gp)t[o]!==void 0&&(n[o]=t[o]);return Object.keys(n).length>0?n:null}function jp(e){const t={};for(const n of Gp)e[n]!==void 0&&(t[n]=e[n]);return t}function kA(e,t,n){const o=e.widgets;return!o||o.mode!=="only"||o.ids.includes(t)===n?e:{...e,widgets:{mode:"only",ids:[...o.ids,t]}}}function sn(e,t){return e.getDesktops().find(n=>n.id===t)?.profile??null}function SA(e){return sn(e,e.getActiveDesktopId())}function Xn(e,t,n){const o=e.manager._desktops.find(i=>i.id===t);if(!o)return!1;const s=JSON.stringify(gc(o.profile));return n?o.profile=n:delete o.profile,e.refreshLayout(),t===e.manager.getActiveDesktopId()&&(JSON.stringify(gc(n))===s?Vp(e,t):wc(e,t)),L(y.WORKSPACE_UPDATED,{desktopId:t,profile:n}),!0}function Vp(e,t){e.setVisibleWidgets?.(EA(sn(e.manager,t)))}function IA(e,t){e.setAppearance?.(gc(sn(e.manager,t)))}function wc(e,t){IA(e,t),Vp(e,t)}function Ri(e,t={}){const n=t.preset?wA(t.preset):null;let o=t.profile??null;!o&&n&&(o=Q(y.WORKSPACE_PROFILE,Hp(n,e.getNavItems()),n));const i=(t.desktopId?e.manager.getDesktops().find(a=>a.id===t.desktopId):void 0)??e.manager.createDesktop(),r=t.label??n?.defaultLabel??n?.label??"";return r&&e.manager.renameDesktop(i.id,r),o&&Xn(e,i.id,o),t.activate!==!1&&e.manager.switchDesktop(i.id),i}function Kp(e,t){switch(t){case"cascade":e.cascade();break;case"tile":e.tile();break;case"columns":e.columns();break;case"focus":e.focusLayout();break}}function qp(e,t,n){const o=n.item.menu?.url;return $o(t)??e.deriveWindowId(o?Mi(o,e.adminUrl):t)}function Yp(e,t,n,o){const s=[(r,a)=>r.id===a,(r,a)=>e.deriveWindowId(r.config.url??"")===a,()=>!0],i=new Map;for(const r of s)for(const a of t){if(!a.url||i.has(a))continue;const l=Mi(a.url,e.adminUrl),c=e.deriveWindowId(l),d=e.manager.getAllByBaseId(qp(e,l,a)).find(u=>!o.has(u.id)&&(!u.config.desktopId||u.config.desktopId===n)&&r(u,c));d&&(o.add(d.id),i.set(a,d))}return i}function Xp(e,t,n,o,s){const i=$o(t);if(i){const a=new Set(e.manager.getAllByBaseId(i).map(l=>l.id));if(Be(t,{newInstance:!0}))return vc(e.manager,i,l=>!a.has(l.id)&&!s.has(l.id))}const r=n.item.menu;return e.manager.openNew({id:e.deriveWindowId(t),baseId:qp(e,t,n),url:t,parentUrl:r?.url??t,title:n.title??n.item.title,icon:n.item.icon,submenu:r?.submenu,selfLabel:r?.selfLabel,multi:!!r?.multi,desktopId:o})}function yc(e,t,n={}){const o=sn(e.manager,t);if(!o||o.provisioned&&!n.force)return;Xn(e,t,{...o,provisioned:!0});const s=Bp(e.getNavItems(),o.windows),i=new Set,r=Yp(e,s,t,i),a=[];let l=0;for(const[d,u]of s.entries()){if(u.url){const f=Mi(u.url,e.adminUrl);l++;const p=r.get(u);if(p){a[d]=p.id,ts(e.manager,p,u);continue}Xp(e,f,u,t,i).then(g=>{g&&(i.add(g.id),a[d]=g.id,ts(e.manager,g,u))}).catch(()=>{});continue}u.item.windowId&&(l++,e.openNative(u.item.windowId),vc(e.manager,u.item.windowId).then(f=>{f&&(a[d]=f.id,ts(e.manager,f,u))}))}Jp(()=>{Zp(e.manager,o.layout,a),L(y.WORKSPACE_PROVISIONED,{desktopId:t,opened:l,layout:o.layout})})}function Zp(e,t,n){const o=n.find(Boolean);t==="focus"&&o&&e.focus(o),Kp(e,t)}function Jp(e){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>requestAnimationFrame(e)):e()}function AA(e,t){const n=sn(e.manager,t);if(!n||!n.provisioned||n.windows.length===0)return;const o=Bp(e.getNavItems(),n.windows),s=new Set,i=Yp(e,o,t,s),r=[],a=[];for(const[l,c]of o.entries()){if(c.url){const d=Mi(c.url,e.adminUrl),u=i.get(c);if(u){r[l]=u.id;continue}a.push(Xp(e,d,c,t,s).then(f=>{f&&(s.add(f.id),r[l]=f.id,ts(e.manager,f,c))}).catch(()=>{}));continue}if(c.item.windowId){if(e.manager.getById(c.item.windowId)){r[l]=c.item.windowId;continue}e.openNative(c.item.windowId),a.push(vc(e.manager,c.item.windowId).then(d=>{d&&(r[l]=d.id,ts(e.manager,d,c))}))}}a.length>0&&Promise.all(a).then(()=>Jp(()=>{e.manager.getActiveDesktopId()===t&&Zp(e.manager,n.layout,r)}))}function bc(e,t){const n=[],o=new Set,s=he(e._desktop);for(const i of e.getAll()){if((i.config.desktopId||e.getActiveDesktopId())!==t)continue;const r=i.config.baseId||i.id;if(o.has(r))continue;o.add(r);const a={match:r,title:i.config.title||r};if(i.config.native!==!0&&i.config.url&&(a.url=i.config.url),i._gridSpan)a.gridSpan={...i._gridSpan};else if(i.state==="normal"&&s.width>0&&s.height>0){const l=i.element;a.place=CA({x:(l.offsetLeft-s.x)/s.width,y:(l.offsetTop-s.y)/s.height,width:l.offsetWidth/s.width,height:l.offsetHeight/s.height})}if(n.push(a),n.length>=yA)break}return n}function CA(e){const t=n=>Number.isFinite(n)?Math.min(1,Math.max(0,n)):0;return{x:t(e.x),y:t(e.y),width:Math.max(.05,t(e.width)),height:Math.max(.05,t(e.height))}}function ts(e,t,n){const o=he(e._desktop);if(n.gridSpan){t._gridSpan={anchor:{...n.gridSpan.anchor},cursor:{...n.gridSpan.cursor},cols:n.gridSpan.cols,rows:n.gridSpan.rows},$p(t,o),t._emitChange("moved");return}if(n.place){const s=n.place;t.element.style.left=`${Math.round(o.x+s.x*o.width)}px`,t.element.style.top=`${Math.round(o.y+s.y*o.height)}px`,t.element.style.width=`${Math.round(s.width*o.width)}px`,t.element.style.height=`${Math.round(s.height*o.height)}px`,t._emitChange("moved")}}function vc(e,t,n,o=8e3){const s=()=>n?e.getAllByBaseId(t).find(n)??null:e.getById(t)??null,i=s();return i?Promise.resolve(i):new Promise(r=>{const a=d=>{document.removeEventListener("os-window-opened",l),window.clearTimeout(c),r(d)},l=d=>{const u=d.detail;if(n||u?.windowId===t){const f=s();f&&a(f)}},c=window.setTimeout(()=>a(null),o);document.addEventListener("os-window-opened",l)})}function LA(e,t,n={}){const o=e.manager._desktops.find(r=>r.id===t);if(!o)return null;const i={...o.profile??zp(),windows:bc(e.manager,t),layout:"free",provisioned:!0};if(n.visibleAppIds){const r=new Set(e.getNavItems().filter(a=>a.kind==="control"||a.locked).map(a=>a.id));i.apps={mode:"only",ids:n.visibleAppIds.filter(a=>!r.has(a))}}return n.mountedWidgetIds&&(i.widgets={mode:"only",ids:[...n.mountedWidgetIds]}),Xn(e,t,i),i}function Mi(e,t){if(/^https?:\/\//i.test(e))return e;try{return new URL(e,t).href}catch{return t}}let Pt=null;function TA(e){return Pt=e,()=>{Pt=null}}function NA(){return Pt!==null}function OA(e){return Pt?(Pt.openCreator(e),!0):!1}function DA(e){return Pt?(Pt.openEditor(e),!0):!1}function Qp(e){const t=e.profile;return t?t.windows.length>0||t.layout!=="free"||t.widgets?.mode==="only"||Object.keys(t.appearance??{}).length>0:!1}function xA(e){const t=Pt;return t?(t.manager.switchDesktop(e),wc(t,e),yc(t,e,{force:!0}),!0):!1}const eh=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],Wi="osHadFullscreenBeforeOverview",RA=250;function th(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[Wi]="true",ac()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function nh(e){if(e.element.dataset[Wi]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[Wi],ac();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[Wi],ac()}}function _c(e,t=!0){t&&nh(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function oh(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function sh(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function MA(e){if(e._overviewActive)return;ih(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,L(y.OVERVIEW_ENTERING,{}),L(y.DOCK_REFRESH_ACTIVE,{});for(const c of eh){const d=document.getElementById(c);d&&(d.inert=!0)}oh(!0),sh(e,!0),e._overviewSnapshot.clear();for(const c of t)e._overviewSnapshot.set(c.id,{transform:c.element.style.transform||"",transition:c.element.style.transition||""});for(const c of t)th(c);const n=e._desktop.getBoundingClientRect(),o=Array.from(document.querySelectorAll(".os-dock"));let s=0;for(const c of o){const d=c.getBoundingClientRect(),u=d.bottom>n.top&&d.top<n.bottom,f=d.height>d.width;u&&f&&(s+=d.width)}const i=new DOMRect(0,0,n.width+s,n.height);e._desktop.classList.add("os-area--overview"),document.getElementById("os-shell")?.classList.add("os-shell--overview"),e._overviewTopBar=rh(e),e._desktop.appendChild(e._overviewTopBar);const a=La(t,i,Ku(e._overviewTopBar));e._overviewLabels.clear();for(const c of a){const d=c.win.element;d.classList.add("os-window--overview");const u=c.x-d.offsetLeft,f=c.y-d.offsetTop;d.style.transform=`translate(${u}px, ${f}px) scale(${c.scale})`;const p=kc(c);d.insertAdjacentElement("afterend",p),e._overviewLabels.set(c.win.id,p)}const l=c=>{const d=c.target,u=d?.closest(".os-window--overview");return u?{id:u.id.replace(/^wp-window-/,""),element:u}:d===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 d=e._overviewPressTarget;if(e._overviewPressTarget=null,!d)return;const u=d.element.getBoundingClientRect();if(!(c.clientX>=u.left&&c.clientX<=u.right&&c.clientY>=u.top&&c.clientY<=u.bottom))return;if(c.preventDefault(),c.stopPropagation(),d.id==="backdrop"){$t(e);return}const p=e.getById(d.id);L(y.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),$t(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){$t(e);return}if(c.key==="Enter"){const u=c.target?.ownerDocument||document;if(u.activeElement&&u.activeElement.tagName==="BUTTON")return;if(c.preventDefault(),e._overviewAddTileFocused){ah(e);return}$t(e)}},e._desktop.addEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._desktop.addEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewClickBlocker=c=>{c.target?.closest(".os-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 u=c.target?.closest(".os-window--overview"),f=u?u.id.replace(/^wp-window-/,""):null;f!==e._lastOverviewHoverId&&(e._lastOverviewHoverId&&L(y.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&L(y.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&L(y.OVERVIEW_ENTERED,{})},300)}function ih(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function WA(e){e._overviewEnterTimeoutId!==null&&(window.clearTimeout(e._overviewEnterTimeoutId),e._overviewEnterTimeoutId=null),e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null),e._overviewExitFinalizer=null}let Ec=null;function PA(e){return Ec=e,()=>{Ec=null}}function rh(e){const t=document.createElement("div");t.className="os-overview-top-bar";const n=Ec?.();if(n){const a=document.createElement("div");a.className="os-overview-top-bar__header",a.appendChild(n),t.appendChild(a)}const o=document.createElement("div");o.className="os-overview-top-bar__list",t.appendChild(o),e._desktops.some(Qp)&&o.classList.add("os-overview-top-bar__list--restorable");for(const a of e._desktops)o.appendChild($A(e,a));const s=document.createElement("button");s.type="button",s.className="os-overview-top-bar__tile os-overview-top-bar__tile--add",e._overviewAddTileFocused&&s.classList.add("os-overview-top-bar__tile--cursor"),s.setAttribute("aria-label",b("Add new workspace")),s.innerHTML='<span class="os-overview-top-bar__tile-preview"><span class="os-overview-top-bar__tile-plus" aria-hidden="true">+</span></span><span class="os-overview-top-bar__tile-label" aria-hidden="true">&nbsp;</span>',s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),ah(e)});const i=document.createElement("div");i.className="os-overview-top-bar__tile-wrapper os-overview-top-bar__tile-wrapper--add",i.appendChild(s);const r=document.createElement("div");return r.className="os-overview-top-bar__tile-actions",i.appendChild(r),o.appendChild(i),t}function ah(e){e._overviewAddTileFocused=!1;const t=dh(e);Pi(e,t.id),OA(t.id)}function $A(e,t){const n=document.createElement("div");n.className="os-overview-top-bar__tile-wrapper";const o=document.createElement("button");o.type="button",o.className="os-overview-top-bar__tile",o.dataset.desktopId=t.id,t.id===e._activeDesktopId&&!e._overviewAddTileFocused&&o.classList.add("os-overview-top-bar__tile--active"),o.setAttribute("aria-label",le(b("Switch to %s"),t.label));const s=t.profile;s?.color&&(n.style.setProperty("--os-workspace-accent",s.color),o.classList.add("os-overview-top-bar__tile--tinted"));const i=document.createElement("span");if(i.className="os-overview-top-bar__tile-preview",s?.icon){const p=document.createElement("span");p.className=`os-overview-top-bar__tile-glyph dashicons ${s.icon}`,p.setAttribute("aria-hidden","true"),i.appendChild(p)}const r=e._stack.filter(p=>p.config.desktopId===t.id).length;if(r>0){const p=document.createElement("span");p.className="os-overview-top-bar__tile-count",p.textContent=String(r),i.appendChild(p)}o.appendChild(i);const a=document.createElement("span");a.className="os-overview-top-bar__tile-label",a.textContent=t.label,a.title=le(b("%s — double-click to rename"),t.label),o.appendChild(a);let l;a.addEventListener("click",p=>{a.hasAttribute("contenteditable")||(p.preventDefault(),p.stopPropagation(),l===void 0&&(l=window.setTimeout(()=>{l=void 0,e._overviewActive&&Pi(e,t.id)},RA)))}),a.addEventListener("dblclick",p=>{a.hasAttribute("contenteditable")||(p.preventDefault(),p.stopPropagation(),window.clearTimeout(l),l=void 0,ch(e,a,t))}),o.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),!a.hasAttribute("contenteditable")&&Pi(e,t.id)});const c=NA(),d=document.createElement("button");d.type="button",d.className="os-overview-top-bar__tile-edit",c?d.setAttribute("aria-label",le(b("Edit %s — its apps, widgets, look and windows"),t.label)):d.setAttribute("aria-label",le(b("Rename %s"),t.label)),d.title=d.getAttribute("aria-label")??"",d.innerHTML=en("edit",{size:14}),d.addEventListener("click",p=>{if(p.preventDefault(),p.stopPropagation(),!c){ch(e,a,t);return}Pi(e,t.id),DA(t.id)});const u=document.createElement("button");u.type="button",u.className="os-overview-top-bar__tile-close",u.setAttribute("aria-label",le(b("Close %s"),t.label)),u.innerHTML=en("close",{size:16}),u.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),hh(e,t.id),ns(e)}),n.appendChild(o),n.appendChild(d),n.appendChild(u);const f=document.createElement("div");if(f.className="os-overview-top-bar__tile-actions",Qp(t)){const p=document.createElement("button");p.type="button",p.className="os-overview-top-bar__tile-action os-overview-top-bar__tile-restore",p.setAttribute("aria-label",le(b("Restore %s — reopen its windows, widgets and look"),t.label)),p.title=p.getAttribute("aria-label")??"",p.innerHTML=`${en("windows",{size:12})}<span>${b("Restore")}</span>`,p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),xA(t.id)&&$t(e)}),f.appendChild(p)}return f.childElementCount>0&&n.appendChild(f),n}function ch(e,t,n){if(t.hasAttribute("contenteditable"))return;t.setAttribute("contenteditable","true");try{t.contentEditable="plaintext-only"}catch{}t.spellcheck=!1,t.focus();const o=t.ownerDocument.defaultView,s=t.ownerDocument.createRange();s.selectNodeContents(t);const i=o?.getSelection();i?.removeAllRanges(),i?.addRange(s);let r=!1;const a=l=>{r||(r=!0,t.removeAttribute("contenteditable"),l&&fh(e,n.id,t.textContent??""),e._overviewActive&&ns(e))};t.addEventListener("keydown",l=>{l.stopPropagation(),(l.key==="Enter"||l.key==="Escape")&&(l.preventDefault(),a(l.key==="Enter"))}),t.addEventListener("blur",()=>a(!0)),t.addEventListener("click",l=>l.stopPropagation())}function ns(e){if(!e._overviewTopBar)return;const t=rh(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Pi(e,t){ph(e,t),$t(e)}function kc(e){const t=document.createElement("div");t.className="os-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=`os-overview-label__icon dashicons ${o}`,s.setAttribute("aria-hidden","true"),t.appendChild(s);const i=document.createElement("span");i.className="os-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="os-overview-label__meta",a.textContent=le(Qt("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function $t(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,L(y.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),L(y.DOCK_REFRESH_ACTIVE,{}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of eh){const r=document.getElementById(i);r&&(r.inert=!1)}oh(!1),sh(e,!1);for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform)}t&&(t.state==="minimized"&&(nh(t),t.restore()),e.focus(t),n&&t.maximize());for(const i of e._stack)i.state==="minimized"&&i.element.classList.remove("os-window--overview");for(const i of e._overviewLabels.values())i.classList.add("os-overview-label--out");e._overviewTopBar&&e._overviewTopBar.classList.add("os-overview-top-bar--out");const s=280;e._overviewExitFinalizer=()=>{for(const i of e._stack)i.element.classList.remove("os-window--overview"),_c(i,i.config.desktopId===e._activeDesktopId);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),L(y.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>ih(e),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&&(L(y.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function UA(e){return[...e._desktops]}function lh(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function BA(e){return lh(e).id}function $i(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&_c(t)}function Sc(e){for(const t of e._stack)$i(e,t)}function FA(e,t,n){const o=e._stack.find(i=>i.id===t);if(!o||!e._desktops.some(i=>i.id===n))return!1;const s=o.config.desktopId||e._activeDesktopId;return s===n||(o.config.desktopId=n,e._overviewActive?Ic(e):$i(e,o),L(y.WINDOW_DESKTOP_CHANGED,{windowId:t,from:s,to:n})),!0}function dh(e,t){e._desktopSeq++;const n={id:`desktop-${e._desktopSeq}`,label:t?.label?.trim().slice(0,uh)||le(b("Workspace %d"),e._desktopSeq)};return e._desktops.push(n),L(y.DESKTOP_CREATED,{desktopId:n.id}),n}const uh=64;function fh(e,t,n){const o=e._desktops.find(r=>r.id===t);if(!o)return!1;const s=n.trim().slice(0,uh);if(!s||s===o.label)return!1;const i=o.label;return o.label=s,L(y.DESKTOP_RENAMED,{desktopId:t,label:s,previousLabel:i}),!0}function ph(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)Ic(e),ns(e);else{if(Sc(e),n?.direction&&HA(e,n.direction),!n?.skipFocus){const i=[...e._stack].reverse().find(r=>r.config.desktopId===t&&r.state!=="minimized");i&&e.focus(i)}const s=e._desktops.find(i=>i.id===t);s&&FE(e._desktop,s.label)}L(y.DESKTOP_SWITCHED,{from:o,to:t})}function HA(e,t){const n=e._desktop,o=t==="next"?"os-area--sliding-from-right":"os-area--sliding-from-left";n.classList.remove("os-area--sliding-from-right","os-area--sliding-from-left"),n.offsetWidth,n.classList.add(o);const s=i=>{i.animationName.startsWith("os-area-slide-from-")&&(n.classList.remove(o),n.removeEventListener("animationend",s))};n.addEventListener("animationend",s)}function hh(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);const i=e._activeDesktopId===t;i&&(e._activeDesktopId=s.id),e._overviewActive?Ic(e):Sc(e),L(y.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id}),i&&L(y.DESKTOP_SWITCHED,{from:t,to:s.id})}function Ic(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("os-window--overview"),_c(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),Sc(e);const t=e._stack.filter(i=>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||""}),th(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=La(t,o,Ku(e._overviewTopBar));for(const i of s){const r=i.win.element;r.classList.add("os-window--overview");const a=i.x-r.offsetLeft,l=i.y-r.offsetTop;r.style.transform=`translate(${a}px, ${l}px) scale(${i.scale})`;const c=kc(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function GA(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 zA(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;L(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=he(e._desktop),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)),l=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(a,l);t.forEach((u,f)=>{const p=f%Math.max(1,c);u._gridSpan=null,u.element.style.left=`${n.x+o+p*s}px`,u.element.style.top=`${n.y+o+p*s}px`,u.element.style.width=`${i}px`,u.element.style.height=`${r}px`});const d=e.getFocused();d&&e.focus(d),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"cascade"}})),L(y.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function mh(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=he(e._desktop),o=jE(t.length,n.width,n.height),s=Q(y.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=GE(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;L(y.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,l=12,c=Math.floor((n.height-a*2-l*(r-1))/r);for(let u=0;u*i<t.length;u++){const f=t.slice(u*i,u*i+i),p=Array.from({length:i},(h,m)=>f[m]?.config.minWidth||0),g=Fu(n.width-a*2,l,p);f.forEach((h,m)=>{h._gridSpan=null,h.element.style.left=`${n.x+a+g[m].x}px`,h.element.style.top=`${n.y+a+u*(c+l)}px`,h.element.style.width=`${g[m].width}px`,h.element.style.height=`${c}px`})}const d=e.getFocused();d&&e.focus(d),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"tile"}})),L(y.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}function gh(e){const t=e._stack.filter(n=>n.config.desktopId===e._activeDesktopId);if(t.length===0)return[];for(const n of t)n.state==="minimized"&&n.restore(),n.state==="fullscreen"&&n.toggleFullscreen(),n.state==="maximized"&&n.toggleMaximize(),n._gridSpan=null;return t}function jA(e,t){const n=e.getFocused();n&&e.focus(n),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:t}}))}const VA=4;function KA(e){const t=gh(e);if(t.length===0)return;if(t.length>VA){mh(e);return}const n=t.length;L(y.ARRANGE_COLUMNS_STARTING,{windowCount:t.length,cols:n});const o=he(e._desktop),s=16,i=12,r=Math.floor(o.height-s*2),a=Fu(o.width-s*2,i,t.map(l=>l.config.minWidth||0));t.forEach((l,c)=>{l.element.style.left=`${o.x+s+a[c].x}px`,l.element.style.top=`${o.y+s}px`,l.element.style.width=`${a[c].width}px`,l.element.style.height=`${r}px`}),jA(e,"columns"),L(y.ARRANGE_COLUMNS_APPLIED,{windowCount:t.length,cols:n})}const wh=.64;function qA(e){const t=gh(e);if(t.length===0)return;const n=he(e._desktop),o=Q(y.ARRANGE_FOCUS_SPLIT,wh,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),s=Number.isFinite(o)&&o>=.3&&o<=.9?o:wh;L(y.ARRANGE_FOCUS_STARTING,{windowCount:t.length,split:s});const i=16,r=12,a=n.width-i*2,l=n.height-i*2,c=e.getFocused(),d=c&&t.includes(c)?t.indexOf(c):0,u=t[d],f=t.filter((h,m)=>m!==d),p=Aa(a,r,Math.floor(a*s),u.config.minWidth||0,f.reduce((h,m)=>Math.max(h,m.config.minWidth||0),0)),g=f.length===0?a:p.first.width;if(u.element.style.left=`${n.x+i}px`,u.element.style.top=`${n.y+i}px`,u.element.style.width=`${g}px`,u.element.style.height=`${l}px`,f.length>0){const h=n.x+i+p.second.x,m=p.second.width,E=Math.floor((l-r*(f.length-1))/f.length);f.forEach((k,N)=>{k.element.style.left=`${h}px`,k.element.style.top=`${n.y+i+N*(E+r)}px`,k.element.style.width=`${m}px`,k.element.style.height=`${E}px`})}e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"focus"}})),L(y.ARRANGE_FOCUS_APPLIED,{windowCount:t.length,split:s})}const yh="desktop-mode-snap-to-grid";function YA(){try{return window.localStorage.getItem(yh)==="1"}catch{return!1}}function XA(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(yh,t?"1":"0")}catch{}L(y.ARRANGE_SNAP_CHANGED,{enabled:t})}}function ZA(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=Q(y.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=zE(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}const bh="desktop-mode-native-window-geometry",vh=64,ut=8192;function Ui(){try{const e=window.localStorage.getItem(bh);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function _h(e){try{window.localStorage.setItem(bh,JSON.stringify(e))}catch{}}function Bi(e){if(!e)return null;const n=Ui()[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>ut||s>ut)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),a=Number(n.y),l=Number.isFinite(r)&&Number.isFinite(a)&&r>=0&&a>=0&&r<=ut&&a<=ut;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function Eh(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>ut||o>ut)return;const s=Ui(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,l=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===l||(os(s,e,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),ss(s))}function kh(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>ut||o>ut)return;const s=Ui(),i=s[e];i&&(i.x===n&&i.y===o||(os(s,e,{...i,x:n,y:o}),ss(s)))}function Sh(e,t,n){if(!e)return;const o=Ui(),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>ut||r>ut)return;os(o,e,{width:i,height:r,state:t}),ss(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;os(o,e,r),ss(o);return}s.state!==t&&(os(o,e,{...s,state:t}),ss(o))}function os(e,t,n){delete e[t],e[t]=n}function ss(e){const t=Object.keys(e);if(t.length>vh){const n={};for(const o of t.slice(-vh))n[o]=e[o];_h(n);return}_h(e)}function JA(e,t,n,o){const s=o.x+Qa-n,i=o.x+o.width-Qa,r=Math.max(s,Math.min(e,i)),a=o.y+YS,l=o.y+o.height-Qa,c=Math.max(a,Math.min(t,l));return{x:r,y:c}}function QA(){const e=globalThis.navigator?.userActivation;return e?e.isActive:!0}const Ac=100,Fi=30;class e0{constructor(t){this._stack=[],this._cascadeMinimized=new WeakSet,this._cascadeDepth=0,this.cascadeIndex=0,this._pendingRestoreState=new Map,this._reservedRestoreIds=new Set,this._openingWindowIds=new Set,this._openingBaseIds=new Set,this._prewarmed=null,this._prewarmInFlight=!1,this._desktops=[{id:"desktop-1",label:"Workspace 1"}],this._activeDesktopId="desktop-1",this._desktopSeq=1,this.onToggleStartupRequested=null,this.desktopResizeObserver=null,this._reflowRestoreTimer=null,this._snapEnabled=YA(),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._overviewExitFinalizer=null,this._snapPendingZone=null,this._snapPreviewEl=null,this._gridSnap=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.openWindowsAs=()=>"default",this._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this._unsubscribeWorkArea=Jo(()=>this.reflowStatefulWindows()),this._uninstallSnapPartnerReflow=KI(this),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(".os-window");if(!n)return;const o=n.id.replace(/^wp-window-/,""),s=this.getById(o);if(s){if(!QA()){this.getFocused()!==s&&t.blur();return}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)continue;const o=he(n);if(t.state==="maximized")t.element.classList.add("os-window--reflowing"),t.element.style.left=`${o.x}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${o.width}px`,t.element.style.height=`${o.height}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("os-window--reflowing");const s=t.state==="snapped-left"?"left":"right",i=Ca(o,s,t.config.minWidth||0,Di(this,t,s));t.element.style.left=`${i.x}px`,t.element.style.top=`${i.y}px`,t.element.style.width=`${i.width}px`,t.element.style.height=`${i.height}px`}else if(t.state==="normal"){const s=parseInt(t.element.style.left,10)||0,i=parseInt(t.element.style.top,10)||0,r=t.element.offsetWidth||0,a=JA(s,i,r,{x:0,y:0,width:n.clientWidth,height:n.clientHeight});(s!==a.x||i!==a.y)&&(t.element.classList.add("os-window--reflowing"),t.element.style.left=`${a.x}px`,t.element.style.top=`${a.y}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("os-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 r=o.state==="minimized";this.focus(o),r&&o.restore();let a=!1;if(!o.config.native){const c=On(t.url);c===On(o.getCurrentUrl())||c===On(o.config.url||"")||c===On(o.config.parentUrl??o.config.url??"")||(a=o.navigateTo(t.url))}t.params&&(o.config.params={...t.params});const l={windowId:o.id,baseId:n,wasMinimized:r,navigated:a,params:o.config.params??{}};return document.dispatchEvent(new CustomEvent("os-window-reopened",{detail:l})),L(y.WINDOW_REOPENED,l),o}const s=this.adoptPrewarmed(n,t);if(s)return s;const i=this.getByBaseId(n)?this.nextInstanceId(n):t.id;return this.createWindow({...t,id:i,baseId:n})}async prewarm(t){const n=t.baseId||t.id;if(t.native||this._prewarmInFlight||this._prewarmed?.baseId===n||this.getByBaseId(n))return!1;this._prewarmInFlight=!0;try{this.discardPrewarmed();const o=await this.createWindow({...t,id:t.id,baseId:n},{prewarm:!0});if(this.getByBaseId(n))return this.teardownSpeculativeWindow(o),!1;const s=window.setTimeout(()=>this.discardPrewarmed(),45e3);return this._prewarmed={baseId:n,win:o,timer:s},!0}finally{this._prewarmInFlight=!1}}adoptPrewarmed(t,n){const o=this._prewarmed;if(!o||o.baseId!==t)return null;const s=o.win;if(On(n.url)!==On(s.config.url||"")||this.getById(s.id))return this.discardPrewarmed(),null;window.clearTimeout(o.timer),this._prewarmed=null,s.config.desktopId=this._activeDesktopId,s.element.style.display="",s.element.removeAttribute("aria-hidden"),this._stack.push(s),$i(this,s),this.focus(s);const i={windowId:s.id,page:s.config.url??n.url,title:s.config.title,url:s.config.url??n.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:i})),L(y.WINDOW_OPENED,i),s}discardPrewarmed(){const t=this._prewarmed;t&&(this._prewarmed=null,window.clearTimeout(t.timer),this.teardownSpeculativeWindow(t.win))}teardownSpeculativeWindow(t){try{globalThis.__openStationConnectionBridge?.onWindowClosed?.(t.id)}catch{}t.onClose=null;try{t.destroy()}catch{}t.element.remove()}async openNew(t){const n=t.baseId||t.id,o=t.id!==n&&!this.getById(t.id)&&!this._openingWindowIds.has(t.id)?t.id:this.nextInstanceId(n),s=!!this.getByBaseIdOnActiveDesktop(n)||this._openingBaseIds.has(n);if(!s){const a=this.adoptPrewarmed(n,t);if(a)return a}const i=40+this.cascadeIndex%8*Fi,r=40+this.cascadeIndex%8*Fi;return this.createWindow({...s&&(t.openAs??this.openWindowsAs())==="default"?{initialState:"normal",x:i,y:r}:{},...t,id:o,baseId:n})}async createWindow(t,n={}){const o=this._pendingRestoreState.get(t.id);o&&(this._pendingRestoreState.delete(t.id),this._reservedRestoreIds.delete(t.id),t={...t,...o});const s=this._desktop.getBoundingClientRect(),i=he(this._desktop),r=12,a=Math.min(Math.round(i.width*.8),1200),l=Math.min(Math.round(i.height*.8),800),c=i.x+40+this.cascadeIndex%8*Fi,d=i.y+40+this.cascadeIndex%8*Fi,u=t.baseId||t.id,f=t.minWidth??320,p=t.minHeight??200,g=typeof t.width=="number",h=typeof t.height=="number",m=typeof t.x=="number",E=typeof t.y=="number",k=typeof t.initialState=="string",N=!g||!h||!k||!m||!E?Bi(u):null;let M=t.width??(N?Math.max(N.width,f):a),S=t.height??(N?Math.max(N.height,p):l);!m&&!E&&!N&&(M=Math.max(f,Math.min(M,i.width-r*2)),S=Math.max(p,Math.min(S,i.height-r*2)));const W=Math.max(i.x+r,Math.min(c,i.x+i.width-M-r)),F=Math.max(i.y+r,Math.min(d,i.y+i.height-S-r)),x=!k&&!o&&!n.prewarm?t.openAs??this.openWindowsAs():"default",q=t.initialState??(x!=="default"?"maximized":void 0)??(N?.state==="maximized"?"maximized":void 0);let J,X;if(N&&typeof N.x=="number"&&typeof N.y=="number"){const Y=Math.max(i.x,i.x+i.width-M-r),ae=Math.max(i.y,i.y+i.height-S-r);J=Math.max(i.x+r,Math.min(N.x,Y)),X=Math.max(i.y+r,Math.min(N.y,ae))}const T=t.x??J??W,D=t.y??X??F,K=g||h||m||E||k,G=!!N,ne={x:T,y:D,width:M,height:S,state:q};let ce;try{ce=Q(y.WINDOW_GEOMETRY,ne,{windowId:t.id,baseId:u,hasSavedGeometry:G,callerPinned:K,desktopRect:{width:s.width,height:s.height},workArea:{...i}})}catch(Y){L(y.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:Y}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,Y),ce=ne}const R=(Y,ae)=>typeof Y=="number"&&Number.isFinite(Y)?Y:ae,C=ce&&typeof ce=="object"?ce:ne,U=Math.max(R(C.width,M),f),B=Math.max(R(C.height,S),p),z=R(C.x,T),_=R(C.y,D),v=C.state??q,A={icon:t.icon||"dashicons-admin-generic",...t,x:z,y:_,width:U,height:B,minWidth:f,minHeight:p,...v?{initialState:v}:{},baseId:u,desktopId:t.desktopId||this._activeDesktopId};if(t.gridSpan){const Y=Pp(t.gridSpan,he(this._desktop));A.x=Y.x,A.y=Y.y,A.width=Y.width,A.height=Y.height}this.cascadeIndex++,this._openingWindowIds.add(t.id),this._openingBaseIds.add(u);const O=Promise.all([PE(ME()),Ea(ka())]);let P;try{P=await O}catch(Y){throw this._openingWindowIds.delete(t.id),this._openingBaseIds.delete(u),Y}this._openingWindowIds.delete(t.id),this._openingBaseIds.delete(u);const[Z]=P,V=Z.createWindow(A);if(t.gridSpan&&(V._gridSpan={anchor:{...t.gridSpan.anchor},cursor:{...t.gridSpan.cursor},cols:t.gridSpan.cols,rows:t.gridSpan.rows}),V.onFocusRequest=Y=>{this._cascadeDepth>0||this.focus(Y)},V.onClose=Y=>this.remove(Y),V.onMinimize=Y=>{this._cascadeDepth++;try{this.cascadeMinimize(Y)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const ae=this.getActiveDesktopId(),be=this._stack.filter(wt=>(wt.config.desktopId||ae)===ae&&wt.state!=="minimized");be.length>0&&this.focus(be[be.length-1])},V.onRestore=Y=>{this._cascadeDepth++;try{this.cascadeRestore(Y)}finally{this._cascadeDepth--}},V.onOpenAnother=Y=>{const ae=Y.config.baseId||Y.id;Y.config.native&&window.wp?.os?.openNewWindow?.(ae,{source:"open-another"})||this.openNew({id:ae,baseId:ae,url:Y.config.url||"",title:Y.config.title,icon:Y.config.icon,submenu:Y.config.submenu,multi:!0})},V.onOpenInNewWindow=Y=>{const ae=Y.config.baseId||Y.id;if(Y.config.native&&window.wp?.os?.openNewWindow?.(ae,{source:"open-in-new-window"}))return;const be=Y.getCurrentUrl();this.openNew({id:ae,baseId:ae,url:be||Y.config.url||"",title:Y.config.title,icon:Y.config.icon,submenu:Y.config.submenu,multi:!0})},V.onToggleStartup=Y=>{this.onToggleStartupRequested?.(Y)},V.snapConfigProvider=()=>this.getSnapConfig(),V.snapPartnerMinWidthProvider=Y=>Di(this,V,Y),V.onDragMove=(Y,ae,be)=>{if(this._gridSnap){rA(this,ae,be);return}XI(this,Y,ae)},V.onDragGesture=(Y,ae)=>{switch(ae.type){case"modifier":ae.active?iA(this,Y,ae.clientX,ae.clientY):lA(this);break;case"shake":aA(this,ae.clientX,ae.clientY,tA.Shake);break}},V.onDragEnd=Y=>this._gridSnap?dA(this,Y):this._snapPendingZone?ZI(this,Y):(Dp(this),!1),n.prewarm)return V.element.style.display="none",V.element.setAttribute("aria-hidden","true"),this._desktop.appendChild(V.element),V;this._stack.push(V),this._desktop.appendChild(V.element),$i(this,V),V.hydrateNative();const ge=Y=>(Y.config.desktopId||this._activeDesktopId)!==this._activeDesktopId;if(ge(V)){this._stack.splice(this._stack.indexOf(V),1);let Y=this._stack.length;for(;Y>0&&!ge(this._stack[Y-1]);)Y--;this._stack.splice(Y,0,V),this._stack.forEach((ae,be)=>ae.setZIndex(Ac+be))}else this.focus(V);if(x==="focused")for(const Y of this._stack)Y!==V&&Y.state!=="minimized"&&(Y.config.desktopId||this._activeDesktopId)===V.config.desktopId&&Y.minimize();const Te={windowId:V.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:Te})),L(y.WINDOW_OPENED,Te),V}nextInstanceId(t){const n=new Set([...this._stack.map(s=>s.id),...this._openingWindowIds,...this._reservedRestoreIds]);if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=typeof t=="string"?this.getById(t):t;if(!n||typeof n.setZIndex!="function"){t&&typeof t!="string"&&console.warn("[openstation] windowManager.focus() expects a Window or a window id; received",t);return}const o=this.blockingChildOf(n)??n;o!==n&&(o.shake?.(),L(y.WINDOW_CHILD_BLOCKED,{windowId:n.id,childWindowId:o.id}),document.dispatchEvent(new CustomEvent("os-window-child-blocked",{detail:{windowId:n.id,childWindowId:o.id}})));const s=o.config.desktopId||this._activeDesktopId;s!==this._activeDesktopId&&this._desktops.some(c=>c.id===s)&&this.switchDesktop(s,{skipFocus:!0});const i=this._stack.length>0?this._stack[this._stack.length-1]:null,r=this._stack.find(c=>c!==o&&c.isFocused()&&c.isFullscreen());r&&Q(y.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:r.id,focusedTo:o.id})&&r.toggleFullscreen();const a=this._stack.indexOf(o);if(a>-1&&this._stack.splice(a,1),this._stack.push(o),this.enforceOwnershipOrder(),this._stack.forEach((c,d)=>{c.setZIndex(Ac+d),c.setFocused(d===this._stack.length-1)}),i&&i!==o&&i.id!==o.id){const c={windowId:i.id,focusedTo:o.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:c})),L(y.WINDOW_BLURRED,c)}const l={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:l})),L(y.WINDOW_FOCUSED,l)}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.enforceOwnershipOrder(),this._stack.forEach((s,i)=>{s.setZIndex(Ac+i)}))}async openChild(t,n){const o=this.getById(t);if(!o)throw new Error(`windowManager.openChild(): no open window with id "${t}". Open the owner first, or use open() for a standalone window.`);const s=Bi(n.baseId||n.id),i=!!s&&typeof s.x=="number"&&typeof s.y=="number";let r={};if(n.x===void 0&&n.y===void 0&&!i){const a=o.getSnapshot(),l=n.width??Math.round(a.width*.8),c=n.height??Math.round(a.height*.8),d=he(this._desktop),u=Math.max(d.x,d.x+d.width-l),f=Math.max(d.y,d.y+d.height-c);r={width:l,height:c,x:Math.min(u,Math.max(d.x,Math.round(a.x+(a.width-l)/2))),y:Math.min(f,Math.max(d.y,Math.round(a.y+(a.height-c)/2)))}}return this.open({...n,...r,desktopId:o.config.desktopId,parentWindowId:t})}ownerOf(t){const n=t.config.parentWindowId;return n?this.getById(n):void 0}childrenOf(t){const n=typeof t=="string"?t:t.id;return this._stack.filter(o=>o.config.parentWindowId===n)}blockingChildOf(t){let n=t,o;const s=new Set([t]);for(;;){const i=this.childrenOf(n).filter(r=>r.state!=="minimized"&&!s.has(r));if(i.length===0)return o;n=i[i.length-1],s.add(n),o=n}}enforceOwnershipOrder(){if(!this._stack.some(s=>s.config.parentWindowId))return;const t=[],n=new Set,o=(s,i)=>{if(!(n.has(s)||i.has(s))){if(i.add(s),s.state!=="minimized"){const r=this.ownerOf(s);r&&r!==s&&o(r,i)}n.has(s)||(n.add(s),t.push(s))}};for(const s of this._stack)o(s,new Set);this._stack.length=0,this._stack.push(...t)}cascadeMinimize(t){for(const n of this.childrenOf(t))n.state!=="minimized"&&(this._cascadeMinimized.add(n),n.minimize())}cascadeRestore(t){for(const n of this.childrenOf(t))this._cascadeMinimized.has(n)&&(this._cascadeMinimized.delete(n),n.restore())}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);const o=this.childrenOf(t).slice();if(o.length>0){this._cascadeDepth++;try{for(const r of o)this._cascadeMinimized.delete(r),r.close()}finally{this._cascadeDepth--}}for(let r=this._stack.length-1;this._cascadeDepth===0&&r>=0;r--){const a=this._stack[r];if(!(a.state==="minimized"||(a.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(a);break}}const s={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("os-window-closing",{detail:s})),L(y.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),L(y.WINDOW_CLOSED,i)}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 UA(this)}getActiveDesktop(){return lh(this)}getActiveDesktopId(){return BA(this)}createDesktop(t){return dh(this,t)}switchDesktop(t,n){ph(this,t,n)}closeDesktop(t){hh(this,t)}renameDesktop(t,n){return fh(this,t,n)}moveWindowToDesktop(t,n){return FA(this,t,n)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=Q(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(c=>!n.has(c.id));L(y.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=Q(y.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(c=>!i.includes(c));let a=0;const l=[];for(const c of i.slice())try{c.close(),c._isDestroyed||c._closePending?a++:l.push(c)}catch(d){l.push(c),typeof console<"u"&&console.error("[openstation] closeAll: window.close() threw for",c.id,d)}return L(y.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r,refused:l}),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("[openstation] 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("[openstation] 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(){zA(this)}tile(){mh(this)}columns(){KA(this)}focusLayout(){qA(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){XA(this,t)}getSnapConfig(){return ZA(this)}enterOverview(){if(Jt()){document.dispatchEvent(new CustomEvent("os-mobile-open-switcher"));return}MA(this)}exitOverview(t,n=!1){$t(this,t,n)}destroy(){this._unsubscribeWorkArea(),this._uninstallSnapPartnerReflow(),this.desktopResizeObserver?.disconnect(),this._reflowRestoreTimer!==null&&(window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=null),this._overviewActive&&$t(this),this.discardPrewarmed(),WA(this),HE()}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}})}sanitizeParams(t){const n={};for(const[o,s]of Object.entries(t))(typeof s=="string"||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s))&&(n[o]=s);return Object.keys(n).length>0?n:void 0}snapshot(){const t=this.getFocused(),o=this._stack.filter(a=>!a.config.ephemeral&&!a.config.parentWindowId).map(a=>{const l=a.getSnapshot(),c=a.getExternalTabsSnapshot(),d=!!a.config.native,u=a.config.params,f=d&&u?this.sanitizeParams(u):null;return{id:a.id,baseId:a.config.baseId||a.id,desktopId:a.config.desktopId||this._activeDesktopId,...d?{native:!0}:{},...f?{params:f}:{},url:d?a.config.url||`#${a.id}`:a.getCurrentUrl(),title:a.config.title,icon:a.config.icon,state:l.state,x:l.x,y:l.y,width:l.width,height:l.height,...c.length>0?{externalTabs:c}:{},...a._gridSpan?{gridSpan:{...a._gridSpan}}:{}}}),s=t&&!t.config.ephemeral&&!t.config.parentWindowId?t.id:"",i={windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Date.now()},r=Q(y.SESSION_SNAPSHOT,i);return r&&Array.isArray(r.windows)?r:i}seedWindowRestoreState(t,n={}){this._pendingRestoreState=new Map(Object.entries(t)),this._reservedRestoreIds=n.reserveIds?new Set(Object.keys(t)):new Set}discardWindowRestoreState(t){if(t){this._pendingRestoreState.delete(t),this._reservedRestoreIds.delete(t);return}this._pendingRestoreState.clear(),this._reservedRestoreIds.clear()}seedDesktops(t,n){GA(this,t,n)}}function t0(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 Ih(e,t){if(e._overviewActive)return;const n=t0(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 Ah=!1;function Cc(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;return Ch(t)}function Ch(e){if(!e)return!1;if(e instanceof HTMLIFrameElement||e instanceof HTMLTextAreaElement)return!0;if(e instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(e.type);if(e instanceof HTMLElement&&e.isContentEditable===!0)return!0;const t=e.getAttribute("contenteditable");return t!==null&&t!=="false"}function n0(e){if(Ah)return;Ah=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(Cc(document)||(n.preventDefault(),Ih(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!=="os-window-switch"||Ih(e,o.direction==="prev"?"prev":"next")})}let is=null;function o0(e){if(e.ctrlKey||e.metaKey||e.altKey||e.key.length!==1)return!1;const t=e.composedPath(),n=t.length>0?t[0]:null;return!(n instanceof Element)||!(n.getRootNode()instanceof ShadowRoot)?!1:Ch(n)}function s0(e=window){if(is)return is;const t=o=>{o0(o)&&o.stopPropagation()};e.addEventListener("keydown",t,!0);const n=()=>{e.removeEventListener("keydown",t,!0),is===n&&(is=null)};return is=n,n}function Lh(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 Th(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(l=>l.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,ns(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function i0(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function r0(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Nh(e){return e._overviewActive?(e.exitOverview(),!0):!1}function a0(){return document.querySelector("os-modal[open], os-confirm-dialog[open]")!==null}function c0(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function l0(e){return c0(e)?(e.toggleShowDesktop(),!0):!1}let Oh=!1;function d0(e){Oh||(Oh=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||Jt()||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||Cc(document)||a0())return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Th(e,"prev"):Lh(e,"prev");break;case"ArrowRight":n=e._overviewActive?Th(e,"next"):Lh(e,"next");break;case"ArrowUp":n=Nh(e)||l0(e)||i0(e);break;case"ArrowDown":n=Nh(e)||r0(e);break}n&&t.preventDefault()},!0))}async function rn(e){return await Ea(ka()),new Promise(t=>{const n=document.createElement("os-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",""),e.rememberLabel&&n.setAttribute("remember-label",e.rememberLabel);const o=s=>{n.remove(),t(s)};n.addEventListener("os-confirm",s=>{e.onRemember?.(s.detail?.remember===!0),o(!0)}),n.addEventListener("os-cancel",()=>o(!1)),document.body.appendChild(n)})}const u0="os-window-close-all";function f0(e){return e.code!=="KeyW"||e.getModifierState?.("AltGraph")||!(e.ctrlKey||e.metaKey)?!1:e.altKey&&!e.shiftKey}let Lc=!1;function Dh(e){const t=e.getActiveDesktopId();return e.getAll().filter(n=>(n.config.desktopId||t)===t)}async function xh(e,t){if(Lc)return 0;const n=Dh(e);if(n.length===0)return 0;if(t&&!t.shouldAsk())return Rh(e);const o=t?{rememberLabel:b("Don't ask again"),onRemember:i=>{i&&t.setAsk(!1)}}:{};Lc=!0;let s=!1;try{s=await rn({title:b("Close all windows?"),message:le(Qt("%d open window on this desktop will be closed.","%d open windows on this desktop will be closed.",n.length),n.length),confirmLabel:b("Close all"),danger:!0,...o})}finally{Lc=!1}return s?Rh(e):0}const p0=700,h0=50;function m0(e,t){const n=()=>t.filter(o=>!e.getById(o)).length;return new Promise(o=>{const s=Date.now()+p0,i=()=>{const r=n();if(r===t.length||Date.now()>=s){o(r);return}setTimeout(i,h0)};i()})}async function Rh(e){e._overviewActive&&e.exitOverview();const t=Dh(e).map(s=>s.id),n=e.getAll().map(s=>s.id).filter(s=>!t.includes(s));e.closeAll({exceptIds:n});const o=await m0(e,t);return o>0&&ue({message:le(Qt("Closed %d window.","Closed %d windows.",o),o)}),o}let Mh=!1;function g0(e,t){if(Mh)return;Mh=!0,document.addEventListener("keydown",o=>{f0(o)&&(o.preventDefault(),o.stopImmediatePropagation(),xh(e,t))},!0);const n=window.location.origin;window.addEventListener("message",o=>{if(o.origin!==n)return;const s=o.data;!s||s.type!==u0||xh(e,t)})}const Wh=ep;let Ph=!1;function $h(e){return e?document.getElementById(`wp-window-${e}`):null}function w0(){Ph||(Ph=!0,y0())}function y0(){ee(y.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=$h(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove(sc),n.classList.add(Zo),wI(n),kp(t),uI(t))}),ee(y.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=$h(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");if(!n)return;t.removeAttribute("aria-busy");const o=!!n.querySelector(`:scope .${Yo}`)?.classList.contains(Ci);if(n.classList.remove(Zo),n.removeAttribute(ic),!o){Ep(t),pp(t);return}n.classList.add(sc);const s=Ti(n);pp(t),window.setTimeout(()=>{Ti(n)===s&&(n.classList.contains(Zo)||Ep(t))},Wh),window.setTimeout(()=>{Ti(n)===s&&(n.classList.contains(Zo)||n.classList.remove(sc))},Wh+ZS)}),ee(y.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Uh())})}function Uh(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),kp(n))})}const b0="desktop_mode_classic";function v0(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has("page")&&!e.searchParams.has(b0)}function _0(e,t){let n;try{n=new URL(t,window.location.origin)}catch{return null}const o=Wu(t);let s=null,i=-1;for(const r of e){const a=r.dataset.url;if(!a||Wu(a)!==o)continue;let l;try{l=new URL(a,window.location.origin)}catch{continue}let c=0,d=!1;for(const[u,f]of l.searchParams){if(u==="openstation_chromeless"||u==="desktop_mode_portal"||xu.includes(u))continue;if(n.searchParams.get(u)!==f){d=!0;break}c++}!d&&c>i&&(s=r,i=c)}return s}function E0(e,t){const n=e.element.querySelectorAll('.os-window__tab[data-kind="submenu"]');if(!n.length)return;if(e._activeTabId!=="primary"){for(const i of n)i.classList.remove("os-window__tab--active"),i.setAttribute("aria-selected","false");return}const o=Lt(t);let s=null;for(const i of n){const r=i.dataset.url;if(r&&Lt(r)===o){s=i;break}}if(s||(s=_0(n,t)),!s){if(Array.from(n).some(a=>a.classList.contains("os-window__tab--active")))return;let r=!1;try{const a=new URL(t,window.location.origin);r=a.pathname.endsWith("/admin.php")&&a.searchParams.has("page")}catch{return}if(!r||!n[0])return;s=n[0]}for(const i of n){const r=i===s;i.classList.toggle("os-window__tab--active",r),i.setAttribute("aria-selected",r?"true":"false")}}function k0(e){const t=e.getCurrentUrl();return t&&t!=="about:blank"?t:e.config.url}function S0(e,t){const n=e.element.querySelector(".os-window__tabs");if(!n||e.config.native)return!1;const o={...e.config,submenu:t.submenu??[],selfLabel:t.selfLabel,parentUrl:t.url||e.config.parentUrl,url:k0(e)};if(!o.url)return!1;const s=o.url;e.config.submenu=o.submenu,e.config.selfLabel=o.selfLabel,e.config.parentUrl=o.parentUrl;const i=SI(o),r=Array.from(n.querySelectorAll(':scope > [data-kind="submenu"]')),a=f=>f.map(p=>`${p.dataset.url??""}
3 ${p.textContent??""}`).join(`
4
5 `);if(a(i)===a(r))return!1;const l=r.find(f=>f.classList.contains("os-window__tab--active"))?.dataset.url;if(l&&!i.some(f=>f.classList.contains("os-window__tab--active"))){const f=i.find(p=>p.dataset.url===l);f?.classList.add("os-window__tab--active"),f?.setAttribute("aria-selected","true")}const c=r.some(f=>f===n.ownerDocument.activeElement),d=r[0]??n.querySelector(':scope > [data-kind="main"]')?.nextSibling??n.querySelector(".os-window__tab-plate")?.nextSibling??null;for(const f of i)n.insertBefore(f,d);for(const f of r)f.remove();const u=n.querySelector(':scope > [data-kind="main"]');return i.length>0?u?.remove():A0(e)>0&&I0(e,n),oc(n),E0(e,s),c&&(n.querySelector(".os-window__tab--active")??n.querySelector(":scope > .os-window__tab"))?.focus(),!0}function I0(e,t){if(t.querySelector('[data-kind="main"]')||t.querySelector('[data-kind="submenu"]'))return;const n=document.createElement("button");n.className="os-window__tab os-window__tab--main os-window__tab--active",n.dataset.kind="main",n.setAttribute("type","button"),n.setAttribute("role","tab"),n.setAttribute("aria-selected","true"),n.textContent=e.config.title||"Main",t.prepend(n),oc(t)}function A0(e){return e._externalTabs.size}const Tc=se("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function C0(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=Tc.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Bh(e.id)}function Bh(e){const t=Tc.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function L0(){return Tc.state.entries.slice()}const T0=32,N0=64,O0=/^[a-z0-9_/-]+$/,ve=se("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function an(e){return`${e.type}:${e.id}`}function Fh(e){return e.root?an(e.root):an(e)}function Hh(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&O0.test(o.trim().toLowerCase());return tn(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"},{field:"revisionCount",valid:o=>o.revisionCount===void 0||typeof o.revisionCount=="number"&&Number.isFinite(o.revisionCount),message:"when present, must be a finite number"}])}function Gh(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function D0(e,t){const n={type:e.type.trim().toLowerCase(),id:e.id,source:t};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,T0).map(i=>{const r={type:i.type.trim().toLowerCase(),id:i.id};return i.rel==="child"&&(r.rel="child"),r})),typeof e.label=="string"&&e.label!==""&&(n.label=e.label);const o=Gh(e.previewUrl);o&&(n.previewUrl=o);const s=Gh(e.revisionsUrl);return s&&(n.revisionsUrl=s,typeof e.revisionCount=="number"&&Number.isFinite(e.revisionCount)&&(n.revisionCount=Math.max(0,Math.trunc(e.revisionCount)))),Array.isArray(e.related)&&e.related.length>0&&(n.related=e.related.slice(0,N0).map(i=>{const r={id:i.id,group:i.group,label:i.label,url:i.url};return typeof i.groupLabel=="string"&&i.groupLabel!==""&&(r.groupLabel=i.groupLabel),typeof i.icon=="string"&&i.icon!==""&&(r.icon=i.icon),typeof i.count=="number"&&(r.count=i.count),r})),n}function zh(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 Nc(e){return e?[an(e),Fh(e),...(e.links??[]).map(t=>an(t)+(t.rel==="child"?"!child":""))].join("|"):""}function Zn(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Me("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=Hh(t);if(a.length>0){o==="api"&&Me("WindowContentRef",a,t),of("WindowContentRef",a,t);return}s=D0(t,o)}if(s=Q(y.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||Hh(s).length>0)){of("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=ve.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&Nc(s)===Nc(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&s.revisionsUrl===i.revisionsUrl&&s.revisionCount===i.revisionCount&&zh(s)===zh(i))return;s===null?ve.state.contentByWindow.delete(e):ve.state.contentByWindow.set(e,s);const r={windowId:e,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("os-window-content-changed",{detail:r})),L(y.WINDOW_CONTENT_CHANGED,r),P0(),M0()}function We(e){return ve.state.contentByWindow.get(e)}function Oc(){const e=new Map;for(const[s,i]of ve.state.contentByWindow){const r=Fh(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=ve.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=Q(y.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[openstation] `os.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function jh(e){return Oc().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function x0(e){const t=new Set,n=jh(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of Vh())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function Vh(){const e=ve.state.focusSeq,t=new Map;for(const[a,l]of ve.state.contentByWindow){const c=an(l),d=t.get(c);(!d||(e.get(a)??0)>(e.get(d)??0))&&t.set(c,a)}const n=new Map,o=(a,l)=>`${a}→${l}`;for(const[a,l]of ve.state.contentByWindow){if(l.root){const c=t.get(an(l.root));c&&c!==a&&n.set(o(a,c),{fromWindowId:a,toWindowId:c,kind:"child-root",bidirectional:!1})}for(const c of l.links??[]){const d=t.get(an(c));if(!d||d===a)continue;if(c.rel==="child"){const f=o(d,a),p=n.get(f);(!p||p.kind!=="child-root")&&n.set(f,{fromWindowId:d,toWindowId:a,kind:"child-root",bidirectional:!1});continue}const u=o(a,d);n.has(u)||n.set(u,{fromWindowId:a,toWindowId:d,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[a,l]of n){if(i.has(a))continue;const c=o(l.toWindowId,l.fromWindowId),d=n.get(c);if(d&&l.kind==="reference"){if(d.kind==="reference"){i.add(c),s.push({...l,bidirectional:!0});continue}continue}s.push(l)}const r=Q(y.WINDOW_LINK_EDGES,s);return Array.isArray(r)?r:(typeof console<"u"&&console.warn("[openstation] `os.window-links.edges` filter returned a non-array; falling back to derived edges."),s)}function R0(e){return ve.state.listeners.add(e),()=>{ve.state.listeners.delete(e)}}function M0(){for(const e of Array.from(ve.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function W0(){return Array.from(ve.state.contentByWindow).map(([e,t])=>`${e}=${Nc(t)}`).sort().join(";")}function P0(){const e=W0();if(e===ve.state.lastGroupsSignature)return;ve.state.lastGroupsSignature=e;const n={groups:Oc()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),L(y.WINDOW_LINK_GROUPS_CHANGED,n)}const $0={get:We,set:(e,t)=>Zn(e,t,{source:"api"}),groups:Oc,edges:Vh,groupOf:jh,related:x0,subscribe:R0};function U0({manager:e}){ve.state.manager=e,!ve.state.started&&(ve.state.started=!0,ee(y.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=ve.state.manager?.getById(t.windowId)?.config?.content;o&&Zn(t.windowId,o,{source:"config"})}),ee(y.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(ve.state.focusSeq.delete(t.windowId),Zn(t.windowId,null,{source:"config"}))}),ee(y.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(ve.state.seq+=1,ve.state.focusSeq.set(t.windowId,ve.state.seq))}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t.data;if(!n||n.type!=="os-content-identity")return;const o=ve.state.manager?.findByIframeSource?.(t.source);o&&Zn(o.id,n.identity??null,{source:"bridge"})}))}const B0=se("desktop-mode/admin-link-deps",()=>({deps:null}));function F0(e){B0.state.deps=e}const Jn=12;function Dc(e,t){return xc(fe(e,t.adminUrl),t)}function xc(e,t){if(e)return(t.dockItems||[]).find(n=>fe(n.url,t.adminUrl)===e||(n.submenu||[]).some(o=>fe(o.url,t.adminUrl)===e))}function Kh(e,t){const n=fe(e,t.adminUrl);if(!n)return;const o=t.dockItems||[],s=o.find(i=>fe(i.url,t.adminUrl)===n);if(s?.title)return s.title;for(const i of o){const r=(i.submenu||[]).find(a=>fe(a.url,t.adminUrl)===n);if(r?.title)return r.title}}function qh(e,t){const n=t.x??0,o=t.y??0,s=Math.max(200,t.width-Jn*2),i=Math.max(200,t.height-Jn*2),r=Math.min(e.width,s),a=Math.min(e.height,i),l=n+Math.max(0,t.width-r-Jn),c=o+Math.max(0,t.height-a-Jn),d=Math.max(n+Jn,Math.min(e.x,l)),u=Math.max(o+Jn,Math.min(e.y,c));return{x:d,y:u,width:r,height:a}}function H0(e,t){for(const n of e){if(n.config.native)continue;const o=xc(n.config.baseId||n.id,t);o&&S0(n,o)}}const Yh=se("desktop-mode/wallpaper-settings",()=>({values:{}}));function G0(e){return{...Yh.state.values[e]??{}}}function z0(e){const t=Yh.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const j0=20,Rc=1,Hi=24,Qn="os-dock--revealed",rs="data-os-dock-behavior",V0="os-dock",Xh="os-side-dock",Gi="os-dock-vt",K0=".os-constellation, .os-dock-peek";function q0(e){const t=e.getAttribute("data-os-dock-placement");if(t==="left"||t==="right"){const n=getComputedStyle(e).direction==="rtl";return t==="left"!==n?"left":"right"}return"bottom"}function Zh(e){return e.getAttribute(rs)==="dynamic"}function Y0(e,t,n,o,s,i=j0){switch(e){case"bottom":return n>=s-i;case"left":return t<=i;case"right":return t>=o-i}return!1}function X0(e,t,n,o){const s=e.getBoundingClientRect();if(s.width<=0||s.height<=0)return!1;let i=s.top-Hi;const r=s.bottom+Hi;let a=s.left-Hi,l=s.right+Hi;switch(t){case"bottom":i=s.top-s.height*Rc;break;case"left":l=s.right+s.width*Rc;break;case"right":a=s.left-s.width*Rc;break}return n>=a&&n<=l&&o>=i&&o<=r}function Z0(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function J0(e){let t=!1,n=null,o=!1;const s=new Map,i=new Map;let r=!1,a=!1;const l=()=>Array.from(e.shellBody.querySelectorAll(".os-dock")),c=S=>{const $=e.getBehaviors(),W=S.id===Xh?$.sidebar:$.dock;S.getAttribute(rs)!==W&&S.setAttribute(rs,W)},d=S=>{const $=S.ownerDocument.activeElement;if($&&S.contains($))return!0;if(!n)return!1;if(o)return S.classList.contains(Qn);const W=q0(S);return Y0(W,n.x,n.y,window.innerWidth,window.innerHeight)||S.classList.contains(Qn)&&X0(S,W,n.x,n.y)},u=(S,$)=>{if(S.classList.contains(Qn)===$){i.delete(S);return}if(!$&&r){a=!0;return}if(s.has(S)){i.set(S,$);return}const W=()=>{S.classList.toggle(Qn,$)},F=document;if(typeof F.startViewTransition!="function"||Z0()){W();return}const x=`os-dock-${S.id||"rail"}`;S.style.setProperty("view-transition-name",x),document.documentElement.classList.add(Gi);let q;try{q=F.startViewTransition(W)}catch{S.style.removeProperty("view-transition-name"),document.documentElement.classList.remove(Gi),W();return}const J=q.finished&&typeof q.finished.then=="function"?q.finished:Promise.resolve(),X=()=>{S.style.removeProperty("view-transition-name"),s.delete(S),s.size===0&&document.documentElement.classList.remove(Gi);const T=i.get(S);i.delete(S),!t&&T!==void 0&&u(S,T)};s.set(S,J.then(X,X))},f=()=>{if(!t)for(const S of l()){if(c(S),!Zh(S)){S.classList.remove(Qn);continue}u(S,d(S))}},p=S=>{if(t||!l().some(Zh))return;n={x:S.clientX,y:S.clientY};const $=S.target;o=$ instanceof Element&&$.closest(K0)!==null,f()};let g=0;const h=()=>{g||(g=requestAnimationFrame(()=>{g=0,f()}))},m=()=>f(),E=()=>{r=!0},k=()=>{r=!1,a&&(a=!1,f())};document.addEventListener("pointerdown",E,{capture:!0,passive:!0}),document.addEventListener("pointerup",k,{capture:!0,passive:!0}),document.addEventListener("pointercancel",k,{capture:!0,passive:!0}),document.addEventListener("pointermove",p,{passive:!0}),document.addEventListener("pointerdown",p,{passive:!0}),document.addEventListener("focusin",h),document.addEventListener("focusout",h),document.addEventListener("os-layout-changed",m);let N=null;typeof MutationObserver<"u"&&(N=new MutationObserver(f),N.observe(e.shellBody,{childList:!0})),f();const M={refresh:f,destroy:()=>{t=!0,g&&(cancelAnimationFrame(g),g=0),N?.disconnect(),document.removeEventListener("pointerdown",E,{capture:!0}),document.removeEventListener("pointerup",k,{capture:!0}),document.removeEventListener("pointercancel",k,{capture:!0}),document.removeEventListener("pointermove",p),document.removeEventListener("pointerdown",p),document.removeEventListener("focusin",h),document.removeEventListener("focusout",h),document.removeEventListener("os-layout-changed",m);for(const S of l())S.classList.remove(Qn),S.style.removeProperty("view-transition-name");i.clear(),document.documentElement.classList.remove(Gi),zi===M&&(zi=null)}};return zi=M,M}let zi=null;function Q0(){zi?.refresh()}function Jh(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const Qh=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","linerWidth","linerColor","glow","glowBlur","eyeColor","eyeScale"],em=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function Mc(){return{appearance:{},physics:{}}}function eC(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function ji(e,t){const n={};if(!e||typeof e!="object"||Array.isArray(e))return n;const o=e;for(const s of t){const i=o[s];i!==void 0&&eC(i)&&Object.assign(n,{[s]:i})}return n}function tm(e){if(!e||typeof e!="object"||Array.isArray(e))return Mc();const t=e;return{appearance:ji(t.appearance,Qh),physics:ji(t.physics,em)}}function tC(e){return{appearance:ji(e,Qh),physics:ji(e,em)}}function nC(){const e=oC();if(e){const t=Pc(e,Wc());return $c(t),lC(t),t}try{const t=window.localStorage.getItem(Of);if(t)return Pc(JSON.parse(t),Wc())}catch{}return Wc()}function Wc(){const e=rm();return e.wallpaper=Ha(),e}function oC(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}const qe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Ie=(e,t)=>typeof e=="boolean"?e:t,Ut=e=>(t,n)=>e.some(o=>o.id===t)?t:n,eo=e=>(t,n)=>typeof t=="string"&&e.test(t)?t:n,Vi=/^[a-z0-9_/-]+$/,nm={wallpaper:(e,t)=>typeof e=="string"&&e!==""?e:t,accent:(e,t)=>e===Fa||zo().some(n=>n.id===e)?e:t,customAccent:eo(/^#[0-9a-fA-F]{6}$/),dockSize:Ut(Ga),windowRadius:Ut(za),openWindowsAs:Ut(Kk),adminBarMode:Ut(_i),desktopLayout:Ut(Yk),dockPlacement:Ut(qk),dockBehavior:Ut(Ei),sideDockBehavior:Ut(Ei),dockRailRenderer:eo(/^[a-z0-9_-]+$/),desktopTheme:eo(/^[a-z0-9_-]*$/),appliedThemeRecommendations:(e,t)=>Array.isArray(e)?Array.from(new Set(e.filter(n=>typeof n=="string"&&/^[a-z0-9_-]+$/.test(n)))).slice(-64):t.slice(),unfocusEffect:eo(Vi),windowReveal:eo(Vi),windowRevealDuration:(e,t)=>typeof e!="number"||!Number.isFinite(e)?t:e>0?Math.min(4e3,Math.max(80,Math.round(e))):0,windowLinkRenderer:eo(Vi),windowLinkVisibility:(e,t)=>e==="focus"||e==="always"||e==="off"?e:t,windowLinksEnabled:Ie,windowLinkRaiseOnFocus:Ie,windowLinkHighlight:Ie,customGradient:(e,t)=>qe(e)?hC(e):{...t},customImage:(e,t)=>e===null||qe(e)?mC(e):t,wallpaperSettings:(e,t)=>qe(e)?iC(e):t,libraryHdOnly:Ie,ai:(e,t)=>pC(e,t),heartbeatRate:(e,t)=>e===15||e===30||e===45||e===60?e:t,nativePostsEnabled:Ie,nativePostsHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativePagesEnabled:Ie,nativePagesHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativeUsersEnabled:Ie,nativePluginsEnabled:Ie,nativeCommentsEnabled:Ie,stationHomeEnabled:Ie,adminAssetCacheEnabled:Ie,windowPrewarmEnabled:Ie,showDesktopOnWallpaperClick:Ie,confirmCloseAllWindows:Ie,mioEnabled:Ie,mioApiEnabled:Ie,mioShowOnWallpaper:Ie,mioStyle:(e,t)=>qe(e)?tm(e):t,showPostStatusRibbons:Ie,developerModeEnabled:Ie,foldersSharingEnabled:Ie,navPlacement:(e,t)=>qe(e)?rC(e):t,navOrder:(e,t)=>Array.isArray(e)?sm(e):t,mobileLayout:(e,t)=>e==="auto"||e==="desktop"||e==="mobile"?e:t,mobileTabs:(e,t)=>Array.isArray(e)?sm(e).slice(0,3):t,dockPromotedPositions:(e,t)=>qe(e)?aC(e):t},om=Object.keys(nm);function Pc(e,t){const n=Bt(t),o=e,s=nm;for(const i of om)i in o&&(n[i]=s[i](o[i],n[i]));return typeof o.mioEnabled=="boolean"?n.mioEnabled=o.mioEnabled:typeof o.mioApiEnabled=="boolean"&&(n.mioEnabled=o.mioApiEnabled),n.mioApiEnabled=n.mioEnabled,n}const sC=new Set(["wallpaper","accent","customAccent","customGradient","customImage","wallpaperSettings","dockSize","windowRadius","adminBarMode","desktopLayout","dockPlacement","dockBehavior","sideDockBehavior","dockRailRenderer","desktopTheme"]);function iC(e){if(!qe(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(o===""||!Vi.test(o)||!qe(s))continue;const i={};let r=0;for(const[a,l]of Object.entries(s)){if(r>=32)break;if(!(a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof l=="boolean")i[a]=l;else if(typeof l=="number"&&Number.isFinite(l))i[a]=l;else if(typeof l=="string")i[a]=l.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function rC(e){const t=["both","rail","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(e)){if(o>=256)break;s===""||typeof i!="string"||!t.includes(i)||(n[s]=i,o++)}return n}function sm(e){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 aC(e){const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(s===""||!qe(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 Ki=null;const cC=250;let cn=null;function lC(e){cn=Bt(e)}function Bt(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},mioStyle:{appearance:{...e.mioStyle.appearance},physics:{...e.mioStyle.physics}},appliedThemeRecommendations:e.appliedThemeRecommendations.slice(),nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),nativePagesHiddenColumns:e.nativePagesHiddenColumns.slice(),navPlacement:{...e.navPlacement},navOrder:e.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function dC(e,t={}){$c(e),uC(e,t.windowId)}function $c(e){try{window.localStorage.setItem(Of,JSON.stringify(e))}catch{}}function uC(e,t){Ki!==null&&clearTimeout(Ki),t&&(Uc=t),Ft("pending"),Ki=setTimeout(()=>{Ki=null;const n=Uc;Uc=null,im(e,n)},cC)}let Uc=null;function fC(e){if(!cn)return{...e};const t=cn,n={};let o=!1;for(const s of Object.keys(e))JSON.stringify(e[s])!==JSON.stringify(t[s])&&(Object.assign(n,{[s]:e[s]}),o=!0);return o?n:null}let Bc=!1,Fc=null;function im(e,t){if(Bc){Fc={state:e,windowId:t},Ft("pending");return}const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Ft("saved",void 0,void 0,e);return}const i=fC(e);if(!i){Ft("saved",void 0,void 0,e);return}Ft("saving"),Bc=!0;const r=Bt(e),a=t||xt;Ae(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:i})},{windowId:a}).then(async l=>{if(!l.ok)throw await Wn(l);cn=r,Ft("saved",void 0,void 0,r)}).catch(l=>{qi=!0,cn?($c(cn),Ft("failed",l instanceof Error?l.message:String(l),Bt(cn))):Ft("failed",l instanceof Error?l.message:String(l))}).finally(()=>{Bc=!1;const l=Fc;if(Fc=null,l&&qi){qi=!1;return}qi=!1,l&&im(l.state,l.windowId)})}let qi=!1;function Ft(e,t,n,o){const s={phase:e};o&&(s.savedSettings=Bt(o)),t&&(s.error=t),n&&(s.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:s}))}function rm(){return Bt(Bn)}function pC(e,t=Bn.ai){if(!qe(e))return{...t};const{enabled:n}=e;return{enabled:typeof n=="boolean"?n:t.enabled}}function hC(e){if(!qe(e))return{...Bn.customGradient};const{from:t,to:n,angle:o}=e;return{from:Jh(t)?t:Bn.customGradient.from,to:Jh(n)?n:Bn.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:Bn.customGradient.angle}}function mC(e){if(!qe(e))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}}function Hc(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 gC(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function Yi(e,t,n){if(!gC(t))return!1;const o=`url("${t}") center / contain no-repeat`;return e.style.backgroundImage="none",e.style.backgroundColor=n,e.style.setProperty("-webkit-mask",o),e.style.setProperty("mask",o),!0}const wC="data-os-constellation";function yC(){return document.body.hasAttribute(wC)}const am="os-item-menu-opening",bC=180,vC=220,cm=32;function lm(e){const{tile:t}=e;let n=null,o=null,s=null,i=!1,r=null;const a=()=>{o!==null&&(window.clearTimeout(o),o=null)},l=()=>{s!==null&&(window.clearTimeout(s),s=null)},c=()=>{a(),l(),t.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),r?.clear(),r=null,e.suppressTooltip(!1)},d=h=>{h.pointerType==="mouse"&&(yC()&&(t.dataset.menuSlug||t.dataset.constellationId)||_C(e)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},bC))))},u=h=>{n&&h.relatedTarget instanceof Node&&n.contains(h.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},vC)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=EC(e,()=>c(),r),document.body.appendChild(n),TC(n),NC(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,l()}),n.addEventListener("pointerleave",h=>{h.relatedTarget instanceof Node&&t.contains(h.relatedTarget)||(i=!1,f())})},g=()=>c();return t.addEventListener("pointerenter",d),t.addEventListener("pointerleave",u),document.addEventListener(am,g),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(am,g),c()}}function _C(e){return e.getInstances().length>=1}function EC(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",le(b("%s — open windows"),e.item.title));const s=document.createElement("div");s.className="os-dock-peek__cards",o.appendChild(s);const i=e.getInstances();let r=0;for(const a of i){const l=kC(a,e,r++,t,n);s.appendChild(l)}if(e.enableGhost!==!1){const a=IC(e,r,t);s.appendChild(a)}return o}function dm(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function kC(e,t,n,o,s){const i=document.createElement("button");i.type="button",i.setAttribute("role","menuitem"),i.className="os-dock-peek__card os-dock-peek__card--instance",i.style.setProperty("--peek-card-index",String(n)),i.style.setProperty("--peek-card-delay",`${n*cm}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${Hc(e.id||r)}`),i.style.setProperty("--peek-card-vt-name",`os-peek-card-${e.id}`);const a=document.createElement("span");a.className="os-dock-peek__card-titlebar";const l=document.createElement("span");l.className="os-dock-peek__card-dots",l.setAttribute("aria-hidden","true");for(let k=0;k<3;k++)l.appendChild(document.createElement("i"));a.appendChild(l);const c=document.createElement("span");c.className="os-dock-peek__card-icon",c.setAttribute("aria-hidden","true");const d=e.config.icon||t.item.icon;d.startsWith("dashicons-")?c.classList.add("dashicons",xE(d)):c.classList.add("dashicons","dashicons-admin-generic"),a.appendChild(c);const u=document.createElement("span");u.className="os-dock-peek__card-label",u.textContent=r,a.appendChild(u),i.appendChild(a);const f=document.createElement("span");f.className="os-dock-peek__card-body",f.setAttribute("aria-hidden","true");for(let k=0;k<3;k++){const N=document.createElement("span");N.className="os-dock-peek__card-line",f.appendChild(N)}const p={window:e,item:t.item},g=Q(y.DOCK_PEEK_CARD_CONTENT,f,p);g!==f&&g.classList.add("os-dock-peek__card-body--custom"),i.appendChild(g),e.state==="minimized"&&(i.dataset.state="minimized");const h=()=>{s.delete(e.id),delete i.dataset.preview},m=k=>{if(h(),k.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(k.previouslyFocusedId){const N=t.windowManager.getById(k.previouslyFocusedId);N&&t.windowManager.focus(N)}};return i.addEventListener("click",()=>{h(),SC(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const k=e.state==="minimized",N=t.windowManager.getFocused(),M=N&&N!==e?N.id:null;(k||M!==null)&&(s.set(e.id,{wasMinimized:k,previouslyFocusedId:M}),i.dataset.preview=""),k?dm(e,i):N&&N!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const k=s.get(e.id);k&&m(k)}),Q(y.DOCK_PEEK_CARD_ELEMENT,i,p)}function SC(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),dm(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 l=s.startViewTransition(r),c=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},d=l;d.finished&&typeof d.finished.then=="function"?d.finished.then(c,c):Promise.resolve().then(c)}function IC(e,t,n){const o=document.createElement("button");o.type="button",o.setAttribute("role","menuitem"),o.className="os-dock-peek__card os-dock-peek__card--ghost",o.style.setProperty("--peek-card-index",String(t)),o.style.setProperty("--peek-card-delay",`${t*cm}ms`);const s=document.createElement("span");s.className="os-dock-peek__card-plus",s.setAttribute("aria-hidden","true"),s.textContent="+",o.appendChild(s);const i=document.createElement("span");return i.className="os-dock-peek__card-label",i.textContent=le(b("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{AC(e,n)}),o}function AC(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const CC=12,LC=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function TC(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of LC){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function NC(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}px`,e.style.left=`${o.left-12}px`):(e.style.top=`${o.top}px`,e.style.left=`${o.right+12}px`),requestAnimationFrame(()=>OC(e))}function OC(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=CC;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("os-dock-peek--clamped"))}function to(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 um(e){let t,n;try{const s=new URL(e,document.baseURI);t=s.origin,n=s.pathname}catch{return null}if(!n)return null;const o=document.querySelectorAll("script[src]");for(const s of Array.from(o))try{const i=new URL(s.src,document.baseURI);if(i.origin===t&&i.pathname===n)return s}catch{}return null}const fm=new Map;function DC(e){const t=fm.get(e);if(t)return t;let n=[];try{const o=new URL(e,document.baseURI);if(o.pathname.endsWith("/load-scripts.php")){const s=[];o.searchParams.forEach((i,r)=>{if(r!=="load"&&!r.startsWith("load["))return;const a=/(\d+)/.exec(r);s.push({order:a?Number(a[1]):s.length,value:i})}),s.sort((i,r)=>i.order-r.order),n=s.map(i=>i.value).join("").split(",").map(i=>i.trim()).filter(Boolean)}}catch{}return fm.set(e,n),n}function xC(){const e=new Set,t=document.querySelectorAll('script[src*="load-scripts.php"]');for(const n of Array.from(t))for(const o of DC(n.src))e.add(o);return e}const RC=["-js","-js-before","-js-after","-js-extra","-js-translations"];function MC(e){return e?RC.some(t=>{const n=document.getElementById(e+t);return!!n&&n.tagName==="SCRIPT"}):!1}function Gc(e){return e.url&&um(e.url)?!0:e.handle?xC().has(e.handle)||MC(e.handle):!1}const Xi=new Map,pm=new Set;function pe(e,t){const n=Xi.get(e);if(n)return n;const o=t?.deps;if(o&&o.length>0){const i=a=>Gc(a)?Promise.resolve():a.url?pe(a.url,{...a,deps:void 0}):(WC(a),Promise.resolve()),r=o.reduce((a,l)=>a.then(()=>i(l)),Promise.resolve(void 0)).then(()=>hm(e,t));return Xi.set(e,r),r}const s=hm(e,t);return Xi.set(e,s),s}function WC(e){if(e.handle){if(pm.has(e.handle))return;pm.add(e.handle)}for(const t of e.l10n??[])Ht(t);for(const t of e.before??[])Ht(t);for(const t of e.after??[])Ht(t)}function hm(e,t){return new Promise((n,o)=>{const s=`script[data-os-vendor="${PC(e)}"]`,i=document.querySelector(s);if(i){if(i.dataset.loaded==="1"){n();return}i.addEventListener("load",()=>n(),{once:!0}),i.addEventListener("error",()=>o(new Error(`Failed to load ${e}`)),{once:!0});return}const r=um(e);if(r){r.dataset.osVendor=e,r.dataset.loaded="1",n();return}if(Gc({handle:t?.handle})){n();return}t?.translations&&Ht(t.translations);for(const l of t?.l10n??[])Ht(l);for(const l of t?.before??[])Ht(l);const a=document.createElement("script");a.src=e,a.async=!0,a.dataset.osVendor=e,a.addEventListener("load",()=>{a.dataset.loaded="1";for(const l of t?.after??[])Ht(l);n()},{once:!0}),a.addEventListener("error",()=>{Xi.delete(e),a.remove(),o(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(a)})}function Ht(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function mm(e){Ht(e)}function PC(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let gm=0;function wm(){return window.openStationItemVisibilityMenu??null}function $C(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function ym(e){const t=wm();if(t){t.openItemVisibilityMenu(e);return}const n=$C();if(!n)return;const o=++gm;pe(n).then(()=>{o===gm&&wm()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const UC={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function BC(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function bm(e){return e==="core"?"core":e==="control"?"controls":"apps"}function vm(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??UC[e.kind]}function _m(e){return e==="rail"||e==="both"}function FC(e){return e==="desktop"||e==="both"}function HC(e,t,n){return _m(e)?"rail":"hidden"}function Em(e,t){if(t.length===0||e.length<=1)return e.slice();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&&!s.has(i)&&(o.push(r),s.add(i))}for(const i of e)s.has(i.id)||o.push(i);return o}function GC(e,t){const n=new Set(t),o=t.slice(),s=[];for(const i of e){if(!n.has(i)){s.push(i);continue}const r=o.shift();r!==void 0&&s.push(r)}return s.push(...o),s}function km(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>(t.item.order??0)-(n.item.order??0)||t.index-n.index).map(t=>t.item)}function Zi(){return window.wp?.os??null}function zC(){const e=Zi()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function jC(){return Zi()?.getNavItems?.()??[]}function VC(e){const t=jC();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function KC(e){const t=Zi();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n={...t.getOsSettings().navPlacement??{}};let o=!1;for(const{item:s,placement:i}of e)s.locked||(n[s.id]=i,o=!0);o&&t.updateOsSettings({navPlacement:n})}function qC(e,t,n){const o=Array.isArray(e)?e:[e],s=zC().placement,i=[];for(const r of o){const a=typeof r=="string"?VC(r):r;a&&i.push({item:a,placement:HC(vm(a,s))})}KC(i)}function YC(e){const t=Zi();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:GC(n,e)})}const ft=["core","apps","controls"];function Sm(e){const{items:t,config:n,layout:o,openWindows:s}=e,i={core:[],apps:[],controls:[]},r=[],a=[],l=new Set,c=new Set,d=new Map,u=new Set;for(const p of t){u.add(p.id),p.windowId&&!d.has(p.windowId)&&d.set(p.windowId,p);const g=vm(p,n.placement);if(_m(g)){c.add(p.id);const h=bm(p.kind);BC(p.kind,o)==="sidebar"?r.push(p):i[h].push(p)}FC(g)&&a.push(p)}for(const p of t)for(const g of p.answersFor??[])d.has(g)||d.set(g,p);for(const p of s){const g=d.get(p.id);if(g){if(c.has(g.id)||l.has(g.id))continue;i.apps.push(g),l.add(g.id);continue}p.fromAdminUrl||l.has(p.id)||u.has(p.id)||(i.apps.push({id:p.id,kind:"app",title:p.title,icon:p.icon,windowId:p.id,transient:!0}),l.add(p.id))}const f=p=>Em(XC(km(p)),n.order);for(const p of ft)i[p]=f(i[p]);return{dock:i,sidebar:f(r),desktop:Em(km(a),n.order),ephemeral:l}}function XC(e){const t=e.filter(o=>o.kind==="core"&&o.tile),n=e.filter(o=>!t.includes(o));return t.length===0||n.length===0?e:[n[0],...t,...n.slice(1)]}const ZC=["action","action2","_wpnonce","nonce","delete_all"];function JC(e){const t=e.slice(e.lastIndexOf("/")+1);return/-new\.php$/.test(t)}function QC(e){if(JC(e.pathname))return!0;for(const t of ZC)if(e.searchParams.has(t))return!0;return!1}function Im(e){return bm(e.navKind??"app")}const Ge=class Ge{constructor(t,n,o,s,i="left"){this.itemElements=new Map,this.systemItems=[],this.systemItemElements=new Map,this.zones={core:[],apps:[],controls:[]},this.badgeOverrides=new Map,this.artOverrides=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/${++Ge.instanceCounter}`,this.container.classList.add("os-dock--no-transition"),this.container.setAttribute("data-os-dock-placement",i),this.container.offsetWidth,this.container.classList.remove("os-dock--no-transition");const r=document.createElement("div");r.className="os-dock__scroll";const a=document.createElement("div");a.className="os-dock__pinned",t.appendChild(r),t.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="os-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.zones=this.zonesFromMenu(o,[]),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-os-dock-placement",t),this.tooltip.classList.remove("os-dock__tooltip--above","os-dock__tooltip--before","os-dock__tooltip--after"),t==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):t==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"))}replaceItems(t){this.zones=this.zonesFromMenu(t,this.systemEntries()),this.render()}setZones(t){this.zones={core:t.core.slice(),apps:t.apps.slice(),controls:t.controls.slice()},this.render()}systemEntries(){const t=[];for(const n of ft)for(const o of this.zones[n])o.type==="system"&&t.push(o);return t}zonesFromMenu(t,n){const o={core:[],apps:[],controls:[]};for(const s of t)o[s.isCore?"core":"apps"].push({type:"menu",item:s});for(const s of n)s.type==="system"&&o[Im(s.item)].push(s);return o}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(t){let n=!1;for(const o of ft){const s=this.zones[o].filter(i=>i.type!=="system"||i.item.id!==t);s.length!==this.zones[o].length&&(n=!0),this.zones[o]=s}n&&(this.badgeOverrides.delete(t),this.artOverrides.delete(t),this.render(),L(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(".os-dock__item-primary");Am(i??o,s),Se.publish("os/badge-changed",{itemId:t,count:s,rail:this.rail})}clearBadge(t){this.setBadge(t,0)}setArt(t,n){if(!n){if(!this.artOverrides.delete(t))return;const s=this._resolveTileElement(t),i=this._declaredIcon(t);s&&i&&this._paintArt(s,t,i),Se.publish("os/art-changed",{itemId:t,icon:"",rail:this.rail});return}this.artOverrides.set(t,n);const o=this._resolveTileElement(t);o&&(this._paintArt(o,t,n),Se.publish("os/art-changed",{itemId:t,icon:n,rail:this.rail}))}getArt(t){return this.artOverrides.get(t)??""}_declaredIcon(t){const n=this.items.find(s=>s.id===t);if(n)return n.icon;const o=this.systemItems.find(s=>s.id===t);return o?o.icon:""}_paintArt(t,n,o){const s=t.querySelector(".os-dock__item-primary")??t,i=this.resolveIcon(o,this._declaredTitle(n),void 0,Vn(n)),r=s.querySelector(".os-dock__item-mask, .os-dock__item-svg, .dashicons, img");r?r.replaceWith(i):s.prepend(i)}_declaredTitle(t){const n=this.items.find(s=>s.id===t);if(n)return n.title;const o=this.systemItems.find(s=>s.id===t);return o?o.title:""}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("os-dock__item--attention-pulse","os-dock__item--attention-shake","os-dock__item--attention-bounce","os-dock__item--intensity-subtle","os-dock__item--intensity-normal","os-dock__item--intensity-strong"),n===null)return;s.classList.add(`os-dock__item--attention-${n}`);const r=o.intensity??"normal";s.classList.add(`os-dock__item--intensity-${r}`);const a=o.durationMs??4e3;if(a>0){const l=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},a);this.attentionTimers.set(t,l)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}appendSystemItem(t){const n=Im(t),o={type:"system",item:t};for(const a of ft)this.zones[a]=this.zones[a].filter(l=>l.type!=="system"||l.item.id!==t.id);const s=this.zones[n],i=t.order??0,r=s.findIndex(a=>a.type==="system"&&(a.item.order??0)>i);r===-1?s.push(o):s.splice(r,0,o),this.render()}render(){if(Ge.activeDragReset){const o=Ge.activeDragReset;Ge.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="",this.systemHost.innerHTML="",this.itemElements.clear(),this.systemItemElements.clear(),this.items=[],this.systemItems=[];for(const o of ft)for(const s of this.zones[o])s.type==="menu"?this.items.push(s.item):this.systemItems.push(s.item);const t=this.buildHookContextBase();L(y.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of ft){const s=this.zones[o];if(s.length===0)continue;const i=o==="controls"?this.systemHost:this.itemHost;if(n){const r=document.createElement("div");r.className=o==="controls"?"os-dock__separator":"os-dock__separator os-dock__separator--group",r.setAttribute("aria-hidden","true"),i.appendChild(r)}for(const r of s)this.paintEntry(r,o,i,t);n=!0}this.updateActiveStates(),L(y.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}paintEntry(t,n,o,s){const i=t.item.id,r=t.type==="menu"?this.createItemButton(t.item):this.createSystemItemButton(t.item);r.dataset.zone=n,r.dataset.navId=i,t.type==="system"&&t.item.locked===!0?r.dataset.navLocked="true":(this.attachDragReorder(r,i,n),r.addEventListener("contextmenu",d=>{d.preventDefault(),ym({x:d.clientX,y:d.clientY,id:i,title:t.item.title,surface:"dock",pluginFile:t.type==="menu"?t.item.pluginFile??null:null,pluginName:t.type==="menu"?t.item.pluginName??null:null})})),t.type==="menu"?this.itemElements.set(i,r):this.systemItemElements.set(i,r),o.appendChild(r);const l=this.badgeOverrides.get(i);if(l!==void 0){const d=r.querySelector(".os-dock__item-primary");Am(d??r,l)}const c=this.artOverrides.get(i);c&&this._paintArt(r,i,c),L(y.DOCK_TILE_RENDERED,{...s,item:t.item,isSystem:t.type==="system",el:r})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=Q(y.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id,o.dataset.osWindowBaseId=t.id,t.submenu&&t.submenu.length>0&&(o.dataset.constellationId=t.id);const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title,void 0,Vn(t.id))),r.addEventListener("click",l=>t.onOpen(l)),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=lm({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:l=>{l&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),this.bindPrewarmDwell(o,()=>this.prewarmNativeWindow(t.id)),Q(y.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];t.multi&&s.push("os-dock__item--multi");const i=Q(y.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const a=this.resolveIcon(t.icon,t.title,t.url,Vn(t.id));if(r.appendChild(a),t.badge>0){const d=t.badge>99?"99+":String(t.badge),u=document.createElement("span");u.className="os-dock__badge",u.textContent=d,u.setAttribute("aria-label",le(Qt("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const l=this.resolveItemBaseId(t);o.dataset.osWindowBaseId=l;const c=lm({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(l),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(t),suppressTooltip:d=>{d&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(t.id,c),this.bindHoverPrewarm(o,t),Q(y.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n,o){let r=!1,a=0,l=0,c=[],d=null,u=-1,f=null,p=!1;const g=()=>{r=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",M),document.removeEventListener("pointerup",F),document.removeEventListener("pointercancel",x),document.removeEventListener("keydown",q,!0),window.removeEventListener("blur",J),document.removeEventListener("visibilitychange",X),u=-1,f=null},h=o==="controls"?this.systemHost:this.itemHost,m=T=>!!T&&T instanceof HTMLElement&&T.classList.contains("os-dock__item")&&T.dataset.zone===o&&!!T.dataset.navId&&T.dataset.navLocked===void 0,E=T=>{for(const D of Array.from(h.children))D instanceof HTMLElement&&D!==t&&m(D)&&T(D)},k=()=>{const T=[];for(const D of Array.from(h.children))m(D)&&T.push(D.dataset.navId);return T},N=T=>{E(D=>{const K=T.get(D);if(!K)return;const G=D.getBoundingClientRect(),ne=K.left-G.left,ce=K.top-G.top;if(Math.abs(ne)<.5&&Math.abs(ce)<.5)return;D.style.transition="none",D.style.transform=`translate(${ne}px, ${ce}px)`,D.offsetHeight,D.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",D.style.transform="";const R=()=>{D.style.transition="",D.style.transform="",D.removeEventListener("transitionend",R)};D.addEventListener("transitionend",R)})},M=T=>{if(u!==-1&&T.pointerId!==u)return;if(!r){const B=T.clientX-a,z=T.clientY-l;if(B*B+z*z<5*5)return;r=!0,c=k(),d=t.nextSibling,f=t.getBoundingClientRect(),t.classList.add("os-dock__item--dragging"),this.tooltip.classList.remove("os-dock__tooltip--visible")}if(!f)return;const D=T.clientX-a,K=T.clientY-l;t.style.transform=`translate(${D}px, ${K}px)`;const ne=document.elementFromPoint(T.clientX,T.clientY)?.closest(".os-dock__item");if(!ne||ne===t||!m(ne))return;const ce=ne.getBoundingClientRect();let R;this.orientation==="bottom"?R=T.clientX<ce.left+ce.width/2:R=T.clientY<ce.top+ce.height/2;const C=new Map;E(B=>{C.set(B,B.getBoundingClientRect())});let U=!1;if(R?ne!==t.nextSibling&&(h.insertBefore(t,ne),U=!0):ne.nextSibling!==t&&(h.insertBefore(t,ne.nextSibling),U=!0),U){t.style.transform="";const B=t.getBoundingClientRect();a=B.left+B.width/2,l=B.top+B.height/2,t.style.transform=`translate(${T.clientX-a}px, ${T.clientY-l}px)`,N(C)}},S=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",M),document.removeEventListener("pointerup",F),document.removeEventListener("pointercancel",x),document.removeEventListener("keydown",q,!0),window.removeEventListener("blur",J),document.removeEventListener("visibilitychange",X),u=-1,f=null,r=!1,Ge.activeDragReset===g&&(Ge.activeDragReset=null)},$=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const T=()=>{t.style.transition="",t.removeEventListener("transitionend",T)};t.addEventListener("transitionend",T)},W=T=>{YC(T)},F=T=>{if(u!==-1&&T.pointerId!==u)return;if(!r){S();return}p=!0;const D=k();$(),S(),D.length===c.length&&D.every((G,ne)=>G===c[ne])||W(D),setTimeout(()=>{p=!1},200)},x=T=>{if(!(T&&u!==-1&&T.pointerId!==u)){if(r&&d!==void 0){const D=new Map;E(K=>{D.set(K,K.getBoundingClientRect())}),h.insertBefore(t,d),N(D)}$(),S()}},q=T=>{T.key==="Escape"&&x()},J=()=>x(),X=()=>{document.visibilityState!=="visible"&&x()};t.addEventListener("pointerdown",T=>{if(!(T.button!==0||Jt())){if(Ge.activeDragReset){const D=Ge.activeDragReset;Ge.activeDragReset=null,D()}(r||u!==-1)&&g(),a=T.clientX,l=T.clientY,u=T.pointerId,r=!1,Ge.activeDragReset=g,document.addEventListener("pointermove",M),document.addEventListener("pointerup",F),document.addEventListener("pointercancel",x),document.addEventListener("keydown",q,!0),window.addEventListener("blur",J),document.addEventListener("visibilitychange",X)}}),t.addEventListener("click",T=>{p&&(T.preventDefault(),T.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=Vo(s);a!==null&&(t=a,i=!0),r=Ya(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if(Yi(a,t,r))return a}if(t.startsWith("dashicons-")&&(i||t!=="dashicons-admin-generic")){const a=document.createElement("span");return a.className=`dashicons ${t}`,a.setAttribute("aria-hidden","true"),r!==null&&(a.style.color=r),a}if(t.startsWith("data:image/svg+xml;base64,")){const a=t.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(a))return this._makeSvgIcon(t)}if(t.startsWith("url("))return this._makeSvgIcon(t);if(t.startsWith("http://")||t.startsWith("https://")){const a=document.createElement("img");return a.className="os-dock__item-img",a.src=t,a.alt="",a.setAttribute("aria-hidden","true"),a}if(o&&!i){const a=this._extractNativeMenuIcon(o);if(a)return a}if(t==="dashicons-admin-generic"){const a=document.createElement("span");return a.className="dashicons dashicons-admin-generic",a.setAttribute("aria-hidden","true"),a}return this.createLetterBadge(n)}_makeMaskSpan(){const t=document.createElement("span");return t.className="os-dock__item-mask",t.setAttribute("aria-hidden","true"),t.style.width="var( --os-dock-icon-size, 20px )",t.style.height="var( --os-dock-icon-size, 20px )",t.style.display="block",t.style.flexShrink="0",t}_makeSvgIcon(t){const n=/^url\(\s*(['"]?)(.+?)\1\s*\)$/.exec(t),o=n?n[2]:t,s=this._makeMaskSpan();if(Yi(s,o,"currentColor"))return s;const i=document.createElement("span");return i.className="os-dock__item-svg",i.style.backgroundImage=t.startsWith("url(")?t:`url("${t}")`,i.style.backgroundSize="contain",i.style.backgroundRepeat="no-repeat",i.style.backgroundPosition="center",i.setAttribute("aria-hidden","true"),i}_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="os-dock__item-img",p.src=a.src,p.alt="",p.setAttribute("aria-hidden","true"),p}const l=r.className.match(/\bdashicons-[\w-]+\b/);if(l&&l[0]!=="dashicons-before"){const p=document.createElement("span");return p.className=`dashicons ${l[0]}`,p.setAttribute("aria-hidden","true"),p}const c=window.getComputedStyle(r,"::before"),d=c.backgroundImage;if(d&&d!=="none"&&!d.includes('url("")'))return this._makeSvgIcon(d);const u=c.maskImage||c.webkitMaskImage;if(u&&u!=="none"&&!u.includes('url("")'))return this._makeSvgIcon(u);const f=window.getComputedStyle(r).backgroundImage;return f&&f!=="none"&&!f.includes('url("")')?this._makeSvgIcon(f):null}createLetterBadge(t){const n=document.createElement("span");n.className="os-dock__item-letter",n.setAttribute("aria-hidden","true");const o=t.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=Hc(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=Q(y.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("os-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("os-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`)}bindHoverPrewarm(t,n){if(!n.url){const{windowId:o}=n;o&&this.bindPrewarmDwell(t,()=>this.prewarmNativeWindow(o));return}this.bindPrewarmDwell(t,()=>{const o=ik(n.url);if(o){this.prewarmNativeWindow(o.id,o.params);return}try{const i=new URL(n.url,window.location.href);if(i.origin!==window.location.origin||QC(i)||Rn(i))return}catch{return}const s=this.deriveWindowId(n.url);this.windowManager.prewarm({id:s,baseId:s,url:n.url,parentUrl:n.url,title:n.title,icon:n.icon.startsWith("dashicons-")?n.icon:"dashicons-admin-generic",submenu:n.submenu,selfLabel:n.selfLabel,multi:!!n.multi})})}bindPrewarmDwell(t,n){let s;const i=()=>{s!==void 0&&(window.clearTimeout(s),s=void 0)};t.addEventListener("pointerenter",r=>{r.pointerType!=="mouse"||!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled||(i(),s=window.setTimeout(()=>{s=void 0,n()},180))}),t.addEventListener("pointerleave",i),t.addEventListener("pointerdown",i)}prewarmNativeWindow(t,n){if(this.windowManager.getById(t))return;const o=window.wp?.os;n?o?.prewarmWindow?.(t,{params:n}):o?.prewarmWindow?.(t)}openPage(t){if(t.windowId&&!t.url){const o=this.windowManager.getById(t.windowId);if(o){const i=o.state==="minimized";this.windowManager.focus(o),i&&o.restore();return}window.wp?.os?.openWindow?.(t.windowId);return}if(to(t.url)||Be(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,selfLabel:t.selfLabel,multi:!!t.multi})}openNewInstance(t){if(to(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=$o(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,selfLabel:t.selfLabel,multi:!0})}deriveWindowId(t){return fe(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:$o(t.url)??this.deriveWindowId(t.url)}bindWindowEvents(){const t=()=>this.updateActiveStates();this.boundRefresh=t,document.addEventListener("os-window-opened",t),document.addEventListener("os-window-closed",t),document.addEventListener("os-window-focused",t),window.wp?.hooks?.addAction?.("os.os.switched",this.hooksNamespace,t),window.wp?.hooks?.addAction?.("os.os.closed",this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.DOCK_REFRESH_ACTIVE,this.hooksNamespace,t)}destroy(){document.removeEventListener("os-window-opened",this.boundRefresh),document.removeEventListener("os-window-closed",this.boundRefresh),document.removeEventListener("os-window-focused",this.boundRefresh),window.wp?.hooks?.removeAction?.("os.os.switched",this.hooksNamespace),window.wp?.hooks?.removeAction?.("os.os.closed",this.hooksNamespace),window.wp?.hooks?.removeAction?.(y.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(y.DOCK_REFRESH_ACTIVE,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.zones={core:[],apps:[],controls:[]},this.container.removeAttribute("data-os-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 l=this.windowManager.getAllByBaseId(a).filter(o);if(l.length===0&&i.url){const f=this.deriveWindowId(i.url);l=this.windowManager.getAll().filter(p=>{const g=p.config.baseId||p.id;if(g===a||g===f||g===i.id||p.config.parentUrl&&this.deriveWindowId(p.config.parentUrl)===f)return!0;if(p.config.url){const h=this.deriveWindowId(p.config.url);return h===a||h===f}return!1}).filter(o)}const c=l.length>0,d=c&&l.every(s),u=!!t&&o(t)&&!s(t)&&l.some(f=>f.id===t.id||(t.config.baseId||t.id)===a);r.classList.toggle("os-dock__item--active",c),r.classList.toggle("os-dock__item--focused",u),r.classList.toggle("os-dock__item--all-minimized",d),r.classList.toggle("os-dock__item--stacked",c&&l.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),l=i.isOpen?i.isOpen():!!a,c=!!a&&s(a),d=!!t&&t.id===i.id&&!s(t);r.classList.toggle("os-dock__item--active",l),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",c)}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("os-show-desktop-active",o)}};Ge.instanceCounter=0,Ge.activeDragReset=null;let Ji=Ge;function Am(e,t){const n=e.querySelector(":scope > .os-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",le(Qt("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="os-dock__badge",s.textContent=o,s.setAttribute("aria-label",le(Qt("%d notification","%d notifications",t),t)),e.appendChild(s)}const Cm=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),Qi={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 Ji(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[Cm]:t,replaceItems:o=>t.replaceItems(o),setZones:o=>t.setZones(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 Lm(e){if(!e)return null;const n=e[Cm];return n instanceof Ji?n:null}const Tm="data:image/svg+xml;base64,",er=new Map;function eL(e){const t=er.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(Tm.length)).includes("currentColor")}catch{}return er.size>=256&&er.clear(),er.set(e,n),n}function ln(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const l=Vo(t.slot);l!==null&&(e=l),s=Ya(t.slot)}if(typeof e=="string"&&e.startsWith("dashicons-")){const l=document.createElement("span");return l.className=`dashicons ${e} ${n}`.trim(),l.setAttribute("aria-hidden","true"),s!==null&&(l.style.color=s),l}if(s!==null&&typeof e=="string"){const l=document.createElement("span");if(l.className=n,l.setAttribute("aria-hidden","true"),l.style.display="inline-block",Yi(l,e,s))return l}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const l=e.slice(Tm.length);if(/^[A-Za-z0-9+/=]+$/.test(l)){const c=document.createElement("span");return c.className=n,c.setAttribute("aria-hidden","true"),c.style.display="inline-block",eL(e)&&Yi(c,e,"currentColor")||(c.style.backgroundImage=`url("${e}")`,c.style.backgroundRepeat="no-repeat",c.style.backgroundPosition="center",c.style.backgroundSize="contain"),c}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const l=e.indexOf(","),c=l>=0?e.slice(l+1):"";if(/^[A-Za-z0-9+/=]+$/.test(c))return Nm(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return Nm(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=tL(o);i.textContent=r;const a=Hc(o);return i.style.backgroundColor=`hsl( ${a}, 60%, 45% )`,i.style.color="#fff",i.style.display="inline-flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.fontWeight="600",i.style.borderRadius="4px",i}function Nm(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 tL(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()}function Om(e){let t=0;const n=()=>{const o=new Date;e.textContent=o.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}),e.dateTime=o.toISOString(),e.title=o.toLocaleDateString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric"}),t=window.setTimeout(n,6e4-(o.getSeconds()*1e3+o.getMilliseconds()))};return n(),()=>window.clearTimeout(t)}const Dm=[y.WINDOW_OPENED,y.WINDOW_REOPENED,y.WINDOW_CLOSED,y.WINDOW_FOCUSED,y.WINDOW_BLURRED,y.WINDOW_MINIMIZED,y.WINDOW_RESTORED,y.WINDOW_TITLE_CHANGED,y.DESKTOP_SWITCHED,y.WINDOW_DESKTOP_CHANGED];let nL=0;function ke(e,t){const n=document.createElement(e);return n.className=t,n}function tr(e,t,n){return ln(e||"dashicons-admin-generic",{title:t,className:"os-taskbar__icon",slot:Vn(n)})}class oL{constructor(t){this.menuEntries=[],this.trayEntries=[],this.stopClock=()=>{},this.openOrder=[],this.onDocPointer=s=>{const i=s.target;i&&!this.menu.contains(i)&&!this.start.contains(i)&&this.closeMenu()},this.deps=t,this.namespace=`openstation/taskbar-${++nL}`,this.root=ke("div","os-taskbar"),this.start=ke("button","os-taskbar__start"),this.start.type="button",this.start.setAttribute("aria-haspopup","menu"),this.start.setAttribute("aria-expanded","false"),this.start.appendChild(tr("dashicons-wordpress",b("Start"),"os-taskbar-start"));const n=ke("span","os-taskbar__start-label");n.textContent=b("Start"),this.start.appendChild(n),this.start.addEventListener("click",()=>this.toggleMenu()),this.tasks=ke("div","os-taskbar__tasks"),this.tasks.setAttribute("role","toolbar"),this.tasks.setAttribute("aria-label",b("Open windows"));const o=ke("div","os-taskbar__tray");this.trayItems=ke("div","os-taskbar__tray-items"),this.clock=ke("time","os-taskbar__clock"),o.append(this.trayItems,this.clock),this.menu=ke("div","os-taskbar__menu"),this.menu.setAttribute("role","menu"),this.menu.hidden=!0,this.menu.addEventListener("keydown",s=>this.onMenuKey(s)),this.root.append(this.start,this.tasks,o),t.container.setAttribute("data-os-dock-placement",t.orientation),t.container.setAttribute("data-os-dock-renderer","taskbar"),t.container.append(this.root,this.menu);for(const s of Dm)ee(s,this.namespace,()=>this.paintTasks());this.paintTasks(),this.stopClock=Om(this.clock)}controller(){return{replaceItems:t=>{this.menuEntries=t.map(n=>({type:"menu",item:n}))},setZones:t=>this.setZones(t),appendSystemItem:t=>{this.trayEntries=[...this.trayEntries.filter(n=>n.id!==t.id),t],this.paintTray()},removeSystemItem:t=>{this.trayEntries=this.trayEntries.filter(n=>n.id!==t),this.paintTray()},destroy:()=>this.destroy()}}setZones(t){this.menuEntries=[...t.core,...t.apps],this.trayEntries=t.controls.filter(n=>n.type==="system").map(n=>n.item),this.paintTray()}windows(){const t=this.deps.windowManager,n=t.getActiveDesktopId(),o=t.getAll(),s=new Set(o.map(i=>i.id));this.openOrder=this.openOrder.filter(i=>s.has(i));for(const i of o)this.openOrder.includes(i.id)||this.openOrder.push(i.id);return o.filter(i=>!i.config.desktopId||i.config.desktopId===n).sort((i,r)=>this.openOrder.indexOf(i.id)-this.openOrder.indexOf(r.id))}paintTasks(){const t=this.deps.windowManager,n=this.windows().map(o=>{const s=ke("button","os-taskbar__task");s.type="button";const i=o.isFocused()&&!o.isMinimized();s.classList.toggle("os-taskbar__task--active",i),s.setAttribute("aria-pressed",i?"true":"false"),s.title=o.config.title;const r=ke("span","os-taskbar__task-label");return r.textContent=o.config.title,s.append(tr(o.config.icon??"",o.config.title,o.config.baseId??o.id),r),s.addEventListener("click",()=>{o.isMinimized()?(o.restore(),t.focus(o)):o.isFocused()?o.minimize():t.focus(o)}),s});this.tasks.replaceChildren(...n)}paintTray(){const t=this.trayEntries.map(n=>{const o=ke("button","os-taskbar__tray-item");return o.type="button",o.title=n.title,o.setAttribute("aria-label",n.title),o.dataset.systemId=n.id,o.appendChild(tr(n.icon,n.title,n.id)),o.addEventListener("click",s=>n.onOpen(s)),o});this.trayItems.replaceChildren(...t)}toggleMenu(){this.menu.hidden?this.openMenu():this.closeMenu()}openMenu(){this.paintMenu(),this.menu.hidden=!1,this.start.setAttribute("aria-expanded","true"),this.start.classList.add("os-taskbar__start--open"),document.addEventListener("pointerdown",this.onDocPointer,!0),this.menu.querySelector('[role="menuitem"]')?.focus()}closeMenu(){this.menu.hidden||(this.menu.hidden=!0,this.start.setAttribute("aria-expanded","false"),this.start.classList.remove("os-taskbar__start--open"),document.removeEventListener("pointerdown",this.onDocPointer,!0))}paintMenu(){const t=ke("div","os-taskbar__banner");t.setAttribute("aria-hidden","true");const n=ke("b","");n.textContent="Open",t.append(n,"Station");const o=ke("div","os-taskbar__menu-list");for(const i of this.menuEntries)o.appendChild(this.menuRow(i));const s=this.trayEntries.find(i=>i.id==="os-exit");s&&(o.appendChild(ke("div","os-taskbar__menu-separator")),o.appendChild(this.systemRow(s))),this.menu.replaceChildren(t,o)}menuRow(t){if(t.type==="system")return this.systemRow(t.item);const n=t.item,o=n.submenu??[],s=this.row(n.icon,n.title,n.id,o.length>0);if(o.length===0)return s.addEventListener("click",()=>{this.closeMenu(),this.deps.openItem(n)}),s;const i=ke("div","os-taskbar__submenu");i.setAttribute("role","menu");const r=this.row("",n.selfLabel||n.title,"",!1);r.addEventListener("click",()=>{this.closeMenu(),this.deps.openItem(n)}),i.appendChild(r);for(const l of o){if(l.offSite)continue;const c=this.row("",l.title,"",!1);c.addEventListener("click",()=>{this.closeMenu(),this.deps.openSubmenuPick(n,l)}),i.appendChild(c)}const a=ke("div","os-taskbar__cascade");return a.append(s,i),s.addEventListener("click",()=>this.openCascade(a)),a.addEventListener("pointerenter",()=>this.openCascade(a)),a}systemRow(t){const n=this.row(t.icon,t.title,t.id,!1);return n.addEventListener("click",o=>{this.closeMenu(),t.onOpen(o)}),n}row(t,n,o,s){const i=ke("button","os-taskbar__menu-item");i.type="button",i.setAttribute("role","menuitem"),i.tabIndex=-1,t?i.appendChild(tr(t,n,o)):i.appendChild(ke("span","os-taskbar__icon os-taskbar__icon--blank"));const r=ke("span","os-taskbar__menu-label");return r.textContent=n,i.appendChild(r),s&&(i.setAttribute("aria-haspopup","menu"),i.appendChild(ke("span","os-taskbar__menu-arrow"))),i.addEventListener("pointerenter",()=>i.focus()),i}openCascade(t){for(const o of this.menu.querySelectorAll(".os-taskbar__cascade--open"))o!==t&&o.classList.remove("os-taskbar__cascade--open");t.classList.add("os-taskbar__cascade--open");const n=t.querySelector(".os-taskbar__submenu");if(n){n.style.removeProperty("--os-taskbar-submenu-shift");const o=n.getBoundingClientRect().bottom-this.deps.container.getBoundingClientRect().top;o>0&&n.style.setProperty("--os-taskbar-submenu-shift",`${-o}px`)}}onMenuKey(t){const n=this.menu.ownerDocument.activeElement;if(!n||!this.menu.contains(n))return;const o=n.closest(".os-taskbar__submenu, .os-taskbar__menu-list"),s=o?[...o.querySelectorAll(':scope > [role="menuitem"], :scope > .os-taskbar__cascade > [role="menuitem"]')]:[],i=s.indexOf(n),r=!!n.closest(".os-taskbar__submenu"),a=n.closest(".os-taskbar__cascade");switch(t.key){case"ArrowDown":s[(i+1)%s.length]?.focus();break;case"ArrowUp":s[(i-1+s.length)%s.length]?.focus();break;case"ArrowRight":!r&&a&&(this.openCascade(a),a.querySelector('.os-taskbar__submenu [role="menuitem"]')?.focus());break;case"ArrowLeft":r&&a&&(a.classList.remove("os-taskbar__cascade--open"),a.querySelector(':scope > [role="menuitem"]')?.focus());break;case"Escape":this.closeMenu(),this.start.focus();break;default:return}t.preventDefault()}destroy(){this.closeMenu(),this.stopClock();for(const t of Dm)Ct(t,this.namespace);this.root.remove(),this.menu.remove(),this.deps.container.removeAttribute("data-os-dock-renderer"),this.deps.container.removeAttribute("data-os-dock-placement")}}const sL={id:"taskbar",label:"Taskbar",description:"A Start menu with every admin page, a button for each open window, and a tray with the clock.",icon:"dashicons-table-row-after",apiVersion:1,mount(e){return e.orientation!=="bottom"?Qi.mount(e):new oL(e).controller()}};function iL(){Oa(Qi),Oa(sL)}const xm="wp-admin-bar-os-clock";let zc=null;function rL(e){if(typeof document>"u")return;const t=document.getElementById(xm);if(!e){zc?.(),zc=null,t?.remove();return}const n=document.getElementById("wp-admin-bar-top-secondary");if(t||!n)return;const o=document.createElement("li");o.id=xm;const s=document.createElement("div");s.className="ab-item ab-empty-item";const i=document.createElement("time");s.append(i),o.append(s),n.insertBefore(o,document.getElementById("wp-admin-bar-my-account")),zc=Om(i)}const Rm="os-desktop-theme-css",aL="os-desktop-theme-inline-css",jc="data-os-desktop-theme-css",Mm="os-desktop-theme-changed";function Wm(){return document.getElementById("os-shell")}function Pm(){const e=[];for(const t of[Rm,aL]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${jc}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function Vc(){for(const e of Pm())e.remove()}function cL(e){const t=Wm();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:Pm().length>0}function $m(e){if(e.cssUrl!==""){const t=document.createElement("link");t.id=Rm,t.rel="stylesheet",t.href=e.cssUrl,t.setAttribute(jc,e.slug),document.head.appendChild(t)}else if(e.cssText!==""){const t=document.createElement("style");t.setAttribute(jc,e.slug),t.textContent=e.cssText,document.head.appendChild(t)}}function Um(e,t=!1){const n=document.body;if(!n)return;n.classList.toggle("os-toolbar-themed",e!==null&&t),rL(e!==null&&t);const o=[];n.classList.forEach(s=>{s.startsWith("os-desktop-theme-")&&o.push(s)});for(const s of o)(e===null||s!==`os-desktop-theme-${e}`)&&n.classList.remove(s);e!==null&&n.classList.add(`os-desktop-theme-${e}`)}function Kc(e){const t=jn(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:ki(o),i=s?s.slug:null;if(i===n)return;const r=Wm();if(!s)r?.removeAttribute("data-os-desktop-theme"),Um(null),Vc(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!cL(s.slug))if(s.cssDeferred&&s.cssUrl===""&&s.cssText===""){const l=s.slug,c=()=>qf().then(()=>{if(jn().state.activeId!==l)return;const d=ki(l);if(!d||d.cssDeferred)throw new Error(`theme "${l}" resolved without a stylesheet`);Vc(),$m(d)}).catch(d=>{jn().state.activeId===l&&(ue({message:b("Could not load that desktop theme — the previous one is still showing."),action:{label:b("Retry"),onClick:()=>void c()},persistent:!0,dismissible:!0}),console.warn("[openstation] desktop theme stylesheet failed to load",d))});c()}else Vc(),$m(s);r?.setAttribute("data-os-desktop-theme",s.slug),Um(s.slug,s.drawsToolbar),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};L(y.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(Mm,{detail:a}))}function lL(e={}){const t=e.deactivate??(()=>Kc(""));return function(o){lS(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=jn().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const dL="",uL="system-default",fL={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function pL(e,t,n={}){const o=t===dL,s=o?null:ki(t);if(!o&&!s)return{};const i=o?uL:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=oS(o?fL:s.recommendedOsSettings,o?void 0:s.slug),l=Object.keys(a);if(l.length===0)return{};const c=e,d={};a.navPlacement&&(e.navPlacement={...e.navPlacement,...a.navPlacement},d.navPlacement=a.navPlacement),a.widgets&&(d.widgets=a.widgets);for(const u of l){const f=a[u];typeof f!="string"&&typeof f!="number"||!(u in e)||typeof c[u]!=typeof f||(c[u]=f,d[u]=f)}return Object.keys(d).length===0?{}:(r||(e.appliedThemeRecommendations=[...e.appliedThemeRecommendations,i].slice(-64)),d)}function Bm(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}function hL(e,t){Hn({id:Df,label:b("Custom gradient"),type:"css",preview:Bm(e()),description:b("Mix your own two-colour gradient and set the angle — your desk, your palette."),resolveValue:()=>Bm(e())})}function mL(e){if(!e.customImage){Gn(Go)&&Mf(Go);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`,o=Gn(Go);o&&o.type==="css"&&o.value===n||Hn({id:Go,label:b("Custom image"),type:"css",value:n,preview:n,description:b("Any image from your media library or an upload, sized to cover the whole desk.")})}function gL(e){const t=/^#?([0-9a-f]{6})$/i.exec(e.trim());if(!t)return!1;const n=i=>{const r=parseInt(i,16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4},o=t[1];return .2126*n(o.slice(0,2))+.7152*n(o.slice(2,4))+.0722*n(o.slice(4,6))>.35}function Fm(e){return JSON.parse(JSON.stringify(e))}function wL(e,t){return e===t?!0:typeof e!="object"||typeof t!="object"||e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}class yL{constructor(t){this.applyWidgets=()=>{},this.listeners=new Set,this.baseState=null,this.overridePatch=null,this.layer=t,this.state=nC(),document.addEventListener("os-settings-save-lifecycle",n=>{const o=n.detail;!o||(window.wp?.os?.windowManager?.getById(xt)?.markActivity(o.phase,{error:o.error}),o.phase!=="failed"||!o.rolledBackTo)||(this.state=o.rolledBackTo,this.apply(),this.notify())}),hL(()=>this.state)}getOsSettingsSnapshot(){return Bt(this.state)}subscribeOsSettings(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}apply(){const t=document.getElementById("os-shell");if(!t)return;z0(this.state.wallpaperSettings),mL(this.state);const n=Gn(this.state.wallpaper)||Gn(Ha())||Gn(Ba)||ja()[0];n&&this.layer.apply(n);const o=zo(),s=o.find(g=>g.id===this.state.accent)??o[0],i=this.state.accent===Fa?this.state.customAccent:s.value,r=Ga.find(g=>g.id===this.state.dockSize)??Ga[1],a=za.find(g=>g.id===this.state.windowRadius)??za[1],l=document.body;l.style.setProperty("--wp-admin-theme-color",i),l.style.setProperty("--os-ui-accent",i);const c=gL(i)?"#0c0b0f":"#fffbff";l.style.setProperty("--os-ui-accent-ink",c);const u=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;u===null?l.style.removeProperty("--os-ui-accent-dim"):l.style.setProperty("--os-ui-accent-dim",u),t.style.setProperty("--os-ui-accent",i),t.style.setProperty("--os-ui-accent-ink",c),u===null?t.style.removeProperty("--os-ui-accent-dim"):t.style.setProperty("--os-ui-accent-dim",u),l.style.setProperty("--os-dock-width",`${r.width}px`),l.style.setProperty("--os-dock-icon-size",`${r.icon}px`),t.style.setProperty("--os-dock-width",`${r.width}px`),t.style.setProperty("--os-dock-icon-size",`${r.icon}px`),l.style.setProperty("--os-window-radius",`${a.value}px`),t.style.setProperty("--os-window-radius",`${a.value}px`);const f=_i.find(g=>g.id===this.state.adminBarMode)??_i[0];for(const g of _i)document.body.classList.toggle(`os-admin-bar-${g.id}`,g.id===f.id);const p=g=>(Ei.find(h=>h.id===g)??Ei[0]).id;document.getElementById(V0)?.setAttribute(rs,p(this.state.dockBehavior)),document.getElementById(Xh)?.setAttribute(rs,p(this.state.sideDockBehavior)),Q0(),UI(),t.setAttribute("data-os-layout",this.state.desktopLayout),gk(this.state.dockRailRenderer),Kc(this.state.desktopTheme)}setWorkspaceAppearance(t){const n=this.baseState??this.state;if(!t||Object.keys(t).length===0){if(!this.baseState)return;this.state=n,this.baseState=null,this.overridePatch=null}else this.baseState=n,this.overridePatch=Fm(t),this.state={...n,...Fm(t)};this.apply(),this.notify()}save(t={}){const n=this._persistableState();this.baseState&&(this.baseState=Bt(n)),dC(n,t),this.notify()}_persistableState(){const t=this.baseState,n=this.overridePatch;if(!t||!n)return this.state;const o={...this.state},s=n,i=t;for(const r of Object.keys(s))wL(o[r],s[r])&&(o[r]=i[r]);return o}update(t,n={}){const o={...t};delete o.appliedThemeRecommendations,delete o.adminAssetCacheEnabled,delete o.windowPrewarmEnabled;const s=Pc(o,this.state),i=om.filter(r=>r in o);Object.assign(this.state,s),this.save(n),i.some(r=>sC.has(r))&&this.apply()}applyThemeRecommendations(t){const n=pL(this.state,t,{force:!0});return Object.keys(n).length>0&&(this.save(),this.apply()),n.widgets&&this.applyWidgets(n.widgets),n}reset(t={}){const n=rm();n.wallpaper=Ha(),n.customImage=this.state.customImage,n.adminAssetCacheEnabled=this.state.adminAssetCacheEnabled,n.windowPrewarmEnabled=this.state.windowPrewarmEnabled,Object.assign(this.state,n),this.save(t),this.apply()}notify(){if(this.listeners.size===0)return;const t=this.getOsSettingsSnapshot();for(const n of Array.from(this.listeners))try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] os-settings listener threw:",o)}}}const bL="os-network-admin";function vL(e,t){const n=e.networkAdmin;return!n||e.isNetworkAdmin?null:{id:bL,title:b("Network Admin"),icon:"dashicons-admin-multisite",placeable:!0,navKind:"core",onOpen:o=>t(n.url,o),get submenu(){return n.rows.map(({title:o,url:s})=>({title:o,url:s,onSelect:i=>t(s,i)}))}}}function Hm(e){return!!e&&(e.metaKey||e.ctrlKey||e.shiftKey||e.button===1)}function qc(e,t){if(Hm(t)){window.open(e,"_blank","noopener,noreferrer");return}window.location.assign(e)}function _L(e){return async(t,n)=>{try{const o=await Ae(e.hopUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({target:t,direction:n})},{source:"desktop-mode/network-hop"});if(!o.ok)return null;const s=await o.json();return typeof s.url=="string"&&s.url!==""?s.url:null}catch{return null}}}const EL=220,kL=360,SL=4e3,Yc="openstation-hop-direction",Xc="os-shell--arriving",Gm="os-shell--revealing";function Zc(){return document.getElementById("os-shell")}function zm(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function IL(e){try{window.sessionStorage.setItem(Yc,e)}catch{}const t=Zc();return!t||zm()?Promise.resolve():(t.classList.add(`os-shell--hop-out-${e}`),new Promise(n=>{window.setTimeout(n,EL)}))}function AL(){try{const e=window.sessionStorage.getItem(Yc);return window.sessionStorage.removeItem(Yc),e==="next"||e==="prev"?e:null}catch{return null}}function CL(e=null){const t=Zc();if(!t||!t.classList.contains(Xc))return;const n=AL()??e;n&&t.classList.add(`os-shell--arriving-${n}`),window.setTimeout(jm,SL)}function jm(){const e=Zc();!e||!e.classList.contains(Xc)||(e.classList.remove(Xc,"os-shell--arriving-next","os-shell--arriving-prev"),!zm()&&(e.classList.add(Gm),window.setTimeout(()=>e.classList.remove(Gm),kL)))}function no(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function LL(e){return!!e&&e.__wpdHtml===!0}const TL="$$wpd$$",Pe=/\$\$wpd\$\$(\d+)\$\$/g,NL="$$wpd-node$$",OL=/^\$\$wpd-node\$\$(\d+)\$\$$/,DL=new Set(["style","script","textarea","title"]);function xL(e){let t="",n=!1,o=null,s=!1,i=null,r="",a=!1;for(let l=0;l<e.length;l++){const c=e[l];t+=c;for(let d=0;d<c.length;d++){const u=c[d];if(s){c.startsWith("-->",d)&&(s=!1,d+=2);continue}if(i!==null){u==="<"&&c[d+1]==="/"&&c.slice(d+2,d+2+i.length).toLowerCase()===i&&(d+=1+i.length,i=null,n=!0,a=!1,r="");continue}if(o!==null){u===o&&(o=null);continue}if(n){u==='"'||u==="'"?(o=u,a=!1):u===">"?(n=!1,a=!1,DL.has(r)&&(i=r),r=""):a&&(/[a-zA-Z0-9-]/.test(u)?r+=u.toLowerCase():a=!1);continue}if(c.startsWith("<!--",d)){s=!0,d+=3;continue}const f=c[d+1]??"";u==="<"&&/[a-zA-Z/!]/.test(f)&&(n=!0,r="",a=/[a-zA-Z]/.test(f))}l<e.length-1&&(t+=n||s||i!==null?`${TL}${l}$$`:`<!--${NL}${l}$$-->`)}return t}const Vm=new WeakMap;function Km(e){const t=Vm.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=xL(e);const o=[],s=(a,l)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const f of Array.from(u.attributes)){const p=f.name,g=f.value,h=p[0];if(Pe.test(g))if(Pe.lastIndex=0,h==="@"){const m=Pe.exec(g);Pe.lastIndex=0,o.push({path:l,kind:"event",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else if(h==="."){const m=Pe.exec(g);Pe.lastIndex=0,o.push({path:l,kind:"prop",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else if(h==="?"){const m=Pe.exec(g);Pe.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else{const m=[],E=[];let k=0,N;for(Pe.lastIndex=0;(N=Pe.exec(g))!==null;)m.push(g.slice(k,N.index)),E.push(Number(N[1])),k=N.index+N[0].length;m.push(g.slice(k)),o.push({path:l,kind:"attr",name:p,template:m,valueIndices:E}),u.setAttribute(p,"")}}}const c=Array.from(a.childNodes);let d=0;for(let u=0;u<c.length;u++){const f=c[u],p=u+d;if(f.nodeType===Node.COMMENT_NODE){const g=OL.exec(f.data);if(g){const h=document.createTextNode("");f.parentNode.replaceChild(h,f),o.push({path:[...l,p],kind:"node",valueIndex:Number(g[1])})}continue}if(f.nodeType===Node.TEXT_NODE){const g=f.textContent||"";if(!Pe.test(g)){Pe.lastIndex=0;continue}Pe.lastIndex=0;const h=f.parentNode;let m=0,E;const k=[],N=[];for(Pe.lastIndex=0;(E=Pe.exec(g))!==null;){E.index>m&&k.push(document.createTextNode(g.slice(m,E.index)));const M=document.createTextNode("");k.push(M),N.push({path:[...l,p+k.length-1],kind:"node",valueIndex:Number(E[1])}),m=E.index+E[0].length}m<g.length&&k.push(document.createTextNode(g.slice(m)));for(const M of k)h.insertBefore(M,f);h.removeChild(f),d+=k.length-1,o.push(...N)}else s(f,[...l,p])}};s(n.content,[]);const r={template:n,buildParts:a=>{const l=[];for(const c of o){let d=a;for(const u of c.path)d=d.childNodes[u];c.kind==="node"?l.push({kind:"node",valueIndex:c.valueIndex,child:{anchor:d,state:null}}):c.kind==="attr"?l.push({kind:"attr",element:d,name:c.name,template:c.template,valueIndices:c.valueIndices}):c.kind==="event"?l.push({kind:"event",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="prop"?l.push({kind:"prop",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="bool"&&l.push({kind:"bool",valueIndex:c.valueIndex,element:d,name:c.name})}return l}};return Vm.set(e,r),r}const qm=new WeakMap;function RL(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function ML(e,t){const n=qm.get(t);if(n&&n.strings===e.strings&&RL(n,t)){nr(n.parts,e.values);return}const o=Km(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),nr(i,e.values),qm.set(t,{strings:e.strings,parts:i,nodes:r})}function nr(e,t){for(const n of e)if(n.kind==="node")or(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+=Ym(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 or(e,t){if(t==null||t===!1){e.state&&(Gt(e.state),e.state=null);return}if(Array.isArray(t)){UL(e,t);return}if(LL(t)){$L(e,t);return}if(t instanceof Node){WL(e,t);return}PL(e,Ym(t))}function WL(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Gt(n),as(e,[t]),e.state={shape:"node",node:t})}function PL(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Gt(n);const o=document.createTextNode(t);as(e,[o]),e.state={shape:"text",node:o,text:t}}function $L(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){nr(n.parts,t.values);return}n&&Gt(n);const o=Km(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);as(e,[s]),nr(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function UL(e,t){const n=e.state;if(n?.shape==="array"){const s=Math.min(n.entries.length,t.length);for(let i=0;i<s;i++)or(n.entries[i],t[i]);if(t.length<n.entries.length){for(let i=t.length;i<n.entries.length;i++){const r=n.entries[i];r.state&&Gt(r.state),r.anchor.remove()}n.entries.length=t.length}else for(let i=n.entries.length;i<t.length;i++){const r=document.createTextNode("");as(e,[r]);const a={anchor:r,state:null};or(a,t[i]),n.entries.push(a)}return}n&&Gt(n);const o=[];for(const s of t){const i=document.createTextNode("");as(e,[i]);const r={anchor:i,state:null};or(r,s),o.push(r)}e.state={shape:"array",entries:o}}function as(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Gt(e){if(e.shape==="text"){e.node.remove();return}if(e.shape==="template"){for(const t of e.parts)t.kind==="node"&&t.child.state&&(Gt(t.child.state),t.child.state=null);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&&Gt(t.state),t.anchor.remove()}function Ym(e){return e==null||e===!1?"":String(e)}const Zt=class Zt 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(Xm)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=BL(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=Xm(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&&ML(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(!Zt._lightStylesAdopted.has(t)){Zt._lightStylesAdopted.add(t);for(const n of t.styles){const o=document.createElement("style");o.dataset.osUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};Zt.props=[],Zt.styles=[],Zt.shadow=!0,Zt._lightStylesAdopted=new WeakSet;let dn=Zt;function cs(e,t){customElements.get(e)||customElements.define(e,t)}function Xm(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function BL(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const FL=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function Ne(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("[os-ui] css`` interpolations must be strings, numbers, or other css`` results. Got: "+typeof s);n+=e[o]}if(FL){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}const Jc=Ne`:host{--_holo-fill:var( --os-ui-holo-fill,${"linear-gradient( 124deg, #afa2e8 0%, #f5a8ea 46%, #8ee9f7 100% )"} );--_holo-ink:var( --os-ui-holo-ink,#0c0b0f );--_holo-sheen:var( --os-ui-holo-sheen,linear-gradient( 124deg,rgba( 159,214,255,0.1 ) 0%,rgba( 236,155,255,0.12 ) 34%,rgba( 242,82,252,0.1 ) 58%,rgba( 147,240,198,0.09 ) 100% ) );--_holo-edge:var( --os-ui-holo-edge,linear-gradient( 124deg,rgba( 154,242,255,0.7 ) 0%,rgba( 236,155,255,0.85 ) 38%,rgba( 242,82,252,0.7 ) 62%,rgba( 159,152,255,0.6 ) 100% ) );--_holo-edge-quiet:var( --os-ui-holo-edge-quiet,linear-gradient( 124deg,rgba( 154,242,255,0.22 ) 0%,rgba( 236,155,255,0.28 ) 38%,rgba( 242,82,252,0.22 ) 62%,rgba( 159,152,255,0.2 ) 100% ) );--_holo-glow:var( --os-ui-holo-glow,0 0 0 1px rgba( 242,82,252,0.28 ),0 2px 10px rgba( 242,82,252,0.22 ) );--_holo-glow-strong:var( --os-ui-holo-glow-strong,0 0 0 1px rgba( 242,82,252,0.42 ),0 4px 18px rgba( 242,82,252,0.38 ),0 1px 3px rgba( 12,11,15,0.6 ) );--_holo-track:var( --os-ui-holo-track,rgba( 255,251,255,0.16 ) );--_holo-track-edge:var( --os-ui-holo-track-edge,#8c8f94 );--_holo-ring-color:var( --os-ui-accent-dim,#2271b1 );--_holo-focus:var( --os-ui-focus-ring,0 0 0 2px rgba( 12,11,15,0.9 ),0 0 0 4px #f252fc,0 0 12px 2px rgba( 242,82,252,0.45 ) );--_holo-focus-field:var( --os-ui-focus-ring-field,0 0 0 1px #f252fc,0 0 0 4px rgba( 242,82,252,0.18 ) );--_holo-t:var( --os-ui-holo-transition,220ms );--_holo-t-fast:var( --os-ui-motion-fast,140ms );--_holo-t-slow:var( --os-ui-motion-slow,340ms );--_holo-t-ambient:var( --os-ui-motion-ambient,12s );--_holo-spring:var( --os-ui-ease-spring,cubic-bezier( 0.32,1.5,0.55,1 ) );--_holo-ease:var( --os-ui-ease-out,cubic-bezier( 0.22,0.9,0.28,1 ) );--_holo-loop:var( --os-ui-ease-loop,cubic-bezier( 0.45,0,0.55,1 ) )}`,HL=Ne` .os-holo-fill{background-color:transparent;background-image:var( --_holo-fill );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;color:var( --_holo-ink );transition:background-position var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,filter var( --_holo-t ) ease}.os-holo-fill:hover{background-position:74% 66%}.os-holo-fill:active{background-position:88% 82%;filter:brightness( 0.94 )}@media ( prefers-reduced-motion:reduce ){.os-holo-fill{transition-duration:1ms}.os-holo-fill:hover,.os-holo-fill:active{background-position:22% 28%}}`,Zm=Ne` .os-holo-sheen{position:relative;isolation:isolate}.os-holo-sheen::before{content:'';position:absolute;inset:0;z-index:-1;border-radius:inherit;background-image:var( --_holo-sheen );background-size:200% 200%;background-position:20% 30%;opacity:0;pointer-events:none;transition:opacity var( --_holo-t ) ease,background-position var( --_holo-t ) ease}.os-holo-sheen:hover::before,.os-holo-sheen:focus-visible::before{opacity:1;background-position:76% 68%}@media ( prefers-reduced-motion:reduce ){.os-holo-sheen::before{transition-duration:1ms}.os-holo-sheen:hover::before,.os-holo-sheen:focus-visible::before{background-position:20% 30%}}`,GL=Ne` .os-holo-edge{position:relative}.os-holo-edge::after{content:'';position:absolute;inset:0;border-radius:inherit;padding:1px;background-image:var( --_holo-edge-quiet );opacity:0;pointer-events:none;-webkit-mask:linear-gradient( #000 0 0 ) content-box,linear-gradient( #000 0 0 );-webkit-mask-composite:xor;mask:linear-gradient( #000 0 0 ) content-box,linear-gradient( #000 0 0 );mask-composite:exclude;transition:opacity var( --_holo-t ) ease}.os-holo-edge:hover::after,.os-holo-edge:focus-visible::after{background-image:var( --_holo-edge );opacity:1}.os-holo-edge.is-lit::after{background-image:var( --_holo-edge );opacity:1}@media ( prefers-reduced-motion:reduce ){.os-holo-edge::after{transition-duration:1ms}}`,zL=Ne` .os-holo-glint{position:absolute;inset:0;border-radius:inherit;overflow:hidden;pointer-events:none}.os-holo-glint::before{content:'';position:absolute;top:-60%;bottom:-60%;width:45%;inset-inline-start:-60%;background:linear-gradient( 90deg,transparent 0%,rgba( 255,251,255,0.14 ) 45%,rgba( 255,251,255,0.22 ) 50%,rgba( 255,251,255,0.14 ) 55%,transparent 100% );transform:rotate( 18deg ) translateX( 0 );opacity:0}:hover>.os-holo-glint::before,:focus-visible>.os-holo-glint::before,:host(:hover )>.os-holo-glint::before,:host(:focus-visible )>.os-holo-glint::before{animation:os-holo-glint var( --_holo-t-slow ) var( --_holo-ease )}@keyframes os-holo-glint{0%{opacity:0;transform:rotate( 18deg ) translateX( 0 )}15%{opacity:1}85%{opacity:1}100%{opacity:0;transform:rotate( 18deg ) translateX( 240vw )}}@media ( prefers-reduced-motion:reduce ){:hover>.os-holo-glint::before,:focus-visible>.os-holo-glint::before,:host(:hover )>.os-holo-glint::before,:host(:focus-visible )>.os-holo-glint::before{animation:none}}`,jL=Ne` .os-holo-ring{position:absolute;inset:0;border-radius:inherit;box-shadow:0 0 0 0 var( --_holo-ring-color );opacity:0;pointer-events:none}:active:not(:disabled )>.os-holo-ring,:host(:active:not( [ disabled ] ) )>.os-holo-ring{animation:os-holo-ring var( --_holo-t-slow ) var( --_holo-ease )}@keyframes os-holo-ring{0%{opacity:0.45;box-shadow:0 0 0 0 var( --_holo-ring-color )}100%{opacity:0;box-shadow:0 0 0 10px transparent}}@media ( prefers-reduced-motion:reduce ){:active:not(:disabled )>.os-holo-ring,:host(:active:not( [ disabled ] ) )>.os-holo-ring{animation:none}}`,VL=Ne` .os-holo-shimmer{background-image:var( --_holo-fill );background-size:300% 300%;background-repeat:no-repeat;animation:os-holo-shimmer 2.4s var( --_holo-loop ) infinite}@keyframes os-holo-shimmer{0%{background-position:0% 50%}100%{background-position:100% 50%}}@media ( prefers-reduced-motion:reduce ){.os-holo-shimmer{animation:none;background-position:30% 50%}}`,KL=Ne` .os-holo-enter{animation:os-holo-enter var( --_holo-t ) var( --_holo-spring )}@keyframes os-holo-enter{from{opacity:0;transform:scale( 0.96 )}}@media ( prefers-reduced-motion:reduce ){.os-holo-enter{animation:none}}`,qL=Ne` input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ),select,textarea{transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):hover:not(:disabled ),select:hover:not(:disabled ),textarea:hover:not(:disabled ){border-color:var( --os-ui-border-strong,#8c8f94 )}input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):focus,input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):focus-visible,select:focus,select:focus-visible,textarea:focus,textarea:focus-visible{outline:none;border-color:var( --os-ui-accent,#2271b1 );box-shadow:var( --_holo-focus-field )}input::placeholder,textarea::placeholder{color:var( --os-ui-fg-faint,#8c8f94 );opacity:1}input::selection,textarea::selection{background:var( --os-ui-selection-bg,rgba( 159,152,255,0.6 ) );color:var( --os-ui-selection-fg,#fffbff )}@media ( prefers-reduced-motion:reduce ){input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ),select,textarea{transition-duration:1ms}}`,YL=Ne` input[ type='checkbox' ],input[ type='radio' ]{appearance:none;-webkit-appearance:none;position:relative;flex:0 0 auto;box-sizing:border-box;width:16px;height:16px;margin:0;padding:0;border:1px solid var( --_holo-track-edge );border-radius:4px;background-color:var( --_holo-track );background-image:none;background-repeat:no-repeat;cursor:inherit;transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input[ type='radio' ]{border-radius:50%}input[ type='checkbox' ]:hover:not(:disabled ),input[ type='radio' ]:hover:not(:disabled ){border-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:focus-visible,input[ type='radio' ]:focus-visible{outline:none;box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked,input[ type='checkbox' ]:indeterminate,input[ type='radio' ]:checked{border-color:transparent;background-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:checked:focus-visible,input[ type='radio' ]:checked:focus-visible{box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:46%;width:3.5px;height:7.5px;border:solid var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );border-width:0 2px 2px 0;transform:translate( -50%,-50% ) rotate( 45deg );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:indeterminate::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:8px;height:2px;border:0;border-radius:1px;background:var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );transform:translate( -50%,-50% )}input[ type='radio' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:6px;height:6px;border-radius:50%;background:var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );transform:translate( -50%,-50% );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:disabled,input[ type='radio' ]:disabled{cursor:not-allowed}@keyframes os-holo-tick{from{opacity:0;transform:translate( -50%,-50% ) rotate( 45deg ) scale( 0.4 )}}@media ( prefers-reduced-motion:reduce ){input[ type='checkbox' ]:checked::after,input[ type='radio' ]:checked::after{animation:none}}`,XL=Ne` @keyframes os-holo-drift{0%{background-position:16% 26%}50%{background-position:84% 74%}100%{background-position:16% 26%}}.os-holo-alive{animation:os-holo-drift var( --_holo-t-ambient ) var( --_holo-loop ) infinite}@media ( prefers-reduced-motion:reduce ){.os-holo-alive{animation:none}}`;Ne` ${Jc} ${HL} ${Zm} ${GL} ${zL} ${jL} ${VL} ${KL} ${qL} ${YL} ${XL} `;const ZL=Ne` ${Jc}:host{display:inline-flex;position:relative;padding:3px;background:var( --os-ui-segmented-bg,var( --os-ui-hover,rgba( 0,0,0,0.05 ) ) );border-radius:8px;gap:2px;box-shadow:var( --os-ui-segmented-edge,none )}.os-segmented__thumb{position:absolute;top:3px;bottom:3px;left:0;width:var( --_thumb-w,0px );border-radius:6px;background-color:var( --os-ui-segmented-selected-bg,color-mix( in srgb,var( --os-ui-accent,#2271b1 ) var( --os-ui-segmented-selected-accent,100% ),var( --os-ui-segmented-selected-base,var( --os-ui-surface,#fff ) ) ) );background-image:var( --os-ui-segmented-selected-image,none );box-shadow:var( --os-ui-segmented-selected-shadow,none );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;transform:translateX( var( --_thumb-x,0px ) );pointer-events:none;opacity:0}:host( [ data-thumb ] ) .os-segmented__thumb{opacity:1}:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition:transform var( --_holo-t-slow ) var( --_holo-spring ),width var( --_holo-t-slow ) var( --_holo-ease ),opacity var( --_holo-t-fast ) linear}@media ( prefers-reduced-motion:reduce ){:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition-duration:1ms}}`,JL=Ne` ${Jc} ${Zm}:host{flex:1 1 auto;min-width:0;--_holo-sheen:var( --os-ui-segmented-hover-sheen,var( --os-ui-holo-sheen,linear-gradient( 124deg,rgba( 159,214,255,0.1 ) 0%,rgba( 236,155,255,0.12 ) 34%,rgba( 242,82,252,0.1 ) 58%,rgba( 147,240,198,0.09 ) 100% ) ) )}button{appearance:none;display:block;width:100%;padding:6px 13px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --os-ui-fg-muted,#646970 );cursor:pointer;border-radius:6px;transition:background-color var( --_holo-t ) ease,color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,background-position var( --_holo-t ) ease;white-space:nowrap}button:hover{color:var( --os-ui-fg,#1d2327 )}:host(:not( [ aria-checked='true' ] ) ) button:hover{background-color:var( --os-ui-segmented-hover-bg,transparent )}button:focus-visible{outline:none;box-shadow:var( --_holo-focus )}:host( [ aria-checked='true' ] ) button{color:var( --os-ui-segmented-selected-fg,color-mix( in srgb,var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) ) var( --os-ui-segmented-selected-accent,100% ),var( --os-ui-fg,#1d2327 ) ) );transition-duration:var( --_holo-t-fast )}:host( [ aria-checked='true' ] ) button::before{display:none}`,ci=class ci extends dn{render(){return this.setAttribute("role","radio"),no`
6 <button
7 type="button"
8 class="os-holo-sheen"
9 @click=${()=>this._onPick()}
10 >
11 <slot></slot>
12 </button>
13 `}_onPick(){this.emit("os-segment-pick",{value:this.value})}};ci.props=["value"],ci.styles=[JL],ci.help=void 0;let Qc=ci;cs("os-segment",Qc);const li=class li extends dn{constructor(){super(...arguments),this._resizeObserver=null}connectedCallback(){super.connectedCallback(),this.addEventListener("os-segment-pick",t=>{const n=t.detail;t.stopPropagation(),this.value=n.value,this.emit("os-pick",{value:n.value})}),typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._placeThumb()),this._resizeObserver.observe(this))}disconnectedCallback(){this._resizeObserver?.disconnect(),this._resizeObserver=null}_placeThumb(){if(!this.shadowRoot?.querySelector(".os-segmented__thumb"))return;const n=this.value,o=Array.from(this.querySelectorAll(":scope > os-segment")).find(c=>c.getAttribute("value")===n);if(!o||this.offsetWidth===0){this.removeAttribute("data-thumb");return}const s=this.getBoundingClientRect(),i=s.width/this.offsetWidth,r=Math.abs(i-1)<.02?1:i;if(!(r>0))return;const a=o.getBoundingClientRect(),l=c=>`${Math.round(c*100)/100}px`;this.style.setProperty("--_thumb-x",l((a.left-s.left)/r)),this.style.setProperty("--_thumb-w",l(a.width/r)),this.setAttribute("data-thumb",""),this.hasAttribute("data-thumb-ready")||requestAnimationFrame(()=>this.setAttribute("data-thumb-ready",""))}set items(t){const n=this.querySelectorAll(":scope > os-segment");for(const i of Array.from(n))i.remove();for(const i of t){const r=document.createElement("os-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("os-segment");for(const s of Array.from(o)){const i=s.getAttribute("value");s.setAttribute("aria-checked",i===n?"true":"false")}this._placeThumb()}),no`<span class="os-segmented__thumb" aria-hidden="true"></span
14 ><slot></slot>`}};li.props=["value","label"],li.styles=[ZL],li.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <os-segment> children where exactly one is active.",status:"stable",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:'<os-segment value="…"> children.'}],events:[{name:"os-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--os-window-bg",description:"Pill background."},{name:"--os-ui-fg",description:"Active label colour."},{name:"--os-ui-fg-muted",description:"Inactive label colour."}],example:no`
15 <os-segmented value="md" label="Dock size">
16 <os-segment value="sm">Small</os-segment>
17 <os-segment value="md">Medium</os-segment>
18 <os-segment value="lg">Large</os-segment>
19 </os-segmented>
20 `};let el=li;cs("os-segmented",el);const QL="openstation_overview",eT="openstation_hop_from";function Jm(e,t){try{const n=new URL(e,window.location.href);return n.searchParams.set(QL,"1"),t&&n.origin!==window.location.origin&&n.searchParams.set(eT,t),n.toString()}catch{return e}}function tl(e){const t=[];e.networkAdmin?.shellUrl&&t.push({value:"network",label:b("Network Admin"),shellUrl:e.networkAdmin.shellUrl,external:!1,foreign:e.networkAdmin.foreign===!0});for(const n of e.sites??[])t.push({value:n.id,label:n.name,shellUrl:n.shellUrl,external:n.kind==="member",foreign:n.foreign===!0,tabUrl:n.active===!1?n.adminUrl:void 0});return t}function nl(e,t,n={}){const o=n.hop??qc,s=tl(e),i=e.current??"",r=s.findIndex(f=>f.value===t);if(r<0||t===i)return!1;const a=s[r];if(a.tabUrl)return window.open(a.tabUrl,"_blank","noopener"),!0;const l=s.findIndex(f=>f.value===i),c=r>l?"next":"prev",d=Jm(a.shellUrl,c),u=n.mint&&a.foreign?n.mint(a.shellUrl,c).catch(()=>null):Promise.resolve(null);return Promise.all([IL(c),u]).then(([,f])=>o(f??d)),!0}function tT(e){const t=n=>{if(n.key!=="Tab"||n.ctrlKey||n.metaKey||n.altKey||n.defaultPrevented)return;const o=e.multisite();if(!o||!e.isShown()||Cc(document))return;const i=(n.target?.ownerDocument??document).activeElement;if(i&&i.closest(".os-overview-top-bar")&&!i.closest(".os-site-switcher"))return;const r=o.current??"",a=tl(o).filter(u=>!u.tabUrl||u.value===r);if(a.length<2)return;const l=a.findIndex(u=>u.value===r),c=n.shiftKey?-1:1,d=a[(l+c+a.length)%a.length];n.preventDefault(),nl(o,d.value,e)};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)}function Qm(){const e=document.createElement("span");return e.className="dashicons dashicons-external os-site-switcher__mark",e.setAttribute("aria-hidden","true"),e}function nT(e,t={}){const n=t.hop??qc,o=tl(e);if(o.length<2)return null;const s=e.current??"",i=new Map(o.map(c=>[c.value,c])),r=document.createElement("os-segmented");r.className="os-site-switcher",r.setAttribute("label",b("Site")),r.setAttribute("value",s);let a=!1;for(const c of o){if(c.external&&!a){a=!0;const u=document.createElement("span");u.className="os-site-switcher__divider",u.setAttribute("role","separator"),u.setAttribute("aria-orientation","vertical"),r.appendChild(u)}const d=document.createElement("os-segment");if(d.setAttribute("value",c.value),c.external){d.setAttribute("data-external",""),d.title=b("External site"),d.appendChild(Qm());const u=document.createElement("span");u.className="screen-reader-text",u.textContent=b("External site:")+" ",d.appendChild(u)}else if(c.tabUrl){d.setAttribute("data-opens-tab",""),d.title=b("OpenStation is not active on this site. Opens its admin in a new tab."),d.appendChild(Qm());const u=document.createElement("span");u.className="screen-reader-text",u.textContent=b("Opens in a new tab:")+" ",d.appendChild(u)}d.appendChild(document.createTextNode(c.label)),r.appendChild(d)}const l=c=>{const d=c.target?.closest("os-segment"),u=d?i.get(d.getAttribute("value")??""):void 0;if(!u)return;if(u.tabUrl&&(c.type==="click"||c.button===1)){c.preventDefault(),c.stopPropagation(),window.open(u.tabUrl,"_blank","noopener");return}if(!Hm(c))return;c.preventDefault(),c.stopPropagation();const f=Jm(u.shellUrl);if(!t.mint||!u.foreign){n(f,c);return}const p=window.open("","_blank");t.mint(u.shellUrl,"next").catch(()=>null).then(g=>{p?p.location.href=g??f:n(f,c)})};return r.addEventListener("click",l,!0),r.addEventListener("auxclick",l,!0),r.addEventListener("os-pick",c=>{const d=c.detail?.value;d&&nl(e,d,t)}),r}function oT(e){return(t,n)=>Ae(t,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e},body:JSON.stringify({accept:n})},{source:"desktop-mode/network"})}async function sT(e,t){const n=e.email?`${e.name} (${e.email})`:e.name,o=await t.confirm({title:b("Arrive logged in next time?"),message:b("%1$s just switched here from %2$s while you were logged in. Link that account to yours, and a switch from there logs you in as you. You can undo this in the Network window.").replace("%1$s",n).replace("%2$s",e.site),confirmLabel:b("Link accounts")});try{await t.post(e.url,o)}catch{}return o}const sr=new Map;function eg(e){if(!e||typeof e.id!="string"||e.id===""){typeof console<"u"&&console.warn("[openstation] Ignored invalid module registration:",e);return}if(typeof e.url!="string"||e.url===""){typeof console<"u"&&console.warn(`[openstation] Module "${e.id}" has no url; ignored.`);return}sr.set(e.id,e)}function iT(){return Array.from(sr.keys())}async function ol(e){if(!e||e.length===0)return;const t=e.filter(n=>!sr.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${iT().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=sr.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():pe(o.url)}))}const rT="os-wallpaper-light",aT=.185,oo=32,cT=3e3,lT=new Set([Go,Df]),tg=new Map;function ng(e,t,n){const o=s=>{const i=s/255;return i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4)};return .2126*o(e)+.7152*o(t)+.0722*o(n)}function og(e){return e>aT?"light":"dark"}function dT(e){const t=[],n=/#([0-9a-f]{3}|[0-9a-f]{6})\b/gi;let o=n.exec(e);for(;o!==null;){const i=o[1],r=i.length===3?i.split("").map(a=>a+a).join(""):i;t.push([parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]),o=n.exec(e)}const s=/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/gi;for(o=s.exec(e);o!==null;)t.push([Number(o[1]),Number(o[2]),Number(o[3])]),o=s.exec(e);return t}function uT(e){const t=/url\(\s*(['"]?)([^'")]+)\1\s*\)/i.exec(e);return t?t[2].trim():null}function fT(e){const t=dT(e);if(t.length===0)return null;const n=t.reduce((o,[s,i,r])=>o+ng(s,i,r),0);return og(n/t.length)}async function pT(e){const t=tg.get(e);if(t)return t;try{const n=new Image;if(n.crossOrigin="anonymous",!await new Promise(d=>{const u=setTimeout(()=>d(!1),cT),f=p=>()=>{clearTimeout(u),d(p)};n.onload=f(!0),n.onerror=f(!1),n.src=e}))return null;const s=document.createElement("canvas");s.width=oo,s.height=oo;const i=s.getContext("2d");if(!i)return null;i.drawImage(n,0,0,oo,oo);const{data:r}=i.getImageData(0,0,oo,oo);let a=0,l=0;for(let d=0;d<r.length;d+=4)r[d+3]!==0&&(a+=ng(r[d],r[d+1],r[d+2]),l++);if(l===0)return null;const c=og(a/l);return tg.set(e,c),c}catch{return null}}async function hT(e){if(e.tone==="light"||e.tone==="dark")return e.tone;if(e.type!=="css"||!lT.has(e.id))return"dark";let t="";try{t=e.resolveValue?"":e.value??""}catch{t=""}if(t===""&&(t=mT()),t==="")return"dark";const n=uT(t);return n!==null?await pT(n)??"dark":fT(t)??"dark"}function mT(){if(typeof document>"u")return"";const t=document.getElementById("os-shell")??document.body;return t?t.style.getPropertyValue("--os-bg").trim():""}function gT(e){typeof document>"u"||!document.body||document.body.classList.toggle(rT,e==="light")}function sg(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:wT(),visible:!document.hidden,settings:G0(e)}}function wT(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class ig{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),this.applyTone(t,n);return}this.applyCanvas(t,n),this.applyTone(t,n)}applyTone(t,n){hT(t).then(o=>{n===this.generation&&gT(o)})}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,L(y.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){L(y.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(t){const n=t.resolveValue?t.resolveValue(sg(t.id,this.pluginUrl)):t.value;typeof n=="string"&&(this.element.style.setProperty("--os-bg",n),document.getElementById("os-shell")?.style.setProperty("--os-bg",n))}applyCanvas(t,n){const o=sg(t.id,this.pluginUrl);L(y.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?ol(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},L(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(yT(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&&L(y.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){L(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="os-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="",L(y.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),L(y.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function yT(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const rg=se("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),so=rg.state.seed,sl=rg.state.listeners;function il(e){Me("Game",tn(e,dg),e);const t=so.findIndex(n=>n.id===e.id);t>=0?so[t]=e:so.push(e),cg()}function ag(e){const t=so.findIndex(n=>n.id===e);t>=0&&(so.splice(t,1),cg())}function bT(e){return sl.add(e),()=>{sl.delete(e)}}function cg(){const e=Array.from(sl);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function lg(){const e=so.slice(),t=Q(y.GAMES,e);return Array.isArray(t)?t.filter(vT):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function ir(e){return lg().find(t=>t.id===e)}const dg=[{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 vT(e){return tn(e,dg).length===0}const ug=new Set;function rr(e){if(ug.has(e))return;const n=window.openStationConfig?.deferredStyles?.[e];if(!n?.url)return;ug.add(e);const o=n.url.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${o}"]`)){const i=document.createElement("link");i.rel="stylesheet",i.href=n.url,i.dataset.osStyleHandle=e,document.head.appendChild(i)}for(const i of n.inline??[]){if(typeof i!="string"||i==="")continue;const r=document.createElement("style");r.dataset.osStyleHandle=e,r.textContent=i,document.head.appendChild(r)}}const _T="desktop-mode/games";function ET(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function ls(e,t={},n={}){const{restUrl:o,restNonce:s}=ET(),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 Ae(nt(o,e),{...t,headers:i,credentials:"same-origin"},{source:_T,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok)throw bt(r.status,a);return a}function kT(e,t,n={}){return ls(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function ST(){return ls("desktop-mode/v1/games/playtime")}function IT(e,t,n={}){return ls(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function AT(e){return ls(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function CT(e,t,n={}){return ls(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const LT=6e4;function TT(e,t={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const l=Date.now();o+=Math.max(0,l-n),n=l},r=()=>{i();const l=Math.floor(o/1e3);l<1||(o-=l*1e3,IT(e,l,{windowId:t.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,LT);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const io=se("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function NT(){return io.state}function rl(e){const t=io.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&&DT()}function OT(e){return io.state.listeners.add(e),()=>{io.state.listeners.delete(e)}}function DT(){for(const e of Array.from(io.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function xT(){return Array.from(io.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function fg(){return window.wp?.os??{}}const RT=760,MT=560,WT=480,PT=380;function $T(){const e=window.openStationConfig?.gameStyleHandles??[];for(const t of e)rr(t)}async function UT(e){if(typeof e.render=="function")return e;const t=fg().loadVendorScript;if(!e.scriptUrl||typeof t!="function")throw new Error(`[openstation] Game "${e.id}" has no render callback and no loadable script.`);await t(e.scriptUrl,{translations:e.scriptTranslations,deps:e.scriptDeps,l10n:e.scriptL10n,before:e.scriptBefore,after:e.scriptAfter});const o=window.openStationGames?.[e.id];if(!o||typeof o.render!="function")throw new Error(`[openstation] No game def on window.openStationGames["${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 il(s),s}async function pg(e,t={}){const n=fg(),o=ir(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);if($T(),typeof n.registerWindow!="function")throw new Error("[openstation] wp.os.registerWindow is missing — the shell must boot before launching games.");const s=`os-game-${e}`,i=`game:${s}`,r=n.windowManager,a=r?.getByBaseId?.(s)??r?.getById(s);if(a){const g=a.config?.desktopId;g&&r?.switchDesktop&&g!==r?.getActiveDesktopId?.()&&r.switchDesktop(g),n.registerWindow({id:s,title:o.title,icon:o.icon,render:()=>{}});return}n.wallpaper?.suspend(i);let l=!1;const c=()=>{l||(l=!0,n.wallpaper?.resume(i))};let d=null;const u=()=>{d?.stop(),d=null};n.onWindow?.(s,{closed:()=>{u(),c()},minimized:()=>d?.pause(),restored:()=>d?.resume()});const f=(g,h)=>{n.activity?.publish("os/game-score-recorded",{game:e,score:g.score,meta:g.meta??{},windowId:s,challengeId:h})},p=g=>{if(t.challenge){const h=t.challenge.id;return CT(h,g,{windowId:s}).then(({challenge:m})=>{rl([m]),f(g,h)})}return kT(e,g,{windowId:s}).then(()=>f(g))};try{await n.registerWindow({id:s,title:o.title,icon:o.icon,width:o.window?.width??RT,height:o.window?.height??MT,minWidth:o.window?.minWidth??WT,minHeight:o.window?.minHeight??PT,render:async g=>{const h=await UT(o),m=h.render;if(typeof m!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);const E={windowId:s,container:g,config:h.config??{},challenge:t.challenge,submitScore:p,close:()=>{n.windowManager?.getById(s)?.close()}};d=TT(e,{windowId:s});const k=m(E);return()=>{try{k?.()}finally{u(),c()}}}})}catch(g){throw u(),c(),g}}const hg={register:il,unregister:ag,list:lg,get:ir,subscribe:bT,launch:pg,getPlaytime:()=>ST().then(e=>e.playtime)},ro=se("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function BT(e){ro.state.pending.set(e.id,e)}function ar(e){ro.state.pending.delete(e)}function FT(e){return(window.openStationWallpapers||{})[e]??null}function mg(e){const t=ro.state.inflight.get(e);if(t)return t;const n=ro.state.pending.get(e);if(!n)return Promise.resolve(null);const o=(async()=>{try{await pe(n.scriptUrl,{translations:n.scriptTranslations,deps:n.scriptDeps,l10n:n.scriptL10n,before:n.scriptBefore,after:n.scriptAfter})}catch(i){return L(y.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=FT(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return L(y.SHELL_ERROR,{scope:"wallpaper-missing-def",id:n.id,error:new Error(`[openstation] No wallpaper def on window.openStationWallpapers["${n.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)}),null;try{Hn(s)}catch(i){return L(y.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return ar(n.id),s})().finally(()=>{ro.state.inflight.delete(e)});return ro.state.inflight.set(e,o),o}function HT(e){return{id:e.id,label:e.label,type:"canvas",preview:e.preview!==""?e.preview:e.value,description:e.description||void 0,mount:async(t,n)=>{const o=await mg(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await ol(o.needs),o.mount(t,n))}}}function GT(e){const{osSettings:t}=e,n=new Set,o=r=>r.type!=="css"||r.value===""?null:{id:r.id,label:r.label,type:"css",value:r.value,preview:r.preview!==""?r.preview:r.value,description:r.description||void 0,tone:r.tone==="light"||r.tone==="dark"?r.tone:void 0},s=async r=>{if(n.has(r.id))return;const a=o(r);if(a){Hn(a),n.add(r.id),t.apply();return}if(!r.scriptUrl)return;BT(r);const l=r.preview!==""||r.value!=="";if(l){try{Hn(HT(r))}catch(c){L(y.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:c}),ar(r.id);return}n.add(r.id)}if(!l||t.state.wallpaper===r.id){const c=await mg(r.id);if(!l){if(!c){ar(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(Mf(r),ar(r),n.delete(r),t.apply())};return async r=>{const a=new Set;for(const l of r)a.add(l.id);for(const l of Array.from(n))a.has(l)||i(l);for(const l of r)n.has(l.id)||await s(l)}}function zT(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??{},window:e.window&&Object.keys(e.window).length>0?e.window:void 0,scriptUrl:e.scriptUrl,scriptTranslations:e.scriptTranslations,scriptL10n:e.scriptL10n,scriptBefore:e.scriptBefore,scriptAfter:e.scriptAfter,scriptDeps:e.scriptDeps}}function jT(){const e=new Set,t=o=>{try{const s=ir(o.id),i=zT(o);il(s&&typeof s.render=="function"?{...i,render:s.render,window:s.window}:i)}catch(s){typeof console<"u"&&console.error(`[openstation] Server game "${o.id}" failed to register:`,s);return}e.add(o.id)},n=o=>{e.has(o)&&(ag(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 Et=se("desktop-mode/heartbeat-bus",()=>({suppliers:new Map,subscribers:new Map,booted:!1})),$e={contribute(e,t){return Et.state.suppliers.set(e,t),()=>{Et.state.suppliers.get(e)===t&&Et.state.suppliers.delete(e)}},subscribe(e,t){let n=Et.state.subscribers.get(e);return n||(n=new Set,Et.state.subscribers.set(e,n)),n.add(t),()=>{n.delete(t)}}};function VT(){if(Et.state.booted)return;Et.state.booted=!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 Et.state.suppliers)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 Et.state.subscribers){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 cr=null,lr={installHintDismissed:!1,notificationsEnabled:!1};const al=new Set;function gg(e){if(!e){cr=null;return}cr=e,lr={...e.state},yg()}function ds(){return{...lr}}function cl(e){if(lr={...lr,...e},yg(),!cr)return ds();const t=JSON.stringify(e),n=KT();return fetch(cr.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("[openstation] pwa-state write failed:",o)}),ds()}function wg(e){return al.add(e),()=>{al.delete(e)}}function yg(){const e=ds();for(const t of Array.from(al))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function KT(){return window.openStationConfig?.restNonce??""}const qT=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:ds,initPwaState:gg,subscribePwaState:wg,updatePwaState:cl},Symbol.toStringTag,{value:"Module"}));function ll(e){const t=Se.filter("os/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=ue({message:t.body?t.title+" — "+t.body:t.title}),Se.publish("os/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=bg(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){cl({notificationsEnabled:!0}),o=bg(t),o||r();return}r()}}),i)}function bg(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("[openstation] Notification ctor threw:",n),null}if(e.onClick){const n=e.onClick;t.onclick=()=>{try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] notification onClick threw:",o)}}}return Se.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function YT(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&cl({notificationsEnabled:!0}),e}function XT(){return typeof Notification>"u"?"unsupported":Notification.permission}function ZT(e){return ir(e)?.title||e}const vg=new Set,_g=new Set;async function JT(e){const{challenge:t}=await AT(e.id);rl([t]),await pg(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function QT(e){const t=le(b("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,ZT(e.game),String(e.scoreToBeat));ll({title:b("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),ue({message:t,persistent:!0,dismissible:!0,action:{label:b("Accept & Play"),onClick:()=>{JT(e).catch(n=>{ue({message:n instanceof Error?n.message:b("Could not accept the challenge.")})})}}})}function eN(e){let t;e.result==="beaten"?t=b("%1$s beat your score: %2$s vs your %3$s."):t=b("%1$s did not beat your score: %2$s vs your %3$s.");const n=le(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));ll({title:b("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),ue({message:n})}function tN(e){const{currentUserId:t}=e;if(!t)return;$e.contribute("openstation_games_subscribe",()=>({challengesVersion:NT().version})),$e.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&rl(o.challenges)});const n=()=>{for(const o of xT())o.state==="pending"&&o.recipientId===t&&!vg.has(o.id)&&(vg.add(o.id),QT(o)),o.state==="completed"&&o.challengerId===t&&!_g.has(o.id)&&(_g.add(o.id),eN(o))};OT(n),n()}const Eg=/^[a-z0-9_/-]+$/,kg=se("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),un=kg.state.registry,nN=kg.state.listeners;function ao(e){const t=[],n=typeof e?.slug=="string"?e.slug.trim().toLowerCase():"";!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.slug!="string"||e.slug.trim()===""?t.push("slug (missing)"):Eg.test(n)||t.push(`slug (must match ${Eg} — 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)")),Me("Command",t,e),un.set(n,{...e,slug:n}),dl()}function Sg(e){un.delete(e.toLowerCase())&&dl()}function dr(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&&dl(),t}function Ig(){return Array.from(un.values())}function oN(){const e=[];for(const t of un.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function sN(e){return un.get(e.toLowerCase())??null}function dl(){const e=Array.from(nN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function iN(){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 pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(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 l of r){if(!l.scriptHandle||!l.slug)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.slug)}return a},i=r=>{const a=new Set;for(const c of Ig())c.owner===r&&a.add(c.slug);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))Sg(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Ag=se("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),us=Ag.state.registry,rN=Ag.state.listeners;function Cg(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("[openstation] registerSettingsTab: id must be [a-z0-9_-]+, got",e.id);return}us.set(t,{...e,id:t}),ul()}function Lg(e){us.delete(e.toLowerCase())&&ul()}function aN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(us.entries()))o.owner===e&&(us.delete(n),t++);return t>0&&ul(),t}function Tg(){return Array.from(us.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function ul(){const e=Array.from(rN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function cN(){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 pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(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 l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{aN(r);const a=n.get(r);if(a){const l=new Set(Tg().map(c=>c.id));for(const c of a)l.has(c)&&Lg(c)}};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))l.has(c)||(i(c),e.delete(c));for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Ng=se("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),fs=Ng.state.registry,lN=Ng.state.listeners,Og=/^[a-z0-9_/-]+$/;function ps(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Og.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Og} — 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)")),Me("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();fs.set(n,{...e,id:n}),ur()}function Dg(e){fs.delete(e.toLowerCase())&&ur()}function dN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(fs.entries()))o.owner===e&&(fs.delete(n),t++);return t>0&&ur(),t}function uN(){return Array.from(fs.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function ur(){const e=Array.from(lN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] title-bar-button registry listener threw:",n)}}typeof document<"u"&&document.addEventListener("os-settings-save-lifecycle",e=>{const t=e.detail;t&&t.phase==="saved"&&ur()});function fN(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(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)||(dN(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const xg=se("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),hs=xg.state.registry,pN=xg.state.listeners,Rg=/^[a-z0-9_/-]+$/;function fl(){for(const e of Array.from(pN))try{e()}catch{}}function Mg(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Rg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Rg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.label!="string"&&typeof e.label!="function"?t.push("label (must be a string or a function)"):typeof e.label=="string"&&e.label.trim()===""&&t.push("label (empty)"),typeof e.onSelect!="function"&&t.push("onSelect (must be a function)"),e.isVisible!==void 0&&typeof e.isVisible!="function"&&t.push("isVisible (must be a function when set)"),e.checked!==void 0&&typeof e.checked!="function"?t.push("checked (must be a function when set)"):e.checkable&&typeof e.checked!="function"&&t.push("checked (required when checkable is set)")),Me("WindowAction",t,e);const n=e.id.trim().toLowerCase();hs.set(n,{...e,id:n}),fl()}function hN(e){hs.delete(String(e||"").toLowerCase())&&fl()}function mN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(hs.entries()))o.owner===e&&(hs.delete(n),t++);return t>0&&fl(),t}function gN(){return Array.from(hs.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function wN(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(y.SHELL_ERROR,{scope:"window-action-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)||(mN(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function Wg(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function yN({items:e,onPick:t}){const n=document.createElement("os-menu");n.classList.add("os-window__menu-panel"),n.classList.add("os-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)=>Wg(r[0])-Wg(a[0])),i=[];for(const[,r]of s){const a=r.find(l=>typeof l.groupLabel=="string"&&l.groupLabel!=="")?.groupLabel;if(a){const l=document.createElement("div");l.className="os-window__related-group",l.setAttribute("role","presentation"),l.textContent=a,n.appendChild(l)}for(const l of r){const c=document.createElement("os-menu-item");c.setAttribute("role","menuitem"),c.setAttribute("value",l.id),c.tabIndex=-1,l.icon&&c.setAttribute("icon",l.icon),c.classList.add("os-window__related-item"),c.textContent=typeof l.count=="number"?`${l.label} (${l.count})`:l.label,c.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),t(l)}),i.push(c),n.appendChild(c)}}return n.addEventListener("keydown",r=>{const a=r,l=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const c=a.key==="ArrowDown";let d=i[c?0:i.length-1];l!==-1&&(d=i[(l+(c?1:-1)+i.length)%i.length]),d?.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 c=i[l];c&&(a.preventDefault(),a.stopPropagation(),c.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function Pg(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)||n(t.windowId))&&(t.url===void 0||typeof t.url=="string")&&(t.windowId===void 0||typeof t.windowId=="string")&&(t.params===void 0||!!t.params&&typeof t.params=="object")&&(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 $g(e){const t=We(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=Q(y.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(Pg):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(Pg))}function pl(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function bN(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function vN(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=$g(t.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",a),l.remove(),e.setAttribute("aria-expanded","false")},a=c=>{c.key==="Escape"&&(c.stopPropagation(),r(),e.focus())},l=yN({items:s,onPick:c=>{r(),bN(o),n(c)}});l._wpdRelatedClose=r,o.appendChild(l),o.addEventListener("keydown",a),e.setAttribute("aria-expanded","true"),i=c=>{const d=c.target;!d||l.contains(d)||e.contains(d)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),l.querySelector('[role="menuitem"]')?.focus()}function _N({manager:e,openUrl:t}){ps({id:"desktop-mode/related-entities",label:b("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>$g(n.id).length>0,render:(n,o)=>{pl(o.element),n.setAttribute("aria-haspopup","menu"),n.setAttribute("aria-expanded","false"),n.addEventListener("click",s=>{if(s.stopPropagation(),o.element?.querySelector(".os-window__related-panel")){pl(o.element);return}vN(n,o,t)})}}),ee(y.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(pl(o.element),o.renderCustomTitleBarButtons?.())})}const hl="os-broadcast",Ug="os-broadcast",Bg=window.location.origin;let ml=null;function EN(e){ml=e}function fr(e,t){const n=String(Q("os.broadcast.topic",e,{payload:t})??e),o=Q("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(hl,{detail:s})),L(y.BROADCAST,s),Se.publish(n,o),!ml)return;const i={type:Ug,topic:n,payload:o};for(const r of ml._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Bg)}catch{}}}function co(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){L(y.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(hl,n),()=>document.removeEventListener(hl,n)}function kN(){window.addEventListener("message",e=>{if(e.origin!==Bg)return;const t=e.data;!t||t.type!==Ug||t._fromParent||typeof t.topic=="string"&&fr(t.topic,t.payload)})}function Fg(e,t,n,o=""){const s=(Array.isArray(n)?n:[n]).map(r=>Math.floor(Number(r))).filter(r=>Number.isFinite(r)&&r>0),i=String(e).trim();i===""||s.length===0||fr(`os.${i}.changed`,{source:o,action:t,ids:s})}const gl=window.location.origin,Oe=se("desktop-mode/connection",()=>({connSeq:0,connections:new Map,connectionsByTarget:new Map,syntheticIframes:new Map}));function SN(e,t){const{syntheticIframes:n}=Oe.state;return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function IN(e){return Oe.state.syntheticIframes.get(e)??null}function AN(){return`os-conn-${++Oe.state.connSeq}`}function CN(e){const t=(l,c)=>{try{l.contentWindow?.postMessage(c,gl)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=AN(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let g=!1,h=!1;const m=()=>{const W=Oe.state.syntheticIframes.get(l);return W||(e.getById(l)?.iframe??null)},E=()=>{if(m())return!1;const W=e.getById(l);return!!W&&W.config?.native===!0},k=[],N=()=>{const W=m();if(W)for(;p.length;){const F=p.shift();t(W,{type:"os-bridge-publish",connectionId:d,topic:F.topic,payload:F.payload})}},M={id:d,target:l,isOpen:()=>g,subscribe(W,F){const x=F;if(E()){const J=hS(l,W,(X,T)=>{L(y.CONNECTION_MESSAGE,{connectionId:d,topic:T.channel,direction:"in"});try{x(X,{topic:T.channel})}catch(D){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",D)}});return k.push(J),J}let q=f.get(W);return q||(q=new Set,f.set(W,q)),q.add(x),()=>{q?.delete(x)}},send(W,F){if(h)return;if(L(y.CONNECTION_MESSAGE,{connectionId:d,topic:W,direction:"out"}),E()){gS(l,W,F);return}if(!g){p.push({topic:W,payload:F});return}const x=m();x&&t(x,{type:"os-bridge-publish",connectionId:d,topic:W,payload:F})},disconnect(){M._destroy("disconnect")},_targetWindow:m,_handleIframeMessage(W){if(!W||typeof W!="object")return;const F=W;if(F.type==="os-bridge-handshake-ack"){if(g)return;g=!0,L(y.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:M});try{c.onOpen?.()}catch(x){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",x)}N();return}if(F.type==="os-bridge-publish"){const x=W,q=typeof x.topic=="string"?x.topic:"";if(!q)return;L(y.CONNECTION_MESSAGE,{connectionId:d,topic:q,direction:"in"});const J=f.get(q);if(J)for(const T of Array.from(J))try{T(x.payload,{topic:q})}catch(D){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",D)}const X=f.get("*");if(X)for(const T of Array.from(X))try{T(x.payload,{topic:q})}catch(D){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",D)}return}F.type==="os-bridge-disconnect"&&M._destroy("disconnect")},_destroy(W){if(h)return;h=!0;const F=g;g=!1,Oe.state.connections.delete(d);const x=Oe.state.connectionsByTarget.get(l);x&&(x.delete(d),x.size===0&&Oe.state.connectionsByTarget.delete(l));for(const q of k.splice(0))try{q()}catch{}if(F){const q=m();q&&t(q,{type:"os-bridge-disconnect",connectionId:d})}L(y.CONNECTION_CLOSED,{connectionId:d,reason:W});try{c.onClose?.(W)}catch(q){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",q)}}};Oe.state.connections.set(d,M);let S=Oe.state.connectionsByTarget.get(l);if(S||(S=new Set,Oe.state.connectionsByTarget.set(l,S)),S.add(d),E())return Promise.resolve().then(()=>{if(!(h||g)){g=!0,L(y.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(W){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",W)}}}),M;const $=m();return $&&t($,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),M},o=(l,c)=>{if(!l||typeof l!="object")return;const d=l;if(typeof d.type!="string"||!d.type.startsWith("os-bridge-"))return;if(d.type==="os-bridge-connection-request"&&typeof d.requestId=="string"&&typeof c=="string"&&c!==""){s(c,d.requestId,Array.isArray(d.topics)?d.topics:[]);return}if(typeof d.connectionId!="string")return;Oe.state.connections.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=Oe.state.syntheticIframes.get(l)??e.getById(l)?.iframe??null;if(!f)return;const p=Q(y.IFRAME_CONNECTION_REQUEST,!0,{windowId:l,requestId:c,topics:d.slice()});if(p===!1){try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!1,reason:"rejected"},gl)}catch{}return}const g=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,h=n(l,{topics:g});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:h.id},gl)}catch{}};return{connect:n,getConnection:l=>Oe.state.connections.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=Oe.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c)){const u=Oe.state.connections.get(d);if(!u||u.isOpen())continue;const f=u._targetWindow();f&&t(f,{type:"os-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:l=>{const c=Oe.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c))Oe.state.connections.get(d)?._destroy("window-closed")}}}const LN=new Set(["saved","no-editor","not-dirty","error"]);let Hg=0;function Gg(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function TN(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Hg+=1;const o=`os-editor-preview-${Date.now()}-${Hg}`;return new Promise(s=>{let i=null,r=!1;const a=c=>{r||(r=!0,window.removeEventListener("message",l),i!==null&&window.clearTimeout(i),s(c))},l=c=>{if(c.origin!==window.location.origin)return;const d=c?.data;if(!d||typeof d!="object"||d.type!=="os-editor-autosave-response"||d.requestId!==o)return;const u=typeof d.status=="string"&&LN.has(d.status)?d.status:"error",f=Gg(d.previewUrl);a(f?{status:u,previewUrl:f}:{status:u})};window.addEventListener("message",l),i=window.setTimeout(()=>a({status:"timeout"}),t);try{n.postMessage({type:"os-editor-autosave-request",requestId:o},window.location.origin)}catch{a({status:"no-editor"})}})}const Fe=se("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),NN=400,zg=1500;function ms(e){return e?`${e.type}:${e.id}`:""}function ON(e){for(const t of Fe.state.pairings.values())if(t.previewWindowId===e)return t}function DN(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function pr(e){return e.iframe??IN(e.id)}function xN(e){const t=e.getCurrentUrl?.()??"";if(!t)return!1;try{return new URL(t,window.location.origin).pathname.endsWith("/post-new.php")}catch{return!1}}function hr(e,t,n,o){Fe.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(Vg(e,t),o!=="none"){const i=e.getById(t.previewWindowId);i&&(o==="destroy"?i.destroy?.():i.close?.())}const s={editorWindowId:t.editorWindowId,previewWindowId:t.previewWindowId,reason:n};document.dispatchEvent(new CustomEvent("os-editor-preview-closed",{detail:s})),L(y.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function wl(e,t,n){t.reloadTimer!==null&&window.clearTimeout(t.reloadTimer),t.reloadTimer=window.setTimeout(()=>{t.reloadTimer=null;const o=e.getById(t.previewWindowId);if(!o)return;const s=n||We(t.editorWindowId)?.previewUrl,i=s&&s!==t.openUrl?s:void 0;typeof o.swapReload=="function"?(i&&(t.openUrl=i),o.swapReload(i)):i&&o.navigateTo?(t.openUrl=i,o.navigateTo(i)):o.reload?.()},NN)}function RN(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=co(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||wl(e,t)})}let jg=0;function Vg(e,t){if(!t.watchId)return;const n=e.getById(t.editorWindowId);try{(n?pr(n):null)?.contentWindow?.postMessage({type:"os-editor-live-unwatch",watchId:t.watchId},window.location.origin)}catch{}t.watchId=""}function Kg(e,t,n){Vg(e,t);const o=Q(y.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:zg},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId),i=(s?pr(s):null)?.contentWindow;if(!i)return;jg+=1;const r=`${t.previewWindowId}-watch-${jg}`;try{i.postMessage({type:"os-editor-live-watch",watchId:r,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:zg},window.location.origin),t.watchId=r}catch{}}let MN=e=>TN({iframe:pr(e)});async function WN(e,t){const n=Fe.state.pairings.get(t.id);if(n){hr(e,n,"toggled","close");return}if(Fe.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=We(t.id);if(!o?.previewUrl){ue({message:b("No preview is available for this content.")});return}Fe.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=DN();s||t.applySnap?.("left");const i=MN(t);i.then(f=>{f.status==="error"&&ue({message:b("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{Fe.state.busyEditors.delete(t.id),e.getById(t.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=b("Preview");o.label&&(a=le(b("Preview: %s"),o.label));let l={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=Q(y.EDITOR_PREVIEW_WINDOW_CONFIG,l,{editorWindowId:t.id,content:o});if(c&&typeof c=="object"&&typeof c.id=="string"&&c.id!==""&&typeof c.url=="string"&&c.url!==""?l=c:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await e.open(l),!e.getById(t.id)||ms(We(t.id))!==ms(o)){e.getById(l.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:l.id,postKey:ms(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};RN(e,d,o),Kg(e,d,o),Fe.state.pairings.set(t.id,d);const u={editorWindowId:t.id,previewWindowId:l.id,content:o};document.dispatchEvent(new CustomEvent("os-editor-preview-opened",{detail:u})),L(y.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Fe.state.pairings.get(t.id)===d&&f.status==="saved"&&wl(e,d,f.previewUrl)})}function PN({manager:e}){ps({id:"desktop-mode/editor-preview",label:b("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>(!t.config.native||!!pr(t))&&(!!We(t.id)?.previewUrl||!t.config.native&&xN(t)),render:(t,n)=>{if(!We(n.id)?.previewUrl){const i=b("Save the post to enable its preview");t.setAttribute("aria-disabled","true"),t.setAttribute("aria-label",i),t.setAttribute("title",i),t.classList.add("os-window__btn--disabled"),t.addEventListener("click",r=>{r.stopPropagation(),ue({message:b("The preview opens once the post has been saved.")})});return}const o=Fe.state.pairings.has(n.id),s=Fe.state.busyEditors.has(n.id);t.setAttribute("aria-pressed",String(o)),s&&(t.setAttribute("aria-busy","true"),t.classList.add("os-window__btn--busy")),t.addEventListener("click",i=>{i.stopPropagation(),WN(e,n)})}}),ee(y.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Fe.state.pairings.get(t.windowId);n&&ms(t.content)!==n.postKey&&hr(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),ee(y.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Fe.state.pairings.get(t.windowId);if(n){hr(e,n,"editor-closed","destroy");return}const o=ON(t.windowId);o&&hr(e,o,"preview-closed","none")}),ee(y.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Fe.state.pairings.get(t.windowId);if(n){const o=We(t.windowId);o&&ms(o)===n.postKey&&Kg(e,n,o)}e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t?.data;if(!(!n||typeof n!="object"||n.type!=="os-editor-live-saved"||typeof n.watchId!="string")){for(const o of Fe.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){wl(e,o,Gg(n.previewUrl));return}}})}const qg=16,Ye=16,$N=1100,UN=860;function BN(e,t){const n=Math.max(0,t.width-Ye*2),o=Math.max(320,Math.min($N,Math.round(n*.5))),s=Math.max(200,Math.min(UN,Math.round(t.height*.8))),i=FN(e.y,Ye,Math.max(Ye,t.height-s-Ye)),r=e.x+e.width+qg;if(r+o+Ye<=t.width)return{x:r,y:i,width:o,height:s};const a=e.x-qg-o;if(a>=Ye)return{x:a,y:i,width:o,height:s};const l=e.x+e.width/2,c=e.y+e.height/2,d=l<=t.width/2,u=c<=t.height/2;return{x:d?Math.max(Ye,t.width-o-Ye):Ye,y:u?Math.max(Ye,t.height-s-Ye):Ye,width:o,height:s}}function FN(e,t,n){return Math.min(Math.max(e,t),n)}function HN(e){return`revisions-${String(e.type).replace(/\//g,"-")}-${e.id}`}function GN(e){const t=e?.revisionCount;return typeof t=="number"&&t>0?le(b("View revisions (%d)"),t):b("View revisions")}function zN(e,t,n){if(Bi(n))return{};if(typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches)return{};const o=e.getById(t)?.element,s=document.getElementById("os-area");return!o||!s||o.offsetParent===null||o.offsetWidth===0?{}:BN({x:o.offsetLeft,y:o.offsetTop,width:o.offsetWidth,height:o.offsetHeight},{width:s.clientWidth,height:s.clientHeight})}async function jN(e,t){const n=We(t.id);if(!n?.revisionsUrl){ue({message:b("No revisions are available for this content.")});return}const o=HN(n);let s=b("Revisions");n.label&&(s=le(b("Revisions: %s"),n.label));let i={id:o,baseId:o,url:n.revisionsUrl,title:s,icon:"dashicons-backup",content:{type:"revisions",id:n.id,root:{type:n.type,id:n.id},label:s},...zN(e,t.id,o)};const r=Q(y.REVISIONS_WINDOW_CONFIG,i,{editorWindowId:t.id,content:n});r&&typeof r=="object"&&typeof r.id=="string"&&r.id!==""&&typeof r.url=="string"&&r.url!==""?i=r:typeof console<"u"&&console.warn("[openstation] `os.revisions.window-config` filter returned an invalid config; using the default."),await e.open(i);const a={editorWindowId:t.id,revisionsWindowId:i.id,content:n};document.dispatchEvent(new CustomEvent("os-revisions-opened",{detail:a})),L(y.REVISIONS_OPENED,a)}function VN({manager:e}){Mg({id:"desktop-mode/view-revisions",label:t=>GN(We(t.id)),icon:"dashicons-backup",order:60,isVisible:t=>!!We(t.id)?.revisionsUrl,onSelect:t=>{jN(e,t)}})}const Yg="none",Xg=se("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),gs=Xg.state.registry,yl=Xg.state.listeners,Zg=/^[a-z0-9_/-]+$/;function mr(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Zg.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Yg&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Zg} — 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)")),Me("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();gs.set(n,{...e,id:n}),vl()}function KN(e){gs.delete(e.toLowerCase())&&vl()}function qN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(gs.entries()))o.owner===e&&(gs.delete(n),t++);return t>0&&vl(),t}function bl(){const e=Array.from(gs.values()),t=Q(y.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function Jg(e){return bl().find(t=>t.id===e)}function YN(e){return yl.add(e),()=>{yl.delete(e)}}function vl(){const e=Array.from(yl);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}mr({id:"darken",label:b("Darken"),description:b("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),mr({id:"frost",label:b("Frost"),description:b("Throw unfocused windows out of focus — a soft, frosted-glass blur, as if you were looking at them through an iced-over pane."),className:"os-window--fx-frost"}),mr({id:"grayscale",label:b("Grayscale"),description:b("Drain the colour from unfocused windows so the focused one is the only thing still in colour — your eye snaps right to it."),className:"os-window--fx-grayscale"});function XN(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(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)||(qN(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const ZN="none",Qg=se("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),ws=Qg.state.registry,JN=Qg.state.listeners,ew=/^[a-z0-9_/-]+$/;function tw(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):ew.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===ZN&&t.push('id ("none" is reserved)'):t.push(`id (must match ${ew} — 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)")),Me("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();ws.set(n,{...e,id:n}),El()}function QN(e){ws.delete(e.toLowerCase())&&El()}function eO(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ws.entries()))o.owner===e&&(ws.delete(n),t++);return t>0&&El(),t}function _l(){const e=Array.from(ws.values()),t=Q(y.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function El(){const e=Array.from(JN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}function tO(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(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)||(eO(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}let fn=null;function nw(){if(fn)return fn;if(window.openStationWindowLinkVisuals)return fn=Promise.resolve(!0),fn;const t=window.openStationConfig?.windowLinkVisualsBundleUrl;return t?(fn=pe(t).then(()=>!0).catch(n=>{throw fn=null,n}),fn):Promise.resolve(!1)}const kl="svg-splines";function nO(){if(_l().some(t=>t.id===kl))return;const e=async t=>{if(!await nw())return;const o=_l().find(s=>s.id===kl);if(!(!o||o.mount===e))return o.mount(t)};tw({id:kl,label:b("Splines"),description:b("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 Sl="data-desktop-unfocus-effect",Il="data-desktop-unfocus-effect-class";let ow=!1;function oO(e){return e.querySelector("canvas")!==null}function sO(e){return e.state==="snapped-left"||e.state==="snapped-right"}function iO({manager:e,osSettings:t}){if(ow)return;ow=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(Il);l&&(r.classList.remove(l),r.removeAttribute(Il));const c=r.getAttribute(Sl);c&&Jg(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(Sl)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Il,a.className)),r.setAttribute(Sl,a.id),a.apply?.(r)},i=()=>{const r=n===Yg?void 0:Jg(n),a=bl();for(const l of e.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(sO(l)||oO(c)||s(c,r)))}};for(const r of["os-window-opened","os-window-reopened","os-window-closed","os-window-focused","os-window-blurred"])document.addEventListener(r,()=>i());document.addEventListener("os-window-changed",r=>{r.detail?.reason==="state"&&i()}),t.subscribeOsSettings(r=>{n=r.unfocusEffect,i()}),YN(()=>i()),i()}function rO(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(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)||(fk(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function aO(e){if(!e.bundleUrl)return()=>{};let t=!1;const n=o=>{const s=o.target;t||!(s instanceof Element)||!s.closest(".os-dock")||(t=!0,pe(e.bundleUrl).then(()=>{document.removeEventListener("pointerover",n,!0),document.removeEventListener("focusin",n,!0),window.openStationDockConstellation?.mount(e.deps)}).catch(()=>{t=!1}))};return document.addEventListener("pointerover",n,!0),document.addEventListener("focusin",n,!0),()=>{document.removeEventListener("pointerover",n,!0),document.removeEventListener("focusin",n,!0)}}const sw=se("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),ys=sw.state.registry,cO=sw.state.listeners,iw=/^[a-z0-9_/-]+$/;function rw(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)"):iw.test(e.id.trim().toLowerCase())||t.push(`id (must match ${iw} — 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)")}Me("WindowTheme",t,e);const n=e.id.trim().toLowerCase();ys.set(n,{...e,id:n}),Al()}function aw(e){ys.delete(e.toLowerCase())&&Al()}function lO(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ys.entries()))o.owner===e&&(ys.delete(n),t++);return t>0&&Al(),t}function cw(){return Array.from(ys.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function Al(){const e=Array.from(cO);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function dO(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async l=>{if(!l.scriptUrl||t.has(l.scriptUrl)){e.add(l.handle);return}try{await pe(l.scriptUrl,{translations:l.scriptTranslations,deps:l.scriptDeps,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){L(y.SHELL_ERROR,{scope:"window-theme-script-load",handle:l.handle,url:l.scriptUrl,error:c});return}t.add(l.scriptUrl),e.add(l.handle)},i=l=>{const c=new Map;if(!l)return c;for(const d of l){if(!d.scriptHandle||!d.id)continue;let u=c.get(d.scriptHandle);u||(u=new Set,c.set(d.scriptHandle,u)),u.add(d.id)}return c},r=l=>{const c=new Set;for(const u of cw())u.owner===l&&c.add(u.id);const d=n.get(l);if(d)for(const u of d)c.add(u);return c},a=l=>{if(l){for(const c of l)if(!(!c.id||!c.tokens))try{rw({id:c.id,label:c.label,tokens:c.tokens,priority:c.priority,match:()=>!0,owner:c.scriptHandle||void 0}),o.add(c.id)}catch(d){L(y.SHELL_ERROR,{scope:"window-theme-shell-register",id:c.id,error:d})}}};return async(l,c)=>{const d=new Set;for(const u of l)u.handle&&d.add(u.handle);for(const u of Array.from(e)){if(d.has(u))continue;const f=r(u);for(const p of f)aw(p),o.delete(p);lO(u),e.delete(u)}a(c);for(const u of l)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const lw=se("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),bs=lw.state.registry,uO=lw.state.listeners,dw=/^[a-z0-9_/-]+$/;function vs(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):dw.test(e.id.trim().toLowerCase())||t.push(`id (must match ${dw} — 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")')),Me("WindowControl",t,e);const n=e.id.trim().toLowerCase();bs.set(n,{...e,id:n}),Cl()}function uw(e){bs.delete(e.toLowerCase())&&Cl()}function fO(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(bs.entries()))o.owner===e&&(bs.delete(n),t++);return t>0&&Cl(),t}function fw(){return Array.from(bs.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Cl(){const e=Array.from(uO);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function pO(){vs({id:"core/minimize",label:b("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),vs({id:"core/maximize",label:b("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),vs({id:"core/focus-tab",label:b("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),vs({id:"core/close",label:b("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function hO(){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 pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(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 l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of fw())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))uw(d);fO(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const pw=se("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),_s=pw.state.registry,mO=pw.state.listeners,hw=/^[a-z0-9_/-]+$/,mw=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function gw(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):hw.test(e.id.trim().toLowerCase())||t.push(`id (must match ${hw} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):mw.has(e.slot)||t.push(`slot (must be one of ${Array.from(mw).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Me("WindowSlot",t,e);const n=e.id.trim().toLowerCase();_s.set(n,{...e,id:n}),Tl()}function Ll(e){_s.delete(e.toLowerCase())&&Tl()}function gO(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(_s.entries()))o.owner===e&&(_s.delete(n),t++);return t>0&&Tl(),t}function ww(){return Array.from(_s.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Tl(){const e=Array.from(mO);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function wO(){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 pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(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 l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of ww())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))Ll(d);gO(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const yO="desktop-mode-notice-dismissed";function bO(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function yw(){return`${yO}:${bO()}`}function Nl(){try{const e=window.localStorage.getItem(yw());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function bw(e){try{window.localStorage.setItem(yw(),JSON.stringify(e))}catch{}}function gr(e){return e?Nl()[e]===!0:!1}function wr(e){if(!e)return;const t=Nl();t[e]=!0,bw(t)}function vw(e){if(!e)return;const t=Nl();t[e]&&(delete t[e],bw(t))}const vO=Ne`:host{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:10px 14px;font:var( --os-ui-notice-font,13px/1.5 var( --os-font,system-ui ) );color:var( --os-ui-notice-color,var( --os-ui-fg,#1d2327 ) );background:var( --os-ui-notice-bg,var( --os-ui-hover,rgba( 0,0,0,0.04 ) ) );border-block-end:1px solid var( --os-ui-notice-border,var( --os-ui-border,rgba( 0,0,0,0.08 ) ) );border-inline-start:4px solid var( --os-ui-notice-accent,var( --os-ui-border,#646970 ) )}:host( [ hidden ] ){display:none}.os-notice__icon{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:var( --os-ui-notice-accent,var( --os-ui-accent,#646970 ) )}.os-notice__icon[ hidden ]{display:none}.os-notice__label{flex:1;min-width:0;word-wrap:break-word}::slotted( a ){color:var( --os-ui-notice-link,var( --wp-admin-theme-color,#2271b1 ) );border-radius:2px}::slotted( a:hover ),::slotted( a:focus-visible ){color:var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) )}::slotted( a:focus-visible ){outline:2px solid var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) );outline-offset:2px}::slotted( p:first-child ){margin-block-start:0}::slotted( p:last-child ){margin-block-end:0}.os-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}.os-notice__close:hover{opacity:1;background:var( --os-ui-hover,rgba( 0,0,0,0.06 ) )}.os-notice__close:focus-visible{opacity:1;outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:1px}.os-notice__close[ hidden ]{display:none}.os-notice__close svg{width:14px;height:14px}:host( [ tone='info' ] ){--os-ui-notice-accent:var( --os-ui-notice-info,var( --os-ui-info-fg,#0969da ) );--os-ui-notice-bg:var( --os-ui-notice-info-bg,rgba( 9,105,218,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-info-border,rgba( 9,105,218,0.16 ) )}:host( [ tone='success' ] ){--os-ui-notice-accent:var( --os-ui-notice-success,var( --os-ui-success-fg,#1a7f37 ) );--os-ui-notice-bg:var( --os-ui-notice-success-bg,rgba( 26,127,55,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-success-border,rgba( 26,127,55,0.16 ) )}:host( [ tone='warning' ] ){--os-ui-notice-accent:var( --os-ui-notice-warning,var( --os-ui-warning-fg,#9a6700 ) );--os-ui-notice-bg:var( --os-ui-notice-warning-bg,rgba( 154,103,0,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-warning-border,rgba( 154,103,0,0.16 ) )}:host( [ tone='error' ] ),:host( [ tone='danger' ] ){--os-ui-notice-accent:var( --os-ui-notice-error,var( --os-ui-danger,#cf222e ) );--os-ui-notice-bg:var( --os-ui-notice-error-bg,rgba( 207,34,46,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-error-border,rgba( 207,34,46,0.16 ) )}:host( [ tone='neutral' ] ){--os-ui-notice-accent:var( --os-ui-notice-neutral,var( --os-ui-fg-muted,#57606a ) );--os-ui-notice-bg:var( --os-ui-notice-neutral-bg,rgba( 87,96,106,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-neutral-border,rgba( 87,96,106,0.16 ) )}`,di=class di extends dn{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&gr(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&wr(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&vw(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return no`
21 <span
22 class="os-notice__icon dashicons ${t??""}"
23 ?hidden=${!t}
24 aria-hidden="true"
25 ></span>
26 <span class="os-notice__label"><slot></slot></span>
27 <button
28 type="button"
29 class="os-notice__close"
30 ?hidden=${!n}
31 aria-label=${b("Dismiss notice")}
32 @click=${o=>this._onDismiss(o)}
33 >
34 ${Vu("close",{size:null})}
35 </button>
36 `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};di.props=["tone","notDismissible","icon","noticeId"],di.styles=[vO],di.help=void 0;let Ol=di;cs("os-notice",Ol);const Es=se("desktop-mode/window-notices",()=>({entries:new Map})),_O=/^[a-z0-9_/-]+$/;function _w(e){return`os-notice/${e.toLowerCase()}`}function EO(e){const t=document.createElement("os-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 Ew(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!_O.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};Es.state.entries.set(t,n);const o=_w(t);return gw({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=Es.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=Es.state.entries.get(t);i&&s.appendChild(EO(i))}}),()=>Dl(t)}function Dl(e){const t=String(e??"").trim().toLowerCase();t&&Es.state.entries.delete(t)&&Ll(_w(t))}function kw(){return Array.from(Es.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 kO(e){const t=String(e??"").trim().toLowerCase();t&&wr(t)}function SO(e){const t=String(e??"").trim().toLowerCase();t&&vw(t)}function IO(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 Sw(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),Ew({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:IO(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of kw())n.owner==="__server__"&&(t.has(n.id)||Dl(n.id))}const Iw=se("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),ks=Iw.state.registry,AO=Iw.state.listeners,Aw=/^[a-z0-9_/-]+$/;function CO(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Aw.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Aw} — 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)")),Me("WindowChrome",t,e);const n=e.id.trim().toLowerCase();ks.set(n,{...e,id:n}),xl()}function Cw(e){ks.delete(e.toLowerCase())&&xl()}function LO(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ks.entries()))o.owner===e&&(ks.delete(n),t++);return t>0&&xl(),t}function Lw(){return Array.from(ks.values()).sort((e,t)=>e.id.localeCompare(t.id))}function xl(){const e=Array.from(AO);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function TO(){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 pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){L(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 l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of Lw())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))Cw(d);LO(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const NO={};function OO(...e){(typeof{url:ya&&ya.tagName.toUpperCase()==="SCRIPT"&&ya.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&NO?"production":void 0)!=="production"&&console.log(...e)}const DO="iframe:";function Rl(e){return DO+e}function Tw(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function xO(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const RO=250;class MO{constructor(t){this.streamingWindowId=null,this.focusedWindowId=null,this.paletteOpen=!1,this.closeGraceTimer=null,this.manager=t.manager,this.adminUrl=t.adminUrl}install(){document.addEventListener("os-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&this.onFocused(o.windowId)}),document.addEventListener("os-window-closed",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&(dr(Rl(o.windowId)),this.streamingWindowId===o.windowId&&(this.streamingWindowId=null),this.focusedWindowId===o.windowId&&(this.focusedWindowId=null))}),document.addEventListener("os-palette-opened",()=>{this.onPaletteOpened()}),document.addEventListener("os-palette-closed",()=>{this.onPaletteClosed()}),document.addEventListener("os-window-changed",n=>{const o=n.detail;!o||typeof o.windowId!="string"||o.reason==="state"&&o.state==="minimized"&&(this.streamingWindowId===o.windowId&&this.stopStreaming(),this.focusedWindowId===o.windowId&&(this.focusedWindowId=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==="os-bridge-ready"){const i=this.manager.findByIframeSource(n.source);i&&i.id===this.streamingWindowId&&this.sendSubscribe(i.id);return}if(o.type!=="os-commands-list"||!Array.isArray(o.commands))return;const s=this.manager.findByIframeSource(n.source);s&&s.id===this.streamingWindowId&&this.applyList(s.id,o.commands)});const t=this.manager.getFocused();t&&(this.focusedWindowId=t.id)}onFocused(t){const n=!this.paletteOpen||this.streamingWindowId===t;this.focusedWindowId===t&&n||(this.focusedWindowId&&this.focusedWindowId!==t&&dr(Rl(this.focusedWindowId)),this.streamingWindowId&&this.streamingWindowId!==t&&this.stopStreaming(),this.focusedWindowId=t,this.paletteOpen&&this.startStreaming(t))}onPaletteOpened(){this.paletteOpen=!0,this.closeGraceTimer!==null&&(window.clearTimeout(this.closeGraceTimer),this.closeGraceTimer=null),this.focusedWindowId&&this.startStreaming(this.focusedWindowId)}onPaletteClosed(){this.paletteOpen=!1,this.closeGraceTimer!==null&&window.clearTimeout(this.closeGraceTimer),this.closeGraceTimer=window.setTimeout(()=>{this.closeGraceTimer=null,this.stopStreaming()},RO)}startStreaming(t){this.streamingWindowId!==t&&(this.stopStreaming(),this.streamingWindowId=t,this.sendSubscribe(t))}stopStreaming(){if(!this.streamingWindowId)return;const t=this.manager.getById(this.streamingWindowId);if(this.streamingWindowId=null,t&&t.iframe&&t.iframe.contentWindow)try{t.iframe.contentWindow.postMessage({type:"os-commands-unsubscribe"},window.location.origin)}catch{}}sendSubscribe(t){const n=this.manager.getById(t);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"os-commands-subscribe"},window.location.origin)}catch(o){OO("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=Rl(t);dr(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=xO(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?Pu(s.iconSvg):"",a={slug:i,label:s.label,icon:Tw(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,Tw(s)):this.runProxy(t,s.name)};try{ao(a)}catch(l){console.error("[openstation] iframe-bridge: dropping bad command",a,l)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Be(t))return;const r=fe(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:"os-commands-invoke",name:n},window.location.origin)}catch{}this.manager.focus(i)}}}}function WO(e){const t=(n,o)=>{const s=e.getById(n);if(!(!s||!s.iframe||!s.iframe.contentWindow))try{s.iframe.contentWindow.postMessage({type:"os-window-active",active:o},window.location.origin)}catch{}};document.addEventListener("os-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&t(o.windowId,!0)}),document.addEventListener("os-window-blurred",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&t(o.windowId,!1)}),window.addEventListener("message",n=>{if(n.origin!==window.location.origin)return;const o=n.data;if(!o||o.type!=="os-bridge-ready")return;const s=e.findByIframeSource(n.source);s&&t(s.id,e.getFocused()?.id===s.id)})}const Nw="global",PO=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,$O=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,UO=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,BO=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,FO=/getSiteEditorPage\s*\(|site-editor\.php/,Ow=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function HO(e){const t=e.match(Ow)?.[1];return{wp_template:b("Edit template"),wp_template_part:b("Edit template part"),wp_navigation:b("Edit navigation menu"),wp_block:b("Edit pattern")}[t??""]}function GO(e){const t=window.__openStationMenuCommands;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 zO{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,this.titleForUrl=t.titleForUrl}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,l=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof l!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const c=document.createElement("div");c.setAttribute("aria-hidden","true"),c.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(c),this.host=c;const d={perLoader:{},statics:[],loadersList:[]},u=h=>{if(!Array.isArray(h)||h.length===0)return"";const m=new Array(h.length);for(let E=0;E<h.length;E++){const k=h[E];m[E]=k&&k.name?k.name:""}return m.join("|")},f=()=>{let h=[];for(const m of d.loadersList){const E=d.perLoader[m];Array.isArray(E)&&(h=h.concat(E))}Array.isArray(d.statics)&&(h=h.concat(d.statics)),this.callbackCache=Object.create(null);for(const m of h)m&&m.name&&typeof m.callback=="function"&&(this.callbackCache[m.name]=m.callback);this.publish(h)},p=h=>{const m=h.loader;let E=null;try{E=m.hook({search:""})}catch{}const k=E&&Array.isArray(E.commands)?E.commands:[],N=a(()=>u(k),[k]);return i(()=>{d.perLoader[m.name]=k,f()},[N]),i(()=>()=>{delete d.perLoader[m.name],f()},[]),null},g=()=>{const h=l(S=>{const $=S("core/commands");return!$||typeof $.getCommandLoaders!="function"?[]:[...$.getCommandLoaders(!1)||[],...$.getCommandLoaders(!0)||[]]},[]),m=l(S=>{const $=S("core/commands");return!$||typeof $.getCommands!="function"?[]:[...$.getCommands(!1)||[],...$.getCommands(!0)||[]]},[]),E=a(()=>Array.isArray(h)?h.map(S=>S&&S.name||""):[],[h]),k=E.join("|");i(()=>{d.loadersList=E,f()},[k]);const N=a(()=>u(Array.isArray(m)?m:[]),[m]);if(i(()=>{d.statics=Array.isArray(m)?m:[],f()},[N]),!Array.isArray(h)||h.length===0)return null;const M=[];for(const S of h)!S||typeof S.hook!="function"||M.push(s(p,{key:S.name,loader:S}));return s(n.Fragment||"div",null,M)};try{this.root=n.createRoot(c),this.root.render(s(g))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(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||""}
37 `;if(s!==this.lastFingerprint){this.lastFingerprint=s,dr(Nw);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),l={slug:r,label:i.label,description:i.kind==="navigate"?HO(i.name):void 0,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?Pu(i.iconSvg):void 0,owner:Nw,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name)};try{ao(l)}catch(c){console.error("[openstation] shell-harvester: dropping bad command",l,c)}}}}classify(t){const n={name:String(t.name),label:String(t.label),icon:typeof t.icon=="string"?t.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof t.callback=="function"?t.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n.windowTitle=o.windowTitle,n;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=GO(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,windowTitle:n.windowTitle},n}if(typeof t.callback=="function"){let i="";try{i=Function.prototype.toString.call(t.callback)}catch{i=""}const r=i.match(PO)||i.match($O)||i.match(UO);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(BO.test(i)){const l=FO.test(i)?n.name.match(Ow):null;if(l){const c=l[1],d=l[2],u=`/${c}/${d}`;try{const f=new URL("site-editor.php",this.adminUrl);f.searchParams.set("p",u),f.searchParams.set("canvas","edit"),n.url=f.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(),Be(t))return;const r=fe(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:this.titleForUrl?.(t)||n,icon:o})}}runInvoke(t){return(n,o)=>{const s=this.callbackCache[t];if(typeof s!="function")throw new Error(le(b("No live callback for command “%s” — the palette and the command registry are out of step. Reload the page."),t));s({close:()=>o.close()})}}}const Dw="os-command-palette-ready";let Ss=null;function jO(){const t=window.openStationConfig?.commandPalette;return!t||!Array.isArray(t.scripts)?null:t}function VO(){const e=window.wp;try{return!!e?.data?.select?.("core/commands")}catch{return!1}}function KO(e){if(!e.url)return;const t=e.url.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(document.head.querySelector(`link[rel="stylesheet"][href="${t}"]`))return;const n=document.createElement("link");n.rel="stylesheet",n.href=e.url,n.dataset.osPaletteStyle=e.handle,document.head.appendChild(n);for(const o of e.inline??[]){if(typeof o!="string"||o==="")continue;const s=document.createElement("style");s.dataset.osPaletteStyle=e.handle,s.textContent=o,document.head.appendChild(s)}}function qO(e){const t=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(document.head.querySelector(`link[rel="preload"][href="${t}"]`))return;const n=document.createElement("link");n.rel="preload",n.as="script",n.href=e,document.head.appendChild(n)}async function YO(){const e=jO();if(!e||e.scripts.length===0)return VO();for(const s of e.styles??[])KO(s);const t=new Set,o=e.scripts.filter(s=>{const i=s.handle||s.url;return!i||t.has(i)?!1:(t.add(i),!0)}).filter(s=>!s.url||!Gc(s));for(const s of o)s.url&&qO(s.url);for(const s of o)if(s.url)await pe(s.url,{handle:s.handle,translations:s.translations,l10n:s.l10n,before:s.before,after:s.after});else for(const i of[s.translations??"",...s.l10n??[],...s.before??[],...s.after??[]])typeof i=="string"&&i!==""&&mm(i);return document.dispatchEvent(new CustomEvent(Dw)),!0}function XO(){return Ss||(Ss=YO().catch(e=>{throw Ss=null,e}),Ss)}let ot=null;function ZO(e){if(ot)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",b("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=b("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),xw(o,e),document.body.appendChild(t),eD(t,e.anchor);const s=a=>{const l=a.target;l&&(t.contains(l)||e.anchor.contains(l)||Ml())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&Ml()};document.addEventListener("keydown",i),ot={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function lo(){if(!ot)return;const e=ot.panel.querySelector(".os-widget-picker__list");e&&xw(e,ot.options)}function Ml(){if(!ot)return;document.removeEventListener("pointerdown",ot.onOutsidePointerDown,!0),document.removeEventListener("keydown",ot.onKeyDown),ot.panel.remove();const{onClose:e}=ot.options;ot=null,e?.()}function xw(e,t){e.innerHTML="";const n=new Set(t.enabledIds()),o=t.registry();if(o.length===0){const s=document.createElement("div");s.className="os-widget-picker__empty",s.textContent=b("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="os-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("os-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=le(b("%s (already added)"),s.label):a=le(b("Add %s"),s.label),i.setAttribute("aria-label",a);const l=document.createElement("span");l.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-widget-picker__entry-text";const d=document.createElement("span");if(d.className="os-widget-picker__entry-label",d.textContent=s.label,c.appendChild(d),s.description){const u=document.createElement("span");u.className="os-widget-picker__entry-description",u.textContent=s.description,c.appendChild(u)}if(i.appendChild(c),r){const u=document.createElement("span");u.className="os-widget-picker__entry-status",u.textContent=b("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}const Is=6;function JO(e,t,n){const{width:o,height:s}=t,i=e.top-Is-n.top,r=n.bottom-(e.bottom+Is);let a,l=null;s<=i?a=e.top-Is-s:s<=r?a=e.bottom+Is:i>=r?(l=Math.max(0,i),a=n.top):(l=Math.max(0,r),a=e.bottom+Is);let c=e.right-o;return c=Math.min(c,n.right-o),c=Math.max(c,n.left),{left:c,top:a,maxHeight:l}}function QO(){const e=Sp,{viewport:t}=Tp(),n=t.width>0&&t.height>0?t:{x:0,y:0,width:window.innerWidth,height:window.innerHeight};return{top:n.y+e,right:n.x+n.width-e,bottom:n.y+n.height-e,left:n.x+e}}function eD(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.style.maxHeight="",e.style.visibility="hidden";const o=e.getBoundingClientRect(),s=JO(n,{width:o.width||342,height:o.height||200},QO());e.style.left=`${Math.round(s.left)}px`,e.style.top=`${Math.round(s.top)}px`,s.maxHeight!==null&&(e.style.maxHeight=`${Math.floor(s.maxHeight)}px`),e.style.visibility=""}const yr="os-widgets__card--floating",tD="os-widgets__card--movable",nD="os-widgets__card--resizable",Rw="os-widgets__card--dragging",Mw="os-widgets__card--resizing",oD=160,Ww=80,sD=280,iD=180,uo=20,pn=20,Pw=5,rD=Pw*Pw,aD='input, textarea, select, button, a, [contenteditable="true"]';function cD(e,t,n){const o=document.createElement("div");o.className="os-widgets__card",o.dataset.widgetId=e.id;const s=e.movable===!0,i=e.resizable===!0;s&&o.classList.add(tD),i&&o.classList.add(nD),s?o.appendChild(lD(e,n.onRemove,n.onRedock)):o.appendChild(uD(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(br(o,Bw(t.geometry,t.floatingParent)),o.classList.add(yr)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${gD(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(yr),l=[];if(i)for(const d of hD()){const u=document.createElement("div");u.className=`os-widgets__resize os-widgets__resize--${d}`,u.setAttribute("aria-hidden","true"),u.dataset.dir=d,o.appendChild(u),l.push(pD(o,u,d,e,t,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=fD(o,d,e,t,n))}return{card:o,body:r,dispose:()=>{for(const d of l)try{d()}catch{}if(c)try{c()}catch{}o.remove()}}}function lD(e,t,n){const o=document.createElement("header");o.className="os-widgets__chrome";const s=document.createElement("span");s.className="os-widgets__grip",s.setAttribute("aria-hidden","true"),o.appendChild(s);const i=document.createElement("span");i.className="os-widgets__title",i.textContent=e.label,o.appendChild(i),o.appendChild(dD(e,n));const r=$w(e,t);return o.appendChild(r),o}function dD(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",le(b("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 uD(e,t){const n=$w(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function $w(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",le(b("Remove %s"),e.label)),n.innerHTML=en("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function fD(e,t,n,o,s){let i=null,r=0,a=0,l=0,c=0,d=!1;const u=h=>{if(h.button!==0)return;const m=h.target;m&&m.closest(aD)||(h.preventDefault(),i=h.pointerId,r=h.clientX,a=h.clientY,d=!1,l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0,t.setPointerCapture(i))},f=()=>{if(!e.classList.contains(yr)){const h=o.floatingParent.getBoundingClientRect(),m=e.getBoundingClientRect(),E={x:m.left-h.left,y:m.top-h.top,width:m.width||n.defaultWidth||sD,height:m.height||n.defaultHeight||iD};br(e,E),e.classList.add(yr),s.onLiberate(E),l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(Rw)},p=h=>{if(i===null||h.pointerId!==i)return;const m=h.clientX-r,E=h.clientY-a;if(!d){if(m*m+E*E<rD)return;d=!0,f()}const k=Hw(fo(l+m),fo(c+E),e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${Fw(k.x)}px`,e.style.top=`${Fw(k.y)}px`},g=h=>{if(!(i===null||h.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(Rw),s.onGeometryChanged(Uw(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g)}}function pD(e,t,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const g=E=>{if(E.button!==0||!r()&&!mD(n))return;E.preventDefault(),E.stopPropagation(),a=E.pointerId,l=E.clientX,c=E.clientY;const k=e.getBoundingClientRect(),N=s.floatingParent.getBoundingClientRect();d=k.left-N.left,u=k.top-N.top,f=k.width,p=k.height,t.setPointerCapture(a),e.classList.add(Mw)},h=E=>{if(a===null||E.pointerId!==a)return;const k=E.clientX-l,N=E.clientY-c,M=wD(n,k,N,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${M.x}px`,e.style.top=`${M.y}px`,e.style.width=`${M.width}px`),e.style.height=`${M.height}px`},m=E=>{if(!(a===null||E.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(Mw),r()?i.onGeometryChanged(Uw(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",g),t.addEventListener("pointermove",h),t.addEventListener("pointerup",m),t.addEventListener("pointercancel",m),()=>{t.removeEventListener("pointerdown",g),t.removeEventListener("pointermove",h),t.removeEventListener("pointerup",m),t.removeEventListener("pointercancel",m)}}function hD(){return["n","e","s","w","ne","nw","se","sw"]}function mD(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 Uw(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function gD(e,t){return po(e,t.minHeight??Ww,t.maxHeight??1/0)}function Bw(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Hw(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function fo(e){return Math.round(e/pn)*pn}function Fw(e){const t=Math.floor(e/pn)*pn;return t>=uo?t:Math.min(e,uo)}function Hw(e,t,n,o,s){const i=he(s),r=i.x+uo,a=i.y+uo,l=Math.max(i.x,i.x+i.width-n-uo),c=Math.max(i.y,i.y+i.height-o-uo);return{x:Math.min(Math.max(r,e),l),y:Math.min(Math.max(a,t),c)}}function wD(e,t,n,o,s,i,r,a,l,c){const d=a.minWidth??oD,u=a.minHeight??Ww,f=a.maxWidth??1/0,p=a.maxHeight??1/0,g=he(l),h=g.x+g.width,m=g.y+g.height;let E=o,k=s,N=i,M=r;if((e==="e"||e==="ne"||e==="se")&&(c?N=vr(fo(o+i+t),o+d,Math.min(o+f,h))-o:N=po(i+t,d,Math.min(f,h-o))),e==="w"||e==="nw"||e==="sw"){const S=o+i;if(c)E=vr(fo(o+t),Math.max(0,S-Math.min(f,S)),S-d),N=S-E;else{const $=po(i-t,d,Math.min(f,S));E=o+(i-$),N=$}}if((e==="s"||e==="se"||e==="sw")&&(c?M=vr(fo(s+r+n),s+u,Math.min(s+p,m))-s:M=po(r+n,u,Math.min(p,m-s))),e==="n"||e==="ne"||e==="nw"){const S=s+r;if(c)k=vr(fo(s+n),Math.max(0,S-Math.min(p,S)),S-u),M=S-k;else{const $=po(r-n,u,Math.min(p,S));k=s+(r-$),M=$}}return c||(N=i,E=o),{x:E,y:k,width:N,height:M}}function vr(e,t,n){const o=po(e,t,n),s=Math.floor(o/pn)*pn;if(s>=t)return s;const i=s+pn;return i<=n?i:o}function po(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const Gw="desktop-mode-widgets",zw="desktop-mode-widgets-geometry",jw="desktop-mode-widgets-docked-heights";function Vw(){try{return window.localStorage.getItem(Gw)}catch{return null}}function yD(){const e=Vw();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function _r(e){try{window.localStorage.setItem(Gw,JSON.stringify(e))}catch{}}function bD(){try{const e=window.localStorage.getItem(zw);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=_D(s);i&&(n[o]=i)}return n}catch{return{}}}function Wl(e){try{window.localStorage.setItem(zw,JSON.stringify(e))}catch{}}function vD(){try{const e=window.localStorage.getItem(jw);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 Kw(e){try{window.localStorage.setItem(jw,JSON.stringify(e))}catch{}}function _D(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}}const ED=120,kD="os-inline-loader",qw="os-inline-loader-keyframes";function SD(){return typeof customElements<"u"&&!!customElements.get("os-spinner")}function ID(){if(document.getElementById(qw))return;const e=document.createElement("style");e.id=qw,e.textContent="@keyframes os-inline-loader-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function Yw(){if(SD()){const n=document.createElement("os-spinner");return n.setAttribute("preset","inline"),n.setAttribute("size","20"),n.setAttribute("aria-hidden","true"),n}const e=document.createElement("span");return e.setAttribute("aria-hidden","true"),e.style.cssText=["flex:0 0 auto","width:16px","height:16px","border-radius:50%","border:2px solid currentColor","border-top-color:transparent","opacity:0.7"].join(";"),typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||(ID(),e.style.animation="os-inline-loader-spin 0.7s linear infinite"),e}function AD(e,t={}){const n=t.label??b("Loading…");let o=null,s=!1;const i=()=>{if(s||o||!e.isConnected)return;o=document.createElement("div"),o.className=kD,o.setAttribute("role","status"),o.setAttribute("aria-live","polite"),o.style.cssText=["display:flex","align-items:center","justify-content:center","gap:10px","padding:20px 16px","font-size:13px","color:var(--os-ui-fg-muted,#646970)"].join(";");const l=document.createElement("span");l.textContent=n,o.appendChild(Yw()),o.appendChild(l),e.appendChild(o)},r=t.immediate?null:window.setTimeout(i,ED);t.immediate&&i();const a=()=>{r!==null&&window.clearTimeout(r)};return{done:()=>{s||(s=!0,a(),o?.remove(),o=null)},fail:(l,c)=>{if(s||(s=!0,a(),o||(s=!1,i(),s=!0),!o))return;o.textContent="",o.setAttribute("aria-live","assertive"),o.style.flexDirection="column",o.style.color="var(--os-ui-fg-muted,#646970)";const d=document.createElement("span");if(d.textContent=l,o.appendChild(d),c){const u=document.createElement("button");u.type="button",u.textContent=b("Retry"),u.className="button button-small",u.addEventListener("click",()=>{o?.remove(),o=null,s=!1,c()}),o.appendChild(u)}}}}function Xw(e){const t=e.getBoundingClientRect(),n=getComputedStyle(e),o=l=>parseFloat(l)||0,s=t.top+o(n.borderTopWidth)+o(n.paddingTop),i=t.left+o(n.borderLeftWidth)+o(n.paddingLeft),r=t.bottom-o(n.borderBottomWidth)-o(n.paddingBottom),a=t.right-o(n.borderRightWidth)-o(n.paddingRight);return{top:s,right:a,bottom:r,left:i,width:a-i,height:r-s}}function CD(e){const t=`os.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 LD=["clock"];function TD(){const e=Si();return(e?ki(e)?.recommendedOsSettings.widgets:void 0)??null}const Er=40,ND=12;class OD{constructor(t,n,o){this.override=null,this.mounted=new Map,this.generation=0,this.unwatchPointer=null,this.stackObserver=null,this.root=t,this.pluginUrl=n,this.enabledIds=yD(),this.geometry=bD(),this.dockedHeights=vD(),this.floatingHost=o??t.parentElement??t,this.listEl=document.createElement("div"),this.listEl.className="os-widgets__list",this.root.appendChild(this.listEl),this.addTile=this.buildAddTile(),this.root.appendChild(this.addTile),typeof ResizeObserver=="function"&&(this.stackObserver=new ResizeObserver(()=>this.positionAddTile())),this.paintEmptyState(),this.watchPointerProximity()}visibleIds(){return this.override??this.enabledIds}hydrate(){Vw()===null&&(this.enabledIds=(TD()??LD).filter(t=>!!Rt(t)),_r(this.enabledIds));for(const t of this.visibleIds())this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){if(Rt(t)){if(this.override){if(this.override.includes(t))return;this.override=[...this.override,t],this.mountById(t),this.paintEmptyState(),L(y.WIDGET_ADDED,{id:t});return}this.enabledIds.includes(t)||(this.enabledIds.push(t),_r(this.enabledIds),this.mountById(t),this.paintEmptyState(),L(y.WIDGET_ADDED,{id:t}))}}remove(t){if(this.override){if(!this.override.includes(t))return;this.override=this.override.filter(o=>o!==t),this.unmountById(t),this.paintEmptyState(),L(y.WIDGET_REMOVED,{id:t}),lo();return}const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(_r(this.enabledIds),this.forgetLayout(t),this.unmountById(t),this.paintEmptyState(),L(y.WIDGET_REMOVED,{id:t}),lo())}setEnabledIds(t){const n=[...new Set(t)].filter(o=>!!Rt(o));for(const o of this.enabledIds)n.includes(o)||this.forgetLayout(o);this.enabledIds=n,_r(n),this.setVisibleIds(this.override),lo()}forgetLayout(t){this.geometry[t]&&(delete this.geometry[t],Wl(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],Kw(this.dockedHeights))}getEnabledIds(){return[...this.enabledIds]}getMountedIds(){return Array.from(this.mounted.keys())}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),ZO({anchor:this.addTile,registry:()=>Ka(),enabledIds:()=>[...this.visibleIds()],onAdd:t=>{this.add(t),Ml(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){Rt(t)&&this.visibleIds().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 Rt(t)?(this.enabledIds.includes(t)||this.add(t),!0):!1}setVisibleIds(t){this.override=t?[...t]:null;const n=new Set(this.visibleIds());for(const o of Array.from(this.mounted.keys()))n.has(o)||this.unmountById(o);for(const o of n)this.mounted.has(o)||!Rt(o)||this.mountById(o);this.paintEmptyState()}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t);this.unwatchPointer?.(),this.unwatchPointer=null,this.stackObserver?.disconnect()}mountById(t){const n=Rt(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=cD(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),this.stackObserver?.observe(i.card);const l={id:t,pluginUrl:this.pluginUrl,storage:CD(t)};L(y.WIDGET_MOUNTING,{id:t,container:i.body,ctx:l});const c=u=>{const f=this.mounted.get(t);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,this.positionAddTile(),L(y.WIDGET_MOUNTED,{id:t,container:i.body,ctx:l})};let d;try{d=n.mount(i.body,l)}catch(u){this.handleMountFailure(t,u);return}if(DD(d)){const u=AD(i.body,{label:b("Loading…")});d.then(f=>{u.done(),c(f)},f=>{u.done(),this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,f)});return}c(d)}unmountById(t){const n=this.mounted.get(t);if(n){L(y.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){L(y.SHELL_ERROR,{scope:"widget-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" teardown threw:`,o)}this.generation++,this.stackObserver?.unobserve(n.frame.card),n.frame.dispose(),this.mounted.delete(t)}}handleMountFailure(t,n){const o=this.mounted.get(t);o&&(o.frame.dispose(),this.mounted.delete(t)),L(y.WIDGET_MOUNT_FAILED,{id:t,error:n}),L(y.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="os-widgets__add",t.setAttribute("aria-label",b("Add widget"));const n=document.createElement("span");n.className="os-widgets__add-plus",n.setAttribute("aria-hidden","true"),n.textContent="+";const o=document.createElement("span");return o.className="os-widgets__add-label",o.textContent=b("Add widget"),t.appendChild(n),t.appendChild(o),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.openPicker()}),t}watchPointerProximity(){let t=null,n=0;const o=()=>{t=null,this.positionAddTile()},s=()=>{n||(n=requestAnimationFrame(()=>{n=0,this.positionAddTile()}))},i=c=>{t||(t=Xw(this.root));const d=c.clientX>=t.left-Er&&c.clientX<=t.right+Er&&c.clientY>=t.top-Er&&c.clientY<=t.bottom+Er;this.root.classList.toggle("os-widgets--hovered",d),d&&s()},r=()=>{this.root.classList.remove("os-widgets--hovered")};document.addEventListener("pointermove",i,{passive:!0}),document.documentElement.addEventListener("pointerleave",r),window.addEventListener("resize",o);let a=null;typeof ResizeObserver=="function"&&(a=new ResizeObserver(o),a.observe(this.root),this.root.parentElement&&a.observe(this.root.parentElement));const l=Jo(()=>this.reclampFloating());this.unwatchPointer=()=>{n&&(cancelAnimationFrame(n),n=0),l(),a?.disconnect(),document.removeEventListener("pointermove",i),document.documentElement.removeEventListener("pointerleave",r),window.removeEventListener("resize",o)}}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],Wl(this.geometry));const o=n.frame.card;o.classList.remove("os-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()}reclampFloating(){for(const[t,n]of this.mounted){if(!n.floating)continue;const o=this.geometry[t];if(!o)continue;const s=Bw(o,this.floatingHost);s.x===o.x&&s.y===o.y||(br(n.frame.card,s),this.persistGeometry(t,s))}}persistGeometry(t,n){this.geometry[t]=n,Wl(this.geometry),this.positionAddTile()}positionAddTile(){const t=this.root.getBoundingClientRect();if(!t.height)return;const n=Xw(this.root);let o=this.listEl.offsetTop+this.listEl.offsetHeight;for(const r of this.mounted.values()){if(!r.floating)continue;const a=r.frame.card.getBoundingClientRect();Math.min(a.right,n.right)-Math.max(a.left,n.left)<n.width/2||(o=Math.max(o,a.bottom-t.top+this.root.scrollTop))}const s=n.bottom-t.top+this.root.scrollTop-this.addTile.offsetHeight,i=Math.max(n.top-t.top,Math.min(o+ND,s));this.addTile.style.top!==`${i}px`&&(this.addTile.style.top=`${i}px`)}persistDockedHeight(t,n){!Number.isFinite(n)||n<=0||(this.dockedHeights[t]=n,Kw(this.dockedHeights))}paintEmptyState(){let t=0;for(const n of this.mounted.values())n.floating||t++;this.root.classList.toggle("os-widgets--has-widgets",t>0),this.positionAddTile()}}function DD(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const Zw=se("desktop-mode/window-menu-pages",()=>({pages:new Map}));function Jw(e,t){t.length?Zw.state.pages.set(e,t):Zw.state.pages.delete(e)}function xD(e,t){e.dataset.osLocation=t,e.dataset.osLocationSrc=e.src}const RD=280,MD=220,WD=520,PD=400;function Qw(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function ey(e,t,n){return o=>{const s=Qw(o,n),i=document.createElement("iframe");i.style.width="100%",i.style.height="100%",i.style.border="0",i.setAttribute("src",e.url),typeof e.sandbox=="string"&&e.sandbox!==""&&i.setAttribute("sandbox",e.sandbox),o.style.padding="0",o.appendChild(i);const r=SN(s,i);t.push(r);let a=null,l=null,c=null;const d=()=>{const E=i.isConnected&&i.getClientRects().length>0;if(a&&E){l||(c=We(s)??null),Zn(s,a,{source:"bridge"}),l=We(s)??null;return}l&&(We(s)===l&&Zn(s,c,{source:"config"}),l=null,c=null)};let u;try{u=new URL(e.url,window.location.origin).origin}catch{u=window.location.origin}let f=null;const p=new Promise(E=>{f=E}),g=()=>{if(e.bridge)try{const E=i.contentDocument;if(E&&!E.querySelector("script[data-os-iframe-bridge]")){const k=window.openStationConfig?.iframeBridgeUrl;if(k){const N=E.createElement("script");N.src=k,N.setAttribute("data-os-iframe-bridge","1"),E.head?.appendChild(N)}}}catch{}wS(s),f?.()};i.addEventListener("load",g);const h=E=>{if(!i.contentWindow||E.source!==i.contentWindow||E.origin!==u&&E.origin!==window.location.origin)return;const k=E.data;k&&typeof k=="object"&&typeof k.type=="string"&&k.type.startsWith("os-bridge-")&&window.__openStationConnectionBridge?.routeIncomingFromIframe(k,s),k&&typeof k=="object"&&(k.type==="os-iframe-navigated"||k.type==="os-iframe-location")&&typeof k.url=="string"&&k.url!==""&&xD(i,k.url),k&&typeof k=="object"&&k.type==="os-window-publish"&&typeof k.channel=="string"&&k.channel!==""&&mS(s,k.channel,k.payload),k&&typeof k=="object"&&k.type==="os-content-identity"&&E.origin===window.location.origin&&(a=k.identity??null,d());try{e.onMessage?.(E.data)}catch(N){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",N)}};window.addEventListener("message",h);const m=typeof ResizeObserver=="function"?new ResizeObserver(()=>d()):null;return m?.observe(i),t.push(()=>{window.removeEventListener("message",h),i.removeEventListener("load",g),m?.disconnect(),a=null,d()}),p}}function $D(e,t,n={}){let o;try{const c=new URL(t,window.location.origin);if(c.origin!==window.location.origin)return()=>{};if(Rn(c))return()=>{};c.searchParams.set("openstation_chromeless","1"),o=c.toString()}catch{return()=>{}}e.replaceChildren();const s=[],i=Qw(e,n.windowId??""),r=ey({url:o},s,i)(e);getComputedStyle(e).position==="static"&&(e.style.position="relative");const a=document.createElement("div");a.style.position="absolute",a.style.inset="0",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center";const l=document.createElement("os-spinner");return l.setAttribute("preset",tp),l.setAttribute("size",np),a.appendChild(l),e.appendChild(a),r.then(()=>a.remove()),()=>{for(const c of s)try{c()}catch{}e.replaceChildren()}}function UD(e){return async t=>{const n=t.render;let o=n;const s=[];t.iframeContent&&(n&&typeof console<"u"&&console.warn("[openstation] registerWindow: both `render` and `iframeContent` provided — ignoring `render` and using the iframe shorthand. Drop one."),o=ey(t.iframeContent,s,t.id));const i=t.onClose,r=t.iframeContent?()=>{for(const l of s)try{l()}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??WD,height:t.height??PD,minWidth:t.minWidth??RD,minHeight:t.minHeight??MD,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let BD=0;function FD(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++BD}`,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 l=()=>{if(!a){a=!0;for(const c of r)Ct(c,o)}};for(const[c,d]of i){const u=t[c];u&&(r.push(d),ee(d,o,f=>{const p=f;if(p.windowId!==e)return;const{windowId:g,...h}=p;u(h),c==="closed"&&!s&&l()}))}return l}function HD(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function GD(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&gI(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function ty(e,t){const n=t??{},o=s=>{const i=s?n[s]:void 0;if(!i?.deps||i.deps.length===0)return;const r=[];for(const a of i.deps){const l=n[a];l&&r.push({handle:a,url:l.url??"",before:l.before,after:l.after,l10n:l.l10n,translations:l.translations})}return r.length>0?r:void 0};return e.map(s=>{const i=s.scriptHandle?n[s.scriptHandle]:void 0,r=[];for(const l of s.companionScripts??[]){if(typeof l!="string"){r.push(l);continue}const c=n[l];c?.url&&r.push({scriptUrl:c.url,scriptHandle:l,scriptBefore:c.before,scriptAfter:c.after,scriptL10n:c.l10n,scriptTranslations:c.translations,scriptDeps:o(l)})}const a=(s.tabs??[]).map(l=>{if(typeof l.scriptUrl=="string")return l;const c=l.scriptHandle?n[l.scriptHandle]:void 0;return{...l,scriptUrl:c?.url??"",scriptBefore:c?.before,scriptAfter:c?.after,scriptL10n:c?.l10n,scriptTranslations:c?.translations,scriptDeps:o(l.scriptHandle)}});return{...s,scriptUrl:s.scriptUrl??i?.url??"",scriptBefore:s.scriptBefore??i?.before,scriptAfter:s.scriptAfter??i?.after,scriptL10n:s.scriptL10n??i?.l10n,scriptTranslations:s.scriptTranslations??i?.translations,scriptDeps:s.scriptDeps??o(s.scriptHandle),companionScripts:r,tabs:a}})}function zD(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,a=new Map,l=new Set,c=new Map,d=_=>{const v=Bi(_.id);return v?{width:Math.max(v.width,_.minWidth),height:Math.max(v.height,_.minHeight)}:{width:_.width,height:_.height}},u=_=>{if(i.has(_.templateId))return;if(document.getElementById(_.templateId)){i.add(_.templateId);return}if(!_.templateHtml)return;const v=document.createElement("template");v.id=_.templateId,v.innerHTML=_.templateHtml,document.body.appendChild(v),i.add(_.templateId)},f=_=>{const v=_.styleUrl;if(!v||l.has(v))return;const A=v.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${A}"]`)){const P=document.createElement("link");P.rel="stylesheet",P.href=v,_.styleHandle&&(P.dataset.osStyleHandle=_.styleHandle),document.head.appendChild(P)}if(Array.isArray(_.styleInline))for(const P of _.styleInline){if(typeof P!="string"||P==="")continue;const Z=document.createElement("style");_.styleHandle&&(Z.dataset.osStyleHandle=_.styleHandle),Z.textContent=P,document.head.appendChild(Z)}l.add(v)},p=_=>{f(_)},g=_=>{for(const v of _.companionStyles??[])f(v)},h=new Set,m=(_,v)=>{if(h.has(_))return;h.add(_);const A=[v.scriptTranslations??"",...v.scriptL10n??[],...v.scriptBefore??[],...v.scriptAfter??[]];for(const O of A)typeof O=="string"&&O!==""&&mm(O)},E=(_,v)=>{const A=v.scriptUrl,O=`${_}|${A}`;if(r.has(A))return m(O,v),Promise.resolve();const P=a.get(A);if(P)return P.then(()=>m(O,v));h.add(O);const Z=pe(A,{translations:v.scriptTranslations,l10n:v.scriptL10n,before:v.scriptBefore,after:v.scriptAfter,deps:v.scriptDeps}).catch(V=>{L(y.SHELL_ERROR,{scope:"native-window-script-load",id:_,error:V})}).then(()=>{r.add(A),a.delete(A)});return a.set(A,Z),Z},k=async _=>{g(_);for(const v of _.companionScripts??[])v.scriptUrl&&await E(_.id,v);_.scriptUrl&&await E(_.id,_)},N=async _=>{_.preloadScript&&await k(_)},M=new Set,S=(_,v)=>{if(!_||M.has(_)||r.has(_)||l.has(_))return;M.add(_);const A=document.createElement("link");A.rel="prefetch",A.as=v,A.href=_,document.head.appendChild(A)},$=()=>{const _=navigator.connection;if(!(_?.saveData||/2g$/.test(_?.effectiveType??""))){for(const v of c.values())if(!v.preloadScript){for(const A of v.companionScripts??[])S(A.scriptUrl,"script");S(v.scriptUrl,"script");for(const A of v.companionStyles??[])S(A.styleUrl,"style")}}};let W=!1;const F=()=>{if(W)return;W=!0;const _=()=>{W=!1,$()};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(_,{timeout:4e3}):window.setTimeout(_,1500)},x=_=>async(v,A)=>{v.appendChild(ny(_.templateId)),GD(v,_),await k(_),window.wp?.os?.apps?.refresh?.();const P=HD()[_.id];return P?.(v,A)},q=(_,v)=>{const A=x(_),O=d(_);t.open({id:_.id,baseId:_.id,native:!0,url:`#${_.id}`,title:_.title,icon:_.icon,width:O.width,height:O.height,minWidth:_.minWidth,minHeight:_.minHeight,render:A,autofocus:_.autofocus,ownerHandle:_.ownerHandle||_.scriptHandle,...v?{params:v}:{}})},J=(_,v)=>{const A=x(_),O=d(_);t.openNew({id:_.id,baseId:_.id,native:!0,url:`#${_.id}`,title:_.title,icon:_.icon,width:O.width,height:O.height,minWidth:_.minWidth,minHeight:_.minHeight,render:A,autofocus:_.autofocus,ownerHandle:_.ownerHandle||_.scriptHandle,...v?{params:v}:{}})},X=(_,v,A)=>{const O=x(_),P=d(_);t.openNew({id:v,baseId:_.id,native:!0,url:`#${_.id}`,title:_.title,icon:_.icon,width:P.width,height:P.height,minWidth:_.minWidth,minHeight:_.minHeight,render:O,autofocus:_.autofocus,ownerHandle:_.ownerHandle||_.scriptHandle,...A})},T=async _=>{if(!s.has(_.id)){if(_.placement==="none"){u(_),p(_),await N(_),s.add(_.id);return}u(_),p(_),await N(_),n({id:_.id,title:_.title,icon:_.icon,windowId:_.id,navKind:_.navKind==="control"?"control":"app",defaultPlacement:"rail",order:_.dockOrder,placeable:_.placeable===!0,isOpen:()=>!!t.getById(_.id),onOpen:()=>q(_)}),L(y.DOCK_ITEM_APPENDED,{id:_.id}),s.add(_.id)}},D=_=>{s.has(_)&&(o(_),s.delete(_),c.delete(_))},K=_=>{try{const v=new URL(_,window.location.origin),A=[v.pathname.split("/").pop()??""];for(const O of["post_type","taxonomy","page"]){const P=v.searchParams.get(O);P&&A.push(`${O}=${P}`)}return A.join("&")}catch{return _}},G=_=>`desktop-mode/menu-pages/${_}`,ne=_=>{const v=G(_.id),A=_.menuPages??[];if(Jw(_.id,A),A.length===0){Ta(v);return}const O=A.map(Z=>({tab:Z.id,key:K(Z.page)})),P=Z=>O.find(V=>V.key===K(Z.href))?.tab??null;yt({id:v,nativeWindowId:_.id,matches:(Z,V)=>P(V)!==null,params:(Z,V)=>{const ge=P(V);return ge?{tab:ge}:void 0}})},ce=async _=>{const v=new Set;for(const A of _)v.add(A.id),ne(A),c.set(A.id,A);for(const A of Array.from(s))v.has(A)||(D(A),Ta(G(A)),Jw(A,[]));for(const A of _)s.has(A.id)||await T(A);F()},R=(_,v={})=>{const A=c.get(_);return A?(Se.publish("os/open-requested",{windowId:_,source:v.source??"api"}),q(A,v.params),!0):!1},C=(_,v={})=>{const A=c.get(_);return A?(Se.publish("os/open-requested",{windowId:_,source:v.source??"api"}),J(A,v.params),!0):!1},U=(_,v,A)=>{const O=c.get(v);return O?(X(O,_,A),!0):!1};return ee(y.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",_=>{const v=_,A=v?.windowId,O=v?.width,P=v?.height;if(!A||typeof O!="number"||typeof P!="number")return;const Z=t.getById(A);if(!Z||Z.state!=="normal")return;const V=Z.config.baseId||Z.id;Eh(V,{width:O,height:P}),Z.element&&kh(V,{x:Z.element.offsetLeft,y:Z.element.offsetTop})}),ee(y.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",_=>{const v=_?.windowId;if(!v)return;const A=t.getById(v);if(!A||A.state!=="normal"||!A.element)return;const O=A.config.baseId||A.id;Eh(O,{width:A.element.offsetWidth,height:A.element.offsetHeight}),kh(O,{x:A.element.offsetLeft,y:A.element.offsetTop})}),ee(y.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",_=>{const v=_?.windowId;if(!v||Jt())return;const A=t.getById(v);if(!A)return;const O=A.config.baseId||A.id,P=c.get(O),Z=P?{width:P.width,height:P.height}:{width:A.config.width,height:A.config.height};Sh(O,"maximized",Z)}),ee(y.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",_=>{const v=_?.windowId;if(!v)return;const A=t.getById(v);if(!A)return;const O=A.config.baseId||A.id;Sh(O,null)}),{sync:ce,openById:R,openNewById:C,restoreById:U,loadScriptById:async _=>{const v=c.get(_);return v?(await k(v),!0):!1},prewarmById:async(_,v={})=>{const A=c.get(_);return!A||t.getById(_)?!1:(await k(A),window.wp?.os?.apps?.prewarm?.(_,v.params??{})===!0)}}}function ny(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(`[openstation] cloneTemplate: no <template> found for ${typeof e=="string"?`#${e}`:"<reference>"}`);return t.content.cloneNode(!0)}function kr(e){const t=window.wp?.os,n=window.openStationConfig,o=t?.config?.adminUrl??n?.adminUrl;if(!o)return null;const s=t?.getMenuItems?.()??n?.dockItems??[],i=fe(e,o);return s.find(r=>fe(r.url,o)===i||(r.submenu??[]).some(a=>fe(a.url,o)===i))??null}const oy="os-icon__badge",As=new Map,Cs=new Map;function jD(e){return Math.max(0,Math.floor(Number(e)||0))}function sy(e,t){if(!e)return;const n=cy(e);if(!n)return;const o=jD(t),s=As.get(e)??0;o!==s&&(o===0?As.delete(e):As.set(e,o),ly(n,o),Se.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),L(y.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function VD(e){sy(e,0)}function KD(e){return As.get(e)??0}function qD(e,t){if(e){if(!t){Cs.delete(e);return}Cs.get(e)!==t&&(Cs.set(e,t),XD(e,t),Se.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function iy(e){return Cs.get(e)??""}function YD(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function XD(e,t){const o=cy(e)?.querySelector(".os-icon__image");if(o){const s=ln(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${YD(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const Pl={setBadge:sy,clearBadge:VD,getBadge:KD,setArt:qD,getArt:iy};function ZD(e){return!e||e.length===0?"":`${Si()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let ry="";function ay(e,t,n){const o=ZD(t);if(o===ry&&e.querySelector(":scope > .os-icons"))return;ry=o;const s=e.querySelector(":scope > .os-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="os-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",b("Desktop icons"));const r=[...t].sort((l,c)=>{const d=l.pinned?0:1,u=c.pinned?0:1;return d-u}),a=new Map;for(const l of r){const c=QD(l,n),d=As.get(l.id)??0;d>0&&ly(c,d);const u=Cs.get(l.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(ln(u,{className:"os-icon__image",title:""}))}i.appendChild(c),a.set(l.id,c)}e.appendChild(i),L(y.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(l=>l.id),container:i,tiles:a})}function cy(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${JD(e)}"]`):null}function ly(e,t){const n=e.querySelector(`:scope > .${oy}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=le(Qt("%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=oy,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function JD(e){const t=window.CSS;return t?.escape?t.escape(e):e}function QD(e,t){const n=document.createElement("button");n.type="button",n.className=e.pinned?"os-icon os-icon--pinned":"os-icon",n.dataset.iconId=e.id,e.pinned&&(n.dataset.pinned="1"),n.setAttribute("role","listitem"),n.setAttribute("aria-label",e.title);const o=ln(e.icon,{title:e.title,className:"os-icon__image",slot:Vn(e.id)});n.appendChild(o);const s=document.createElement("span");return s.className="os-icon__label",s.textContent=e.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),L(y.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),ex(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),ym({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function ex(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(to(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=kr(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,selfLabel:s?.selfLabel,multi:!!s?.multi})}catch{}}}function tx(e){const t=[],n=new Map,o=s=>{t.push(s),n.set(s.id,s)};for(const s of e.menuItems)n.has(s.id)||o({id:s.id,kind:s.isCore?"core":"plugin",title:s.title,icon:s.icon,windowId:e.resolveMenuWindowId?.(s)||void 0,menu:s});for(const s of e.systemTiles){const i=n.get(s.item.id);if(i){i.tile=s.item;continue}const a=(s.item.submenu??[]).map(l=>l.windowId).filter(l=>!!l);o({id:s.item.id,kind:s.kind,title:s.item.title,icon:s.item.icon,locked:s.locked,defaultPlacement:s.item.defaultPlacement,windowId:s.item.windowId,answersFor:a.length>0?a:void 0,order:s.item.order,tile:s.item})}for(const s of e.icons){const i=s.window?n.get(s.id)??n.get(s.window):n.get(s.id);if(i){i.entry=s,s.window&&(i.windowId=s.window);continue}o({id:s.id,kind:"app",title:s.title,icon:s.icon,windowId:s.window||void 0,entry:s})}return t}const dy="os-side-dock";function nx(e,t,n,o,s="bottom"){let i=t,r=s,a=n,l=o??[],c=null,d=null,u=null,f=null,p=null;const g=new Map;let h=[],m=Sm({items:[],config:{placement:{},order:[]},layout:i,openWindows:[]});const E=()=>e.getSettings?.()??{navPlacement:{},navOrder:[]},k=()=>{const v=e.windowManager.getActiveDesktopId(),A=[],O=new Set;for(const P of e.windowManager.getAll()){if((P.config.desktopId||v)!==v)continue;const Z=P.config.baseId||P.id;O.has(Z)||(O.add(Z),A.push({id:Z,title:P.config.title||Z,icon:P.config.icon||"dashicons-admin-generic",fromAdminUrl:P.config.native!==!0}))}return A},N=v=>v.windowId?v.windowId:$o(v.url)??fe(v.url,e.adminUrl),M=()=>{const v=[];for(const O of g.values())v.push({item:O,kind:O.navKind??"app",locked:O.locked});h=tx({menuItems:a,systemTiles:v,icons:l,resolveMenuWindowId:N});const A=E();m=Sm({items:h,config:{placement:_A(A.navPlacement,h,e.getWorkspaceProfile?.()??null),order:A.navOrder},layout:i,openWindows:k()})},S=v=>v.tile?{type:"system",item:v.tile}:v.menu?{type:"menu",item:v.windowId?{...v.menu,windowId:v.windowId}:v.menu}:{type:"menu",item:{id:v.id,title:v.title,icon:v.icon,url:v.entry?.url||"",windowId:v.windowId,badge:0,submenu:[],isCore:!1}},$=v=>!!v.entry||!!v.windowId||!!v.menu?.url,W=(v,A)=>v.entry?v.entry:{id:v.id,title:v.title,icon:v.icon,window:v.windowId??"",url:v.menu?.url||"",position:2e3+A},F=v=>({core:(v.core??[]).map(S),apps:(v.apps??[]).map(S),controls:(v.controls??[]).map(S)}),x=(v,A,O)=>{if(!v)return;if(v.setZones){v.setZones(A),O.clear();for(const V of ft)for(const ge of A[V])ge.type==="system"&&O.add(ge.item.id);return}const P=[],Z=new Set;for(const V of ft)for(const ge of A[V])ge.type==="menu"?P.push(ge.item):Z.add(ge.item.id);v.replaceItems(P);for(const V of Array.from(O))Z.has(V)||(v.removeSystemItem(V),O.delete(V));for(const V of ft)for(const ge of A[V])ge.type==="system"&&!O.has(ge.item.id)&&(v.appendSystemItem(ge.item),O.add(ge.item.id))},q=new Set,J=new Set,X=()=>{M(),x(c,F(m.dock),q),x(d,{core:m.sidebar.map(S),apps:[],controls:[]},J),e.renderIcons(m.desktop.filter($).map(W))},T=()=>Array.from(m.ephemeral).sort().join(","),D=()=>{const v=document.getElementById(dy);if(v)return v;const A=document.createElement("nav");return A.id=dy,A.className="os-dock",A.setAttribute("role","toolbar"),A.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(A,e.shellBody.firstChild),A},K=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},G=()=>{if(c){try{c.destroy()}catch(v){L(y.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:v})}c=null,u=null}if(d){try{d.destroy()}catch(v){L(y.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:v})}d=null,f=null}q.clear(),J.clear()},ne=v=>{const A=Da();if(!A)return L(y.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return A.mount(v)}catch(O){if(L(y.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:A.id,error:O}),A===Qi)return null;try{return Qi.mount(v)}catch{return null}}},ce=(v,A)=>({container:v,items:[],fullMenu:a.slice(),fullSystemTiles:h.filter(O=>!!O.tile).filter(O=>R(O.id)).map(O=>O.tile),orientation:A,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:O=>{if(to(O.url)||Be(O.url))return;const P=fe(O.url,e.adminUrl);e.windowManager.open({id:P,baseId:P,url:O.url,parentUrl:O.url,title:O.title,icon:O.icon.startsWith("dashicons-")?O.icon:"dashicons-admin-generic",submenu:O.submenu,selfLabel:O.selfLabel,multi:!!O.multi})},openSubmenuPick:(O,P)=>{to(P.url)||Be(P.url,{newInstance:!0})||e.windowManager.openNew({id:fe(P.url,e.adminUrl),baseId:fe(O.url,e.adminUrl),url:P.url,parentUrl:O.url,title:O.title,icon:O.icon.startsWith("dashicons-")?O.icon:"dashicons-admin-generic",submenu:O.submenu,selfLabel:O.selfLabel,multi:!!O.multi})},openSystemItem:O=>O.onOpen()}),R=v=>{for(const A of ft)if(m.dock[A].some(O=>O.id===v))return!0;return m.sidebar.some(A=>A.id===v)},C=()=>i==="classic"?"bottom":r,U=()=>{G(),M(),i==="classic"?(p=D(),d=ne(ce(p,"left")),f=Lm(d)):K(),c=ne(ce(e.bottomDockEl,C())),u=Lm(c),X()},B=()=>{document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:C(),primary:u,side:f}}))},z={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:v=>{v!==i&&(i=v,e.shellRoot.setAttribute("data-os-layout",v),U(),B())},getDockPlacement:()=>r,setDockPlacement:v=>{if(v===r)return;const A=C();r=v,C()!==A&&(U(),B())},applyDockItems:v=>{a=v,X()},applyDesktopIcons:v=>{l=v??[],X()},appendSystemTile:v=>{g.set(v.id,v),X()},removeSystemTile:v=>{g.delete(v)&&X()},listSystemTiles:()=>Array.from(g.values()).map(v=>({id:v.id,title:v.title,icon:v.icon,navKind:v.navKind??"app",placeable:v.placeable===!0,locked:v.locked===!0})),getSystemTile:v=>g.get(v)??null,getMenuItems:()=>a.slice(),getNavItems:()=>h.slice(),getNav:()=>m,refresh:X,destroy:()=>{G(),K()}};for(const v of["os-window-opened","os-window-closed"])document.addEventListener(v,()=>{const A=T();M(),T()!==A&&X()});e.shellRoot.setAttribute("data-os-layout",i),U();let _=Da()?.id??null;return mk(()=>{const v=Da()?.id??null;v!==_&&(_=v,U(),B())}),z}const uy=200,ho=new Map;function fy(e){const t=ho.get(e.id);if(t&&t.el.isConnected&&t.leaving===void 0)return;mo(e.id);const n=()=>{mo(e.id),e.onCancel?.()},o=l=>{l.key==="Escape"&&n()};document.addEventListener("keydown",o);const s=document.createElement("div");s.id=e.id,s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),s.style.cssText=["position:fixed","inset:0","z-index:9999","display:flex","box-sizing:border-box",...e.layerStyle].join(";");const i=document.createElement("div");i.setAttribute("aria-hidden","true"),i.style.cssText=["position:absolute","inset:0",...e.scrimStyle].join(";");const r=document.createElement("div");r.style.cssText=["position:relative","display:flex","align-items:center","gap:12px","width:100%","box-sizing:border-box","font-size:14px","font-family:inherit",...e.cardStyle].join(";");const a=document.createElement("span");a.textContent=e.label,r.appendChild(Yw()),r.appendChild(a),s.appendChild(i),s.appendChild(r),s.addEventListener("click",l=>{l.target instanceof Node&&r.contains(l.target)||n()}),document.body.appendChild(s),ho.set(e.id,{el:s,onKey:o})}function mo(e,t=0){const n=ho.get(e);if(n&&t>0){if(n.leaving!==void 0)return;document.removeEventListener("keydown",n.onKey);const{el:o}=n;o.style.pointerEvents="none",o.style.transition=`opacity ${t}ms linear`,o.style.opacity="0",n.leaving=window.setTimeout(()=>{o.remove(),ho.get(e)===n&&ho.delete(e)},t);return}n&&(window.clearTimeout(n.leaving),document.removeEventListener("keydown",n.onKey),n.el.remove(),ho.delete(e)),document.getElementById(e)?.remove()}const py="os-ai-loading";function ox(e){fy({id:py,label:b("Starting the command palette…"),onCancel:e,layerStyle:["align-items:flex-start","justify-content:center","padding-top:clamp(60px,16vh,180px)","padding-inline:16px"],scrimStyle:["background-color:var(--os-ui-scrim,rgba(0,0,0,0.36))","background-image:var(--os-ui-scrim-image,none)","background-repeat:var(--os-ui-scrim-image-repeat,repeat)","background-size:var(--os-ui-scrim-image-size,auto)","background-position:var(--os-ui-scrim-image-position,center)","backdrop-filter:blur(8px) saturate(0.75)","-webkit-backdrop-filter:blur(8px) saturate(0.75)"],cardStyle:["max-width:600px","padding:20px 22px","border-radius:16px","background-color:var(--os-ai-panel-bg,var(--os-ui-surface,rgba(255,255,255,0.97)))","color:var(--os-ui-fg,#1d2327)","font-family:var(--os-ui-font,inherit)","box-shadow:0 0 0 1px var(--os-ui-border,rgba(0,0,0,0.07)),0 4px 16px rgba(0,0,0,0.12),0 24px 64px rgba(0,0,0,0.22)"]})}function $l(e=!1){mo(py,e?uy:0)}function sx(e){return window.openStationCreateAiAssistant?Promise.resolve(window.openStationCreateAiAssistant):new Promise((t,n)=>{const o=document.querySelector('script[data-os-ai="1"]'),s=()=>{const r=window.openStationCreateAiAssistant;if(!r){document.querySelector('script[data-os-ai="1"]')?.remove(),n(new Error("[openstation] ai-assistant bundle loaded but did not register openStationCreateAiAssistant"));return}t(r)};if(o){window.openStationCreateAiAssistant?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.osAi="1",i.addEventListener("load",s),i.addEventListener("error",()=>{i.remove(),n(new Error("failed to load ai-assistant bundle"))}),document.head.appendChild(i)})}class ix{constructor(t,n){this._real=null,this._loadPromise=null,this._pendingAsk=null,this._runtime="idle",this._intendOpen=!1,this.ask=(...o)=>this._ensure().then(s=>s.ask(...o)),this._config=t,this._scriptUrl=n}_ensure(){if(this._loadPromise)return this._real&&this._loadPaletteRuntime(this._real),this._loadPromise;rr("desktop-mode-ai-assistant");const t=sx(this._scriptUrl).then(n=>{const o=n(this._config);return this._pendingAsk&&o.attachAsk(this._pendingAsk),this._real=o,o});return this._loadPromise=t,t.catch(()=>{this._loadPromise===t&&(this._loadPromise=null)}),this._loadPromise.then(n=>this._loadPaletteRuntime(n),()=>{}),this._loadPromise}_loadPaletteRuntime(t){this._runtime==="idle"&&(this._runtime="loading",t.setBaselineLoading(!0),XO().then(()=>{this._runtime="ready"},n=>{this._runtime="idle",console.warn("[openstation] command-palette runtime failed to load",n)}).finally(()=>t.setBaselineLoading(!1)))}open(){this._intendOpen=!0,this._real||ox(()=>this.close()),this._ensure().then(t=>{this._intendOpen&&t.open(),$l(!0)}).catch(t=>{this._intendOpen=!1,$l(),console.warn("[openstation] command palette failed to load",t)})}close(){this._intendOpen=!1,$l(),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 hy=e=>!e||typeof e!="object"?!1:e.name==="AbortError",rx=e=>{if(!e)return[];const t=oN();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}}):[]},ax=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 cx(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 lx(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function dx(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",l=r.restNonce??"";if(!a||!l)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Ae(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":l},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw hy(c)?c:new Error(`[openstation] wp.os.ai.ask: network error — ${String(c?.message??c)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",l=sN(r);if(!l)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??e.fallbackContext();let d;try{d=await Promise.resolve(l.run(a,c))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:d}},o=async(s,i,r,a,l,c)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:lx(a)}};l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);let u;try{u=await t(d,c)}catch(g){if(hy(g))throw g;return null}if(!u.ok)return null;const f=await u.json().catch(()=>({}));return(typeof f.message=="string"?f.message.trim():"")!==""?f.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("[openstation] wp.os.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 l=rx(r.tools),c=ax(r.systemPrompt),d={query:a};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),l.length>0&&(d.command_tools=l),c&&(d.system_prompt_text=c.text,d.system_prompt_mode=c.mode);const u=await t(d,r.signal);if(!u.ok){const k=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[openstation] wp.os.ai.ask: HTTP ${u.status} — ${k.message??u.statusText}`)}const f=await u.json();if(f.answer_type!=="tool_call"||!f.tool)return{answer_type:f.answer_type,message:f.message??"",entity:f.entity??null,admin_links:f.admin_links??null,request_id:f.request_id,continue:f.continue??null};const p=await n(f,r);if(!p.ok)return p.response;const{slug:g,args:h,result:m}=p;let E=cx(f.message,m);if(r.followUp===!0){const k=await o(a,g,h,m,c,r.signal);k!==null&&(E=k)}return{answer_type:"tool_call",message:E,entity:null,admin_links:null,toolCall:{slug:g,args:h,result:m},request_id:f.request_id}}}const st=se("openstation/trash-optimistic",()=>({changes:new Map,reconcile:new Set})),ux=e=>`${e.type}:${e.id}`;function my(e){return{subtitle:"",mime:"",preview:"",icon:"",deleted_at:new Date().toISOString(),deleted_by:"",deleted_by_id:0,can_restore:!1,can_purge:!1,edit_link:"",...e}}function go(e){const t=e.file,n=t.type==="shortcut"?"shortcut":"placement";return my({id:t.type==="folder"?Number(t.ref):e.id,type:t.type==="folder"?"folder":n,title:t.title,icon:t.icon,preview:t.previewUrl})}function fx(){return Array.from(st.state.changes.values())}function px(e,t){const n=st.subscribe(e);return()=>{n()}}function hn(e,t="in"){const n=ux(e);if(st.state.changes.get(n)?.pending)return null;const o={item:e,direction:t,pending:!0};return st.state.changes.set(n,o),st.notify(),{async finish(s){st.state.changes.get(n)!==o||!o.pending||(o.pending=!1,s&&(st.notify(),await Promise.allSettled(Array.from(st.state.reconcile,async i=>i()))),st.state.changes.get(n)===o&&(st.state.changes.delete(n),st.notify()))}}}const gy="[os-bin badge]";function pt(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(gy,...e)}catch{}}function Sr(...e){console.warn(gy,...e)}const Ls="desktop-mode-recycle-bin",hx="openstation_recycle_bin_seen_ts";function mx(){return window.wp?.os}const ye=se("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function Ts(e){const t=Math.max(0,Math.floor(e)),n=ye.state.current;ye.state.current=t,pt("setRecycleBinCount",{prev:n,next:t}),Ir(t)}function wy(e){Ts(ye.state.current+e)}function gx(){return ye.state.current}function Ir(e){const t=fx().filter(i=>i.pending),o=e+t.reduce((i,r)=>i+(r.direction==="in"?1:-1),0)>0?ye.state.fullArt:ye.state.emptyArt;if(pt("paintIconState",{count:e,full:e>0,hasArt:!!o}),!o)return;const s=mx();s?.dock?.setArt?.(Ls,o),s?.taskbar?.setArt?.(Ls,o),s?.icons?.setArt?.(Ls,o)}function wx(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;ye.state.emptyArt=String(o?.recycleBinIconEmpty??""),ye.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;pt("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:ye.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)||Sr("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),ye.state.started){Ts(n);return}ye.state.started=!0,ye.state.countUrl=t,ye.state.seenTs=Date.now(),Ts(n),yx(),bx(),px(()=>Ir(ye.state.current)),vx(),_x(),Ex()}function yx(){ee(y.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===Ls&&Ir(ye.state.current)})}function bx(){ee(y.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(Ls)&&Ir(ye.state.current)})}function vx(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":wy(+r);break;case"untrashed":case"deleted":wy(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])co(`os.${s}.changed`,e)}function _x(){const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;if(!n||n.type!=="os-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=ye.state.seenTs){pt("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:ye.state.seenTs});return}pt("postMessage triggers refetch",{ts:o,prevSeenTs:ye.state.seenTs}),ye.state.seenTs=o,kx()})}function Ex(){const e=window.jQuery;if(!e){Sr("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}pt("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[hx]=ye.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;pt("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>ye.state.seenTs&&(ye.state.seenTs=o.ts),typeof o.count=="number"&&Ts(o.count))})}async function kx(){if(!ye.state.countUrl){pt("refetchCount: no countUrl, skip");return}pt("refetchCount: hitting",ye.state.countUrl);try{const e=await Ae(ye.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}},{silent:!0,source:"desktop-mode/recycle-bin"});if(!e.ok){Sr("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();pt("refetchCount: response",t),typeof t.count=="number"&&Ts(t.count)}catch(e){Sr("refetchCount: fetch failed",e)}}const Sx="desktop-mode-os-settings",Ix="desktop-mode-recycle-bin";function Ax(e){const t=Tx();t&&t.addFilter("os.dock.peek-card-content","desktop-mode/built-in-peek-renderers",(n,o)=>{const s=o,i=s.window.id;return i===Sx?Cx():i===Ix?Lx(s,e.getRecycleBinCount):n})}function Cx(e){const t=document.createElement("span");t.className="os-dock-peek__card-body os-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="os-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="os-dock-peek__os-subtitle",o.textContent=b("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="os-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`os-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function Lx(e,t){const n=document.createElement("span");n.className="os-dock-peek__card-body os-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="os-dock-peek__bin-stage";const i=document.createElement("span");i.className="os-dock-peek__bin-stack";for(let l=0;l<3;l++){const c=document.createElement("span");c.className="os-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="os-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="os-dock-peek__bin-label",o===0?a.textContent=b("Trash — empty"):o===1?a.textContent=b("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function Tx(){return window.wp?.hooks??null}const Ns="desktop-mode-bug-report",Nx="WordPress",Ox="openstation",yy=6e3;function Dx(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="os-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="os-bug-report__intro",n.textContent=b("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(xx()),t.appendChild(Rx("title",b("Title"),{placeholder:b("A short summary"),required:!0})),t.appendChild(by("description",b("What happened? What did you expect?"),{placeholder:b("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(by("steps",b("Steps to reproduce (bug only)"),{placeholder:b("One step per line"),rows:4}));const o=Mx();t.appendChild(o);const s=document.createElement("div");s.className="os-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="os-bug-report__submit",i.textContent=b("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=b("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const l=Px(t);if(!l.title.trim()||!l.description.trim()){Wx(t,b("Title and description are both required."));return}const c=$x(l);window.open(c,"_blank","noopener")}),e.appendChild(t)}function xx(){const e=document.createElement("div");e.className="os-bug-report__field os-bug-report__field--type";const t=document.createElement("span");t.className="os-bug-report__label",t.textContent=b("Type"),e.appendChild(t);const n=document.createElement("div");n.className="os-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:b("Bug"),checked:!0},{value:"feature",label:b("Feature request")},{value:"question",label:b("Question")}];for(const s of o){const i=document.createElement("label");i.className="os-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 Rx(e,t,n={}){const o=document.createElement("div");o.className="os-bug-report__field";const s=document.createElement("label");s.className="os-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("input");return i.type="text",i.name=e,i.className="os-bug-report__input",n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function by(e,t,n={}){const o=document.createElement("div");o.className="os-bug-report__field";const s=document.createElement("label");s.className="os-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("textarea");return i.name=e,i.className="os-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 Mx(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=b("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=_y(vy()),e.appendChild(n),e}function Wx(e,t){let n=e.querySelector(".os-bug-report__error");n||(n=document.createElement("div"),n.className="os-bug-report__error",n.setAttribute("role","alert"),e.prepend(n)),n.textContent=t}function Px(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 $x(e){const t=Ux(e.type),n=Bx(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/${Nx}/${Ox}/issues/new?${o.toString()}`}function Ux(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function Bx(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(_y(vy())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(`
38 `);return n.length>yy&&(n=n.slice(0,yy)+`
39
40 …(truncated to fit GitHub URL length limit)`),n}function vy(){const e=window.wp?.os?.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 _y(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(`
41 `)}let mn=null,Ey=!1,ky=!1,Sy=!1,Ul=null,Os=!1,Bl=[],gn="pending";const Fx=5e3,Hx=3e3;function Gx(e,t,n){if(ky)return;ky=!0;const o=typeof t.shellBuild=="string"?t.shellBuild:"",s=(r,a)=>{jx(r).then(l=>{if(!(o!==""&&l!==""&&l!==o)){a&&Iy(r);return}a&&(Ul=r),!(Sy||!n)&&(Sy=!0,n({current:o,served:l}))})},i=r=>{!r||typeof r.addEventListener!="function"||r.addEventListener("statechange",()=>{r.state==="installed"&&navigator.serviceWorker.controller&&s(r,!0)})};e.waiting&&navigator.serviceWorker.controller&&s(e.waiting,!0),i(e.installing??null),typeof e.addEventListener=="function"&&e.addEventListener("updatefound",()=>{i(e.installing??null)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{if(Ul=null,Os){Os=!1;const a=Bl;Bl=[];for(const l of a)l();return}const r=navigator.serviceWorker.controller;r&&s(r,!1)})}function Iy(e){Os=!0;try{e.postMessage({type:"os-sw-skip-waiting"})}catch{Os=!1}}function zx(){const e=Ul;return e?new Promise(t=>{let n=!1;const o=()=>{n||(n=!0,window.clearTimeout(s),t())},s=window.setTimeout(o,Hx);Bl.push(o),Iy(e),Os||o()}):Promise.resolve()}function jx(e){return new Promise(t=>{let n=!1,o=0;const s=r=>{const a=r.data;a&&a.type==="os-sw-build"&&i(typeof a.shellBuild=="string"?a.shellBuild:"")},i=r=>{n||(n=!0,window.clearTimeout(o),navigator.serviceWorker.removeEventListener("message",s),t(r))};o=window.setTimeout(()=>i(""),Fx),navigator.serviceWorker.addEventListener("message",s);try{e.postMessage({type:"os-sw-get-build"})}catch{i("")}})}const Vx=5*6e4;let Ay=null,Fl=0;function Kx(e){if(Ay)return;Fl=Date.now();const t=()=>{if(typeof document<"u"&&document.visibilityState==="hidden")return;const n=Date.now();if(!(n-Fl<Vx)){Fl=n;try{e.update().catch(()=>{})}catch{}}};document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),Ay=()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t)}}const qx=["/desktop-mode/sw.js"];function Yx(e,t){if(e===t.swUrl||e===t.swFallbackUrl)return!0;try{const n=new URL(e);return n.pathname.endsWith("/openstation/sw.js")||n.searchParams.has("openstation_sw")?!0:qx.some(o=>n.pathname.endsWith(o))}catch{return!1}}function Cy(){const e=window.openStationConfig?.pwa?.swConfig;Zx({adminAssetCache:e?.adminAssetCache===!0,windowPrewarm:e?.windowPrewarm===!0})}async function Xx(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return gn="unsupported",null;if(mn||Ey)return mn;if(!t.forceReplace){const s=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(i=>{const r=i.active?.scriptURL??i.installing?.scriptURL??"";return r!==""&&!Yx(r,e)});if(s)return gn="foreign-sw",typeof console<"u"&&console.warn("[openstation] another service worker is already registered ("+s.scope+"); skipping openstation SW. Set openstation_pwa_force_replace_sw=true to override."),null}const n=async o=>navigator.serviceWorker.register(o,{scope:e.swScope||"/",updateViaCache:"none"});try{try{mn=await n(e.swUrl)}catch(o){if(!e.swFallbackUrl||e.swFallbackUrl===e.swUrl)throw o;mn=await n(e.swFallbackUrl)}return gn="registered",Gx(mn,e,t.onShellUpdated),Kx(mn),Cy(),navigator.serviceWorker.addEventListener("controllerchange",Cy),mn}catch(o){return Ey=!0,gn="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",o),null}}function Zx(e){try{navigator.serviceWorker?.controller?.postMessage({type:"os-sw-config",...e})}catch{}}function Jx(){return gn}const Qx="os-pwa-install";function Ly(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Ty(){if(Ly())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 zt=null;function eR(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(),zt=s}function o(){zt=null,t({message:le(b("Installed %s as an app."),e)})}}function tR(e,t){return{id:Qx,title:b("Install web app"),icon:"dashicons-download",onOpen:()=>{nR(e,t)}}}async function nR(e,t){if(zt){const n=zt;zt=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:b("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await Ty()){t({message:le(b("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(Jx()==="foreign-sw"){t({message:b("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the openstation_pwa_force_replace_sw filter to true.")});return}t({message:b("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 oR(){if(!zt)return"unavailable";const e=zt;zt=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function sR(){Promise.resolve().then(()=>qT).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function iR(e,t,n){if(!e.pwa)return;gg(e.pwa),eR(e.pwa.appName||"WordPress",t);const o=n?()=>{t({message:b("A new version of OpenStation is available."),action:{label:b("Reload"),onClick:()=>{zx().then(()=>n())}},persistent:!0,dismissible:!0})}:void 0;Xx(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw,onShellUpdated:o})}const Ds=se("desktop-mode/drag-bridge-resolvers",()=>({byKind:new Map}));function rR(e,t){return Ds.state.byKind.set(e,t),()=>{Ds.state.byKind.get(e)===t&&Ds.state.byKind.delete(e)}}function aR(e){return Ds.state.byKind.has(e.kind)}async function cR(e){const t=Ds.state.byKind.get(e.kind);if(!t)return e;try{return await t(e)}catch(n){return console.error("[openstation] bridge payload resolver threw:",n),null}}const wo={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function lR(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function dR(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function uR(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function fR(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 pR{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(lR(n)){this._startDrag(n.payload);return}if(dR(n)){this._endDrag();return}if(uR(n)&&this._payload&&t.source)try{t.source.postMessage({type:"os-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=fR(t);this._payload=n,document.dispatchEvent(new CustomEvent(wo.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(wo.END,{detail:{payload:t}}))}}class hR{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("os-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 mR="os-drag-ghost",Ny="os-drag-ghost--accept",Oy="os-drag-ghost--reject",gR="os-drag-hint",Dy="os-drag-hint--accept",xy="os-drag-hint--reject",Ry="os-drag-hint--neutral",wR=16,yR=18;function bR(e,t,n){const o=IR(e),s=e.ghost?.offsetX??AR(e.source),i=e.ghost?.offsetY??CR(e.source);o.classList.add(mR),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=_R(e),a=r?vR():null;a&&document.body.appendChild(a);const l={get element(){return o},moveTo(c,d){o.style.transform=`translate3d(${c-s}px, ${d-i}px, 0)`,a&&(a.style.transform=`translate3d(${c+wR}px, ${d+yR}px, 0)`)},setMode(c,d){o.classList.remove(Ny,Oy),c==="accept"?o.classList.add(Ny):c==="reject"&&o.classList.add(Oy),a&&r&&(a.classList.remove(Dy,xy,Ry),c==="accept"?(a.classList.add(Dy),a.textContent=d?.acceptLabel??r.accept):c==="reject"?(a.classList.add(xy),a.textContent=r.reject):(a.classList.add(Ry),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(c){const d=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return c()}finally{o.style.visibility=d,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return l.moveTo(t,n),l.setMode("neutral"),l}function vR(){const e=document.createElement("div");return e.className=gR,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 _R(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??ER(e),reject:t?.reject??kR(),neutral:t?.neutral??SR(e)}}function ER(e){return e.type==="shortcut"?b("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?b("Drop here to move","desktop-mode"):b("Drop here","desktop-mode")}function kR(e){return b("Can’t drop here","desktop-mode")}function SR(e){return e.type==="shortcut"?b("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?b("Drop in a folder","desktop-mode"):""}function IR(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 AR(e){return e.offsetWidth/2}function CR(e){return e.offsetHeight/2}let My=!1;function LR(e){My||(My=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const Wy=4,Ce={START:"os.drag.start",MOVE:"os.drag.move",ENTER:"os.drag.enter",LEAVE:"os.drag.leave",REJECTED:"os.drag.rejected",COMMIT:"os.drag.commit",CANCEL:"os.drag.cancel",END:"os.drag.end"},Ar="os-file-tile--dragging",Py="os-file-tile--drop-target",$y="data-os-trash-drop-active",Uy="data-files-drop-active",By="data-os-dragging",Fy="data-os-drag-type",Hl="data-os-drag-mode";class TR{constructor(){this._registry=new hR,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)<Wy&&Math.abs(s)<Wy)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),kt(Ce.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("[openstation] 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||Jt())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(),LR(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:()=>Hy(),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(Ar),t._ghost=bR(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(By,""),document.body.setAttribute(Fy,String(t.payload.type)),document.body.setAttribute(Hl,"neutral")),kt(Ce.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(l){console.error("[openstation] drop target accept() threw:",r.id,l)}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&&Gl(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(NR(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),kt(Ce.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Hl,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),Gl(n,t),this._cleanupDom(t);const i=this._active;this._active=null;try{n.onDrop(t,{clientX:o,clientY:s})}catch(r){console.error("[openstation] drop target onDrop threw:",n.id,r)}try{t._callbacks.onCommit?.(n)}catch(r){console.error("[openstation] drag onCommit threw:",r)}kt(Ce.COMMIT,{payload:t.payload,targetId:n.id}),kt(Ce.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&&Gl(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}kt(Ce.CANCEL,{payload:t.payload,reason:n}),kt(Ce.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(Ar)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(By),document.body.removeAttribute(Fy),document.body.removeAttribute(Hl)),OR()}}function kt(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function NR(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}kt(Ce.ENTER,{payload:t.payload,targetId:e.id})}function Gl(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}kt(Ce.LEAVE,{payload:t.payload,targetId:e.id})}function Hy(){if(typeof document>"u")return[];const e=[];for(const t of[`.${Ar}`,`.${Py}`,`[${$y}]`,`[${Uy}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function OR(){for(const e of Hy())e.classList.remove(Ar,Py),e.removeAttribute($y),e.removeAttribute(Uy)}const DR=".os-window",Gy="wp-window-";function zy(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(DR);return o instanceof HTMLElement?o:null}function xR(e){if(!e.id.startsWith(Gy))return null;const t=e.id.slice(Gy.length);return t.length>0?t:null}const RR="desktop-mode-iframe-drop-",Cr="iframe.os-window__iframe",zl="data-os-iframe-drop-active";let jl=!1,jy=null;const Xe=new Map,wn=new Map;let St=null,yn=null;function MR(){document.querySelectorAll(Cr).forEach(t=>{Xe.has(t)||(Xe.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function WR(){Xe.forEach((e,t)=>{t.style.pointerEvents=e}),Xe.clear()}function Vy(e,t){const n=zy(e,t);if(!n)return null;const o=n.querySelector(Cr);return o instanceof HTMLIFrameElement?o:null}const Ky=e=>{if(!St)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=Vy(e.clientX,e.clientY);if(t===yn){t&&Vl(t,e.clientX,e.clientY);return}yn&&(Kl(),ht(yn,{type:"os-drag-leave"})),yn=t,t&&(ht(t,{type:"os-drag-over",payload:St}),Vl(t,e.clientX,e.clientY))},qy=e=>{if(!St)return;const t=Vy(e.clientX,e.clientY);if(!t){e.preventDefault(),Lr();return}e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const n=St;Lr();const o=t.getBoundingClientRect();ht(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},Yy=()=>{Lr()};function PR(e){if(St){St=e;return}St=e,MR(),document.addEventListener("dragover",Ky,!0),document.addEventListener("drop",qy,!0),document.addEventListener("dragend",Yy,!0)}function Lr(){St&&(St=null,Kl(),yn&&(ht(yn,{type:"os-drag-leave"}),yn=null),document.removeEventListener("dragover",Ky,!0),document.removeEventListener("drop",qy,!0),document.removeEventListener("dragend",Yy,!0),WR())}function Tr(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}let yo=null,Nr=null,bo=0;function Vl(e,t,n){Nr={iframe:e,clientX:t,clientY:n},!bo&&(bo=requestAnimationFrame(()=>{bo=0;const o=Nr;if(Nr=null,!o||!o.iframe.isConnected)return;const s=o.iframe.getBoundingClientRect();ht(o.iframe,{type:"os-drag-move",position:{x:o.clientX-s.left,y:o.clientY-s.top}})}))}function Kl(){Nr=null,bo&&(cancelAnimationFrame(bo),bo=0)}function ht(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function $R(e,t){let n;try{n=new URL(e.src)}catch{return}if(!/\/post(-new)?\.php$/.test(n.pathname))return;const o=We(t)?.type??n.searchParams.get("post_type");return b(o==="page"?"Add to page":"Add to post","desktop-mode")}function UR(e,t,n,o){return e.registerDropTarget({id:`${RR}${o}`,element:n,accept:s=>!!Tr(s),acceptLabel:$R(t,o),onEnter:s=>{const i=Tr(s.payload);i&&(n.setAttribute(zl,""),yo=t,ht(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(zl),yo===t&&(yo=null),ht(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(zl),yo=null;const r=Tr(s.payload);if(!r)return;const a=t.getBoundingClientRect(),l={x:i.clientX-a.left,y:i.clientY-a.top};if(!aR(r)){ht(t,{type:"os-drop",payload:r,position:l});return}BR(t,r,l)}})}async function BR(e,t,n){const o=await cR(t);if(!o){ht(e,{type:"os-drag-leave"});return}ht(e,{type:"os-drop",payload:o,position:n})}function Xy(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 FR(e,t,n){try{if(!window.localStorage?.getItem("openStationDragDebug"))return}catch{return}console.info("[openstation] drag-start: suppressing %d iframe(s); bridgeable=%s",e,t,n)}function HR(e){const t=jy;if(!t)return;const n=document.querySelectorAll(Cr),o=!!Tr(e);FR(n.length,o,e),n.forEach(s=>{if(Xe.has(s)||(Xe.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||wn.has(s))return;const i=s.parentElement;if(!i)return;const r=Xy(s),a=UR(t,s,i,r);wn.set(s,a)})}function GR(){Kl(),yo=null,Xe.forEach((e,t)=>{t.style.pointerEvents=e}),Xe.clear(),wn.forEach(e=>{try{e()}catch{}}),wn.clear()}function zR(e){jl||(jl=!0,jy=e,document.addEventListener(Ce.START,t=>{const n=t.detail;HR(n?.payload)}),document.addEventListener(Ce.END,()=>{GR()}),document.addEventListener(Ce.MOVE,t=>{const n=yo;if(!n)return;const o=t.detail;typeof o?.clientX!="number"||typeof o?.clientY!="number"||Vl(n,o.clientX,o.clientY)}),document.addEventListener(wo.START,t=>{const n=t.detail;n?.payload&&PR(n.payload)}),document.addEventListener(wo.END,()=>{Lr()}),ee(y.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(Xe))t.isConnected||Xe.delete(t);for(const[t,n]of Array.from(wn))if(!t.isConnected){try{n()}catch{}wn.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:jl,iframesInDom:document.querySelectorAll(Cr).length,suppressedCount:Xe.size,registeredCount:wn.size,suppressedIframeIds:Array.from(Xe.keys()).map(Xy)}))}const jR=250,VR=1e3,KR="os-drag-hover";let Zy=!1,ql=null,Yl=null,xs=null,Rs=null,Xl=null;function Jy(){xs!==null&&(clearTimeout(xs),xs=null)}function Qy(){Rs!==null&&(clearTimeout(Rs),Rs=null)}function Ms(){Jy(),Qy(),Yl=null}function eb(){Qy(),Rs=setTimeout(()=>{Rs=null,Ms()},VR)}function qR(e,t){const n=ql?.getById(e);if(!(!n||n.isFocused()||!Q(y.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{ql?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function tb(e,t){e!==Yl&&(Jy(),Yl=e,e!==null&&(xs=setTimeout(()=>{xs=null,qR(e,t)},jR)))}function nb(e,t,n){const o=zy(e,t);tb(o?xR(o):null,n)}const YR=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||nb(t.clientX,t.clientY,t.payload?.type??"")},XR=()=>{Ms()};function ZR(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 JR=e=>{eb();const t=Xl??(ZR(e)?"os-file":"external");nb(e.clientX,e.clientY,t)},ob=()=>{Ms()},QR=e=>{e.relatedTarget===null&&Ms()};function eM(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 tM=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==KR)return;const n=eM(e.source);n&&(eb(),tb(n,typeof t.payloadType=="string"?t.payloadType:"external"))},nM=e=>{const t=e.detail;t?.payload&&(Xl=t.payload.kind??"")},oM=()=>{Xl=null,Ms()};function sM(e){Zy||(Zy=!0,ql=e,document.addEventListener(Ce.MOVE,YR),document.addEventListener(Ce.END,XR),document.addEventListener(wo.START,nM),document.addEventListener(wo.END,oM),document.addEventListener("dragover",JR,!0),document.addEventListener("drop",ob,!0),document.addEventListener("dragend",ob,!0),document.addEventListener("dragleave",QR,!0),window.addEventListener("message",tM))}function sb(){const e=window.wp?.os;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=Q("os.open-command.items",o);return Array.isArray(i)?i:o}const iM={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=sb();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=sb(),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 rM(){ao(iM)}const Le=[],aM=new Set;function ib(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=Le.findIndex(n=>n.id===e.id);return t>=0?Le[t]=e:Le.push(e),Zl(),()=>{const n=Le.findIndex(o=>o.id===e.id);n>=0&&(Le.splice(n,1),Zl())}}function cM(e){const t=Le.findIndex(n=>n.id===e);t>=0&&(Le.splice(t,1),Zl())}function rb(){return Le.slice()}function Zl(){for(const e of Array.from(aM))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",t)}}function vo(e,t){try{document.dispatchEvent(new CustomEvent(t?"os-palette-opened":"os-palette-closed",{detail:{id:e}}))}catch{}}function ab(){if(Le.length===0)return;const e=Le.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{Le[0].open(),vo(Le[0].id,!0)}catch{}return}try{Le[e].close(),vo(Le[e].id,!1)}catch{}const t=e+1;if(t<Le.length)try{Le[t].open(),vo(Le[t].id,!0)}catch{}}function Or(e){const t=Le.find(n=>n.id===e);if(t){for(const n of Le)if(n.id!==e)try{n.isOpen()&&(n.close(),vo(n.id,!1))}catch{}try{t.open(),vo(t.id,!0)}catch{}}}let cb=!1;function lM(){if(cb)return;cb=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),ab())},!0);const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;n&&n.type==="os-palette-cycle"&&ab()})}const it=se("os/presence",()=>({byUser:new Map,serverTimeMs:0})),dM=5*60*1e3;let lb=Date.now(),db=!1;function Dr(){lb=Date.now()}function uM(e){if(!e||!e.snapshot)return;const t=it.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 l={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=t.get(r);n.set(r,l),(!c||c.status!==l.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:l.status,entry:l})}it.state.byUser=n,typeof e.serverTimeMs=="number"&&(it.state.serverTimeMs=e.serverTimeMs),it.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("os-presence-changed",{detail:i})),Se.publish("os/presence-changed",i)}Se.publish("os/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function fM(){db||(db=!0,document.addEventListener("pointerdown",Dr,{capture:!0,passive:!0}),window.addEventListener("keydown",Dr,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||Dr()}),$e.contribute("openstation_presence_active",()=>!0),$e.contribute("openstation_user_active",()=>Date.now()-lb<dM),$e.subscribe("openstation_presence",e=>{uM(e)}))}function pM(e){const t=it.state.byUser.get(e);return t?t.status:"offline"}function hM(){return new Map(it.state.byUser)}function mM(e){return it.state.byUser.get(e)??null}function gM(e){return it.subscribe(t=>e(t))}function wM(){Dr()}function yM(e){if(!Array.isArray(e)||e.length===0)return;const t=it.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)){it.state.byUser=n,it.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("os-presence-changed",{detail:i})),Se.publish("os/presence-changed",i)}Se.publish("os/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const bM=Object.freeze({getStatus:pM,getAll:hM,getEntry:mM,subscribe:gM,markActive:wM,applyBatch:yM});function ub(e){const t=new Set;let n=null;const o=new Set;e.onChange&&o.add(e.onChange);const s=()=>e.order().filter(a=>t.has(a)),i=()=>{const a=s();for(const l of o)try{l(a)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=a=>{const l=t.size,c=Array.from(t);a(),!(t.size===l&&c.every(d=>t.has(d)))&&i()};return{keys:s,has:a=>t.has(a),size:()=>t.size,anchor:()=>n,set(a){r(()=>{t.clear();for(const l of a)t.add(l)}),n=a.length>0?a[a.length-1]:null},add(a){r(()=>{t.add(a)}),n=a},remove(a){r(()=>{t.delete(a)}),n===a&&(n=null)},toggle(a){r(()=>{t.has(a)?t.delete(a):t.add(a)}),n=a},selectRange(a,l=!1){const c=e.order(),d=c.indexOf(a),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{l||t.clear(),t.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{l||t.clear();for(let g=f;g<=p;g+=1)t.add(c[g])})},selectAll(){const a=e.order();r(()=>{for(const l of a)t.add(l)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const a=new Set(e.order());let l=!1;return r(()=>{for(const c of Array.from(t))a.has(c)||(t.delete(c),l=!0)}),n!==null&&!a.has(n)&&(n=null),l},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const vM=".os-file-tile",_M="os-file-tile--selected",EM="os-selection-marquee",fb=4,pb=36,hb=12,mb="data-os-marquee";function kM(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function SM(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(mb,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(mb)}}const IM=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note, .os-mobile-home, .os-mobile-edge",AM="os-area--overview";function CM(e,t){const n=t.itemSelector??vM,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??IM,r=()=>Array.from(e.querySelectorAll(n)).filter(R=>t.keyOf(R)!==null),a=()=>{const R=[],C=new Map;r().forEach((B,z)=>{const _=B.parentElement??e;let v=C.get(_);v||(v=[],C.set(_,v),R.push(_)),v.push({key:t.keyOf(B),top:parseFloat(B.style.top)||0,left:parseFloat(B.style.left)||0,index:z})});const U=[];for(const B of R){const z=C.get(B)??[];z.sort((_,v)=>_.top!==v.top?_.top-v.top:_.left!==v.left?_.left-v.left:_.index-v.index);for(const _ of z)U.push(_.key)}return U},l=t.order??a,c=ub({order:l,onChange:R=>{p(),t.onChange?.(R),u(R)}}),d={},u=R=>{typeof document>"u"||(_o={surface:t.surface??"",scope:t.scope??"",keys:R.slice(),count:R.length},Ql=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:_o})))},f=R=>r().find(C=>t.keyOf(C)===R)??null,p=()=>{for(const R of r()){const C=t.keyOf(R),U=c.has(C);U!==R.hasAttribute("selected")&&(U?R.setAttribute("selected",""):R.removeAttribute("selected")),R.classList.toggle(_M,U),R.hasAttribute("selectable")||R.setAttribute("selectable","");const B=U?"true":"false";R.getAttribute("aria-selected")!==B&&R.setAttribute("aria-selected",B)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let g=null;const h=R=>{if(!(R.target instanceof Element))return;const C=R.target.closest(n);if(C&&e.contains(C)){const U=t.keyOf(C);if(U===null)return;if(g=U,R.stopPropagation(),R.shiftKey){c.selectRange(U,R.ctrlKey||R.metaKey);return}if(R.ctrlKey||R.metaKey){c.toggle(U);return}c.set([U]);return}if(M){M=!1;return}c.clear()};o.addEventListener("click",h);let m=null,E=null,k=null,N=[],M=!1,S=0,$=null,W=null;const F=R=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(R),W=R}catch{}},x=()=>{if(W===null||typeof o.releasePointerCapture!="function"){W=null;return}try{o.hasPointerCapture?.(W)&&o.releasePointerCapture(W)}catch{}W=null},q=(R,C)=>{const U=o.getBoundingClientRect();return{x:R-U.left+o.scrollLeft,y:C-U.top+o.scrollTop}},J=()=>{m?.remove(),m=null,E=null,k=null,$?.(),$=null,x(),S&&(cancelAnimationFrame(S),S=0),document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",K),document.removeEventListener("pointercancel",G),o.removeEventListener("lostpointercapture",G),o.removeEventListener("scroll",X),window.removeEventListener("blur",G)};function X(){if(!E||!k)return;const R=q(k.x,k.y),C=R.x-E.x,U=R.y-E.y;if(!m&&Math.abs(C)<fb&&Math.abs(U)<fb)return;m||(m=document.createElement("div"),m.className=EM,m.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(m),M=!0,$=SM(o),T());const B=Math.min(E.x,R.x),z=Math.min(E.y,R.y),_=Math.abs(C),v=Math.abs(U);m.style.left=`${B}px`,m.style.top=`${z}px`,m.style.width=`${_}px`,m.style.height=`${v}px`;const A=o.getBoundingClientRect(),O=A.left-o.scrollLeft,P=A.top-o.scrollTop,Z={left:B+O,top:z+P,right:B+_+O,bottom:z+v+P},V=[];for(const ge of r()){const Te=ge.getBoundingClientRect();Te.left<Z.right&&Te.right>Z.left&&Te.top<Z.bottom&&Te.bottom>Z.top&&V.push(t.keyOf(ge))}c.set(Array.from(new Set([...N,...V])))}function T(){if(S||typeof requestAnimationFrame!="function")return;const R=()=>{if(S=0,!m||!k)return;const C=o.getBoundingClientRect();if(kM(o)){let B=0;if(k.y<C.top+pb?B=-hb:k.y>C.bottom-pb&&(B=hb),B!==0){const z=o.scrollTop;o.scrollTop+=B,o.scrollTop!==z&&X()}}S=requestAnimationFrame(R)};S=requestAnimationFrame(R)}const D=R=>{E&&(k={x:R.clientX,y:R.clientY},X())},K=()=>{m&&(Jl=Date.now()),J()},G=()=>{J()},ne=R=>{if(!s||R.button!==0||!(R.target instanceof Element)||o.classList.contains(AM)||R.target.closest(n))return;const C=R.target.closest(i);C&&C!==o&&o.contains(C)||(E=q(R.clientX,R.clientY),k={x:R.clientX,y:R.clientY},typeof R.pointerId=="number"&&F(R.pointerId),N=R.ctrlKey||R.metaKey||R.shiftKey?c.keys():[],N.length===0&&c.clear(),document.addEventListener("pointermove",D),document.addEventListener("pointerup",K),document.addEventListener("pointercancel",G),o.addEventListener("lostpointercapture",G),window.addEventListener("blur",G),o.addEventListener("scroll",X,{passive:!0}))};o.addEventListener("pointerdown",ne);const ce=R=>{if(R.key==="a"&&(R.ctrlKey||R.metaKey)){R.preventDefault(),c.selectAll();return}if(R.key==="Escape"){if(m||E){J();return}c.size()>0&&c.clear();return}const C=R.key==="ArrowRight"||R.key==="ArrowDown",U=R.key==="ArrowLeft"||R.key==="ArrowUp";if(!C&&!U)return;const B=C?1:-1,z=l();if(z.length===0)return;const _=g??c.anchor(),v=_===null?-1:z.indexOf(_),A=Math.min(z.length-1,Math.max(0,v<0?0:v+B));R.preventDefault();const O=z[A];g=O,R.shiftKey?c.selectRange(O):c.set([O]),f(O)?.focus()};return e.addEventListener("keydown",ce),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){J(),o.removeEventListener("click",h),o.removeEventListener("pointerdown",ne),e.removeEventListener("keydown",ce),Ql===d&&(_o=null,Ql=null)}}}let Jl=0;function LM(){return Jl>0&&Date.now()-Jl<500}let _o=null,Ql=null;function TM(){return _o?{..._o,keys:_o.keys.slice()}:null}function ed(e){return typeof e.sort=="number"?e.sort:100}function NM(e,t){return le(b("%1$s (%2$d items)","desktop-mode"),e,t)}function gb(e,t){if(e.length===0)return[];const n=e.map(a=>{const l=t(a);return Array.isArray(l)?l:[]});if(e.length===1)return n[0];const o=e.length,s=[],i=a=>a.multiId??a.id;for(const a of n[0]){const l=i(a),c=[];let d=!1;for(const p of n){const g=p.find(h=>i(h)===l);if(!g||g.multi!==!0){d=!0;break}c.push(g)}if(d||s.some(p=>p.id===l))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):NM(u.label,o);s.push({id:l,label:f,icon:u.icon,disabled:c.some(p=>p.disabled===!0),danger:c.some(p=>p.danger===!0),sort:Math.min(...c.map(ed)),multi:!0,onClick:async p=>{const g=new Map,h=[];c.forEach((m,E)=>{const k=m.bulk;if(typeof k!="function"){h.push(m);return}const N=g.get(k);N?N.push(e[E]):g.set(k,[e[E]])});for(const[m,E]of g)try{await m(E)}catch(k){console.error(`[openstation] selection action '${l}' failed for a batch:`,k)}for(const m of h)try{await m.onClick(p)}catch(E){console.error(`[openstation] selection action '${l}' failed for one item:`,E)}}})}s.sort((a,l)=>{const c=ed(a),d=ed(l);return c!==d?c-d:a.label.localeCompare(l.label)});const r=Q("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function wb(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 td=8;function yb(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function nd(e){yb(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-td)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-td)}px`)})}function bb(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,yb(e,o=>{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-td)}px`)})}const OM="os-wallpaper-menu";let Eo=null,od=null,vb=0;function sd(){if(!Eo)return;const e=Eo.dataset.menuScope??"selection",t=od;Eo.dispatchEvent(new CustomEvent("tile-menu-closed")),Eo.remove(),Eo=null,od=null,t?.(),L(`os.${e}.menu.closed`,{})}function DM(e,t){sd();const n=++vb;gi(()=>n===vb,()=>xM(e,t))}function xM(e,{actions:t,dataset:n,className:o,scope:s="selection",onOpened:i,onClosed:r}){if(t.length===0)return;const a=document.createElement("os-context-menu");a.setAttribute("open",""),a.classList.add(OM),o&&a.classList.add(o),a.dataset.menuScope=s;for(const[u,f]of Object.entries(n??{}))a.dataset[u]=f;a.style.left=`${e.x}px`,a.style.top=`${e.y}px`;const l=new Map;for(const u of t){l.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.danger&&f.setAttribute("danger",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",RM(u.icon)),f.textContent=u.label,a.appendChild(f)}a.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=l.get(f.id);p&&(sd(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(g=>{console.error(`[openstation] menu action '${p.id}' threw:`,g)}))}),document.body.appendChild(a),Eo=a,od=r??null,nd(a);const c=wb(a,{close:()=>sd()});a.addEventListener("tile-menu-closed",c);const d=t.map(u=>u.id);i?.(d),L(`os.${s}.menu.opened`,{items:d,count:t.length})}function RM(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const MM={active:TM,resolveCommonActions:gb,createModel:ub};let Ws=null;function WM(){$e.contribute("openstation_content_changes_seen_ts",()=>Ws===null?0:Ws),$e.subscribe("openstation_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=Ws===null,n=Ws??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===""||(fr(`os.${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));Ws=o})}const PM="desktop_mode_nonces",id=new Map;let _b=!1;function rd(e,t){if(typeof e!="string"||e==="")return()=>{};let n=id.get(e);return n||(n=new Set,id.set(e,n)),n.add(t),()=>{n.delete(t)}}function $M(){_b||(_b=!0,$e.subscribe(PM,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=id.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)}}}),UM())}function UM(){rd("wp_rest",BM),rd("desktop-mode-plugins",e=>{Eb("desktop-mode-plugins","ajaxNonce",e)}),rd("updates",e=>{Eb("desktop-mode-plugins","updatesNonce",e)})}function BM(e){const t=FM();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=kb();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Eb(e,t,n){const s=kb()?.[e];if(!s||typeof s!="object")return;const i=s,r=i.extra;let a=!1;r&&typeof r=="object"&&t in r&&(r[t]=n,a=!0),(t in i||!a)&&(i[t]=n)}function FM(){if(!(typeof window>"u"))return window.openStationConfig}function kb(){if(!(typeof window>"u"))return window.openStationWindowConfig}const HM="desktop_mode_auth",GM=5e3,Sb=1e3,zM=1e4;let Ib=!1,xr=!1,ad=!1,Rr=0,Ab=0,Ps=0,ko=null,Cb=0,Lb=null,Tb=null,Nb=()=>{try{window.location.reload()}catch{}};function cd(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function ld(e=Sb){const t=Date.now();if(t<Ps){ko===null&&(ko=window.setTimeout(()=>{ko=null,Ps=Date.now()+Sb,cd()},Ps-t));return}Ps=t+e,cd()}function jM(){xr=!0,!ad&&(ad=!0,L(y.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function VM(){for(const e of KM())try{e.contentWindow?.location.reload()}catch{}}function KM(){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 dd(){const e=Date.now();e-Cb<zM||(Cb=e,xr=!1,ad=!1,ko!==null&&(window.clearTimeout(ko),ko=null),Ps=0,ld(),VM(),L(y.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function qM(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(Rr<=0){Rr=t;return}t!==Rr&&Nb()}}function YM(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<Ab||(Ab=o+GM,cd())}function XM(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");Tb=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&ld(),t=n}),Tb.observe(e,{attributes:!0,attributeFilter:["class"]})}function ZM(e={}){Ib||(Ib=!0,Rr=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(Nb=e.reloadShell),$e.subscribe("wp-auth-check",t=>{if(t===!1){jM();return}t===!0&&xr&&dd()}),$e.subscribe("nonces_expired",()=>{if(xr){dd();return}ld()}),$e.subscribe(HM,qM),Lb=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&dd()},window.addEventListener("message",Lb),XM())}const Ob=window.location.origin;function JM(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 l;try{l=new URL(a,window.location.href)}catch(m){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",a,m);return}if(l.origin!==Ob)return;let c;try{c=new URL(t.adminUrl).pathname}catch(m){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,m),c="/wp-admin/"}if(!l.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(l.pathname)||l.searchParams.has("action")&&l.searchParams.get("action")==="logout"||l.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Be(l.href)))return;const d=fe(l.href,t.adminUrl),u=Dc(l.href,t),f=(i.dataset.osWindowTitle||"").trim(),p=(i.textContent||"").trim()||u?.title||"",g=!!i.closest("#wp-admin-bar-new-content"),h={id:d,baseId:d,multi:!!u?.multi||g,url:l.href,parentUrl:u?.url??l.href,title:f||u?.title||p,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu,selfLabel:u?.selfLabel};if(g){e.openNew(h);return}e.open(h)},!0)}function Db(e){const t=e?.scriptDepPayloads;if(!t||typeof t!="object")return e;const n=e;for(const o of Object.keys(n)){if(o==="scriptDepPayloads")continue;const s=n[o];if(!(!s||typeof s!="object"))for(const i of Object.values(s)){if(!i||typeof i!="object")continue;const r=i.scriptDeps;Array.isArray(r)&&(i.scriptDeps=QM(r,t,o))}}return e}function QM(e,t,n){const o=[];for(const s of e){if(typeof s!="string"){o.push(s);continue}const i=t[s];if(i){o.push({...i,handle:s});continue}console.warn(`[openstation] ${n}: script dependency "${s}" is not in scriptDepPayloads and was dropped.`)}return o}function e1(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.total!="number"||!Number.isFinite(t.total)?null:{total:Math.max(0,Math.floor(t.total)),formatted:typeof t.formatted=="string"&&t.formatted!==""?t.formatted:String(t.total),text:typeof t.text=="string"?t.text:"",url:typeof t.url=="string"?t.url:""}}function t1(e){if(!e.url)return null;const t=document.createElement("li");t.id="wp-admin-bar-updates";const n=document.createElement("a");n.className="ab-item",n.href=e.url;const o=document.createElement("span");o.className="ab-icon",o.setAttribute("aria-hidden","true");const s=document.createElement("span");s.className="ab-label",s.setAttribute("aria-hidden","true");const i=document.createElement("span");return i.className="screen-reader-text updates-available-text",n.append(o,s,i),t.appendChild(n),t}function n1(e){const t=e1(e);if(!t)return;let n=document.getElementById("wp-admin-bar-updates");if(t.total<=0){n&&(n.style.display="none");return}if(!n){const i=document.getElementById("wp-admin-bar-root-default");if(!i||(n=t1(t),!n))return;const r=document.getElementById("wp-admin-bar-comments");r&&r.parentNode===i?i.insertBefore(n,r):i.appendChild(n)}n.style.display="";const o=n.querySelector(".ab-label");o&&(o.textContent=t.formatted);const s=n.querySelector(".updates-available-text");s&&(s.textContent=t.text)}const o1="os-registry-changed";function s1(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 ud(e,t,n){const{added:o,removed:s}=s1(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(o1,{detail:i}))}function i1(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:l,syncServerWindowActions:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:g,renderIcons:h,applyDesktopIcons:m,refreshRootPlacements:E,syncShortcuts:k,syncWindowSubmenus:N,applyMultisite:M}=e,S=new Map,$=F=>(F??[]).map(x=>String(x?.id??"")),W=F=>$(F).sort().join(`
42 `);return function(x){Db(x),x.scriptDepPayloads&&typeof x.scriptDepPayloads=="object"&&(n.scriptDepPayloads={...n.scriptDepPayloads,...x.scriptDepPayloads});const q=x.dockItems,J=x.nativeWindows,X=x.serverWidgets,T=x.serverWallpapers,D=x.serverCommandScripts,K=x.serverCommands,G=x.serverSettingsTabScripts,ne=x.serverSettingsTabs,ce=x.serverDockRailRendererScripts,R=x.serverTitleBarButtonScripts,C=x.serverWindowActionScripts,U=x.serverUnfocusEffectScripts,B=x.serverWindowLinkRendererScripts,z=x.serverWindowNotices,_=x.serverGames,v=x.serverDesktopThemes,A=x.desktopIcons;if(!Array.isArray(q)||q.length===0)return;for(const P of q)!P||typeof P.url!="string"||typeof P.icon!="string"||(P.icon.startsWith("url(")?S.set(P.url,P.icon):P.icon==="dashicons-admin-generic"&&S.has(P.url)&&(P.icon=S.get(P.url)));const O=n.dockItems;if(t(q),n.dockItems=q,ud("dock-items",O,q),k?.(),N?.(),Array.isArray(J)){const P=n.nativeWindows;o(ty(J,x.nativeWindowScriptData)),n.nativeWindows=J,x.nativeWindowScriptData&&(n.nativeWindowScriptData=x.nativeWindowScriptData),ud("native-windows",P,J)}if(Array.isArray(X)&&(s(X),n.serverWidgets=X),Array.isArray(T)&&(i(T),n.serverWallpapers=T),Array.isArray(_)&&(p(_),n.serverGames=_),Array.isArray(v)&&(g?.(v),n.serverDesktopThemes=v),Array.isArray(D)&&(r(D,Array.isArray(K)?K:void 0),n.serverCommandScripts=D,Array.isArray(K)&&(n.serverCommands=K)),Array.isArray(G)&&(a(G,Array.isArray(ne)?ne:void 0),n.serverSettingsTabScripts=G,Array.isArray(ne)&&(n.serverSettingsTabs=ne)),Array.isArray(R)&&(l(R),n.serverTitleBarButtonScripts=R),Array.isArray(C)&&(c(C),n.serverWindowActionScripts=C),Array.isArray(U)&&(d(U),n.serverUnfocusEffectScripts=U),Array.isArray(B)&&(u(B),n.serverWindowLinkRendererScripts=B),Array.isArray(ce)&&(f(ce),n.serverDockRailRendererScripts=ce),Array.isArray(z)&&(Sw(z),n.serverWindowNotices=z),Array.isArray(A)){const P=n.desktopIcons;if(h(A),m?.(A),k?.(),W(P)!==W(A)){const Z=new Set($(P));E?.($(A).filter(V=>V!==""&&!Z.has(V)))}n.desktopIcons=A,ud("desktop-icons",P,A)}n1(x.updateCounts),"multisite"in x&&M?.(x.multisite??null)}}const r1=8e3,a1=600;function c1(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:h,applyMultisite:m,renderIcons:E,refreshRootPlacements:k,syncShortcuts:N,syncWindowSubmenus:M}=e,S=i1({applyDockItems:D=>t?.applyDockItems(D),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:h,applyMultisite:m,renderIcons:E,applyDesktopIcons:D=>t?.applyDesktopIcons(D),refreshRootPlacements:k,syncShortcuts:N,syncWindowSubmenus:M});let $=typeof o.menuSig=="string"?o.menuSig:"",W=!1,F=null,x=!1,q=!1;const J=()=>{if(!o.adminUrl)return Promise.resolve();const D=(()=>{try{const K=new URL("admin.php",o.adminUrl);return K.searchParams.set("openstation_chromeless","1"),K.searchParams.set("openstation_menu_refresh","1"),K.toString()}catch{return null}})();return D?new Promise(K=>{const G=document.createElement("iframe");G.setAttribute("aria-hidden","true"),G.tabIndex=-1,G.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",G.src=D;let ne=!1;const ce=()=>{ne||(ne=!0,window.clearTimeout(C),window.removeEventListener("message",R),G.parentNode&&G.parentNode.removeChild(G),K())},R=U=>{if(U.source!==G.contentWindow)return;const B=U.data;!B||B.type!=="os-plugins-changed"||ce()},C=window.setTimeout(()=>{L(y.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),ce()},r1);window.addEventListener("message",R),document.body.appendChild(G)}):Promise.resolve()},X=()=>{if(x){q=!0;return}x=!0,J().finally(()=>{x=!1,q&&(q=!1,X())})},T=()=>{F!==null&&window.clearTimeout(F),F=window.setTimeout(()=>{F=null,X()},a1)};return window.addEventListener("message",D=>{if(D.origin!==Ob)return;const K=D.data;if(K){if(K.type==="os-plugins-changed"){K.payload&&(S(K.payload),typeof K.payload.menuSig=="string"&&($=K.payload.menuSig));return}if(K.type==="os-updates-changed"){T();return}if(K.type==="os-menu-signature"){const G=K.sig;typeof G=="string"&&G!==""&&G!==$&&!W&&(W=!0,J().finally(()=>{W=!1}))}}}),J}function xb(e,t){const n=qh(e,t);return{x:n.x,y:n.y,width:n.width,height:n.height,initialState:e.state}}function l1(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"}function d1(e,t,n=5e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=l=>{window.clearTimeout(a),document.removeEventListener("os-window-opened",r),s(l)},r=l=>{l.detail?.windowId===t&&i(e.getById(t)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function u1(e,t,n,o){const s=he(n);Array.isArray(t.session.desktops)&&t.session.desktops.length>0&&e.seedDesktops(t.session.desktops,t.session.activeDesktop||t.session.desktops[0].id);const i={};for(const r of t.session.windows)r.native&&(i[r.id]={desktopId:r.desktopId,...r.unplaced?{}:xb(r,s),...r.params?{params:r.params}:{},...r.gridSpan?{gridSpan:r.gridSpan}:{}});Object.keys(i).length>0&&e.seedWindowRestoreState(i,{reserveIds:!0});for(const r of t.session.windows){if(r.native){if(e.discardWindowRestoreState(r.id),!o?.(r.id,r.baseId||r.id,i[r.id]))continue;await d1(e,r.id);continue}if(Rn(r.url,t.adminUrl))continue;const a=Dc(r.url,t)??xc(r.baseId||r.id,t),l=await e.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!a?.multi,url:r.url,parentUrl:a?.url??r.url,title:Kh(r.url,t)??r.title,icon:r.icon||"dashicons-admin-generic",...r.unplaced?{}:xb(r,s),submenu:a?.submenu,selfLabel:a?.selfLabel,...r.gridSpan?{gridSpan:r.gridSpan}:{}});if(Array.isArray(r.externalTabs))for(const c of r.externalTabs)c&&typeof c.url=="string"&&c.url!==""&&l.addExternalTab(c.url,typeof c.label=="string"&&c.label!==""?c.label:c.url)}if(e.discardWindowRestoreState(),t.session.focused){const r=e.getById(t.session.focused),a=e.getActiveDesktopId();r&&(r.config.desktopId||a)===a&&e.focus(r)}}async function f1(e,t){if(Rn(t.currentPage,t.adminUrl)||Be(t.currentPage))return;const n=fe(t.currentPage,t.adminUrl),o=Dc(t.currentPage,t);await e.open({id:n,baseId:n,multi:!!o?.multi,url:t.currentPage,parentUrl:o?.url??t.currentPage,title:t.currentTitle||o?.title||"",icon:t.currentIcon,submenu:o?.submenu,selfLabel:o?.selfLabel})}function p1(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function fd(e,t,n,o){const s=Qu(t,n),i=window.fetch(t,s);i.then(c=>{if(c.status===401||c.status===403){let d;typeof t=="string"?d=t:t instanceof URL?d=t.href:d=t.url,YM(c.status,d)}},()=>{});let r=o?.window??null;!r&&o?.windowId&&(r=e.getById(o.windowId)??null);const a=r??e.getFocused()??null,l=r??(o?.silent?null:a);return i.then(c=>Rb(t,s,o,l,{res:c}),c=>Rb(t,s,o,l,{err:c})),o?.silent||a&&typeof a.trackActivity=="function"&&a.trackActivity(i.then(c=>{if(!c.ok)throw new Error(g1(c));return c})).catch(()=>{}),i}function Rb(e,t,n,o,s){try{let i;typeof e=="string"?i=e:e instanceof URL?i=e.href:i=e.url;const r=t?.method??(typeof e=="object"&&"method"in e?e.method:"GET"),a={url:i,method:String(r||"GET").toUpperCase(),windowId:o?.id??null,silent:n?.silent===!0,...n?.source?{source:n.source}:{}};let l;"res"in s?l={...a,status:s.res.status,ok:s.res.ok}:(l={...a,error:h1(s.err)},m1(e,t,s.err)&&(l.aborted=!0)),Se.publish("os/request-settled",l)}catch{}}function h1(e){const t=e?.message;return typeof t=="string"?t:String(e)}function m1(e,t,n){return t?.signal?.aborted||e instanceof Request&&e.signal?.aborted?!0:n?.name==="AbortError"}function g1(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return le(b("Request failed (HTTP %s)."),t)}const w1="os-remember-session";function y1(e){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!navigator.serviceWorker.controller)return;const t=[];for(const n of e)try{const o=new URL(n,window.location.href);o.origin===window.location.origin&&t.push(o.toString())}catch{}try{navigator.serviceWorker.controller.postMessage({type:w1,urls:t})}catch{}}const b1=500,v1=1500;function Mb(e){const{updated:t,...n}=e;return JSON.stringify(n)}function Wb(e){try{if(!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled)return;y1(e.windows.filter(n=>!n.native&&n.url).map(n=>EI(n.url)||"").filter(Boolean))}catch{}}function _1(e,t){let n=null,o=!1,s=!1,i=null,r=0,a=null;const l=()=>{if(o)return s=!0,Promise.resolve();const f=e.snapshot(),p=Mb(f);return p===a?Promise.resolve():(o=!0,r=Date.now(),Wb(f),i=(async()=>{try{(await fd(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:f}),keepalive:!0},{silent:!0}))?.ok&&(a=p)}catch(g){L(y.SHELL_ERROR,{scope:"session-save",error:g})}})().finally(()=>{o=!1,i=null,s&&(s=!1,u())}),i)},c=async()=>{for(n!==null&&(clearTimeout(n),n=null);i;)await i;s=!1,await l()},d=()=>{n!==null&&(clearTimeout(n),n=null),s=!1;const f=e.snapshot(),p=Mb(f);if(p===a)return;Wb(f);const g=new Blob([JSON.stringify({session:f})],{type:"application/json"}),h=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);if(navigator.sendBeacon&&navigator.sendBeacon(h,g)){a=p;return}l()},u=()=>{n!==null&&clearTimeout(n);let f=b1;if(r!==0){const p=Date.now()-r;f=Math.max(f,v1-p)}n=window.setTimeout(()=>{n=null,l()},f)};return window.addEventListener("pagehide",d),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&d()}),Object.assign(u,{flush:c})}const E1=120;function k1(e){document.addEventListener("os-window-opened",e),document.addEventListener("os-window-closed",e),document.addEventListener("os-window-focused",e),document.addEventListener("os-window-changed",e),ee(y.DESKTOP_CREATED,"desktop-mode/session-save",e),ee(y.DESKTOP_CLOSED,"desktop-mode/session-save",e),ee(y.DESKTOP_SWITCHED,"desktop-mode/session-save",e),ee(y.DESKTOP_RENAMED,"desktop-mode/session-save",e),ee(y.WORKSPACE_UPDATED,"desktop-mode/session-save",e),ee(y.WORKSPACE_PROVISIONED,"desktop-mode/session-save",e)}function S1(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;L(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,E1)}),document.addEventListener("visibilitychange",()=>{L(y.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function I1(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 Q(y.DOCK_TILE_CLASS,e,o)}function A1(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 Q(y.DOCK_TILE_ELEMENT,e,o)}function C1(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 Q(y.DOCK_TILE_TOOLTIP,e,o)}function L1(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};L(y.DOCK_TILE_RENDERED,{...o,el:e})}const T1=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),pd=new Set;function N1(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(T1))return!0;for(const n of pd)if(t.closest(n))return!0;return!1}function O1(e){return typeof e!="string"||e.trim()===""?()=>{}:(pd.add(e),()=>{pd.delete(e)})}const It=new Map,D1=window.location.origin;function Pb(e){let t=It.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},It.set(e,t)),x1(e,t),t}function x1(e,t){const n=hd(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(()=>So(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function R1(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function hd(e){const t=window.wp?.os?.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 M1(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 So(e){const t=hd(e);if(!t||!t.contentWindow)return;const n=It.get(e),o=n?M1(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},D1)}catch{}}ee(y.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&It.has(t.windowId)&&So(t.windowId)}),ee(y.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=It.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const jt=new Map,W1=1e3;function $b(e,t,n){const o=jt.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,!!jt.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const l=o.channels.get(a.channel);if(l)for(const c of l)try{c(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=jt.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>$b(e,t,n),W1))})}function P1(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function $1(e,t){const n=jt.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let U1=0;const Ub={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=Pb(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),So(e),()=>{const r=It.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const l=a.indexOf(s);l>=0&&a.splice(l,1),a.length===0&&r.headers.delete(t),So(e),Bb(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=Pb(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,So(e)),()=>{const i=It.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),So(e)),Bb(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=hd(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=Ub.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",l=new URL(a,window.location.origin);l.searchParams.set(i,t),o.src=l.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){$1(e,{id:++U1,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=jt.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},jt.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=P1();r&&$b(e,r.restUrl,r.restNonce)}return()=>{const r=jt.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),jt.delete(e))}}}};function Bb(e){const t=It.get(e);t&&t.headers.size===0&&t.observers.size===0&&(R1(t),It.delete(e))}function B1(e){const t=[];for(const l of e.getVisibleRects()){if(l.state==="minimized"||l.element.offsetParent===null)continue;const c=l.element.getBoundingClientRect();t.push({id:`window:${l.windowId}`,kind:"window",rect:Fb(c),face:"top",element:l.element})}const n=document.getElementById("os-shell");if(n){const l=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:l.left,y:l.bottom-1,width:l.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const l of Array.from(o)){const c=l.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const d=l.getAttribute("data-os-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,d==="bottom"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:c.width,height:1},face:"top",element:l}):d==="right"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:l}):t.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:l})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(l=>{const c=l.getBoundingClientRect();if(c.width===0&&c.height===0)return;const d=l.dataset.widgetId??String(r++);t.push({id:`widget:${d}`,kind:"widget",rect:Fb(c),face:"top",element:l})});const a=Q(y.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function Fb(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const F1="__openstationKeyedListKey",H1="__openstationKeyedListData";function G1(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function z1(e,t,n){const o=G1(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const l of t){const c=String(n.keyOf(l));a.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),a.add(c);const d=s.get(c);if(d){const f=d.data;n.updateItem?.(d.el,l,f),d.data=l,i.set(c,d),r.push(d.el);continue}const u=n.buildItem(l);u[F1]=c,u[H1]=l,i.set(c,{el:u,data:l}),r.push(u)}for(const[l,c]of s)i.has(l)||c.el.remove();for(let l=0;l<r.length;l++){const c=r[l],d=e.children[l];d!==c&&e.insertBefore(c,d??null)}o.byKey=i}function j1(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function V1(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:l=F=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",F)}}=e;let c=e.sentinel??null;c||(c=document.createElement("div"),c.dataset.osInfiniteListSentinel="",c.style.height="1px",t.appendChild(c));const d=new Set;let u=r,f=!0,p=!1,g=null,h=0,m=!1,E=null;const k=F=>{if(p!==F){p=F;try{a(F)}catch(x){l(x)}}},N=()=>{E&&(E.disconnect(),E=null)},M=()=>{E||!c||m||(E=new IntersectionObserver(F=>{for(const x of F)x.isIntersecting&&S()},{rootMargin:i}),E.observe(c))},S=async()=>{if(m||p||!f)return;k(!0),g=new AbortController;const F=g;try{const x=await n(u,F.signal);if(m||F!==g)return;let q=0;const J=document.createDocumentFragment();for(const X of x.items??[]){const T=String(o(X));if(d.has(T))continue;d.add(T);const D=s(X,h+q);J.appendChild(D),q++}q>0&&(c&&c.parentNode===t?t.insertBefore(J,c):t.appendChild(J),h+=q),u=x.nextCursor??null,u||(f=!1,N())}catch(x){if(x?.name==="AbortError")return;l(x)}finally{F===g&&(k(!1),g=null)}},$=()=>{if(m)return;g?.abort(),g=null,d.clear(),u=r,f=!0,h=0;const F=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);F&&c&&t.appendChild(c),k(!1),M(),S()},W=()=>{m||(m=!0,N(),g?.abort(),g=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,k(!1))};return M(),S(),{reset:$,loadMore:S,hasMore:()=>f,isLoading:()=>p,destroy:W}}const K1=520,q1=720,Y1=500;function X1(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=J1(),o=Q1();return Ae(nt(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(()=>"");let r=null;try{r=JSON.parse(i)}catch{r=null}throw bt(s.status,r,`[openstation] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>Z1(s,e,t))}function Z1(e,t,n){return new Promise((o,s)=>{const i=n.width??K1,r=n.height??q1,a=Math.max(0,Math.floor((window.screen.width-i)/2)),l=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${l}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(e.authorize_url,`os-oauth-${t}`,c);if(!d){s(new Error("[openstation] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let f=null,p=!1;const g=()=>{p||(p=!0,window.removeEventListener("message",h),f!==null&&(window.clearInterval(f),f=null))},h=m=>{if(m.origin!==u)return;const E=m.data;if(!E||E.type!=="os-oauth-callback")return;const k=E.payload;if(g(),k&&k.ok)o(k);else{const N=k?.reason??"unknown",M=k?.message??"OAuth flow failed",S=new Error(`[openstation] startOAuth(${t}) failed: ${N} — ${M}`);S.cause=k,s(S)}};window.addEventListener("message",h),f=window.setInterval(()=>{d.closed&&(g(),s(new Error(`[openstation] startOAuth(${t}) cancelled — popup closed before completing.`)))},Y1)})}function Hb(){return window.openStationConfig??{}}function J1(){const e=Hb().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function Q1(){const e=Hb().restNonce;return typeof e=="string"&&e!==""?e:null}const Mr=["os-section","os-button","os-swatch","os-swatch-grid","os-segmented","os-segment","os-select","os-option","os-multiselect","os-color-field","os-range-field","os-text-field","os-number-field","os-checkbox","os-checkbox-label","os-switch","os-toast","os-toast-container","os-tabs","os-tab","os-tabpanel","os-window-button","os-menu","os-menu-item","os-action-menu","os-context-menu","os-context-menu-option","os-confirm-dialog","os-modal","os-user-search","os-role-picker","os-flyout","os-coachmark","os-tooltip","os-tab-chip","os-stack","os-cluster","os-icon","os-body","os-panel","os-row","os-grid","os-app-frame","os-split","os-display","os-disclosure","os-empty-state","os-key","os-code","os-badge","os-ribbon","os-tile","os-log","os-steps","os-step","os-table","os-spinner","os-relative-time","os-histogram","os-fact","os-facts","os-stat","os-avatar","os-textarea","os-chip","os-tag-input","os-form","os-save-status","os-category-picker","os-crumb-chain","os-card","os-rating-summary","os-notice","os-progress-bar","os-field-row","os-repeater","os-token-field"],Gb=new Set(Mr);let Wr=null;function md(){return!!window.openStationComponents}function eW(){return window.openStationConfig?.componentsBundleUrl??""}function tW(e){return new Promise((t,n)=>{const o=()=>{if(md()){t();return}n(new Error("[openstation] component kit loaded but did not set `window.openStationComponents`."))},s=document.querySelector('script[data-os-components="1"]');if(s){md()?o():(s.addEventListener("load",o),s.addEventListener("error",()=>n(new Error("failed to load component kit"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osComponents="1",i.addEventListener("load",o),i.addEventListener("error",()=>n(new Error("failed to load component kit"))),document.head.appendChild(i)})}function nW(e){const t=e.filter(n=>!Gb.has(n));t.length===0||typeof console>"u"||console.error(`[openstation] wp.os.loadComponents(): not a component — ${t.map(n=>`<${n}>`).join(", ")}. The kit registers ${Mr.length} tags; see docs/components-reference.md for the list. The others in this call still loaded.`)}async function oW(e){if(e){if(nW(e),e.filter(o=>Gb.has(o)&&!customElements.get(o)).length===0)return}else if(md())return;const t=eW();t&&(Wr||(Wr=tW(t).catch(n=>{throw Wr=null,n})),await Wr)}const sW=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","dockPlacement","icons","iconSet","files","confirm","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","openNewWindow","cloneTemplate","onWindow","createInfiniteList","startOAuth","repaintLoadingOverlays","loadVendorScript","getWallpaperSurfaces","wallpaper","games","mode","deactivationFeedback","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","resetOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","getNavItems","getNav","renderIcon","applyTileClasses","applyTileElement","applyTileTooltip","dispatchTileRendered","isDockElement","registerDockSelector","registerTitleBarButton","unregisterTitleBarButton","listTitleBarButtons","registerWindowAction","unregisterWindowAction","listWindowActions","registerUnfocusEffect","unregisterUnfocusEffect","listUnfocusEffects","registerWindowReveal","unregisterWindowReveal","listWindowReveals","relations","registerWindowLinkRenderer","unregisterWindowLinkRenderer","listWindowLinkRenderers","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","desktopThemes","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","getConnection","broadcast","subscribe","announceContentChange","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","workArea","selection","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","getWindowParams","debug","registerNativeUrlRemap","fetch"]);function iW(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:l,registerWindow:c,openWindowById:d,openNewWindowById:u,loadWindowScriptById:f,prewarmWindowById:p,placeSystemTile:g,setDefaultWindow:h,refreshMenu:m,openOsSettings:E,aiAssistant:k,dragBridge:N,dragManager:M,connect:S,getConnection:$,wallpaperSuspend:W,mio:F,mode:x,workspaces:q,config:J}=e,X={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,iconSet:XE,files:r,confirm:rn,saveSession:a,hooks:TE(),HOOKS:y,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:T=>{Hn(T),s.apply()},registerWidget:T=>{Va(T)},widgetLayer:l,widgets:{redock:T=>{l?.redock(T)}},loadVendorScript:pe,getWallpaperSurfaces:()=>B1(t),wallpaper:W,mio:F,mode:x,games:hg,registerWindow:c,openWindow:d,openNewWindow:u,embedAdminPage:$D,loadWindowScript:f,prewarmWindow:p,loadComponents:oW,fetch:(T,D,K)=>fd(t,T,D,K),repaintLoadingOverlays:Uh,cloneTemplate:ny,onWindow:FD,createInfiniteList:V1,startOAuth:X1,registerSystemTile:T=>{g(T),L(y.DOCK_ITEM_APPENDED,{id:T.id})},registerModule:eg,loadModules:ol,whenReady:Tu,ready:Tu,isReady:OE,setDefaultWindow:h,refreshMenu:m,config:J,ai:k,dragBridge:N,dragManager:M,registerCommand:ao,unregisterCommand:Sg,listCommands:Ig,registerDestructiveAdminAction:C0,unregisterDestructiveAdminAction:Bh,listDestructiveAdminActions:L0,registerSettingsTab:Cg,unregisterSettingsTab:Lg,listSettingsTabs:Tg,registerDockRailRenderer:Oa,unregisterDockRailRenderer:uk,listDockRailRenderers:hk,openOsSettings:E,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:T=>s.subscribeOsSettings(T),updateOsSettings:(T,D={})=>{s.update(T,D),(T.navPlacement||T.navOrder)&&o?.refresh()},resetOsSettings:(T={})=>{s.reset(T),o?.refresh()},deriveWindowId:(T,D)=>fe(T,D??J.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:T=>o?.getSystemTile(T)??null,getMenuItems:()=>o?.getMenuItems()??[],getNavItems:()=>o?.getNavItems()??[],getNav:()=>o?.getNav()??null,renderIcon:ln,applyTileClasses:I1,applyTileElement:A1,applyTileTooltip:C1,dispatchTileRendered:L1,isDockElement:N1,registerDockSelector:O1,registerTitleBarButton:ps,unregisterTitleBarButton:Dg,listTitleBarButtons:uN,registerWindowAction:Mg,unregisterWindowAction:hN,listWindowActions:gN,registerUnfocusEffect:mr,unregisterUnfocusEffect:KN,listUnfocusEffects:bl,registerWindowReveal:ze,unregisterWindowReveal:jk,listWindowReveals:Lf,relations:$0,registerWindowLinkRenderer:tw,unregisterWindowLinkRenderer:QN,listWindowLinkRenderers:_l,registerWindowTheme:rw,unregisterWindowTheme:aw,listWindowThemes:cw,desktopThemes:{list:aS,getActive:Si,setActive:Kc,ensureFull:qf,subscribe:dS,resolveIcon:Vo,resolveIconColor:Ya,applyRecommendedOsSettings:T=>{const D=T!==void 0?T:Si()??"";return s.applyThemeRecommendations(D)}},applyWindowTheme:(T,D)=>{const K=t.getById(T);K&&K.setAppearanceTheme(D)},registerWindowControl:vs,unregisterWindowControl:uw,listWindowControls:fw,applyWindowControls:(T,D)=>{const K=t.getById(T);K&&K.setAppearanceControls(D)},registerWindowSlot:gw,unregisterWindowSlot:Ll,listWindowSlots:ww,applyWindowSlot:(T,D,K)=>{const G=t.getById(T);G&&G.setAppearanceSlot(D,K)},registerWindowNotice:Ew,unregisterWindowNotice:Dl,listWindowNotices:kw,dismissWindowNotice:kO,undismissWindowNotice:SO,registerWindowChrome:CO,unregisterWindowChrome:Cw,listWindowChromes:Lw,applyWindowChrome:(T,D)=>{const K=t.getById(T);K&&K.setAppearanceChrome(D)},connect:S,getConnection:$,broadcast:fr,subscribe:co,announceContentChange:Fg,registerPalette:ib,unregisterPalette:cM,listPalettes:rb,openPalette:Or,devtools:Ub,createSharedStore:se,presence:bM,workArea:BI,workspaces:q,selection:MM,activity:Se,heartbeat:$e,showToast:ue,notify:ll,pwa:{promptInstall:oR,undismissInstallHint:sR,getState:ds,subscribe:wg,requestNotificationPermission:YT,getNotificationPermission:XT},renderKeyedList:z1,clearKeyedList:j1,registerNamespace:(T,D)=>{if(typeof T!="string"||T===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!D||typeof D!="object"){console.warn(`[openstation] registerNamespace("${T}"): api must be an object`);return}if(sW.has(T)){console.warn(`[openstation] registerNamespace("${T}"): name is reserved by the shell — pick a plugin-specific key`);return}X[T]=D;const K=window.wp?.os;K&&K!==X&&(K[T]=D)},getWindowConfig:T=>{const D=window.openStationWindowConfig;if(!D||typeof D!="object")return;const K=D[T];return K===void 0?void 0:K},getWindowParams:T=>{const D=t.getById(T);if(D)return{...D.config.params??{}}},registerNativeUrlRemap:yt,debug:{window:T=>{const D=(J.nativeWindows??[]).find(C=>C.id===T);if(!D)return null;const K=D.scriptUrl||(D.scriptHandle?J.nativeWindowScriptData?.[D.scriptHandle]?.url??"":"");let G="unknown",ne=!1;K&&(document.querySelector(`script[data-os-vendor="${K.replace(/"/g,'\\"')}"]`)?(G="lazy",ne=!0):Array.from(document.querySelectorAll("script[src]")).find(B=>B.src===K)&&(G="eager",ne=!0));const ce=window.openStationWindowConfig,R=!!(ce&&typeof ce=="object"&&Object.prototype.hasOwnProperty.call(ce,T));return{id:T,scriptHandle:D.scriptHandle||"",scriptUrl:K,loadPath:G,tagInDom:ne,configPresent:R,extras:{hasTranslations:!!D.scriptTranslations,l10nCount:(D.scriptL10n??[]).length,beforeCount:(D.scriptBefore??[]).length,afterCount:(D.scriptAfter??[]).length}}}}};return X}function rW(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const gd=se("desktop-mode/layout",()=>({layout:"classic"}));function zb(e){gd.state.layout!==e&&(gd.state.layout=e,gd.notify())}class jb{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 aW extends jb{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const $s=new Map,wd=new Set;function Ze(e){if(!e.type)throw new Error("[openstation] registerType: `type` is required.");if(!e.label)throw new Error("[openstation] registerType: `label` is required.");$s.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),L("os.files.type-registered",e.type,e),Kb()}function cW(e){$s.delete(e)&&(L("os.files.type-unregistered",e),Kb())}function lW(e){const t=$s.get(e);return t||null}function Vb(){const e=Array.from($s.values()).slice(),t=Q("os.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 Vt(e){const t=$s.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new aW(e,e.type)}function dW(e){return wd.add(e),()=>wd.delete(e)}function Kb(){for(const e of wd)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const Pr=new Map,yd=new Set;let bd={};function qb(e){bd={...e},kd()}function vd(){return{...bd}}function je(e){if(!e.id)throw new Error("[openstation] registerOpener: `id` is required.");if(!e.label)throw new Error("[openstation] registerOpener: `label` is required.");if(!Array.isArray(e.types)||e.types.length===0)throw new Error("[openstation] registerOpener: `types` must be a non-empty array.");if(!e.handler||typeof e.handler!="object")throw new Error("[openstation] registerOpener: `handler` is required.");Pr.set(e.id,{id:e.id,label:e.label,types:e.types.slice(),isDefault:!!e.isDefault,sort:typeof e.sort=="number"?e.sort:100,appliesTo:typeof e.appliesTo=="function"?e.appliesTo:void 0,handler:e.handler}),L("os.files.opener-registered",e.id,e),kd()}function uW(e){Pr.delete(e)&&(L("os.files.opener-unregistered",e),kd())}function fW(e){return Pr.get(e)??null}function Yb(){const e=Array.from(Pr.values()).slice(),t=Q("os.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 _d(e,t){return Yb().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function Ed(e,t){const n=_d(e,t);if(n.length===0)return null;const o=bd[e];let s=null;return o&&(s=n.find(r=>r.id===o)??null),s||(s=n.find(r=>r.isDefault)??null),s||(s=n[0]),Q("os.files.resolve-opener",s,e)??null}function Xb(e){return yd.add(e),()=>yd.delete(e)}function kd(){for(const e of yd)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let Kt=null;function pW(e){Kt=e}function Sd(e){return!Kt||!e.url?!1:Kt.openUrl({id:Kt.deriveWindowId(e.url),...e})}async function Us(e,t){if(!Kt)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=Ed(e.type(),e);if(!n)return L("os.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;L("os.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):Kt.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),l=Kt.openUrl({id:i,url:s,title:r,icon:a});return L("os.files.opened",{file:e,openerId:n.id,kind:"url"}),l}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=Kt.openNativeWindow(o.windowId,s);return L("os.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),L("os.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return L("os.files.open-failed",{reason:"handler-threw",type:e.type(),ref:e.ref(),openerId:n.id,error:o}),console.error("[openstation] file opener threw:",o),!1}}const hW="dashicons-portfolio";function mW(){Ze({type:"shortcut",label:"Plugin shortcut",sort:1}),Ze({type:"folder",label:"Folder",sort:5}),Ze({type:"post",label:"Post",sort:10}),Ze({type:"attachment",label:"Media",sort:20}),Ze({type:"upload",label:"Uploaded file",sort:25}),Ze({type:"user",label:"User",sort:30}),Ze({type:"term",label:"Taxonomy term",sort:40}),Ze({type:"comment",label:"Comment",sort:50}),Ze({type:"bookmark",label:"Bookmark",sort:60}),Ze({type:"link",label:"Web link",sort:70}),Ze({type:"embed",label:"Embedded web window",sort:80})}function gW(){const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]%16+64,e[8]=e[8]%64+128;const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}class Io extends Uo{constructor(t,n,o=new Uo("",{status:0})){super(t,{status:o.status,code:o.code,data:o.data,serverMessage:o.serverMessage}),this.name="JobRequestError",this.retryable=n}}async function wW(e,t,n){const o=new AbortController,s=window.setTimeout(()=>o.abort(),15e3);try{const i=await Ae(nt(e.restRoot,t),{method:n?"POST":"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:n?JSON.stringify(n):void 0,signal:o.signal,cache:"no-store"},{source:"desktop-mode/agents",silent:!n}),r=await i.json().catch(()=>null);if(!i.ok)throw new Io(r?.message||`HTTP ${i.status}`,i.status>=500&&!r?.code||i.status===408,bt(i.status,r));if(!r||!r.jobId&&typeof r.text!="string")throw new Io(b("The job status could not be read.","desktop-mode"),!0,bt(i.status,null));return r}finally{window.clearTimeout(s)}}function yW(e){return new Promise(t=>window.setTimeout(t,e))}async function bW(e,t,n,o,s=()=>{}){const i=`desktop-mode/v1/agents/${e}`,r=Date.now()+2*60*60*1e3;let a=!1,l=2e3;for(;Date.now()<r;){try{const c=await wW(n,a?`${i}/jobs/${o}`:`${i}/invoke`,a?void 0:{...t,async:!0,requestId:o});if(!("jobId"in c))return c;if(c.jobId!==o)throw new Io(b("The server returned a different job.","desktop-mode"),!1);if(a=!0,c.status==="completed"&&c.result)return c.result;if(c.status==="failed")throw new Io(c.error?.message||b("The agent job failed.","desktop-mode"),!1);if(c.status!=="queued"&&c.status!=="running")throw new Io(b("The server returned an invalid job state.","desktop-mode"),!1);s(c.status),l=Math.min(1e4,Math.max(l*1.25,(c.pollAfter||3)*1e3))}catch(c){if(c instanceof Io&&!c.retryable)throw c;s("reconnecting"),l=Math.min(l*2,3e4)}await yW(document.hidden?Math.max(l,15e3):l)}throw new Error(b("The background job has not returned a result. Some work may already have been applied. Check the site before submitting again.","desktop-mode"))}const Ve=se("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function Zb(e){Ve.state.activeAgent=e,Ve.state.transcripts[e.id]||(Ve.state.transcripts[e.id]=[]),Ve.state.conversationIds||(Ve.state.conversationIds={},Ve.state.conversationsRev=0),Ve.notify()}const Jb="desktop-mode/v1/agents/conversations";async function Qb(e,t,n={}){const o=await Ae(nt(e.restRoot,t),{...n,headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce,...n.headers??{}}},{source:"desktop-mode/agents",silent:!0}),s=await o.json().catch(()=>null);if(!o.ok)throw bt(o.status,s);return s}function vW(e){return e.filter(t=>!t.pending)}async function _W(e,t){const n=Ve.state,o=vW(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await Qb(t,`${Jb}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await Qb(t,Jb,{method:"POST",body:JSON.stringify({agentId:e.id,messages:o})});n.conversationIds[e.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,Ve.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const ev={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function tv(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function Id(e){if(e.type==="shortcut"){const t=e.data;let n=ev[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=tv(t.ref);return!n||!o?null:{kind:n,id:o,title:String(t.title??"")||`#${o}`}}if(e.type==="desktop-file"){const n=e.data.placement?.file;if(!n)return null;const o=ev[String(n.type??"")],s=tv(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function EW(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function kW(e){return le(b('The user dropped the %1$s "%2$s" (id %3$s) onto you. Handle it according to your instructions, using your tools as needed.',"desktop-mode"),e.kind,e.title,String(e.id))}function SW(e){return le(b('The user sent you the %1$s "%2$s" (id %3$s) from the "Send to" menu. Handle it according to your instructions, using your tools as needed.',"desktop-mode"),e.kind,e.title,String(e.id))}function IW(e,t,n){return Ad(e,"agents-send-to"),ov(e,SW(t),n,"send-to",nv(t))}function nv(e){return{kind:e.kind,id:e.id,title:e.title}}function Ad(e,t="agents"){Zb(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function ov(e,t,n,o,s){Zb(e);const i=Ve.state.transcripts[e.id],r=b("The agent finished without a text answer.","desktop-mode"),a=i.filter(c=>!c.pending&&c.role!=="error"&&!(c.role==="agent"&&c.text===r)).map(c=>({role:c.role,text:c.text}));i.push({role:"user",text:t,at:Date.now(),attachment:s});const l={role:"agent",text:b("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(l),Ve.notify();try{const c=await bW(e.id,{message:t,source:o,history:a},n,gW(),d=>{const u={queued:b("Queued — waiting for a WordPress worker…","desktop-mode"),reconnecting:b("Reconnecting to the background job…","desktop-mode"),running:b("Working in the background…","desktop-mode")};l.text=u[d],Ve.notify()});c.text?.trim()?l.text=c.text:(l.role="error",l.text=r),l.toolCalls=c.toolCalls,Array.isArray(c.callToActions)&&c.callToActions.length>0&&(l.callToActions=c.callToActions)}catch(c){l.role="error",l.text=c instanceof Error?c.message:String(c)}l.pending=!1,Ve.notify(),_W(e,n)}function AW(e,t,n){return Ad(e,"agents-drop"),ov(e,kW(t),n,"drag",nv(t))}const sv=se("desktop-files/rest-deps",()=>({deps:null}));function iv(e){sv.state.deps=e}function Ao(){const{deps:e}=sv.state;if(!e)throw new Error("[openstation] files REST client called before installRestDeps().");return e}function CW(){return Ao()}class Cd 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}}const me=lk({prefix:"[openstation] files REST",source:"desktop-mode/files",url:e=>nt(Ao().baseUrl,e),nonce:()=>Ao().nonce,conflict:e=>{const t=e?.data?.data??e?.data;return t&&typeof t=="object"?new Cd(t):null}});function Ue(e=0){return me(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function Bs(e){return me("/placements",{method:"POST",body:JSON.stringify(e)})}function bn(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),me(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Ld(e){return me(`/placements/${e}`,{method:"DELETE"})}async function $r(e,t){const{baseUrl:n,nonce:o}=Ao(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Ae(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 await Wn(r);return await r.json()}function rv(){return me("/folders",{method:"GET"})}function Td(e){return me("/folders",{method:"POST",body:JSON.stringify(e)})}function av(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),me(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Nd(e){return me(`/folders/${e}`,{method:"DELETE"})}function cv(e){return me("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function LW(e){return me(`/folders/${e}/shares`,{method:"GET"})}function TW(e,t){return me(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function NW(e,t,n){return me(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function OW(e,t){return me(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function DW(e,t){return me(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function xW(e,t){return me(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function lv(e){return me(`/folders/${e}/leave`,{method:"POST"})}function RW(){return me("/folder-sharing-tables/purge",{method:"POST"})}function MW(e){return me(`/uploads/${e}/shares`,{method:"GET"})}function WW(e,t){return me(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function PW(e,t){return me(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function $W(e,t){return me(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function UW(e,t){return me(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function dv(e){return me(`/uploads/${e}/leave`,{method:"POST"})}function BW(e,t){return me(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function Ur(e){return me(`/uploads/${e}/media`,{method:"POST"})}function uv(e,t){return me(`/uploads/${e}/post`,{method:"POST",body:JSON.stringify({postType:t})})}function fv(e,t){return me(`/posts/${e}/uploads`,{method:"POST",body:JSON.stringify({fileIds:t})})}function FW(e,t){return me("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function vn(e){const{baseUrl:t,nonce:n}=Ao(),o=nt(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function pv(e){const{baseUrl:t,nonce:n}=Ao(),o=nt(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const HW=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:Cd,acceptFileShare:$W,acceptShare:DW,addUploadToMediaLibrary:Ur,attachUploadsToPost:fv,createFolder:Td,createPlacement:Bs,deleteFolder:Nd,deletePlacement:Ld,denyFileShare:UW,denyShare:xW,ensureUploadPath:FW,getFilesRestDeps:CW,getFolderZipUrl:pv,getUploadDownloadUrl:vn,installRestDeps:iv,inviteFileShare:WW,inviteShare:TW,leaveFileShare:dv,leaveShare:lv,listFileShares:MW,listFolders:rv,listPlacements:Ue,listShares:LW,purgeFolderSharingTables:RW,renameUpload:BW,restoreTrashedItem:$r,revokeFileShare:PW,revokeShare:OW,saveAssociations:cv,startPostFromUpload:uv,updateFolder:av,updatePlacement:bn,updateShareCapability:NW},Symbol.toStringTag,{value:"Module"})),GW="desktop-mode/files";function rt(){return se(GW,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function Co(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function qt(e,t){const n=rt(),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(),Co({kind:"placements-set",folderId:e})}function Od(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=rt(),o=new Map(n.state.placementsByFolder);for(const[a,l]of o)if(l.findIndex(d=>d&&d.id===e.id)>=0&&a!==e.parentId){const d=l.filter(Boolean),u=d.findIndex(f=>f.id===e.id);u>=0&&d.splice(u,1),o.set(a,d)}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(),Co({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function Fs(e,t="local"){const n=rt(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(l=>l&&l.id===e)>=0){const l=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,l),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),Co({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function Dd(e){const t=rt(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),Co({kind:"folders-set"})}function xd(e,t="local"){const n=rt(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),Co({kind:"folder-upserted",folderRowId:e.id,source:t})}function Rd(e,t="local"){const n=rt(),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(),Co({kind:"folder-removed",folderRowId:e,source:t})}function Md(e){return rt().subscribe(e)}function Yt(){return rt().getState()}function hv(e){const t=Yt(),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 te={getState:Yt,subscribe:Md,setFolderPlacements:qt,upsertPlacement:Od,upsertFolder:xd,removePlacement:Fs,removeFolder:Rd,currentPlacement:hv},zW=Ne`:host{display:inline-block}`,jW=Ne`:host{position:absolute;width:var( --os-ui-ribbon-size,90px );height:var( --os-ui-ribbon-size,90px );overflow:hidden;pointer-events:none;z-index:var( --os-ui-ribbon-z,2 )}:host( [ hidden ] ){display:none}.banner{position:absolute;display:block;width:var( --os-ui-ribbon-banner-width,140px );padding:var( --os-ui-ribbon-padding,4px 0 );text-align:center;font:var( --os-ui-ribbon-font,700 10px/1.4 var( --os-font,system-ui ) );letter-spacing:var( --os-ui-ribbon-tracking,0.06em );text-transform:uppercase;color:var( --os-ui-ribbon-fg,var( --os-ui-fg-on-accent,#fff ) );background:var( --os-ui-ribbon-bg,var( --wp-admin-theme-color,#2271b1 ) );background-size:260% 260%;background-position:30% 40%;box-shadow:var( --os-ui-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( --os-ui-ribbon-banner-offset,20px );inset-inline-end:var( --os-ui-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( --os-ui-ribbon-banner-offset,20px );inset-inline-start:var( --os-ui-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( --os-ui-ribbon-banner-offset,20px );inset-inline-end:var( --os-ui-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( --os-ui-ribbon-banner-offset,20px );inset-inline-start:var( --os-ui-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( --os-ui-ribbon-success,var( --os-ui-success-fg,#1a7f37 ) )}:host( [ tone='warning' ] ) .banner{background:var( --os-ui-ribbon-warning,var( --os-ui-warning-bg,#9a6700 ) )}:host( [ tone='danger' ] ) .banner{background:var( --os-ui-ribbon-danger,var( --os-ui-danger,#cf222e ) )}:host( [ tone='info' ] ) .banner{background:var( --os-ui-ribbon-info,var( --os-ui-info-bg,#0969da ) )}:host( [ tone='neutral' ] ) .banner{background:var( --os-ui-ribbon-neutral,var( --os-ui-surface,#57606a ) )}`,ui=class ui extends dn{render(){return no`<span class="banner" part="banner"><slot></slot></span>`}};ui.props=["placement","tone"],ui.styles=[jW],ui.help=void 0;let Wd=ui;cs("os-ribbon",Wd);const de="os-file-tile",mv={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function VW(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function KW(){return window.wp?.os?.dragManager??null}const qW=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],Mo=class Mo extends dn{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null,this._onSettingsSave=t=>{t.detail?.phase==="saved"&&this._paint()}}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this.click())},this.addEventListener("keydown",this._keydownHandler)),document.addEventListener("os-settings-save-lifecycle",this._onSettingsSave),this._paint()}disconnectedCallback(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null),this._keydownHandler&&(this.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),document.removeEventListener("os-settings-save-lifecycle",this._onSettingsSave)}requestUpdate(){this.isConnected&&this._paint()}attributeChangedCallback(t,n,o){if(n!==o){if(t==="selected"||t==="selectable"||t==="aria-selected"){this._paintSelection();return}super.attributeChangedCallback(t,n,o)}}_paintSelection(){const t=this.hasAttribute("selected"),n=this.hasAttribute("selectable");if(this.classList.toggle(`${de}--selected`,t),this.setAttribute("role",n?"option":"listitem"),n){const o=t?"true":"false";this.getAttribute("aria-selected")!==o&&this.setAttribute("aria-selected",o)}else this.removeAttribute("aria-selected")}render(){return no``}_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")??"",l=this.hasAttribute("selected"),c=this.hasAttribute("selectable"),d=this.hasAttribute("missing"),u=this.hasAttribute("access-gated"),f=[de,`${de}--folder`,`${de}--missing`,`${de}--access-gated`,`${de}--selected`];for(const E of f)this.classList.remove(E);this.classList.add(de),r==="folder"&&this.classList.add(`${de}--folder`),d&&this.classList.add(`${de}--missing`),u&&this.classList.add(`${de}--access-gated`),l&&this.classList.add(`${de}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",c?"option":"listitem"),c?this.setAttribute("aria-selected",l?"true":"false"):this.removeAttribute("aria-selected"),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.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const g=[`${de}__visual`,`${de}__label`,`${de}__lock`];for(const E of g)this.querySelectorAll(`:scope > .${E}`).forEach(k=>k.remove());this.querySelectorAll(":scope > os-ribbon").forEach(E=>E.remove());const h=document.createElement("span");if(h.className=`${de}__visual`,i){const E=document.createElement("img");E.src=i,E.alt="",E.loading="lazy",E.decoding="async",E.className=`${de}__preview`,E.draggable=!1,h.appendChild(E)}else if(s){const E=ln(s,{title:o,className:`${de}__icon`});h.appendChild(E)}this.appendChild(h);const m=document.createElement("span");if(m.className=`${de}__label`,m.textContent=o,this.appendChild(m),u){const E=document.createElement("span");E.className=`${de}__lock dashicons dashicons-lock`,E.setAttribute("aria-hidden","true"),this.appendChild(E)}if(a&&a!=="publish"&&mv[a]&&VW()){const E=document.createElement("os-ribbon");E.setAttribute("placement","top-end"),E.setAttribute("tone",YW(a)),E.textContent=mv[a],this.appendChild(E)}RE(this),L("os.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=KW();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,l=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-l.left,offsetY:o.clientY-l.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};Mo.shadow=!1,Mo.props=qW,Mo.styles=[zW],Mo.help=void 0;let Pd=Mo;function YW(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}cs("os-tile",Pd);function XW(e){const t=document.createElement("os-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=Q("os.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 ZW(e,t){const n=document.createElement("div");n.className="os-drag-stack";const o=e.getBoundingClientRect();n.style.width=`${o.width}px`,n.style.height=`${o.height}px`;const s=e.cloneNode(!0);s.removeAttribute("id"),s.removeAttribute("selected"),s.removeAttribute("aria-selected"),s.classList.remove(`${de}--selected`),s.style.left="0px",s.style.top="0px",s.style.position="relative",n.appendChild(s);const i=document.createElement("span");return i.className="os-drag-stack__count",i.textContent=String(t),n.appendChild(i),n}function gv(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:Vt(e.file).title()}function JW(e,t){const n=Vt(e.file),o=n.previewUrl(),s=gv(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:iy(e.file.ref)||i||e.file.type==="shortcut"&&Vo(Vn(e.file.ref))||Vo(pS(e.file.type))||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 QW(e,t){const n=XW(JW(e,t)),o=Q("os.files.tile-class",de,e);o&&o!==de&&(n.className=o);const s=Q("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=hv(e),a=Vt(r.file);if(r.accessGated){ue({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}Us(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),L("os.files.tile-rendered",{tile:n,placement:e}),n}function _n(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const eP=se("desktop-mode/tile-payload-handlers",()=>({handlers:new Map}));function Hs(){return eP.state.handlers}function Gs(e,t){const n=Hs().get(e);return n?n.push(t):Hs().set(e,[t]),()=>{const o=Hs().get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&Hs().delete(e)}}function $d(e,t){const n=Hs().get(e);if(n)return n.find(o=>o.appliesTo(t))}function tP(e,t){return $d(e,t)?.acceptLabel}function nP(e,t){const n=$d(e.type,t);return n?n.accept(e.data,t):!1}function oP(e,t,n){const o=$d(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function sP(e,t,n){const o=t.slice().sort((s,i)=>{const r=typeof s.sort=="number"?s.sort:100,a=typeof i.sort=="number"?i.sort:100;return r!==a?r-a:s.label.localeCompare(i.label)});o.length!==0&&DM(e,{actions:o,scope:"files.tile",dataset:{placementId:String(n.placementIds[0]??""),placementIds:n.placementIds.join(",")},onOpened:s=>{L("os.files.tile-menu.opened",{placementId:n.placementIds[0],placementIds:n.placementIds.slice(),items:s})},onClosed:()=>{L("os.files.tile-menu.closed",{})}})}const iP="my-wordpress",Lo=se("desktop-mode/my-wordpress/open-target",()=>({kind:null,entityId:"",id:0,title:"",requestedAt:0}));function rP(e){Lo.state.kind=e.kind,Lo.state.entityId=e.entityId,Lo.state.id=e.id,Lo.state.title=e.title,Lo.state.requestedAt=Date.now(),Lo.notify()}function aP(e){const t=window.wp?.os?.openWindow;t?.(iP,{source:e})}function wv(e){const t=Number(e.postId);!Number.isFinite(t)||t<=0||(rP({kind:"detail",entityId:e.entityId||"posts",id:t,title:e.postTitle??""}),aP("my-wordpress/open-detail"))}function cP(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function Ud(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function Bd(e){const t=()=>{const n=e.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};t()||queueMicrotask(()=>void t())}const He="os-create-folder-dialog";let zs=null;function Fd(){zs&&(zs.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),zs.remove(),zs=null,L("os.files.create-folder.closed",{}))}function Hd(e){if(Fd(),Q("os.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${He}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=He,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${He}-title`);const i=document.createElement("h2");i.id=`${He}-title`,i.className=`${He}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${He}__field`,r.id=`${He}-input`,r.setAttribute("label",e.label??"Folder name"),r.setAttribute("value",n),r.setAttribute("autocomplete","off"),r.setAttribute("spellcheck","false"),s.appendChild(r);const a=document.createElement("p");a.className=`${He}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const l=document.createElement("div");l.className=`${He}__actions`;const c=document.createElement("os-button");c.className=`${He}__btn ${He}__btn--secondary`,c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className=`${He}__btn ${He}__btn--primary`,d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(d),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),zs=o,Bd(r),L("os.files.create-folder.opened",{});const u=m=>{Ud(r,m),Ud(c,m),Ud(d,m),s.classList.toggle(`${He}--busy`,m)},f=m=>{a.textContent=m,a.hidden=!1},p=()=>{Fd(),e.onCancel?.()},g=async()=>{const m=cP(r).trim();if(!m){f("Please enter a name."),Bd(r);return}a.hidden=!0,u(!0);try{await e.onSubmit(m),Fd()}catch(E){u(!1),f(E instanceof Error?E.message:"Could not create the folder."),Bd(r)}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void g()),o.addEventListener("click",m=>{m.target===o&&p()});const h=m=>{m.key==="Escape"?(m.preventDefault(),p()):m.key==="Enter"&&!m.isComposing&&(m.preventDefault(),g())};s.addEventListener("keydown",h),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",h)})}function Br(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function lP(e){return e.id<=0||Br(e)!==null}function yv(e){e.length!==0&&qC(e)}const dP="rest_cookie_invalid_nonce",bv=()=>b("Could not reach the site. Check your connection and try again.","desktop-mode");function vv(e){return typeof navigator<"u"&&navigator.onLine===!1?!0:e instanceof TypeError}function uP(e){return ef(e)?e.code===dP||e.status===401?"session":e.status>=200&&e.status<300?"unreadable":e.status===404?"gone":e.status>=500?"server":e.status>=400?"refused":"unknown":vv(e)?"offline":"unknown"}function _v(e){return ef(e)?e.serverMessage:vv(e)?bv():e instanceof Error?e.message:""}function fP(e,t){const{fallback:n,lead:o}=t,s=uP(e),i=s==="offline"||s==="unreadable"?"warning":"error";let r="",a=!0;switch(s){case"offline":r=bv();break;case"session":r=b("Your session has expired. Reload the page and try again.","desktop-mode");break;case"unreadable":r=b("The site sent an unreadable reply. Reload the page to check whether the change went through.","desktop-mode");break;case"gone":case"refused":case"server":{const c=e;c.serverMessage?r=c.serverMessage:s==="gone"?(r=b("It no longer exists. Reload the page to catch up.","desktop-mode"),a=!1):s==="server"?(r=le(b("The server answered with error %d.","desktop-mode"),c.status),a=!1):(r=le(b("The server refused the request (HTTP %d).","desktop-mode"),c.status),a=!1);break}case"unknown":default:r=_v(e);break}let l;return o?l=r?`${o}: ${r}`:n:r?a?l=r:l=`${n} ${r}`:l=n,{message:l,reason:r,kind:s,type:i}}function En(e,t,n){if(!e)return;const{duration:o,...s}=n,i=fP(t,s),r={message:i.message,type:i.type};o&&(r.duration=o),e(r)}function Ev(e){const t=window.wp?.os;return typeof t?.showToast!="function"?()=>{}:t.showToast(e)??(()=>{})}function To(e,t,n){Fg(e,t,n,"desktop-files")}function Fr(e){En(Ev,e,{fallback:"Could not move this item to the recycle bin.",duration:5e3})}function Gd(e,t){Ev({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function kv(e){const t=hn(go(e));if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Item",i=e.file?.type==="shortcut"?"shortcut":"placement";te.removePlacement(n);try{await Ld(n),To(i,"trashed",[n]),t.finish(!0),Gd(`"${s}" moved to Trash`,async()=>{const r=hn(go(e),"out");try{await $r(n,"placement");const a=await Ue(o);te.setFolderPlacements(o,a.placements),To(i,"untrashed",[n]),r?.finish(!0)}catch(a){r?.finish(!1),console.error("[openstation] restore failed:",a)}})}catch(r){console.error("[openstation] deletePlacement failed:",r),t.finish(!1),te.upsertPlacement(e),Fr(r),Ue(o).then(a=>{te.setFolderPlacements(o,a.placements)}).catch(()=>{})}}async function Sv(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=hn(go(e));if(!n)return;const o=e.id,s=e.parentId,i=e.file?.title??"Folder";te.removePlacement(o);const r=te.getState().folders.get(t);te.removeFolder(t);try{await Nd(t),To("folder","trashed",[t]),n.finish(!0),Gd(`"${i}" moved to Trash`,async()=>{const a=hn(go(e),"out");try{await $r(t,"folder");const l=await Ue(s);te.setFolderPlacements(s,l.placements),To("folder","untrashed",[t]),a?.finish(!0)}catch(l){a?.finish(!1),console.error("[openstation] restore folder failed:",l)}})}catch(a){console.error("[openstation] deleteFolder failed:",a),r&&te.upsertFolder(r),n.finish(!1),te.upsertPlacement(e),Fr(a),Ue(s).then(l=>{te.setFolderPlacements(s,l.placements)}).catch(()=>{})}}async function Iv(e){if(e.length===0)return;if(e.length===1)return pP(e[0]);const t=new Map(e.map(d=>[d.id,hn(go(d))]));e=e.filter(d=>t.get(d.id));const n=new Map(te.getState().folders),o=new Set;for(const d of e)if(o.add(d.parentId),te.removePlacement(d.id),d.file?.type==="folder"){const u=parseInt(d.file.ref,10);u&&te.removeFolder(u)}const s=async()=>{for(const d of o)try{const u=await Ue(d);te.setFolderPlacements(d,u.placements)}catch(u){console.error("[openstation] files: re-hydrate failed:",u)}},i=await Promise.allSettled(e.map(async d=>{if(d.file?.type==="folder"){const u=parseInt(d.file.ref,10);if(!u)throw new Error("folder placement without a folder id");return await Nd(u),{id:u,kind:"folder",restoreId:u,restoreKind:"folder"}}return await Ld(d.id),{id:d.id,kind:d.file?.type==="shortcut"?"shortcut":"placement",restoreId:d.id,restoreKind:"placement"}}));i.forEach((d,u)=>{if(d.status==="rejected"){const f=e[u];te.upsertPlacement(f);const p=f.file.type==="folder"&&n.get(Number(f.file.ref));p&&te.upsertFolder(p),t.get(e[u].id)?.finish(!1)}});const r=[];let a=0;for(const d of i)d.status==="fulfilled"?r.push(d.value):(a+=1,console.error("[openstation] trash (bulk) failed for one item:",d.reason));if(a>0&&s(),r.length===0){Fr(i.find(d=>d.status==="rejected")?.reason);return}for(const d of["placement","shortcut","folder"]){const u=r.filter(f=>f.kind===d).map(f=>f.id);u.length>0&&To(d,"trashed",u)}i.forEach((d,u)=>{d.status==="fulfilled"&&t.get(e[u].id)?.finish(!0)});const l=r.length===1?"item":"items",c=a>0?`${r.length} ${l} moved to Trash · ${a} could not be moved`:`${r.length} ${l} moved to Trash`;Gd(c,async()=>{const d=r.map(g=>{const h=e.find(m=>m.file.type==="folder"?Number(m.file.ref)===g.id&&g.kind==="folder":m.id===g.id&&g.kind!=="folder");return h?hn(go(h),"out"):null}),u=await Promise.allSettled(r.map(g=>$r(g.restoreId,g.restoreKind)));await s();const f=r.filter((g,h)=>u[h].status==="fulfilled"),p=r.length-f.length;for(const g of u)g.status==="rejected"&&console.error("[openstation] restore (bulk) failed for one item:",g.reason);for(const g of["placement","shortcut","folder"]){const h=f.filter(m=>m.kind===g).map(m=>m.id);h.length>0&&To(g,"untrashed",h)}u.forEach((g,h)=>{d[h]?.finish(g.status==="fulfilled")}),p>0&&Fr(new Error(`${p} of ${r.length} items could not be restored.`))})}function pP(e){return e.file?.type==="folder"?Sv(e):kv(e)}const hP=5,Av=e=>Iv(e);async function mP(e){if(!(e.length>hP&&!await rn({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await Us(Vt(t.file))}function gP(e){const t=parseInt(e.file.ref,10);t&&Hd({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:e.file.title,onSubmit:async n=>{const o=n.trim();if(!o||o===e.file.title)return;const s=e.file.title,i={...e,file:{...e.file,title:o}};te.upsertPlacement(i);try{const r=te.getState().folders.get(t)?.updatedAtMs??0,a=await av(t,{name:o},r);te.upsertFolder(a);const l=await Ue(e.parentId);te.setFolderPlacements(e.parentId,l.placements)}catch(r){console.error("[openstation] rename folder failed:",r),te.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function wP(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=typeof e.file.postType=="string"?e.file.postType:"post";wv({entityId:n==="page"?"pages":"posts",postId:t,postTitle:e.file.title||`#${t}`})}function yP(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>mP(i),onClick:()=>{Us(Vt(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>wP(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>gP(e)}),e.canTrash!==!1&&t.push({id:"delete-folder",multiId:"trash",label:"Move folder to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:i=>`Move ${i} items to Trash`,bulk:Av,onClick:()=>Sv(e)});else{const i=Br(e),r=e.file.type==="shortcut";if(i||r){const a=i??e.file.ref;t.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,multi:!0,bulkLabel:l=>`Hide ${l} items from desktop`,bulk:l=>{yv(l.map(c=>Br(c)??c.file.ref).filter(c=>!!c))},onClick:()=>yv([a])})}else e.canTrash!==!1&&t.push({id:"remove",multiId:"trash",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:a=>`Move ${a} items to Trash`,bulk:Av,onClick:()=>kv(e)})}const o=Q("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const Xt=16,Cv=88,Lv=104,bP=20,vP=16,zd=Cv+bP,jd=Lv+vP;function js(e,t){const n=Math.max(0,Math.round((e-Xt)/zd)),o=Math.max(0,Math.round((t-Xt)/jd));return No(n,o)}function No(e,t){return{col:e,row:t,x:Xt+e*zd,y:Xt+t*jd}}const _P=5,EP=4;function Vs(e){if(!e)return{width:0,height:0};if(typeof HTMLElement<"u"&&e instanceof HTMLElement)return{width:e.clientWidth,height:e.clientHeight};const t=e;return{width:typeof t.width=="number"?t.width:0,height:typeof t.height=="number"?t.height:0}}function kP(e){const t=Vs(e).height;return t<=0?_P:Math.max(1,Math.floor((t-Xt)/jd))}function SP(e){const t=Vs(e).width;return t<=0?EP:Math.max(1,Math.floor((t-Xt)/zd))}const Tv=999;function Ks(e,t="column",n){if(t==="row"){const s=SP(n);for(let i=0;i<Tv;i++)for(let r=0;r<s;r++)if(!e.has(De(r,i)))return No(r,i);return No(0,0)}const o=kP(n);for(let s=0;s<Tv;s++)for(let i=0;i<o;i++)if(!e.has(De(s,i)))return No(s,i);return No(0,0)}function Nv(e,t,n="column",o){const s=new Set(t),i=[];for(let r=0;r<e;r++){const a=Ks(s,n,o);s.add(De(a.col,a.row)),i.push(a)}return i}function kn(e,t,n,o,s="column"){const i=js(e,t);return n.has(De(i.col,i.row))?Ks(n,s,o):i}function Ov(e,t){const n=new Set;for(const o of e){const s=js(o.x,o.y);n.add(De(s.col,s.row))}return n}function De(e,t){return`${e},${t}`}function IP(e){const t=String(e),{placementsByFolder:n}=rt().state;for(const o of n.values())for(const s of o)if(s.file?.type==="folder"&&s.file.ref===t)return s.file}function AP(e,t){const n=IP(e);if(n)return Vt(n);const o=rt().state.folders.get(e);return Vt({type:"folder",ref:String(e),title:o?.name||t||"Folder",icon:hW,previewUrl:"",exists:!0})}function Dv(e){return e instanceof Cd}function CP(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 xv(e){const t=CP(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{Us(AP(n,e.detail.current.parentName))}}),ue({message:t,action:o,duration:7e3})}const LP=se("desktop-mode/canvas-payload-handlers",()=>({handlers:new Map}));function Rv(){return LP.state.handlers}function TP(e,t){const n=Rv().get(e.type);return n?n.accept(e.data,t):!1}function NP(e,t,n){const o=Rv().get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function Sn(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function Hr(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}const Mv="application/x-wp-media-attachment",Wv="data-files-drop-active";function Pv(){const e=window.wp?.os?.dragBridge;if(!e)return null;try{return e.getPayload()}catch{return null}}function $v(e){if(!e)return null;switch(e.kind){case"attachment":case"post":case"user":return typeof e.id!="number"?null:{kind:e.kind,ref:String(e.id),title:e.title};default:return null}}function OP(e){if(!e)return null;let t="";try{t=e.getData(Mv)}catch{return null}if(!t)return null;try{const n=JSON.parse(t),o=typeof n.id=="number"?n.id:Number(n.id);return!Number.isFinite(o)||o<=0?null:{kind:"attachment",ref:String(o),title:typeof n.title=="string"?n.title:void 0}}catch{return null}}function Uv(e){const t=e.dataTransfer?.types,n=t?Array.from(t):[];return n.includes("Files")?!1:n.includes(Mv)?!0:$v(Pv())!==null}function Bv(e,t,n){if(!(e instanceof Element)||!t.contains(e))return!1;let o=e;for(;o&&o!==t;){if(o===n)return!0;if(o.classList.contains("wp-window")||o.id==="os-widgets")return!1;o=o.parentElement}return o===t}function Fv(e,t){if(!(e instanceof Element))return null;const n=e.closest(`.${de}`);return!(n instanceof HTMLElement)||!t.contains(n)?null:n.dataset.fileType==="folder"?n:null}function DP(e){const{host:t,container:n,folderId:o}=e;let s=null;const i=()=>{t.removeAttribute(Wv),s&&(s.classList.remove(`${de}--drop-target`),s=null)},r=c=>{if(!Uv(c))return;if(!Bv(c.target,t,n)){i();return}c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),t.setAttribute(Wv,"");const d=Fv(c.target,n);d!==s&&(s?.classList.remove(`${de}--drop-target`),d?.classList.add(`${de}--drop-target`),s=d)},a=c=>{const d=c.relatedTarget;d instanceof Node&&t.contains(d)||i()},l=c=>{if(!Uv(c))return;if(!Bv(c.target,t,n)){i();return}i(),c.preventDefault(),c.stopPropagation();const d=$v(Pv())??OP(c.dataTransfer);if(!d)return;const u=Fv(c.target,n);let f=o;if(u){const p=parseInt(u.getAttribute("ref")??"",10);!Number.isNaN(p)&&p>0&&(f=p)}e.fileEntities([d],f)};return t.addEventListener("dragover",r),t.addEventListener("dragleave",a),t.addEventListener("drop",l),()=>{i(),t.removeEventListener("dragover",r),t.removeEventListener("dragleave",a),t.removeEventListener("drop",l)}}function xP(){return window.openStationConfig?.desktopStorage?.canAddToMedia===!0}function RP(e){if(e.type!=="upload"||e.isMedia!==!0||!xP())return;const t=parseInt(String(e.ref??""),10);if(!(!Number.isFinite(t)||t<=0))return{kind:"upload",fileId:t,title:String(e.title??""),mime:String(e.mime??""),thumbnailUrl:e.previewUrl?String(e.previewUrl):void 0}}async function MP(e){if(e.kind!=="upload")return null;try{const t=await Ur(e.fileId);return{kind:"attachment",id:t.attachmentId,url:t.url,title:t.title||e.title,alt:"",mime:e.mime,thumbnailUrl:e.thumbnailUrl}}catch(t){return En(ue,t,{lead:"Could not add to the Media Library",fallback:"Could not add to the Media Library."}),null}}function WP(){return rR("upload",MP)}function PP(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};if(t.type==="upload")return RP(t)}function qs(){return window.wp?.os?.dragManager??null}const $P="os-files-layer";function Ys(e){return e===0?"column":"row"}function UP(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function Vd(e,t){return t!==0||!e?e:{get width(){return he(e).width},get height(){return he(e).height}}}function Hv(e,t=0){const n=Ys(t),o=Vd(e,t),s=document.createElement("div");s.className=$P,s.setAttribute("role","list"),s.dataset.folderId=String(t),e.appendChild(s);let i="",r=!1;const a=C=>{const U=te.getState().placementsByFolder.get(t)??[],B=new Map;for(const z of U)z&&B.set(String(z.id),z);return C.map(z=>B.get(z)).filter(z=>!!z)},l=new Set,c=new Set,d=CM(s,{itemSelector:`.${de}`,background:e,surface:"files",scope:String(t),keyOf:C=>C.dataset.placementId??null,onChange:C=>{const U=a(C),B=U.length===1?U[0]:null;for(const z of l)try{z(B)}catch(_){console.error("[openstation] files: selection listener threw:",_)}for(const z of c)try{z(U)}catch(_){console.error("[openstation] files: selection listener threw:",_)}}}),u=()=>a(d.keys()),f=C=>Kd(C,o,n),p=(C,U,B,z)=>{const _=B.get(U.id),v=z.get(U.id);_?_n(C,_.x,_.y):v?_n(C,v.x,v.y):_n(C,U.x,U.y)},g=(C,U,B)=>{const z=QW(C,t),_=U.get(C.id);if(_){if(_n(z,_.x,_.y),z.classList.add(`${de}--pinned`),Kv(z,C,d,u),Gv(C)){const A=qs();A&&N.set(C.id,Vv(A,z,C))}return z}const v=B.get(C.id);if(v&&_n(z,v.x,v.y),VP(z,C,t,d,u),Kv(z,C,d,u),C.file.type==="folder"){const A=parseInt(C.file.ref,10);if(A>0){const O=qs();if(O){const P=jP(O,z,A);k.set(C.id,P)}}}else if(Gv(C)){const A=qs();A&&N.set(C.id,Vv(A,z,C))}return z},h=C=>{const U=new Map;for(const v of s.querySelectorAll("[data-placement-id]")){const A=v.dataset.placementId??"",O=parseInt(A,10);if(A===""||Number.isNaN(O)&&A!=="-0")return!1;U.set(O,v)}const B=new Set;for(const v of C)B.add(v.id);for(const v of C){const A=U.get(v.id);if(!A)continue;if(A.dataset.fileType!==v.file.type||A.dataset.fileRef!==v.file.ref||A.classList.contains(`${de}--pinned`)!==Re(v))return!1}for(const[v,A]of U){if(B.has(v))continue;const O=k.get(v);if(O){try{O()}catch{}k.delete(v)}const P=N.get(v);if(P){try{P()}catch{}N.delete(v)}A.remove()}const{pinnedSlots:z,displaced:_}=f(C);for(const v of C){const A=U.get(v.id);if(A){p(A,v,z,_),jv(A,v);continue}s.appendChild(g(v,z,_))}return d.refresh(),L("os.files.grid-rendered",{folderId:t,count:C.length}),!0},m=C=>{const B=(C.placementsByFolder.get(t)??[]).slice().sort((O,P)=>{const Z=Re(O)?0:1,V=Re(P)?0:1;return Z-V}),z=BP(B);if(z===i&&!r)return;i=z;const _=r;if(r=!1,!_&&zP(B,s,o,n)||!_&&h(B))return;s.replaceChildren();for(const[,O]of k)try{O()}catch{}k.clear();for(const[,O]of N)try{O()}catch{}N.clear();const{pinnedSlots:v,displaced:A}=f(B);for(const O of B)s.appendChild(g(O,v,A));d.refresh(),L("os.files.grid-rendered",{folderId:t,count:B.length})},E=[],k=new Map,N=new Map;let M=null,S=null;const $=C=>{if(M||C.payload.type!=="desktop-file")return;const U=document.createElement("div");U.className="os-files-drop-preview",U.setAttribute("aria-hidden","true"),s.appendChild(U),M=U;const B=C.payload.ghost,z=B?.offsetX??0,_=B?.offsetY??0,A=C.payload.data?.placement?.id,O=(V,ge)=>{const Te=s.getBoundingClientRect(),Y=Math.max(0,V-Te.left-z),ae=Math.max(0,ge-Te.top-_),be=te.getState().placementsByFolder.get(t)??[],wt=Gr(be,A),xe=kn(Y,ae,wt,o,n);U.style.transform=`translate3d(${xe.x}px, ${xe.y}px, 0)`},P=C.payload.source.getBoundingClientRect();O(P.left+z,P.top+_);const Z=V=>{O(V.clientX,V.clientY)};document.addEventListener("pointermove",Z),S=Z},W=()=>{S&&(document.removeEventListener("pointermove",S),S=null),M&&(M.remove(),M=null)},F={id:`os-files-canvas-${t}`,element:e,accept:C=>{if(C.type!=="desktop-file"&&C.type!=="shortcut")return TP(C,{folderId:t,host:e});if(t>0&&C.type==="desktop-file"){const U=C.data;for(const B of Sn(U)){if(B.file?.type!=="folder")continue;const z=parseInt(B.file.ref,10);if(!Number.isNaN(z)&&zv(z,t))return!1}}return!0},onEnter:C=>{e.setAttribute("data-files-drop-active",""),(C.payload.type==="desktop-file"||C.payload.type==="shortcut")&&$(C)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),W()},onDrop:(C,U)=>{if(e.removeAttribute("data-files-drop-active"),W(),C.payload.type!=="desktop-file"&&C.payload.type!=="shortcut"){NP(C,U,{folderId:t,host:e});return}const B=s.getBoundingClientRect(),z=C.payload.ghost,_=z?.offsetX??0,v=z?.offsetY??0,A=Math.max(0,U.clientX-B.left-_),O=Math.max(0,U.clientY-B.top-v),P=te.getState().placementsByFolder.get(t)??[];if(C.payload.type==="desktop-file"){const Z=C.payload.data,V=Sn(Z),ge=new Set(V.map(ae=>ae.id)),Te=Gr(P,ge),Y=kn(A,O,Te,o,n);Te.add(De(Y.col,Y.row));for(const ae of V){let be=Y;if(ae.id!==Z.placement.id){const xe=ae.x-Z.placement.x,ma=ae.y-Z.placement.y;be=kn(Math.max(0,Y.x+xe),Math.max(0,Y.y+ma),Te,o,n),Te.add(De(be.col,be.row))}const wt={...ae,x:be.x,y:be.y,parentId:t};if(te.upsertPlacement(wt),L("os.files.tile-manually-placed",{folderId:t,placementId:ae.id}),Xs(ae)){const xe=Br(ae);xe&&GP(xe,be.x,be.y);continue}bn(ae.id,{x:be.x,y:be.y,parentId:t},ae.updatedAtMs).then(xe=>{te.upsertPlacement(xe,"remote")}).catch(xe=>{Dv(xe)?xv(xe):console.error("[openstation] files: drag persist failed",xe),te.upsertPlacement(ae)})}return}if(C.payload.type==="shortcut"){const Z=C.payload.data;qd(Hr(Z),t,e)}}},x=qs();if(x&&E.push(x.registerDropTarget(F)),E.push(DP({host:e,container:s,folderId:t,fileEntities:(C,U)=>{qd(C,U,U===t?e:null)}})),!te.getState().hydratedFolders.has(t)){const C=UP(t);C&&te.setFolderPlacements(t,C)}m(te.getState()),queueMicrotask(()=>ne());const q=te.subscribe(C=>{m(C),ne()}),J=()=>{r=!0,m(te.getState())};document.addEventListener("os-desktop-theme-changed",J);let X=()=>{};const T=new Promise(C=>{X=C});te.getState().hydratedFolders.has(t)?queueMicrotask(X):Ue(t).then(C=>{te.setFolderPlacements(t,C.placements)}).catch(C=>{console.error("[openstation] files: failed to hydrate folder",t,C)}).finally(()=>{X()});const D=C=>{const U=new Set;for(let B=0;B<C;B+=1)U.add(De(0,B));return U},K=(C,U)=>{const B=C.slice();switch(U){case"name-asc":B.sort((z,_)=>z.file.title.localeCompare(_.file.title));break;case"name-desc":B.sort((z,_)=>_.file.title.localeCompare(z.file.title));break;case"date-asc":B.sort((z,_)=>z.updatedAtMs-_.updatedAtMs);break;case"date-desc":B.sort((z,_)=>_.updatedAtMs-z.updatedAtMs);break}return B},G=C=>{const U=te.getState().placementsByFolder.get(t);if(!U||U.length===0)return;const B=U.filter(A=>Re(A)),z=U.filter(A=>!Re(A)),_=K(z,C),v=Nv(_.length,D(B.length),n,o);_.forEach((A,O)=>{const{x:P,y:Z}=v[O],V={...A,x:P,y:Z,sortOrder:O};te.upsertPlacement(V),!Xs(A)&&bn(A.id,{x:P,y:Z,sortOrder:O}).catch(ge=>{console.error("[openstation] files: sort persist failed",ge)})})},ne=()=>{const C=te.getState().placementsByFolder.get(t);if(!C||C.length===0)return;const U=Vs(o),B=U.width>0?U.width:1/0,z=U.height>0?U.height:1/0;if(!C.some(P=>P.x+Cv>B||P.y+Lv>z))return;const v=C.filter(P=>Re(P)),A=C.filter(P=>!Re(P)),O=Nv(A.length,D(v.length),n,o);A.forEach((P,Z)=>{const V=s.querySelector(`[data-placement-id="${P.id}"]`);V&&_n(V,O[Z].x,O[Z].y)})};let ce=Vs(o),R=null;return typeof ResizeObserver<"u"&&(R=new ResizeObserver(()=>{const C=Vs(o);C.width===ce.width&&C.height===ce.height||(ce=C,ne())}),R.observe(e)),{host:e,folderId:t,onSelectionChange(C){return l.add(C),()=>{l.delete(C)}},onSelectionChanged(C){return c.add(C),()=>{c.delete(C)}},getSelection:u,selectAll:()=>d.model.selectAll(),clearSelection:()=>d.model.clear(),sort:G,reflow:ne,hydrated:T,dispose(){q(),document.removeEventListener("os-desktop-theme-changed",J),R?.disconnect(),R=null;for(const C of E)try{C()}catch{}E.length=0;for(const C of k.values())try{C()}catch{}k.clear();for(const C of N.values())try{C()}catch{}N.clear(),d.destroy(),l.clear(),c.clear(),s.remove()}}}function BP(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}:${Re(n)?1:0}`);return t.join("|")}function Re(e){return!!e.file.pinned}function Kd(e,t,n){const o=new Map,s=new Set;let i=0;for(const a of e){if(!Re(a))continue;const l=No(0,i);o.set(a.id,{x:l.x,y:l.y}),s.add(De(l.col,l.row)),i+=1}const r=new Map;for(const a of e){if(o.has(a.id))continue;const l=js(a.x,a.y),c=De(l.col,l.row);if(!s.has(c)){s.add(c);continue}const d=kn(a.x,a.y,s,t,n);s.add(De(d.col,d.row)),r.set(a.id,{x:d.x,y:d.y})}return{pinnedSlots:o,displaced:r}}function FP(e,t){if(t.length===0)return;const n=new Set(t),o=te.getState().placementsByFolder.get(0)??[],s=f=>f.file?.type==="shortcut"&&n.has(f.file.ref)&&!Re(f)&&!Xs(f),i=o.filter(s).sort((f,p)=>f.id-p.id);if(i.length===0)return;const r=Vd(e,0),a=Ys(0),l=o.filter(f=>!s(f)).sort((f,p)=>(Re(f)?0:1)-(Re(p)?0:1)),{pinnedSlots:c,displaced:d}=Kd(l,r,a),u=new Set;for(const f of l){const p=c.get(f.id)??d.get(f.id)??f,g=js(p.x,p.y);u.add(De(g.col,g.row))}for(const f of i){const p=Ks(u,a,r);u.add(De(p.col,p.row)),!(p.x===f.x&&p.y===f.y)&&(te.upsertPlacement({...f,x:p.x,y:p.y}),bn(f.id,{x:p.x,y:p.y}).catch(g=>{console.error("[openstation] files: placing a new desktop icon failed",g)}))}}function Xs(e){return lP(e)}const HP="desktop-mode-recycle-bin";function Gv(e){return!(e.file?.type==="folder"||e.file?.ref===HP)}function Gr(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,a)=>{const l=Re(r)?0:1,c=Re(a)?0:1;return l-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(Re(r))s.add(De(0,i)),i+=1;else{const a=js(r.x,r.y);s.add(De(a.col,a.row))}return s}function qd(e,t,n){const o=te.getState().placementsByFolder.get(t)??[],s=Gr(o),i=Ys(t);for(const r of e){const a=Ks(s,i,Vd(n,t));s.add(De(a.col,a.row)),Bs({parentId:t,type:r.kind,ref:r.ref,x:a.x,y:a.y}).then(l=>{te.upsertPlacement(l),L("os.files.shortcut-dropped",{folderId:t,placement:l})}).catch(l=>{console.error("[openstation] shortcut drop failed:",l)})}}function zv(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=te.getState();for(const a of o.placementsByFolder.values())for(const l of a){if(l.file?.type!=="folder")continue;const c=parseInt(l.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,l.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 GP(e,t,n){const o=window.wp?.os;if(!o?.getOsSettings||!o?.updateOsSettings)return;const s=o.getOsSettings().dockPromotedPositions??{};o.updateOsSettings({dockPromotedPositions:{...s,[e]:{x:t,y:n}}})}function zP(e,t,n,o){const s=Array.from(t.querySelectorAll("[data-placement-id]"));if(s.length!==e.length)return!1;const i=new Map;for(const l of s){const c=l.dataset.placementId??"",d=parseInt(c,10);if(c===""||Number.isNaN(d)&&c!=="-0")return!1;i.set(d,l)}for(const l of e){const c=i.get(l.id);if(!c||c.dataset.fileType!==l.file.type||c.dataset.fileRef!==l.file.ref||c.classList.contains(`${de}--pinned`)!==Re(l))return!1}const{pinnedSlots:r,displaced:a}=Kd(e,n,o);for(const l of e){const c=i.get(l.id);if(!c)continue;const d=r.get(l.id)??a.get(l.id)??{x:l.x,y:l.y};_n(c,d.x,d.y),jv(c,l)}return!0}function jv(e,t){const n=gv(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function Vv(e,t,n){const o={placement:n};let s=null;return e.registerDropTarget({id:`os-files-tile-${n.id}-reject`,element:t,get acceptLabel(){return s?tP(s,o):void 0},accept:i=>(s=i.type,nP(i,o)),onEnter:()=>{t.classList.add(`${de}--drop-target`)},onLeave:()=>{t.classList.remove(`${de}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${de}--drop-target`),oP(i,r,o)}})}function jP(e,t,n,o){const s={id:`os-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;for(const a of Sn(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||Xs(a))return!1;if(a.file.type==="folder"){const l=parseInt(a.file.ref,10);if(!Number.isNaN(l)&&zv(l,n))return!1}}}return!0},onEnter:()=>{t.classList.add(`${de}--drop-target`)},onLeave:()=>{t.classList.remove(`${de}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${de}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a=te.getState().placementsByFolder.get(n)??[],l=Gr(a),c=Ys(n);for(const d of Sn(r)){const u=Ks(l,c);l.add(De(u.col,u.row)),te.upsertPlacement({...d,x:u.x,y:u.y,parentId:n}),bn(d.id,{x:u.x,y:u.y,parentId:n},d.updatedAtMs).then(f=>{te.upsertPlacement(f,"remote")}).catch(f=>{Dv(f)?xv(f):console.error("[openstation] files: move-into-folder persist failed",f),te.upsertPlacement(d)})}return}if(i.payload.type==="shortcut"){const r=i.payload.data;qd(Hr(r),n)}}};return e.registerDropTarget(s)}function VP(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=qs();if(!r)return;const l=te.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||l.x,parseFloat(e.style.top)||l.y;const c=o.model.has(String(l.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===l.id)?d:[l];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(l.id)])};document.addEventListener("os.drag.start",f);const p=()=>{document.removeEventListener("os.drag.start",f),document.removeEventListener("pointerup",p)};document.addEventListener("pointerup",p)}if(u.length>1){const f=[],p=()=>{for(const h of f)h.classList.remove(`${de}--dragging`);f.length=0,document.removeEventListener("os.drag.start",g),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},g=()=>{for(const h of u){const m=e.parentElement?.querySelector(`[data-placement-id="${h.id}"]`);m&&m!==e&&(m.classList.add(`${de}--dragging`),f.push(m))}};document.addEventListener("os.drag.start",g),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:e,data:{placement:l,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:PP(l)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?ZW(e,u.length):void 0,hint:u.length>1?{accept:`Move ${u.length} items here`,reject:`Can’t drop ${u.length} items here`,neutral:`Moving ${u.length} items`}:void 0}},origin:i})})}function Kv(e,t,n,o){e.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=te.currentPlacement(t);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),a=r.length>0?r:[i],l=gb(a,yP);sP({x:s.clientX,y:s.clientY},l,{placementIds:a.map(c=>c.id)})})}function qv(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 Oo="os-folder-status-bar";function KP(e,t,n={}){const o=document.createElement("div");o.className=Oo,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const a=Yt().placementsByFolder.get(t)??[],l=a.filter(p=>p.file.type==="folder").length,c=a.length-l;let d=0;for(const p of a)if(p.file.type==="upload"){const g=Number(p.file.sizeBytes??0);Number.isFinite(g)&&g>0&&(d+=g)}const u={folderId:t,selectedCount:n.selection?.count()??0,totals:{files:c,folders:l,total:a.length,bytes:d}},f=qP(u);YP(o,f)};s();const i=Md(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function qP(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:Xv(n,"file","files")+(t>0?`, ${Xv(t,"folder","folders")}`:"")+(o>0?` (${qv(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=Q("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function YP(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,l=typeof r.sort=="number"?r.sort:100;return a!==l?a-l: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(Yv("start",o)),e.appendChild(Yv("end",s))}function Yv(e,t){const n=document.createElement("div");n.className=`${Oo}__cluster ${Oo}__cluster--${e}`;for(const o of t)n.appendChild(XP(o));return n}function XP(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${Oo}__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=`${Oo}__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=`${Oo}__label`,o.textContent=e.label,n.appendChild(o),n}function Xv(e,t,n){return`${e} ${e===1?t:n}`}const zr="os-icon-canvas-menu";let Zs=null,jr=null,Yd=null,Js=null,Qs=null;function ZP(e,t){t.openOnBackgroundClick;const n=i=>{JP(i.target)||Zv(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(Yd===e&&Zs){In();return}const a=QP(t),l=Q("os.icon-canvas.menu",a,t.scope),c=Array.isArray(l)?l:a,d=++o;gi(()=>d===o,()=>e$(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),In()}}}function JP(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function Zv(e){return e instanceof Element?e.closest(`.${zr}`)!==null:!1}function QP(e){const n=[{id:"sort-by",label:b("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:b("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:b("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:b("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:b("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function Jv(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 e$(e,t,n){if(In(),e.length===0)return;Yd=n;const o=Jv(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(zr),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=Qv(s,r);Vr(r)&&a.addEventListener("mouseenter",()=>{e_(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,l=i.get(a.id);if(l){if(Vr(l)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${l.id}"]`);c&&e_(l,c);return}In(),l.onClick?.()}}),document.body.appendChild(s),Zs=s,nd(s),queueMicrotask(()=>{Js=r=>{Zv(r.target)||In()},Qs=r=>{r.key==="Escape"&&In()},document.addEventListener("mousedown",Js),document.addEventListener("keydown",Qs)})}function Qv(e,t){const n=document.createElement("os-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",t$(t.icon)),Vr(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function e_(e,t){if(t_(),!Vr(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(zr,`${zr}--flyout`);const o=new Map;for(const s of Jv(e.children??[]))o.set(s.id,s),Qv(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),In(),r.onClick?.())}),document.body.appendChild(n),jr=n,bb(n,t)}function Vr(e){return Array.isArray(e.children)&&e.children.length>0}function t_(){jr&&(jr.remove(),jr=null)}function In(){t_(),Zs&&(Zs.remove(),Zs=null),Yd=null,Js&&(document.removeEventListener("mousedown",Js),Js=null),Qs&&(document.removeEventListener("keydown",Qs),Qs=null)}function t$(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const An="os-breadcrumbs";function n$(e,t,n={}){if(e.replaceChildren(),e.classList.add(An),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${An}__back`,s.setAttribute("aria-label",b("Back","desktop-mode")),s.title=b("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=`${An}__crumbs`,o.setAttribute("aria-label",b("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const l=document.createElement("span");l.className=`${An}__sep`,l.setAttribute("aria-hidden","true"),l.textContent="›",o.appendChild(l)}if(!s.onClick){const l=document.createElement("span");l.className=`${An}__crumb ${An}__crumb--current`,l.setAttribute("aria-current","page"),l.textContent=s.label,o.appendChild(l);return}const r=document.createElement("button");r.type="button",r.className=`${An}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}function Kr(e){const t=document.createElement("a");t.href=e,t.setAttribute("download",""),t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async function ei(e,t={}){const n=await Ae(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":o$(),...t.headers??{}},...t});if(!n.ok)throw await Wn(n);return await n.json()}function o$(){return window.wp?.os?.config?.restNonce??""}function s$(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function ti(e){return nt(s$(),e)}function i$(e,t){const n=Q("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(r$(e));return}t.replaceChildren(w$()),a$(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(y$(o))})}function r$(e){const t=document.createElement("div");t.className="os-files__access-gated";const n=document.createElement("div");n.className="os-files__access-gated-ring";const o=document.createElement("span");o.className="dashicons dashicons-lock os-files__access-gated-glyph",o.setAttribute("aria-hidden","true"),n.appendChild(o),t.appendChild(n);const s=document.createElement("h2");s.className="os-files__access-gated-title",s.textContent="No permission to view",t.appendChild(s);const i=document.createElement("p");i.className="os-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="os-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 a$(e){const t=e.file;switch(t.type){case"post":return c$(t.ref,t);case"folder":return h$(t);case"shortcut":return m$(t);case"attachment":return f$(t.ref,t);case"upload":return p$(t);case"user":return l$(t.ref,t);case"term":return d$(t);case"comment":return u$(t.ref,t);case"bookmark":return g$(t);default:return at(t)}}async function c$(e,t){const n=parseInt(e,10);if(!n)return at(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await ei(ti(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return at(t);const s=mt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=qr(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="os-my-wordpress__article-meta";const a=[];if(a.push(n_(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="os-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const c=document.createElement("os-button");c.setAttribute("variant","secondary"),c.textContent=b("Explore details","desktop-mode"),c.title=b("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),c.addEventListener("click",()=>{const u=typeof t.postType=="string"?t.postType:"post";wv({entityId:u==="page"?"pages":"posts",postId:n,postTitle:qr(o.title.rendered)||`#${n}`})}),l.appendChild(c);const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=b("Open in editor","desktop-mode"),d.addEventListener("click",()=>{const u=window.wp?.os?.config?.adminUrl;if(!u)return;const f=`${u}post.php?post=${n}&action=edit`,p=window.wp?.os?.windowManager,h=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${h}-edit-${n}`,url:f,title:qr(o.title.rendered),icon:t.icon})}),l.appendChild(d),s.appendChild(l),s}async function l$(e,t){const n=parseInt(e,10);if(!n)return at(t);let o=null;try{o=await ei(ti(`desktop-mode/v1/user-stats/${n}`))}catch{return at(t)}const s=mt("os-my-wordpress__user"),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.profile.avatarUrl){const c=document.createElement("img");c.className="os-my-wordpress__user-avatar",c.src=o.profile.avatarUrl,c.alt="",i.appendChild(c)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");if(a.className="os-my-wordpress__article-title",a.textContent=o.profile.name||t.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const c=document.createElement("div");c.className="os-my-wordpress__user-roles";for(const d of o.profile.roleLabels){const u=document.createElement("span");u.className="os-my-wordpress__user-role",u.textContent=d,c.appendChild(u)}r.appendChild(c)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const c=document.createElement("div");c.className="os-my-wordpress__user-bio",c.textContent=o.profile.description,s.appendChild(c)}const l=document.createElement("div");return l.className="os-my-wordpress__user-stats",l.appendChild(Do(o.counts.posts.total.toLocaleString(),b("Posts","desktop-mode"))),l.appendChild(Do(o.counts.pages.total.toLocaleString(),b("Pages","desktop-mode"))),l.appendChild(Do(o.counts.commentsReceived.toLocaleString(),b("Comments received","desktop-mode"))),s.appendChild(l),s}async function d$(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return at(e);let o=null;try{o=await ei(ti(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return at(e)}const s=mt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=o.profile.name||e.title||`#${t}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const l=document.createElement("div");l.className="os-my-wordpress__article-content",l.innerHTML=o.profile.description,s.appendChild(l)}const a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(Do(o.counts.posts.total.toLocaleString(),b("Posts","desktop-mode"))),a.appendChild(Do(o.counts.commentsReceived.toLocaleString(),b("Comments","desktop-mode"))),a.appendChild(Do(o.counts.distinctAuthors.toLocaleString(),b("Authors","desktop-mode"))),s.appendChild(a),s}async function u$(e,t){const n=parseInt(e,10);if(!n)return at(t);let o=null;try{o=await ei(ti(`desktop-mode/v1/comment-stats/${n}`))}catch{return at(t)}const s=mt(),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.author.avatarUrl){const d=document.createElement("img");d.className="os-my-wordpress__user-avatar",d.src=o.author.avatarUrl,d.alt="",i.appendChild(d)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");a.className="os-my-wordpress__article-title",a.textContent=o.author.name,r.appendChild(a);const l=document.createElement("p");l.className="os-my-wordpress__article-meta",l.textContent=`${n_(o.comment.date)} · ${o.comment.status}`,r.appendChild(l),i.appendChild(r),s.appendChild(i);const c=document.createElement("div");if(c.className="os-my-wordpress__article-content",c.innerHTML=o.comment.rendered,s.appendChild(c),o.post){const d=document.createElement("div");d.className="os-my-wordpress__comment-post";const u=document.createElement("a");u.className="os-my-wordpress__comment-post-title",u.href=o.post.link,u.target="_blank",u.rel="noopener noreferrer",u.textContent=o.post.title,d.appendChild(u),s.appendChild(d)}return s}async function f$(e,t){const n=parseInt(e,10);if(!n)return at(t);let o=null;try{o=await ei(ti(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return at(t)}const s=mt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=qr(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="os-my-wordpress__article-hero";const l=o.media_details?.sizes;a.src=l?.large?.source_url??l?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),l=document.createElement("a");l.href=o.source_url,l.textContent=o.source_url,l.target="_blank",l.rel="noopener noreferrer",a.appendChild(l),s.appendChild(a)}return s}function p$(e){const t=mt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Uploaded file","desktop-mode"),t.appendChild(n);const o=typeof e.mime=="string"?e.mime:"",s=typeof e.sizeBytes=="number"?e.sizeBytes:0,i=typeof e.kind=="string"?e.kind:"file",r=document.createElement("p");r.className="os-my-wordpress__article-meta",r.textContent=[o,s>0?qv(s):""].filter(Boolean).join(" · "),t.appendChild(r);const a=parseInt(e.ref,10),l=()=>{const c=document.createElement("p");return c.className="os-my-wordpress__article-meta os-files__no-preview",c.textContent=b("No preview available for this file type.","desktop-mode"),c};if(a>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=vn(a),c.alt=e.title||"",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="video"){const c=document.createElement("video");c.className="os-my-wordpress__article-hero",c.controls=!0,c.preload="metadata",c.src=vn(a),c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="audio"){const c=document.createElement("audio");c.controls=!0,c.preload="metadata",c.src=vn(a),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else t.appendChild(l());if(a>0){const c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=b("Download","desktop-mode"),d.addEventListener("click",()=>{Kr(vn(a))}),c.appendChild(d),t.appendChild(c)}return t}function h$(e){const t=mt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=b("Double-click to open.","desktop-mode"),t.appendChild(o),t}function m$(e){const t=mt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=b("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function g$(e){const t=mt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("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 at(e){const t=mt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||e.type,t.appendChild(n);const o=document.createElement("p");if(o.className="os-my-wordpress__article-meta",o.textContent=le(b("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="os-my-wordpress__article-meta",s.textContent=b("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function mt(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function Do(e,t){const n=document.createElement("div");n.className="os-my-wordpress__user-stat";const o=document.createElement("span");o.className="os-my-wordpress__user-stat-value",o.textContent=e,n.appendChild(o);const s=document.createElement("span");return s.className="os-my-wordpress__user-stat-label",s.textContent=t,n.appendChild(s),n}function w$(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function y$(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:b("Unknown error.","desktop-mode"),t}function qr(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function n_(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function o_(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=b("Select an item to preview it here.","desktop-mode"),e}function b$(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=le(b("%d items selected","desktop-mode"),e.length),t.appendChild(n);const o=new Map;for(const i of e){const r=i.file?.type||"item";o.set(r,(o.get(r)??0)+1)}const s=Array.from(o.entries()).sort((i,r)=>r[1]-i[1]||i[0].localeCompare(r[0])).map(([i,r])=>`${r} × ${i}`).join(" · ");if(s){const i=document.createElement("div");i.className="os-files-preview__selection-breakdown",i.textContent=s,t.appendChild(i)}return t}const Yr="desktop-mode-embed-",v$=800,_$=600,Xd=360,Zd=240,Xr=16,Jd=new Map;function E$(e,t){const n=e.ref();if(!n)return;const o=window.wp?.os?.windowManager;if(!o)return;const s=t?.placement,i=s?.meta??null,r=s?`${Yr}${s.id}`:`${Yr}anon-${A$(n)}`,a=i?.name?.trim()??"",l=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:l,icon:e.icon(),minWidth:Xd,minHeight:Zd},d=i?.window,u=document.getElementById("os-area"),f=u?he(u):{x:0,y:0,width:window.innerWidth,height:window.innerHeight};if(d&&Number.isFinite(d.width)&&Number.isFinite(d.height)){const{x:p,y:g,width:h,height:m}=I$(d,f);c.x=p,c.y=g,c.width=h,c.height=m}else c.width=Math.min(v$,Math.max(Xd,f.width-Xr*2)),c.height=Math.min(_$,Math.max(Zd,f.height-Xr*2));s&&d&&Jd.set(r,{...d}),o.open(c)}let s_=!1;function k$(){if(s_)return;s_=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(Yr))return;const s=o.slice(Yr.length),i=parseInt(s,10);if(!i)return;const l=window.wp?.os?.windowManager?.getById?.(o)?.element;if(!l)return;const c={x:l.offsetLeft,y:l.offsetTop,width:l.offsetWidth,height:l.offsetHeight},d=Jd.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(Jd.set(o,c),S$(i,c))};ee(y.WINDOW_DRAG_END,"os-embed-persist",e),ee(y.WINDOW_RESIZE_END,"os-embed-persist",e)}async function S$(e,t){try{const i={...(await Ue(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await bn(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function I$(e,t){const n=Math.max(Xd,Math.min(e.width,t.width-Xr)),o=Math.max(Zd,Math.min(e.height,t.height-Xr)),s=t.x+Math.max(0,t.width-n),i=t.y+Math.max(0,t.height-o),r=Math.max(t.x,Math.min(e.x,s)),a=Math.max(t.y,Math.min(e.y,i));return{x:r,y:a,width:n,height:o}}function A$(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 ni(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function i_(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 C$(){je({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ni()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),je({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ni()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),je({id:"agent-chat",label:b("Agent chat","desktop-mode"),types:["user"],isDefault:!0,sort:5,appliesTo:e=>e.shape.isAgent===!0,handler:{kind:"js",open:e=>{const t=e.shape;Ad({id:Number.parseInt(t.ref,10),name:t.title,description:t.agentDescription??"",avatarUrl:t.previewUrl??""},"agents-open")}}}),je({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ni()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),je({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`${ni()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),je({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ni()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),je({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&&Kr(vn(t))}}}),je({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?.os?.windowManager;if(!n)return;const o=`os-folder-${t}`,s=te.getState().folders.get(t),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),l=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:l,icon:e.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window"),rr("desktop-mode-my-wordpress");const d=[{folderId:t,title:e.title()}];let u=null;const f=document.createElement("header");c.appendChild(f);const p=document.createElement("div");p.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",c.appendChild(p);const g=()=>{const m=d.map((E,k)=>k===d.length-1?{label:E.title}:{label:E.title,onClick:()=>{d.length=k+1,h()}});n$(f,m,{onBack:()=>{d.length<=1||(d.pop(),h())},backDisabled:d.length<=1})},h=()=>{u?.(),u=null,p.replaceChildren();const m=document.createElement("div");m.className="os-folder-window__split",p.appendChild(m);const E=document.createElement("div");E.className="os-folder-window__layer",m.appendChild(E);const k=document.createElement("div");k.className="os-folder-window__preview",k.appendChild(o_()),m.appendChild(k);const N=d[d.length-1],M=Hv(E,N.folderId),S=M.onSelectionChanged(x=>{if(x.length===0){k.replaceChildren(o_());return}if(x.length>1){k.replaceChildren(b$(x));return}i$(x[0],k)}),$=x=>{if(!(x.target instanceof Element))return;const q=x.target.closest(".os-file-tile");if(!q||q.dataset.fileType!=="folder")return;const J=parseInt(q.dataset.fileRef??"",10);if(!J)return;x.preventDefault(),x.stopPropagation();const X=q.querySelector(".os-file-tile__label")?.textContent??`#${J}`;d.push({folderId:J,title:X}),h()};E.addEventListener("dblclick",$,!0);const W=ZP(E,{scope:`os-folder:${N.folderId}`,onSort:x=>M.sort(x),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{Hd({onSubmit:async x=>{const q=await Td({name:x}),J=te.getState().placementsByFolder.get(N.folderId)??[],X=Ov(J),T=kn(Xt,Xt,X,E,Ys(N.folderId)),D=await Bs({type:"folder",ref:String(q.id),parentId:N.folderId,x:T.x,y:T.y});te.upsertFolder(q),te.upsertPlacement(D)}})}}]}),F=KP(p,N.folderId,{selection:{count:()=>M.getSelection().length,subscribe:x=>M.onSelectionChanged(()=>x())}});u=()=>{S(),W.dispose(),F.dispose(),E.removeEventListener("dblclick",$,!0),M.dispose()},g()};h()},width:720,height:480,minWidth:360,minHeight:240})}}}),je({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?.os;if(n){if(t.shortcutSystemTile&&n.getSystemTile){n.getSystemTile(t.shortcutSystemTile)?.onOpen();return}if(L(y.DESKTOP_ICON_CLICKED,{id:e.shape.ref,target:t.shortcutWindow?"window":"url"}),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}if(Be(o.toString()))return;const s=n.config?.adminUrl,i=s?fe(o.toString(),s):`desktop-icon-${e.ref()}`,r=kr(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,selfLabel:r?.selfLabel,multi:!!r?.multi})}catch{}}}}}),je({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=i_(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),je({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=i_(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),je({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{E$(e,t)}}})}const L$="os-file-associations";let Cn=null;function T$(){Cg({id:L$,label:"File Associations",order:50,render(e){Cn&&(Cn(),Cn=null),r_(e),Cn=Xb(()=>{if(!e.isConnected){Cn&&(Cn(),Cn=null);return}r_(e)})}})}function r_(e){e.replaceChildren();const t=Vb();if(t.length===0){const i=document.createElement("p");i.className="os-file-associations__empty",i.textContent="No file types are registered.",e.appendChild(i);return}const n=document.createElement("p");n.className="os-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=vd(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(N$(i.type,i.label,o));e.appendChild(s)}function N$(e,t,n){const o=document.createElement("div");o.className="os-file-associations__row",o.setAttribute("role","listitem"),o.dataset.fileType=e;const s=document.createElement("label");s.className="os-file-associations__label",s.textContent=t,o.appendChild(s);const i=_d(e);if(i.length===0){const c=document.createElement("span");return c.className="os-file-associations__none",c.textContent="No app available",o.appendChild(c),o}const r=Ed(e),a=n[e]??r?.id??"",l=document.createElement("os-select");l.setAttribute("value",a),l.setAttribute("aria-label",`Default app for ${t}`),l.className="os-file-associations__select",s.htmlFor=`assoc-${e}`,l.id=`assoc-${e}`;for(const c of i){const d=document.createElement("os-option");d.setAttribute("value",c.id),d.textContent=c.isDefault?`${c.label} (default)`:c.label,l.appendChild(d)}return l.addEventListener("os-pick",c=>{const d=c.detail?.value;if(!d)return;const u={...vd(),[e]:d};qb(u),cv(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(l),o}function O$(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,Dd(t),!0)}function D$(){return window.openStationConfig?.filesOverlaysBundleUrl??""}async function oi(){if(window.openStationFilesOverlays)return window.openStationFilesOverlays;const e=D$();if(!e)return null;try{await pe(e)}catch(t){return console.warn("[openstation] files-overlays bundle failed to load",t),null}return window.openStationFilesOverlays??null}async function a_(...e){await(await oi())?.openShareSettingsModal(...e)}async function x$(...e){await(await oi())?.openFileShareModal(...e)}async function R$(...e){return(await oi())?.openPendingFileInviteModal(...e)}async function M$(...e){return(await oi())?.openPendingInviteModal(...e)}function W$(...e){oi().then(t=>t?.openUrlDialog(...e))}function c_(){return Number(window.openStationConfig?.currentUserId??0)}function P$(e){window.wp?.os?.windowManager?.getById?.(e)?.close?.()}function Qd(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function l_(e){const t=Yt().folders.get(e);return t?Number(t.ownerId):0}function d_(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function $$(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function U$(e){return Number(e.file.ownerId??0)}function B$(){lt("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!Qd())return e;const n=$$(t);if(n===null)return e;const o=l_(n)||U$(t),s=c_();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:()=>{a_({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 rn({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 lv(n),Fs(t.id);try{const a=await Ue(0);qt(0,a.placements)}catch{}const r=`os-folder-${n}`;P$(r),ue({message:"You left the shared folder."})}catch(r){En(ue,r,{lead:"Could not leave",fallback:"Could not leave."})}}});return e}),ps({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!Qd())return!1;const t=e.config.baseId??e.id,n=d_(t);return n===null?!1:l_(n)===c_()},onClick:e=>{if(!Qd())return;const t=e.config.baseId??e.id,n=d_(t);n!==null&&a_({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),ee("os.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(".os-file-tile__share-badge"))return;const s=document.createElement("span");s.className="os-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)})}let eu=null;function Zr(){return eu||(eu=se("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),eu}function F$(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 u_(e){const t=Zr(),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(F$(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 Jr(e,t={}){const n=Zr();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 f_=new Set;function H$(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function G$(){const e=Zr(),t=n=>{if(H$()){for(const o of n.pending)if(!f_.has(o.id)){if(f_.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;R$({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?Jr(o.id):i==="denied"&&Jr(o.id,{denied:!0,fileId:s})});continue}M$({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Jr(o.id):s==="denied"&&Jr(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function z$(){return Number(window.openStationConfig?.currentUserId??0)}function p_(){return window.openStationConfig?.desktopStorage??{}}function j$(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function V$(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function K$(){lt("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&p_().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:()=>{Kr(pv(i))}}),e}const n=V$(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{Kr(vn(n))}});const o=Number(t.file.ownerId??0),s=z$();return o===s&&j$()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{x$({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 rn({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 dv(n),Fs(t.id);try{const r=await Ue(0);qt(0,r.placements)}catch{}ue({message:"You left the shared file."})}catch(r){En(ue,r,{lead:"Could not leave",fallback:"Could not leave."})}}}),e}),lt("os.wallpaper-context-menu","desktop-mode/uploads",e=>(p_().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>h_(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>h_(!0)})),e))}function h_(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&&q$(n,e)}),t.click()}async function q$(e,t){const n=window.openStationConfig?.fileDropBundleUrl;if(n){try{await pe(n)}catch{ue({message:"Upload machinery failed to load — try again."});return}await window.openStationFileDrop?.routePickedFiles(e,t)}}function Y$(){return window.openStationConfig?.desktopStorage??{}}function m_(e){if(e.file.type!=="upload"||e.file.isMedia!==!0)return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function X$(e){return e.file.kind==="image"}function Z$(e){ue({message:e.created?"Added to the Media Library.":"Already in the Media Library.",action:{label:"Open",onClick:()=>{Sd({url:e.editUrl,title:e.title||"Attachment",icon:"dashicons-admin-media"})}}})}async function J$(e){try{Z$(await Ur(e))}catch(t){En(ue,t,{lead:"Could not add to the Media Library",fallback:"Could not add to the Media Library."})}}const Q$=async e=>{let t=0,n=0,o=0;for(const i of e){const r=m_(i);if(r!==null)try{(await Ur(r)).created?t+=1:n+=1}catch{o+=1}}const s=[];t>0&&s.push(`Added ${t} ${t===1?"file":"files"} to the Media Library.`),n>0&&s.push(`${n} already there.`),o>0&&s.push(`${o} could not be added.`),s.length>0&&ue({message:s.join(" ")})};async function g_(e,t){try{const n=await uv(e,t);Sd({url:n.editUrl,title:t==="page"?"Add New Page":"Add New Post",icon:t==="page"?"dashicons-admin-page":"dashicons-admin-post"})||(window.location.href=n.editUrl)}catch(n){En(ue,n,{lead:`Could not start a ${t}`,fallback:`Could not start a ${t}.`})}}function e2(){lt("os.files.tile-menu","desktop-mode/media-library",(e,t)=>{const n=m_(t);if(n===null)return e;const o=Y$();return!o.canAddToMedia||(e.push({id:"desktop-mode/upload-add-to-media",label:"Add to Media Library",icon:"dashicons-admin-media",sort:50,multi:!0,bulkLabel:s=>`Add ${s} files to Media Library`,bulk:Q$,onClick:()=>J$(n)}),!X$(t))||(o.canStartPost&&e.push({id:"desktop-mode/upload-start-post",label:"Start a post with this image",icon:"dashicons-admin-post",sort:55,onClick:()=>g_(n,"post")}),o.canStartPage&&e.push({id:"desktop-mode/upload-start-page",label:"Start a page with this image",icon:"dashicons-admin-page",sort:56,onClick:()=>g_(n,"page")})),e})}function tu(){return window.openStationConfig??{}}let Qr=[];function t2(e,t){return e.filter(n=>n.entityKinds.length===0||n.entityKinds.includes(t))}function n2(e){const t=e.file;if(t.isAgent===!0)return null;const n=Id({type:"desktop-file",data:{placement:e}});return n&&n.kind==="post"&&t.postType==="page"?{...n,kind:"page"}:n}async function o2(){const e=tu();if(!(!e.restUrl||!e.restNonce))try{const t=await Ae(nt(e.restUrl,"desktop-mode/v1/agents"),{credentials:"same-origin",headers:{"X-WP-Nonce":e.restNonce,Accept:"application/json"}},{silent:!0});if(!t.ok)return;const n=await t.json(),o=new Set(Qr.map(s=>s.id));Qr=(Array.isArray(n)?n:[]).flatMap(s=>{const i=s.triggers??[],r=i.find(c=>c.kind==="send-to"),a=i.some(c=>typeof c.config?.capability=="string"&&c.config.capability!=="");if(!r||a&&!o.has(s.id))return[];const l=Array.isArray(r.config?.entityKinds)?r.config.entityKinds.map(String):[];return[{id:s.id,name:s.name,description:s.description??"",avatarUrl:s.avatarUrl??"",entityKinds:l}]})}catch{}}function s2(e,t){const n=n2(t);if(!n)return e;const o=tu();for(const s of t2(Qr,n.kind))e.push({id:`desktop-mode/agent-send-to-${s.id}`,label:le(b("Send to %s","desktop-mode"),s.name),icon:"dashicons-share-alt",sort:70,onClick:()=>{IW({id:s.id,name:s.name,description:s.description,avatarUrl:s.avatarUrl},n,{restRoot:String(o.restUrl??""),restNonce:String(o.restNonce??"")})}});return e}function i2(){const e=tu().agentsSendTo;Qr=Array.isArray(e)?e:[],lt("os.files.tile-menu","desktop-mode/agents-send-to",s2),ee("os.agents.roster-changed","desktop-mode/agents-send-to/desktop",()=>{o2()})}function r2(){return window.openStationConfig?.desktopStorage?.canAddToMedia===!0}function a2(e){const t=e.placement.file;if(t.type!=="post"||t.exists===!1||t.status==="trash"||!r2())return 0;const n=parseInt(String(t.ref??""),10);return Number.isFinite(n)&&n>0?n:0}function w_(e){const t=Sn(e);if(t.length===0)return[];const n=[];for(const o of t){const s=o?.file;if(!s||s.type!=="upload"||s.isMedia!==!0)return[];const i=parseInt(String(s.ref??""),10);if(!Number.isFinite(i)||i<=0)return[];n.push(i)}return n}async function c2(e,t){const n=parseInt(String(e.file.ref??""),10);try{const o=await fv(n,t),s=o.attachments.length,i=s===1?"file":`${s} files`,r=o.title||e.file.title||`#${n}`;if(Sd({url:o.editUrl,title:r,icon:e.file.icon||"dashicons-admin-post"}),ue({message:`Added ${i} to “${r}”.`}),o.featuredImageSet)try{const a=await Ue(e.parentId);qt(e.parentId,a.placements)}catch{}}catch(o){En(ue,o,{lead:"Could not add to the post",fallback:"Could not add to the post."})}}function y_(e){return{appliesTo:t=>{if(a2(t)===0)return!1;const n=t.placement.file.postType==="page";return e==="page"?n:!n},accept:t=>w_(t).length>0,acceptLabel:e==="page"?"Add to page":"Add to post",onDrop:(t,n,o)=>{const s=w_(t.payload.data);s.length!==0&&c2(o.placement,s)}}}function l2(){const e=Gs("desktop-file",y_("page")),t=Gs("desktop-file",y_("other"));return()=>{e(),t()}}mW(),C$(),k$(),T$(),O$(),B$(),K$(),e2(),i2(),WP(),l2();const nu=window.openStationConfig?.serverPendingShares;Array.isArray(nu)&&nu.length>0&&u_(nu),G$();const Ke={DesktopFile:jb,registerType:Ze,unregisterType:cW,getType:lW,getTypes:Vb,resolve:Vt,subscribe:dW,registerOpener:je,unregisterOpener:uW,getOpener:fW,getOpeners:Yb,getOpenersForType:_d,resolveOpener:Ed,subscribeOpeners:Xb,getUserAssociations:vd,open:Us,registerTilePayloadHandler:Gs,rest:HW,store:{get:rt,getState:Yt,subscribe:Md,setFolderPlacements:qt,upsertPlacement:Od,removePlacement:Fs,setFolders:Dd,upsertFolder:xd,removeFolder:Rd}},b_="__synthFromDockItem";function d2(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function u2(e,t){const n=!!e.tile,o=t[e.id];return{id:d2(e.id),parentId:0,x:o?o.x:0,y:o?o.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[b_]:e.id},file:{type:"shortcut",ref:n?e.id:`dock-promoted:${e.id}`,title:e.title,icon:e.icon,previewUrl:"",exists:!0,...n?{shortcutSystemTile:e.id}:{shortcutUrl:e.menu?.url??""}}}}let ou=!1;const su=new Map;function f2(e){const t=window.wp?.os;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 p2(e,t,n={}){if(!ou){ou=!0;try{const s=Ke.store.getState().placementsByFolder.get(0)??[],i=new Set(e.map(d=>d.id)),r=new Map;for(const d of s){const u=d.meta&&typeof d.meta=="object"?d.meta[b_]:null;typeof u=="string"&&r.set(u,d)}const a=new Set;for(const d of t)d.entry&&a.add(d.entry.id);const l=new Map;for(const d of s){const u=d?.file?.ref;typeof u=="string"&&a.has(u)&&l.set(u,d)}for(const d of e)d.entry||r.has(d.id)||Ke.store.upsertPlacement(u2(d,n));const c=[];for(const[d,u]of r)i.has(d)||(Ke.store.removePlacement(u.id),n[d]&&c.push(d));c.length>0&&f2(c);for(const d of t){const u=d.entry;if(!u)continue;const f=l.get(u.id);if(!i.has(d.id)){f&&(su.set(u.id,f),Ke.store.removePlacement(f.id));continue}if(!f){const p=su.get(u.id);p&&(Ke.store.upsertPlacement(p),su.delete(u.id))}}}finally{ou=!1}}}function h2(e){queueMicrotask(e);const t=Ke.store.subscribe(e),n="desktop-mode/shortcuts-sync";return ee(y.DOCK_ITEM_APPENDED,n,e),()=>{t(),Ct(y.DOCK_ITEM_APPENDED,n)}}const ea="os-note-created",m2="openstation_notes";function g2(e){if(!e.bundleUrl)return()=>{};let t=null;const n=[];let o=null;const s=()=>(t||(t=pe(e.bundleUrl).then(()=>{const a=window.openStationNotes;if(!a)return null;const l=a.boot({host:e.host,config:e.config,onError:e.onError});document.removeEventListener(ea,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(Ce.START,r);for(const c of n.splice(0))document.dispatchEvent(c);return l}).catch(a=>(t=null,console.warn("[openstation] notes bundle failed to load",a),null))),t),i=a=>{n.push(new CustomEvent(ea,{detail:a.detail})),s()};document.addEventListener(ea,i);const r=()=>{s()};return window.addEventListener("dragstart",r,!0),document.addEventListener(Ce.START,r),lt("os.wallpaper-context-menu","desktop-mode/notes-sentinel",(a,l)=>{if(!Array.isArray(a)||a.some(u=>u.id==="new-note"))return a;const{x:c,y:d}=l??{x:0,y:0};return[...a,{id:"new-note",label:b("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{s().then(u=>{if(!u)return;const f=u.normalizedFromClient(c,d);u.createNoteAt({...f,focus:!0})})}}]}),e.hasNotes?(typeof requestIdleCallback=="function"?requestIdleCallback:l=>window.setTimeout(l,200))(()=>void s()):o=$e.subscribe(m2,a=>{a&&(o?.(),o=null,s())}),()=>{document.removeEventListener(ea,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(Ce.START,r),o?.(),o=null}}const w2={id:"clock",get label(){return b("Clock")},get description(){return b("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("os-widget-clock");const t=document.createElement("div");t.className="os-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="os-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 y2(){Va(w2)}async function b2(){const e=window;if(e.openStationReleaseCard)return e.openStationReleaseCard;const t=e.openStationConfig?.releaseCardBundleUrl??"";if(!t)return null;try{await pe(t)}catch{return null}return e.openStationReleaseCard??null}function v_(e,t){if(t){const o=b('WordPress %1$s "%2$s" is available.');return le(o,e,t)}const n=b("WordPress %s is available.");return le(n,e)}async function v2(e){const{update:t,openUrl:n}=e;if(!t||typeof t.version!="string"||!t.version||typeof t.url!="string"||!t.url)return!1;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(gr(a))return!1;const l=`${a}:no-art`,c=()=>n({url:t.url,title:b("WordPress Updates")}),u=e.resolveArt&&e.loadImage&&e.showCard?null:await b2(),f=e.resolveArt??u?.resolveReleaseArt,p=e.loadImage??u?.preloadImage,g=e.showCard??u?.showReleaseCard,h=f?await f(s,i):null;return h&&h.artUrl&&p&&g&&await p(h.artUrl)?(g({message:v_(o,i?h.name:""),artUrl:h.artUrl,dismissKey:a,onUpdate:c}),!0):gr(l)?!1:(ue({message:v_(o,""),persistent:!0,dismissible:!0,onDismiss:()=>wr(l),action:{label:b("Update now"),onClick:c}}),!0)}function __(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(gr(i))continue;const r=s.actionLabel,a=s.actionUrl,l=s.title||r||"";let c;r&&a&&(c={label:r,onClick:()=>n({url:a,title:l})}),ue({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>wr(i),action:c})}}const iu="desktop-mode/starter",_2="desktop-mode/dev-mode-gate";let E_=!1;function E2({osSettings:e,layer:t}){if(E_)return;E_=!0,lt(y.WIDGETS,_2,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==iu));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(iu):t.unmount(iu),lo())})}function k2(e){const{layer:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await pe(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter,deps:c.scriptDeps})}catch(d){L(y.SHELL_ERROR,{scope:"widget-script-load",id:c.id,error:d});return}o.add(c.scriptUrl)}},i=c=>(window.openStationWidgets||{})[c]??null,r=c=>({id:c.id,label:c.label,description:c.description,icon:c.icon,movable:c.movable,resizable:c.resizable,minWidth:c.minWidth||void 0,minHeight:c.minHeight||void 0,maxWidth:c.maxWidth||void 0,maxHeight:c.maxHeight||void 0,defaultWidth:c.defaultWidth||void 0,defaultHeight:c.defaultHeight||void 0,mount:async(d,u)=>{await s(c);const f=i(c.id);if(!f){const p=new Error(`[openstation] No mount callback on window.openStationWidgets["${c.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`);throw L(y.SHELL_ERROR,{scope:"widget-missing-mount",id:c.id,error:p}),p}return f(d,u)}}),a=async c=>{if(n.has(c.id))return;const d=r(c);try{Va(d)}catch(u){L(y.SHELL_ERROR,{scope:"widget-register",id:c.id,error:u});return}n.add(c.id),lo(),t&&t.mountIfEnabled(c.id)},l=c=>{n.has(c)&&(t?.unmount(c),Jk(c),n.delete(c),lo())};return async c=>{const d=new Set;for(const u of c)d.add(u.id);for(const u of Array.from(n))d.has(u)||l(u);for(const u of c)n.has(u.id)||await a(u)}}const k_=new Set(Mr),S2=2e3,ru=new Set,S_=new WeakSet;let I_=!1;function I2(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 l=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=l}}return s[o]}function A2(e){let t=null,n=1/0;for(const o of k_){const s=I2(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function C2(e){return e.startsWith("os-")?e.slice(4):e}function L2(e,t){if(ru.has(e))return;if(ru.add(e),k_.has(e)){const s=C2(e);console.error(`[wp.os] <${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.
43
44 Fix — side-effect-import the component module from wherever you render it:
45
46 import '<rel>/ui/components/${s}/${s}';
47
48 Or pull every os-* component in one go (heavier — only do this from an entry bundle):
49
50 import '<rel>/ui/components';
51
52 See docs/components-reference.md for the full list.`,`
53 First offending element:`,t);return}const o=A2(e);if(o){console.error(`[wp.os] <${e}> is not a registered os-* component. Did you mean <${o}>?
54
55 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'.`,`
56 First offending element:`,t);return}console.error(`[wp.os] <${e}> looks like a os-* tag but no component by that name exists.
57
58 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.`,`
59 First offending element:`,t)}function A_(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||ru.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||L2(t,e)},S2)}function C_(e){e instanceof Element&&(A_(e),e.shadowRoot&&ta(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];A_(o),o.shadowRoot&&ta(o.shadowRoot)}}function ta(e){if(S_.has(e))return;S_.add(e),C_(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&&C_(r)}}}).observe(e,{childList:!0,subtree:!0})}function T2(){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"&&ta(s),s};n.__wpdPatched=!0,e.attachShadow=n}function N2(){I_||typeof document>"u"||(I_=!0,T2(),ta(document))}const L_=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
60 <defs><linearGradient id="mio" x1="19" y1="19" x2="5" y2="5" gradientUnits="userSpaceOnUse">
61 <stop offset="0" stop-color="#3f6dff"/><stop offset=".5" stop-color="#a855f7"/><stop offset="1" stop-color="#ff4fd8"/>
62 </linearGradient></defs>
63 <circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/>
64 <rect x="8" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/>
65 <rect x="13.1" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/>
66 </svg>`,O2=`data:image/svg+xml;base64,${btoa(L_)}`;let au=0;function D2(e,t,n){const o=`openstation/mio-window-${++au}`,s=new Set,i=r=>{const a=t(),l=a.available&&a.enabled;let c=b(l?"Disable MIO in this window":"Enable MIO in this window");a.available||(c=b("Enable MIO in the dock first")),r.setAttribute("aria-label",c),r.setAttribute("title",c),r.setAttribute("aria-pressed",String(l)),r.toggleAttribute("disabled",!a.available),r.inert=!a.available,r.setAttribute("aria-hidden",String(!a.available)),r.dataset.mioAvailable=String(a.available),r.toggleAttribute("active",l),r.dataset.mioDisabled=String(!l),r.dataset.mioThinking=String(l&&a.thinking)};return ps({id:o,label:b("MIO in this window"),icon:L_.replace('id="mio"',`id="mio-${au}"`).replace("url(#mio)",`url(#mio-${au})`),placement:"right",order:20,match:r=>r.id===e,render:r=>{r.classList.add("os-mio-window-toggle");const a=r.querySelector("svg");if(a){const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M3 3L21 21"),l.setAttribute("class","os-mio-window-toggle__slash"),a.appendChild(l)}s.add(r),i(r),r.addEventListener("os-button-activate",()=>{t().available&&n()})}}),{update:()=>{for(const r of s)r.isConnected?i(r):s.delete(r)},dispose:()=>{Dg(o),s.clear()}}}class x2{constructor(t,n,o,s){this.host=t,this.frame=n,this.handle=o,this.visibility=s,this.request=null,this.dismissed=new Set,this.active=!1,this.visible=!1,this.raf=0,this.bubble=document.createElement("aside"),this.bubble.className="os-mio-callout",this.bubble.hidden=!0,this.bubble.setAttribute("aria-label",b("MIO tip")),this.message=document.createElement("span"),this.message.setAttribute("role","status");const i=document.createElement("os-button");i.setAttribute("variant","ghost"),i.setAttribute("aria-label",b("Dismiss MIO tip"));const r=document.createElement("span");r.textContent="×",r.setAttribute("aria-hidden","true");const a=document.createElement("span");a.className="screen-reader-text",a.textContent=b("Dismiss MIO tip"),i.append(r,a),i.addEventListener("click",()=>{this.request&&(this.dismissed.add(this.request.id),this.update(),this.request.onDismiss?.())}),this.bubble.append(this.message,i),n.append(this.bubble),this.observer=new MutationObserver(()=>this.update()),this.observer.observe(t,{childList:!0,subtree:!0,attributes:!0})}show(t){if(!t.id.trim()||!t.message.trim()||typeof t.target!="function")throw new Error("MIO callouts require an id, message and a live target resolver.");this.request=t,this.message.textContent=t.message,this.update()}clear(){this.request=null,this.update()}setActive(t){this.active=t,this.update()}update(){cancelAnimationFrame(this.raf),this.raf=0;const t=this.request,n=this.active&&t&&!this.dismissed.has(t.id)?t.target():null,o=this.frame.getBoundingClientRect(),s=n?.getBoundingClientRect(),i=!!(n?.isConnected&&this.host.contains(n)&&s&&s.width>0&&s.height>0&&s.bottom>o.top&&s.top<o.bottom&&s.right>o.left&&s.left<o.right);if(this.bubble.hidden=!i,i&&s){const r=(f,p,g)=>Math.max(p,Math.min(f,g)),a=getComputedStyle(this.frame).direction==="rtl",l={x:r(a?s.left+60:s.right-60,o.left+60,o.right-60),y:r(s.bottom+65,o.top+65,o.bottom-65)};this.handle()?.setAnchor?.(l,!0);const c=this.handle()?.getPosition()??l,d=this.bubble.offsetWidth,u=this.bubble.offsetHeight;this.bubble.style.left=`${r(c.x-o.left+(a?45:-d-45),8,o.width-d-8)}px`,this.bubble.style.top=`${r(c.y-o.top-u-24,8,o.height-u-8)}px`}i!==this.visible&&(this.visible=i,i||this.handle()?.setAnchor?.(null),this.visibility(i)),this.active&&t&&!this.dismissed.has(t.id)&&(this.raf=requestAnimationFrame(()=>this.update()))}dispose(){this.setActive(!1),this.observer.disconnect(),this.bubble.remove()}}function R2(e,t,n){const o=e.getBoundingClientRect(),s=n()?.getPosition(),i=s?{x:s.x-o.left,y:s.y-o.top}:null,r=new ResizeObserver(a);function a(){if(!e.isConnected||e.hidden)return;const l=e.getBoundingClientRect(),c=t.getBoundingClientRect();let d=i?{x:l.left+i.x,y:l.top+i.y}:null;c.left-l.left>=140&&(d={x:c.left-70,y:Math.min(c.top+70,l.bottom-70)}),n()?.setAnchor?.(d,!0)}return r.observe(t),r.observe(e),a(),{close:l=>{r.disconnect();const c=e.getBoundingClientRect();n()?.setAnchor?.(l&&i?{x:c.left+i.x,y:c.top+i.y}:null,!1)}}}const gt=Object.freeze({rounds:8,calls:16,validationFailures:3,repeatedReads:4});class na extends Error{constructor(t,n=!0){super(t.map(o=>`${o.path}: ${o.message}`).join("; ")),this.errors=t,this.retryable=n,this.name="MioValidationError"}}function xo(e,t){try{e?.(t)}catch{}}function T_(e){if(!e||typeof e!="object")return null;const t=e;return t.effect==="none"&&t.status==="completed"||t.effect==="none"&&t.status==="rejected"&&Array.isArray(t.errors)||t.effect==="write"&&t.status==="confirmed"&&typeof t.receipt=="string"&&t.receipt.length>0&&t.receipt.length<=500||t.effect==="write"&&t.status==="unknown"?t:null}class M2{constructor(t){this.records=new Map,this.inspectors=new Map,this.receipts=new Map,this.context=t}list(){return Array.from(this.records.values(),t=>structuredClone(t))}record(t,n,o,s){const i=this.records.get(t.callId);if(i?.status==="confirmed"&&o!=="confirmed")return structuredClone(i);if(i?.receipt&&s&&i.receipt!==s)throw new Error("MIO operation receipt changed unexpectedly.");const r=s&&this.receipts.has(s)&&this.receipts.get(s)!==t.callId,a={turnId:t.turnId,callId:t.callId,idempotencyKey:t.idempotencyKey,windowId:t.windowId,revision:t.revision,ability:n,effect:t.effect,status:r?"unknown":o,...s?{receipt:s}:{}};for(s&&!r&&this.receipts.set(s,t.callId),this.records.set(t.callId,a),this.context.operationStatus&&this.inspectors.set(t.callId,this.context.operationStatus);this.records.size>64;){const l=this.records.keys().next().value,c=this.records.get(l);c?.receipt&&this.receipts.get(c.receipt)===l&&this.receipts.delete(c.receipt),this.records.delete(l),this.inspectors.delete(l)}if(xo(this.context.onOperation,structuredClone(a)),r)throw new Error("MIO received a duplicate write receipt; inspect the operation status before continuing.");return structuredClone(a)}async inspect(t,n){const o=this.records.get(t),s=this.inspectors.get(t);if(!o)throw new Error("Unknown MIO operation.");if(o.effect!=="write"||o.status==="confirmed"||!s)return structuredClone(o);n.throwIfAborted();const i=T_(await s(structuredClone(o),n));return n.throwIfAborted(),i?.effect==="write"&&i.status==="confirmed"?this.record({...o,signal:n,limits:gt,validationFailures:0,validationRemaining:0},o.ability,"confirmed",i.receipt):i?.effect==="none"&&i.status==="rejected"?this.record({...o,signal:n,limits:gt,validationFailures:0,validationRemaining:0},o.ability,"rejected"):structuredClone(o)}}function W2(e){return`Reads: ${e.reads}; rejected candidates: ${e.rejected}; confirmed writes: ${e.confirmedWrites}; unknown write outcomes: ${e.unknownWrites}. Completed writes are not rolled back.`}const cu=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t;class P2{constructor(t,n,o){this.entries=new Map,this.listeners=new Set,this.disposed=!1,this.context=t,this.active=n,this.messages=o}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notify(){for(const t of this.listeners)xo(t,void 0)}create(t){const n=[];if(this.disposed)return n;try{const o=this.context.responseActions?.(t);if(!Array.isArray(o)||this.disposed)return n;const s=new Set;let i=!1;for(const r of o.slice(0,100))try{if(!r||typeof r!="object")continue;const a={...r};if(!cu(a.id,80)||s.has(a.id)||!cu(a.label,40)||typeof a.run!="function"||!["read","navigate"].includes(a.effect)||a.emphasis!==void 0&&!["primary","secondary"].includes(a.emphasis)||a.allowed!==void 0&&typeof a.allowed!="function"||a.ariaLabel!==void 0&&!cu(a.ariaLabel,160))continue;s.add(a.id),a.icon!==void 0&&(typeof a.icon!="string"||!/^(?:dashicons-)?[a-z][a-z0-9-]{0,63}$/.test(a.icon))&&delete a.icon,a.emphasis==="primary"&&!i?i=!0:a.emphasis="secondary";const l=crypto.randomUUID();if(this.entries.set(l,{messageId:t.messageId,turnId:t.summary.turnId,action:a,pending:null,status:""}),n.push(l),n.length===3)break}catch{}}catch{}return n}prune(){const t=new Set(this.messages().slice(-40).flatMap(n=>n.role==="assistant"?(n.actionIds??[]).map(o=>`${n.id}/${o}`):[]));for(const[n,o]of this.entries)t.has(`${o.messageId}/${n}`)||(o.pending?.abort(),this.entries.delete(n))}allowed(t){try{return!this.disposed&&this.active()&&(t.action.allowed?.()??!0)}catch{return!1}}list(t){return this.prune(),t.role!=="assistant"?[]:(t.actionIds??[]).flatMap(n=>{const o=this.entries.get(n);if(!o||o.messageId!==t.id)return[];const s=this.allowed(o);if(!s&&!o.status)return[];const{label:i,ariaLabel:r,icon:a,emphasis:l}=o.action;return[{id:n,label:i,ariaLabel:r,icon:a,emphasis:l??"secondary",pending:o.pending!==null,available:s,status:o.status}]})}async run(t,n){this.prune();const o=this.entries.get(n);if(!o||o.messageId!==t||o.pending)return;if(!this.allowed(o)){o.status=b("This action is no longer available."),this.notify();return}const s=new AbortController;o.pending=s,o.status=b("Working…"),this.notify();try{if(s.signal.throwIfAborted(),!this.allowed(o))throw new Error(b("This action is no longer available."));await o.action.run({signal:s.signal,messageId:t,turnId:o.turnId}),o.status=b("Done.")}catch(i){o.status=i instanceof Error?i.message.slice(0,500):b("Could not complete this action. Try again."),s.signal.aborted&&(o.status="")}finally{o.pending=null,this.notify()}}cancel(){for(const t of this.entries.values())t.pending?.abort()}dispose(){this.disposed=!0,this.cancel(),this.entries.clear(),this.listeners.clear()}}const $2=new Set("a an and are as at be by can do for from how i in is it me of on or please that the this to use we what with you your".split(" ")),lu=e=>(e.toLocaleLowerCase().match(/[\p{L}\p{N}_-]+/gu)??[]).filter(t=>!$2.has(t)),N_=e=>({id:e.id,title:e.title,version:e.version,topics:e.topics??[],componentIds:e.componentIds??[]});function O_(e){const t=[],n=new Map;let o={id:"intro",title:"Introduction",markdown:""},s="";for(const i of e.split(`
67 `)){const r=i.match(/^\s*(`{3,}|~{3,})/)?.[1];r&&(s?r[0]===s[0]&&r.length>=s.length&&(s=""):s=r);const a=!s&&i.match(/^#{1,6}\s+(.+?)\s*#*$/);if(a){o.markdown&&t.push(o);const l=a[1].toLowerCase().replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^-|-$/g,"")||"section",c=n.get(l)??0;n.set(l,c+1),o={id:c?`${l}-${c}`:l,title:a[1],markdown:""}}o.markdown+=`${o.markdown?`
68 `:""}${i}`}return o.markdown&&t.push(o),t}function U2(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%4294967291;return t.toString(36)}function D_(e,t){const n=[...new Set(lu(t))],o=t.trim().toLowerCase();return e.map(s=>{const i=[s.id,s.id.replace(/\.md$/,""),s.title,...s.componentIds??[],...s.topics??[]].map(f=>f.toLowerCase()),r=i.includes(o)?1e3:0,a=O_(s.markdown).map(f=>{const p=new Set(lu(f.markdown)),g=new Set(lu(`${s.title} ${s.id} ${f.title} ${i.join(" ")}`));return{section:f,score:r+n.reduce((h,m)=>h+(p.has(m)?1:0)+(g.has(m)?10:0),0)}}).sort((f,p)=>p.score-f.score),l=a[0],c=l?.section.markdown??"";let d=Math.min(c.length,3200);d<c.length&&/[\uD800-\uDBFF]/.test(c[d-1])&&d--;const u=c.slice(0,d);return{...N_(s),score:l?.score??0,section:l?.section.id,excerpt:u,truncated:(l?.section.markdown.length??0)>u.length,sections:a.slice(0,2).map(f=>({id:f.section.id,title:f.section.title}))}}).filter(s=>s.score>0).sort((s,i)=>i.score-s.score).slice(0,4)}function x_(e,t,n,o){const s=e.find(p=>p.id===t);if(!s)throw new Error("Unknown help document.");const i=O_(s.markdown),r=n?i.find(p=>p.id===n):null;if(n&&!r)throw new Error("Unknown help section.");const a=r?.markdown??s.markdown,l=U2(`${t}
69 ${s.version??""}
70 ${n??""}
71 ${a}`);let c=0;if(o){const p=o.match(/^([a-z0-9]+):(\d+)$/);if(!p||p[1]!==l||Number(p[2])>=a.length)throw new Error("Invalid or stale help cursor; read the document again.");c=Number(p[2])}let d=Math.min(a.length,c+12e3);d<a.length&&/[\uD800-\uDBFF]/.test(a[d-1])&&d--;const u=new URL(t,"https://mio.invalid/"),f=[...s.markdown.matchAll(/\]\(([^)\s]+)(?:\s+[^)]*)?\)/g)].map(p=>{try{const g=new URL(p[1],u);return g.origin===u.origin?decodeURIComponent(g.pathname.slice(1)):""}catch{return""}}).filter(p=>e.some(g=>g.id===p));return{...N_(s),section:n,markdown:a.slice(c,d),truncated:d<a.length,cursor:d<a.length?`${l}:${d}`:null,sections:i.map(p=>({id:p.id,title:p.title})),links:[...new Set(f)]}}function B2(e){return["search_help","read_help"].map(t=>{const n=t==="search_help"?"query":"id";return{name:t,effect:"read",description:t==="search_help"?"Search local help by document, topic or exact component ID. Returns section IDs and explicit truncation.":"Read a document or section. Follow cursor with the same id and section until truncated is false.",parameters:{type:"object",properties:{[n]:{type:"string"},...t==="read_help"?{section:{type:"string"},cursor:{type:"string"}}:{}},required:[n],additionalProperties:!1},validate:o=>{if(!(Object.keys(o).every(i=>(t==="read_help"?["id","section","cursor"]:["query"]).includes(i)&&typeof o[i]=="string"&&o[i].length<=500)&&typeof o[n]=="string"))return!1;if(t==="read_help")try{x_(e,o.id,o.section,o.cursor)}catch(i){return{ok:!1,retryable:!0,errors:[{code:"help_location",path:"$",message:i.message,suggestion:"Use search_help to find a current document and section."}]}}return!0},run:o=>t==="search_help"?D_(e,o.query):x_(e,o.id,o.section,o.cursor)}})}const R_=Object.freeze({prompt:16e3,transcript:96e3,tools:96e3,request:22e4}),M_=e=>new TextEncoder().encode(e).byteLength;class F2 extends Error{constructor(t,n,o){super(`MIO ${t} budget exceeded (${n}/${o} UTF-8 bytes). Use a compact draft reference or smaller edit; no document was truncated.`),this.scope=t,this.usedBytes=n,this.limitBytes=o,this.code="mio_request_budget",this.name="MioBudgetError",this.remainingBytes=Math.max(0,o-n)}}const H2=e=>JSON.stringify(e).replace(/\//g,"\\/").replace(/[^\x00-\x7f]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`);function W_(e){const t={prompt:e.prompt,transcript:e.transcript,tools:H2(e.tools),request:JSON.stringify(e)};for(const n of Object.keys(t)){const o=M_(t[n]);if(o>R_[n])throw new F2(n,o,R_[n])}}function oa(e,t){return new na([{code:e,path:"$",message:t}])}function P_(e){if(!Array.isArray(e)||!e.length||e.length>20)throw new Error("Invalid MIO validation feedback.");return e.map(t=>{if(!t||typeof t.code!="string"||typeof t.path!="string"||typeof t.message!="string")throw new Error("Invalid MIO validation feedback.");return{code:t.code.slice(0,80),path:t.path.slice(0,300),message:t.message.slice(0,1e3),...typeof t.suggestion=="string"?{suggestion:t.suggestion.slice(0,1e3)}:{}}})}function G2(e,t,n){if(typeof e!="string"||M_(e)>96e3)throw oa("argument_budget","Provide JSON arguments within 96,000 UTF-8 bytes; use a draft reference or a smaller patch for larger documents.");let o;try{o=JSON.parse(e)}catch{throw oa("invalid_json","Provide a valid JSON object for the tool arguments.")}if(!o||typeof o!="object"||Array.isArray(o))throw oa("invalid_envelope","Expected an object containing the advertised argument properties.");const s=t.validate(o,n);if(s===!1)throw oa("invalid_arguments",`Arguments do not satisfy ${t.name}; check its schema and live options.`);if(s!==!0&&s?.ok!==!0)throw!s||s.ok!==!1||typeof s.retryable!="boolean"?new Error("Invalid MIO validator result."):new na(P_(s.errors),s.retryable);return o}function du(e){return Array.isArray(e)?`[${e.map(du).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${du(e[t])}`).join(",")}}`:JSON.stringify(e)}function z2(){let e=[];return{read:()=>e.map(t=>({...t,...t.actionIds?{actionIds:[...t.actionIds]}:{}})),write:t=>{e=t.slice(-40).map(n=>({...n,...n.actionIds?{actionIds:[...n.actionIds]}:{}}))},clear:()=>{e=[]}}}class j2{constructor(t,n,o,s=z2()){this.context=t,this.transport=n,this.active=o,this.conversation=s,this.disposed=!1,this.pending=null,this.abortTurn=null,this.thinkingListeners=new Set,this.operations=new M2(t),this.responseActions=new P2(t,()=>!this.disposed&&o(),()=>s.read())}subscribeThinking(t){return this.thinkingListeners.add(t),t(this.pending!==null),()=>{this.thinkingListeners.delete(t)}}notifyThinking(){for(const t of this.thinkingListeners)xo(t,this.pending!==null)}cancel(){this.responseActions.cancel(),this.pending?.abort(),this.abortTurn?.(),this.abortTurn=null,this.pending=null,this.notifyThinking()}dispose(){this.disposed=!0,this.responseActions.dispose(),this.cancel(),this.conversation.clear(),this.thinkingListeners.clear()}async ask(t){if(this.disposed)throw new Error("This MIO window session is disposed.");if(this.pending)throw new Error("MIO is already answering.");if(!t.trim()||t.length>4e3)throw new Error("Write a message of 1–4000 characters.");const n=new AbortController,{signal:o}=n,s=crypto.randomUUID();let i=0,r=0,a=0,l=!1,c,d="failed",u=null;const f=()=>({turnId:s,windowId:this.context.windowId,revision:c,signal:o,limits:gt,validationFailures:r,validationRemaining:Math.max(0,gt.validationFailures-r)}),p=()=>{const W=this.operations.list().filter(F=>F.turnId===s);return{...f(),status:d,reads:a,rejected:r,calls:i,confirmedWrites:W.filter(F=>F.status==="confirmed").length,unknownWrites:W.filter(F=>F.effect==="write"&&(F.status==="unknown"||F.status==="running")).length}},g=()=>{l||(l=!0,d="aborted",u?.context.effect==="write"&&this.operations.record(u.context,u.name,"unknown"),xo(this.context.onTurnAbort,f()))},h=()=>{if(o.aborted||!this.active())throw n.abort(),g(),new DOMException("The window context changed.","AbortError")};this.pending=n,this.abortTurn=g,this.notifyThinking();const m=[...this.conversation.read().slice(-39),{role:"user",text:t,id:crypto.randomUUID()}];this.conversation.write(m),this.responseActions.prune();const E=W=>{const F={role:"assistant",text:W,id:crypto.randomUUID()},x=this.responseActions.create(Object.freeze({messageId:F.id,summary:Object.freeze(p()),operations:Object.freeze(this.operations.list().filter(q=>q.turnId===s).map(q=>Object.freeze(q)))}));if(x.length&&(F.actionIds=x),this.disposed||this.pending!==n){this.responseActions.prune();return}this.conversation.write([...m,F].slice(-40)),this.responseActions.prune()},k=[],N=new Set,M=new Map,S=()=>[...B2(this.context.documents),...this.context.abilities()].filter(W=>!W.allowed||W.allowed()),$=(W,F,x,q)=>{r++,this.operations.record(F,x,"rejected");const J=P_(W.errors);if(k.push(JSON.parse(JSON.stringify({name:x,callId:F.callId,effect:"none",status:"rejected",result:{effect:"none",status:"rejected",errors:J,data:q,retryable:W.retryable,validationRemaining:Math.max(0,gt.validationFailures-r)}}))),!W.retryable)throw new Error(`MIO validation is terminal: ${W.message}`);if(r>=gt.validationFailures)throw new Error("MIO validation retry budget exhausted; no further candidates will run in this turn.")};try{h(),c=this.context.revision?.(),xo(this.context.onTurnBegin,f());for(let W=0;W<gt.rounds;W++){h();const F=S();if(new Set(F.map(T=>T.name)).size!==F.length)throw new Error("MIO ability names must be unique within a window.");c=this.context.revision?.();const x=await this.context.prompt();h();const q={messages:m.slice(-20).map(({role:T,text:D})=>({role:T,text:D})),help:D_(this.context.documents,t),outcomes:k},J={prompt:x,transcript:JSON.stringify(this.context.compactHistory?this.context.compactHistory(structuredClone(q),f()):q),tools:F.map(({name:T,description:D,parameters:K,effect:G})=>({name:T,description:`[Effect: ${G??"write"}] ${D}`,parameters:K}))};W_(J),h();const X=await this.transport(J,o);if(h(),!Array.isArray(X.calls)||X.calls.length>gt.calls)throw new Error("Invalid MIO tool response.");if(!X.calls.length){if(typeof X.message!="string"||!X.message.trim())throw new Error("MIO returned no answer.");return d="completed",E(X.message),X.message}for(const T of X.calls){if(h(),i>=gt.calls)throw new Error("MIO reached its action limit. Review the changes before continuing.");i++;const D=S().find(_=>_.name===T.name);if(!D||!F.some(_=>_.name===T.name))throw new Error("MIO requested an unavailable action.");c=this.context.revision?.();const K=`${s}:${i}`,G={...f(),callId:K,idempotencyKey:K,effect:D.effect??"write"};let ne;try{ne=G2(T.arguments,D,G)}catch(_){if(_ instanceof na){$(_,G,T.name);break}throw _}const ce=du([T.name,ne]);if(G.effect==="write"&&N.has(ce))throw new Error("MIO repeated an action; stopped to avoid replaying a write.");if(G.effect!=="write"){const _=(M.get(ce)??0)+1;if(M.set(ce,_),_>gt.repeatedReads)throw new Error("MIO repeated-read budget exhausted.")}if(h(),D.allowed&&!D.allowed())throw new Error("MIO requested an unavailable action.");G.effect==="write"&&N.add(ce),u={context:G,name:T.name},this.operations.record(G,T.name,"running");try{if(h(),D.allowed&&!D.allowed())throw new Error("MIO requested an unavailable action.")}catch(_){throw u=null,this.operations.record(G,T.name,"rejected"),_}let R;try{R=await D.run(ne,o,G)}catch(_){throw this.operations.record(G,T.name,G.effect==="write"?"unknown":"rejected"),u=null,_}const C=T_(R);if(C?.effect==="none"&&C.status==="rejected"){this.operations.record(G,T.name,"rejected"),u=null,N.delete(ce),h();const _=D.history?D.history({name:T.name,callId:K,args:ne,result:C},G):C.data;$(new na(C.errors,C.retryable),G,T.name,_);break}if(C?.effect==="none"&&C.status==="completed")this.operations.record(G,T.name,"completed"),u=null;else if(G.effect==="write"){const _=!C&&!!R&&typeof R=="object"&&R.saved===!0,v=C?.effect==="write"&&C.status==="confirmed"?C.receipt:void 0;if(this.operations.record(G,T.name,v||_?"confirmed":"unknown",v??(_?K:void 0)),u=null,!v&&!_)throw new Error("MIO write outcome is unknown; inspect its status before making another change.")}else this.operations.record(G,T.name,"completed"),G.effect==="read"&&a++,u=null;h();const U={name:T.name,callId:K,args:ne,result:R},B=D.history?D.history(U,G):{result:R},z=this.operations.list().find(_=>_.callId===K);k.push(JSON.parse(JSON.stringify({...B,name:T.name,callId:K,effect:C?.effect??G.effect,status:z?.status,receipt:z?.receipt})))}}throw new Error("MIO reached its action limit. Review the changes before continuing.")}catch(W){if(this.pending===n){const F=W instanceof Error?W.message:String(W);E(`${F} ${W2(p())}`)}throw W}finally{xo(this.context.onTurnEnd,p()),this.pending===n&&(this.pending=null,this.abortTurn=null,this.notifyThinking())}}}function V2(e){return async(t,n)=>{W_(t);const o=window.wp?.os?.config;if(!o?.aiSearchUrl||!o.restNonce)throw new Error("Enable the AI assistant in Preferences → Features and connect a provider.");const s=o.aiSearchUrl.replace(/\/ai\/search(?=\?|$)/,"/mio/turn");if(s===o.aiSearchUrl)throw new Error("MIO transport URL is unavailable.");const i=await Ae(s,{method:"POST",credentials:"same-origin",cache:"no-store",signal:n,headers:{"Content-Type":"application/json","X-WP-Nonce":o.restNonce},body:JSON.stringify(t)},{windowId:e,source:"mio/window"}),r=await i.json();if(!i.ok){const a=bt(i.status,r);throw a.serverMessage?a:bt(i.status,r,"MIO could not reach the AI provider.")}return r}}class K2{constructor(t){this.options=t,this.residents=new Map,this.attachmentObserver=new MutationObserver(()=>{for(const n of this.residents.values())(!n.context.host.isConnected||!n.frame.isConnected)&&n.dispose?.()}),this.owner=null,this.chat=null,this.chatPlacement=null,this.thinkingOwner=null,this.revision=0,this.transitioning=!1,this.targetLayer=null,this.moving=Promise.resolve(),this.animation=null,this.deskPosition=null;for(const n of["os-window-focused","os-window-closed"])document.addEventListener(n,()=>this.refresh());for(const n of[y.WINDOW_MINIMIZED,y.WINDOW_RESTORED,y.DESKTOP_SWITCHED,y.WINDOW_DESKTOP_CHANGED])ee(n,"openstation/mio-residency",()=>this.refresh())}canChat(){return this.options.enabled()&&(this.options.chatAvailable?.()??!0)}getWindowId(){return this.owner?.id??null}register(t,n){const o=document.getElementById(`wp-window-${t}`),s=o?.querySelector(".os-window__body");if(!o||!s||!n.host.isConnected||!s.contains(n.host)||!n.title.trim()||typeof n.prompt!="function")throw new Error("MIO requires an explicit context belonging to a live window body.");if(this.residents.has(t))throw new Error("This window already registered MIO. Dispose its lease before replacing it.");const i=document.createElement("div");i.className="os-mio-residence",i.hidden=!0,o.appendChild(i);const r=()=>{i.style.top=`${s.offsetTop}px`,i.style.left=`${s.offsetLeft}px`,i.style.width=`${s.clientWidth}px`,i.style.height=`${s.clientHeight}px`},a=new ResizeObserver(r);a.observe(s),r();const l=document.createElement("os-button");l.className="os-mio-chat-launcher",l.hidden=!this.canChat(),l.setAttribute("variant","ghost"),l.textContent=b("Ask MIO"),l.setAttribute("aria-haspopup","dialog"),i.appendChild(l);const c={enabled:n.enabled!==!1,thinking:!1,calloutVisible:!1,id:t,context:n,frame:i,button:l,observer:a,session:new j2({...n,windowId:t},V2(t),()=>this.canChat()&&c.enabled&&this.owner===c&&this.options.focused()===t&&n.host.isConnected)};c.callout=new x2(n.host,i,this.options.handle,p=>{c.calloutVisible=p,this.syncVisibility()}),this.residents.set(t,c),this.attachmentObserver.observe(document.body,{childList:!0,subtree:!0});const d=p=>{this.residents.get(t)!==c||c.enabled===p||(c.enabled=p,p||c.session.cancel(),this.refresh(),L("os.mio.window-enabled-changed",{windowId:t,enabled:p}))};c.toggle=D2(t,()=>({enabled:c.enabled,available:this.options.enabled(),thinking:c.thinking}),()=>d(!c.enabled)),c.session.subscribeThinking(p=>{c.thinking=p,c.toggle?.update(),this.syncThinking()});const u=async()=>{if(!n.host.isConnected||!this.canChat()||!c.enabled||this.options.focused()!==t||this.residents.get(t)!==c||(await this.options.ready(),await window.wp?.os?.loadComponents(["os-button","os-textarea"]),await this.moving,!n.host.isConnected||!this.canChat()||!c.enabled||this.owner!==c||this.options.focused()!==t))return;this.closeChat(),this.chat=window.openStationMountMioChat?.(i,n.title,c.session,()=>this.closeChat(!0))??null,l.hidden=this.chat!==null,c.callout?.setActive(!1),this.syncVisibility();const p=i.querySelector(".os-mio-chat");p&&(this.chatPlacement=R2(i,p,this.options.handle))};l.addEventListener("click",()=>{u().catch(p=>{l.textContent=p instanceof Error?p.message:b("MIO could not open.")})});const f=()=>{if(this.residents.get(t)!==c)return;this.residents.delete(t),c.session.dispose(),c.callout?.dispose(),c.toggle?.dispose(),a.disconnect(),this.refresh();const p=this.options.layer();p&&i.contains(p)&&(this.options.shell.appendChild(p),delete p.dataset.mioWindow,delete p.dataset.mioThinking),i.remove(),this.residents.size||this.attachmentObserver.disconnect()};return c.dispose=f,this.refresh(),{showCallout:p=>c.callout?.show(p),clearCallout:()=>c.callout?.clear(),isEnabled:()=>c.enabled,setEnabled:d,openChat:u,getOperations:()=>c.session.operations.list(),inspectOperation:(p,g=new AbortController().signal)=>c.session.operations.inspect(p,g),dispose:f}}closeChat(t=!1){this.chatPlacement?.close(t),this.chatPlacement=null,this.chat?.destroy(),this.chat=null,this.owner&&(this.owner.button.hidden=!this.canChat(),t&&(this.owner.button.shadowRoot?.querySelector("button")??this.owner.button).focus()),this.syncCallouts()}syncVisibility(){const t=this.options.layer();t&&(t.dataset.mioVisible=String(this.owner?!!this.chat||this.owner.calloutVisible:this.options.wallpaperVisible?.()??!0))}syncCallouts(){for(const t of this.residents.values())t.callout?.setActive(this.options.enabled()&&t.enabled&&this.owner===t&&!this.chat&&!this.transitioning);this.syncVisibility()}syncThinking(){const t=this.owner?.thinking&&this.options.enabled()&&this.owner.enabled?this.owner.id:null,n=this.options.layer();n&&(n.dataset.mioThinking=String(t!==null)),this.thinkingOwner!==t&&(this.thinkingOwner&&L("os.mio.thinking-changed",{windowId:this.thinkingOwner,thinking:!1}),this.thinkingOwner=t,t&&L("os.mio.thinking-changed",{windowId:t,thinking:!0}))}refresh(){const t=this.options.enabled();!this.canChat()&&this.chat&&this.closeChat();for(const c of this.residents.values())c.toggle?.update(),c.button.hidden=!this.canChat()||c===this.owner&&this.chat!==null,this.canChat()||c.session.cancel();if(!t)for(const c of this.residents.values())c.frame.hidden=!0;const n=t?this.options.focused():null,o=n?this.residents.get(n)??null:null,s=o?.enabled&&o.context.host.isConnected?o:null,i=this.options.layer();if(this.owner===s&&i===this.targetLayer){this.syncVisibility();return}this.targetLayer=i;const r=this.owner;this.transitioning=!0,this.closeChat(),r?.session.cancel(),this.owner=s,this.syncCallouts(),this.syncThinking();const a=++this.revision;this.animation?.cancel(),this.animation=null,this.options.handle()?.setAnimating(!1),s&&i&&!i.dataset.mioWindow&&(this.deskPosition=this.options.handle()?.getPosition()??null),s&&(s.frame.hidden=!1,s.button.hidden=!this.canChat());const l=async()=>{const c=async(d,u)=>{if(!i?.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;const f=this.options.handle()?.getPosition(),p=i.getBoundingClientRect();i.style.transformOrigin=f?`${f.x-p.left}px ${f.y-p.top}px`:"50% 50%",this.animation=i.animate([{transform:`scale(${d})`,opacity:d},{transform:`scale(${u})`,opacity:u}],{duration:150,easing:"ease-in-out",fill:"forwards"}),await this.animation.finished};try{if(await c(1,0),a!==this.revision)return;for(const d of this.residents.values())d.frame.hidden=d!==s;if(i){i.style.opacity="0",this.animation?.cancel(),this.animation=null,(s?.frame??this.options.shell).appendChild(i),s?(i.dataset.mioWindow=s.id,i.dataset.mioThinking=String(s.thinking)):(delete i.dataset.mioWindow,delete i.dataset.mioThinking);const d=i.getBoundingClientRect(),u=s?{x:d.right-82,y:d.bottom-95}:this.deskPosition;u&&this.options.handle()?.setPosition(u.x,u.y)}L("os.mio.owner-changed",{windowId:s?.id??null,previousWindowId:r?.id??null}),this.options.handle()?.setAnimating(!document.hidden),await c(0,1)}catch{}finally{a===this.revision&&(this.animation?.cancel(),this.animation=null,i?.style.removeProperty("opacity"),this.transitioning=!1,this.syncCallouts(),this.options.handle()?.setAnimating(!document.hidden))}};this.moving=l()}}const $_={appearance:{radius:56,bodyColor:789263,bodyAlpha:1,hueStart:296.5,hueSpan:-52.5,hueAngle:225,hueDrift:0,hueSpin:0,hueLoop:!0,saturation:1,lightness:.75,iridescence:0,outlineWidth:4,linerWidth:2,linerColor:16776191,glow:10,glowBlur:!0,eyeColor:16776191,eyeScale:.3},physics:{points:12,shapePreset:"blob",shapeLobes:3,shapeAmount:1,shapeAngle:0,shapeShuffle:60,radialStiffness:460,edgeStiffness:540,bendStiffness:170,pressure:2400,damping:9,airDamping:.5,magnetStrength:2200,magnetRange:260,magnetGrip:.24,magnetDamping:7,floatAmplitude:10,floatSpeed:1.1,idleWobble:.085,idleWobbleSpeed:.55,speedStretch:.3,friction:.86,restitution:.2,dragStiffness:480,throwBoost:1,minStretch:.55,maxStretch:1.7,minAngularGap:.25,limitIterations:3,dragMaxAccel:9e3,subStep:1/240,maxSubSteps:8}},ie={radius:[16,220],bodyAlpha:[0,1],hueStart:[-720,720],hueSpan:[-360,360],hueDrift:[-180,180],hueAngle:[-360,360],hueSpin:[-180,180],saturation:[0,1],lightness:[.15,1],iridescence:[0,2],outlineWidth:[.5,24],linerWidth:[0,12],glow:[0,20],eyeScale:[.05,.6],points:[12,128],shapeLobes:[0,8],shapeAmount:[0,1.4],shapeAngle:[-360,360],shapeShuffle:[0,3600],radialStiffness:[0,2e3],edgeStiffness:[0,4e3],bendStiffness:[0,2e3],pressure:[0,8e3],damping:[0,30],airDamping:[0,20],magnetStrength:[0,8e3],magnetRange:[0,2e3],magnetGrip:[0,.6],magnetDamping:[0,40],floatAmplitude:[0,200],floatSpeed:[0,20],idleWobble:[0,.4],idleWobbleSpeed:[0,8],speedStretch:[0,.8],friction:[0,1],restitution:[0,1],dragStiffness:[1,4e3],throwBoost:[0,4],minStretch:[.1,1],maxStretch:[1,4],minAngularGap:[0,.9],limitIterations:[0,8],dragMaxAccel:[100,2e5],subStep:[1/1e3,1/30],maxSubSteps:[1,32]};function re(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function uu(e,t){if(typeof e=="number"&&Number.isFinite(e))return Math.min(16777215,Math.max(0,Math.floor(e)));if(typeof e=="string"){const n=e.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{6}$/.test(n))return Number.parseInt(n,16);if(/^[0-9a-fA-F]{3}$/.test(n)){const[o,s,i]=n.split("");return Number.parseInt(`${o}${o}${s}${s}${i}${i}`,16)}}return t}function U_(e,t){return typeof e=="boolean"?e:t}const q2=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function Y2(e,t){return q2.includes(e)?e:t}function si(e,t=$_){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:re(o.radius,t.appearance.radius,ie.radius),bodyColor:uu(o.bodyColor,t.appearance.bodyColor),bodyAlpha:re(o.bodyAlpha,t.appearance.bodyAlpha,ie.bodyAlpha),hueStart:re(o.hueStart,t.appearance.hueStart,ie.hueStart),hueSpan:re(o.hueSpan,t.appearance.hueSpan,ie.hueSpan),hueDrift:re(o.hueDrift,t.appearance.hueDrift,ie.hueDrift),hueLoop:U_(o.hueLoop,t.appearance.hueLoop),hueAngle:re(o.hueAngle,t.appearance.hueAngle,ie.hueAngle),hueSpin:re(o.hueSpin,t.appearance.hueSpin,ie.hueSpin),saturation:re(o.saturation,t.appearance.saturation,ie.saturation),lightness:re(o.lightness,t.appearance.lightness,ie.lightness),iridescence:re(o.iridescence,t.appearance.iridescence,ie.iridescence),outlineWidth:re(o.outlineWidth,t.appearance.outlineWidth,ie.outlineWidth),linerWidth:re(o.linerWidth,t.appearance.linerWidth,ie.linerWidth),linerColor:uu(o.linerColor,t.appearance.linerColor),glow:re(o.glow,t.appearance.glow,ie.glow),glowBlur:U_(o.glowBlur,t.appearance.glowBlur),eyeColor:uu(o.eyeColor,t.appearance.eyeColor),eyeScale:re(o.eyeScale,t.appearance.eyeScale,ie.eyeScale)},r={points:Math.round(re(s.points,t.physics.points,ie.points)),shapePreset:Y2(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(re(s.shapeLobes,t.physics.shapeLobes,ie.shapeLobes)),shapeAmount:re(s.shapeAmount,t.physics.shapeAmount,ie.shapeAmount),shapeAngle:re(s.shapeAngle,t.physics.shapeAngle,ie.shapeAngle),shapeShuffle:re(s.shapeShuffle,t.physics.shapeShuffle,ie.shapeShuffle),radialStiffness:re(s.radialStiffness,t.physics.radialStiffness,ie.radialStiffness),edgeStiffness:re(s.edgeStiffness,t.physics.edgeStiffness,ie.edgeStiffness),bendStiffness:re(s.bendStiffness,t.physics.bendStiffness,ie.bendStiffness),pressure:re(s.pressure,t.physics.pressure,ie.pressure),damping:re(s.damping,t.physics.damping,ie.damping),airDamping:re(s.airDamping,t.physics.airDamping,ie.airDamping),magnetStrength:re(s.magnetStrength,t.physics.magnetStrength,ie.magnetStrength),magnetRange:re(s.magnetRange,t.physics.magnetRange,ie.magnetRange),magnetGrip:re(s.magnetGrip,t.physics.magnetGrip,ie.magnetGrip),magnetDamping:re(s.magnetDamping,t.physics.magnetDamping,ie.magnetDamping),floatAmplitude:re(s.floatAmplitude,t.physics.floatAmplitude,ie.floatAmplitude),floatSpeed:re(s.floatSpeed,t.physics.floatSpeed,ie.floatSpeed),idleWobble:re(s.idleWobble,t.physics.idleWobble,ie.idleWobble),idleWobbleSpeed:re(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,ie.idleWobbleSpeed),speedStretch:re(s.speedStretch,t.physics.speedStretch,ie.speedStretch),friction:re(s.friction,t.physics.friction,ie.friction),restitution:re(s.restitution,t.physics.restitution,ie.restitution),dragStiffness:re(s.dragStiffness,t.physics.dragStiffness,ie.dragStiffness),throwBoost:re(s.throwBoost,t.physics.throwBoost,ie.throwBoost),minStretch:re(s.minStretch,t.physics.minStretch,ie.minStretch),maxStretch:re(s.maxStretch,t.physics.maxStretch,ie.maxStretch),minAngularGap:re(s.minAngularGap,t.physics.minAngularGap,ie.minAngularGap),dragMaxAccel:re(s.dragMaxAccel,t.physics.dragMaxAccel,ie.dragMaxAccel),limitIterations:Math.round(re(s.limitIterations,t.physics.limitIterations,ie.limitIterations)),subStep:re(s.subStep,t.physics.subStep,ie.subStep),maxSubSteps:Math.round(re(s.maxSubSteps,t.physics.maxSubSteps,ie.maxSubSteps))};return{appearance:i,physics:r}}const B_="desktop-mode-mio-position",F_="os-mio",X2="os-mio-toggle";class Z2{constructor(t){this.layer=null,this.handle=null,this.mounting=null,this.parked=null,this.generation=0,this.loading=null,this.look=Mc(),this.options=t,this.residency=new K2({shell:t.shell,focused:t.focusedWindow??(()=>null),layer:()=>this.layer,handle:()=>this.handle,enabled:()=>this.enabled,chatAvailable:t.chatAvailable,wallpaperVisible:t.wallpaperVisible,ready:()=>this.mount()}),this.enabled=t.enabled,this.look=tm(t.savedLook),this.config=this.resolveConfig()}boot(){this.enabled&&this.mount()}syncEnabled(t){this.setEnabled(t,!1),this.residency.refresh()}refreshWindowAvailability(){this.residency.refresh()}api(){return{registerWindow:(t,n)=>this.residency.register(t,n),getWindowId:()=>this.residency.getWindowId(),isEnabled:()=>this.enabled,enable:()=>this.setEnabled(!0),disable:()=>{this.setEnabled(!1)},toggle:()=>this.setEnabled(!this.enabled),getPosition:()=>this.handle?.getPosition()??null,setPosition:(t,n)=>this.handle?.setPosition(t,n),getConfig:()=>this.config,setConfig:t=>{this.config=si(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=tC(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=si({appearance:n.appearance,physics:n.physics},this.config),this.handle?.applyConfig(this.config),this.commitLook()},getLook:()=>({appearance:{...this.look.appearance},physics:{...this.look.physics}}),commitStyle:()=>this.commitLook(),resetStyle:()=>{this.look=Mc(),this.config=this.resolveConfig(),this.handle?.applyConfig(this.config),this.commitLook()}}}async setEnabled(t,n=!0){t!==this.enabled&&(this.enabled=t,this.generation++,n&&this.options.persist(t),L(t?"os.mio.enabled":"os.mio.disabled",{}),L(y.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount())}resolveConfig(){const t=si(this.options.serverConfig,$_),n=Q("os.mio.config",t),o=si(n,t);return si({appearance:this.look.appearance,physics:this.look.physics},o)}commitLook(){this.options.persistLook?.({appearance:{...this.look.appearance},physics:{...this.look.physics}})}ensureLayer(){if(this.layer&&this.layer.isConnected)return this.layer;const t=document.getElementById(F_);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=F_,n.className="os-mio",n.dataset.mioVisible=String(this.options.wallpaperVisible?.()??!0),n.setAttribute("aria-hidden","true"),this.options.shell.appendChild(n),this.layer=n,n}mount(){if(this.mounting?.generation===this.generation)return this.mounting.promise;const t=this.mountInstance().finally(()=>{this.mounting?.promise===t&&(this.mounting=null)});return this.mounting={generation:this.generation,promise:t},t}async mountInstance(){const t=this.generation;if(this.handle)return;const n=this.parked;if(n){this.parked=null,n.layer.style.removeProperty("display"),n.handle.applyConfig(this.config),n.handle.setAnimating(!0),this.handle=n.handle,this.layer=n.layer,this.residency.refresh();return}try{await this.loadBundle()}catch(i){console.warn("[desktop-mode/mio] bundle failed to load.",i);return}if(t!==this.generation||!this.enabled)return;const o=window.openStationMountMio;if(typeof o!="function"){console.warn("[desktop-mode/mio] bundle loaded but did not publish window.openStationMountMio.");return}const s=await o({host:this.ensureLayer(),config:this.config,position:J2(),savePosition:i=>{this.residency.getWindowId()||H_(i)}});if(!s){this.layer?.remove(),this.layer=null;return}if(t!==this.generation||!this.enabled){const i=this.layer;this.layer=null,s.setAnimating(!1),i?(i.style.display="none",this.parked={handle:s,layer:i}):s.destroy();return}this.handle=s,this.residency.refresh()}unmount(){const t=this.residency.getWindowId()!==null;this.residency.closeChat();const n=this.handle,o=this.layer;if(this.handle=null,this.layer=null,this.residency.refresh(),!n||!o){o?.remove();return}const s=n.getPosition();s&&!t&&H_(s),n.setAnimating(!1),o.style.display="none",this.parked={handle:n,layer:o}}loadBundle(){if(typeof window.openStationMountMio=="function")return Promise.resolve();if(!this.loading){if(!this.options.bundleUrl)return Promise.reject(new Error("No Mio bundle URL in the shell config."));this.loading=pe(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function J2(){try{const e=window.localStorage.getItem(B_);if(!e)return null;const t=JSON.parse(e);return typeof t?.x!="number"||typeof t?.y!="number"||!Number.isFinite(t.x)||!Number.isFinite(t.y)?null:{x:t.x,y:t.y}}catch{return null}}function H_(e){try{window.localStorage.setItem(B_,JSON.stringify(e))}catch{}}const fu="--os-admin-bar-height",Q2="wpadminbar";function eU(e){const t=e.getBoundingClientRect();return t.height<=0||t.top<0?null:Math.round(t.bottom*100)/100}function tU(e={}){const t=e.bar===void 0?document.getElementById(Q2):e.bar,n=e.root??document.documentElement,o={refresh:()=>{},destroy:()=>{}};if(!t)return o;let s,i=!1;const r=()=>{if(i)return;const c=eU(t);c!==s&&(s=c,c===null?n.style.removeProperty(fu):n.style.setProperty(fu,`${c}px`))};let a=null;typeof ResizeObserver<"u"&&(a=new ResizeObserver(r),a.observe(t,{box:"border-box"}));let l=null;return typeof MutationObserver<"u"&&document.body&&(l=new MutationObserver(r),l.observe(document.body,{attributes:!0,attributeFilter:["class"]})),window.addEventListener("resize",r),r(),{refresh:r,destroy:()=>{i=!0,a?.disconnect(),l?.disconnect(),window.removeEventListener("resize",r),n.style.removeProperty(fu)}}}const nU="New: ",oU=b("Edit this workspace…"),sU=b("New workspace…"),G_=b("Keep this desk"),z_=b("Make this workspace open the way the desk is now — these windows where they are, these widgets, these apps.");function iU(e,t,n=()=>{},o=()=>!1){const s=()=>{const i=e.manager.getActiveDesktopId(),r=c=>e.manager.getAll().filter(d=>(d.config.desktopId||i)===c).length,a=c=>c===i?b("You are here"):le(b("%d open"),r(c)),l=e.manager.getDesktops().map(c=>({label:c.label,description:a(c.id),icon:c.profile?.icon||"dashicons-desktop",run:()=>e.manager.switchDesktop(c.id)}));for(const c of es())l.push({label:`${nU}${c.label}`,description:c.description,icon:c.icon,run:()=>{Ri(e,{preset:c.id})}});return l.push({label:sU,description:b("Blank, or set up for a job — the wizard asks."),icon:"dashicons-plus-alt2",run:n}),l.push({label:oU,description:b("Name, apps, widgets, look and windows."),icon:"dashicons-admin-generic",run:()=>t(e.manager.getActiveDesktopId())}),l.push({label:G_,description:z_,icon:"dashicons-saved",run:()=>{o(e.manager.getActiveDesktopId())}}),l};ao({slug:"keep-desk",label:G_,description:z_,icon:"dashicons-saved",run(i,r){if(!o(e.manager.getActiveDesktopId()))return b("There is no desk to keep.");r.close()}}),ao({slug:"workspace",label:b("Workspace"),description:b("Switch, create or edit a workspace."),hint:"[name]",icon:"dashicons-desktop",suggest(i){const r=i.trim().toLowerCase();return s().filter(c=>!r||c.label.toLowerCase().includes(r)).slice(0,12).map(c=>({value:c.label,label:c.label,description:c.description,icon:c.icon}))},run(i,r){const a=i.trim();if(!a)return b("Type a workspace name to switch to it, or pick a template to create one.");const l=a.toLowerCase(),c=s(),d=c.find(u=>u.label.toLowerCase()===l)??c.find(u=>u.label.toLowerCase().includes(l));if(!d)return le(b("No workspace matching **%s** — try `/workspace` alone to see them all."),a);d.run(),r.close()}})}const sa="os-workspace-wizard-loading";let ia=0;function pu(){return window.openStationWorkspaceWizard??null}function rU(){return window.openStationConfig?.workspaceWizardBundleUrl??""}function aU(){fy({id:sa,label:b("Opening the workspace wizard…"),onCancel:cU,layerStyle:["align-items:center","justify-content:center","padding:16px"],scrimStyle:["background-color:var(--os-ui-scrim,rgba(0,0,0,0.45))","background-image:var(--os-ui-scrim-image,none)","background-repeat:var(--os-ui-scrim-image-repeat,repeat)","background-size:var(--os-ui-scrim-image-size,auto)","background-position:var(--os-ui-scrim-image-position,center)","backdrop-filter:blur(2px)","-webkit-backdrop-filter:blur(2px)"],cardStyle:["max-width:min(760px,94vw)","padding:20px","border-radius:10px","background-color:var(--os-ui-modal-bg,#1d2327)","color:var(--os-ui-modal-fg,var(--os-fg,#fff))","border:1px solid var(--os-ui-modal-border,rgba(255,255,255,0.25))","box-shadow:0 20px 50px rgba(0,0,0,0.6)"]})}function j_(e){const t=pu();if(t){t.openWorkspaceWizard(e);return}const n=rU();if(!n)return;const o=++ia;aU(),pe(n).then(()=>{o===ia&&(pu()?.openWorkspaceWizard(e),mo(sa,uy))}).catch(s=>{o===ia&&mo(sa),typeof console<"u"&&console.warn("[openstation] workspace-wizard bundle failed to load; wizard suppressed:",s)})}function cU(){ia++,mo(sa),pu()?.closeWorkspaceWizard()}function lU(e,t,n=()=>({}),o=()=>{},s=()=>!1){return{list:()=>e.manager.getDesktops(),active:()=>{const i=e.manager.getActiveDesktopId();return e.manager.getDesktops().find(r=>r.id===i)??null},getProfile:i=>sn(e.manager,i),setProfile:(i,r)=>Xn(e,i,r),create:i=>Ri(e,i),switchTo:i=>e.manager.switchDesktop(i),arrange:i=>Kp(e.manager,i),provision:(i,r)=>yc(e,i,r),capture:i=>bc(e.manager,i),captureAppearance:n,edit:t,openCreator:o,saveDesk:s,presets:es,registerPreset:Fp,unregisterPreset:mc}}const V_="desktop-mode/workspace-presets";let ra=null;const Ln=new Set;function dU(e){const t=bA.includes(e.layout)?e.layout:"free";return{id:e.id,label:e.label||e.id,description:e.description||"",icon:e.icon||"dashicons-desktop",color:e.color||"",apps:Array.isArray(e.apps)?e.apps.slice():[],widgets:Array.isArray(e.widgets)?e.widgets.slice():[],appearance:jp(e.appearance??{}),windows:Array.isArray(e.windows)?e.windows.map(n=>({...n})):[],layout:t,order:typeof e.order=="number"?e.order:0}}function uU(e){if(!Array.isArray(e))return;const t=new Set(e.map(o=>o.id).filter(Boolean)),n=new Set(es().filter(o=>!Ln.has(o.id)).map(o=>o.id));for(const o of e)!o?.id||n.has(o.id)||(Fp(dU(o)),Ln.add(o.id));for(const o of[...Ln])t.has(o)||(mc(o),Ln.delete(o));ra=t}function fU(){return lt(y.WORKSPACE_PRESETS,V_,e=>ra?e.filter(t=>Ln.has(t.id)||ra?.has(t.id)):e),()=>{LE(y.WORKSPACE_PRESETS,V_),ra=null;for(const e of Ln)mc(e);Ln.clear()}}function pU(){return document.fullscreenElement!==null}function hU(){if(pU()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function K_(e){const t=document.createElement("span");return t.className="os-shortcuts__chord",e.forEach((n,o)=>{if(o>0){const i=document.createElement("span");i.className="os-shortcuts__plus",i.textContent="+",t.appendChild(i)}const s=document.createElement("kbd");s.className="os-shortcuts__kbd",s.textContent=n,t.appendChild(s)}),t}function mU(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const c=document.createElement("h2");c.className="os-shortcuts__heading",c.textContent=e.heading,t.appendChild(c)}const n=document.createElement("div");n.className="os-shortcuts__scroller";const o=document.createElement("table");o.className="os-shortcuts__table";const s=e.headers??{},i=["key","outside","inside","showDesktop"],r=document.createElement("thead"),a=document.createElement("tr");for(const c of i){const d=document.createElement("th");d.scope="col",d.textContent=s[c]??"",a.appendChild(d)}r.appendChild(a),o.appendChild(r);const l=document.createElement("tbody");for(const c of e.rows??[]){const d=document.createElement("tr"),u=document.createElement("td");if(u.className="os-shortcuts__key-cell",u.appendChild(K_(c.keys??[])),c.note){const f=document.createElement("span");f.className="os-shortcuts__note",f.textContent=c.note,u.appendChild(f)}d.appendChild(u);for(const f of["outside","inside","showDesktop"]){const p=document.createElement("td");p.textContent=c[f]??"",d.appendChild(p)}l.appendChild(d)}return o.appendChild(l),n.appendChild(o),t.appendChild(n),t}function gU(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const o=document.createElement("h2");o.className="os-shortcuts__heading",o.textContent=e.heading,t.appendChild(o)}const n=document.createElement("ul");n.className="os-shortcuts__list";for(const o of e.items??[]){const s=document.createElement("li");s.className="os-shortcuts__item",s.appendChild(K_(o.keys??[]));const i=document.createElement("span");i.className="os-shortcuts__description",i.textContent=o.description??"",s.appendChild(i),n.appendChild(s)}return t.appendChild(n),t}function wU(e){e.innerHTML="";const t=document.createElement("div");t.className="os-shortcuts";const n=window.openStationAdminBar?.shortcuts;if(!n){const o=document.createElement("p");o.className="os-shortcuts__empty",o.textContent="Keyboard shortcuts are unavailable.",t.appendChild(o),e.appendChild(t);return}n.contextual&&t.appendChild(mU(n.contextual)),n.general&&t.appendChild(gU(n.general)),e.appendChild(t)}const hu="openstation-shortcuts",yU=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round"><rect x="5" y="14" width="54" height="36" rx="7"/><path d="M17 26h2M27 26h2M37 26h2M47 26h2M22 39h20"/></svg>')}`;function bU(e){e({id:hu,baseId:hu,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:yU,native:!0,render:wU,width:760,height:560,minWidth:480,minHeight:360})}const q_="openstation-rebrand",vU=1200,_U="a[href], button:not([disabled])";async function EU(e){const t=e.seenIntrosUrl;if(t)try{await Ae(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:q_})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function kU(){const e=document.createElement("div");e.className="os-announce",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","os-announce-title"),e.setAttribute("aria-describedby","os-announce-desc");const t=document.createElement("div");t.className="os-announce__card",e.appendChild(t);const n=document.createElement("div");n.className="os-announce__hero",t.appendChild(n);const o=document.createElement("span");o.className="os-announce__eyebrow";const s=document.createElement("span");s.className="os-announce__eyebrow-dot",s.setAttribute("aria-hidden","true"),o.appendChild(s),o.appendChild(document.createTextNode(b("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=b("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=b("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",t.appendChild(a);const l=document.createElement("p");l.id="os-announce-desc",l.textContent=b("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),a.appendChild(l);const c=document.createElement("p");c.textContent=b("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=b("Everything is already set up. You don't need to install any new plugins, so you can keep using the same features as before."),a.appendChild(d);const u=document.createElement("div");u.className="os-announce__actions",t.appendChild(u);const f=document.createElement("button");return f.type="button",f.className="os-announce__btn os-announce__btn--primary",f.dataset.rebrandDismiss="",f.textContent=b("Got it"),u.appendChild(f),e}async function SU(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(q_))return;await new Promise(c=>window.setTimeout(c,vU));const n=kU(),o=n.querySelector(".os-announce__card"),i=document.activeElement;let r=!1;const a=()=>{r||(r=!0,document.removeEventListener("keydown",l,!0),n.remove(),i?.focus?.(),EU(t))};function l(c){if(!n.isConnected){document.removeEventListener("keydown",l,!0);return}if(c.key==="Escape"){c.preventDefault(),a();return}if(c.key!=="Tab")return;const d=Array.from(n.querySelectorAll(_U));if(d.length===0)return;const u=d[0],f=d[d.length-1],p=n.ownerDocument.activeElement;c.shiftKey&&(p===u||!n.contains(p))?(c.preventDefault(),f.focus()):!c.shiftKey&&(p===f||!n.contains(p))&&(c.preventDefault(),u.focus())}n.addEventListener("click",c=>{o&&!o.contains(c.target)&&a()});for(const c of n.querySelectorAll("[data-rebrand-dismiss]"))c.addEventListener("click",a);document.addEventListener("keydown",l,!0),document.body.appendChild(n),n.querySelector(".os-announce__btn--primary")?.focus()}const IU="shell-tour",AU="os-shell-tour-start",CU="openstation-shell-tour";function Y_(){return window.openStationUsageFeedback??null}function LU(){return window.openStationConfig?.usageFeedbackBundleUrl??""}async function TU(e){let t=Y_();if(!t){const n=LU();if(!n)return!1;try{await pe(n)}catch(o){return typeof console<"u"&&console.warn("[openstation] usage-feedback bundle failed to load; prompt suppressed:",o),!1}t=Y_()}return t?(t.showUsageFeedbackPrompt(e),!0):!1}const aa="usage-feedback",NU=4e3;async function OU(e){const t=e.seenIntrosUrl;if(t)try{await Ae(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:aa})},{source:"desktop-mode/usage-feedback",silent:!0})}catch{}}async function DU(e){const{config:t}=e,n=t.usageFeedback;if(!n||t.seenIntros?.includes(aa))return;const o=e.showPrompt??TU;await new Promise(i=>window.setTimeout(i,NU)),!await o({restUrl:n.restUrl,restNonce:t.restNonce??"",onAnswered:i=>{if(t.seenIntros=[...t.seenIntros??[],aa],i==="sent"){ue({message:b("Thank you! That really helps.")});return}OU(t)}})&&typeof console<"u"&&console.warn("[openstation] usage feedback prompt could not be shown.")}const ca="openstation/shell-tour-loader",xU=1200;let mu=0;function la(){return window.openStationShellTour??null}function RU(e,t){return!(e.shellTour===!1||e.soloWindow||e.seenIntros?.includes(IU)||e.rebrandNotice||e.usageFeedback&&!e.seenIntros?.includes(aa)||t())}function da(e){if(e.isMobile())return;const t=la();if(t){t.startShellTour(e);return}const n=e.config.shellTourBundleUrl??"";if(!n)return;const o=++mu;pe(n).then(()=>{o!==mu||e.isMobile()||la()?.startShellTour(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] shell-tour bundle failed to load; tour suppressed:",s)})}function MU(e){const t=new AbortController,{signal:n}=t;let o=0;const s=()=>{t.abort(),window.clearTimeout(o),Ct(y.DESKTOP_ICON_CLICKED,ca),Ct(y.MODE_CHANGED,ca)};return document.addEventListener(AU,()=>da(e),{signal:n}),document.addEventListener("os-intros-reset",()=>da(e),{signal:n}),ee(y.DESKTOP_ICON_CLICKED,ca,i=>{i?.id===CU&&da(e)}),ee(y.MODE_CHANGED,ca,i=>{i?.mode==="mobile"&&(mu++,la()?.endShellTour())}),RU(e.config,e.isMobile)&&(o=window.setTimeout(()=>{(e.updateNoticeShown??Promise.resolve(!1)).catch(()=>!1).then(i=>{i||n.aborted||la()?.isShellTourRunning()||da(e)})},xU)),s}function WU(){const e=window.wp?.os?.refreshMenu;if(typeof e=="function")try{e()}catch{}}const PU="(display-mode: standalone)";function X_(e,t){return e||t?.standalone===!0?"standalone":"browser"}const $U=["auto","desktop","mobile"],ua={mobile:767,tablet:1024};function fa(e){return $U.includes(e)?e:"auto"}function UU(e){const t=e&&typeof e=="object"?e:{},n=(i,r)=>{const a=typeof i=="number"?i:Number(i);return Number.isFinite(a)&&a>0?Math.floor(a):r},o=n(t.mobile,ua.mobile),s=Math.max(o+1,n(t.tablet,ua.tablet));return{mobile:o,tablet:s}}function Z_(e,t="auto",n=ua){return t==="mobile"?"mobile":t==="desktop"?"desktop":e<=n.mobile?"mobile":e<=n.tablet?"tablet":"desktop"}function BU(e={}){const t=e.root??document.documentElement,n=e.win??window,o=UU({...ua,...e.breakpoints??{}});let s=fa(e.preference);const i=new Set,r=()=>typeof n.innerWidth=="number"&&n.innerWidth>0?n.innerWidth:Number.POSITIVE_INFINITY;let a=Z_(r(),s,o);Nu(t,a);const l=e.nav??(typeof navigator<"u"?navigator:void 0),c=typeof n.matchMedia=="function"?n.matchMedia(PU):null;let d=X_(!!c?.matches,l);Ou(t,d);const u=()=>{d=X_(!!c?.matches,l),Ou(t,d)},f=()=>{const h=Z_(r(),s,o);if(h===a)return;const m={mode:h,previous:a,preference:s};a=h,Nu(t,a),L(y.MODE_CHANGED,m),document.dispatchEvent(new CustomEvent("os-mode-changed",{detail:m}));for(const E of i)try{E(m)}catch(k){console.error("[openstation] mode listener threw:",k)}},p=[];if(typeof n.matchMedia=="function")for(const h of[o.mobile,o.tablet]){const m=n.matchMedia(`(max-width: ${h}px)`);typeof m.addEventListener=="function"?m.addEventListener("change",f):typeof m.addListener=="function"&&m.addListener(f),p.push(m)}return c&&(typeof c.addEventListener=="function"?c.addEventListener("change",u):typeof c.addListener=="function"&&c.addListener(u)),{api:{get:()=>a,getPreference:()=>s,getBreakpoints:()=>({...o}),isMobile:()=>a==="mobile",getDisplay:()=>d,isStandalone:()=>d==="standalone",subscribe(h,m){return i.add(h),m?.immediate&&h({mode:a,previous:a,preference:s}),()=>{i.delete(h)}}},setPreference(h){const m=fa(h);m!==s&&(s=m,f())},dispose(){for(const h of p)typeof h.removeEventListener=="function"?h.removeEventListener("change",f):typeof h.removeListener=="function"&&h.removeListener(f);c&&(typeof c.removeEventListener=="function"?c.removeEventListener("change",u):typeof c.removeListener=="function"&&c.removeListener(u)),i.clear()}}}function FU(e){return Jt(e)||DE(e)}function HU(e={}){const t=e.root??document.documentElement,n=e.doc??document,o=a=>{FU(t)&&a.cancelable&&a.preventDefault()},s=a=>{a.touches?.length>1&&o(a)},i=a=>{a.ctrlKey&&o(a)},r={passive:!1};return n.addEventListener("gesturestart",o,r),n.addEventListener("gesturechange",o,r),n.addEventListener("gestureend",o,r),n.addEventListener("touchmove",s,r),n.addEventListener("wheel",i,r),()=>{n.removeEventListener("gesturestart",o),n.removeEventListener("gesturechange",o),n.removeEventListener("gestureend",o),n.removeEventListener("touchmove",s),n.removeEventListener("wheel",i)}}const Tn="openstation/mobile";function GU(e){const t=Array.isArray(e?.windows)?e.windows:[],n=e?.focused??"",o=t.find(s=>s.id===n);return{restore:o?[o]:[],recents:t.filter(s=>s!==o)}}function zU(e){const{manager:t,mode:n}=e,o=new Map,s=new Map;let i=[];const r=new Set,a=()=>{for(const h of r)h()},l=h=>{if(!n.isMobile())return;const m=t.getById(h);if(!(!m||m.isMinimized()||m.isMaximized()||m.isFullscreen())){if(!o.has(m.id)){const E=m.getSnapshot();o.set(m.id,{x:E.x,y:E.y,width:E.width,height:E.height,state:E.state,unplaced:!1})}m.maximize()}},c=h=>{if(!n.isMobile())return;const m=t.getById(h);if(!m)return;const E=t.getActiveDesktopId(),k=m.config.desktopId||E;k!==E&&(s.has(h)||s.set(h,k),t.moveWindowToDesktop(h,E))},d=()=>{if(s.size===0)return;const h=new Set(t.getDesktops().map(k=>k.id));for(const[k,N]of s)h.has(N)&&t.moveWindowToDesktop(k,N);s.clear();const m=t.getActiveDesktopId(),E=t.getFocused();if(E&&(E.config.desktopId||m)!==m){const k=[...t.getAll()].reverse().find(N=>(N.config.desktopId||m)===m&&!N.isMinimized());k&&t.focus(k)}},u=h=>{const m=he();if(m.width<=0||m.height<=0)return null;const E=12,k=Math.min(Math.round(m.width*.8),1200),N=Math.min(Math.round(m.height*.8),800),M=40+h%8*30;return{x:Math.max(m.x+E,Math.min(m.x+M,m.x+m.width-k-E)),y:Math.max(m.y+E,Math.min(m.y+M,m.y+m.height-N-E)),width:k,height:N}};lt(y.WINDOW_GEOMETRY,Tn,(h,m)=>!n.isMobile()||h.state==="minimized"?h:(o.set(m.windowId,{x:h.x,y:h.y,width:h.width,height:h.height,state:h.state??"normal",unplaced:!m.hasSavedGeometry&&!m.callerPinned}),{...h,state:"maximized"}));const f=h=>{const m=h?.windowId;m&&l(m)};ee(y.WINDOW_RESTORED,Tn,f),ee(y.WINDOW_UNMAXIMIZED,Tn,f),ee(y.WINDOW_OPENED,Tn,h=>{const m=h?.windowId;m&&(c(m),l(m))}),ee(y.WINDOW_CLOSED,Tn,h=>{const m=h?.windowId;m&&(o.delete(m),s.delete(m))});const p=n.subscribe(h=>{if(h.mode==="mobile"){for(const E of t.getAll())c(E.id),l(E.id);return}if(h.previous!=="mobile")return;d();let m=0;for(const E of t.getAll()){const k=o.get(E.id);if(!(!k||!E.isMaximized())){if(k.unplaced){const N=u(m++);N&&(E._savedGeometry=N)}E.toggleMaximize()}}o.clear()});lt(y.SESSION_SNAPSHOT,Tn,h=>{const m=new Set(h.windows.map(N=>N.id)),E=h.windows.map(N=>{const M=o.get(N.id),S=s.get(N.id);return!n.isMobile()||!M&&!S?N:{...N,...M?{x:M.x,y:M.y,width:M.width,height:M.height,state:M.state,...M.unplaced?{unplaced:!0}:{}}:{},...S?{desktopId:S}:{}}}),k=i.filter(N=>!m.has(N.id));return k.length?{...h,windows:[...E,...k]}:{...h,windows:E}});const g={list:()=>i.slice(),forget(h){const m=i.filter(E=>E.id!==h);m.length!==i.length&&(i=m,a())},open(h){if(g.forget(h.id),h.native)return e.openNative(h.id,h.baseId||h.id,{desktopId:h.desktopId,...h.params?{params:h.params}:{}}),void 0;const m=kr(h.url);t.openNew({id:h.id,baseId:h.baseId||h.id,url:h.url,parentUrl:m?.url??h.url,title:h.title,icon:h.icon||"dashicons-admin-generic",desktopId:h.desktopId,x:h.x,y:h.y,width:h.width,height:h.height,submenu:m?.submenu,selfLabel:m?.selfLabel,multi:!!m?.multi}).then(E=>{for(const k of h.externalTabs??[])E.addExternalTab(k.url,k.label)}).catch(E=>{console.error("[openstation] could not reopen a recent window:",E)})},subscribe(h){return r.add(h),()=>{r.delete(h)}}};return ee(y.WINDOW_OPENED,Tn,h=>{const m=h?.windowId;m&&g.forget(m)}),{recents:g,trimSessionForMobile(h){const{restore:m,recents:E}=GU(h.session);return i=E,a(),{...h,session:{...h.session,windows:m}}},forcedIds:()=>Array.from(o.keys()),foldedIds:()=>Array.from(s.keys()),dispose(){p(),r.clear()}}}let pa=null;function gu(){return window.openStationMobile}function jU(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-mobile="1"]'),s=()=>{const a=gu();if(a){t(a);return}n(new Error("[openstation] mobile bundle loaded but did not set `window.openStationMobile`."))},i=()=>n(new Error("failed to load the mobile bundle"));if(o){gu()?s():(o.addEventListener("load",s),o.addEventListener("error",i));return}const r=document.createElement("script");r.src=e,r.async=!0,r.dataset.osMobile="1",r.addEventListener("load",s),r.addEventListener("error",i),document.head.appendChild(r)})}function VU(e){const t=gu();return t?Promise.resolve(t):e?(pa||(pa=jU(e).catch(n=>{throw pa=null,n})),pa):Promise.reject(new Error("[openstation] no `mobileBundleUrl` in the shell config — is `mobile[.min].js` built and the config key wired?"))}function KU(e){const{manager:t,adminUrl:n,openNative:o}=e;return s=>{if(s.windowId){const u=t.getById(s.windowId);if(u)return u.isMinimized()&&u.restore(),t.focus(u),!0;if(o(s.windowId))return!0}if(s.tile)return s.tile.onOpen(),!0;const i=s.menu?.url||s.entry?.url||"";if(!i)return!1;if(to(i)||Be(i))return!0;let r;try{r=new URL(i,window.location.origin)}catch{return!1}const a=r.toString(),l=fe(a,n),c=s.menu??kr(a)??null,d=s.icon||c?.icon||"dashicons-admin-generic";return t.open({id:l,baseId:l,url:a,parentUrl:c?.url??a,title:s.title,icon:d.startsWith("dashicons-")||d.startsWith("data:")||/^https?:/.test(d)?d:"dashicons-admin-generic",submenu:c?.submenu,selfLabel:c?.selfLabel,multi:!!c?.multi}),!0}}function qU(){return window.wp?.os?.config??{}}async function YU(e,t){const{restUrl:n,restNonce:o}=qU();if(!n||!e||!(t>0))throw new Error("[openstation] trashByRestPath: missing REST config or target.");const s=await Ae(nt(n,`${e.replace(/\/+$/,"")}/${t}`),{method:"DELETE",credentials:"same-origin",headers:{"X-WP-Nonce":String(o??""),Accept:"application/json"}},{source:"my-wordpress/trash"});if(!s.ok)throw await Wn(s)}const XU=se("desktop-mode/recycle-bin-payload-handlers",()=>({handlers:new Map}));function J_(){return XU.state.handlers}function ZU(e){const t=J_().get(e.type);return t?t.accept(e.data):!1}function JU(e,t){const n=J_().get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}const QU=new Set(["user","attachment"]),wu="data-os-trash-drop-active",ii="desktop-mode-recycle-bin",eB=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${ii}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${ii}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${ii}"]`},{id:"recycle-bin-window",selector:"[data-os-recycle-bin-root]"}];let Q_=!1;const yu=new Map;let eE=null;function tB(e){return e.payload.type==="desktop-file"}function nB(e){return e.payload.type==="shortcut"}function oB(e){if(!e.kind||!e.ref||!e.restPath||QU.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return Number.isFinite(t)&&t>0}function sB(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:b("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const s=o.data,i=s?.placement;if(!i)return!1;const r=Sn(s);return r.length>1?r.every(a=>a.file?.ref!==ii&&a.canTrash!==!1):i.file?.ref===ii?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=Hr(s);return i.length>0&&i.every(r=>oB(r))}return ZU(o)},onEnter:()=>{n.setAttribute(wu,"")},onLeave:()=>{n.removeAttribute(wu)},onDrop:(o,s)=>{if(n.removeAttribute(wu),tB(o)){Iv(Sn(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&JU(o,s))&&nB(o)){const r=Hr(o.payload.data).map(l=>({title:l.title??"",icon:l.icon??"",restPath:l.restPath,kind:l.kind,ref:Number.parseInt(l.ref,10)})).filter(l=>!!l.restPath&&Number.isFinite(l.ref)&&l.ref>0);if(r.length===0)return;const a=r.map(l=>hn(my({id:l.ref,type:l.kind,title:l.title,icon:l.icon})));Promise.allSettled(r.map((l,c)=>a[c]?YU(l.restPath,l.ref):Promise.reject(new Error("Item is already moving to Trash.")))).then(l=>{const c=l.filter(p=>p.status==="rejected");for(const p of c)console.error("[openstation] recycle-bin: shortcut trash failed:",p.reason);const d=r.filter((p,g)=>l[g]?.status==="fulfilled").reduce((p,g)=>{var h;return(p[h=g.kind]??(p[h]=[])).push(g.ref),p},{}),u=window.wp?.os?.announceContentChange;for(const[p,g]of Object.entries(d))u?.(p,"trashed",g,"recycle-bin");l.forEach((p,g)=>{a[g]?.finish(p.status==="fulfilled")});const f=r.length-c.length;if(f>1||c.length>0){const p=c.length>0?_v(c[0].reason):"",g={message:c.length>0?`${f} moved to Trash · ${c.length} could not be moved${p?`: ${p}`:""}`:`${f} items moved to Trash`,duration:c.length>0?6e3:4e3};c.length>0&&(g.type=f>0?"warning":"error"),ue(g)}})}}})}function iB(e){if(Q_)return;Q_=!0;const t=()=>{for(const{id:n,selector:o}of eB){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=yu.get(n);if(!i){r?.deregister(),yu.delete(n);continue}r&&r.el===i||(r?.deregister(),yu.set(n,{el:i,deregister:sB(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),ee(y.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),ee(y.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){eE=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;eE.observe(n,{childList:!0,subtree:!0})}}function bu(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function rB(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function tE(e){return{appliesTo(t){return bu(t)!==null},accept(t,n){const o=bu(n);if(!o)return!1;const s=Id({type:e,data:t});return EW(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:b("Send to agent","desktop-mode"),onDrop(t,n,o){const s=bu(o);if(!s)return;const i=Id({type:t.payload.type,data:t.payload.data}),r=rB();!i||!r||AW({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let nE=!1;function aB(){nE||(nE=!0,Gs("shortcut",tE("shortcut")),Gs("desktop-file",tE("desktop-file")))}let oE=!1,Nn=0;function cB(){oE||(oE=!0,$e.contribute("openstation_files_subscribe",()=>{const e=Yt(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:Nn,sharesVersion:Zr().state.sharesVersion}}),$e.subscribe("openstation_files",e=>{lB(e)}))}function lB(e){const t=e.folders??[];for(const i of t)xd(i,"remote"),i.updatedAtMs>Nn&&(Nn=i.updatedAtMs);const n=e.placements??[];for(const i of n)Od(i,"remote"),i.updatedAtMs>Nn&&(Nn=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])Rd(i,"remote");for(const i of o.placements??[])Fs(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>Nn&&(Nn=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&u_(s),e.truncated){const i=Array.from(Yt().hydratedFolders);for(const r of i)Ue(r).then(a=>{qt(r,a.placements)}).catch(()=>{})}}let sE=!1;const dB=[];function uB(){if(sE)return;sE=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||fB()};dB.push(co("os.placement.changed",e),co("os.shortcut.changed",e),co("os.folder.changed",e))}function fB(){rv().then(t=>{Dd(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from(Yt().hydratedFolders);for(const t of e)Ue(t).then(n=>{qt(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const ri="os-wallpaper-menu";let Ro=null;function iE(){return Ro!==null}let rE=0;function pB(e,t,n,o={}){ai();const s=++rE;gi(()=>s===rE,()=>hB(e,t,n,o))}function hB(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,g=typeof f.sort=="number"?f.sort:100;return p!==g?p-g:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(ri),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const l=()=>{r&&(r.remove(),r=null,a=null)};for(const u of n){i.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.heading&&f.setAttribute("heading",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",aE(u.icon));const p=Array.isArray(u.children)&&u.children.length>0;p&&f.setAttribute("has-children",""),f.textContent=u.label,f.addEventListener("mouseenter",()=>{if(p){c(u,f);return}l()}),s.appendChild(f)}s.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=i.get(f.id)??null;if(p){if(Array.isArray(p.children)&&p.children.length>0){if(u.stopPropagation(),a&&a.id===p.id){l();return}const g=s.querySelector(`[data-menu-item-id="${p.id}"]`);g&&c(p,g);return}ai(),p.onClick(new MouseEvent("click"))}});function c(u,f){l();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(ri,`${ri}--flyout`),p.dataset.parentId=u.id;const g=(u.children??[]).slice().sort((h,m)=>{const E=typeof h.sort=="number"?h.sort:100,k=typeof m.sort=="number"?m.sort:100;return E!==k?E-k:h.label.localeCompare(m.label)});for(const h of g){const m=document.createElement("os-context-menu-option");m.dataset.menuItemId=h.id,m.setAttribute("value",h.id),h.icon&&m.setAttribute("icon",aE(h.icon)),h.disabled&&m.setAttribute("disabled",""),h.checked&&m.setAttribute("checked",""),m.textContent=h.label,m.addEventListener("os-context-menu-pick",E=>{E.stopPropagation(),ai(),h.onClick(new MouseEvent("click"))}),p.appendChild(m)}document.body.appendChild(p),r=p,a=u,bb(p,f)}e.appendChild(s),Ro=s,nd(s);const d=wb(s,{close:()=>ai(),siblingSelectors:[`.${ri}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),L("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function ai(){Ro&&(document.querySelectorAll(`.${ri}--flyout`).forEach(e=>e.remove()),Ro.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),Ro.remove(),Ro=null,L("os.wallpaper-menu.closed",{}))}function mB(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:"add-widget",label:e.labels.addWidget,icon:"dashicons-screenoptions",sort:15,onClick:()=>e.addWidget()},{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=>gB(i,e)),o=[...t,...n],s=Q("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function gB(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()}L("os.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function aE(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function vu(e){const t=e.dataTransfer?.types;return t?Array.from(t).includes("Files"):!1}function wB(e){if(!e.bundleUrl||Jt())return()=>{};let t=null,n=!1;const o=[],s=()=>{window.removeEventListener("dragenter",r,!0),window.removeEventListener("dragover",a),window.removeEventListener("drop",l)},i=()=>(t||(t=pe(e.bundleUrl).then(()=>{const c=window.openStationFileDrop;if(c){c.boot(e.boot),n=!0,s();for(const d of o.splice(0))c.replayCapturedDrop(d)}}).catch(c=>{t=null,console.warn("[openstation] file-drop bundle failed to load",c),o.length>0&&(o.length=0,ue({message:b("That drop could not be processed — please try again.","desktop-mode")}))})),t),r=c=>{vu(c)&&i()},a=c=>{!n&&vu(c)&&(c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"))},l=c=>{if(n||!vu(c))return;const d=c.defaultPrevented;c.preventDefault(),o.push({files:c.dataTransfer?Array.from(c.dataTransfer.files):[],clientX:c.clientX,clientY:c.clientY,target:c.target,alreadyClaimed:d}),i()};return window.addEventListener("dragenter",r,!0),window.addEventListener("dragover",a),window.addEventListener("drop",l),s}const cE=[];let _u=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(_u){Promise.resolve().then(o);return}cE.push(o)}},ready(o){n.whenReady(o)},isReady(){return _u}};t.wp.os=n})();let Eu=[],ha=Number.POSITIVE_INFINITY,ku=!1;function Je(e,t=1500){if(Eu.push(e),t<ha&&(ha=t),ku)return;ku=!0;const n=()=>{const o=Eu;Eu=[],ha=Number.POSITIVE_INFINITY,ku=!1;for(const s of o)try{s()}catch(i){typeof console<"u"&&console.error("[openstation] scheduleIdleBoot callback threw:",i)}};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(n,{timeout:ha}):window.setTimeout(n,0)}function lE(){const e=window.openStationConfig;if(!e)return;Db(e);const t=document.getElementById("os-area");if(!t)return;const n=ek(window.location.href);if(n)try{window.history.replaceState(window.history.state,"",n)}catch{}CL(e.arrivalDirection==="next"||e.arrivalDirection==="prev"?e.arrivalDirection:null);const o=new e0(t),s=document.getElementById("os-wallpaper"),i=e.pluginUrl||"";let r=null;s&&(r=new ig(s,i));const a=document.getElementById("os-widgets");let l=null;y2(),iL(),a&&(l=new OD(a,i)),eg({id:"pixijs",url:`${i}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const c=new yL(r??new ig(document.createElement("div"),i));c.apply(),c.applyWidgets=w=>l?.setEnabledIds(w),o.openWindowsAs=()=>c.state.openWindowsAs;const d=BU({preference:fa(c.getOsSettingsSnapshot().mobileLayout??e.mode?.preference),breakpoints:e.mode?.breakpoints});c.subscribeOsSettings(w=>{d.setPreference(fa(w.mobileLayout))}),HU();const u=zU({manager:o,mode:d.api,openNative:(w,I,H)=>Z(w,I,H)}),f=document.getElementById("os-shell"),p=new Z2({shell:f??document.body,focusedWindow:()=>{const w=o.getFocused();return w&&o.isActive(w.id)?w.id:null},bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:c.state.mioEnabled,wallpaperVisible:()=>c.state.mioShowOnWallpaper,chatAvailable:()=>!!(c.state.ai.enabled&&e.aiAssistant?.available&&e.aiAssistant.assistantProviderConfigured),persist:w=>{c.state.mioEnabled=w,c.state.mioApiEnabled=w,c.save()},savedLook:c.state.mioStyle,persistLook:w=>{c.state.mioStyle=w,c.save()}}),g=p.api();if(c.subscribeOsSettings(w=>p.syncEnabled(w.mioEnabled)),document.addEventListener("os-ai-status-changed",()=>p.refreshWindowAvailability()),!d.api.isMobile())p.boot();else{const w=d.api.subscribe(I=>{I.mode!=="mobile"&&(w(),p.boot())})}l&&E2({osSettings:c,layer:l});const h=new ix({aiSearchUrl:e.aiSearchUrl??"",restNonce:e.restNonce,adminUrl:e.adminUrl,isAiSupported:()=>e.aiAssistant?.available===!0,canConnectProvider:()=>!!e.currentUserIsAdmin,isAiAvailable:()=>e.aiAssistant?.available===!0&&e.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>c.getOsSettingsSnapshot().ai.enabled!==!1},e.aiAssistantBundleUrl??"");h.attachAsk(dx({config:()=>e,fallbackContext:()=>({close:()=>h.close(),openInWindow:(w,I,H)=>{o.open({url:w,title:I,icon:H??"dashicons-admin-generic"})},confirm:w=>rn({message:w})})}));const m=new pR,E=new TR;document.addEventListener(Ce.START,w=>{const H=w.detail?.payload;if(!H||H.type!=="shortcut"&&H.type!=="desktop-file")return;const j=H.data?.bridgePayload;j&&m.start(j)}),document.addEventListener(Ce.END,()=>{m.end()}),Je(()=>zR(E)),Je(()=>sM(o)),window.addEventListener("message",w=>{if(w.origin!==window.location.origin)return;const I=w.data;!I||I.type!=="os-drop-failed"||ue({message:"Could not insert into the editor."})}),ib({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>h.open(),close:()=>h.close(),isOpen:()=>h.isOpen}),s0(),lM(),n0(o),d0(o),g0(o,{shouldAsk:()=>c.state.confirmCloseAllWindows,setAsk:w=>{c.state.confirmCloseAllWindows=w,c.save()}}),Je(()=>{new MO({manager:o,adminUrl:e.adminUrl}).install(),WO(o);const w=new zO({manager:o,adminUrl:e.adminUrl,titleForUrl:I=>Kh(I,e)});w.install(),document.addEventListener(Dw,()=>w.install(),{once:!0})}),document.addEventListener("os-open-ai",()=>{Or("desktop-mode-ai-assistant")}),document.addEventListener("click",w=>{const I=w.target;!(I instanceof Element)||!I.closest("#wp-admin-bar-command-palette")||(w.preventDefault(),w.stopImmediatePropagation(),Or("desktop-mode-ai-assistant"))},!0);const k=document.getElementById("os-dock"),N=document.getElementById("os-shell"),M=N?.querySelector(".os-shell__body");let S=null,$=null;const W=(w,I)=>{if(d.api.isMobile()){w.setAppearance?.(null),w.setVisibleWidgets?.(null);return}wc(w,I)},F=(w,I)=>{d.api.isMobile()||yc(w,I)};let x=!1;const q=()=>jp(c.getOsSettingsSnapshot()),J=w=>({presets:es(),apps:w.getNavItems().map(I=>({id:I.id,title:I.title,kind:I.kind,locked:I.locked,url:I.menu?.url||I.entry?.url||void 0,windowId:I.windowId})),widgets:Ka().map(I=>({id:I.id,label:I.label||I.id,description:I.description})),enabledWidgetIds:l?.getEnabledIds()??[],wallpapers:ja().map(I=>({id:I.id,label:I.label,preview:I.preview})),accents:zo().map(I=>({id:I.id,label:I.label,value:I.value})),resolvePreset:I=>Hp(I,w.getNavItems()),captureAppearance:q}),X=w=>{if(!$)return;const I=$,H=w??Ri(I).id;j_({mode:"create",...J(I),onCreate:j=>{Ri(I,{desktopId:H,label:j.label||void 0,...j.preset?{preset:j.preset}:{profile:j.profile??void 0}}),W(I,H),F(I,H)}})},T=(w=o.getActiveDesktopId())=>{if(!$)return!1;const I=S?.getNav();let H;I&&(H=[...I.dock.core,...I.dock.apps,...I.dock.controls,...I.sidebar,...I.desktop].filter(Ee=>!I.ephemeral.has(Ee.id)).map(Ee=>Ee.id));const j=LA($,w,{visibleAppIds:H,mountedWidgetIds:l?.getMountedIds()});if(!j)return!1;const we=o.getDesktops().find(_e=>_e.id===w)?.label??"",Qe=o.getAll().filter(_e=>(_e.config.desktopId||w)===w).length,ct=j.windows.length;let oe;return Qe>ct?oe=le(b("%1$s will open like this — the top %2$d of %3$d windows, where they are."),we,ct,Qe):oe=le(b("%1$s will open like this — %2$d windows, where they are."),we,ct),ue({message:oe}),!0},D=w=>{if(!$)return;const I=o.getDesktops().find(j=>j.id===w);if(!I)return;const H=$;j_({mode:"edit",desktopId:w,label:I.label,profile:I.profile??zp(),...J(H),onSave:j=>{j.label&&o.renameDesktop(w,j.label),Xn(H,w,j.profile)},captureWindows:()=>bc(o,w),onDelete:o.getDesktops().length>1?()=>o.closeDesktop(w):void 0})},K=w=>w.some(I=>!!I.windowId&&o.getAllByBaseIdOnActiveDesktop(I.windowId).length>0),G=zD({manager:o,appendSystemTile:w=>S?.appendSystemTile(w),removeSystemTile:w=>S?.removeSystemTile(w)}),ne=G.sync;sk({getSnapshot:()=>c.getOsSettingsSnapshot(),openById:(w,I)=>G.openById(w,I),openNewById:(w,I)=>G.openNewById(w,I),adminUrl:e.adminUrl});const ce=w=>{const I=fe(w,e.adminUrl),H=S?S.getMenuItems():e.dockItems??[];for(const j of H){if(fe(j.url,e.adminUrl)===I)return{title:j.title,icon:j.icon,url:j.url,submenu:j.submenu,selfLabel:j.selfLabel,multi:j.multi};for(const we of j.submenu??[])if(fe(we.url,e.adminUrl)===I)return{title:we.title,icon:j.icon,url:j.url,multi:j.multi}}return null},R=qc,C=(w,I)=>{const H=e.multisite?.hopUrl;return H?_L({hopUrl:H,restNonce:e.restNonce})(w,I):Promise.resolve(null)};if(PA(()=>e.multisite?nT(e.multisite,{mint:C}):null),document.addEventListener("os-app-effect",w=>{const I=w.detail?.effect;I?.type==="hop"&&e.multisite&&typeof I.site=="string"&&nl(e.multisite,I.site,{mint:C})}),tT({multisite:()=>e.multisite,isShown:()=>!!document.querySelector(".os-area--overview .os-site-switcher"),mint:C}),e.hopLinkOffer&&sT(e.hopLinkOffer,{confirm:w=>rn(w),post:oT(e.restNonce)}),F0({adminUrl:e.adminUrl,deriveSlug:w=>fe(w,e.adminUrl),openWindow:w=>{o.open(w)},findDockEntry:ce,openOtherAdmin:R}),yt({id:"desktop-mode-dashboard",nativeWindowId:"desktop-mode-dashboard",matches:(w,I)=>v0(I),enabled:w=>w.stationHomeEnabled===!0}),yt({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(w,I)=>{if(!I.pathname.endsWith("/edit.php"))return!1;const H=I.searchParams.get("post_type");return!H||H==="post"},enabled:w=>w.nativePostsEnabled===!0}),yt({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(w,I)=>I.pathname.endsWith("/edit.php")?I.searchParams.get("post_type")==="page":!1,enabled:w=>w.nativePagesEnabled===!0}),yt({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(w,I)=>I.pathname.endsWith("/users.php"),enabled:w=>w.nativeUsersEnabled===!0}),yt({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(w,I)=>{if(ok(I))return!1;const H=I.pathname;return H.endsWith("/profile.php")?!0:H.endsWith("/user-edit.php")?I.searchParams.has("user_id"):!1},enabled:w=>w.nativeUsersEnabled===!0,params:(w,I)=>{const H=parseInt(I.searchParams.get("user_id")??"0",10);return{userId:H>0?H:0}}}),yt({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(w,I)=>I.pathname.endsWith("/edit-comments.php"),enabled:w=>w.nativeCommentsEnabled===!0,params:(w,I)=>{const H=parseInt(I.searchParams.get("p")??"0",10);return{post:H>0?H:0}}}),yt({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(w,I)=>{const H=I.pathname;return H.endsWith("/plugins.php")||H.endsWith("/plugin-install.php")},enabled:w=>w.nativePluginsEnabled===!0,params:(w,I)=>({tab:I.pathname.endsWith("/plugin-install.php")?"browse":"installed"})}),k&&N&&M&&e.dockItems){t.classList.add("os-area--with-dock");const w=c.getOsSettingsSnapshot(),I=w.desktopLayout,H=w.dockPlacement,j=oe=>{ay(t,oe,{openWindow:G.openById,manager:o,deriveWindowId:_e=>fe(_e,e.adminUrl)})};S=nx({shellRoot:N,shellBody:M,bottomDockEl:k,desktopArea:t,windowManager:o,adminUrl:e.adminUrl,renderIcons:j,getSettings:()=>{const oe=c.getOsSettingsSnapshot();return{navPlacement:oe.navPlacement,navOrder:oe.navOrder}},getWorkspaceProfile:()=>d.api.isMobile()?null:SA(o)},I,e.dockItems,e.desktopIcons,H),tU(),$I({shell:N,shellBody:M,area:t}),fA(o),J0({shellBody:M,getBehaviors:()=>({dock:c.state.dockBehavior,sidebar:c.state.sideDockBehavior})}),aO({bundleUrl:e.dockConstellationBundleUrl??"",deps:{windowManager:o,adminUrl:e.adminUrl,getMenuItems:()=>S?.getMenuItems()??[],getSystemItem:oe=>S?.getSystemTile(oe)??null}}),$={manager:o,getNavItems:()=>S?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:oe=>fe(oe,e.adminUrl),openNative:G.openById,refreshLayout:()=>S?.refresh(),setVisibleWidgets:oe=>l?.setVisibleIds(oe),setAppearance:oe=>c.setWorkspaceAppearance(oe)},fU(),uU(e.workspacePresets),iU($,D,X,T),TA({...$,openCreator:X,openEditor:D}),ee(y.DESKTOP_SWITCHED,"desktop-mode/workspace-provision",oe=>{!$||!oe?.to||(W($,oe.to),F($,oe.to))});const we=(oe,_e)=>{if(!$||!_e)return;const Ee=o.getActiveDesktopId(),et=sn(o,Ee);if(!et||et.widgets?.mode!=="only")return;const hi=kA(et,oe,_e);hi!==et&&Xn($,Ee,hi)};if(ee(y.WIDGET_ADDED,"desktop-mode/workspace-widgets",oe=>we(oe.id,!0)),$){const oe=o.getActiveDesktopId();W($,oe),F($,oe)}const Qe=tR(e.pwa?.appName||"WordPress",ue),ct={id:Zf,title:"System",icon:RS,navKind:"control",placeable:!0,order:qo.system,onOpen:()=>v(),get submenu(){const oe=[{title:"OpenStation Preferences",url:"",windowId:xt,onSelect:()=>v()}];return e.homeUrl&&oe.push({title:"View site",url:e.homeUrl}),oe.push({title:"Fullscreen",url:"",onSelect:hU},{title:"Keyboard shortcuts",url:"",windowId:hu,onSelect:()=>bU(_e=>{o.open(_e)})},{title:"Report a bug",url:"",windowId:Ns,onSelect:()=>A()}),!Ly()&&!x&&oe.push({title:Qe.title,url:"",onSelect:Qe.onOpen}),e.logoutUrl&&oe.push({title:"Log out",url:"",onSelect:()=>{window.location.assign(e.logoutUrl)}}),oe},isOpen:()=>K(ct.submenu??[])};S.appendSystemTile(ct),Ty().then(oe=>{x=oe})}const U="os-settings-layout",B=8e3;function z(w){const I=document.getElementById(w);return I&&!I.closest("[hidden]")?I:null}function _(w,I=performance.now()+B){const H=z(w);if(H){H.scrollIntoView({block:"start",behavior:"instant"});return}performance.now()<I&&requestAnimationFrame(()=>_(w,I))}function v(w={}){const I={extended:"features",effects:"windows"},H=w.tabId?I[w.tabId]:void 0;H&&(w={...w,tabId:H});const j=!!o.getById(xt);G.openById(xt,{source:"os-settings",...w.tabId?{params:{tab:w.tabId}}:{}}),w.tabId&&j&&window.wp?.os?.apps?.local(xt,"tab",{value:w.tabId})}function A(w=Ns,I){rr("desktop-mode-bug-report");const H={id:w,baseId:Ns,url:`#${Ns}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:j=>Dx(j),width:560,height:620,minWidth:420,minHeight:480,...I};I?o.openNew(H):o.open(H)}if(S){if(S.appendSystemTile(PS()),e.multisite){const w=vL(e.multisite,R);w&&S.appendSystemTile(w)}S.appendSystemTile({id:OS,title:b("Site assistant"),icon:MS,navKind:"control",placeable:!0,order:qo.assistant,onOpen:()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))}}),S.appendSystemTile({id:X2,title:"Mio",icon:O2,navKind:"control",placeable:!0,order:qo.mio,isOpen:()=>g.isEnabled(),onOpen:()=>{g.toggle()}}),S.appendSystemTile({id:DS,title:"Workspaces",icon:xS,navKind:"control",placeable:!0,order:qo.overview,isOpen:()=>o._overviewActive,onOpen:()=>{o._overviewActive?o.exitOverview():o.enterOverview()}})}const O=S?.getPrimary()??null;ne(ty(Array.isArray(e.nativeWindows)?e.nativeWindows:[],e.nativeWindowScriptData));const P=l1(e.session);function Z(w,I,H){const j=I||w;return j==="desktop-mode-dashboard"&&c.getOsSettingsSnapshot().stationHomeEnabled!==!0?!1:j===Ns?(A(w,H),!0):H?G.restoreById(w,j,H):G.openById(w)}const V=typeof e.soloWindow=="string"?e.soloWindow:"";V&&queueMicrotask(()=>{if(Z(V))return;const w=V.startsWith("os-game-")?V.slice(8):"";if(w){hg.launch(w).catch(I=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",I)});return}typeof console<"u"&&console.error(`[openstation] solo window "${V}" is not registered; nothing to paint.`)});const ge=d.api.isMobile()?u.trimSessionForMobile(e):e,Te=P&&!V?u1(o,ge,t,Z).catch(w=>{typeof console<"u"&&console.error("[openstation] session restore failed:",w)}):Promise.resolve(),Y=e.defaultWindow?.enabled!==!1,ae=e.defaultWindow?.url??"",be=typeof ae=="string"&&ae.startsWith("native:");let wt=Te;if(!V&&p1({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:P,defaultEnabled:Y,isNativeDefault:be})&&(wt=Te.then(()=>f1(o,e).catch(w=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",w)}))),e.landInOverview&&!V&&wt.then(()=>{o.enterOverview(),jm()}),!V&&$){const w=$;Te.then(()=>{const I=o.getActiveDesktopId();d.api.isMobile()||AA(w,I),W(w,I)})}const xe=_1(o,e);k1(xe);const ma=async w=>{try{const I=await fd(o,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:w})},{source:"desktop-mode/default-window"});if(!I.ok)throw await Wn(I);const H=await I.json();e.defaultWindow=H,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:H}))}catch(I){L(y.SHELL_ERROR,{scope:"default-window-save",error:I}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",I)}};if(o.onToggleStartupRequested=w=>{const I=e.defaultWindow,H=!!w.config.native,j=H?`native:${w.id}`:w.getCurrentUrl(),we=H?I?.url===j:Lt(I?.url??"")===Lt(j),Qe=!!I?.enabled&&we;ma(Qe?null:j)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!P&&be){const w=ae.slice(7);queueMicrotask(()=>{Z(w)})}const yB=w=>{S?.appendSystemTile(w)},dE=k2({layer:l});dE(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const Su=GT({osSettings:c});Su(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),ee(y.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",w=>{const I=w?.wallpapers;Array.isArray(I)&&Su(I)});const uE=jT();uE(Array.isArray(e.serverGames)?e.serverGames:[]);const fE=lL();fE(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const pE=iN();pE(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const hE=cN();hE(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const mE=fN();mE(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const gE=wN();gE(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const wE=XN();wE(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const yE=tO();yE(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),iO({manager:o,osSettings:c}),eI({osSettings:c}),U0({manager:o}),nO();{let w=!1;ee(y.WINDOW_LINK_GROUPS_CHANGED,"desktop-mode/window-link-visuals-sentinel",()=>{w||(w=!0,nw().then(I=>{I&&window.openStationWindowLinkVisuals?.start({manager:o,osSettings:c})}).catch(()=>{w=!1}))})}_N({manager:o,openUrl:w=>{if(w.windowId&&G.openById(w.windowId,{source:"related-entities",...w.params?{params:w.params}:{}})||!w.url||Be(w.url))return;const I=fe(w.url,e.adminUrl);o.open({id:I,baseId:I,url:w.url,title:w.label,icon:w.icon||"dashicons-admin-links"})}}),PN({manager:o}),VN({manager:o});const bE=rO();bE(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),dO()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),pO(),hO()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),wO()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),Sw(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),TO()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const fi=CN(o);EN(o),Je(()=>kN()),w0(),ee("os.shell.toast","desktop-mode/shell-toast",w=>{!w||typeof w.message!="string"||ue({message:w.message,type:typeof w.type=="string"?w.type:void 0,action:w.action,duration:w.duration})});const Iu=e,bB=Iu.recycleBinCount;wx(Number(bB)||0,typeof Iu.recycleBinCountUrl=="string"?Iu.recycleBinCountUrl:""),Ax({getRecycleBinCount:gx}),window.__openStationConnectionBridge=fi,ee(y.WINDOW_CLOSED,"desktop-mode/connection-cleanup",w=>{w?.windowId&&fi.onWindowClosed(w.windowId)}),ee(y.IFRAME_READY,"desktop-mode/connection-rearm",w=>{w?.windowId&&fi.onIframeReady(w.windowId)});const vB=UD(o),_B=w=>{if(S){S.applyDesktopIcons(w);return}ay(t,w,{openWindow:G.openById,manager:o,deriveWindowId:I=>fe(I,e.adminUrl)})},Au=()=>{S&&p2(S.getNav().desktop,S.getNavItems(),c.getOsSettingsSnapshot().dockPromotedPositions)},EB=c1({layoutDispatcher:S,desktopArea:t,config:e,applyMultisite:w=>{const I=e.multisite;e.multisite=w&&I?{...w,current:I.current,isNetworkAdmin:I.isNetworkAdmin}:w,ns(o)},syncNativeWindows:ne,syncServerWidgets:dE,syncServerWallpapers:Su,syncServerCommands:pE,syncServerSettingsTabs:hE,syncServerTitleBarButtons:mE,syncServerWindowActions:gE,syncServerUnfocusEffects:wE,syncServerWindowLinkRenderers:yE,syncServerDockRailRenderers:bE,syncServerGames:uE,syncServerDesktopThemes:fE,renderIcons:_B,refreshRootPlacements:w=>{Ue(0).then(I=>{qt(0,I.placements),FP(t,w)}).catch(()=>{})},syncShortcuts:Au,syncWindowSubmenus:()=>H0(o.getAll(),e)});document.addEventListener(Mm,()=>{S&&S.setLayout(S.getLayout());for(const w of o._stack)try{w.repaintWindowControls(),w.repaintThemedChrome()}catch(I){L(y.SHELL_ERROR,{scope:"desktop-theme-repaint",id:w.id,error:I})}}),c.subscribeOsSettings(w=>{if(!S)return;const I=S.getLayout(),H=S.getDockPlacement();S.setDockPlacement(w.dockPlacement),S.setLayout(w.desktopLayout),pi.dock=S.getPrimary(),pi.sideDock=S.getSide(),pi.desktopLayout=w.desktopLayout,pi.dockPlacement=S.getDockPlacement(),I===w.desktopLayout&&H===w.dockPlacement&&S.refresh(),Au(),zb(w.desktopLayout)}),h2(Au),zb(c.getOsSettingsSnapshot().desktopLayout);const pi=iW({manager:o,dock:O,layoutDispatcher:S,osSettings:c,iconsApi:Pl,filesApi:Ke,saveSession:xe,widgetLayer:l,registerWindow:vB,openWindowById:G.openById,openNewWindowById:G.openNewById,loadWindowScriptById:G.loadScriptById,prewarmWindowById:G.prewarmById,placeSystemTile:yB,setDefaultWindow:ma,refreshMenu:EB,openOsSettings:v,aiAssistant:h,dragBridge:m,dragManager:E,connect:fi.connect,getConnection:fi.getConnection,mio:g,mode:d.api,workspaces:lU($??{manager:o,getNavItems:()=>S?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:w=>fe(w,e.adminUrl),openNative:G.openById,refreshLayout:()=>S?.refresh()},D,q,X,T),wallpaperSuspend:{suspend:w=>r?.suspend(w),resume:w=>r?.resume(w),isSuspended:()=>r?.isSuspended()??!1},config:e});rW(pi);let Wo=null,vE=0;const kB=KU({manager:o,adminUrl:e.adminUrl,openNative:Z}),_E=()=>{const w=++vE;if(!d.api.isMobile()){Wo&&(Wo.unmount(),Wo=null);return}if(Wo||!N)return;const I=N;VU(e.mobileBundleUrl??"").then(H=>{w!==vE||!d.api.isMobile()||Wo||(Wo=H.mount({manager:o,shell:I,area:t,mode:d.api,getNav:()=>S?.getNav()??null,openNavItem:kB,getBadge:j=>Math.max(j.menu?.badge??0,Pl.getBadge(j.id)),getPinnedTabIds:()=>{const j=c.getOsSettingsSnapshot().mobileTabs;return Array.isArray(j)&&j.length>0?j:e.mode?.tabBar??[]},subscribeNav:j=>{const we=c.subscribeOsSettings(j);return document.addEventListener("os-layout-changed",j),document.addEventListener("os-registry-changed",j),()=>{we(),document.removeEventListener("os-layout-changed",j),document.removeEventListener("os-registry-changed",j)}},wallpaper:{suspend:j=>r?.suspend(j),resume:j=>r?.resume(j)},openExternal:j=>{window.open(j,"_blank","noopener")},adminUrl:e.adminUrl,renderIcon:(j,we)=>ln(j,we),getArt:j=>Pl.getArt(j.id)||O?.getArt(j.id)||"",subscribeArt:j=>Se.subscribe("os/art-changed",()=>j())}))}).catch(H=>{typeof console<"u"&&console.error("[openstation] the phone layer failed to load:",H)})};_E(),d.api.subscribe(_E),d.api.subscribe(w=>{if(w.mode!=="mobile"&&w.previous!=="mobile"||(S?.refresh(),!$))return;const I=o.getActiveDesktopId();W($,I),F($,I)}),Je(()=>iB(E)),Je(()=>aB()),VT(),qS(),e.gamesEnabled!==!1&&tN({currentUserId:Number(e.currentUserId)||0}),Je(()=>WM()),Je(()=>$M()),Je(()=>ZM({currentUserId:Number(e.currentUserId)||0})),g2({bundleUrl:e.notesBundleUrl??"",hasNotes:!!e.hasNotes,host:t,config:e,onError:w=>{ue(w)}}),pW({openUrl:({id:w,url:I,title:H,icon:j})=>(Be(I)||o.open({id:w,baseId:w,url:I,title:H,icon:j}),!0),openNativeWindow:w=>G.openById(w),deriveWindowId:w=>fe(w,e.adminUrl)}),qb(e.userFileAssociations??{});const SB=v2({update:e.coreUpdate,openUrl:({url:w,title:I})=>{Be(w)||o.open({id:"update-core",baseId:"update-core",url:w,title:I,icon:"dashicons-update"})}}),EE=({url:w,title:I})=>{if(Be(w))return;const H=fe(w,e.adminUrl);o.open({id:H,baseId:H,url:w,title:I,icon:"dashicons-info"})};if(__({notices:e.coreNotices,openUrl:EE}),__({notices:e.pluginNotices,openUrl:EE,keyPrefix:"plugin-notice"}),SU({config:e}),MU({config:e,windowManager:o,isMobile:()=>d.api.isMobile(),updateNoticeShown:SB,openPalette:()=>Or("desktop-mode-ai-assistant"),openLayoutSettings:()=>{const w=!!o.getById(xt);return v({tabId:"appearance"}),_(U),{windowId:xt,wasAlreadyOpen:w}},findLayoutTarget:()=>z(U)??document.querySelector(`.os-dock__item[data-system-id="${Zf}"]`),closeWindow:w=>o.getById(w)?.close(),closePalette:()=>{const w=rb().find(I=>I.id==="desktop-mode-ai-assistant");w?.isOpen()&&(w.close(),vo(w.id,!1))},mio:!0,refreshDesktopIcons:WU,findAssistant:()=>document.querySelector("#desktop-mode-ai-assistant:not([hidden]) .os-ai__panel"),openFallbackWindow:()=>{const w=`${e.adminUrl}edit.php`,I=fe(w,e.adminUrl);o.open({id:I,baseId:I,url:w,title:b("Posts"),icon:"dashicons-admin-post"})}}),DU({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){iv({baseUrl:e.filesUrl,nonce:e.restNonce});const w=document.getElementById("os-area");if(w){const I=Hv(w,0),H=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},j=setTimeout(H,2e3);I.hydrated.then(()=>{clearTimeout(j),H()})}}Je(()=>cB()),Je(()=>uB()),Je(()=>fM()),L(y.COMPONENTS_REGISTERED,{tags:[...Mr]}),rM(),iR(e,ue,async()=>{await xe.flush(),window.location.reload()});const kE=()=>{$E(e.shellOverlaysBundleUrl??""),WE(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(kE,{timeout:1500}):window.setTimeout(kE,0),L(y.INIT,{config:e}),_u=!0;const IB=cE.splice(0);for(const w of IB)try{w()}catch(I){L(y.SHELL_ERROR,{scope:"when-ready-cb",error:I}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",I)}if(c.apply(),!d.api.isMobile())l?.hydrate();else{const w=d.api.subscribe(I=>{I.mode!=="mobile"&&(w(),l?.hydrate())})}window.addEventListener("pagehide",()=>{r?.teardownActive(),l?.disposeAll()}),S1(),JM(o,e);const SE=(w,I=!0)=>{const H=Ke.store.getState().placementsByFolder.get(0)??[],j=w(H),we=he(t),Qe=Math.max(1,Math.floor((we.height-16)/110)),ct=new Set;let oe=0;for(const _e of j){const Ee=kn(16+Math.floor(oe/Qe)*96,16+oe%Qe*110,ct,we);ct.add(`${Ee.col},${Ee.row}`),oe++,!(_e.x===Ee.x&&_e.y===Ee.y)&&(Ke.store.upsertPlacement({..._e,x:Ee.x,y:Ee.y,sortOrder:oe}),!(!I||Xs(_e))&&bn(_e.id,{x:Ee.x,y:Ee.y,sortOrder:oe}).catch(et=>{console.error("[openstation] relayout persist failed",et)}))}},IE=w=>I=>{const H=I.slice();switch(w){case"name-asc":H.sort((j,we)=>j.file.title.localeCompare(we.file.title));break;case"name-desc":H.sort((j,we)=>we.file.title.localeCompare(j.file.title));break;case"date-asc":H.sort((j,we)=>j.updatedAtMs-we.updatedAtMs);break;case"date-desc":H.sort((j,we)=>we.updatedAtMs-j.updatedAtMs);break}return H},Cu="desktop-mode:root-sort-mode",AB=w=>w==="name-asc"||w==="name-desc"||w==="date-asc"||w==="date-desc";let ga=(()=>{try{const w=window.localStorage.getItem(Cu);return AB(w)?w:null}catch{return null}})();const AE=w=>{ga=w;try{w?window.localStorage.setItem(Cu,w):window.localStorage.removeItem(Cu)}catch{}};ee("os.files.tile-manually-placed","desktop-mode/root-sort-clear",w=>{w?.folderId===0&&AE(null)});{let w=he(t);const I=()=>{if(!ga)return;const H=he(t);H.width===w.width&&H.height===w.height||(w=H,SE(IE(ga),!1))};typeof ResizeObserver<"u"&&new ResizeObserver(I).observe(t),Jo(I)}let CE=!1;t.addEventListener("pointerdown",w=>{w.isPrimary&&(CE=w.target===t)}),t.addEventListener("click",w=>{c.state.showDesktopOnWallpaperClick&&w.target===t&&CE&&(t.classList.contains("os-area--overview")||iE()||E.recentlyEndedDrag()||LM()||o.toggleShowDesktop())}),t.addEventListener("contextmenu",w=>{if(w.target!==t)return;w.preventDefault();const I=w.clientX,H=w.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(iE()){ai();return}const j={x:I,y:H},we=()=>{const oe=t.getBoundingClientRect(),_e=Math.max(0,j.x-oe.left),Ee=Math.max(0,j.y-oe.top),et=Ov(Ke.store.getState().placementsByFolder.get(0)??[]);return kn(_e,Ee,et,he(t))},Qe=(oe,_e)=>{W$({title:oe,description:_e,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:Ee,url:et})=>{const hi=we(),CB=await Bs({type:"link",ref:et,parentId:0,x:hi.x,y:hi.y,meta:Ee?{name:Ee}:void 0});Ke.store.upsertPlacement(CB)}})},ct=mB({createFolder:()=>{Hd({onSubmit:async oe=>{const _e=await Td({name:oe}),Ee=we(),et=await Bs({type:"folder",ref:String(_e.id),parentId:0,x:Ee.x,y:Ee.y});Ke.store.upsertFolder(_e),Ke.store.upsertPlacement(et)}})},createUrl:()=>Qe("New URL","Opens the URL in a new browser tab."),addWidget:()=>l?.openPicker(),toggleShowDesktop:()=>o.toggleShowDesktop(),openOsSettings:()=>v(),sortIcons:oe=>{AE(oe),SE(IE(oe))},currentSortMode:ga,includeShowDesktop:!c.state.showDesktopOnWallpaperClick,position:{x:I,y:H},labels:{createFolder:"New folder",showDesktop:"Show desktop",osSettings:"OpenStation Preferences",sortHeading:"Sort by",sortNameAsc:"Name (A → Z)",sortNameDesc:"Name (Z → A)",sortDateAsc:"Date (oldest first)",sortDateDesc:"Date (newest first)",newUrl:"New URL",addWidget:"Add widget"},serverItems:e.serverWallpaperMenuItems??[]});pB(document.body,{x:I,y:H},ct)})()}),wB({bundleUrl:e.fileDropBundleUrl??"",boot:{config:e.dropConfig,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.desktopStorage}}),document.dispatchEvent(new CustomEvent("os-init",{detail:{config:e,restored:P}}))}return N2(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",lE):lE(),wa.clampGeometryToViewport=qh,Object.defineProperty(wa,Symbol.toStringTag,{value:"Module"}),wa}({});
72