var openStation=function(oa){"use strict";var sa=typeof document<"u"?document.currentScript:null;function _t(){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 pt(e,t,n,o){_t().addFilter(e,t,n,o)}function ee(e,t,n,o){_t().addAction(e,t,n,o)}function jt(e,t){return _t().removeAction(e,t)}function FE(e,t){return _t().removeFilter(e,t)}function J(e,t,...n){return _t().applyFilters(e,t,...n)}function A(e,...t){_t().doAction(e,...t)}function ou(e){return _t().didAction(e)}function HE(){return _t()}const v={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 GE=0;function su(e){if(ou(v.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++GE}`;ee(v.INIT,t,e)}function zE(){return ou(v.INIT)>0}const ia="data-os-mode";function iu(e,t){e.getAttribute(ia)!==t&&e.setAttribute(ia,t)}function Vt(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(ia)==="mobile"}const ra="data-os-display";function ru(e,t){e.getAttribute(ra)!==t&&e.setAttribute(ra,t)}function jE(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(ra)==="standalone"}const VE=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"],aa=[];function KE(e){if(!e.pathname.endsWith("/admin.php")||!e.searchParams.get("page"))return aa;const t=e.searchParams.get("action");return t==="edit"&&e.searchParams.get("id")?["id"]:t==="new"?["action"]:aa}function au(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=[...VE,...KE(n)];for(const c of a){const d=n.searchParams.get(c);d&&r.set(c,d)}const l=r.toString();return au(l?`${i}?${l}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),au(o)}function qE(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function YE(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 cu(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 In(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 lu(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 An=null;function oi(){return!!window.openStationWindowSystem}function du(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(oi()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){oi()?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 XE(){return window.openStationConfig?.windowSystemBundleUrl??""}function ZE(e){!e||oi()||An||(An=du(e).catch(t=>{An=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function JE(e){if(oi())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 An||(An=du(e)),await An,window.openStationWindowSystem}let Cn=null;function Lo(){return!!window.openStationShellOverlays}function uu(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(Lo()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){Lo()?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 QE(e){!e||Lo()||Cn||(Cn=uu(e).catch(t=>{Cn=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function ca(e){return Lo()||!e?Promise.resolve():(Cn||(Cn=uu(e)),Cn)}function la(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function si(e,t){const n=la();if(Lo()||!n){t();return}ca(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const fu="desktop-mode";function da(){return window.wp?.i18n}function b(e,t=fu){return da()?.__(e,t)??e}function Kt(e,t,n,o=fu){return da()?._n(e,t,n,o)??(n===1?e:t)}function le(e,...t){const n=da()?.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 e_=900,t_=260,ua="os-desktop-name-hud";let Je=null,St=null;function n_(e,t){t.trim()&&(St!==null&&window.clearTimeout(St),Je||(Je=document.createElement("div"),Je.className=ua,Je.setAttribute("role","status")),Je.textContent=t,Je.classList.remove(`${ua}--out`),e.appendChild(Je),St=window.setTimeout(()=>{Je?.classList.add(`${ua}--out`),St=window.setTimeout(()=>{Je?.remove(),St=null},t_)},e_))}function o_(){St!==null&&(window.clearTimeout(St),St=null),Je?.remove(),Je=null}function s_(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 i_(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 r_(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{const g=p%s,h=Math.floor(p/s),m=t.left+r+g*(c+a),_=t.top+n+r+h*(d+a)+l,I=f.element.offsetWidth,O=f.element.offsetHeight,$=Math.min(c/I,u/O),S=I*$,R=O*$;return{win:f,x:m+(c-S)/2,y:_+(u-R)/2,scale:$}})}const a_=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],pu=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],c_=[...a_,...pu],hu={close:{a:'fill="currentColor"',b:''},check:{a:'fill="currentColor"',b:''},"chevron-right":{a:'fill="currentColor"',b:''},"arrow-up-right":{a:'fill="currentColor"',b:''},plus:{a:'fill="currentColor"',b:''},search:{a:'fill="currentColor"',b:''},pin:{a:'fill="currentColor"',b:''},trash:{a:'fill="currentColor"',b:''},download:{a:'fill="currentColor"',b:''},settings:{a:'fill="currentColor"',b:''},info:{a:'fill="currentColor"',b:''},bell:{a:'fill="currentColor"',b:''},more:{a:'fill="currentColor"',b:''},maximize:{a:'fill="currentColor"',b:''},edit:{a:'fill="currentColor"',b:''},color:{a:'fill="currentColor"',b:''},wallpaper:{a:'fill="currentColor"',b:''},warning:{a:'fill="currentColor"',b:''},minimize:{a:'fill="currentColor"',b:''},window:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},windows:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},dock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},spaces:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},copilot:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},snap:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},command:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},apps:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},widgets:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},user:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''},lock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:''}};function mu(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function gu(e){return Object.prototype.hasOwnProperty.call(hu,e)?hu[e]:null}function l_(e){return gu(e)!==null}function qt(e,t={}){const n=gu(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="${mu(s)}"`),i?a.push('role="img"',`aria-label="${mu(i)}"`):a.push('aria-hidden="true"','focusable="false"');const l=r?`${n.b}`:n.b;return`${l}`}function wu(e,t={}){const n=qt(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 d_(e,t={}){const n=qt(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const u_=Object.freeze({svg:qt,node:wu,dataUri:d_,names:Object.freeze([...c_]),ours:Object.freeze([...pu]),has:l_}),f_=120,p_=56;function yu(e){return f_+(e?.querySelector(".os-overview-top-bar__header")?p_:0)}const h_="openstation";function Ln(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")===h_}const vu=["target","intent","openstation_overview","openstation_hop","openstation_hop_from"];function m_(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!Ln(n)||!vu.some(o=>n.searchParams.has(o))?null:(vu.forEach(o=>n.searchParams.delete(o)),n.href)}const bu="__openStationSharedStores";function g_(){const e=window;let t=e[bu];return t||(t=new Map,e[bu]=t),t}function ae(e,t){const n=g_();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 w_="os_tab",y_="os_person_view";function v_(e){return e.searchParams.has(y_)}const To=ae("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function b_(e){To.state.deps=e}function ht(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=To.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>pa(e.id)}function pa(e){const t=To.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function Tn(e){const{deps:t,remaps:n}=To.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 Me(e,t={}){const{deps:n,remaps:o}=To.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(u){console.warn(`[openstation] URL remap onMatch hook threw for "${r.id}":`,u)}let a;const l=s.searchParams.get(w_);if(r.params)try{a=r.params(e,s)??void 0}catch(u){console.warn(`[openstation] URL remap params hook threw for "${r.id}":`,u)}l&&/^[a-z0-9_-]+$/.test(l)&&(a={...a??{},tab:l});const c=t.newInstance&&n.openNewById?n.openNewById:n.openById;if(a?c(r.nativeWindowId,{params:a}):c(r.nativeWindowId))return!0}return!1}const Eu="X-WP-Nonce";function _u(e,t){const n=E_();if(!n)return t;const o=__(e);if(!o||!S_(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Eu)?t:(i.set(Eu,n),{...t??{},headers:i})}function E_(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function __(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 S_(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=_u(e,t);return fetch(e,s)}class No 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 Su(e){return e instanceof No}function ku(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 mt(e,t,n=""){return new No(n,{status:e,...ku(t)})}async function Nn(e,t=""){let n=null;try{n=await e.json()}catch{n=null}return mt(e.status,n,t)}function Iu(e,t){return new No(t,{status:e,code:"openstation_bad_response"})}function k_(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}=ku(c);throw mt(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 Iu(a.status,`${t} ${a.status} returned non-JSON body — ${d.message}. First 120 chars: ${u}`)}throw Iu(a.status,`${t} ${a.status}: empty or unparseable body.`)}return c}}const Oo=ae("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),gt=Oo.state.registry,ha=Oo.state.listeners,I_=/^[a-z0-9_-]+$/;function Au(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!I_.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).`);gt.set(e.id,e),ii()}function A_(e){gt.delete(e)&&ii()}function C_(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(gt.entries()))o.owner===e&&(gt.delete(n),t++);return t>0&&ii(),t}function L_(e){return gt.get(e)}function T_(){return Array.from(gt.values())}function N_(e){return ha.add(e),()=>{ha.delete(e)}}function O_(e){Oo.state.activeId!==e&&(Oo.state.activeId=e,ii())}function ma(){return gt.get(Oo.state.activeId)??gt.get("default")??gt.values().next().value}function ii(){const e=Array.from(ha);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function Yt(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 D_ 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 Oe(e,t,n){if(t.length!==0)throw new D_(e,t,n)}function Cu(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const kt=[[0,0],[100,0],[100,100],[0,100]],R_=48,x_=80,ga=6,wa=8,Lu=4,Tu=3,Nu=64,ya=105,It=2;function Ou(e){return`${Math.round(e*1e3)/1e3}%`}function At(e){return e.slice().reverse()}function Do(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function M_(e,t,n,o){const s=[];for(let i=0;i{n.push(`${Ou(s[0])} ${Ou(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 Du(e){return it(kt,[At(M_(50,50,e,R_))])}function Ru(e){return it(kt,[At(Do(50-e,-It,50+e,100+It))])}function xu(e){const t=100/ga,n=[];for(let o=0;o`${ai(s)} ${ai(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",Fu[e%Fu.length]),o.setAttribute("stroke",K_),o.setAttribute("stroke-width",String(q_)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function J_(){const e=`os-iris-${++Y_}`,t=document.createElementNS(Dn,"svg");t.setAttribute("viewBox",`0 0 ${ba} ${ba}`),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(Dn,"defs"),o=document.createElementNS(Dn,"mask");o.setAttribute("id",e);const s=document.createElementNS(Dn,"g"),i=document.createElementNS(Dn,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let l=0;lr.map(({el:c,index:d})=>{const u=X_(d),f=ai(u.x*Bu),p=ai(u.y*Bu);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 Ro="none",Q_=460,eS="cubic-bezier( 0.33, 0, 0.2, 1 )",Gu=80,zu=4e3,tS=70,nS=600,ju=ae("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),ci=ju.state.registry,oS=ju.state.listeners,Vu=/^[a-z0-9_/-]+$/;function Ku(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function sS(e){return typeof e!="number"||!Number.isFinite(e)?Q_:Math.min(zu,Math.max(Gu,e))}const _a=0;function qu(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?_a:Math.min(zu,Math.max(Gu,e))}function Rn(e){return typeof e!="number"||!Number.isFinite(e)?tS:Math.min(nS,Math.max(0,e))}function Yu(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 Xu(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=Ku(e.from),r=Ku(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 iS(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function Be(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)"):Vu.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Ro&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Vu} — 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(...Xu(r,`layers[ ${a} ]`))})):t.push(...Xu(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):iS(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)"))}Oe("WindowReveal",t,e);const n=e.id.trim().toLowerCase();ci.set(n,{...e,id:n}),Qu()}function rS(e){ci.delete(e.toLowerCase())&&Qu()}function Zu(){const e=Array.from(ci.values()),t=J(v.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 Ju(e){return Zu().find(t=>t.id===e)}function aS(e){return ci.has(e)}function Qu(){const e=Array.from(oS);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Be({id:"sweep",label:b("Sweep"),description:b("A straight edge travels across the window, uncovering the page behind it."),...j_(),duration:420}),Be({id:"iris",label:b("Iris"),description:b("The page opens out from the centre of the window, like a camera shutter."),...W_(),duration:520}),Be({id:"curtain",label:b("Curtain"),description:b("Two panels part from the middle of the window and slide off the sides."),...P_(),duration:480}),Be({id:"blinds",label:b("Blinds"),description:b("Six horizontal slats retract at once, letting the page through between them."),...$_(),duration:560}),Be({id:"diagonal",label:b("Diagonal"),description:b("A slanted edge sweeps off the trailing corner of the window."),...V_(),duration:460}),Be({id:"rise",label:b("Rise"),description:b("The page rises into the window from the bottom edge upward."),...z_(),duration:440}),Be({id:"shutter",label:b("Shutter"),description:b("Two panels part from the middle of the window and slide off the top and bottom."),...U_(),duration:480}),Be({id:"slats",label:b("Slats"),description:b("Eight vertical slats retract at once, letting the page through between them."),...B_(),duration:560}),Be({id:"diamond",label:b("Diamond"),description:b("The page opens out from the centre of the window through a growing rhombus."),...F_(),duration:520}),Be({id:"mosaic",label:b("Mosaic"),description:b("The page arrives as a grid of tiles, each opening out from its own centre."),...H_(),duration:600}),Be({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:J_,duration:720,edgeLag:0}),Be({id:"radar",label:b("Radar"),description:b("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...G_(),duration:760});const ef="desktop-mode-os-settings",Ct="desktop-mode-os-settings",tf="custom-gradient",xo="custom-image",Sa="galaxy",nf="custom",of=[{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 li(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return of;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:of}function ka(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:Sa}const Ia=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],Aa=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],di=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],ui=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"}],cS=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],lS=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],xn={wallpaper:Sa,accent:"pulse",customAccent:"#f252fc",dockSize:"default",windowRadius:"round",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:{}},sf={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},rf=["dockRailRenderer","windowReveal","accent"],af={windowRevealDuration:{min:80,max:4e3}},dS=/^[a-z0-9_-]+$/;[...Object.keys(sf),...rf,...Object.keys(af)];function cf(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries(sf)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of rf){const i=t[s];typeof i=="string"&&dS.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(af)){const r=t[s];typeof r=="number"&&Number.isFinite(r)&&(o[s]=Math.min(i.max,Math.max(i.min,Math.round(r))))}return{...n,...o}}function uS(e){const t=cf(e);return typeof t.dockRailRenderer=="string"&&L_(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==Ro&&!aS(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!li().some(n=>n.id===t.accent)&&delete t.accent,t}const fS=/^[a-z0-9_-]+$/,lf=128;function pS(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function Ca(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!fS.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>=lf)break;c===""||!pS(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>=lf)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:cf(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload",cssDeferred:t.cssDeferred===!0}}function hS(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=Ca(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const Lt=ae("desktop-mode/desktop-themes",hS);function Mn(){return Lt}function mS(){return Lt.getState().themes.slice()}function La(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return Lt.getState().themes.find(n=>n.slug===t||n.id===e)??null}function Ta(){return Lt.getState().activeId}function gS(e){const t=Ca(e);if(!t)return null;const n=Lt.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)),Lt.setState({themes:n}),t}let Mo=null;function df(){if(Mo)return Mo;const e=window.openStationConfig?.desktopThemesUrl;return e?(Mo=Ae(e,{method:"GET",credentials:"same-origin"},{source:"desktop-mode/desktop-themes"}).then(async t=>{if(!t.ok)throw await Nn(t);return t.json()}).then(t=>{for(const n of t?.themes??[])gS(n)}).catch(()=>{Mo=null}),Mo):Promise.resolve()}function wS(e){const t=[];for(const n of e){const o=Ca(n);o&&t.push(o)}Lt.setState({themes:t})}function yS(e){return Lt.subscribe(e)}function fi(e){const t=Mn().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=J(v.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function Na(e){const t=Mn().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=J(v.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?vS(o):null}function vS(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 Xt={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"},bS={"desktop-mode-os-settings":Xt.OS_SETTINGS,"desktop-mode-recycle-bin":Xt.RECYCLE_BIN,"desktop-mode-bug-report":Xt.BUG_REPORT,"os-exit":Xt.EXIT_OPENSTATION,"os-pwa-install":Xt.PWA_INSTALL};function pi(e){if(typeof e!="string"||e==="")return"";const t=bS[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function ES(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Xt.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Xt?n:""}const hi=ae("desktop-mode/window-channels",()=>({parentSubs:new Map,nativeSubs:new Map,readyWindows:new Set,loadingWindows:new Set,pendingSends:new Map}));function Oa(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 uf(e,t,n,o){const s={channel:n,windowId:t},i=Oa(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=Oa(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 _S(e,t,n){const o=Oa(hi.state.parentSubs,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function SS(e,t,n){uf(hi.state.parentSubs,e,t,n)}function kS(e,t,n){uf(hi.state.nativeSubs,e,t,n)}function IS(e){const{readyWindows:t,loadingWindows:n,pendingSends:o}=hi.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)&&(A(v.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const AS="os.activity.";function Da(e){return AS+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let CS=0;const _e={publish(e,t){A(Da(e),t)},subscribe(e,t){const n=`os/activity-sub/${++CS}`,o=Da(e);ee(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,jt(o,n))}},filter(e,t,...n){return J(Da(e),t,...n)}},LS=4e3,TS=200,NS=1200;function ue(e){const t=_e.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return si(()=>!n,()=>{o=RS(t)}),()=>{n=!0,o&&o()}}const OS={success:"positive",warning:"warning",error:"critical","shell-error":"critical"};function DS(e){return e?window.openStationConfig?.toastTypes?.find(o=>o.id===e)?.tone??OS[e]??null:null}function RS(e){const t=PS(),n=document.createElement("os-toast");n.textContent=e.message;const o=DS(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??LS,a=0;const l=()=>{i!==null&&(window.clearTimeout(i),i=null)},c=()=>{s||(s=!0,l(),WS(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),MS()},TS))},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,NS),d()}),xS(n),d(),_e.publish("os/toast-shown",{...e}),c}let mi=null,Wo=0;function ff(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(mi=t))}function xS(e){Wo===0&&document.addEventListener("focusin",ff,!0),Wo+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(mi=n)}function MS(){Wo=Math.max(0,Wo-1),Wo===0&&document.removeEventListener("focusin",ff,!0)}function WS(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||mi?.isConnected===!0&&mi.focus()}function PS(){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 $S="http://localhost/";function rt(e,t){const n=typeof window<"u"&&window.location?window.location.href:$S,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 US="os-site-assistant",BS="os-overview",pf="os-system",Po={assistant:5,mio:10,overview:20,system:30,exit:35},FS=`data:image/svg+xml;base64,${btoa('')}`,HS=`data:image/svg+xml;base64,${btoa('')}`,GS=`data:image/svg+xml;base64,${btoa('')}`,zS="os-exit";function jS(){return{id:zS,title:b("Exit OpenStation"),navKind:"control",locked:!0,order:Po.exit,icon:"dashicons-exit",onOpen:()=>{VS()}}}async function VS(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Ra(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{}Ra(o)}function Ra(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const hf=800;function KS(e,t=hf){window.setTimeout(()=>{if(e){Ra(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const qS="desktop_mode_nonces",YS="desktop-mode/v1",XS=3e4,ZS=3,Wn=ae("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function mf(){return window.wp?.os?.config??{}}function JS(){const e=mf().restUrl;return e?rt(e,YS):null}function QS(){Wn.state.negativeConfirms=0}async function ek(){const e=Wn.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=ZS)return;const t=JS();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt{const n=t[1];if(n){if(n[qS]!==void 0){QS();return}ek()}})}const ok=0,xa=40,gf=250,sk=120,ik=250,$o="os-window__loading",gi="os-window__loading--visible",wi=ae("desktop-mode/window-reveal-active",()=>({id:Ro,duration:_a}));function wf(e){wi.state.id=typeof e=="string"&&e!==""?e:Ro}function rk(){const e=wi.state.id;return!e||e===Ro?null:Ju(e)??null}function yf(e){wi.state.duration=qu(e)}function ak(){return wi.state.duration}function ck({osSettings:e}){const t=e.getOsSettingsSnapshot();wf(t.windowReveal),yf(t.windowRevealDuration),e.subscribeOsSettings(n=>{wf(n.windowReveal),yf(n.windowRevealDuration)})}const Pn="os-window__reveal",Uo="os-window__reveal--edge",lk="os-window__reveal--custom",Zt="os-window__body--revealing",Ma="data-os-reveal",Wa="data-os-reveal-layer",Tt=new WeakMap,vf=ae("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function bf(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const dk="--os-window-reveal-duration",uk="--os-window-reveal-edge-thickness";function Ef(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 fk(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return qu(Ef(window.getComputedStyle(e).getPropertyValue(dk)))}catch{return 0}}function pk(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function hk(e,t){const n=pk(e,uk);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return Rn(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return Rn(t*Number(s[1]));const i=Ef(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?Rn(i):null}function _f(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 mk(e,t){const n=sS(t.duration),o=ak(),s=o!==_a?o:fk(e)||n,i=hk(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=Rn(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:Rn(r*s/n)}}function Sf(e){return e.querySelector(":scope .os-window__body")}function gk(e){return e.querySelector(`:scope .${Pn}:not( .${Uo} )`)}function wk(e){return e.querySelector(`:scope .${Uo}`)}function kf(e){return Array.from(e.querySelectorAll(`:scope .${Pn}:not( .${Uo} )`))}function If(e){return Array.from(e.querySelectorAll(`:scope .${Uo}`))}function Pa(e){return Array.from(e.querySelectorAll(`:scope .${Pn}`))}function Af(e,t,n,o){const s=document.createElement("div");s.className=o?`${Pn} ${Uo}`:Pn;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(Ma,e.id),s.setAttribute(Wa,String(n)),s.style.clipPath=t.from,s}function yk(){const e=rk();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(Pn),s.classList.add(lk),s.setAttribute("aria-hidden","true"),s.setAttribute(Ma,e.id),s.setAttribute(Wa,"0"),vf.set(s,o.play),[s]}const t=Yu(e);if(t.length===0)return[];const n=[];return Rn(e.edgeLag)>0&&t.forEach((o,s)=>n.push(Af(e,o,s,!0))),t.forEach((o,s)=>n.push(Af(e,o,s,!1))),n}function vk(e){const t=Sf(e);if(t){t.classList.remove(Zt);for(const n of Pa(t))Tt.get(n)?.cancel(),Tt.delete(n),n.remove();for(const n of yk())t.appendChild(n)}}function Cf(e){const t=Sf(e);if(!t)return;const n=gk(t);if(!n)return;let o;try{o=Ju(n.getAttribute(Ma)??"")}catch(S){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",S)}if(!o){Pa(t).forEach(S=>S.remove());return}const i=!!t.querySelector(`:scope .${$o}`)?.classList.contains(gi)?gf:0,{duration:r,edgeLag:a}=mk(t,o),l=o.easing??eS,c=vf.get(n);if(c){t.classList.add(Zt);const S=()=>{Tt.delete(n),n.remove(),t.classList.remove(Zt)};if(bf()||typeof n.animate!="function"){window.setTimeout(S,i);return}let R=[];try{R=c({duration:r,easing:l,delay:i})}catch(W){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,W)}if(R.length===0){S();return}R[0].addEventListener("finish",S),R[0].addEventListener("cancel",()=>{Tt.delete(n),t.classList.remove(Zt)}),Tt.set(n,R[0]);return}const d=wk(t);d&&(a<=0||_f(d))&&If(t).forEach(S=>S.remove()),_f(n)&&kf(t).forEach(S=>S.remove());const u=Pa(t);if(u.length===0)return;t.classList.add(Zt);const f=()=>{for(const S of u)Tt.delete(S),S.remove();t.classList.remove(Zt)};if(bf()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,g=Yu(o),h=(S,R)=>{const W=g[Number(S.getAttribute(Wa))];if(!W)return S.remove(),null;S.style.willChange="clip-path";let U;try{U=S.animate([{clipPath:W.from},{clipPath:W.to}],{duration:R,easing:p,delay:i,fill:"both"})}catch(F){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,F),S.remove(),null}return Tt.set(S,U),U},m=kf(t).map(S=>h(S,r)).filter(S=>S!==null),_=If(t).map(S=>h(S,r+a)).filter(S=>S!==null),I=m[0]??null,O=_[0]??null;if(!I&&!O){f();return}(O??I)?.addEventListener("finish",f);const $=()=>{for(const S of u)Tt.delete(S);t.classList.remove(Zt)};I?.addEventListener("cancel",$),O?.addEventListener("cancel",$)}const bk="os-window-tab-change";function Lf(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function Tf(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function Nf(e,t){return`${e.id||"os-window"}-tab-${Tf(t)}`}function Of(e,t){return`${e.id||"os-window"}-panel-${Tf(t)}`}function Ek(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 _k(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 Sk(e){const t=Lf(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 Df(e){const t=new Map;for(const n of Lf(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function Rf(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 kk(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of Df(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 Rf(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}Sk(n),Ek(n),e.dispatchEvent(new CustomEvent(bk,{bubbles:!0,detail:{value:t}}))}}function Ik(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=Df(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=Nf(e,d.value),u.setAttribute("aria-controls",Of(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();_k(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of Rf(e)){const u=d.getAttribute("for");u&&(d.id=Of(e,u),a?d.setAttribute("aria-labelledby",Nf(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&&kk(e,c)}const Bo="os-window__body--loading",$a="os-window__body--loading-out",Ua="data-os-loading-at",xf="data-os-loading-cycle";function yi(e){return e.getAttribute(xf)??"0"}function Ak(e){e.setAttribute(Ua,String(Date.now())),e.setAttribute(xf,String(Number(yi(e))+1))}function Ck(e,t){const n=Number(e.getAttribute(Ua)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=sk-o;if(s<=0){t.classList.add(gi);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(Bo)&&t.classList.add(gi)},s)}const Lk=Symbol.for("desktop-mode/window-config");function Tk(e){return e[Lk]}const Mf=window.location.origin;function Nk(e){const t=new URL(e,Mf);return t.origin!==Mf||Ln(t)?null:(t.searchParams.set("openstation_chromeless","1"),t.toString())}function Ba(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function Wf(){const e=document.createElement("div");e.className=$o,e.setAttribute("role","status"),e.setAttribute("aria-live","polite");const t=document.createElement("os-spinner");return t.setAttribute("preset","classic"),t.setAttribute("size","clamp(96px, 14vw, 192px)"),t.setAttribute("label",b("Loading window content")),e.appendChild(t),e}function Ok(e){let t=Wf();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=J(v.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($o)&&t.classList.add($o),t}function Pf(e){e.querySelector(":scope .os-window__loading")?.remove()}function $f(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=Tk(e),s=o?Ok(o):Wf();t.appendChild(s),Ck(t,s)}const Dk=8,Uf=Object.freeze({top:0,right:0,bottom:0,left:0});function Bf(e,t,n,o){return{left:e,top:t,width:n,height:o,right:e+n,bottom:t+o}}function Rk(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]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 Wk(e,t){return e.top===t.top&&e.right===t.right&&e.bottom===t.bottom&&e.left===t.left}function Hf(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const Pk="os-work-area-changed",$k="data-os-dock-behavior",Uk="os/work-area";function Bk(){return{insets:{...Uf},rect:{x:0,y:0,width:0,height:0},viewport:{x:0,y:0,width:0,height:0},area:{width:0,height:0}}}const wt=ae(Uk,()=>({snapshot:Bk(),installed:!1,areaEl:null})),$n={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 Fa(e){return{insets:{...e.insets},rect:{...e.rect},viewport:{...e.viewport},area:{...e.area}}}function Fk(){return Fa(wt.state.snapshot)}function ge(e){const t=e??wt.state.areaEl;if(!t)return{...wt.state.snapshot.rect};const n=t.clientWidth||t.getBoundingClientRect().width,o=t.clientHeight||t.getBoundingClientRect().height;return Ff(n,o,wt.state.snapshot.insets)}function Hk(e){const{installed:t,snapshot:n}=wt.state;if(!t)return{...Uf};const o=n.viewport;return Mk(Bf(o.x,o.y,o.width,o.height),e.getBoundingClientRect())}function Fo(e){return wt.subscribe(t=>{e(Fa(t.snapshot))})}function Gk(e){const t=zk(e),n=[],o=e.shellBody.querySelectorAll(e.chromeSelector??".os-dock");for(const l of Array.from(o))l.hidden||l.getAttribute($k)==="dynamic"||n.push(l.getBoundingClientRect());const s=xk(t,n),i=e.area.clientWidth||t.width,r=e.area.clientHeight||t.height,a=Ff(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 zk(e){const{area:t}=e;if(t.offsetWidth>0&&t.offsetParent===e.shellBody){const n=e.shellBody.getBoundingClientRect();return Bf(n.left+t.offsetLeft,n.top+t.offsetTop,t.offsetWidth,t.offsetHeight)}return t.getBoundingClientRect()}function jk(e,t){e.style.setProperty($n.top,`${t.insets.top}px`),e.style.setProperty($n.right,`${t.insets.right}px`),e.style.setProperty($n.bottom,`${t.insets.bottom}px`),e.style.setProperty($n.left,`${t.insets.left}px`),e.style.setProperty($n.width,`${t.rect.width}px`),e.style.setProperty($n.height,`${t.rect.height}px`)}function Vk(e,t){return Wk(e.insets,t.insets)&&Hf(e.rect,t.rect)&&Hf(e.viewport,t.viewport)&&e.area.width===t.area.width&&e.area.height===t.area.height}function Kk(e){const t=new Map;let n=null,o=null,s=!1,i=!1,r=null;const a=()=>{if(s||i)return;const p=Gk(e);if(!!wt.state.installed&&Vk(wt.state.snapshot,p))return;jk(e.shell,p),wt.setState({snapshot:p,installed:!0,areaEl:e.area});const h=Fa(p);A(v.WORK_AREA_CHANGED,h),document.dispatchEvent(new CustomEvent(Pk,{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(v.OVERVIEW_ENTERING,vi,u),ee(v.OVERVIEW_EXITED,vi,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),jt(v.OVERVIEW_ENTERING,vi),jt(v.OVERVIEW_EXITED,vi),bi===r&&(bi=null)}},bi=r,r}const vi="openstation/work-area";let bi=null;function qk(){bi?.refresh()}const Yk={get:Fk,rectOf:ge,insetsOf:Hk,subscribe:Fo};function Xk(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){Gf(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=tI(e,n),i=fa(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=ec(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"){Ho(e);return}const u=e.getById(l.id);if(!u){Ho(e);return}Zk(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&Ho(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 Zk(e,t){const n=e._splitOverviewZone;if(!n){Ho(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),A(v.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),Ho(e)}function Ho(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();Gf(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 Gf(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const zf=30,Jk=260;function Qk(e,t){return e<=t.left+zf?"left":e>=t.right-zf?"right":null}function eI(e,t){const n=ge(e._desktop),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?n.x:n.x+n.width-o,y:n.y,width:o,height:s}}function tI(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 nI(e,t){if(e._snapPendingZone===t&&e._snapPreviewEl)return;if(e._snapPendingZone=t,!e._snapPreviewEl){const o=document.createElement("div");o.className="os-snap-preview",o.setAttribute("aria-hidden","true"),e._desktop.appendChild(o),e._snapPreviewEl=o,Promise.resolve().then(()=>{o.classList.add("os-snap-preview--visible")})}const n=eI(e,t);e._snapPreviewEl.style.left=`${n.x}px`,e._snapPreviewEl.style.top=`${n.y}px`,e._snapPreviewEl.style.width=`${n.width}px`,e._snapPreviewEl.style.height=`${n.height}px`,e._snapPreviewEl.dataset.zone=t}function Ha(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()},Jk)}function oI(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=Qk(n,o),i=e._snapPendingZone;s?(nI(e,s),i!==s&&A(v.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(Ha(e),A(v.SNAP_ZONE_CANCELED,{windowId:t.id}))}function sI(e,t){const n=e._snapPendingZone;return n?(Ha(e),t.snapTo(n),A(v.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{Xk(e,t,n)}),!0):!1}function jf(e){e._snapPendingZone&&Ha(e)}const iI=6,rI=6,aI=8,cI={Shake:"shake"},Vf="os-window--grid-snapping",Kf="os-area--grid-snapping";function lI(e){const t={cols:iI,rows:rI},n=J(v.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 Ga(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:qf(Math.floor(s*o.cols),o.cols),row:qf(Math.floor(i*o.rows),o.rows)}}function qf(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t-1,e)):0}function dI(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 Ei(e,t,n,o){const s=dI(e,t,n,o),i=Math.round(aI/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 uI(e,t){return e.col===t.col&&e.row===t.row}function za(e,t,n){const o=e._desktop.getBoundingClientRect();return{x:t-o.left,y:n-o.top}}function ja(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 fI(e,t,n,o){if(e._gridSnap)return;jf(e);const s=ge(e._desktop),i=lI(s),r=za(e,n,o),a=Ga(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:Ei(a,a,s,i),overlayEl:l,targetEl:c,windowEl:t.element};e._gridSnap=d,t.element.classList.add(Vf),e._desktop.classList.add(Kf),ja(d,s),requestAnimationFrame(()=>{e._gridSnap===d&&l.classList.add("os-grid-snap--visible")}),A(v.GRID_SNAP_ARMED,{windowId:t.id,anchor:{...a},dims:{...i}}),A(v.GRID_SNAP_CHANGED,{windowId:t.id,anchor:{...a},cursor:{...a},rect:{...d.rect}})}function pI(e,t,n){const o=e._gridSnap;if(!o)return;const s=ge(e._desktop),i=za(e,t,n),r=Ga(i.x,i.y,s,o.dims),a=Ei(o.anchor,r,s,o.dims),l=!uI(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,ja(o,s),(l||c)&&A(v.GRID_SNAP_CHANGED,{windowId:o.windowId,anchor:{...o.anchor},cursor:{...r},rect:{...a}})}function hI(e,t,n,o){const s=e._gridSnap;if(!s)return;const i=ge(e._desktop),r=za(e,t,n),a=Ga(r.x,r.y,i,s.dims);s.anchor=a,s.cursor=a,s.rect=Ei(a,a,i,s.dims),ja(s,i),s.targetEl.classList.remove("os-grid-snap__target--reset"),s.targetEl.offsetWidth,s.targetEl.classList.add("os-grid-snap__target--reset"),A(v.GRID_SNAP_ANCHOR_RESET,{windowId:s.windowId,anchor:{...a},reason:o}),A(v.GRID_SNAP_CHANGED,{windowId:s.windowId,anchor:{...a},cursor:{...a},rect:{...s.rect}})}const mI=200;function Yf(e){const t=e._gridSnap;if(!t)return null;e._gridSnap=null,t.windowEl.classList.remove(Vf),e._desktop.classList.remove(Kf);const n=t.overlayEl;return n.classList.remove("os-grid-snap--visible"),window.setTimeout(()=>n.remove(),mI),t}function gI(e){const t=Yf(e);t&&A(v.GRID_SNAP_CANCELED,{windowId:t.windowId})}function wI(e,t){const n=Yf(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 A(v.GRID_SNAP_COMMITTED,{...s,anchor:{...n.anchor},cursor:{...n.cursor},dims:{...n.dims}}),A(v.WINDOW_DRAG_END,{windowId:t.id,x:o.x,y:o.y}),A(v.WINDOW_MOVED,{windowId:t.id,x:o.x,y:o.y}),A(v.WINDOW_RESIZED,{windowId:t.id,width:o.width,height:o.height}),!0}function Xf(e,t){return Ei(e.anchor,e.cursor,t,{cols:e.cols,rows:e.rows})}function Zf(e,t){const n=e._gridSpan;if(!n||e.state!=="normal"&&e.state!=="minimized")return!1;const o=Xf(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 yI(e){const t=ge(e._desktop),n=[];for(const o of e._stack)Zf(o,t)&&(o._emitChange("moved"),n.push(o.id));return n.length>0&&A(v.GRID_SNAP_REFLOWED,{windowIds:n}),n}function vI(e){return Fo(()=>{yI(e)})}function bI(e){return[e.id,e.menu?.url??"",e.entry?.url??"",e.windowId??"",e.title].join(` `).toLowerCase()}function Jf(e,t){const n=t.trim().toLowerCase();return n?bI(e).includes(n):!1}function EI(e,t){if(t.length===0)return[];const n=[],o=new Set;for(const s of e)o.has(s.id)||t.some(i=>Jf(s,i))&&(o.add(s.id),n.push(s.id));return n}function Qf(e,t){const n=[];for(const o of t){const s=e.find(i=>Jf(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 _I=["index.php","upload.php","options-general.php"];function SI(){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 Va=new Map;function ep(e){e?.id&&Va.set(e.id,e)}function Ka(e){Va.delete(e)}function Go(){const e=[...SI(),...Va.values()],t=J(v.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 kI(e){return Go().find(t=>t.id===e)??null}function tp(e,t){const n=[...e.apps,...e.apps.length?_I:[]],o=EI(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 II=12,AI=["free","cascade","tile","columns","focus"],np=["wallpaper","wallpaperSettings","customGradient","customImage","accent","customAccent","desktopTheme","desktopLayout","dockPlacement","dockSize","dockBehavior","sideDockBehavior","windowRadius","windowReveal","unfocusEffect","adminBarMode"];function op(){return{preset:"",icon:"dashicons-desktop",color:"",apps:{mode:"all",ids:[]},widgets:{mode:"all",ids:[]},appearance:{},windows:[],layout:"free",provisioned:!0}}function CI(e){return e.kind!=="control"&&!e.locked}function LI(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)||!CI(i)||(s[i.id]="hidden");return s}function TI(e){const t=e?.widgets;return!t||t.mode!=="only"?null:t.ids}function NI(e){const t=e?.appearance;if(!t)return null;const n={};for(const o of np)t[o]!==void 0&&(n[o]=t[o]);return Object.keys(n).length>0?n:null}function sp(e){const t={};for(const n of np)e[n]!==void 0&&(t[n]=e[n]);return t}function OI(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 Jt(e,t){return e.getDesktops().find(n=>n.id===t)?.profile??null}function DI(e){return Jt(e,e.getActiveDesktopId())}function Un(e,t,n){const o=e.manager._desktops.find(s=>s.id===t);return o?(n?o.profile=n:delete o.profile,e.refreshLayout(),t===e.manager.getActiveDesktopId()&&qa(e,t),A(v.WORKSPACE_UPDATED,{desktopId:t,profile:n}),!0):!1}function RI(e,t){e.setVisibleWidgets?.(TI(Jt(e.manager,t)))}function xI(e,t){e.setAppearance?.(NI(Jt(e.manager,t)))}function qa(e,t){xI(e,t),RI(e,t)}function _i(e,t={}){const n=t.preset?kI(t.preset):null;let o=t.profile??null;!o&&n&&(o=J(v.WORKSPACE_PROFILE,tp(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&&Un(e,i.id,o),t.activate!==!1&&e.manager.switchDesktop(i.id),i}function ip(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 rp(e,t,n){const o=n.item.menu?.url;return Tn(t)??e.deriveWindowId(o?Si(o,e.adminUrl):t)}function ap(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=Si(a.url,e.adminUrl),c=e.deriveWindowId(l),d=e.manager.getAllByBaseId(rp(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 cp(e,t,n,o,s){const i=Tn(t);if(i){const a=new Set(e.manager.getAllByBaseId(i).map(l=>l.id));if(Me(t,{newInstance:!0}))return Za(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:rp(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 Ya(e,t,n={}){const o=Jt(e.manager,t);if(!o||o.provisioned&&!n.force)return;Un(e,t,{...o,provisioned:!0});const s=Qf(e.getNavItems(),o.windows),i=new Set,r=ap(e,s,t,i),a=[];let l=0;for(const[d,u]of s.entries()){if(u.url){const f=Si(u.url,e.adminUrl);l++;const p=r.get(u);if(p){a[d]=p.id,zo(e.manager,p,u);continue}cp(e,f,u,t,i).then(g=>{g&&(i.add(g.id),a[d]=g.id,zo(e.manager,g,u))}).catch(()=>{});continue}u.item.windowId&&(l++,e.openNative(u.item.windowId),Za(e.manager,u.item.windowId).then(f=>{f&&(a[d]=f.id,zo(e.manager,f,u))}))}dp(()=>{lp(e.manager,o.layout,a),A(v.WORKSPACE_PROVISIONED,{desktopId:t,opened:l,layout:o.layout})})}function lp(e,t,n){const o=n.find(Boolean);t==="focus"&&o&&e.focus(o),ip(e,t)}function dp(e){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>requestAnimationFrame(e)):e()}function MI(e,t){const n=Jt(e.manager,t);if(!n||!n.provisioned||n.windows.length===0)return;const o=Qf(e.getNavItems(),n.windows),s=new Set,i=ap(e,o,t,s),r=[],a=[];for(const[l,c]of o.entries()){if(c.url){const d=Si(c.url,e.adminUrl),u=i.get(c);if(u){r[l]=u.id;continue}a.push(cp(e,d,c,t,s).then(f=>{f&&(s.add(f.id),r[l]=f.id,zo(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(Za(e.manager,c.item.windowId).then(d=>{d&&(r[l]=d.id,zo(e.manager,d,c))}))}}a.length>0&&Promise.all(a).then(()=>dp(()=>{e.manager.getActiveDesktopId()===t&&lp(e.manager,n.layout,r)}))}function Xa(e,t){const n=[],o=new Set,s=ge(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=WI({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>=II)break}return n}function WI(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 zo(e,t,n){const o=ge(e._desktop);if(n.gridSpan){t._gridSpan={anchor:{...n.gridSpan.anchor},cursor:{...n.gridSpan.cursor},cols:n.gridSpan.cols,rows:n.gridSpan.rows},Zf(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 Za(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 PI(e,t,n={}){const o=e.manager._desktops.find(r=>r.id===t);if(!o)return null;const i={...o.profile??op(),windows:Xa(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]}),Un(e,t,i),i}function Si(e,t){if(/^https?:\/\//i.test(e))return e;try{return new URL(e,t).href}catch{return t}}let Nt=null;function $I(e){return Nt=e,()=>{Nt=null}}function UI(){return Nt!==null}function BI(e){return Nt?(Nt.openCreator(e),!0):!1}function FI(e){return Nt?(Nt.openEditor(e),!0):!1}function up(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 HI(e){const t=Nt;return t?(t.manager.switchDesktop(e),qa(t,e),Ya(t,e,{force:!0}),!0):!1}const fp=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],ki="osHadFullscreenBeforeOverview",GI=250;function pp(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[ki]="true",Ba()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function hp(e){if(e.element.dataset[ki]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[ki],Ba();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[ki],Ba()}}function Ja(e,t=!0){t&&hp(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function mp(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function gp(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function zI(e){if(e._overviewActive)return;wp(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,A(v.OVERVIEW_ENTERING,{}),A(v.DOCK_REFRESH_ACTIVE,{});for(const c of fp){const d=document.getElementById(c);d&&(d.inert=!0)}mp(!0),gp(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)pp(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.topd.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=yp(e),e._desktop.appendChild(e._overviewTopBar);const a=fa(t,i,yu(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=ec(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"){Ot(e);return}const p=e.getById(d.id);A(v.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),Ot(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){Ot(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){vp(e);return}Ot(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&&A(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&A(v.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&A(v.OVERVIEW_ENTERED,{})},300)}function wp(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function jI(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 Qa=null;function VI(e){return Qa=e,()=>{Qa=null}}function yp(e){const t=document.createElement("div");t.className="os-overview-top-bar";const n=Qa?.();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(up)&&o.classList.add("os-overview-top-bar__list--restorable");for(const a of e._desktops)o.appendChild(KI(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='',s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),vp(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 vp(e){e._overviewAddTileFocused=!1;const t=_p(e);Ii(e,t.id),BI(t.id)}function KI(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&&Ii(e,t.id)},GI)))}),a.addEventListener("dblclick",p=>{a.hasAttribute("contenteditable")||(p.preventDefault(),p.stopPropagation(),window.clearTimeout(l),l=void 0,bp(e,a,t))}),o.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),!a.hasAttribute("contenteditable")&&Ii(e,t.id)});const c=UI(),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=qt("edit",{size:14}),d.addEventListener("click",p=>{if(p.preventDefault(),p.stopPropagation(),!c){bp(e,a,t);return}Ii(e,t.id),FI(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=qt("close",{size:16}),u.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),Ap(e,t.id),jo(e)}),n.appendChild(o),n.appendChild(d),n.appendChild(u);const f=document.createElement("div");if(f.className="os-overview-top-bar__tile-actions",up(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=`${qt("windows",{size:12})}${b("Restore")}`,p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),HI(t.id)&&Ot(e)}),f.appendChild(p)}return f.childElementCount>0&&n.appendChild(f),n}function bp(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&&kp(e,n.id,t.textContent??""),e._overviewActive&&jo(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 jo(e){if(!e._overviewTopBar)return;const t=yp(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Ii(e,t){Ip(e,t),Ot(e)}function ec(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(Kt("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function Ot(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,A(v.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),A(v.DOCK_REFRESH_ACTIVE,{}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of fp){const r=document.getElementById(i);r&&(r.inert=!1)}mp(!1),gp(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"&&(hp(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"),Ja(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),A(v.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>wp(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&&(A(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function qI(e){return[...e._desktops]}function Ep(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function YI(e){return Ep(e).id}function Ai(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&Ja(t)}function tc(e){for(const t of e._stack)Ai(e,t)}function XI(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?nc(e):Ai(e,o),A(v.WINDOW_DESKTOP_CHANGED,{windowId:t,from:s,to:n})),!0}function _p(e,t){e._desktopSeq++;const n={id:`desktop-${e._desktopSeq}`,label:t?.label?.trim().slice(0,Sp)||le(b("Workspace %d"),e._desktopSeq)};return e._desktops.push(n),A(v.DESKTOP_CREATED,{desktopId:n.id}),n}const Sp=64;function kp(e,t,n){const o=e._desktops.find(r=>r.id===t);if(!o)return!1;const s=n.trim().slice(0,Sp);if(!s||s===o.label)return!1;const i=o.label;return o.label=s,A(v.DESKTOP_RENAMED,{desktopId:t,label:s,previousLabel:i}),!0}function Ip(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)nc(e),jo(e);else{tc(e),n?.direction&&ZI(e,n.direction);const s=[...e._stack].reverse().find(r=>r.config.desktopId===t&&r.state!=="minimized");s&&e.focus(s);const i=e._desktops.find(r=>r.id===t);i&&n_(e._desktop,i.label)}A(v.DESKTOP_SWITCHED,{from:o,to:t})}function ZI(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 Ap(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?nc(e):tc(e),A(v.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id}),i&&A(v.DESKTOP_SWITCHED,{from:t,to:s.id})}function nc(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"),Ja(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),tc(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||""}),pp(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=fa(t,o,yu(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=ec(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function JI(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 QI(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;A(v.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=ge(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"}})),A(v.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function Cp(e){const t=e._stack.filter(f=>f.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const f of t)f.state==="minimized"&&f.restore(),f.state==="fullscreen"&&f.toggleFullscreen(),f.state==="maximized"&&f.toggleMaximize();const n=ge(e._desktop),o=r_(t.length,n.width,n.height),s=J(v.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=s_(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;A(v.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,l=12,c=Math.floor((n.width-a*2-l*(i-1))/i),d=Math.floor((n.height-a*2-l*(r-1))/r);t.forEach((f,p)=>{const g=p%i,h=Math.floor(p/i);f._gridSpan=null,f.element.style.left=`${n.x+a+g*(c+l)}px`,f.element.style.top=`${n.y+a+h*(d+l)}px`,f.element.style.width=`${c}px`,f.element.style.height=`${d}px`});const u=e.getFocused();u&&e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"tile"}})),A(v.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}function Lp(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 eA(e,t){const n=e.getFocused();n&&e.focus(n),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:t}}))}const tA=4;function nA(e){const t=Lp(e);if(t.length===0)return;if(t.length>tA){Cp(e);return}const n=t.length;A(v.ARRANGE_COLUMNS_STARTING,{windowCount:t.length,cols:n});const o=ge(e._desktop),s=16,i=12,r=Math.floor((o.width-s*2-i*(n-1))/n),a=Math.floor(o.height-s*2);t.forEach((l,c)=>{l.element.style.left=`${o.x+s+c*(r+i)}px`,l.element.style.top=`${o.y+s}px`,l.element.style.width=`${r}px`,l.element.style.height=`${a}px`}),eA(e,"columns"),A(v.ARRANGE_COLUMNS_APPLIED,{windowCount:t.length,cols:n})}const Tp=.64;function oA(e){const t=Lp(e);if(t.length===0)return;const n=ge(e._desktop),o=J(v.ARRANGE_FOCUS_SPLIT,Tp,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),s=Number.isFinite(o)&&o>=.3&&o<=.9?o:Tp;A(v.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((g,h)=>h!==d),p=f.length===0?a:Math.floor(a*s);if(u.element.style.left=`${n.x+i}px`,u.element.style.top=`${n.y+i}px`,u.element.style.width=`${p}px`,u.element.style.height=`${l}px`,f.length>0){const g=n.x+i+p+r,h=a-p-r,m=Math.floor((l-r*(f.length-1))/f.length);f.forEach((_,I)=>{_.element.style.left=`${g}px`,_.element.style.top=`${n.y+i+I*(m+r)}px`,_.element.style.width=`${h}px`,_.element.style.height=`${m}px`})}e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"focus"}})),A(v.ARRANGE_FOCUS_APPLIED,{windowCount:t.length,split:s})}const Np="desktop-mode-snap-to-grid";function sA(){try{return window.localStorage.getItem(Np)==="1"}catch{return!1}}function iA(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(Np,t?"1":"0")}catch{}A(v.ARRANGE_SNAP_CHANGED,{enabled:t})}}function rA(e){if(!e._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const t=e._desktop.getBoundingClientRect(),n=t.width>=t.height?12:8,o={cellWidth:Math.max(40,Math.round(t.width/n)),cellHeight:Math.max(40,Math.round(t.height/Math.round(n*.66)))},s=J(v.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=i_(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}const Op="desktop-mode-native-window-geometry",Dp=64,at=8192;function Ci(){try{const e=window.localStorage.getItem(Op);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function Rp(e){try{window.localStorage.setItem(Op,JSON.stringify(e))}catch{}}function Li(e){if(!e)return null;const n=Ci()[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>at||s>at)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<=at&&a<=at;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function xp(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>at||o>at)return;const s=Ci(),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||(Vo(s,e,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),Ko(s))}function Mp(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>at||o>at)return;const s=Ci(),i=s[e];i&&(i.x===n&&i.y===o||(Vo(s,e,{...i,x:n,y:o}),Ko(s)))}function Wp(e,t,n){if(!e)return;const o=Ci(),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>at||r>at)return;Vo(o,e,{width:i,height:r,state:t}),Ko(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;Vo(o,e,r),Ko(o);return}s.state!==t&&(Vo(o,e,{...s,state:t}),Ko(o))}function Vo(e,t,n){delete e[t],e[t]=n}function Ko(e){const t=Object.keys(e);if(t.length>Dp){const n={};for(const o of t.slice(-Dp))n[o]=e[o];Rp(n);return}Rp(e)}function aA(e,t,n,o){const s=o.x+xa-n,i=o.x+o.width-xa,r=Math.max(s,Math.min(e,i)),a=o.y+ok,l=o.y+o.height-xa,c=Math.max(a,Math.min(t,l));return{x:r,y:c}}const Pp=100,Ti=30;class cA{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=sA(),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._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this._unsubscribeWorkArea=Fo(()=>this.reflowStatefulWindows()),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);s&&(this._overviewActive||this.getFocused()!==s&&this.focus(s))},0)})}reflowStatefulWindows(){if(!this._overviewActive){for(const t of this._stack){const n=t.element.parentElement;if(!n)continue;const o=ge(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=Math.floor(o.width/2),i=o.height,r=t.state==="snapped-left"?o.x:o.x+o.width-s;t.element.style.left=`${r}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${s}px`,t.element.style.height=`${i}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=aA(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=In(t.url);c===In(o.getCurrentUrl())||c===In(o.config.url||"")||c===In(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})),A(v.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(In(n.url)!==In(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),Ai(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})),A(v.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*Ti,r=40+this.cascadeIndex%8*Ti;return this.createWindow({...s?{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=ge(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*Ti,d=i.y+40+this.cascadeIndex%8*Ti,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",_=typeof t.y=="number",I=typeof t.initialState=="string",O=!g||!h||!I||!m||!_?Li(u):null;let $=t.width??(O?Math.max(O.width,f):a),S=t.height??(O?Math.max(O.height,p):l);!m&&!_&&!O&&($=Math.max(f,Math.min($,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-$-r)),U=Math.max(i.y+r,Math.min(d,i.y+i.height-S-r)),F=t.initialState??(O?.state==="maximized"?"maximized":void 0);let K,Q;if(O&&typeof O.x=="number"&&typeof O.y=="number"){const q=Math.max(i.x,i.x+i.width-$-r),se=Math.max(i.y,i.y+i.height-S-r);K=Math.max(i.x+r,Math.min(O.x,q)),Q=Math.max(i.y+r,Math.min(O.y,se))}const Z=t.x??K??W,C=t.y??Q??U,D=g||h||m||_||I,V=!!O,j={x:Z,y:C,width:$,height:S,state:F};let te;try{te=J(v.WINDOW_GEOMETRY,j,{windowId:t.id,baseId:u,hasSavedGeometry:V,callerPinned:D,desktopRect:{width:s.width,height:s.height},workArea:{...i}})}catch(q){A(v.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:q}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,q),te=j}const N=(q,se)=>typeof q=="number"&&Number.isFinite(q)?q:se,L=te&&typeof te=="object"?te:j,M=Math.max(N(L.width,$),f),P=Math.max(N(L.height,S),p),H=N(L.x,Z),z=N(L.y,C),y=L.state??F,E={icon:t.icon||"dashicons-admin-generic",...t,x:H,y:z,width:M,height:P,minWidth:f,minHeight:p,...y?{initialState:y}:{},baseId:u,desktopId:t.desktopId||this._activeDesktopId};if(t.gridSpan){const q=Xf(t.gridSpan,ge(this._desktop));E.x=q.x,E.y=q.y,E.width=q.width,E.height=q.height}this.cascadeIndex++,this._openingWindowIds.add(t.id),this._openingBaseIds.add(u);const T=Promise.all([JE(XE()),ca(la())]);let x;try{x=await T}catch(q){throw this._openingWindowIds.delete(t.id),this._openingBaseIds.delete(u),q}this._openingWindowIds.delete(t.id),this._openingBaseIds.delete(u);const[X]=x,Y=X.createWindow(E);if(t.gridSpan&&(Y._gridSpan={anchor:{...t.gridSpan.anchor},cursor:{...t.gridSpan.cursor},cols:t.gridSpan.cols,rows:t.gridSpan.rows}),Y.onFocusRequest=q=>{this._cascadeDepth>0||this.focus(q)},Y.onClose=q=>this.remove(q),Y.onMinimize=q=>{this._cascadeDepth++;try{this.cascadeMinimize(q)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const se=this._stack.filter(Ee=>Ee.state!=="minimized");se.length>0&&this.focus(se[se.length-1])},Y.onRestore=q=>{this._cascadeDepth++;try{this.cascadeRestore(q)}finally{this._cascadeDepth--}},Y.onOpenAnother=q=>{const se=q.config.baseId||q.id;q.config.native&&window.wp?.os?.openNewWindow?.(se,{source:"open-another"})||this.openNew({id:se,baseId:se,url:q.config.url||"",title:q.config.title,icon:q.config.icon,submenu:q.config.submenu,multi:!0})},Y.onOpenInNewWindow=q=>{const se=q.config.baseId||q.id;if(q.config.native&&window.wp?.os?.openNewWindow?.(se,{source:"open-in-new-window"}))return;const Ee=q.getCurrentUrl();this.openNew({id:se,baseId:se,url:Ee||q.config.url||"",title:q.config.title,icon:q.config.icon,submenu:q.config.submenu,multi:!0})},Y.onToggleStartup=q=>{this.onToggleStartupRequested?.(q)},Y.snapConfigProvider=()=>this.getSnapConfig(),Y.onDragMove=(q,se,Ee)=>{if(this._gridSnap){pI(this,se,Ee);return}oI(this,q,se)},Y.onDragGesture=(q,se)=>{switch(se.type){case"modifier":se.active?fI(this,q,se.clientX,se.clientY):gI(this);break;case"shake":hI(this,se.clientX,se.clientY,cI.Shake);break}},Y.onDragEnd=q=>this._gridSnap?wI(this,q):this._snapPendingZone?sI(this,q):(jf(this),!1),n.prewarm)return Y.element.style.display="none",Y.element.setAttribute("aria-hidden","true"),this._desktop.appendChild(Y.element),Y;this._stack.push(Y),this._desktop.appendChild(Y.element),Ai(this,Y),Y.hydrateNative(),this.focus(Y);const ce={windowId:Y.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:ce})),A(v.WINDOW_OPENED,ce),Y}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?.(),A(v.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=this._stack.length>0?this._stack[this._stack.length-1]:null,i=this._stack.find(l=>l!==o&&l.isFocused()&&l.isFullscreen());i&&J(v.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:i.id,focusedTo:o.id})&&i.toggleFullscreen();const r=this._stack.indexOf(o);if(r>-1&&this._stack.splice(r,1),this._stack.push(o),this.enforceOwnershipOrder(),this._stack.forEach((l,c)=>{l.setZIndex(Pp+c),l.setFocused(c===this._stack.length-1)}),s&&s!==o&&s.id!==o.id){const l={windowId:s.id,focusedTo:o.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:l})),A(v.WINDOW_BLURRED,l)}const a={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:a})),A(v.WINDOW_FOCUSED,a)}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(Pp+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=Li(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=ge(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})),A(v.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),A(v.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 qI(this)}getActiveDesktop(){return Ep(this)}getActiveDesktopId(){return YI(this)}createDesktop(t){return _p(this,t)}switchDesktop(t,n){Ip(this,t,n)}closeDesktop(t){Ap(this,t)}renameDesktop(t,n){return kp(this,t,n)}moveWindowToDesktop(t,n){return XI(this,t,n)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=J(v.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(c=>!n.has(c.id));A(v.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=J(v.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(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 A(v.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(){QI(this)}tile(){Cp(this)}columns(){nA(this)}focusLayout(){oA(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){iA(this,t)}getSnapConfig(){return rA(this)}enterOverview(){if(Vt()){document.dispatchEvent(new CustomEvent("os-mobile-open-switcher"));return}zI(this)}exitOverview(t,n=!1){Ot(this,t,n)}destroy(){this._unsubscribeWorkArea(),this.desktopResizeObserver?.disconnect(),this._reflowRestoreTimer!==null&&(window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=null),this._overviewActive&&Ot(this),this.discardPrewarmed(),jI(this),o_()}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=J(v.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){JI(this,t,n)}}function lA(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 $p(e,t){if(e._overviewActive)return;const n=lA(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 Up=!1;function oc(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;return Bp(t)}function Bp(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 dA(e){if(Up)return;Up=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(oc(document)||(n.preventDefault(),$p(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"||$p(e,o.direction==="prev"?"prev":"next")})}let qo=null;function uA(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:Bp(n)}function fA(e=window){if(qo)return qo;const t=o=>{uA(o)&&o.stopPropagation()};e.addEventListener("keydown",t,!0);const n=()=>{e.removeEventListener("keydown",t,!0),qo===n&&(qo=null)};return qo=n,n}function Fp(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 Hp(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,jo(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function pA(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function hA(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Gp(e){return e._overviewActive?(e.exitOverview(),!0):!1}function mA(){return document.querySelector("os-modal[open], os-confirm-dialog[open]")!==null}function gA(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function wA(e){return gA(e)?(e.toggleShowDesktop(),!0):!1}let zp=!1;function yA(e){zp||(zp=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||Vt()||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||oc(document)||mA())return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Hp(e,"prev"):Fp(e,"prev");break;case"ArrowRight":n=e._overviewActive?Hp(e,"next"):Fp(e,"next");break;case"ArrowUp":n=Gp(e)||wA(e)||pA(e);break;case"ArrowDown":n=Gp(e)||hA(e);break}n&&t.preventDefault()},!0))}async function Qt(e){return await ca(la()),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 vA="os-window-close-all";function bA(e){return e.code!=="KeyW"||e.getModifierState?.("AltGraph")||!(e.ctrlKey||e.metaKey)?!1:e.altKey&&!e.shiftKey}let sc=!1;function jp(e){const t=e.getActiveDesktopId();return e.getAll().filter(n=>(n.config.desktopId||t)===t)}async function Vp(e,t){if(sc)return 0;const n=jp(e);if(n.length===0)return 0;if(t&&!t.shouldAsk())return Kp(e);const o=t?{rememberLabel:b("Don't ask again"),onRemember:i=>{i&&t.setAsk(!1)}}:{};sc=!0;let s=!1;try{s=await Qt({title:b("Close all windows?"),message:le(Kt("%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{sc=!1}return s?Kp(e):0}const EA=700,_A=50;function SA(e,t){const n=()=>t.filter(o=>!e.getById(o)).length;return new Promise(o=>{const s=Date.now()+EA,i=()=>{const r=n();if(r===t.length||Date.now()>=s){o(r);return}setTimeout(i,_A)};i()})}async function Kp(e){e._overviewActive&&e.exitOverview();const t=jp(e).map(s=>s.id),n=e.getAll().map(s=>s.id).filter(s=>!t.includes(s));e.closeAll({exceptIds:n});const o=await SA(e,t);return o>0&&ue({message:le(Kt("Closed %d window.","Closed %d windows.",o),o)}),o}let qp=!1;function kA(e,t){if(qp)return;qp=!0,document.addEventListener("keydown",o=>{bA(o)&&(o.preventDefault(),o.stopImmediatePropagation(),Vp(e,t))},!0);const n=window.location.origin;window.addEventListener("message",o=>{if(o.origin!==n)return;const s=o.data;!s||s.type!==vA||Vp(e,t)})}const Yp=gf;let Xp=!1;function Zp(e){return e?document.getElementById(`wp-window-${e}`):null}function IA(){Xp||(Xp=!0,AA())}function AA(){ee(v.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=Zp(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove($a),n.classList.add(Bo),Ak(n),$f(t),vk(t))}),ee(v.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=Zp(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 .${$o}`)?.classList.contains(gi);if(n.classList.remove(Bo),n.removeAttribute(Ua),!o){Pf(t),Cf(t);return}n.classList.add($a);const s=yi(n);Cf(t),window.setTimeout(()=>{yi(n)===s&&(n.classList.contains(Bo)||Pf(t))},Yp),window.setTimeout(()=>{yi(n)===s&&(n.classList.contains(Bo)||n.classList.remove($a))},Yp+ik)}),ee(v.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Jp())})}function Jp(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),$f(n))})}const CA="desktop_mode_classic";function LA(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has("page")&&!e.searchParams.has(CA)}const ic=ae("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function TA(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=ic.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Qp(e.id)}function Qp(e){const t=ic.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function NA(){return ic.state.entries.slice()}const OA=32,DA=64,RA=/^[a-z0-9_/-]+$/,ye=ae("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function en(e){return`${e.type}:${e.id}`}function eh(e){return e.root?en(e.root):en(e)}function th(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&RA.test(o.trim().toLowerCase());return Yt(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 nh(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function xA(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,OA).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=nh(e.previewUrl);o&&(n.previewUrl=o);const s=nh(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,DA).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 oh(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 rc(e){return e?[en(e),eh(e),...(e.links??[]).map(t=>en(t)+(t.rel==="child"?"!child":""))].join("|"):""}function Ni(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Oe("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=th(t);if(a.length>0){o==="api"&&Oe("WindowContentRef",a,t),Cu("WindowContentRef",a,t);return}s=xA(t,o)}if(s=J(v.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||th(s).length>0)){Cu("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=ye.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&rc(s)===rc(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&s.revisionsUrl===i.revisionsUrl&&s.revisionCount===i.revisionCount&&oh(s)===oh(i))return;s===null?ye.state.contentByWindow.delete(e):ye.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})),A(v.WINDOW_CONTENT_CHANGED,r),UA(),PA()}function ze(e){return ye.state.contentByWindow.get(e)}function ac(){const e=new Map;for(const[s,i]of ye.state.contentByWindow){const r=eh(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=ye.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=J(v.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[openstation] `os.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function sh(e){return ac().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function MA(e){const t=new Set,n=sh(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of ih())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function ih(){const e=ye.state.focusSeq,t=new Map;for(const[a,l]of ye.state.contentByWindow){const c=en(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 ye.state.contentByWindow){if(l.root){const c=t.get(en(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(en(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=J(v.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 WA(e){return ye.state.listeners.add(e),()=>{ye.state.listeners.delete(e)}}function PA(){for(const e of Array.from(ye.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function $A(){return Array.from(ye.state.contentByWindow).map(([e,t])=>`${e}=${rc(t)}`).sort().join(";")}function UA(){const e=$A();if(e===ye.state.lastGroupsSignature)return;ye.state.lastGroupsSignature=e;const n={groups:ac()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),A(v.WINDOW_LINK_GROUPS_CHANGED,n)}const BA={get:ze,set:(e,t)=>Ni(e,t,{source:"api"}),groups:ac,edges:ih,groupOf:sh,related:MA,subscribe:WA};function FA({manager:e}){ye.state.manager=e,!ye.state.started&&(ye.state.started=!0,ee(v.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=ye.state.manager?.getById(t.windowId)?.config?.content;o&&Ni(t.windowId,o,{source:"config"})}),ee(v.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(ye.state.focusSeq.delete(t.windowId),Ni(t.windowId,null,{source:"config"}))}),ee(v.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(ye.state.seq+=1,ye.state.focusSeq.set(t.windowId,ye.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=ye.state.manager?.findByIframeSource?.(t.source);o&&Ni(o.id,n.identity??null,{source:"bridge"})}))}const HA=ae("desktop-mode/admin-link-deps",()=>({deps:null}));function GA(e){HA.state.deps=e}const rh=ae("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),Bn=rh.state.seed,zA=rh.state.listeners;function Fn(e){Oe("Wallpaper",Yt(e,lh),e);const t=Bn.findIndex(n=>n.id===e.id);t>=0?Bn[t]=e:Bn.push(e),ch()}function ah(e){const t=Bn.findIndex(n=>n.id===e);t>=0&&(Bn.splice(t,1),ch())}function ch(){const e=Array.from(zA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function cc(){const e=Bn.slice(),t=J(v.WALLPAPERS,e);return Array.isArray(t)?t.filter(jA):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function Yo(e){return cc().find(t=>t.id===e)}const lh=[{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 jA(e){return Yt(e,lh).length===0}const dh=ae("desktop-mode/wallpaper-settings",()=>({values:{}}));function VA(e){return{...dh.state.values[e]??{}}}function KA(e){const t=dh.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const qA=20,lc=1,Oi=24,Hn="os-dock--revealed",Xo="data-os-dock-behavior",YA="os-dock",uh="os-side-dock",Di="os-dock-vt",XA=".os-constellation, .os-dock-peek";function ZA(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 fh(e){return e.getAttribute(Xo)==="dynamic"}function JA(e,t,n,o,s,i=qA){switch(e){case"bottom":return n>=s-i;case"left":return t<=i;case"right":return t>=o-i}return!1}function QA(e,t,n,o){const s=e.getBoundingClientRect();if(s.width<=0||s.height<=0)return!1;let i=s.top-Oi;const r=s.bottom+Oi;let a=s.left-Oi,l=s.right+Oi;switch(t){case"bottom":i=s.top-s.height*lc;break;case"left":l=s.right+s.width*lc;break;case"right":a=s.left-s.width*lc;break}return n>=a&&n<=l&&o>=i&&o<=r}function e0(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function t0(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 R=e.getBehaviors(),W=S.id===uh?R.sidebar:R.dock;S.getAttribute(Xo)!==W&&S.setAttribute(Xo,W)},d=S=>{const R=S.ownerDocument.activeElement;if(R&&S.contains(R))return!0;if(!n)return!1;if(o)return S.classList.contains(Hn);const W=ZA(S);return JA(W,n.x,n.y,window.innerWidth,window.innerHeight)||S.classList.contains(Hn)&&QA(S,W,n.x,n.y)},u=(S,R)=>{if(S.classList.contains(Hn)===R){i.delete(S);return}if(!R&&r){a=!0;return}if(s.has(S)){i.set(S,R);return}const W=()=>{S.classList.toggle(Hn,R)},U=document;if(typeof U.startViewTransition!="function"||e0()){W();return}const F=`os-dock-${S.id||"rail"}`;S.style.setProperty("view-transition-name",F),document.documentElement.classList.add(Di);let K;try{K=U.startViewTransition(W)}catch{S.style.removeProperty("view-transition-name"),document.documentElement.classList.remove(Di),W();return}const Q=K.finished&&typeof K.finished.then=="function"?K.finished:Promise.resolve(),Z=()=>{S.style.removeProperty("view-transition-name"),s.delete(S),s.size===0&&document.documentElement.classList.remove(Di);const C=i.get(S);i.delete(S),!t&&C!==void 0&&u(S,C)};s.set(S,Q.then(Z,Z))},f=()=>{if(!t)for(const S of l()){if(c(S),!fh(S)){S.classList.remove(Hn);continue}u(S,d(S))}},p=S=>{if(t||!l().some(fh))return;n={x:S.clientX,y:S.clientY};const R=S.target;o=R instanceof Element&&R.closest(XA)!==null,f()};let g=0;const h=()=>{g||(g=requestAnimationFrame(()=>{g=0,f()}))},m=()=>f(),_=()=>{r=!0},I=()=>{r=!1,a&&(a=!1,f())};document.addEventListener("pointerdown",_,{capture:!0,passive:!0}),document.addEventListener("pointerup",I,{capture:!0,passive:!0}),document.addEventListener("pointercancel",I,{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 O=null;typeof MutationObserver<"u"&&(O=new MutationObserver(f),O.observe(e.shellBody,{childList:!0})),f();const $={refresh:f,destroy:()=>{t=!0,g&&(cancelAnimationFrame(g),g=0),O?.disconnect(),document.removeEventListener("pointerdown",_,{capture:!0}),document.removeEventListener("pointerup",I,{capture:!0}),document.removeEventListener("pointercancel",I,{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(Hn),S.style.removeProperty("view-transition-name");i.clear(),document.documentElement.classList.remove(Di),Ri===$&&(Ri=null)}};return Ri=$,$}let Ri=null;function n0(){Ri?.refresh()}function ph(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const hh=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","linerWidth","linerColor","glow","glowBlur","eyeColor","eyeScale"],mh=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function dc(){return{appearance:{},physics:{}}}function o0(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function xi(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&&o0(i)&&Object.assign(n,{[s]:i})}return n}function gh(e){if(!e||typeof e!="object"||Array.isArray(e))return dc();const t=e;return{appearance:xi(t.appearance,hh),physics:xi(t.physics,mh)}}function s0(e){return{appearance:xi(e,hh),physics:xi(e,mh)}}function i0(){const e=r0();if(e){const t=fc(e,uc());return pc(t),f0(t),t}try{const t=window.localStorage.getItem(ef);if(t)return fc(JSON.parse(t),uc())}catch{}return uc()}function uc(){const e=Eh();return e.wallpaper=ka(),e}function r0(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}const je=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Se=(e,t)=>typeof e=="boolean"?e:t,tn=e=>(t,n)=>e.some(o=>o.id===t)?t:n,Gn=e=>(t,n)=>typeof t=="string"&&e.test(t)?t:n,Mi=/^[a-z0-9_/-]+$/,wh={wallpaper:(e,t)=>typeof e=="string"&&e!==""?e:t,accent:(e,t)=>e===nf||li().some(n=>n.id===e)?e:t,customAccent:Gn(/^#[0-9a-fA-F]{6}$/),dockSize:tn(Ia),windowRadius:tn(Aa),adminBarMode:tn(di),desktopLayout:tn(lS),dockPlacement:tn(cS),dockBehavior:tn(ui),sideDockBehavior:tn(ui),dockRailRenderer:Gn(/^[a-z0-9_-]+$/),desktopTheme:Gn(/^[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:Gn(Mi),windowReveal:Gn(Mi),windowRevealDuration:(e,t)=>typeof e!="number"||!Number.isFinite(e)?t:e>0?Math.min(4e3,Math.max(80,Math.round(e))):0,windowLinkRenderer:Gn(Mi),windowLinkVisibility:(e,t)=>e==="focus"||e==="always"||e==="off"?e:t,windowLinksEnabled:Se,windowLinkRaiseOnFocus:Se,windowLinkHighlight:Se,customGradient:(e,t)=>je(e)?w0(e):{...t},customImage:(e,t)=>e===null||je(e)?y0(e):t,wallpaperSettings:(e,t)=>je(e)?c0(e):t,libraryHdOnly:Se,ai:(e,t)=>g0(e,t),heartbeatRate:(e,t)=>e===15||e===30||e===45||e===60?e:t,nativePostsEnabled:Se,nativePostsHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativePagesEnabled:Se,nativePagesHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativeUsersEnabled:Se,nativePluginsEnabled:Se,nativeCommentsEnabled:Se,stationHomeEnabled:Se,adminAssetCacheEnabled:Se,windowPrewarmEnabled:Se,showDesktopOnWallpaperClick:Se,confirmCloseAllWindows:Se,mioEnabled:Se,mioApiEnabled:Se,mioShowOnWallpaper:Se,mioStyle:(e,t)=>je(e)?gh(e):t,showPostStatusRibbons:Se,developerModeEnabled:Se,foldersSharingEnabled:Se,navPlacement:(e,t)=>je(e)?l0(e):t,navOrder:(e,t)=>Array.isArray(e)?vh(e):t,mobileLayout:(e,t)=>e==="auto"||e==="desktop"||e==="mobile"?e:t,mobileTabs:(e,t)=>Array.isArray(e)?vh(e).slice(0,3):t,dockPromotedPositions:(e,t)=>je(e)?d0(e):t},yh=Object.keys(wh);function fc(e,t){const n=on(t),o=e,s=wh;for(const i of yh)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 a0=new Set(["wallpaper","accent","customAccent","customGradient","customImage","wallpaperSettings","dockSize","windowRadius","adminBarMode","desktopLayout","dockPlacement","dockBehavior","sideDockBehavior","dockRailRenderer","desktopTheme"]);function c0(e){if(!je(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(o===""||!Mi.test(o)||!je(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 l0(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 vh(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 d0(e){const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(s===""||!je(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 Wi=null;const u0=250;let nn=null;function f0(e){nn=on(e)}function on(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 p0(e,t={}){pc(e),h0(e,t.windowId)}function pc(e){try{window.localStorage.setItem(ef,JSON.stringify(e))}catch{}}function h0(e,t){Wi!==null&&clearTimeout(Wi),t&&(hc=t),Dt("pending"),Wi=setTimeout(()=>{Wi=null;const n=hc;hc=null,bh(e,n)},u0)}let hc=null;function m0(e){if(!nn)return{...e};const t=nn,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 mc=!1,gc=null;function bh(e,t){if(mc){gc={state:e,windowId:t},Dt("pending");return}const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Dt("saved",void 0,void 0,e);return}const i=m0(e);if(!i){Dt("saved",void 0,void 0,e);return}Dt("saving"),mc=!0;const r=on(e),a=t||Ct;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 Nn(l);nn=r,Dt("saved",void 0,void 0,r)}).catch(l=>{Pi=!0,nn?(pc(nn),Dt("failed",l instanceof Error?l.message:String(l),on(nn))):Dt("failed",l instanceof Error?l.message:String(l))}).finally(()=>{mc=!1;const l=gc;if(gc=null,l&&Pi){Pi=!1;return}Pi=!1,l&&bh(l.state,l.windowId)})}let Pi=!1;function Dt(e,t,n,o){const s={phase:e};o&&(s.savedSettings=on(o)),t&&(s.error=t),n&&(s.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:s}))}function Eh(){return on(xn)}function g0(e,t=xn.ai){if(!je(e))return{...t};const{enabled:n}=e;return{enabled:typeof n=="boolean"?n:t.enabled}}function w0(e){if(!je(e))return{...xn.customGradient};const{from:t,to:n,angle:o}=e;return{from:ph(t)?t:xn.customGradient.from,to:ph(n)?n:xn.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:xn.customGradient.angle}}function y0(e){if(!je(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 wc(e){if(!e)return 214;let t=5381;for(let n=0;n4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function $i(e,t,n){if(!v0(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 b0="data-os-constellation";function E0(){return document.body.hasAttribute(b0)}const _h="os-item-menu-opening",_0=180,S0=220,Sh=32;function kh(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"&&(E0()&&(t.dataset.menuSlug||t.dataset.constellationId)||k0(e)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},_0))))},u=h=>{n&&h.relatedTarget instanceof Node&&n.contains(h.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},S0)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=I0(e,()=>c(),r),document.body.appendChild(n),D0(n),R0(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(_h,g),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(_h,g),c()}}function k0(e){return e.getInstances().length>=1}function I0(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=A0(a,e,r++,t,n);s.appendChild(l)}if(e.enableGhost!==!1){const a=L0(e,r,t);s.appendChild(a)}return o}function Ih(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function A0(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*Sh}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${wc(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 I=0;I<3;I++)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",qE(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 I=0;I<3;I++){const O=document.createElement("span");O.className="os-dock-peek__card-line",f.appendChild(O)}const p={window:e,item:t.item},g=J(v.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=I=>{if(h(),I.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(I.previouslyFocusedId){const O=t.windowManager.getById(I.previouslyFocusedId);O&&t.windowManager.focus(O)}};return i.addEventListener("click",()=>{h(),C0(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const I=e.state==="minimized",O=t.windowManager.getFocused(),$=O&&O!==e?O.id:null;(I||$!==null)&&(s.set(e.id,{wasMinimized:I,previouslyFocusedId:$}),i.dataset.preview=""),I?Ih(e,i):O&&O!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const I=s.get(e.id);I&&m(I)}),J(v.DOCK_PEEK_CARD_ELEMENT,i,p)}function C0(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),Ih(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 L0(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*Sh}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",()=>{T0(e,n)}),o}function T0(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const N0=12,O0=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function D0(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of O0){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function R0(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(()=>x0(e))}function x0(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=N0;let r=0,a=0;n.topo-i&&(r=o-i-n.bottom),n.lefts-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 zn(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 Ah(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 Ch=new Map;function M0(e){const t=Ch.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 Ch.set(e,n),n}function W0(){const e=new Set,t=document.querySelectorAll('script[src*="load-scripts.php"]');for(const n of Array.from(t))for(const o of M0(n.src))e.add(o);return e}const P0=["-js","-js-before","-js-after","-js-extra","-js-translations"];function $0(e){return e?P0.some(t=>{const n=document.getElementById(e+t);return!!n&&n.tagName==="SCRIPT"}):!1}function yc(e){return e.url&&Ah(e.url)?!0:e.handle?W0().has(e.handle)||$0(e.handle):!1}const Ui=new Map,Lh=new Set;function pe(e,t){const n=Ui.get(e);if(n)return n;const o=t?.deps;if(o&&o.length>0){const i=a=>yc(a)?Promise.resolve():a.url?pe(a.url,{...a,deps:void 0}):(U0(a),Promise.resolve()),r=o.reduce((a,l)=>a.then(()=>i(l)),Promise.resolve(void 0)).then(()=>Th(e,t));return Ui.set(e,r),r}const s=Th(e,t);return Ui.set(e,s),s}function U0(e){if(e.handle){if(Lh.has(e.handle))return;Lh.add(e.handle)}for(const t of e.l10n??[])Rt(t);for(const t of e.before??[])Rt(t);for(const t of e.after??[])Rt(t)}function Th(e,t){return new Promise((n,o)=>{const s=`script[data-os-vendor="${B0(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=Ah(e);if(r){r.dataset.osVendor=e,r.dataset.loaded="1",n();return}if(yc({handle:t?.handle})){n();return}t?.translations&&Rt(t.translations);for(const l of t?.l10n??[])Rt(l);for(const l of t?.before??[])Rt(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??[])Rt(l);n()},{once:!0}),a.addEventListener("error",()=>{Ui.delete(e),a.remove(),o(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(a)})}function Rt(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function Nh(e){Rt(e)}function B0(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let Oh=0;function Dh(){return window.openStationItemVisibilityMenu??null}function F0(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function Rh(e){const t=Dh();if(t){t.openItemVisibilityMenu(e);return}const n=F0();if(!n)return;const o=++Oh;pe(n).then(()=>{o===Oh&&Dh()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const H0={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function G0(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function xh(e){return e==="core"?"core":e==="control"?"controls":"apps"}function Mh(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??H0[e.kind]}function Wh(e){return e==="rail"||e==="both"}function z0(e){return e==="desktop"||e==="both"}function j0(e,t,n){return Wh(e)?"rail":"hidden"}function Ph(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 V0(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 $h(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 Bi(){return window.wp?.os??null}function K0(){const e=Bi()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function q0(){return Bi()?.getNavItems?.()??[]}function Y0(e){const t=q0();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function X0(e){const t=Bi();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 Z0(e,t,n){const o=Array.isArray(e)?e:[e],s=K0().placement,i=[];for(const r of o){const a=typeof r=="string"?Y0(r):r;a&&i.push({item:a,placement:j0(Mh(a,s))})}X0(i)}function J0(e){const t=Bi();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:V0(n,e)})}const ct=["core","apps","controls"];function Uh(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=Mh(p,n.placement);if(Wh(g)){c.add(p.id);const h=xh(p.kind);G0(p.kind,o)==="sidebar"?r.push(p):i[h].push(p)}z0(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=>Ph(Q0($h(p)),n.order);for(const p of ct)i[p]=f(i[p]);return{dock:i,sidebar:f(r),desktop:Ph($h(a),n.order),ephemeral:l}}function Q0(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 eC=["action","action2","_wpnonce","nonce","delete_all"];function tC(e){const t=e.slice(e.lastIndexOf("/")+1);return/-new\.php$/.test(t)}function nC(e){if(tC(e.pathname))return!0;for(const t of eC)if(e.searchParams.has(t))return!0;return!1}function Bh(e){return xh(e.navKind??"app")}const Ue=class Ue{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/${++Ue.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 ct)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[Bh(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 ct){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(),A(v.DOCK_ITEM_REMOVED,{id:t,placement:this.rail}))}setBadge(t,n){const o=this._resolveTileElement(t);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(t):this.badgeOverrides.set(t,s);const i=o.querySelector(".os-dock__item-primary");Fh(i??o,s),_e.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),_e.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),_e.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,pi(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=Bh(t),o={type:"system",item:t};for(const a of ct)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(Ue.activeDragReset){const o=Ue.activeDragReset;Ue.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 ct)for(const s of this.zones[o])s.type==="menu"?this.items.push(s.item):this.systemItems.push(s.item);const t=this.buildHookContextBase();A(v.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of ct){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(),A(v.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(),Rh({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");Fh(d??r,l)}const c=this.artOverrides.get(i);c&&this._paintArt(r,i,c),A(v.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=J(v.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,pi(t.id))),r.addEventListener("click",l=>t.onOpen(l)),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=kh({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)),J(v.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=J(v.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,pi(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(Kt("%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=kh({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),J(v.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",$),document.removeEventListener("pointerup",U),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",K,!0),window.removeEventListener("blur",Q),document.removeEventListener("visibilitychange",Z),u=-1,f=null},h=o==="controls"?this.systemHost:this.itemHost,m=C=>!!C&&C instanceof HTMLElement&&C.classList.contains("os-dock__item")&&C.dataset.zone===o&&!!C.dataset.navId&&C.dataset.navLocked===void 0,_=C=>{for(const D of Array.from(h.children))D instanceof HTMLElement&&D!==t&&m(D)&&C(D)},I=()=>{const C=[];for(const D of Array.from(h.children))m(D)&&C.push(D.dataset.navId);return C},O=C=>{_(D=>{const V=C.get(D);if(!V)return;const j=D.getBoundingClientRect(),te=V.left-j.left,N=V.top-j.top;if(Math.abs(te)<.5&&Math.abs(N)<.5)return;D.style.transition="none",D.style.transform=`translate(${te}px, ${N}px)`,D.offsetHeight,D.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",D.style.transform="";const L=()=>{D.style.transition="",D.style.transform="",D.removeEventListener("transitionend",L)};D.addEventListener("transitionend",L)})},$=C=>{if(u!==-1&&C.pointerId!==u)return;if(!r){const H=C.clientX-a,z=C.clientY-l;if(H*H+z*z<5*5)return;r=!0,c=I(),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=C.clientX-a,V=C.clientY-l;t.style.transform=`translate(${D}px, ${V}px)`;const te=document.elementFromPoint(C.clientX,C.clientY)?.closest(".os-dock__item");if(!te||te===t||!m(te))return;const N=te.getBoundingClientRect();let L;this.orientation==="bottom"?L=C.clientX{M.set(H,H.getBoundingClientRect())});let P=!1;if(L?te!==t.nextSibling&&(h.insertBefore(t,te),P=!0):te.nextSibling!==t&&(h.insertBefore(t,te.nextSibling),P=!0),P){t.style.transform="";const H=t.getBoundingClientRect();a=H.left+H.width/2,l=H.top+H.height/2,t.style.transform=`translate(${C.clientX-a}px, ${C.clientY-l}px)`,O(M)}},S=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",U),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",K,!0),window.removeEventListener("blur",Q),document.removeEventListener("visibilitychange",Z),u=-1,f=null,r=!1,Ue.activeDragReset===g&&(Ue.activeDragReset=null)},R=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const C=()=>{t.style.transition="",t.removeEventListener("transitionend",C)};t.addEventListener("transitionend",C)},W=C=>{J0(C)},U=C=>{if(u!==-1&&C.pointerId!==u)return;if(!r){S();return}p=!0;const D=I();R(),S(),D.length===c.length&&D.every((j,te)=>j===c[te])||W(D),setTimeout(()=>{p=!1},200)},F=C=>{if(!(C&&u!==-1&&C.pointerId!==u)){if(r&&d!==void 0){const D=new Map;_(V=>{D.set(V,V.getBoundingClientRect())}),h.insertBefore(t,d),O(D)}R(),S()}},K=C=>{C.key==="Escape"&&F()},Q=()=>F(),Z=()=>{document.visibilityState!=="visible"&&F()};t.addEventListener("pointerdown",C=>{if(!(C.button!==0||Vt())){if(Ue.activeDragReset){const D=Ue.activeDragReset;Ue.activeDragReset=null,D()}(r||u!==-1)&&g(),a=C.clientX,l=C.clientY,u=C.pointerId,r=!1,Ue.activeDragReset=g,document.addEventListener("pointermove",$),document.addEventListener("pointerup",U),document.addEventListener("pointercancel",F),document.addEventListener("keydown",K,!0),window.addEventListener("blur",Q),document.addEventListener("visibilitychange",Z)}}),t.addEventListener("click",C=>{p&&(C.preventDefault(),C.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=fi(s);a!==null&&(t=a,i=!0),r=Na(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if($i(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($i(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 f=new URL(t,window.location.href);o=(f.pathname.split("/").pop()||"")+f.search}catch{return null}if(!o)return null;const s=n.querySelectorAll("li.menu-top > a");let i=null;for(const f of Array.from(s))if(f.href.endsWith(o)){i=f.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 f=document.createElement("img");return f.className="os-dock__item-img",f.src=a.src,f.alt="",f.setAttribute("aria-hidden","true"),f}const l=r.className.match(/\bdashicons-[\w-]+\b/);if(l&&l[0]!=="dashicons-before"){const f=document.createElement("span");return f.className=`dashicons ${l[0]}`,f.setAttribute("aria-hidden","true"),f}const d=window.getComputedStyle(r,"::before").backgroundImage;if(d&&d!=="none"&&!d.includes('url("")'))return this._makeSvgIcon(d);const u=window.getComputedStyle(r).backgroundImage;return u&&u!=="none"&&!u.includes('url("")')?this._makeSvgIcon(u):null}createLetterBadge(t){const n=document.createElement("span");n.className="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=wc(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(t,n,o){const s=J(v.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("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=Tn(n.url);if(o){this.prewarmNativeWindow(o);return}try{const i=new URL(n.url,window.location.href);if(i.origin!==window.location.origin||nC(i)||Ln(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){if(this.windowManager.getById(t))return;window.wp?.os?.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(zn(t.url)||Me(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(zn(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=Tn(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:Tn(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?.(v.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.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?.(v.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.WINDOW_RESTORED,this.hooksNamespace);for(const t of this.attentionTimers.values())window.clearTimeout(t);this.attentionTimers.clear();for(const t of this.peekTeardowns.values())t();for(this.peekTeardowns.clear(),this.tooltip.remove();this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.itemElements.clear(),this.systemItemElements.clear(),this.systemItems=[],this.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)}};Ue.instanceCounter=0,Ue.activeDragReset=null;let Fi=Ue;function Fh(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(Kt("%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(Kt("%d notification","%d notifications",t),t)),e.appendChild(s)}const Hh=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),vc={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 Fi(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[Hh]: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 Gh(e){if(!e)return null;const n=e[Hh];return n instanceof Fi?n:null}function oC(){Au(vc)}const zh="os-desktop-theme-css",sC="os-desktop-theme-inline-css",bc="data-os-desktop-theme-css",jh="os-desktop-theme-changed";function Vh(){return document.getElementById("os-shell")}function Kh(){const e=[];for(const t of[zh,sC]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${bc}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function Ec(){for(const e of Kh())e.remove()}function iC(e){const t=Vh();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:Kh().length>0}function qh(e){if(e.cssUrl!==""){const t=document.createElement("link");t.id=zh,t.rel="stylesheet",t.href=e.cssUrl,t.setAttribute(bc,e.slug),document.head.appendChild(t)}else if(e.cssText!==""){const t=document.createElement("style");t.setAttribute(bc,e.slug),t.textContent=e.cssText,document.head.appendChild(t)}}function Yh(e){const t=document.body;if(!t)return;const n=[];t.classList.forEach(o=>{o.startsWith("os-desktop-theme-")&&n.push(o)});for(const o of n)(e===null||o!==`os-desktop-theme-${e}`)&&t.classList.remove(o);e!==null&&t.classList.add(`os-desktop-theme-${e}`)}function _c(e){const t=Mn(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:La(o),i=s?s.slug:null;if(i===n)return;const r=Vh();if(!s)r?.removeAttribute("data-os-desktop-theme"),Yh(null),Ec(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!iC(s.slug))if(s.cssDeferred&&s.cssUrl===""&&s.cssText===""){const l=s.slug,c=()=>df().then(()=>{if(Mn().state.activeId!==l)return;const d=La(l);if(!d||d.cssDeferred)throw new Error(`theme "${l}" resolved without a stylesheet`);Ec(),qh(d)}).catch(d=>{Mn().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 Ec(),qh(s);r?.setAttribute("data-os-desktop-theme",s.slug),Yh(s.slug),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};A(v.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(jh,{detail:a}))}function rC(e={}){const t=e.deactivate??(()=>_c(""));return function(o){wS(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=Mn().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const aC="",cC="system-default",lC={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function dC(e,t,n={}){const o=t===aC,s=o?null:La(t);if(!o&&!s)return{};const i=o?cC:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=uS(o?lC:s.recommendedOsSettings),l=Object.keys(a);if(l.length===0)return{};const c=e,d={};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 Xh(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}function uC(e,t){Fn({id:tf,label:b("Custom gradient"),type:"css",preview:Xh(e()),description:b("Mix your own two-colour gradient and set the angle — your desk, your palette."),resolveValue:()=>Xh(e())})}function fC(e){if(!e.customImage){Yo(xo)&&ah(xo);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`,o=Yo(xo);o&&o.type==="css"&&o.value===n||Fn({id:xo,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 pC(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 Zh(e){return JSON.parse(JSON.stringify(e))}function hC(e,t){return e===t?!0:typeof e!="object"||typeof t!="object"||e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}class mC{constructor(t){this.listeners=new Set,this.baseState=null,this.overridePatch=null,this.layer=t,this.state=i0(),document.addEventListener("os-settings-save-lifecycle",n=>{const o=n.detail;!o||(window.wp?.os?.windowManager?.getById(Ct)?.markActivity(o.phase,{error:o.error}),o.phase!=="failed"||!o.rolledBackTo)||(this.state=o.rolledBackTo,this.apply(),this.notify())}),uC(()=>this.state)}getOsSettingsSnapshot(){return on(this.state)}subscribeOsSettings(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}apply(){const t=document.getElementById("os-shell");if(!t)return;KA(this.state.wallpaperSettings),fC(this.state);const n=Yo(this.state.wallpaper)||Yo(ka())||Yo(Sa)||cc()[0];n&&this.layer.apply(n);const o=li(),s=o.find(g=>g.id===this.state.accent)??o[0],i=this.state.accent===nf?this.state.customAccent:s.value,r=Ia.find(g=>g.id===this.state.dockSize)??Ia[1],a=Aa.find(g=>g.id===this.state.windowRadius)??Aa[1],l=document.body;l.style.setProperty("--wp-admin-theme-color",i),l.style.setProperty("--os-ui-accent",i);const c=pC(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=di.find(g=>g.id===this.state.adminBarMode)??di[0];for(const g of di)document.body.classList.toggle(`os-admin-bar-${g.id}`,g.id===f.id);const p=g=>(ui.find(h=>h.id===g)??ui[0]).id;document.getElementById(YA)?.setAttribute(Xo,p(this.state.dockBehavior)),document.getElementById(uh)?.setAttribute(Xo,p(this.state.sideDockBehavior)),n0(),qk(),t.setAttribute("data-os-layout",this.state.desktopLayout),O_(this.state.dockRailRenderer),_c(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=Zh(t),this.state={...n,...Zh(t)};this.apply(),this.notify()}save(t={}){p0(this._persistableState(),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))hC(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=fc(o,this.state),i=yh.filter(r=>r in o);Object.assign(this.state,s),this.save(n),i.some(r=>a0.has(r))&&this.apply()}applyThemeRecommendations(t){const n=dC(this.state,t,{force:!0});return Object.keys(n).length>0&&(this.save(),this.apply()),n}reset(t={}){const n=Eh();n.wallpaper=ka(),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 gC="os-network-admin";function wC(e,t){const n=e.networkAdmin;return!n||e.isNetworkAdmin?null:{id:gC,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 Jh(e){return!!e&&(e.metaKey||e.ctrlKey||e.shiftKey||e.button===1)}function Sc(e,t){if(Jh(t)){window.open(e,"_blank","noopener,noreferrer");return}window.location.assign(e)}function yC(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 vC=220,bC=360,EC=4e3,kc="openstation-hop-direction",Ic="os-shell--arriving",Qh="os-shell--revealing";function Ac(){return document.getElementById("os-shell")}function em(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function _C(e){try{window.sessionStorage.setItem(kc,e)}catch{}const t=Ac();return!t||em()?Promise.resolve():(t.classList.add(`os-shell--hop-out-${e}`),new Promise(n=>{window.setTimeout(n,vC)}))}function SC(){try{const e=window.sessionStorage.getItem(kc);return window.sessionStorage.removeItem(kc),e==="next"||e==="prev"?e:null}catch{return null}}function kC(e=null){const t=Ac();if(!t||!t.classList.contains(Ic))return;const n=SC()??e;n&&t.classList.add(`os-shell--arriving-${n}`),window.setTimeout(tm,EC)}function tm(){const e=Ac();!e||!e.classList.contains(Ic)||(e.classList.remove(Ic,"os-shell--arriving-next","os-shell--arriving-prev"),!em()&&(e.classList.add(Qh),window.setTimeout(()=>e.classList.remove(Qh),bC)))}function jn(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function IC(e){return!!e&&e.__wpdHtml===!0}const AC="$$wpd$$",De=/\$\$wpd\$\$(\d+)\$\$/g,CC="$$wpd-node$$",LC=/^\$\$wpd-node\$\$(\d+)\$\$$/,TC=new Set(["style","script","textarea","title"]);function NC(e){let t="",n=!1,o=null,s=!1,i=null,r="",a=!1;for(let l=0;l",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,TC.has(r)&&(i=r),r=""):a&&(/[a-zA-Z0-9-]/.test(u)?r+=u.toLowerCase():a=!1);continue}if(c.startsWith("`)}return t}const nm=new WeakMap;function om(e){const t=nm.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=NC(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(De.test(g))if(De.lastIndex=0,h==="@"){const m=De.exec(g);De.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=De.exec(g);De.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=De.exec(g);De.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else{const m=[],_=[];let I=0,O;for(De.lastIndex=0;(O=De.exec(g))!==null;)m.push(g.slice(I,O.index)),_.push(Number(O[1])),I=O.index+O[0].length;m.push(g.slice(I)),o.push({path:l,kind:"attr",name:p,template:m,valueIndices:_}),u.setAttribute(p,"")}}}const c=Array.from(a.childNodes);let d=0;for(let u=0;um&&I.push(document.createTextNode(g.slice(m,_.index)));const $=document.createTextNode("");I.push($),O.push({path:[...l,p+I.length-1],kind:"node",valueIndex:Number(_[1])}),m=_.index+_[0].length}m{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 nm.set(e,r),r}const sm=new WeakMap;function OC(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function DC(e,t){const n=sm.get(t);if(n&&n.strings===e.strings&&OC(n,t)){Hi(n.parts,e.values);return}const o=om(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),Hi(i,e.values),sm.set(t,{strings:e.strings,parts:i,nodes:r})}function Hi(e,t){for(const n of e)if(n.kind==="node")Gi(n.child,t[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;sString(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=rm(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&&DC(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(!Gt._lightStylesAdopted.has(t)){Gt._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)}}}};Gt.props=[],Gt.styles=[],Gt.shadow=!0,Gt._lightStylesAdopted=new WeakSet;let sn=Gt;function Jo(e,t){customElements.get(e)||customElements.define(e,t)}function rm(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function PC(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const $C=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function Le(e,...t){let n=e[0];for(let o=1;o.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}}`,HC=Le` .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}}`,GC=Le` .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%}}`,zC=Le` .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}}`,jC=Le` 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}}`,VC=Le` 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}}`,KC=Le` @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}}`;Le` ${Cc} ${UC} ${am} ${BC} ${FC} ${HC} ${GC} ${zC} ${jC} ${VC} ${KC} `;const qC=Le` ${Cc}: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}}`,YC=Le` ${Cc} ${am}: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}`,Xs=class Xs extends sn{render(){return this.setAttribute("role","radio"),jn` `}_onPick(){this.emit("os-segment-pick",{value:this.value})}};Xs.props=["value"],Xs.styles=[YC],Xs.help=void 0;let Lc=Xs;Jo("os-segment",Lc);const Zs=class Zs extends sn{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()}),jn``}};Zs.props=["value","label"],Zs.styles=[qC],Zs.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width 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:' 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:jn` Small Medium Large `};let Tc=Zs;Jo("os-segmented",Tc);const XC="openstation_overview",ZC="openstation_hop_from";function cm(e,t){try{const n=new URL(e,window.location.href);return n.searchParams.set(XC,"1"),t&&n.origin!==window.location.origin&&n.searchParams.set(ZC,t),n.toString()}catch{return e}}function Nc(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 Oc(e,t,n={}){const o=n.hop??Sc,s=Nc(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=cm(a.shellUrl,c),u=n.mint&&a.foreign?n.mint(a.shellUrl,c).catch(()=>null):Promise.resolve(null);return Promise.all([_C(c),u]).then(([,f])=>o(f??d)),!0}function JC(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()||oc(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=Nc(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(),Oc(o,d.value,e)};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)}function lm(){const e=document.createElement("span");return e.className="dashicons dashicons-external os-site-switcher__mark",e.setAttribute("aria-hidden","true"),e}function QC(e,t={}){const n=t.hop??Sc,o=Nc(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(lm());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(lm());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(!Jh(c))return;c.preventDefault(),c.stopPropagation();const f=cm(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&&Oc(e,d,t)}),r}function eL(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 tL(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 zi=new Map;function dm(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}zi.set(e.id,e)}function nL(){return Array.from(zi.keys())}async function Dc(e){if(!e||e.length===0)return;const t=e.filter(n=>!zi.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${nL().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=zi.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():pe(o.url)}))}const oL="os-wallpaper-light",sL=.185,Vn=32,iL=3e3,rL=new Set([xo,tf]),um=new Map;function fm(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 pm(e){return e>sL?"light":"dark"}function aL(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 cL(e){const t=/url\(\s*(['"]?)([^'")]+)\1\s*\)/i.exec(e);return t?t[2].trim():null}function lL(e){const t=aL(e);if(t.length===0)return null;const n=t.reduce((o,[s,i,r])=>o+fm(s,i,r),0);return pm(n/t.length)}async function dL(e){const t=um.get(e);if(t)return t;try{const n=new Image;if(n.crossOrigin="anonymous",!await new Promise(d=>{const u=setTimeout(()=>d(!1),iL),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=Vn,s.height=Vn;const i=s.getContext("2d");if(!i)return null;i.drawImage(n,0,0,Vn,Vn);const{data:r}=i.getImageData(0,0,Vn,Vn);let a=0,l=0;for(let d=0;d"u")return"";const t=document.getElementById("os-shell")??document.body;return t?t.style.getPropertyValue("--os-bg").trim():""}function pL(e){typeof document>"u"||!document.body||document.body.classList.toggle(oL,e==="light")}function hm(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:hL(),visible:!document.hidden,settings:VA(e)}}function hL(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class mm{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){uL(t).then(o=>{n===this.generation&&pL(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,A(v.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){A(v.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[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(hm(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=hm(t.id,this.pluginUrl);A(v.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?Dc(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},A(v.WALLPAPER_MOUNTED,{id:t.id,container:this.element,ctx:o}),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(mL(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&&A(v.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){A(v.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="",A(v.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),A(v.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function mL(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const gm=ae("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),Kn=gm.state.seed,Rc=gm.state.listeners;function xc(e){Oe("Game",Yt(e,bm),e);const t=Kn.findIndex(n=>n.id===e.id);t>=0?Kn[t]=e:Kn.push(e),ym()}function wm(e){const t=Kn.findIndex(n=>n.id===e);t>=0&&(Kn.splice(t,1),ym())}function gL(e){return Rc.add(e),()=>{Rc.delete(e)}}function ym(){const e=Array.from(Rc);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function vm(){const e=Kn.slice(),t=J(v.GAMES,e);return Array.isArray(t)?t.filter(wL):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function ji(e){return vm().find(t=>t.id===e)}const bm=[{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 wL(e){return Yt(e,bm).length===0}const Em=new Set;function Vi(e){if(Em.has(e))return;const n=window.openStationConfig?.deferredStyles?.[e];if(!n?.url)return;Em.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 yL="desktop-mode/games";function vL(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function Qo(e,t={},n={}){const{restUrl:o,restNonce:s}=vL(),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(rt(o,e),{...t,headers:i,credentials:"same-origin"},{source:yL,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok)throw mt(r.status,a);return a}function bL(e,t,n={}){return Qo(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function EL(){return Qo("desktop-mode/v1/games/playtime")}function _L(e,t,n={}){return Qo(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function SL(e){return Qo(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function kL(e,t,n={}){return Qo(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const IL=6e4;function AL(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,_L(e,l,{windowId:t.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,IL);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const qn=ae("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function CL(){return qn.state}function Mc(e){const t=qn.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&&TL()}function LL(e){return qn.state.listeners.add(e),()=>{qn.state.listeners.delete(e)}}function TL(){for(const e of Array.from(qn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function NL(){return Array.from(qn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function _m(){return window.wp?.os??{}}const OL=760,DL=560,RL=480,xL=380;function ML(){const e=window.openStationConfig?.gameStyleHandles??[];for(const t of e)Vi(t)}async function WL(e){if(typeof e.render=="function")return e;const t=_m().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 xc(s),s}async function Sm(e,t={}){const n=_m(),o=ji(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);if(ML(),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 kL(h,g,{windowId:s}).then(({challenge:m})=>{Mc([m]),f(g,h)})}return bL(e,g,{windowId:s}).then(()=>f(g))};try{await n.registerWindow({id:s,title:o.title,icon:o.icon,width:o.window?.width??OL,height:o.window?.height??DL,minWidth:o.window?.minWidth??RL,minHeight:o.window?.minHeight??xL,render:async g=>{const h=await WL(o),m=h.render;if(typeof m!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);const _={windowId:s,container:g,config:h.config??{},challenge:t.challenge,submitScore:p,close:()=>{n.windowManager?.getById(s)?.close()}};d=AL(e,{windowId:s});const I=m(_);return()=>{try{I?.()}finally{u(),c()}}}})}catch(g){throw u(),c(),g}}const km={register:xc,unregister:wm,list:vm,get:ji,subscribe:gL,launch:Sm,getPlaytime:()=>EL().then(e=>e.playtime)},Yn=ae("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function PL(e){Yn.state.pending.set(e.id,e)}function Ki(e){Yn.state.pending.delete(e)}function $L(e){return(window.openStationWallpapers||{})[e]??null}function Im(e){const t=Yn.state.inflight.get(e);if(t)return t;const n=Yn.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 A(v.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=$L(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return A(v.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{Fn(s)}catch(i){return A(v.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return Ki(n.id),s})().finally(()=>{Yn.state.inflight.delete(e)});return Yn.state.inflight.set(e,o),o}function UL(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 Im(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await Dc(o.needs),o.mount(t,n))}}}function BL(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){Fn(a),n.add(r.id),t.apply();return}if(!r.scriptUrl)return;PL(r);const l=r.preview!==""||r.value!=="";if(l){try{Fn(UL(r))}catch(c){A(v.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:c}),Ki(r.id);return}n.add(r.id)}if(!l||t.state.wallpaper===r.id){const c=await Im(r.id);if(!l){if(!c){Ki(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(ah(r),Ki(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 FL(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 HL(){const e=new Set,t=o=>{try{const s=ji(o.id),i=FL(o);xc(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)&&(wm(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 yt=ae("desktop-mode/heartbeat-bus",()=>({suppliers:new Map,subscribers:new Map,booted:!1})),Re={contribute(e,t){return yt.state.suppliers.set(e,t),()=>{yt.state.suppliers.get(e)===t&&yt.state.suppliers.delete(e)}},subscribe(e,t){let n=yt.state.subscribers.get(e);return n||(n=new Set,yt.state.subscribers.set(e,n)),n.add(t),()=>{n.delete(t)}}};function GL(){if(yt.state.booted)return;yt.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 yt.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 yt.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 qi=null,Yi={installHintDismissed:!1,notificationsEnabled:!1};const Wc=new Set;function Am(e){if(!e){qi=null;return}qi=e,Yi={...e.state},Lm()}function es(){return{...Yi}}function Pc(e){if(Yi={...Yi,...e},Lm(),!qi)return es();const t=JSON.stringify(e),n=zL();return fetch(qi.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)}),es()}function Cm(e){return Wc.add(e),()=>{Wc.delete(e)}}function Lm(){const e=es();for(const t of Array.from(Wc))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function zL(){return window.openStationConfig?.restNonce??""}const jL=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:es,initPwaState:Am,subscribePwaState:Cm,updatePwaState:Pc},Symbol.toStringTag,{value:"Module"}));function $c(e){const t=_e.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}),_e.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=Tm(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){Pc({notificationsEnabled:!0}),o=Tm(t),o||r();return}r()}}),i)}function Tm(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 _e.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function VL(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&Pc({notificationsEnabled:!0}),e}function KL(){return typeof Notification>"u"?"unsupported":Notification.permission}function qL(e){return ji(e)?.title||e}const Nm=new Set,Om=new Set;async function YL(e){const{challenge:t}=await SL(e.id);Mc([t]),await Sm(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function XL(e){const t=le(b("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,qL(e.game),String(e.scoreToBeat));$c({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:()=>{YL(e).catch(n=>{ue({message:n instanceof Error?n.message:b("Could not accept the challenge.")})})}}})}function ZL(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));$c({title:b("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),ue({message:n})}function JL(e){const{currentUserId:t}=e;if(!t)return;Re.contribute("openstation_games_subscribe",()=>({challengesVersion:CL().version})),Re.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&Mc(o.challenges)});const n=()=>{for(const o of NL())o.state==="pending"&&o.recipientId===t&&!Nm.has(o.id)&&(Nm.add(o.id),XL(o)),o.state==="completed"&&o.challengerId===t&&!Om.has(o.id)&&(Om.add(o.id),ZL(o))};LL(n),n()}const Dm=/^[a-z0-9_/-]+$/,Rm=ae("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),rn=Rm.state.registry,QL=Rm.state.listeners;function Xn(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)"):Dm.test(n)||t.push(`slug (must match ${Dm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.run!="function"&&t.push("run (must be a function)")),Oe("Command",t,e),rn.set(n,{...e,slug:n}),Uc()}function xm(e){rn.delete(e.toLowerCase())&&Uc()}function Xi(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(rn.entries()))o.owner===e&&(rn.delete(n),t++);return t>0&&Uc(),t}function Mm(){return Array.from(rn.values())}function eT(){const e=[];for(const t of rn.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function tT(e){return rn.get(e.toLowerCase())??null}function Uc(){const e=Array.from(QL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function nT(){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){A(v.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const 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 Mm())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))xm(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Wm=ae("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),ts=Wm.state.registry,oT=Wm.state.listeners;function Pm(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}ts.set(t,{...e,id:t}),Bc()}function $m(e){ts.delete(e.toLowerCase())&&Bc()}function sT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ts.entries()))o.owner===e&&(ts.delete(n),t++);return t>0&&Bc(),t}function Um(){return Array.from(ts.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Bc(){const e=Array.from(oT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function iT(){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){A(v.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const 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=>{sT(r);const a=n.get(r);if(a){const l=new Set(Um().map(c=>c.id));for(const c of a)l.has(c)&&$m(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 Bm=ae("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),ns=Bm.state.registry,rT=Bm.state.listeners,Fm=/^[a-z0-9_/-]+$/;function os(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Fm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Fm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (missing)"),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)")),Oe("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();ns.set(n,{...e,id:n}),Zi()}function Hm(e){ns.delete(e.toLowerCase())&&Zi()}function aT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ns.entries()))o.owner===e&&(ns.delete(n),t++);return t>0&&Zi(),t}function cT(){return Array.from(ns.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Zi(){const e=Array.from(rT);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"&&Zi()});function lT(){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){A(v.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(aT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Gm=ae("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),ss=Gm.state.registry,dT=Gm.state.listeners,zm=/^[a-z0-9_/-]+$/;function Fc(){for(const e of Array.from(dT))try{e()}catch{}}function jm(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):zm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${zm} — 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)")),Oe("WindowAction",t,e);const n=e.id.trim().toLowerCase();ss.set(n,{...e,id:n}),Fc()}function uT(e){ss.delete(String(e||"").toLowerCase())&&Fc()}function fT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ss.entries()))o.owner===e&&(ss.delete(n),t++);return t>0&&Fc(),t}function pT(){return Array.from(ss.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function hT(){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){A(v.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)||(fT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function Vm(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function mT({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)=>Vm(r[0])-Vm(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 Km(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 qm(e){const t=ze(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=J(v.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(Km):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(Km))}function Hc(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function gT(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function wT(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=qm(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=mT({items:s,onPick:c=>{r(),gT(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 yT({manager:e,openUrl:t}){os({id:"desktop-mode/related-entities",label:b("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>qm(n.id).length>0,render:(n,o)=>{Hc(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")){Hc(o.element);return}wT(n,o,t)})}}),ee(v.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(Hc(o.element),o.renderCustomTitleBarButtons?.())})}const Gc="os-broadcast",Ym="os-broadcast",Xm=window.location.origin;let zc=null;function vT(e){zc=e}function Ji(e,t){const n=String(J("os.broadcast.topic",e,{payload:t})??e),o=J("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Gc,{detail:s})),A(v.BROADCAST,s),_e.publish(n,o),!zc)return;const i={type:Ym,topic:n,payload:o};for(const r of zc._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Xm)}catch{}}}function Zn(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){A(v.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Gc,n),()=>document.removeEventListener(Gc,n)}function bT(){window.addEventListener("message",e=>{if(e.origin!==Xm)return;const t=e.data;!t||t.type!==Ym||t._fromParent||typeof t.topic=="string"&&Ji(t.topic,t.payload)})}function Zm(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||Ji(`os.${i}.changed`,{source:o,action:t,ids:s})}const ET=new Set(["saved","no-editor","not-dirty","error"]);let Jm=0;function Qm(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function _T(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Jm+=1;const o=`os-editor-preview-${Date.now()}-${Jm}`;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"&&ET.has(d.status)?d.status:"error",f=Qm(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 We=ae("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),ST=400,eg=1500;function is(e){return e?`${e.type}:${e.id}`:""}function kT(e){for(const t of We.state.pairings.values())if(t.previewWindowId===e)return t}function IT(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function AT(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 Qi(e,t,n,o){We.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(ng(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})),A(v.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function jc(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||ze(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?.()},ST)}function CT(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=Zn(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||jc(e,t)})}let tg=0;function ng(e,t){if(!t.watchId)return;const n=e.getById(t.editorWindowId);try{n?.iframe?.contentWindow?.postMessage({type:"os-editor-live-unwatch",watchId:t.watchId},window.location.origin)}catch{}t.watchId=""}function og(e,t,n){ng(e,t);const o=J(v.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:eg},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;tg+=1;const i=`${t.previewWindowId}-watch-${tg}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:eg},window.location.origin),t.watchId=i}catch{}}let LT=_T;async function TT(e,t){const n=We.state.pairings.get(t.id);if(n){Qi(e,n,"toggled","close");return}if(We.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=ze(t.id);if(!o?.previewUrl){ue({message:b("No preview is available for this content.")});return}We.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=IT();s||t.applySnap?.("left");const i=LT(t);i.then(f=>{f.status==="error"&&ue({message:b("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{We.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=J(v.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)||is(ze(t.id))!==is(o)){e.getById(l.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:l.id,postKey:is(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};CT(e,d,o),og(e,d,o),We.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})),A(v.EDITOR_PREVIEW_OPENED,u),i.then(f=>{We.state.pairings.get(t.id)===d&&f.status==="saved"&&jc(e,d,f.previewUrl)})}function NT({manager:e}){os({id:"desktop-mode/editor-preview",label:b("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!ze(t.id)?.previewUrl||AT(t)),render:(t,n)=>{if(!ze(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=We.state.pairings.has(n.id),s=We.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(),TT(e,n)})}}),ee(v.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=We.state.pairings.get(t.windowId);n&&is(t.content)!==n.postKey&&Qi(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),ee(v.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=We.state.pairings.get(t.windowId);if(n){Qi(e,n,"editor-closed","destroy");return}const o=kT(t.windowId);o&&Qi(e,o,"preview-closed","none")}),ee(v.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=We.state.pairings.get(t.windowId);if(n){const o=ze(t.windowId);o&&is(o)===n.postKey&&og(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 We.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){jc(e,o,Qm(n.previewUrl));return}}})}const sg=16,Ve=16,OT=1100,DT=860;function RT(e,t){const n=Math.max(0,t.width-Ve*2),o=Math.max(320,Math.min(OT,Math.round(n*.5))),s=Math.max(200,Math.min(DT,Math.round(t.height*.8))),i=xT(e.y,Ve,Math.max(Ve,t.height-s-Ve)),r=e.x+e.width+sg;if(r+o+Ve<=t.width)return{x:r,y:i,width:o,height:s};const a=e.x-sg-o;if(a>=Ve)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(Ve,t.width-o-Ve):Ve,y:u?Math.max(Ve,t.height-s-Ve):Ve,width:o,height:s}}function xT(e,t,n){return Math.min(Math.max(e,t),n)}function MT(e){return`revisions-${String(e.type).replace(/\//g,"-")}-${e.id}`}function WT(e){const t=e?.revisionCount;return typeof t=="number"&&t>0?le(b("View revisions (%d)"),t):b("View revisions")}function PT(e,t,n){if(Li(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?{}:RT({x:o.offsetLeft,y:o.offsetTop,width:o.offsetWidth,height:o.offsetHeight},{width:s.clientWidth,height:s.clientHeight})}async function $T(e,t){const n=ze(t.id);if(!n?.revisionsUrl){ue({message:b("No revisions are available for this content.")});return}const o=MT(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},...PT(e,t.id,o)};const r=J(v.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})),A(v.REVISIONS_OPENED,a)}function UT({manager:e}){jm({id:"desktop-mode/view-revisions",label:t=>WT(ze(t.id)),icon:"dashicons-backup",order:60,isVisible:t=>!!ze(t.id)?.revisionsUrl,onSelect:t=>{$T(e,t)}})}const ig="none",rg=ae("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),rs=rg.state.registry,Vc=rg.state.listeners,ag=/^[a-z0-9_/-]+$/;function er(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):ag.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===ig&&t.push('id ("none" is reserved)'):t.push(`id (must match ${ag} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.className!="string"&&typeof e.apply!="function"&&t.push("className|apply (at least one must be provided — a CSS class to toggle or an apply callback)")),Oe("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();rs.set(n,{...e,id:n}),qc()}function BT(e){rs.delete(e.toLowerCase())&&qc()}function FT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(rs.entries()))o.owner===e&&(rs.delete(n),t++);return t>0&&qc(),t}function Kc(){const e=Array.from(rs.values()),t=J(v.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 cg(e){return Kc().find(t=>t.id===e)}function HT(e){return Vc.add(e),()=>{Vc.delete(e)}}function qc(){const e=Array.from(Vc);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}er({id:"darken",label:b("Darken"),description:b("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),er({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"}),er({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 GT(){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){A(v.SHELL_ERROR,{scope:"unfocus-effect-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(FT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const zT="none",lg=ae("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),as=lg.state.registry,jT=lg.state.listeners,dg=/^[a-z0-9_/-]+$/;function ug(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):dg.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===zT&&t.push('id ("none" is reserved)'):t.push(`id (must match ${dg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.mount!="function"&&t.push("mount (not a function)")),Oe("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();as.set(n,{...e,id:n}),Xc()}function VT(e){as.delete(e.toLowerCase())&&Xc()}function KT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(as.entries()))o.owner===e&&(as.delete(n),t++);return t>0&&Xc(),t}function Yc(){const e=Array.from(as.values()),t=J(v.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 Xc(){const e=Array.from(jT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}function qT(){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){A(v.SHELL_ERROR,{scope:"window-link-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(KT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}let an=null;function fg(){if(an)return an;if(window.openStationWindowLinkVisuals)return an=Promise.resolve(!0),an;const t=window.openStationConfig?.windowLinkVisualsBundleUrl;return t?(an=pe(t).then(()=>!0).catch(n=>{throw an=null,n}),an):Promise.resolve(!1)}const Zc="svg-splines";function YT(){if(Yc().some(t=>t.id===Zc))return;const e=async t=>{if(!await fg())return;const o=Yc().find(s=>s.id===Zc);if(!(!o||o.mount===e))return o.mount(t)};ug({id:Zc,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 Jc="data-desktop-unfocus-effect",Qc="data-desktop-unfocus-effect-class";let pg=!1;function XT(e){return e.querySelector("canvas")!==null}function ZT(e){return e.state==="snapped-left"||e.state==="snapped-right"}function JT({manager:e,osSettings:t}){if(pg)return;pg=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(Qc);l&&(r.classList.remove(l),r.removeAttribute(Qc));const c=r.getAttribute(Jc);c&&cg(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(Jc)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Qc,a.className)),r.setAttribute(Jc,a.id),a.apply?.(r)},i=()=>{const r=n===ig?void 0:cg(n),a=Kc();for(const l of e.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(ZT(l)||XT(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()}),HT(()=>i()),i()}function QT(){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){A(v.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(C_(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function eN(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 hg=ae("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),cs=hg.state.registry,tN=hg.state.listeners,mg=/^[a-z0-9_/-]+$/;function gg(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)"):mg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${mg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!e.tokens||typeof e.tokens!="object")t.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(e.tokens))if(!o.startsWith("--")){t.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof e.match!="function"&&t.push("match (must be a function)")}Oe("WindowTheme",t,e);const n=e.id.trim().toLowerCase();cs.set(n,{...e,id:n}),el()}function wg(e){cs.delete(e.toLowerCase())&&el()}function nN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(cs.entries()))o.owner===e&&(cs.delete(n),t++);return t>0&&el(),t}function yg(){return Array.from(cs.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function el(){const e=Array.from(tN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function oN(){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){A(v.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 yg())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{gg({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){A(v.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)wg(p),o.delete(p);nN(u),e.delete(u)}a(c);for(const u of l)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const vg=ae("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),ls=vg.state.registry,sN=vg.state.listeners,bg=/^[a-z0-9_/-]+$/;function ds(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):bg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${bg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)"),typeof e.render!="function"&&(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (required when render is omitted)"),typeof e.match!="function"&&t.push("match (must be a function)"),e.placement!==void 0&&e.placement!=="left"&&e.placement!=="right"&&e.placement!=="controls"&&t.push('placement (must be "left", "right", or "controls")')),Oe("WindowControl",t,e);const n=e.id.trim().toLowerCase();ls.set(n,{...e,id:n}),tl()}function Eg(e){ls.delete(e.toLowerCase())&&tl()}function iN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ls.entries()))o.owner===e&&(ls.delete(n),t++);return t>0&&tl(),t}function _g(){return Array.from(ls.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(sN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function rN(){ds({id:"core/minimize",label:b("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),ds({id:"core/maximize",label:b("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),ds({id:"core/focus-tab",label:b("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),ds({id:"core/close",label:b("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function aN(){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){A(v.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const 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 _g())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))Eg(d);iN(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Sg=ae("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),us=Sg.state.registry,cN=Sg.state.listeners,kg=/^[a-z0-9_/-]+$/,Ig=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Ag(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):kg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${kg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):Ig.has(e.slot)||t.push(`slot (must be one of ${Array.from(Ig).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Oe("WindowSlot",t,e);const n=e.id.trim().toLowerCase();us.set(n,{...e,id:n}),ol()}function nl(e){us.delete(e.toLowerCase())&&ol()}function lN(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&&ol(),t}function Cg(){return Array.from(us.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function ol(){const e=Array.from(cN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function dN(){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){A(v.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const 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 Cg())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))nl(d);lN(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const uN="desktop-mode-notice-dismissed";function fN(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function Lg(){return`${uN}:${fN()}`}function sl(){try{const e=window.localStorage.getItem(Lg());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function Tg(e){try{window.localStorage.setItem(Lg(),JSON.stringify(e))}catch{}}function tr(e){return e?sl()[e]===!0:!1}function nr(e){if(!e)return;const t=sl();t[e]=!0,Tg(t)}function Ng(e){if(!e)return;const t=sl();t[e]&&(delete t[e],Tg(t))}const pN=Le`: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 ) )}`,Js=class Js extends sn{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&tr(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&nr(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&Ng(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return jn` `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};Js.props=["tone","notDismissible","icon","noticeId"],Js.styles=[pN],Js.help=void 0;let il=Js;Jo("os-notice",il);const fs=ae("desktop-mode/window-notices",()=>({entries:new Map})),hN=/^[a-z0-9_/-]+$/;function Og(e){return`os-notice/${e.toLowerCase()}`}function mN(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 Dg(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!hN.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};fs.state.entries.set(t,n);const o=Og(t);return Ag({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=fs.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=fs.state.entries.get(t);i&&s.appendChild(mN(i))}}),()=>rl(t)}function rl(e){const t=String(e??"").trim().toLowerCase();t&&fs.state.entries.delete(t)&&nl(Og(t))}function Rg(){return Array.from(fs.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 gN(e){const t=String(e??"").trim().toLowerCase();t&&nr(t)}function wN(e){const t=String(e??"").trim().toLowerCase();t&&Ng(t)}function yN(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 xg(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),Dg({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:yN(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of Rg())n.owner==="__server__"&&(t.has(n.id)||rl(n.id))}const Mg=ae("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),ps=Mg.state.registry,vN=Mg.state.listeners,Wg=/^[a-z0-9_/-]+$/;function bN(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Wg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Wg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Oe("WindowChrome",t,e);const n=e.id.trim().toLowerCase();ps.set(n,{...e,id:n}),al()}function Pg(e){ps.delete(e.toLowerCase())&&al()}function EN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ps.entries()))o.owner===e&&(ps.delete(n),t++);return t>0&&al(),t}function $g(){return Array.from(ps.values()).sort((e,t)=>e.id.localeCompare(t.id))}function al(){const e=Array.from(vN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function _N(){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){A(v.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const 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 $g())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))Pg(d);EN(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const cl=window.location.origin,Te=ae("desktop-mode/connection",()=>({connSeq:0,connections:new Map,connectionsByTarget:new Map,syntheticIframes:new Map}));function SN(e,t){const{syntheticIframes:n}=Te.state;return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function kN(){return`os-conn-${++Te.state.connSeq}`}function IN(e){const t=(l,c)=>{try{l.contentWindow?.postMessage(c,cl)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=kN(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let g=!1,h=!1;const m=()=>{const W=Te.state.syntheticIframes.get(l);return W||(e.getById(l)?.iframe??null)},_=()=>{if(m())return!1;const W=e.getById(l);return!!W&&W.config?.native===!0},I=[],O=()=>{const W=m();if(W)for(;p.length;){const U=p.shift();t(W,{type:"os-bridge-publish",connectionId:d,topic:U.topic,payload:U.payload})}},$={id:d,target:l,isOpen:()=>g,subscribe(W,U){const F=U;if(_()){const Q=_S(l,W,(Z,C)=>{A(v.CONNECTION_MESSAGE,{connectionId:d,topic:C.channel,direction:"in"});try{F(Z,{topic:C.channel})}catch(D){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",D)}});return I.push(Q),Q}let K=f.get(W);return K||(K=new Set,f.set(W,K)),K.add(F),()=>{K?.delete(F)}},send(W,U){if(h)return;if(A(v.CONNECTION_MESSAGE,{connectionId:d,topic:W,direction:"out"}),_()){kS(l,W,U);return}if(!g){p.push({topic:W,payload:U});return}const F=m();F&&t(F,{type:"os-bridge-publish",connectionId:d,topic:W,payload:U})},disconnect(){$._destroy("disconnect")},_targetWindow:m,_handleIframeMessage(W){if(!W||typeof W!="object")return;const U=W;if(U.type==="os-bridge-handshake-ack"){if(g)return;g=!0,A(v.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:$});try{c.onOpen?.()}catch(F){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",F)}O();return}if(U.type==="os-bridge-publish"){const F=W,K=typeof F.topic=="string"?F.topic:"";if(!K)return;A(v.CONNECTION_MESSAGE,{connectionId:d,topic:K,direction:"in"});const Q=f.get(K);if(Q)for(const C of Array.from(Q))try{C(F.payload,{topic:K})}catch(D){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",D)}const Z=f.get("*");if(Z)for(const C of Array.from(Z))try{C(F.payload,{topic:K})}catch(D){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",D)}return}U.type==="os-bridge-disconnect"&&$._destroy("disconnect")},_destroy(W){if(h)return;h=!0;const U=g;g=!1,Te.state.connections.delete(d);const F=Te.state.connectionsByTarget.get(l);F&&(F.delete(d),F.size===0&&Te.state.connectionsByTarget.delete(l));for(const K of I.splice(0))try{K()}catch{}if(U){const K=m();K&&t(K,{type:"os-bridge-disconnect",connectionId:d})}A(v.CONNECTION_CLOSED,{connectionId:d,reason:W});try{c.onClose?.(W)}catch(K){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",K)}}};Te.state.connections.set(d,$);let S=Te.state.connectionsByTarget.get(l);if(S||(S=new Set,Te.state.connectionsByTarget.set(l,S)),S.add(d),_())return Promise.resolve().then(()=>{if(!(h||g)){g=!0,A(v.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(W){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",W)}}}),$;const R=m();return R&&t(R,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),$},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;Te.state.connections.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=Te.state.syntheticIframes.get(l)??e.getById(l)?.iframe??null;if(!f)return;const p=J(v.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"},cl)}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},cl)}catch{}};return{connect:n,getConnection:l=>Te.state.connections.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=Te.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c)){const u=Te.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=Te.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c))Te.state.connections.get(d)?._destroy("window-closed")}}}const AN={};function CN(...e){(typeof{url:sa&&sa.tagName.toUpperCase()==="SCRIPT"&&sa.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&AN?"production":void 0)!=="production"&&console.log(...e)}const LN="iframe:";function ll(e){return LN+e}function Ug(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function TN(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const NN=250;class ON{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"&&(Xi(ll(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&&Xi(ll(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()},NN)}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){CN("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=ll(t);Xi(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=TN(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?lu(s.iconSvg):"",a={slug:i,label:s.label,icon:Ug(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,Ug(s)):this.runProxy(t,s.name)};try{Xn(a)}catch(l){console.error("[openstation] iframe-bridge: dropping bad command",a,l)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Me(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 DN(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 Bg="global",RN=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,xN=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,MN=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,WN=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,PN=/getSiteEditorPage\s*\(|site-editor\.php/,Fg=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function $N(e){const t=e.match(Fg)?.[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 UN(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 BN{constructor(t){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=t.manager,this.adminUrl=t.adminUrl}install(){this.tryMount(0)}tryMount(t){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){t<40&&window.setTimeout(()=>this.tryMount(t+1),150);return}this.mount()}mount(){const t=window.wp,n=t.element,o=t.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,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 _=0;_{let h=[];for(const m of d.loadersList){const _=d.perLoader[m];Array.isArray(_)&&(h=h.concat(_))}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 _=null;try{_=m.hook({search:""})}catch{}const I=_&&Array.isArray(_.commands)?_.commands:[],O=a(()=>u(I),[I]);return i(()=>{d.perLoader[m.name]=I,f()},[O]),i(()=>()=>{delete d.perLoader[m.name],f()},[]),null},g=()=>{const h=l(S=>{const R=S("core/commands");return!R||typeof R.getCommandLoaders!="function"?[]:[...R.getCommandLoaders(!1)||[],...R.getCommandLoaders(!0)||[]]},[]),m=l(S=>{const R=S("core/commands");return!R||typeof R.getCommands!="function"?[]:[...R.getCommands(!1)||[],...R.getCommands(!0)||[]]},[]),_=a(()=>Array.isArray(h)?h.map(S=>S&&S.name||""):[],[h]),I=_.join("|");i(()=>{d.loadersList=_,f()},[I]);const O=a(()=>u(Array.isArray(m)?m:[]),[m]);if(i(()=>{d.statics=Array.isArray(m)?m:[],f()},[O]),!Array.isArray(h)||h.length===0)return null;const $=[];for(const S of h)!S||typeof S.hook!="function"||$.push(s(p,{key:S.name,loader:S}));return s(n.Fragment||"div",null,$)};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||""} `;if(s!==this.lastFingerprint){this.lastFingerprint=s,Xi(Bg);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"?$N(i.name):void 0,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?lu(i.iconSvg):void 0,owner:Bg,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name)};try{Xn(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;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=UN(n.name);if(s){try{n.url=new URL(s.url,this.adminUrl).toString(),n.kind="navigate",s.label!==""&&(n.windowTitle=s.label)}catch{n.kind="skip"}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}if(typeof t.callback=="function"){let i="";try{i=Function.prototype.toString.call(t.callback)}catch{i=""}const r=i.match(RN)||i.match(xN)||i.match(MN);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(WN.test(i)){const l=PN.test(i)?n.name.match(Fg):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("{if(i.close(),Me(t))return;const r=fe(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title: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 Hg="os-command-palette-ready";let hs=null;function FN(){const t=window.openStationConfig?.commandPalette;return!t||!Array.isArray(t.scripts)?null:t}function HN(){const e=window.wp;try{return!!e?.data?.select?.("core/commands")}catch{return!1}}function GN(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 zN(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 jN(){const e=FN();if(!e||e.scripts.length===0)return HN();for(const s of e.styles??[])GN(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||!yc(s));for(const s of o)s.url&&zN(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!==""&&Nh(i);return document.dispatchEvent(new CustomEvent(Hg)),!0}function VN(){return hs||(hs=jN().catch(e=>{throw hs=null,e}),hs)}const Jn=[];function dl(e){Oe("Widget",Yt(e,Gg),e);const t=Jn.findIndex(n=>n.id===e.id);t>=0?Jn[t]=e:Jn.push(e)}function KN(e){const t=Jn.findIndex(n=>n.id===e);t>=0&&Jn.splice(t,1)}function ul(){const e=Jn.slice(),t=J(v.WIDGETS,e);return Array.isArray(t)?t.filter(qN):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function Qn(e){return ul().find(t=>t.id===e)}const Gg=[{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 qN(e){return Yt(e,Gg).length===0}let Qe=null;function YN(e){if(Qe)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),zg(o,e),document.body.appendChild(t),XN(t,e.anchor);const s=a=>{const l=a.target;l&&(t.contains(l)||e.anchor.contains(l)||fl())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&fl()};document.addEventListener("keydown",i),Qe={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function ms(){if(!Qe)return;const e=Qe.panel.querySelector(".os-widget-picker__list");e&&zg(e,Qe.options)}function fl(){if(!Qe)return;document.removeEventListener("pointerdown",Qe.onOutsidePointerDown,!0),document.removeEventListener("keydown",Qe.onKeyDown),Qe.panel.remove();const{onClose:e}=Qe.options;Qe=null,e?.()}function zg(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)}}function XN(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.style.visibility="hidden";const o=e.getBoundingClientRect(),s=o.width||320,i=o.height||200,r=6;let a=n.right-s,l=n.top-i-r;a<8&&(a=8),l<8&&(l=n.bottom+r),e.style.left=`${Math.round(a)}px`,e.style.top=`${Math.round(l)}px`,e.style.visibility=""}const or="os-widgets__card--floating",ZN="os-widgets__card--movable",JN="os-widgets__card--resizable",jg="os-widgets__card--dragging",Vg="os-widgets__card--resizing",QN=160,Kg=80,eO=280,tO=180,eo=20,cn=20,qg=5,nO=qg*qg,oO='input, textarea, select, button, a, [contenteditable="true"]';function sO(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(ZN),i&&o.classList.add(JN),s?o.appendChild(iO(e,n.onRemove,n.onRedock)):o.appendChild(aO(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(sr(o,Zg(t.geometry,t.floatingParent)),o.classList.add(or)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${fO(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(or),l=[];if(i)for(const d of dO()){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(lO(o,u,d,e,t,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=cO(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 iO(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(rO(e,n));const r=Yg(e,t);return o.appendChild(r),o}function rO(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='',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n.dataset.noDrag="true",n}function aO(e,t){const n=Yg(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function Yg(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=qt("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function cO(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(oO)||(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(or)){const h=o.floatingParent.getBoundingClientRect(),m=e.getBoundingClientRect(),_={x:m.left-h.left,y:m.top-h.top,width:m.width||n.defaultWidth||eO,height:m.height||n.defaultHeight||tO};sr(e,_),e.classList.add(or),s.onLiberate(_),l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(jg)},p=h=>{if(i===null||h.pointerId!==i)return;const m=h.clientX-r,_=h.clientY-a;if(!d){if(m*m+_*_{if(!(i===null||h.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(jg),s.onGeometryChanged(Xg(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 lO(e,t,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const g=_=>{if(_.button!==0||!r()&&!uO(n))return;_.preventDefault(),_.stopPropagation(),a=_.pointerId,l=_.clientX,c=_.clientY;const I=e.getBoundingClientRect(),O=s.floatingParent.getBoundingClientRect();d=I.left-O.left,u=I.top-O.top,f=I.width,p=I.height,t.setPointerCapture(a),e.classList.add(Vg)},h=_=>{if(a===null||_.pointerId!==a)return;const I=_.clientX-l,O=_.clientY-c,$=pO(n,I,O,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${$.x}px`,e.style.top=`${$.y}px`,e.style.width=`${$.width}px`),e.style.height=`${$.height}px`},m=_=>{if(!(a===null||_.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(Vg),r()?i.onGeometryChanged(Xg(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 dO(){return["n","e","s","w","ne","nw","se","sw"]}function uO(e){return e==="s"}function sr(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 Xg(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function fO(e,t){return no(e,t.minHeight??Kg,t.maxHeight??1/0)}function Zg(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Qg(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function to(e){return Math.round(e/cn)*cn}function Jg(e){const t=Math.floor(e/cn)*cn;return t>=eo?t:Math.min(e,eo)}function Qg(e,t,n,o,s){const i=ge(s),r=i.x+eo,a=i.y+eo,l=Math.max(i.x,i.x+i.width-n-eo),c=Math.max(i.y,i.y+i.height-o-eo);return{x:Math.min(Math.max(r,e),l),y:Math.min(Math.max(a,t),c)}}function pO(e,t,n,o,s,i,r,a,l,c){const d=a.minWidth??QN,u=a.minHeight??Kg,f=a.maxWidth??1/0,p=a.maxHeight??1/0,g=ge(l),h=g.x+g.width,m=g.y+g.height;let _=o,I=s,O=i,$=r;if((e==="e"||e==="ne"||e==="se")&&(c?O=ir(to(o+i+t),o+d,Math.min(o+f,h))-o:O=no(i+t,d,Math.min(f,h-o))),e==="w"||e==="nw"||e==="sw"){const S=o+i;if(c)_=ir(to(o+t),Math.max(0,S-Math.min(f,S)),S-d),O=S-_;else{const R=no(i-t,d,Math.min(f,S));_=o+(i-R),O=R}}if((e==="s"||e==="se"||e==="sw")&&(c?$=ir(to(s+r+n),s+u,Math.min(s+p,m))-s:$=no(r+n,u,Math.min(p,m-s))),e==="n"||e==="ne"||e==="nw"){const S=s+r;if(c)I=ir(to(s+n),Math.max(0,S-Math.min(p,S)),S-u),$=S-I;else{const R=no(r-n,u,Math.min(p,S));I=s+(r-R),$=R}}return c||(O=i,_=o),{x:_,y:I,width:O,height:$}}function ir(e,t,n){const o=no(e,t,n),s=Math.floor(o/cn)*cn;if(s>=t)return s;const i=s+cn;return i<=n?i:o}function no(e,t,n){return ntypeof n=="string"):[]}catch{return[]}}function pl(e){try{window.localStorage.setItem(ew,JSON.stringify(e))}catch{}}function mO(){try{const e=window.localStorage.getItem(tw);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=wO(s);i&&(n[o]=i)}return n}catch{return{}}}function hl(e){try{window.localStorage.setItem(tw,JSON.stringify(e))}catch{}}function gO(){try{const e=window.localStorage.getItem(nw);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 sw(e){try{window.localStorage.setItem(nw,JSON.stringify(e))}catch{}}function wO(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 yO=120,vO="os-inline-loader",iw="os-inline-loader-keyframes";function bO(){return typeof customElements<"u"&&!!customElements.get("os-spinner")}function EO(){if(document.getElementById(iw))return;const e=document.createElement("style");e.id=iw,e.textContent="@keyframes os-inline-loader-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function _O(){if(bO()){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||(EO(),e.style.animation="os-inline-loader-spin 0.7s linear infinite"),e}function SO(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=vO,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(_O()),o.appendChild(l),e.appendChild(o)},r=t.immediate?null:window.setTimeout(i,yO);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 kO(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 IO=["clock"],rr=40,AO=12;class CO{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=hO(),this.geometry=mO(),this.dockedHeights=gO(),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(){ow()===null&&(this.enabledIds=IO.filter(t=>!!Qn(t)),pl(this.enabledIds));for(const t of this.visibleIds())this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){if(Qn(t)){if(this.override){if(this.override.includes(t))return;this.override=[...this.override,t],this.mountById(t),this.paintEmptyState(),A(v.WIDGET_ADDED,{id:t});return}this.enabledIds.includes(t)||(this.enabledIds.push(t),pl(this.enabledIds),this.mountById(t),this.paintEmptyState(),A(v.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(),A(v.WIDGET_REMOVED,{id:t}),ms();return}const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(pl(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],hl(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],sw(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),A(v.WIDGET_REMOVED,{id:t}),ms())}getEnabledIds(){return[...this.enabledIds]}getMountedIds(){return Array.from(this.mounted.keys())}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),YN({anchor:this.addTile,registry:()=>ul(),enabledIds:()=>[...this.enabledIds],onAdd:t=>{this.add(t),fl(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){Qn(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 Qn(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)||!Qn(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=Qn(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=sO(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:kO(t)};A(v.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(),A(v.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(LO(d)){const u=SO(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){A(v.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){A(v.SHELL_ERROR,{scope:"widget-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[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)),A(v.WIDGET_MOUNT_FAILED,{id:t,error:n}),A(v.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[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=this.root.getBoundingClientRect());const d=c.clientX>=t.left-rr&&c.clientX<=t.right+rr&&c.clientY>=t.top-rr&&c.clientY<=t.bottom+rr;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=Fo(()=>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),sr(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],hl(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=Zg(o,this.floatingHost);s.x===o.x&&s.y===o.y||(sr(n.frame.card,s),this.persistGeometry(t,s))}}persistGeometry(t,n){this.geometry[t]=n,hl(this.geometry),this.positionAddTile()}positionAddTile(){const t=this.root.getBoundingClientRect();if(!t.height)return;let n=this.listEl.offsetTop+this.listEl.offsetHeight;for(const i of this.mounted.values()){if(!i.floating)continue;const r=i.frame.card.getBoundingClientRect();Math.min(r.right,t.right)-Math.max(r.left,t.left)0),this.positionAddTile()}}function LO(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const TO=280,NO=220,OO=520,DO=400;function rw(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function aw(e,t,n){return o=>{const s=rw(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;try{a=new URL(e.url,window.location.origin).origin}catch{a=window.location.origin}let l=null;const c=new Promise(f=>{l=f}),d=()=>{if(e.bridge)try{const f=i.contentDocument;if(f&&!f.querySelector("script[data-os-iframe-bridge]")){const p=window.openStationConfig?.iframeBridgeUrl;if(p){const g=f.createElement("script");g.src=p,g.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(g)}}}catch{}IS(s),l?.()};i.addEventListener("load",d);const u=f=>{if(!i.contentWindow||f.source!==i.contentWindow||f.origin!==a&&f.origin!==window.location.origin)return;const p=f.data;p&&typeof p=="object"&&typeof p.type=="string"&&p.type.startsWith("os-bridge-")&&window.__openStationConnectionBridge?.routeIncomingFromIframe(p,s),p&&typeof p=="object"&&p.type==="os-window-publish"&&typeof p.channel=="string"&&p.channel!==""&&SS(s,p.channel,p.payload);try{e.onMessage?.(f.data)}catch(g){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",g)}};return window.addEventListener("message",u),t.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),c}}function RO(e,t,n={}){let o;try{const c=new URL(t,window.location.origin);if(c.origin!==window.location.origin)return()=>{};if(Ln(c))return()=>{};c.searchParams.set("openstation_chromeless","1"),o=c.toString()}catch{return()=>{}}e.replaceChildren();const s=[],i=rw(e,n.windowId??""),r=aw({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","comet"),a.appendChild(l),e.appendChild(a),r.then(()=>a.remove()),()=>{for(const c of s)try{c()}catch{}e.replaceChildren()}}function xO(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=aw(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??OO,height:t.height??DO,minWidth:t.minWidth??TO,minHeight:t.minHeight??NO,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let MO=0;function WO(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++MO}`,s=n.persistent===!0,i=[["opened",v.WINDOW_OPENED],["reopened",v.WINDOW_REOPENED],["focused",v.WINDOW_FOCUSED],["blurred",v.WINDOW_BLURRED],["closing",v.WINDOW_CLOSING],["closed",v.WINDOW_CLOSED],["minimized",v.WINDOW_MINIMIZED],["restored",v.WINDOW_RESTORED],["maximized",v.WINDOW_MAXIMIZED],["unmaximized",v.WINDOW_UNMAXIMIZED],["fullscreenEntered",v.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",v.WINDOW_FULLSCREEN_EXITED],["resized",v.WINDOW_RESIZED],["bodyResized",v.WINDOW_BODY_RESIZED],["boundsChanged",v.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const l=()=>{if(!a){a=!0;for(const c of r)jt(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 PO(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function $O(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&Ik(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function cw(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 UO(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=y=>{const E=Li(y.id);return E?{width:Math.max(E.width,y.minWidth),height:Math.max(E.height,y.minHeight)}:{width:y.width,height:y.height}},u=y=>{if(i.has(y.templateId))return;if(document.getElementById(y.templateId)){i.add(y.templateId);return}if(!y.templateHtml)return;const E=document.createElement("template");E.id=y.templateId,E.innerHTML=y.templateHtml,document.body.appendChild(E),i.add(y.templateId)},f=y=>{const E=y.styleUrl;if(!E||l.has(E))return;const T=E.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${T}"]`)){const X=document.createElement("link");X.rel="stylesheet",X.href=E,y.styleHandle&&(X.dataset.osStyleHandle=y.styleHandle),document.head.appendChild(X)}if(Array.isArray(y.styleInline))for(const X of y.styleInline){if(typeof X!="string"||X==="")continue;const Y=document.createElement("style");y.styleHandle&&(Y.dataset.osStyleHandle=y.styleHandle),Y.textContent=X,document.head.appendChild(Y)}l.add(E)},p=y=>{f(y)},g=y=>{for(const E of y.companionStyles??[])f(E)},h=new Set,m=(y,E)=>{if(h.has(y))return;h.add(y);const T=[E.scriptTranslations??"",...E.scriptL10n??[],...E.scriptBefore??[],...E.scriptAfter??[]];for(const x of T)typeof x=="string"&&x!==""&&Nh(x)},_=(y,E)=>{const T=E.scriptUrl,x=`${y}|${T}`;if(r.has(T))return m(x,E),Promise.resolve();const X=a.get(T);if(X)return X.then(()=>m(x,E));h.add(x);const Y=pe(T,{translations:E.scriptTranslations,l10n:E.scriptL10n,before:E.scriptBefore,after:E.scriptAfter,deps:E.scriptDeps}).catch(ce=>{A(v.SHELL_ERROR,{scope:"native-window-script-load",id:y,error:ce})}).then(()=>{r.add(T),a.delete(T)});return a.set(T,Y),Y},I=async y=>{g(y);for(const E of y.companionScripts??[])E.scriptUrl&&await _(y.id,E);y.scriptUrl&&await _(y.id,y)},O=async y=>{y.preloadScript&&await I(y)},$=new Set,S=(y,E)=>{if(!y||$.has(y)||r.has(y)||l.has(y))return;$.add(y);const T=document.createElement("link");T.rel="prefetch",T.as=E,T.href=y,document.head.appendChild(T)},R=()=>{const y=navigator.connection;if(!(y?.saveData||/2g$/.test(y?.effectiveType??""))){for(const E of c.values())if(!E.preloadScript){for(const T of E.companionScripts??[])S(T.scriptUrl,"script");S(E.scriptUrl,"script");for(const T of E.companionStyles??[])S(T.styleUrl,"style")}}};let W=!1;const U=()=>{if(W)return;W=!0;const y=()=>{W=!1,R()};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(y,{timeout:4e3}):window.setTimeout(y,1500)},F=y=>async(E,T)=>{E.appendChild(lw(y.templateId)),$O(E,y),await I(y),window.wp?.os?.apps?.refresh?.();const X=PO()[y.id];return X?.(E,T)},K=(y,E)=>{const T=F(y),x=d(y);t.open({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:x.width,height:x.height,minWidth:y.minWidth,minHeight:y.minHeight,render:T,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle,...E?{params:E}:{}})},Q=(y,E)=>{const T=F(y),x=d(y);t.openNew({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:x.width,height:x.height,minWidth:y.minWidth,minHeight:y.minHeight,render:T,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle,...E?{params:E}:{}})},Z=(y,E,T)=>{const x=F(y),X=d(y);t.openNew({id:E,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:X.width,height:X.height,minWidth:y.minWidth,minHeight:y.minHeight,render:x,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle,...T})},C=async y=>{if(!s.has(y.id)){if(y.placement==="none"){u(y),p(y),await O(y),s.add(y.id);return}u(y),p(y),await O(y),n({id:y.id,title:y.title,icon:y.icon,windowId:y.id,navKind:y.navKind==="control"?"control":"app",defaultPlacement:"rail",order:y.dockOrder,placeable:y.placeable===!0,isOpen:()=>!!t.getById(y.id),onOpen:()=>K(y)}),A(v.DOCK_ITEM_APPENDED,{id:y.id}),s.add(y.id)}},D=y=>{s.has(y)&&(o(y),s.delete(y),c.delete(y))},V=y=>{try{const E=new URL(y,window.location.origin),T=[E.pathname.split("/").pop()??""];for(const x of["post_type","taxonomy","page"]){const X=E.searchParams.get(x);X&&T.push(`${x}=${X}`)}return T.join("&")}catch{return y}},j=y=>`desktop-mode/menu-pages/${y}`,te=y=>{const E=j(y.id),T=y.menuPages??[];if(T.length===0){pa(E);return}const x=T.map(Y=>({tab:Y.id,key:V(Y.page)})),X=Y=>x.find(ce=>ce.key===V(Y.href))?.tab??null;ht({id:E,nativeWindowId:y.id,matches:(Y,ce)=>X(ce)!==null,params:(Y,ce)=>{const q=X(ce);return q?{tab:q}:void 0}})},N=async y=>{const E=new Set;for(const T of y)E.add(T.id),te(T),c.set(T.id,T);for(const T of Array.from(s))E.has(T)||(D(T),pa(j(T)));for(const T of y)s.has(T.id)||await C(T);U()},L=(y,E={})=>{const T=c.get(y);return T?(_e.publish("os/open-requested",{windowId:y,source:E.source??"api"}),K(T,E.params),!0):!1},M=(y,E={})=>{const T=c.get(y);return T?(_e.publish("os/open-requested",{windowId:y,source:E.source??"api"}),Q(T,E.params),!0):!1},P=(y,E,T)=>{const x=c.get(E);return x?(Z(x,y,T),!0):!1};return ee(v.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",y=>{const E=y,T=E?.windowId,x=E?.width,X=E?.height;if(!T||typeof x!="number"||typeof X!="number")return;const Y=t.getById(T);if(!Y||Y.state!=="normal")return;const ce=Y.config.baseId||Y.id;xp(ce,{width:x,height:X}),Y.element&&Mp(ce,{x:Y.element.offsetLeft,y:Y.element.offsetTop})}),ee(v.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E)return;const T=t.getById(E);if(!T||T.state!=="normal"||!T.element)return;const x=T.config.baseId||T.id;xp(x,{width:T.element.offsetWidth,height:T.element.offsetHeight}),Mp(x,{x:T.element.offsetLeft,y:T.element.offsetTop})}),ee(v.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E||Vt())return;const T=t.getById(E);if(!T)return;const x=T.config.baseId||T.id,X=c.get(x),Y=X?{width:X.width,height:X.height}:{width:T.config.width,height:T.config.height};Wp(x,"maximized",Y)}),ee(v.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E)return;const T=t.getById(E);if(!T)return;const x=T.config.baseId||T.id;Wp(x,null)}),{sync:N,openById:L,openNewById:M,restoreById:P,loadScriptById:async y=>{const E=c.get(y);return E?(await I(E),!0):!1},prewarmById:async y=>{const E=c.get(y);return!E||t.getById(y)?!1:(await I(E),window.wp?.os?.apps?.prewarm?.(y)===!0)}}}function lw(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