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

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

64 lines 609.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var openStation=function(Nr){"use strict";var Or=typeof document<"u"?document.currentScript:null;function gt(){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 yt(e,t,n,o){gt().addFilter(e,t,n,o)}function Z(e,t,n,o){gt().addAction(e,t,n,o)}function ao(e,t){return gt().removeAction(e,t)}function wb(e,t){return gt().removeFilter(e,t)}function q(e,t,...n){return gt().applyFilters(e,t,...n)}function A(e,...t){gt().doAction(e,...t)}function yd(e){return gt().didAction(e)}function gb(){return gt()}const g={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",ARRANGE_CUSTOM_ACTION:"os.arrange.custom-action",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 yb=0;function vd(e){if(yd(g.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++yb}`;Z(g.INIT,t,e)}function vb(){return yd(g.INIT)>0}const Dr="data-os-mode";function bd(e,t){e.getAttribute(Dr)!==t&&e.setAttribute(Dr,t)}function Pt(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(Dr)==="mobile"}const Rr="data-os-display";function Ed(e,t){e.getAttribute(Rr)!==t&&e.setAttribute(Rr,t)}function bb(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(Rr)==="standalone"}const Eb=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"],xr=[];function _b(e){if(!e.pathname.endsWith("/admin.php")||!e.searchParams.get("page"))return xr;const t=e.searchParams.get("action");return t==="edit"&&e.searchParams.get("id")?["id"]:t==="new"?["action"]:xr}function _d(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 de(e,t){let n=null;try{n=new URL(e,t)}catch{n=null}if(n){const s=new URL(t).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams,a=[...Eb,..._b(n)];for(const c of a){const d=n.searchParams.get(c);d&&r.set(c,d)}const l=r.toString();return _d(l?`${i}?${l}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),_d(o)}function Sb(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function kb(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 Sd(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 pn(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 kd(e){if(typeof e!="string"||e===""||typeof DOMParser>"u")return"";let t;try{t=new DOMParser().parseFromString(e,"image/svg+xml")}catch{return""}const n=t.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||t.getElementsByTagName("parsererror").length>0)return"";const o=new Set(["script","style","foreignobject","iframe","object","embed"]),s=i=>{const r=Array.from(i.children);for(const a of r){if(o.has(a.nodeName.toLowerCase())){a.remove();continue}for(const 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 hn=null;function Ps(){return!!window.openStationWindowSystem}function Id(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(Ps()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){Ps()?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 Ib(){return window.openStationConfig?.windowSystemBundleUrl??""}function Ab(e){!e||Ps()||hn||(hn=Id(e).catch(t=>{hn=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function Cb(e){if(Ps())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 hn||(hn=Id(e)),await hn,window.openStationWindowSystem}let mn=null;function co(){return!!window.openStationShellOverlays}function Ad(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(co()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){co()?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 Lb(e){!e||co()||mn||(mn=Ad(e).catch(t=>{mn=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function Mr(e){return co()||!e?Promise.resolve():(mn||(mn=Ad(e)),mn)}function Wr(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function $s(e,t){const n=Wr();if(co()||!n){t();return}Mr(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Cd="desktop-mode";function Pr(){return window.wp?.i18n}function _(e,t=Cd){return Pr()?.__(e,t)??e}function $t(e,t,n,o=Cd){return Pr()?._n(e,t,n,o)??(n===1?e:t)}function re(e,...t){const n=Pr()?.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 Tb=900,Nb=260,$r="os-desktop-name-hud";let Xe=null,vt=null;function Ob(e,t){t.trim()&&(vt!==null&&window.clearTimeout(vt),Xe||(Xe=document.createElement("div"),Xe.className=$r,Xe.setAttribute("role","status")),Xe.textContent=t,Xe.classList.remove(`${$r}--out`),e.appendChild(Xe),vt=window.setTimeout(()=>{Xe?.classList.add(`${$r}--out`),vt=window.setTimeout(()=>{Xe?.remove(),vt=null},Nb)},Tb))}function Db(){vt!==null&&(window.clearTimeout(vt),vt=null),Xe?.remove(),Xe=null}function Rb(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 xb(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 Mb(e,t,n){if(e<=1)return{cols:1,rows:1};const o=t/Math.max(1,n),s=6;let i={cols:e,rows:1,score:1/0};for(let r=1;r<=Math.min(s,e);r++){const a=Math.min(s,Math.ceil(e/r));if(r*a<e)continue;const l=t/r/Math.max(1,n/a),c=Math.abs(l-o),d=r*a-e,u=c+d*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function Ur(e,t,n=0){const o=e.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,l=34,c=(t.width-r*2-a*(s-1))/s,d=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-l);return e.map((f,p)=>{const v=p%s,h=Math.floor(p/s),w=t.left+r+v*(c+a),E=t.top+n+r+h*(d+a)+l,S=f.element.offsetWidth,O=f.element.offsetHeight,M=Math.min(c/S,u/O),b=S*M,W=O*M;return{win:f,x:w+(c-b)/2,y:E+(u-W)/2,scale:M}})}const Wb=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],Ld=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],Pb=[...Wb,...Ld],Td={close:{a:'fill="currentColor"',b:'<path d="m13.06 12 6.47-6.47-1.06-1.06L12 10.94 5.53 4.47 4.47 5.53 10.94 12l-6.47 6.47 1.06 1.06L12 13.06l6.47 6.47 1.06-1.06L13.06 12Z" />'},check:{a:'fill="currentColor"',b:'<path d="M16.5 7.5 10 13.9l-2.5-2.4-1 1 3.5 3.6 7.5-7.6z" />'},"chevron-right":{a:'fill="currentColor"',b:'<path d="M10.6 6L9.4 7l4.6 5-4.6 5 1.2 1 5.4-6z" />'},"arrow-up-right":{a:'fill="currentColor"',b:'<path d="M10 6H18V14H16.5V8.5L7 18L6 17L15.5 7.5H10V6Z" />'},plus:{a:'fill="currentColor"',b:'<path d="M11 12.5V17.5H12.5V12.5H17.5V11H12.5V6H11V11H6V12.5H11Z" />'},search:{a:'fill="currentColor"',b:'<path d="M13 5c-3.3 0-6 2.7-6 6 0 1.4.5 2.7 1.3 3.7l-3.8 3.8 1.1 1.1 3.8-3.8c1 .8 2.3 1.3 3.7 1.3 3.3 0 6-2.7 6-6S16.3 5 13 5zm0 10.5c-2.5 0-4.5-2-4.5-4.5s2-4.5 4.5-4.5 4.5 2 4.5 4.5-2 4.5-4.5 4.5z" />'},pin:{a:'fill="currentColor"',b:'<path d="m21.5 9.1-6.6-6.6-4.2 5.6c-1.2-.1-2.4.1-3.6.7-.1 0-.1.1-.2.1-.5.3-.9.6-1.2.9l3.7 3.7-5.7 5.7v1.1h1.1l5.7-5.7 3.7 3.7c.4-.4.7-.8.9-1.2.1-.1.1-.2.2-.3.6-1.1.8-2.4.6-3.6l5.6-4.1zm-7.3 3.5.1.9c.1.9 0 1.8-.4 2.6l-6-6c.8-.4 1.7-.5 2.6-.4l.9.1L15 4.9 19.1 9l-4.9 3.6z" />'},trash:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M12 5.5A2.25 2.25 0 0 0 9.878 7h4.244A2.251 2.251 0 0 0 12 5.5ZM12 4a3.751 3.751 0 0 0-3.675 3H5v1.5h1.27l.818 8.997a2.75 2.75 0 0 0 2.739 2.501h4.347a2.75 2.75 0 0 0 2.738-2.5L17.73 8.5H19V7h-3.325A3.751 3.751 0 0 0 12 4Zm4.224 4.5H7.776l.806 8.861a1.25 1.25 0 0 0 1.245 1.137h4.347a1.25 1.25 0 0 0 1.245-1.137l.805-8.861Z" />'},download:{a:'fill="currentColor"',b:'<path d="M18 11.3l-1-1.1-4 4V3h-1.5v11.3L7 10.2l-1 1.1 6.2 5.8 5.8-5.8zm.5 3.7v3.5h-13V15H4v5h16v-5h-1.5z" />'},settings:{a:'fill="currentColor"',b:'<path d="m19 7.5h-7.628c-.3089-.87389-1.1423-1.5-2.122-1.5-.97966 0-1.81309.62611-2.12197 1.5h-2.12803v1.5h2.12803c.30888.87389 1.14231 1.5 2.12197 1.5.9797 0 1.8131-.62611 2.122-1.5h7.628z" /><path d="m19 15h-2.128c-.3089-.8739-1.1423-1.5-2.122-1.5s-1.8131.6261-2.122 1.5h-7.628v1.5h7.628c.3089.8739 1.1423 1.5 2.122 1.5s1.8131-.6261 2.122-1.5h2.128z" />'},info:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm.75 4v1.5h-1.5V8h1.5Zm0 8v-5h-1.5v5h1.5Z" />'},bell:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M17 11.5c0 1.353.17 2.368.976 3 .266.209.602.376 1.024.5v1H5v-1c.422-.124.757-.291 1.024-.5.806-.632.976-1.647.976-3V9c0-2.8 2.2-5 5-5s5 2.2 5 5v2.5ZM15.5 9v2.5c0 .93.066 1.98.515 2.897l.053.103H7.932a4.018 4.018 0 0 0 .053-.103c.449-.917.515-1.967.515-2.897V9c0-1.972 1.528-3.5 3.5-3.5s3.5 1.528 3.5 3.5Zm-5.492 9.008c0-.176.023-.346.065-.508h3.854A1.996 1.996 0 0 1 12 20c-1.1 0-1.992-.892-1.992-1.992Z" />'},more:{a:'fill="currentColor"',b:'<path d="M11 13h2v-2h-2v2zm-6 0h2v-2H5v2zm12-2v2h2v-2h-2z" />'},maximize:{a:'fill="currentColor"',b:'<path d="M6 4a2 2 0 0 0-2 2v3h1.5V6a.5.5 0 0 1 .5-.5h3V4H6Zm3 14.5H6a.5.5 0 0 1-.5-.5v-3H4v3a2 2 0 0 0 2 2h3v-1.5Zm6 1.5v-1.5h3a.5.5 0 0 0 .5-.5v-3H20v3a2 2 0 0 1-2 2h-3Zm3-16a2 2 0 0 1 2 2v3h-1.5V6a.5.5 0 0 0-.5-.5h-3V4h3Z" />'},edit:{a:'fill="currentColor"',b:'<path d="m19 7-3-3-8.5 8.5-1 4 4-1L19 7Zm-7 11.5H5V20h7v-1.5Z" />'},color:{a:'fill="currentColor"',b:'<path d="M17.2 10.9c-.5-1-1.2-2.1-2.1-3.2-.6-.9-1.3-1.7-2.1-2.6L12 4l-1 1.1c-.6.9-1.3 1.7-2 2.6-.8 1.2-1.5 2.3-2 3.2-.6 1.2-1 2.2-1 3 0 3.4 2.7 6.1 6.1 6.1s6.1-2.7 6.1-6.1c0-.8-.3-1.8-1-3zm-5.1 7.6c-2.5 0-4.6-2.1-4.6-4.6 0-.3.1-1 .8-2.3.5-.9 1.1-1.9 2-3.1.7-.9 1.3-1.7 1.8-2.3.7.8 1.3 1.6 1.8 2.3.8 1.1 1.5 2.2 2 3.1.7 1.3.8 2 .8 2.3 0 2.5-2.1 4.6-4.6 4.6z" />'},wallpaper:{a:'fill="currentColor"',b:'<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 4.5h14c.3 0 .5.2.5.5v8.4l-3-2.9c-.3-.3-.8-.3-1 0L11.9 14 9 12c-.3-.2-.6-.2-.8 0l-3.6 2.6V5c-.1-.3.1-.5.4-.5zm14 15H5c-.3 0-.5-.2-.5-.5v-2.4l4.1-3 3 1.9c.3.2.7.2.9-.1L16 12l3.5 3.4V19c0 .3-.2.5-.5.5z" />'},warning:{a:'fill="currentColor"',b:'<path fill-rule="evenodd" clip-rule="evenodd" d="M5.5 12a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0ZM12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16Zm-.75 12v-1.5h1.5V16h-1.5Zm0-8v5h1.5V8h-1.5Z" />'},minimize:{a:'fill="currentColor"',b:'<path d="M5 11.25h14v1.5H5z" />'},window:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="4.125" y="5.4375" width="15.75" height="13.125" rx="1.75"/><path d="M4.125 9.8125h15.75"/><circle cx="7.275" cy="7.625" r="0.7438" fill="currentColor" stroke="none"/>'},windows:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="8.5" width="11.375" height="10.0625" rx="1.75"/><path d="M3.6875 12h11.375"/><path d="M8.5 8.5V7.1875a1.75 1.75 0 0 1 1.75-1.75h7.875A1.75 1.75 0 0 1 19.875 7.1875v7a1.75 1.75 0 0 1-1.75 1.75h-3.0625"/>'},dock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.25" y="8.5" width="17.5" height="7" rx="3.5"/><circle cx="7.625" cy="12" r="1.0062" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.0062" fill="currentColor" stroke="none"/><circle cx="16.375" cy="12" r="1.0062" fill="currentColor" stroke="none"/>'},spaces:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="5.4375" width="7.4375" height="7.875" rx="1.75"/><rect x="12.875" y="5.4375" width="7.4375" height="7.875" rx="1.75"/><circle cx="9.375" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/><circle cx="12" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/><circle cx="14.625" cy="17.6875" r="0.7875" fill="currentColor" stroke="none"/>'},copilot:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<path d="M10 2.5Q10.9 8.5 17.5 10Q10.9 11.5 10 17.5Q9.1 11.5 2.5 10Q9.1 8.5 10 2.5Z" fill="currentColor" stroke="none"/><path d="M17.9 14Q18.35 17.1 21.5 17.6Q18.35 18.1 17.9 21.2Q17.45 18.1 14.3 17.6Q17.45 17.1 17.9 14Z" fill="currentColor" stroke="none"/>'},snap:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="5.4375" width="16.625" height="13.125" rx="1.75"/><path d="M12 5.4375v13.125"/><path d="M12 12h8.3125"/>'},command:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<path d="M14.625 6.75v10.5a2.625 2.625 0 1 0 2.625-2.625H6.75a2.625 2.625 0 1 0 2.625 2.625V6.75a2.625 2.625 0 1 0-2.625 2.625h10.5a2.625 2.625 0 1 0-2.625-2.625"/>'},apps:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="4.125" y="4.125" width="6.5625" height="6.5625" rx="1.75"/><rect x="13.3125" y="4.125" width="6.5625" height="6.5625" rx="1.75"/><rect x="4.125" y="13.3125" width="6.5625" height="6.5625" rx="1.75"/><rect x="13.3125" y="13.3125" width="6.5625" height="6.5625" rx="1.75"/>'},widgets:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="3.6875" y="3.6875" width="9.625" height="9.625" rx="1.75"/><rect x="15.0625" y="3.6875" width="5.25" height="5.25" rx="1.75"/><rect x="15.0625" y="10.6875" width="5.25" height="9.625" rx="1.75"/><rect x="3.6875" y="15.0625" width="9.625" height="5.25" rx="1.75"/>'},user:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<circle cx="12" cy="8.9375" r="3.5"/><path d="M5.4375 19.4375a6.5625 6.5625 0 0 1 13.125 0"/>'},lock:{a:'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"',b:'<rect x="5.4375" y="10.6875" width="13.125" height="8.75" rx="1.75"/><path d="M8.5 10.6875V8.0625a3.5 3.5 0 0 1 7 0v2.625"/>'}};function Nd(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Od(e){return Object.prototype.hasOwnProperty.call(Td,e)?Td[e]:null}function $b(e){return Od(e)!==null}function bt(e,t={}){const n=Od(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="${Nd(s)}"`),i?a.push('role="img"',`aria-label="${Nd(i)}"`):a.push('aria-hidden="true"','focusable="false"');const l=r?`<g transform="rotate(${r} 12 12)">${n.b}</g>`:n.b;return`<svg ${a.join(" ")}>${l}</svg>`}function Dd(e,t={}){const n=bt(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 Ub(e,t={}){const n=bt(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const Bb=Object.freeze({svg:bt,node:Dd,dataUri:Ub,names:Object.freeze([...Pb]),ours:Object.freeze([...Ld]),has:$b}),Fb=120,Hb=56;function Rd(e){return Fb+(e?.querySelector(".os-overview-top-bar__header")?Hb:0)}const Gb="openstation";function lo(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")===Gb}const xd=["target","intent","openstation_overview"];function zb(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!lo(n)||!xd.some(o=>n.searchParams.has(o))?null:(xd.forEach(o=>n.searchParams.delete(o)),n.href)}const Md="__openStationSharedStores";function Vb(){const e=window;let t=e[Md];return t||(t=new Map,e[Md]=t),t}function ie(e,t){const n=Vb();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 Wd="X-WP-Nonce";function Pd(e,t){const n=jb();if(!n)return t;const o=Kb(e);if(!o||!qb(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Wd)?t:(i.set(Wd,n),{...t??{},headers:i})}function jb(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function Kb(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 qb(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function $e(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=Pd(e,t);return fetch(e,s)}const uo=ie("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),dt=uo.state.registry,Br=uo.state.listeners,Yb=/^[a-z0-9_-]+$/;function $d(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!Yb.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).`);dt.set(e.id,e),Us()}function Xb(e){dt.delete(e)&&Us()}function Zb(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(dt.entries()))o.owner===e&&(dt.delete(n),t++);return t>0&&Us(),t}function Jb(e){return dt.get(e)}function Qb(){return Array.from(dt.values())}function eE(e){return Br.add(e),()=>{Br.delete(e)}}function tE(e){uo.state.activeId!==e&&(uo.state.activeId=e,Us())}function Fr(){return dt.get(uo.state.activeId)??dt.get("default")??dt.values().next().value}function Us(){const e=Array.from(Br);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function Ut(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 nE 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 Te(e,t,n){if(t.length!==0)throw new nE(e,t,n)}function Ud(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const Et=[[0,0],[100,0],[100,100],[0,100]],oE=48,sE=80,Hr=6,Gr=8,Bd=4,Fd=3,Hd=64,zr=105,_t=2;function Gd(e){return`${Math.round(e*1e3)/1e3}%`}function St(e){return e.slice().reverse()}function fo(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function iE(e,t,n,o){const s=[];for(let i=0;i<o;i++){const r=i/o*Math.PI*2;s.push([e+Math.cos(r)*n,t+Math.sin(r)*n])}return s}function st(e,t=[]){const n=[],o=s=>{n.push(`${Gd(s[0])} ${Gd(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 zd(e){return st(Et,[St(iE(50,50,e,oE))])}function Vd(e){return st(Et,[St(fo(50-e,-_t,50+e,100+_t))])}function jd(e){const t=100/Hr,n=[];for(let o=0;o<Hr;o++){const s=o*t;n.push(St(fo(-_t,s,100+_t,s+e)))}return st(Et,n)}function Kd(e){return st(Et,[St(fo(-_t,50-e,100+_t,50+e))])}function qd(e){const t=100/Gr,n=[];for(let o=0;o<Gr;o++){const s=o*t;n.push(St(fo(s,-_t,s+e,100+_t)))}return st(Et,n)}function Yd(e){return st(Et,[St([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function Xd(e){const t=100/Bd,n=100/Fd,o=[];for(let s=0;s<Fd;s++)for(let i=0;i<Bd;i++){const r=i*t+t/2,a=s*n+n/2,l=t/2*e,c=n/2*e;o.push(St(fo(r-l,a-c,r+l,a+c)))}return st(Et,o)}function Zd(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<Hd;s++){const i=t+s/(Hd-1)*n;o.push([50+Math.cos(i)*zr,50+Math.sin(i)*zr])}return st(Et,[St(o)])}function rE(){return{from:zd(0),to:zd(sE)}}function aE(){return{from:Vd(0),to:Vd(52)}}function cE(){return{from:jd(0),to:jd(100/Hr+.5)}}function lE(){return{from:Kd(0),to:Kd(52)}}function dE(){return{from:qd(0),to:qd(100/Gr+.5)}}function uE(){return{from:Yd(0),to:Yd(zr)}}function fE(){return{from:Xd(0),to:Xd(1.04)}}function pE(){return{from:Zd(0),to:Zd(360)}}function hE(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function mE(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function wE(){return{from:st([[-60,0],[100,0],[100,100],[0,100]]),to:st([[100,0],[260,0],[260,100],[160,100]])}}const Vr=6,jr=100,wn=jr/2,Bs=200,Jd=90,Qd=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],gE="#101014",yE=1.25,gn="http://www.w3.org/2000/svg";let vE=0;function Fs(e){return Math.round(e*1e3)/1e3}function Kr(e){return e/Vr*Math.PI*2-Math.PI/2}function bE(e){const n=Kr(e)+Math.PI/Vr+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function EE(e){const t=Kr(e),n=Kr(e+1);return[[wn,wn],[wn+Math.cos(t)*Bs,wn+Math.sin(t)*Bs],[wn+Math.cos(n)*Bs,wn+Math.sin(n)*Bs]]}function eu(e,t){const n=EE(e),o=document.createElementNS(gn,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${Fs(s)} ${Fs(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",Qd[e%Qd.length]),o.setAttribute("stroke",gE),o.setAttribute("stroke-width",String(yE)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function _E(){const e=`os-iris-${++vE}`,t=document.createElementNS(gn,"svg");t.setAttribute("viewBox",`0 0 ${jr} ${jr}`),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(gn,"defs"),o=document.createElementNS(gn,"mask");o.setAttribute("id",e);const s=document.createElementNS(gn,"g"),i=document.createElementNS(gn,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let l=0;l<Vr;l++){const c=eu(l,!0),d=eu(l,!1);s.appendChild(c),i.appendChild(d),r.push({el:c,index:l},{el:d,index:l})}o.appendChild(s),n.appendChild(o),t.appendChild(n),t.appendChild(i);const a=document.createElement("div");return a.appendChild(t),{element:a,play:l=>r.map(({el:c,index:d})=>{const u=bE(d),f=Fs(u.x*Jd),p=Fs(u.y*Jd);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 po="none",SE=460,kE="cubic-bezier( 0.33, 0, 0.2, 1 )",tu=80,nu=4e3,IE=70,AE=600,ou=ie("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),Hs=ou.state.registry,CE=ou.state.listeners,su=/^[a-z0-9_/-]+$/;function iu(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function LE(e){return typeof e!="number"||!Number.isFinite(e)?SE:Math.min(nu,Math.max(tu,e))}const qr=0;function ru(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?qr:Math.min(nu,Math.max(tu,e))}function yn(e){return typeof e!="number"||!Number.isFinite(e)?IE:Math.min(AE,Math.max(0,e))}function au(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 cu(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=iu(e.from),r=iu(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 TE(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function Ue(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)"):su.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===po&&t.push('id ("none" is reserved)'):t.push(`id (must match ${su} — 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(...cu(r,`layers[ ${a} ]`))})):t.push(...cu(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):TE(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)"))}Te("WindowReveal",t,e);const n=e.id.trim().toLowerCase();Hs.set(n,{...e,id:n}),uu()}function NE(e){Hs.delete(e.toLowerCase())&&uu()}function lu(){const e=Array.from(Hs.values()),t=q(g.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 du(e){return lu().find(t=>t.id===e)}function OE(e){return Hs.has(e)}function uu(){const e=Array.from(CE);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Ue({id:"sweep",label:_("Sweep"),description:_("A straight edge travels across the window, uncovering the page behind it."),...mE(),duration:420}),Ue({id:"iris",label:_("Iris"),description:_("The page opens out from the centre of the window, like a camera shutter."),...rE(),duration:520}),Ue({id:"curtain",label:_("Curtain"),description:_("Two panels part from the middle of the window and slide off the sides."),...aE(),duration:480}),Ue({id:"blinds",label:_("Blinds"),description:_("Six horizontal slats retract at once, letting the page through between them."),...cE(),duration:560}),Ue({id:"diagonal",label:_("Diagonal"),description:_("A slanted edge sweeps off the trailing corner of the window."),...wE(),duration:460}),Ue({id:"rise",label:_("Rise"),description:_("The page rises into the window from the bottom edge upward."),...hE(),duration:440}),Ue({id:"shutter",label:_("Shutter"),description:_("Two panels part from the middle of the window and slide off the top and bottom."),...lE(),duration:480}),Ue({id:"slats",label:_("Slats"),description:_("Eight vertical slats retract at once, letting the page through between them."),...dE(),duration:560}),Ue({id:"diamond",label:_("Diamond"),description:_("The page opens out from the centre of the window through a growing rhombus."),...uE(),duration:520}),Ue({id:"mosaic",label:_("Mosaic"),description:_("The page arrives as a grid of tiles, each opening out from its own centre."),...fE(),duration:600}),Ue({id:"obturator",label:_("Camera shutter"),description:_("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:_E,duration:720,edgeLag:0}),Ue({id:"radar",label:_("Radar"),description:_("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...pE(),duration:760});const fu="desktop-mode-os-settings",vn="desktop-mode-os-settings",DE="custom-gradient",Gs="custom-image",Yr="galaxy",pu="custom",hu=[{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:"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 zs(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return hu;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:hu}function Xr(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:Yr}const Zr=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],Jr=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],Vs=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],js=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"}],RE=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],xE=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],bn={wallpaper:Yr,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,nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,stationHomeEnabled:!1,adminAssetCacheEnabled:!1,windowPrewarmEnabled:!1,showDesktopOnWallpaperClick:!1,confirmCloseAllWindows:!0,mioEnabled:!1,mioStyle:{appearance:{},physics:{}},showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,navPlacement:{},navOrder:[],mobileLayout:"auto",mobileTabs:[],dockPromotedPositions:{}},mu={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},wu=["dockRailRenderer","windowReveal","accent"],gu={windowRevealDuration:{min:80,max:4e3}},ME=/^[a-z0-9_-]+$/;[...Object.keys(mu),...wu,...Object.keys(gu)];function yu(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries(mu)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of wu){const i=t[s];typeof i=="string"&&ME.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(gu)){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 WE(e){const t=yu(e);return typeof t.dockRailRenderer=="string"&&Jb(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==po&&!OE(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!zs().some(n=>n.id===t.accent)&&delete t.accent,t}const PE=/^[a-z0-9_-]+$/,vu=128;function $E(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function Qr(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!PE.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>=vu)break;c===""||!$E(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>=vu)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:yu(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload",cssDeferred:t.cssDeferred===!0}}function UE(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=Qr(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const kt=ie("desktop-mode/desktop-themes",UE);function En(){return kt}function BE(){return kt.getState().themes.slice()}function ea(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return kt.getState().themes.find(n=>n.slug===t||n.id===e)??null}function ta(){return kt.getState().activeId}function FE(e){const t=Qr(e);if(!t)return null;const n=kt.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)),kt.setState({themes:n}),t}let ho=null;function bu(){if(ho)return ho;const e=window.openStationConfig?.desktopThemesUrl;return e?(ho=$e(e,{method:"GET",credentials:"same-origin"},{source:"desktop-mode/desktop-themes"}).then(t=>{if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.json()}).then(t=>{for(const n of t?.themes??[])FE(n)}).catch(()=>{ho=null}),ho):Promise.resolve()}function HE(e){const t=[];for(const n of e){const o=Qr(n);o&&t.push(o)}kt.setState({themes:t})}function GE(e){return kt.subscribe(e)}function Ks(e){const t=En().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=q(g.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function na(e){const t=En().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=q(g.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?zE(o):null}function zE(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 Bt={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"},VE={"desktop-mode-os-settings":Bt.OS_SETTINGS,"desktop-mode-recycle-bin":Bt.RECYCLE_BIN,"desktop-mode-bug-report":Bt.BUG_REPORT,"os-exit":Bt.EXIT_OPENSTATION,"os-pwa-install":Bt.PWA_INSTALL};function qs(e){if(typeof e!="string"||e==="")return"";const t=VE[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function jE(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Bt.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Bt?n:""}const Ys=ie("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 Eu(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 KE(e,t,n){const o=oa(Ys.state.parentSubs,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function qE(e,t,n){Eu(Ys.state.parentSubs,e,t,n)}function YE(e,t,n){Eu(Ys.state.nativeSubs,e,t,n)}function XE(e){const{readyWindows:t,loadingWindows:n,pendingSends:o}=Ys.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(g.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const ZE="os.activity.";function sa(e){return ZE+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let JE=0;const Ee={publish(e,t){A(sa(e),t)},subscribe(e,t){const n=`os/activity-sub/${++JE}`,o=sa(e);Z(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,ao(o,n))}},filter(e,t,...n){return q(sa(e),t,...n)}},QE=4e3,e_=200,t_=1200;function ue(e){const t=Ee.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return $s(()=>!n,()=>{o=n_(t)}),()=>{n=!0,o&&o()}}function n_(e){const t=r_(),n=document.createElement("os-toast");n.textContent=e.message,e.action&&(n.setAttribute("action",e.action.label),n.addEventListener("os-toast-action",()=>{e.action?.onClick(),l()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{e.onDismiss?.(),l()})),t.appendChild(n);let o=!1,s=null,i=e.duration??QE,r=0;const a=()=>{s!==null&&(window.clearTimeout(s),s=null)},l=()=>{o||(o=!0,a(),i_(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),s_()},e_))},c=()=>{o||e.persistent||s!==null||(r=Date.now(),s=window.setTimeout(l,i))},d=()=>{s!==null&&(i=Math.max(0,i-(Date.now()-r)),a())};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),n.addEventListener("os-toast-hold",u=>{if(u.detail?.held){d();return}i=Math.max(i,t_),c()}),o_(n),c(),Ee.publish("os/toast-shown",{...e}),l}let Xs=null,mo=0;function _u(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(Xs=t))}function o_(e){mo===0&&document.addEventListener("focusin",_u,!0),mo+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(Xs=n)}function s_(){mo=Math.max(0,mo-1),mo===0&&document.removeEventListener("focusin",_u,!0)}function i_(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||Xs?.isConnected===!0&&Xs.focus()}function r_(){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 a_="http://localhost/";function it(e,t){const n=typeof window<"u"&&window.location?window.location.href:a_,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 c_="os-overview",l_="os-system",Zs={mio:10,overview:20,system:30,exit:35},d_=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="currentColor"><rect x="6" y="6" width="23" height="23" rx="4"/><rect x="35" y="6" width="23" height="23" rx="4"/><rect x="6" y="35" width="23" height="23" rx="4"/><rect x="35" y="35" width="23" height="23" rx="4"/></svg>')}`,u_=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="6" stroke-linecap="round"><path d="M10 22h44M10 42h44"/><circle cx="24" cy="22" r="7" fill="currentColor" stroke="none"/><circle cx="42" cy="42" r="7" fill="currentColor" stroke="none"/></svg>')}`,f_="os-exit";function p_(){return{id:f_,title:_("Exit OpenStation"),navKind:"control",locked:!0,order:Zs.exit,icon:"dashicons-exit",onOpen:()=>{h_()}}}async function h_(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){ia(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{}ia(o)}function ia(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const Su=800;function m_(e,t=Su){window.setTimeout(()=>{if(e){ia(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const w_="desktop_mode_nonces",g_="desktop-mode/v1",y_=3e4,v_=3,_n=ie("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function ku(){return window.wp?.os?.config??{}}function b_(){const e=ku().restUrl;return e?it(e,g_):null}function E_(){_n.state.negativeConfirms=0}async function __(){const e=_n.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=v_)return;const t=b_();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<y_)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await $e(t,{credentials:"same-origin"},{silent:!0,source:"desktop-mode/plugin-presence"});if(o.status!==404){e.negativeConfirms+=1;return}if((await o.json())?.code!=="rest_no_route"){e.negativeConfirms+=1;return}S_()}catch{}finally{e.confirmInFlight=!1}}}function S_(){if(!_n.state.exiting){_n.state.exiting=!0,m_(ku().adminUrl||"");try{ue({message:_("OpenStation is no longer active. Returning to the WordPress dashboard…"),duration:Su})}catch{}}}function k_(){if(_n.state.booted)return;_n.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[w_]!==void 0){E_();return}__()}})}const I_=0,ra=40,Iu=250,A_=120,C_=250,wo="os-window__loading",Js="os-window__loading--visible",Qs=ie("desktop-mode/window-reveal-active",()=>({id:po,duration:qr}));function Au(e){Qs.state.id=typeof e=="string"&&e!==""?e:po}function L_(){const e=Qs.state.id;return!e||e===po?null:du(e)??null}function Cu(e){Qs.state.duration=ru(e)}function T_(){return Qs.state.duration}function N_({osSettings:e}){const t=e.getOsSettingsSnapshot();Au(t.windowReveal),Cu(t.windowRevealDuration),e.subscribeOsSettings(n=>{Au(n.windowReveal),Cu(n.windowRevealDuration)})}const Sn="os-window__reveal",go="os-window__reveal--edge",O_="os-window__reveal--custom",Ft="os-window__body--revealing",aa="data-os-reveal",ca="data-os-reveal-layer",It=new WeakMap,Lu=ie("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function Tu(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const D_="--os-window-reveal-duration",R_="--os-window-reveal-edge-thickness";function Nu(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 x_(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return ru(Nu(window.getComputedStyle(e).getPropertyValue(D_)))}catch{return 0}}function M_(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function W_(e,t){const n=M_(e,R_);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return yn(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return yn(t*Number(s[1]));const i=Nu(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?yn(i):null}function Ou(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 P_(e,t){const n=LE(t.duration),o=T_(),s=o!==qr?o:x_(e)||n,i=W_(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=yn(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:yn(r*s/n)}}function Du(e){return e.querySelector(":scope .os-window__body")}function $_(e){return e.querySelector(`:scope .${Sn}:not( .${go} )`)}function U_(e){return e.querySelector(`:scope .${go}`)}function Ru(e){return Array.from(e.querySelectorAll(`:scope .${Sn}:not( .${go} )`))}function xu(e){return Array.from(e.querySelectorAll(`:scope .${go}`))}function la(e){return Array.from(e.querySelectorAll(`:scope .${Sn}`))}function Mu(e,t,n,o){const s=document.createElement("div");s.className=o?`${Sn} ${go}`:Sn;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(aa,e.id),s.setAttribute(ca,String(n)),s.style.clipPath=t.from,s}function B_(){const e=L_();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(Sn),s.classList.add(O_),s.setAttribute("aria-hidden","true"),s.setAttribute(aa,e.id),s.setAttribute(ca,"0"),Lu.set(s,o.play),[s]}const t=au(e);if(t.length===0)return[];const n=[];return yn(e.edgeLag)>0&&t.forEach((o,s)=>n.push(Mu(e,o,s,!0))),t.forEach((o,s)=>n.push(Mu(e,o,s,!1))),n}function F_(e){const t=Du(e);if(t){t.classList.remove(Ft);for(const n of la(t))It.get(n)?.cancel(),It.delete(n),n.remove();for(const n of B_())t.appendChild(n)}}function Wu(e){const t=Du(e);if(!t)return;const n=$_(t);if(!n)return;let o;try{o=du(n.getAttribute(aa)??"")}catch(b){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",b)}if(!o){la(t).forEach(b=>b.remove());return}const i=!!t.querySelector(`:scope .${wo}`)?.classList.contains(Js)?Iu:0,{duration:r,edgeLag:a}=P_(t,o),l=o.easing??kE,c=Lu.get(n);if(c){t.classList.add(Ft);const b=()=>{It.delete(n),n.remove(),t.classList.remove(Ft)};if(Tu()||typeof n.animate!="function"){window.setTimeout(b,i);return}let W=[];try{W=c({duration:r,easing:l,delay:i})}catch(U){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,U)}if(W.length===0){b();return}W[0].addEventListener("finish",b),W[0].addEventListener("cancel",()=>{It.delete(n),t.classList.remove(Ft)}),It.set(n,W[0]);return}const d=U_(t);d&&(a<=0||Ou(d))&&xu(t).forEach(b=>b.remove()),Ou(n)&&Ru(t).forEach(b=>b.remove());const u=la(t);if(u.length===0)return;t.classList.add(Ft);const f=()=>{for(const b of u)It.delete(b),b.remove();t.classList.remove(Ft)};if(Tu()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,v=au(o),h=(b,W)=>{const U=v[Number(b.getAttribute(ca))];if(!U)return b.remove(),null;b.style.willChange="clip-path";let j;try{j=b.animate([{clipPath:U.from},{clipPath:U.to}],{duration:W,easing:p,delay:i,fill:"both"})}catch(B){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,B),b.remove(),null}return It.set(b,j),j},w=Ru(t).map(b=>h(b,r)).filter(b=>b!==null),E=xu(t).map(b=>h(b,r+a)).filter(b=>b!==null),S=w[0]??null,O=E[0]??null;if(!S&&!O){f();return}(O??S)?.addEventListener("finish",f);const M=()=>{for(const b of u)It.delete(b);t.classList.remove(Ft)};S?.addEventListener("cancel",M),O?.addEventListener("cancel",M)}const H_="os-window-tab-change";function Pu(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function $u(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function Uu(e,t){return`${e.id||"os-window"}-tab-${$u(t)}`}function Bu(e,t){return`${e.id||"os-window"}-panel-${$u(t)}`}function G_(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 z_(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 V_(e){const t=Pu(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 Fu(e){const t=new Map;for(const n of Pu(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function Hu(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 j_(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of Fu(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 Hu(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}V_(n),G_(n),e.dispatchEvent(new CustomEvent(H_,{bubbles:!0,detail:{value:t}}))}}function K_(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=Fu(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=Uu(e,d.value),u.setAttribute("aria-controls",Bu(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();z_(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of Hu(e)){const u=d.getAttribute("for");u&&(d.id=Bu(e,u),a?d.setAttribute("aria-labelledby",Uu(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&&j_(e,c)}const yo="os-window__body--loading",da="os-window__body--loading-out",ua="data-os-loading-at",Gu="data-os-loading-cycle";function ei(e){return e.getAttribute(Gu)??"0"}function q_(e){e.setAttribute(ua,String(Date.now())),e.setAttribute(Gu,String(Number(ei(e))+1))}function Y_(e,t){const n=Number(e.getAttribute(ua)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=A_-o;if(s<=0){t.classList.add(Js);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(yo)&&t.classList.add(Js)},s)}const X_=Symbol.for("desktop-mode/window-config");function Z_(e){return e[X_]}const zu=window.location.origin;function J_(e){const t=new URL(e,zu);return t.origin!==zu||lo(t)?null:(t.searchParams.set("openstation_chromeless","1"),t.toString())}function fa(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function Vu(){const e=document.createElement("div");e.className=wo,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",_("Loading window content")),e.appendChild(t),e}function Q_(e){let t=Vu();const n={windowId:e.id,config:e};if(typeof e.loading?.render=="function")try{e.loading.render(t,n)}catch(o){typeof console<"u"&&console.error(`[openstation] loading.render threw for "${e.id}":`,o)}try{const o=q(g.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(wo)&&t.classList.add(wo),t}function ju(e){e.querySelector(":scope .os-window__loading")?.remove()}function Ku(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=Z_(e),s=o?Q_(o):Vu();t.appendChild(s),Y_(t,s)}const eS=8,qu=Object.freeze({top:0,right:0,bottom:0,left:0});function Yu(e,t,n,o){return{left:e,top:t,width:n,height:o,right:e+n,bottom:t+o}}function tS(e,t){const n={top:Math.abs(t.top-e.top),bottom:Math.abs(e.bottom-t.bottom),left:Math.abs(t.left-e.left),right:Math.abs(e.right-t.right)},s=t.height>t.width?["left","right","top","bottom"]:["top","bottom","left","right"];let i=s[0];for(const r of s)n[r]<n[i]&&(i=r);return i}function nS(e,t,n=eS){const o={top:0,right:0,bottom:0,left:0};if(e.width<=0||e.height<=0)return o;for(const r of t){if(r.width<=0||r.height<=0)continue;const a=Math.min(e.right,r.right)-Math.max(e.left,r.left),l=Math.min(e.bottom,r.bottom)-Math.max(e.top,r.top);if(!(a<=0||l<=0))switch(tS(e,r)){case"bottom":o.bottom=Math.max(o.bottom,e.bottom-r.top+n);break;case"top":o.top=Math.max(o.top,r.bottom-e.top+n);break;case"left":o.left=Math.max(o.left,r.right-e.left+n);break;case"right":o.right=Math.max(o.right,e.right-r.left+n);break}}const s=Math.floor(e.height/2),i=Math.floor(e.width/2);return{top:Math.min(s,Math.ceil(o.top)),bottom:Math.min(s,Math.ceil(o.bottom)),left:Math.min(i,Math.ceil(o.left)),right:Math.min(i,Math.ceil(o.right))}}function Xu(e,t,n){return{x:n.left,y:n.top,width:Math.max(0,e-n.left-n.right),height:Math.max(0,t-n.top-n.bottom)}}function oS(e,t){const n=s=>Math.min(Math.max(0,t.width),Math.max(0,s)),o=s=>Math.min(Math.max(0,t.height),Math.max(0,s));return{top:o(e.top-t.top),bottom:o(t.bottom-e.bottom),left:n(e.left-t.left),right:n(t.right-e.right)}}function sS(e,t){return e.top===t.top&&e.right===t.right&&e.bottom===t.bottom&&e.left===t.left}function Zu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const iS="os-work-area-changed",rS="data-os-dock-behavior",aS="os/work-area";function cS(){return{insets:{...qu},rect:{x:0,y:0,width:0,height:0},viewport:{x:0,y:0,width:0,height:0},area:{width:0,height:0}}}const ut=ie(aS,()=>({snapshot:cS(),installed:!1,areaEl:null})),kn={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 pa(e){return{insets:{...e.insets},rect:{...e.rect},viewport:{...e.viewport},area:{...e.area}}}function lS(){return pa(ut.state.snapshot)}function he(e){const t=e??ut.state.areaEl;if(!t)return{...ut.state.snapshot.rect};const n=t.clientWidth||t.getBoundingClientRect().width,o=t.clientHeight||t.getBoundingClientRect().height;return Xu(n,o,ut.state.snapshot.insets)}function dS(e){const{installed:t,snapshot:n}=ut.state;if(!t)return{...qu};const o=n.viewport;return oS(Yu(o.x,o.y,o.width,o.height),e.getBoundingClientRect())}function ti(e){return ut.subscribe(t=>{e(pa(t.snapshot))})}function uS(e){const t=fS(e),n=[],o=e.shellBody.querySelectorAll(e.chromeSelector??".os-dock");for(const l of Array.from(o))l.hidden||l.getAttribute(rS)==="dynamic"||n.push(l.getBoundingClientRect());const s=nS(t,n),i=e.area.clientWidth||t.width,r=e.area.clientHeight||t.height,a=Xu(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 fS(e){const{area:t}=e;if(t.offsetWidth>0&&t.offsetParent===e.shellBody){const n=e.shellBody.getBoundingClientRect();return Yu(n.left+t.offsetLeft,n.top+t.offsetTop,t.offsetWidth,t.offsetHeight)}return t.getBoundingClientRect()}function pS(e,t){e.style.setProperty(kn.top,`${t.insets.top}px`),e.style.setProperty(kn.right,`${t.insets.right}px`),e.style.setProperty(kn.bottom,`${t.insets.bottom}px`),e.style.setProperty(kn.left,`${t.insets.left}px`),e.style.setProperty(kn.width,`${t.rect.width}px`),e.style.setProperty(kn.height,`${t.rect.height}px`)}function hS(e,t){return sS(e.insets,t.insets)&&Zu(e.rect,t.rect)&&Zu(e.viewport,t.viewport)&&e.area.width===t.area.width&&e.area.height===t.area.height}function mS(e){const t=new Map;let n=null,o=null,s=!1,i=!1,r=null;const a=()=>{if(s||i)return;const p=uS(e);if(!!ut.state.installed&&hS(ut.state.snapshot,p))return;pS(e.shell,p),ut.setState({snapshot:p,installed:!0,areaEl:e.area});const h=pa(p);A(g.WORK_AREA_CHANGED,h),document.dispatchEvent(new CustomEvent(iS,{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[v,h]of t)p.has(v)||(h.disconnect(),t.delete(v));for(const v of p){if(t.has(v))continue;const h=new ResizeObserver(a);h.observe(v),t.set(v,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 Z(g.OVERVIEW_ENTERING,ni,u),Z(g.OVERVIEW_EXITED,ni,f),c(),a(),r={refresh:a,destroy:()=>{s=!0,n?.disconnect(),o?.disconnect();for(const p of t.values())p.disconnect();t.clear(),document.removeEventListener("os-layout-changed",d),window.removeEventListener("resize",a),ao(g.OVERVIEW_ENTERING,ni),ao(g.OVERVIEW_EXITED,ni),oi===r&&(oi=null)}},oi=r,r}const ni="openstation/work-area";let oi=null;function wS(){oi?.refresh()}const gS={get:lS,rectOf:he,insetsOf:dS,subscribe:ti};function yS(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){Ju(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=SS(e,n),i=Ur(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=Ca(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"){vo(e);return}const u=e.getById(l.id);if(!u){vo(e);return}vS(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&vo(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 vS(e,t){const n=e._splitOverviewZone;if(!n){vo(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(g.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),vo(e)}function vo(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();Ju(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 Ju(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const Qu=30,bS=260;function ES(e,t){return e<=t.left+Qu?"left":e>=t.right-Qu?"right":null}function _S(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?0:n.width-o,y:0,width:o,height:s}}function SS(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 kS(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=_S(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()},bS)}function IS(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=ES(n,o),i=e._snapPendingZone;s?(kS(e,s),i!==s&&A(g.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(ha(e),A(g.SNAP_ZONE_CANCELED,{windowId:t.id}))}function AS(e,t){const n=e._snapPendingZone;return n?(ha(e),t.state==="normal"&&(t._savedGeometry={x:t.element.offsetLeft,y:t.element.offsetTop,width:t.element.offsetWidth,height:t.element.offsetHeight}),t.applySnap(n),A(g.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{yS(e,t,n)}),!0):!1}function ef(e){e._snapPendingZone&&ha(e)}const CS=6,LS=6,TS=8,NS={Shake:"shake"},tf="os-window--grid-snapping",nf="os-area--grid-snapping";function OS(e){const t={cols:CS,rows:LS},n=q(g.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 ma(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:of(Math.floor(s*o.cols),o.cols),row:of(Math.floor(i*o.rows),o.rows)}}function of(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t-1,e)):0}function DS(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 si(e,t,n,o){const s=DS(e,t,n,o),i=Math.round(TS/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 RS(e,t){return e.col===t.col&&e.row===t.row}function wa(e,t,n){const o=e._desktop.getBoundingClientRect();return{x:t-o.left,y:n-o.top}}function ga(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 xS(e,t,n,o){if(e._gridSnap)return;ef(e);const s=he(e._desktop),i=OS(s),r=wa(e,n,o),a=ma(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:si(a,a,s,i),overlayEl:l,targetEl:c,windowEl:t.element};e._gridSnap=d,t.element.classList.add(tf),e._desktop.classList.add(nf),ga(d,s),requestAnimationFrame(()=>{e._gridSnap===d&&l.classList.add("os-grid-snap--visible")}),A(g.GRID_SNAP_ARMED,{windowId:t.id,anchor:{...a},dims:{...i}}),A(g.GRID_SNAP_CHANGED,{windowId:t.id,anchor:{...a},cursor:{...a},rect:{...d.rect}})}function MS(e,t,n){const o=e._gridSnap;if(!o)return;const s=he(e._desktop),i=wa(e,t,n),r=ma(i.x,i.y,s,o.dims),a=si(o.anchor,r,s,o.dims),l=!RS(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,ga(o,s),(l||c)&&A(g.GRID_SNAP_CHANGED,{windowId:o.windowId,anchor:{...o.anchor},cursor:{...r},rect:{...a}})}function WS(e,t,n,o){const s=e._gridSnap;if(!s)return;const i=he(e._desktop),r=wa(e,t,n),a=ma(r.x,r.y,i,s.dims);s.anchor=a,s.cursor=a,s.rect=si(a,a,i,s.dims),ga(s,i),s.targetEl.classList.remove("os-grid-snap__target--reset"),s.targetEl.offsetWidth,s.targetEl.classList.add("os-grid-snap__target--reset"),A(g.GRID_SNAP_ANCHOR_RESET,{windowId:s.windowId,anchor:{...a},reason:o}),A(g.GRID_SNAP_CHANGED,{windowId:s.windowId,anchor:{...a},cursor:{...a},rect:{...s.rect}})}const PS=200;function sf(e){const t=e._gridSnap;if(!t)return null;e._gridSnap=null,t.windowEl.classList.remove(tf),e._desktop.classList.remove(nf);const n=t.overlayEl;return n.classList.remove("os-grid-snap--visible"),window.setTimeout(()=>n.remove(),PS),t}function $S(e){const t=sf(e);t&&A(g.GRID_SNAP_CANCELED,{windowId:t.windowId})}function US(e,t){const n=sf(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(g.GRID_SNAP_COMMITTED,{...s,anchor:{...n.anchor},cursor:{...n.cursor},dims:{...n.dims}}),A(g.WINDOW_DRAG_END,{windowId:t.id,x:o.x,y:o.y}),A(g.WINDOW_MOVED,{windowId:t.id,x:o.x,y:o.y}),A(g.WINDOW_RESIZED,{windowId:t.id,width:o.width,height:o.height}),!0}function rf(e,t){return si(e.anchor,e.cursor,t,{cols:e.cols,rows:e.rows})}function af(e,t){const n=e._gridSpan;if(!n||e.state!=="normal"&&e.state!=="minimized")return!1;const o=rf(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 BS(e){const t=he(e._desktop),n=[];for(const o of e._stack)af(o,t)&&(o._emitChange("moved"),n.push(o.id));return n.length>0&&A(g.GRID_SNAP_REFLOWED,{windowIds:n}),n}function FS(e){return ti(()=>{BS(e)})}function HS(e){return[e.id,e.menu?.url??"",e.entry?.url??"",e.windowId??"",e.title].join(`
2 `).toLowerCase()}function cf(e,t){const n=t.trim().toLowerCase();return n?HS(e).includes(n):!1}function GS(e,t){if(t.length===0)return[];const n=[],o=new Set;for(const s of e)o.has(s.id)||t.some(i=>cf(s,i))&&(o.add(s.id),n.push(s.id));return n}function lf(e,t){const n=[];for(const o of t){const s=e.find(i=>cf(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 zS=["index.php","upload.php","options-general.php"];function VS(){return[{id:"commerce",label:_("Commerce"),description:_("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:_("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:_("Learning"),description:_("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:_("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:_("Publishing"),description:_("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:_("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:_("New draft")},{match:"edit.php",url:"edit.php"}],layout:"focus"}]}const ya=new Map;function df(e){e?.id&&ya.set(e.id,e)}function va(e){ya.delete(e)}function bo(){const e=[...VS(),...ya.values()],t=q(g.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 jS(e){return bo().find(t=>t.id===e)??null}function uf(e,t){const n=[...e.apps,...e.apps.length?zS:[]],o=GS(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 KS=12,qS=["free","cascade","tile","columns","focus"],ff=["wallpaper","wallpaperSettings","customGradient","customImage","accent","customAccent","desktopTheme","desktopLayout","dockPlacement","dockSize","dockBehavior","sideDockBehavior","windowRadius","windowReveal","unfocusEffect","adminBarMode"];function pf(){return{preset:"",icon:"dashicons-desktop",color:"",apps:{mode:"all",ids:[]},widgets:{mode:"all",ids:[]},appearance:{},windows:[],layout:"free",provisioned:!0}}function YS(e){return e.kind!=="control"&&!e.locked}function XS(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)||!YS(i)||(s[i.id]="hidden");return s}function ZS(e){const t=e?.widgets;return!t||t.mode!=="only"?null:t.ids}function JS(e){const t=e?.appearance;if(!t)return null;const n={};for(const o of ff)t[o]!==void 0&&(n[o]=t[o]);return Object.keys(n).length>0?n:null}function hf(e){const t={};for(const n of ff)e[n]!==void 0&&(t[n]=e[n]);return t}function QS(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 Ht(e,t){return e.getDesktops().find(n=>n.id===t)?.profile??null}function ek(e){return Ht(e,e.getActiveDesktopId())}function In(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()&&ba(e,t),A(g.WORKSPACE_UPDATED,{desktopId:t,profile:n}),!0):!1}function tk(e,t){e.setVisibleWidgets?.(ZS(Ht(e.manager,t)))}function nk(e,t){e.setAppearance?.(JS(Ht(e.manager,t)))}function ba(e,t){nk(e,t),tk(e,t)}function Ea(e,t={}){const n=t.preset?jS(t.preset):null;let o=t.profile??null;!o&&n&&(o=q(g.WORKSPACE_PROFILE,uf(n,e.getNavItems()),n));const s=e.manager.createDesktop(),i=t.label??n?.defaultLabel??n?.label??"";return i&&e.manager.renameDesktop(s.id,i),o&&In(e,s.id,o),t.activate!==!1&&e.manager.switchDesktop(s.id),s}function mf(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 _a(e,t,n={}){const o=Ht(e.manager,t);if(!o||o.provisioned&&!n.force)return;In(e,t,{...o,provisioned:!0});const s=lf(e.getNavItems(),o.windows);let i=0;for(const a of s){if(a.url){const l=gf(a.url,e.adminUrl);i++,e.manager.open({id:e.deriveWindowId(l),url:l,title:a.title,icon:a.item.icon,desktopId:t}).then(c=>ii(e.manager,c,a)).catch(()=>{});continue}a.item.windowId&&(i++,e.openNative(a.item.windowId),wf(e.manager,a.item.windowId).then(l=>{l&&ii(e.manager,l,a)}))}const r=()=>{mf(e.manager,o.layout),A(g.WORKSPACE_PROVISIONED,{desktopId:t,opened:i,layout:o.layout})};typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>requestAnimationFrame(r)):r()}function ok(e,t){const n=Ht(e.manager,t);if(!n||!n.provisioned||n.windows.length===0)return;const o=lf(e.getNavItems(),n.windows);for(const s of o){if(s.url){const i=gf(s.url,e.adminUrl),r=e.deriveWindowId(i);if(e.manager.getById(r))continue;e.manager.open({id:r,url:i,title:s.title,icon:s.item.icon,desktopId:t}).then(a=>ii(e.manager,a,s)).catch(()=>{});continue}if(s.item.windowId){if(e.manager.getById(s.item.windowId))continue;e.openNative(s.item.windowId),wf(e.manager,s.item.windowId).then(i=>{i&&ii(e.manager,i,s)})}}}function Sa(e,t){const n=[],o=new Set,s=he(e._desktop);for(const i of e.getAll()){if((i.config.desktopId||e.getActiveDesktopId())!==t)continue;const r=i.config.baseId||i.id;if(o.has(r))continue;o.add(r);const a={match:r,title:i.config.title||r};if(i.config.native!==!0&&i.config.url&&(a.url=i.config.url),i._gridSpan)a.gridSpan={...i._gridSpan};else if(i.state==="normal"&&s.width>0&&s.height>0){const l=i.element;a.place=sk({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>=KS)break}return n}function sk(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 ii(e,t,n){const o=he(e._desktop);if(n.gridSpan){t._gridSpan={anchor:{...n.gridSpan.anchor},cursor:{...n.gridSpan.cursor},cols:n.gridSpan.cols,rows:n.gridSpan.rows},af(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 wf(e,t,n=8e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=l=>{document.removeEventListener("os-window-opened",r),window.clearTimeout(a),s(l)},r=l=>{l.detail?.windowId===t&&i(e.getById(t)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}function ik(e,t,n={}){const o=e.manager._desktops.find(r=>r.id===t);if(!o)return null;const i={...o.profile??pf(),windows:Sa(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]}),In(e,t,i),i}function gf(e,t){if(/^https?:\/\//i.test(e))return e;try{return new URL(e,t).href}catch{return t}}let At=null;function rk(e){return At=e,()=>{At=null}}function ak(){return At!==null}function ck(){return At?(At.openCreator(),!0):!1}function lk(e){return At?(At.openEditor(e),!0):!1}function yf(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 dk(e){const t=At;return t?(t.manager.switchDesktop(e),ba(t,e),_a(t,e,{force:!0}),!0):!1}const vf=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],ri="osHadFullscreenBeforeOverview";function bf(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[ri]="true",fa()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function Ef(e){if(e.element.dataset[ri]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[ri],fa();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[ri],fa()}}function ka(e,t=!0){t&&Ef(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function _f(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function Sf(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function uk(e){if(e._overviewActive)return;kf(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,A(g.OVERVIEW_ENTERING,{}),A(g.DOCK_REFRESH_ACTIVE,{});for(const c of vf){const d=document.getElementById(c);d&&(d.inert=!0)}_f(!0),Sf(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)bf(c);const n=e._desktop.getBoundingClientRect(),o=Array.from(document.querySelectorAll(".os-dock"));let s=0;for(const c of o){const d=c.getBoundingClientRect(),u=d.bottom>n.top&&d.top<n.bottom,f=d.height>d.width;u&&f&&(s+=d.width)}const i=new DOMRect(0,0,n.width+s,n.height);e._desktop.classList.add("os-area--overview"),document.getElementById("os-shell")?.classList.add("os-shell--overview"),e._overviewTopBar=If(e),e._desktop.appendChild(e._overviewTopBar);const a=Ur(t,i,Rd(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=Ca(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"){ft(e);return}const p=e.getById(d.id);A(g.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),ft(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){ft(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){Af(e);return}ft(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(g.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&A(g.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&A(g.OVERVIEW_ENTERED,{})},300)}function kf(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function fk(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 Ia=null;function pk(e){return Ia=e,()=>{Ia=null}}function If(e){const t=document.createElement("div");t.className="os-overview-top-bar";const n=Ia?.();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(yf)&&o.classList.add("os-overview-top-bar__list--restorable");for(const a of e._desktops)o.appendChild(hk(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",_("Add new desktop")),s.innerHTML='<span class="os-overview-top-bar__tile-preview"><span class="os-overview-top-bar__tile-plus" aria-hidden="true">+</span></span><span class="os-overview-top-bar__tile-label" aria-hidden="true">&nbsp;</span>',s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Af(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 Af(e){if(e._overviewAddTileFocused=!1,ck()){ft(e);return}const t=Lf(e);Aa(e,t.id)}function hk(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",re(_("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 u=document.createElement("span");u.className=`os-overview-top-bar__tile-glyph dashicons ${s.icon}`,u.setAttribute("aria-hidden","true"),i.appendChild(u)}const r=e._stack.filter(u=>u.config.desktopId===t.id).length;if(r>0){const u=document.createElement("span");u.className="os-overview-top-bar__tile-count",u.textContent=String(r),i.appendChild(u)}o.appendChild(i);const a=document.createElement("span");a.className="os-overview-top-bar__tile-label",a.textContent=t.label,o.appendChild(a),o.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),!a.hasAttribute("contenteditable")&&Aa(e,t.id)});const l=document.createElement("button");l.type="button",l.className="os-overview-top-bar__tile-rename",l.setAttribute("aria-label",re(_("Rename %s"),t.label)),l.innerHTML=bt("edit",{size:14}),l.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),mk(e,a,t)});const c=document.createElement("button");c.type="button",c.className="os-overview-top-bar__tile-close",c.setAttribute("aria-label",re(_("Close %s"),t.label)),c.innerHTML=bt("close",{size:16}),c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),Df(e,t.id),ai(e)}),n.appendChild(o),n.appendChild(l),n.appendChild(c);const d=document.createElement("div");if(d.className="os-overview-top-bar__tile-actions",yf(t)){const u=document.createElement("button");u.type="button",u.className="os-overview-top-bar__tile-action os-overview-top-bar__tile-restore",u.setAttribute("aria-label",re(_("Restore %s — reopen its windows, widgets and look"),t.label)),u.title=u.getAttribute("aria-label")??"",u.innerHTML=`${bt("windows",{size:12})}<span>${_("Restore")}</span>`,u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),dk(t.id)&&ft(e)}),d.appendChild(u)}if(ak()){const u=document.createElement("button");u.type="button",u.className="os-overview-top-bar__tile-action os-overview-top-bar__tile-edit",u.setAttribute("aria-label",re(_("Edit %s — its apps, widgets, look and windows"),t.label)),u.title=u.getAttribute("aria-label")??"",u.innerHTML=`${bt("settings",{size:12})}<span>${_("Edit")}</span>`,u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),Aa(e,t.id),lk(t.id)}),d.appendChild(u)}return d.childElementCount>0&&n.appendChild(d),n}function mk(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&&Nf(e,n.id,t.textContent??""),e._overviewActive&&ai(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 ai(e){if(!e._overviewTopBar)return;const t=If(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Aa(e,t){Of(e,t),ft(e)}function Ca(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=re($t("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function ft(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,A(g.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),A(g.DOCK_REFRESH_ACTIVE,{}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of vf){const r=document.getElementById(i);r&&(r.inert=!1)}_f(!1),Sf(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"&&(Ef(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"),ka(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(g.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>kf(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(g.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function wk(e){return[...e._desktops]}function Cf(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function gk(e){return Cf(e).id}function ci(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&ka(t)}function La(e){for(const t of e._stack)ci(e,t)}function yk(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?Ta(e):ci(e,o),A(g.WINDOW_DESKTOP_CHANGED,{windowId:t,from:s,to:n})),!0}function Lf(e,t){e._desktopSeq++;const n={id:`desktop-${e._desktopSeq}`,label:t?.label?.trim().slice(0,Tf)||re(_("Desktop %d"),e._desktopSeq)};return e._desktops.push(n),A(g.DESKTOP_CREATED,{desktopId:n.id}),n}const Tf=64;function Nf(e,t,n){const o=e._desktops.find(r=>r.id===t);if(!o)return!1;const s=n.trim().slice(0,Tf);if(!s||s===o.label)return!1;const i=o.label;return o.label=s,A(g.DESKTOP_RENAMED,{desktopId:t,label:s,previousLabel:i}),!0}function Of(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)Ta(e),ai(e);else{La(e),n?.direction&&vk(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&&Ob(e._desktop,i.label)}A(g.DESKTOP_SWITCHED,{from:o,to:t})}function vk(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 Df(e,t){if(e._desktops.length<=1)return;const n=e._desktops.findIndex(r=>r.id===t);if(n===-1)return;const o=n>0?n-1:1,s=e._desktops[o];for(const r of e._stack)r.config.desktopId===t&&(r.config.desktopId=s.id);e._desktops.splice(n,1),e._activeDesktopId===t&&(e._activeDesktopId=s.id),e._overviewActive?Ta(e):La(e),A(g.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function Ta(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"),ka(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),La(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||""}),bf(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=Ur(t,o,Rd(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=Ca(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function bk(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 Ek(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;A(g.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=he(e._desktop),o=30,s=30,i=Math.min(Math.round(n.width*.7),1100),r=Math.min(Math.round(n.height*.75),750),a=Math.max(1,Math.floor((n.width-i-o)/s)),l=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(a,l);t.forEach((u,f)=>{const p=f%Math.max(1,c);u._gridSpan=null,u.element.style.left=`${n.x+o+p*s}px`,u.element.style.top=`${n.y+o+p*s}px`,u.element.style.width=`${i}px`,u.element.style.height=`${r}px`});const d=e.getFocused();d&&e.focus(d),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"cascade"}})),A(g.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function Rf(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=he(e._desktop),o=Mb(t.length,n.width,n.height),s=q(g.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=Rb(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;A(g.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 v=p%i,h=Math.floor(p/i);f._gridSpan=null,f.element.style.left=`${n.x+a+v*(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(g.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}function xf(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 _k(e,t){const n=e.getFocused();n&&e.focus(n),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:t}}))}const Sk=4;function kk(e){const t=xf(e);if(t.length===0)return;if(t.length>Sk){Rf(e);return}const n=t.length;A(g.ARRANGE_COLUMNS_STARTING,{windowCount:t.length,cols:n});const o=he(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`}),_k(e,"columns"),A(g.ARRANGE_COLUMNS_APPLIED,{windowCount:t.length,cols:n})}const Mf=.64;function Ik(e){const t=xf(e);if(t.length===0)return;const n=he(e._desktop),o=q(g.ARRANGE_FOCUS_SPLIT,Mf,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),s=Number.isFinite(o)&&o>=.3&&o<=.9?o:Mf;A(g.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((v,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 v=n.x+i+p+r,h=a-p-r,w=Math.floor((l-r*(f.length-1))/f.length);f.forEach((E,S)=>{E.element.style.left=`${v}px`,E.element.style.top=`${n.y+i+S*(w+r)}px`,E.element.style.width=`${h}px`,E.element.style.height=`${w}px`})}e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"focus"}})),A(g.ARRANGE_FOCUS_APPLIED,{windowCount:t.length,split:s})}const Wf="desktop-mode-snap-to-grid";function Ak(){try{return window.localStorage.getItem(Wf)==="1"}catch{return!1}}function Ck(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(Wf,t?"1":"0")}catch{}A(g.ARRANGE_SNAP_CHANGED,{enabled:t})}}function Lk(e){if(!e._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const t=e._desktop.getBoundingClientRect(),n=t.width>=t.height?12:8,o={cellWidth:Math.max(40,Math.round(t.width/n)),cellHeight:Math.max(40,Math.round(t.height/Math.round(n*.66)))},s=q(g.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=xb(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}const Pf="desktop-mode-native-window-geometry",$f=64,rt=8192;function li(){try{const e=window.localStorage.getItem(Pf);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function Uf(e){try{window.localStorage.setItem(Pf,JSON.stringify(e))}catch{}}function di(e){if(!e)return null;const n=li()[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>rt||s>rt)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<=rt&&a<=rt;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function Bf(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>rt||o>rt)return;const s=li(),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||(Eo(s,e,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),_o(s))}function Ff(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>rt||o>rt)return;const s=li(),i=s[e];i&&(i.x===n&&i.y===o||(Eo(s,e,{...i,x:n,y:o}),_o(s)))}function Hf(e,t,n){if(!e)return;const o=li(),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>rt||r>rt)return;Eo(o,e,{width:i,height:r,state:t}),_o(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;Eo(o,e,r),_o(o);return}s.state!==t&&(Eo(o,e,{...s,state:t}),_o(o))}function Eo(e,t,n){delete e[t],e[t]=n}function _o(e){const t=Object.keys(e);if(t.length>$f){const n={};for(const o of t.slice(-$f))n[o]=e[o];Uf(n);return}Uf(e)}function Tk(e,t,n,o){const s=o.x+ra-n,i=o.x+o.width-ra,r=Math.max(s,Math.min(e,i)),a=o.y+I_,l=o.y+o.height-ra,c=Math.max(a,Math.min(t,l));return{x:r,y:c}}const Gf=100,ui=30;class Nk{constructor(t){this._stack=[],this._cascadeMinimized=new WeakSet,this._cascadeDepth=0,this.cascadeIndex=0,this._pendingRestoreState=new Map,this._prewarmed=null,this._prewarmInFlight=!1,this._desktops=[{id:"desktop-1",label:"Desktop 1"}],this._activeDesktopId="desktop-1",this._desktopSeq=1,this.onToggleStartupRequested=null,this.desktopResizeObserver=null,this._reflowRestoreTimer=null,this._snapEnabled=Ak(),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.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={x:0,y:0,width:n.clientWidth,height:n.clientHeight};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=Tk(s,i,r,o);(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=pn(t.url);c===pn(o.getCurrentUrl())||c===pn(o.config.url||"")||c===pn(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(g.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(pn(n.url)!==pn(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),ci(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(g.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)?t.id:this.nextInstanceId(n),s=40+this.cascadeIndex%8*ui,i=40+this.cascadeIndex%8*ui;return this.createWindow({initialState:"normal",x:s,y:i,...t,id:o,baseId:n})}async createWindow(t,n={}){const o=this._pendingRestoreState.get(t.id);o&&(this._pendingRestoreState.delete(t.id),t={...t,...o});const s=this._desktop.getBoundingClientRect(),i=he(this._desktop),r=12,a=Math.min(Math.round(i.width*.8),1200),l=Math.min(Math.round(i.height*.8),800),c=i.x+40+this.cascadeIndex%8*ui,d=i.y+40+this.cascadeIndex%8*ui,u=t.baseId||t.id,f=t.minWidth??320,p=t.minHeight??200,v=typeof t.width=="number",h=typeof t.height=="number",w=typeof t.x=="number",E=typeof t.y=="number",S=typeof t.initialState=="string",O=!v||!h||!S||!w||!E?di(u):null;let M=t.width??(O?Math.max(O.width,f):a),b=t.height??(O?Math.max(O.height,p):l);!w&&!E&&!O&&(M=Math.max(f,Math.min(M,i.width-r*2)),b=Math.max(p,Math.min(b,i.height-r*2)));const U=Math.max(i.x+r,Math.min(c,i.x+i.width-M-r)),j=Math.max(i.y+r,Math.min(d,i.y+i.height-b-r)),B=t.initialState??(O?.state==="maximized"?"maximized":void 0);let V,J;if(O&&typeof O.x=="number"&&typeof O.y=="number"){const z=Math.max(i.x,i.x+i.width-M-r),ee=Math.max(i.y,i.y+i.height-b-r);V=Math.max(i.x+r,Math.min(O.x,z)),J=Math.max(i.y+r,Math.min(O.y,ee))}const K=t.x??V??U,T=t.y??J??j,R=v||h||w||E||S,Y=!!O,X={x:K,y:T,width:M,height:b,state:B};let oe;try{oe=q(g.WINDOW_GEOMETRY,X,{windowId:t.id,baseId:u,hasSavedGeometry:Y,callerPinned:R,desktopRect:{width:s.width,height:s.height},workArea:{...i}})}catch(z){A(g.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:z}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,z),oe=X}const N=(z,ee)=>typeof z=="number"&&Number.isFinite(z)?z:ee,m=oe&&typeof oe=="object"?oe:X,k=Math.max(N(m.width,M),f),I=Math.max(N(m.height,b),p),D=N(m.x,K),$=N(m.y,T),x=m.state??B,C={icon:t.icon||"dashicons-admin-generic",...t,x:D,y:$,width:k,height:I,minWidth:f,minHeight:p,...x?{initialState:x}:{},baseId:u,desktopId:t.desktopId||this._activeDesktopId};if(t.gridSpan){const z=rf(t.gridSpan,he(this._desktop));C.x=z.x,C.y=z.y,C.width=z.width,C.height=z.height}this.cascadeIndex++;const[H]=await Promise.all([Cb(Ib()),Mr(Wr())]),P=H.createWindow(C);if(t.gridSpan&&(P._gridSpan={anchor:{...t.gridSpan.anchor},cursor:{...t.gridSpan.cursor},cols:t.gridSpan.cols,rows:t.gridSpan.rows}),P.onFocusRequest=z=>{this._cascadeDepth>0||this.focus(z)},P.onClose=z=>this.remove(z),P.onMinimize=z=>{this._cascadeDepth++;try{this.cascadeMinimize(z)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const ee=this._stack.filter(le=>le.state!=="minimized");ee.length>0&&this.focus(ee[ee.length-1])},P.onRestore=z=>{this._cascadeDepth++;try{this.cascadeRestore(z)}finally{this._cascadeDepth--}},P.onOpenAnother=z=>{const ee=z.config.baseId||z.id;z.config.native&&window.wp?.os?.openNewWindow?.(ee,{source:"open-another"})||this.openNew({id:ee,baseId:ee,url:z.config.url||"",title:z.config.title,icon:z.config.icon,submenu:z.config.submenu,multi:!0})},P.onOpenInNewWindow=z=>{const ee=z.config.baseId||z.id;if(z.config.native&&window.wp?.os?.openNewWindow?.(ee,{source:"open-in-new-window"}))return;const le=z.getCurrentUrl();this.openNew({id:ee,baseId:ee,url:le||z.config.url||"",title:z.config.title,icon:z.config.icon,submenu:z.config.submenu,multi:!0})},P.onToggleStartup=z=>{this.onToggleStartupRequested?.(z)},P.snapConfigProvider=()=>this.getSnapConfig(),P.onDragMove=(z,ee,le)=>{if(this._gridSnap){MS(this,ee,le);return}IS(this,z,ee)},P.onDragGesture=(z,ee)=>{switch(ee.type){case"modifier":ee.active?xS(this,z,ee.clientX,ee.clientY):$S(this);break;case"shake":WS(this,ee.clientX,ee.clientY,NS.Shake);break}},P.onDragEnd=z=>this._gridSnap?US(this,z):this._snapPendingZone?AS(this,z):(ef(this),!1),n.prewarm)return P.element.style.display="none",P.element.setAttribute("aria-hidden","true"),this._desktop.appendChild(P.element),P;this._stack.push(P),this._desktop.appendChild(P.element),ci(this,P),P.hydrateNative(),this.focus(P);const ce={windowId:P.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:ce})),A(g.WINDOW_OPENED,ce),P}nextInstanceId(t){const n=new Set(this._stack.map(s=>s.id));if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=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(g.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&&q(g.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(Gf+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(g.WINDOW_BLURRED,l)}const a={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:a})),A(g.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(Gf+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=di(n.baseId||n.id),i=!!s&&typeof s.x=="number"&&typeof s.y=="number";let r={};if(n.x===void 0&&n.y===void 0&&!i){const a=o.getSnapshot(),l=n.width??Math.round(a.width*.8),c=n.height??Math.round(a.height*.8),d=he(this._desktop),u=Math.max(d.x,d.x+d.width-l),f=Math.max(d.y,d.y+d.height-c);r={width:l,height:c,x:Math.min(u,Math.max(d.x,Math.round(a.x+(a.width-l)/2))),y:Math.min(f,Math.max(d.y,Math.round(a.y+(a.height-c)/2)))}}return this.open({...n,...r,desktopId:o.config.desktopId,parentWindowId:t})}ownerOf(t){const n=t.config.parentWindowId;return n?this.getById(n):void 0}childrenOf(t){const n=typeof t=="string"?t:t.id;return this._stack.filter(o=>o.config.parentWindowId===n)}blockingChildOf(t){let n=t,o;const s=new Set([t]);for(;;){const i=this.childrenOf(n).filter(r=>r.state!=="minimized"&&!s.has(r));if(i.length===0)return o;n=i[i.length-1],s.add(n),o=n}}enforceOwnershipOrder(){if(!this._stack.some(s=>s.config.parentWindowId))return;const t=[],n=new Set,o=(s,i)=>{if(!(n.has(s)||i.has(s))){if(i.add(s),s.state!=="minimized"){const r=this.ownerOf(s);r&&r!==s&&o(r,i)}n.has(s)||(n.add(s),t.push(s))}};for(const s of this._stack)o(s,new Set);this._stack.length=0,this._stack.push(...t)}cascadeMinimize(t){for(const n of this.childrenOf(t))n.state!=="minimized"&&(this._cascadeMinimized.add(n),n.minimize())}cascadeRestore(t){for(const n of this.childrenOf(t))this._cascadeMinimized.has(n)&&(this._cascadeMinimized.delete(n),n.restore())}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);const o=this.childrenOf(t).slice();if(o.length>0){this._cascadeDepth++;try{for(const r of o)this._cascadeMinimized.delete(r),r.close()}finally{this._cascadeDepth--}}for(let r=this._stack.length-1;this._cascadeDepth===0&&r>=0;r--){const a=this._stack[r];if(!(a.state==="minimized"||(a.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(a);break}}const s={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("os-window-closing",{detail:s})),A(g.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),A(g.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 wk(this)}getActiveDesktop(){return Cf(this)}getActiveDesktopId(){return gk(this)}createDesktop(t){return Lf(this,t)}switchDesktop(t,n){Of(this,t,n)}closeDesktop(t){Df(this,t)}renameDesktop(t,n){return Nf(this,t,n)}moveWindowToDesktop(t,n){return yk(this,t,n)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=q(g.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(g.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=q(g.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(g.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(){Ek(this)}tile(){Rf(this)}columns(){kk(this)}focusLayout(){Ik(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){Ck(this,t)}getSnapConfig(){return Lk(this)}enterOverview(){if(Pt()){document.dispatchEvent(new CustomEvent("os-mobile-open-switcher"));return}uk(this)}exitOverview(t,n=!1){ft(this,t,n)}destroy(){this._overviewActive&&ft(this),this.discardPrewarmed(),fk(this),Db()}getVisibleRects(){return this._stack.map(t=>{const n=t.getSnapshot();return{windowId:t.id,rect:{x:n.x,y:n.y,width:n.width,height:n.height},state:n.state,element:t.element}})}sanitizeParams(t){const n={};for(const[o,s]of Object.entries(t))(typeof s=="string"||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s))&&(n[o]=s);return Object.keys(n).length>0?n:void 0}snapshot(){const t=this.getFocused(),o=this._stack.filter(a=>!a.config.ephemeral&&!a.config.parentWindowId).map(a=>{const l=a.getSnapshot(),c=a.getExternalTabsSnapshot(),d=!!a.config.native,u=a.config.params,f=d&&u?this.sanitizeParams(u):null;return{id:a.id,baseId:a.config.baseId||a.id,desktopId:a.config.desktopId||this._activeDesktopId,...d?{native:!0}:{},...f?{params:f}:{},url:d?a.config.url||`#${a.id}`:a.getCurrentUrl(),title:a.config.title,icon:a.config.icon,state:l.state,x:l.x,y:l.y,width:l.width,height:l.height,...c.length>0?{externalTabs:c}:{},...a._gridSpan?{gridSpan:{...a._gridSpan}}:{}}}),s=t&&!t.config.ephemeral&&!t.config.parentWindowId?t.id:"",i={windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Date.now()},r=q(g.SESSION_SNAPSHOT,i);return r&&Array.isArray(r.windows)?r:i}seedWindowRestoreState(t){this._pendingRestoreState=new Map(Object.entries(t))}seedDesktops(t,n){bk(this,t,n)}}function Ok(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 zf(e,t){if(e._overviewActive)return;const n=Ok(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 Vf=!1;function jf(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;return Kf(t)}function Kf(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 Dk(e){if(Vf)return;Vf=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(jf(document)||(n.preventDefault(),zf(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"||zf(e,o.direction==="prev"?"prev":"next")})}let So=null;function Rk(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:Kf(n)}function xk(e=window){if(So)return So;const t=o=>{Rk(o)&&o.stopPropagation()};e.addEventListener("keydown",t,!0);const n=()=>{e.removeEventListener("keydown",t,!0),So===n&&(So=null)};return So=n,n}function qf(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 Yf(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,ai(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function Mk(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function Wk(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Xf(e){return e._overviewActive?(e.exitOverview(),!0):!1}function Pk(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function $k(e){return Pk(e)?(e.toggleShowDesktop(),!0):!1}let Zf=!1;function Uk(e){Zf||(Zf=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||Pt()||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||jf(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Yf(e,"prev"):qf(e,"prev");break;case"ArrowRight":n=e._overviewActive?Yf(e,"next"):qf(e,"next");break;case"ArrowUp":n=Xf(e)||$k(e)||Mk(e);break;case"ArrowDown":n=Xf(e)||Wk(e);break}n&&t.preventDefault()},!0))}async function An(e){return await Mr(Wr()),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 Bk="os-window-close-all";function Fk(e){return e.code!=="KeyW"||e.getModifierState?.("AltGraph")||!(e.ctrlKey||e.metaKey)?!1:e.altKey&&!e.shiftKey}let Na=!1;function Jf(e){const t=e.getActiveDesktopId();return e.getAll().filter(n=>(n.config.desktopId||t)===t)}async function Qf(e,t){if(Na)return 0;const n=Jf(e);if(n.length===0)return 0;if(t&&!t.shouldAsk())return ep(e);const o=t?{rememberLabel:_("Don't ask again"),onRemember:i=>{i&&t.setAsk(!1)}}:{};Na=!0;let s=!1;try{s=await An({title:_("Close all windows?"),message:re($t("%d open window on this desktop will be closed.","%d open windows on this desktop will be closed.",n.length),n.length),confirmLabel:_("Close all"),danger:!0,...o})}finally{Na=!1}return s?ep(e):0}const Hk=700,Gk=50;function zk(e,t){const n=()=>t.filter(o=>!e.getById(o)).length;return new Promise(o=>{const s=Date.now()+Hk,i=()=>{const r=n();if(r===t.length||Date.now()>=s){o(r);return}setTimeout(i,Gk)};i()})}async function ep(e){e._overviewActive&&e.exitOverview();const t=Jf(e).map(s=>s.id),n=e.getAll().map(s=>s.id).filter(s=>!t.includes(s));e.closeAll({exceptIds:n});const o=await zk(e,t);return o>0&&ue({message:re($t("Closed %d window.","Closed %d windows.",o),o)}),o}let tp=!1;function Vk(e,t){if(tp)return;tp=!0,document.addEventListener("keydown",o=>{Fk(o)&&(o.preventDefault(),o.stopImmediatePropagation(),Qf(e,t))},!0);const n=window.location.origin;window.addEventListener("message",o=>{if(o.origin!==n)return;const s=o.data;!s||s.type!==Bk||Qf(e,t)})}const np=Iu;let op=!1;function sp(e){return e?document.getElementById(`wp-window-${e}`):null}function jk(){op||(op=!0,Kk())}function Kk(){Z(g.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=sp(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove(da),n.classList.add(yo),q_(n),Ku(t),F_(t))}),Z(g.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=sp(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 .${wo}`)?.classList.contains(Js);if(n.classList.remove(yo),n.removeAttribute(ua),!o){ju(t),Wu(t);return}n.classList.add(da);const s=ei(n);Wu(t),window.setTimeout(()=>{ei(n)===s&&(n.classList.contains(yo)||ju(t))},np),window.setTimeout(()=>{ei(n)===s&&(n.classList.contains(yo)||n.classList.remove(da))},np+C_)}),Z(g.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>ip())})}function ip(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),Ku(n))})}const qk="os_person_view";function Yk(e){return e.searchParams.has(qk)}const ko=ie("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function Xk(e){ko.state.deps=e}function Ct(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=ko.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Zk(e.id)}function Zk(e){const t=ko.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function fi(e){const{deps:t,remaps:n}=ko.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 Ze(e){const{deps:t,remaps:n}=ko.state;if(!t||!e)return!1;let o;try{o=new URL(e,t.adminUrl)}catch{return!1}const s=t.getSnapshot();for(const i of n){if(!i.matches(e,o)||i.enabled&&!i.enabled(s))continue;if(i.onMatch)try{i.onMatch(e,o)}catch(l){console.warn(`[openstation] URL remap onMatch hook threw for "${i.id}":`,l)}let r;if(i.params)try{r=i.params(e,o)??void 0}catch(l){console.warn(`[openstation] URL remap params hook threw for "${i.id}":`,l)}if(r?t.openById(i.nativeWindowId,{params:r}):t.openById(i.nativeWindowId))return!0}return!1}const Jk="desktop_mode_classic";function Qk(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has("page")&&!e.searchParams.has(Jk)}const Oa=ie("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function eI(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=Oa.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>rp(e.id)}function rp(e){const t=Oa.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function tI(){return Oa.state.entries.slice()}const nI=32,oI=64,sI=/^[a-z0-9_/-]+$/,ge=ie("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function Gt(e){return`${e.type}:${e.id}`}function ap(e){return e.root?Gt(e.root):Gt(e)}function cp(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&sI.test(o.trim().toLowerCase());return Ut(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 lp(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function iI(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,nI).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=lp(e.previewUrl);o&&(n.previewUrl=o);const s=lp(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,oI).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 dp(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 Da(e){return e?[Gt(e),ap(e),...(e.links??[]).map(t=>Gt(t)+(t.rel==="child"?"!child":""))].join("|"):""}function pi(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Te("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=cp(t);if(a.length>0){o==="api"&&Te("WindowContentRef",a,t),Ud("WindowContentRef",a,t);return}s=iI(t,o)}if(s=q(g.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||cp(s).length>0)){Ud("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=ge.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&Da(s)===Da(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&s.revisionsUrl===i.revisionsUrl&&s.revisionCount===i.revisionCount&&dp(s)===dp(i))return;s===null?ge.state.contentByWindow.delete(e):ge.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(g.WINDOW_CONTENT_CHANGED,r),dI(),cI()}function Je(e){return ge.state.contentByWindow.get(e)}function Ra(){const e=new Map;for(const[s,i]of ge.state.contentByWindow){const r=ap(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=ge.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=q(g.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 up(e){return Ra().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function rI(e){const t=new Set,n=up(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of fp())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function fp(){const e=ge.state.focusSeq,t=new Map;for(const[a,l]of ge.state.contentByWindow){const c=Gt(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 ge.state.contentByWindow){if(l.root){const c=t.get(Gt(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(Gt(c));if(!d||d===a)continue;if(c.rel==="child"){const f=o(d,a),p=n.get(f);(!p||p.kind!=="child-root")&&n.set(f,{fromWindowId:d,toWindowId:a,kind:"child-root",bidirectional:!1});continue}const u=o(a,d);n.has(u)||n.set(u,{fromWindowId:a,toWindowId:d,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[a,l]of n){if(i.has(a))continue;const c=o(l.toWindowId,l.fromWindowId),d=n.get(c);if(d&&l.kind==="reference"){if(d.kind==="reference"){i.add(c),s.push({...l,bidirectional:!0});continue}continue}s.push(l)}const r=q(g.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 aI(e){return ge.state.listeners.add(e),()=>{ge.state.listeners.delete(e)}}function cI(){for(const e of Array.from(ge.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function lI(){return Array.from(ge.state.contentByWindow).map(([e,t])=>`${e}=${Da(t)}`).sort().join(";")}function dI(){const e=lI();if(e===ge.state.lastGroupsSignature)return;ge.state.lastGroupsSignature=e;const n={groups:Ra()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),A(g.WINDOW_LINK_GROUPS_CHANGED,n)}const uI={get:Je,set:(e,t)=>pi(e,t,{source:"api"}),groups:Ra,edges:fp,groupOf:up,related:rI,subscribe:aI};function fI({manager:e}){ge.state.manager=e,!ge.state.started&&(ge.state.started=!0,Z(g.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=ge.state.manager?.getById(t.windowId)?.config?.content;o&&pi(t.windowId,o,{source:"config"})}),Z(g.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(ge.state.focusSeq.delete(t.windowId),pi(t.windowId,null,{source:"config"}))}),Z(g.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(ge.state.seq+=1,ge.state.focusSeq.set(t.windowId,ge.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=ge.state.manager?.findByIframeSource?.(t.source);o&&pi(o.id,n.identity??null,{source:"bridge"})}))}const pI=ie("desktop-mode/admin-link-deps",()=>({deps:null}));function hI(e){pI.state.deps=e}const pp=ie("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),Cn=pp.state.seed,mI=pp.state.listeners;function Ln(e){Te("Wallpaper",Ut(e,wp),e);const t=Cn.findIndex(n=>n.id===e.id);t>=0?Cn[t]=e:Cn.push(e),mp()}function hp(e){const t=Cn.findIndex(n=>n.id===e);t>=0&&(Cn.splice(t,1),mp())}function mp(){const e=Array.from(mI);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function xa(){const e=Cn.slice(),t=q(g.WALLPAPERS,e);return Array.isArray(t)?t.filter(wI):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function Io(e){return xa().find(t=>t.id===e)}const wp=[{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 wI(e){return Ut(e,wp).length===0}const gp=ie("desktop-mode/wallpaper-settings",()=>({values:{}}));function gI(e){return{...gp.state.values[e]??{}}}function yI(e){const t=gp.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const vI=20,Ma=1,hi=24,Tn="os-dock--revealed",Ao="data-os-dock-behavior",bI="os-dock",yp="os-side-dock",mi="os-dock-vt",EI=".os-constellation, .os-dock-peek";function _I(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 vp(e){return e.getAttribute(Ao)==="dynamic"}function SI(e,t,n,o,s,i=vI){switch(e){case"bottom":return n>=s-i;case"left":return t<=i;case"right":return t>=o-i}return!1}function kI(e,t,n,o){const s=e.getBoundingClientRect();if(s.width<=0||s.height<=0)return!1;let i=s.top-hi;const r=s.bottom+hi;let a=s.left-hi,l=s.right+hi;switch(t){case"bottom":i=s.top-s.height*Ma;break;case"left":l=s.right+s.width*Ma;break;case"right":a=s.left-s.width*Ma;break}return n>=a&&n<=l&&o>=i&&o<=r}function II(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function AI(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=b=>{const W=e.getBehaviors(),U=b.id===yp?W.sidebar:W.dock;b.getAttribute(Ao)!==U&&b.setAttribute(Ao,U)},d=b=>{const W=b.ownerDocument.activeElement;if(W&&b.contains(W))return!0;if(!n)return!1;if(o)return b.classList.contains(Tn);const U=_I(b);return SI(U,n.x,n.y,window.innerWidth,window.innerHeight)||b.classList.contains(Tn)&&kI(b,U,n.x,n.y)},u=(b,W)=>{if(b.classList.contains(Tn)===W){i.delete(b);return}if(!W&&r){a=!0;return}if(s.has(b)){i.set(b,W);return}const U=()=>{b.classList.toggle(Tn,W)},j=document;if(typeof j.startViewTransition!="function"||II()){U();return}const B=`os-dock-${b.id||"rail"}`;b.style.setProperty("view-transition-name",B),document.documentElement.classList.add(mi);let V;try{V=j.startViewTransition(U)}catch{b.style.removeProperty("view-transition-name"),document.documentElement.classList.remove(mi),U();return}const J=V.finished&&typeof V.finished.then=="function"?V.finished:Promise.resolve(),K=()=>{b.style.removeProperty("view-transition-name"),s.delete(b),s.size===0&&document.documentElement.classList.remove(mi);const T=i.get(b);i.delete(b),!t&&T!==void 0&&u(b,T)};s.set(b,J.then(K,K))},f=()=>{if(!t)for(const b of l()){if(c(b),!vp(b)){b.classList.remove(Tn);continue}u(b,d(b))}},p=b=>{if(t||!l().some(vp))return;n={x:b.clientX,y:b.clientY};const W=b.target;o=W instanceof Element&&W.closest(EI)!==null,f()};let v=0;const h=()=>{v||(v=requestAnimationFrame(()=>{v=0,f()}))},w=()=>f(),E=()=>{r=!0},S=()=>{r=!1,a&&(a=!1,f())};document.addEventListener("pointerdown",E,{capture:!0,passive:!0}),document.addEventListener("pointerup",S,{capture:!0,passive:!0}),document.addEventListener("pointercancel",S,{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",w);let O=null;typeof MutationObserver<"u"&&(O=new MutationObserver(f),O.observe(e.shellBody,{childList:!0})),f();const M={refresh:f,destroy:()=>{t=!0,v&&(cancelAnimationFrame(v),v=0),O?.disconnect(),document.removeEventListener("pointerdown",E,{capture:!0}),document.removeEventListener("pointerup",S,{capture:!0}),document.removeEventListener("pointercancel",S,{capture:!0}),document.removeEventListener("pointermove",p),document.removeEventListener("pointerdown",p),document.removeEventListener("focusin",h),document.removeEventListener("focusout",h),document.removeEventListener("os-layout-changed",w);for(const b of l())b.classList.remove(Tn),b.style.removeProperty("view-transition-name");i.clear(),document.documentElement.classList.remove(mi),wi===M&&(wi=null)}};return wi=M,M}let wi=null;function CI(){wi?.refresh()}function bp(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const Ep=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","linerWidth","linerColor","glow","glowBlur","eyeColor","eyeScale"],_p=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function Wa(){return{appearance:{},physics:{}}}function LI(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function gi(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&&LI(i)&&Object.assign(n,{[s]:i})}return n}function Sp(e){if(!e||typeof e!="object"||Array.isArray(e))return Wa();const t=e;return{appearance:gi(t.appearance,Ep),physics:gi(t.physics,_p)}}function TI(e){return{appearance:gi(e,Ep),physics:gi(e,_p)}}function NI(){const e=OI();if(e){const t=$a(e,Pa());return Ua(t),PI(t),t}try{const t=window.localStorage.getItem(fu);if(t)return $a(JSON.parse(t),Pa())}catch{}return Pa()}function Pa(){const e=Lp();return e.wallpaper=Xr(),e}function OI(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}const He=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Se=(e,t)=>typeof e=="boolean"?e:t,zt=e=>(t,n)=>e.some(o=>o.id===t)?t:n,Nn=e=>(t,n)=>typeof t=="string"&&e.test(t)?t:n,yi=/^[a-z0-9_/-]+$/,kp={wallpaper:(e,t)=>typeof e=="string"&&e!==""?e:t,accent:(e,t)=>e===pu||zs().some(n=>n.id===e)?e:t,customAccent:Nn(/^#[0-9a-fA-F]{6}$/),dockSize:zt(Zr),windowRadius:zt(Jr),adminBarMode:zt(Vs),desktopLayout:zt(xE),dockPlacement:zt(RE),dockBehavior:zt(js),sideDockBehavior:zt(js),dockRailRenderer:Nn(/^[a-z0-9_-]+$/),desktopTheme:Nn(/^[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:Nn(yi),windowReveal:Nn(yi),windowRevealDuration:(e,t)=>typeof e!="number"||!Number.isFinite(e)?t:e>0?Math.min(4e3,Math.max(80,Math.round(e))):0,windowLinkRenderer:Nn(yi),windowLinkVisibility:(e,t)=>e==="focus"||e==="always"||e==="off"?e:t,windowLinksEnabled:Se,windowLinkRaiseOnFocus:Se,windowLinkHighlight:Se,customGradient:(e,t)=>He(e)?HI(e):{...t},customImage:(e,t)=>e===null||He(e)?GI(e):t,wallpaperSettings:(e,t)=>He(e)?RI(e):t,libraryHdOnly:Se,ai:(e,t)=>FI(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,nativeUsersEnabled:Se,nativePluginsEnabled:Se,nativeCommentsEnabled:Se,stationHomeEnabled:Se,adminAssetCacheEnabled:Se,windowPrewarmEnabled:Se,showDesktopOnWallpaperClick:Se,confirmCloseAllWindows:Se,mioEnabled:Se,mioStyle:(e,t)=>He(e)?Sp(e):t,showPostStatusRibbons:Se,developerModeEnabled:Se,foldersSharingEnabled:Se,navPlacement:(e,t)=>He(e)?xI(e):t,navOrder:(e,t)=>Array.isArray(e)?Ap(e):t,mobileLayout:(e,t)=>e==="auto"||e==="desktop"||e==="mobile"?e:t,mobileTabs:(e,t)=>Array.isArray(e)?Ap(e).slice(0,3):t,dockPromotedPositions:(e,t)=>He(e)?MI(e):t},Ip=Object.keys(kp);function $a(e,t){const n=On(t),o=e,s=kp;for(const i of Ip)i in o&&(n[i]=s[i](o[i],n[i]));return n}const DI=new Set(["wallpaper","accent","customAccent","customGradient","customImage","wallpaperSettings","dockSize","windowRadius","adminBarMode","desktopLayout","dockPlacement","dockBehavior","sideDockBehavior","dockRailRenderer","desktopTheme"]);function RI(e){if(!He(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(o===""||!yi.test(o)||!He(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 xI(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 Ap(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 MI(e){const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(s===""||!He(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 vi=null;const WI=250;let Vt=null;function PI(e){Vt=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(),navPlacement:{...e.navPlacement},navOrder:e.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function $I(e,t={}){Ua(e),UI(e,t.windowId)}function Ua(e){try{window.localStorage.setItem(fu,JSON.stringify(e))}catch{}}function UI(e,t){vi!==null&&clearTimeout(vi),t&&(Ba=t),Lt("pending"),vi=setTimeout(()=>{vi=null;const n=Ba;Ba=null,Cp(e,n)},WI)}let Ba=null;function BI(e){if(!Vt)return{...e};const t=Vt,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 Fa=!1,Ha=null;function Cp(e,t){if(Fa){Ha={state:e,windowId:t},Lt("pending");return}const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Lt("saved");return}const i=BI(e);if(!i){Lt("saved");return}Lt("saving"),Fa=!0;const r=On(e),a=t||vn;$e(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:i})},{windowId:a}).then(l=>{if(!l.ok)throw new Error(`${l.status} ${l.statusText}`);Vt=r,Lt("saved")}).catch(l=>{bi=!0,Vt?(Ua(Vt),Lt("failed",l instanceof Error?l.message:String(l),On(Vt))):Lt("failed",l instanceof Error?l.message:String(l))}).finally(()=>{Fa=!1;const l=Ha;if(Ha=null,l&&bi){bi=!1;return}bi=!1,l&&Cp(l.state,l.windowId)})}let bi=!1;function Lt(e,t,n){const o={phase:e};t&&(o.error=t),n&&(o.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:o}))}function Lp(){return On(bn)}function FI(e,t=bn.ai){if(!He(e))return{...t};const{enabled:n}=e;return{enabled:typeof n=="boolean"?n:t.enabled}}function HI(e){if(!He(e))return{...bn.customGradient};const{from:t,to:n,angle:o}=e;return{from:bp(t)?t:bn.customGradient.from,to:bp(n)?n:bn.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:bn.customGradient.angle}}function GI(e){if(!He(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 Ga(e){if(!e)return 214;let t=5381;for(let n=0;n<e.length;n++)t=Math.imul(t,33)+e.charCodeAt(n);return(t%360+360)%360}function zI(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function Ei(e,t,n){if(!zI(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 VI="data-os-constellation";function jI(){return document.body.hasAttribute(VI)}const Tp="os-item-menu-opening",KI=180,qI=220,Np=32;function Op(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"&&(jI()&&(t.dataset.menuSlug||t.dataset.constellationId)||YI(e)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},KI))))},u=h=>{n&&h.relatedTarget instanceof Node&&n.contains(h.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},qI)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=XI(e,()=>c(),r),document.body.appendChild(n),oA(n),sA(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())})},v=()=>c();return t.addEventListener("pointerenter",d),t.addEventListener("pointerleave",u),document.addEventListener(Tp,v),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(Tp,v),c()}}function YI(e){return e.getInstances().length>=1}function XI(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",re(_("%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=ZI(a,e,r++,t,n);s.appendChild(l)}if(e.enableGhost!==!1){const a=QI(e,r,t);s.appendChild(a)}return o}function Dp(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function ZI(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*Np}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${Ga(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 S=0;S<3;S++)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",Sb(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 S=0;S<3;S++){const O=document.createElement("span");O.className="os-dock-peek__card-line",f.appendChild(O)}const p={window:e,item:t.item},v=q(g.DOCK_PEEK_CARD_CONTENT,f,p);v!==f&&v.classList.add("os-dock-peek__card-body--custom"),i.appendChild(v),e.state==="minimized"&&(i.dataset.state="minimized");const h=()=>{s.delete(e.id),delete i.dataset.preview},w=S=>{if(h(),S.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(S.previouslyFocusedId){const O=t.windowManager.getById(S.previouslyFocusedId);O&&t.windowManager.focus(O)}};return i.addEventListener("click",()=>{h(),JI(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const S=e.state==="minimized",O=t.windowManager.getFocused(),M=O&&O!==e?O.id:null;(S||M!==null)&&(s.set(e.id,{wasMinimized:S,previouslyFocusedId:M}),i.dataset.preview=""),S?Dp(e,i):O&&O!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const S=s.get(e.id);S&&w(S)}),q(g.DOCK_PEEK_CARD_ELEMENT,i,p)}function JI(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),Dp(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 QI(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*Np}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=re(_("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{eA(e,n)}),o}function eA(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const tA=12,nA=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function oA(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of nA){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function sA(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(()=>iA(e))}function iA(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=tA;let r=0,a=0;n.top<i?r=i-n.top:n.bottom>o-i&&(r=o-i-n.bottom),n.left<i?a=i-n.left:n.right>s-i&&(a=s-i-n.right),!(a===0&&r===0)&&(e.style.setProperty("--peek-clamp-x",`${a}px`),e.style.setProperty("--peek-clamp-y",`${r}px`),e.classList.add("os-dock-peek--clamped"))}function Co(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 Rp(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 xp=new Map;function rA(e){const t=xp.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 xp.set(e,n),n}function aA(){const e=new Set,t=document.querySelectorAll('script[src*="load-scripts.php"]');for(const n of Array.from(t))for(const o of rA(n.src))e.add(o);return e}function za(e){return e.url&&Rp(e.url)?!0:!!e.handle&&aA().has(e.handle)}const _i=new Map;function fe(e,t){const n=_i.get(e);if(n)return n;const o=t?.deps;if(o&&o.length>0){const i=a=>!a.url||za(a)?Promise.resolve():fe(a.url,{...a,deps:void 0}),r=o.reduce((a,l)=>a.then(()=>i(l)),Promise.resolve(void 0)).then(()=>Mp(e,t));return _i.set(e,r),r}const s=Mp(e,t);return _i.set(e,s),s}function Mp(e,t){return new Promise((n,o)=>{const s=`script[data-os-vendor="${cA(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=Rp(e);if(r){r.dataset.osVendor=e,r.dataset.loaded="1",n();return}if(za({handle:t?.handle})){n();return}t?.translations&&Lo(t.translations);for(const l of t?.l10n??[])Lo(l);for(const l of t?.before??[])Lo(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??[])Lo(l);n()},{once:!0}),a.addEventListener("error",()=>{_i.delete(e),a.remove(),o(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(a)})}function Lo(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function Wp(e){Lo(e)}function cA(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let Pp=0;function $p(){return window.openStationItemVisibilityMenu??null}function lA(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function Up(e){const t=$p();if(t){t.openItemVisibilityMenu(e);return}const n=lA();if(!n)return;const o=++Pp;fe(n).then(()=>{o===Pp&&$p()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const dA={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function uA(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function Bp(e){return e==="core"?"core":e==="control"?"controls":"apps"}function Fp(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??dA[e.kind]}function Hp(e){return e==="rail"||e==="both"}function fA(e){return e==="desktop"||e==="both"}function pA(e,t,n){return Hp(e)?"rail":"hidden"}function Gp(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 hA(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 zp(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 Si(){return window.wp?.os??null}function mA(){const e=Si()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function wA(){return Si()?.getNavItems?.()??[]}function gA(e){const t=wA();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function yA(e){const t=Si();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 vA(e,t,n){const o=Array.isArray(e)?e:[e],s=mA().placement,i=[];for(const r of o){const a=typeof r=="string"?gA(r):r;a&&i.push({item:a,placement:pA(Fp(a,s))})}yA(i)}function bA(e){const t=Si();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:hA(n,e)})}const at=["core","apps","controls"];function Vp(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 v=Fp(p,n.placement);if(Hp(v)){c.add(p.id);const h=Bp(p.kind);uA(p.kind,o)==="sidebar"?r.push(p):i[h].push(p)}fA(v)&&a.push(p)}for(const p of t)for(const v of p.answersFor??[])d.has(v)||d.set(v,p);for(const p of s){const v=d.get(p.id);if(v){if(c.has(v.id)||l.has(v.id))continue;i.apps.push(v),l.add(v.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=>Gp(EA(zp(p)),n.order);for(const p of at)i[p]=f(i[p]);return{dock:i,sidebar:f(r),desktop:Gp(zp(a),n.order),ephemeral:l}}function EA(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 _A=["action","action2","_wpnonce","nonce","delete_all"];function SA(e){const t=e.slice(e.lastIndexOf("/")+1);return/-new\.php$/.test(t)}function kA(e){if(SA(e.pathname))return!0;for(const t of _A)if(e.searchParams.has(t))return!0;return!1}function jp(e){return Bp(e.navKind??"app")}const Pe=class Pe{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/${++Pe.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 at)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[jp(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 at){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(g.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");Kp(i??o,s),Ee.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),Ee.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),Ee.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,qs(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=jp(t),o={type:"system",item:t};for(const a of at)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(Pe.activeDragReset){const o=Pe.activeDragReset;Pe.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 at)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(g.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of at){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(g.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(),Up({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");Kp(d??r,l)}const c=this.artOverrides.get(i);c&&this._paintArt(r,i,c),A(g.DOCK_TILE_RENDERED,{...s,item:t.item,isSystem:t.type==="system",el:r})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=q(g.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=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,qs(t.id))),r.addEventListener("click",l=>t.onOpen(l)),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=Op({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:""},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(t.id),enableGhost:!!t.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(t.onOpenNew??t.onOpen)()},suppressTooltip:l=>{l&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),this.bindPrewarmDwell(o,()=>this.prewarmNativeWindow(t.id)),q(g.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];t.multi&&s.push("os-dock__item--multi");const i=q(g.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,qs(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",re($t("%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),c=Op({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(l),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(t),suppressTooltip:d=>{d&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(t.id,c),this.bindHoverPrewarm(o,t),q(g.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 v=()=>{r=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",M),document.removeEventListener("pointerup",j),document.removeEventListener("pointercancel",B),document.removeEventListener("keydown",V,!0),window.removeEventListener("blur",J),document.removeEventListener("visibilitychange",K),u=-1,f=null},h=o==="controls"?this.systemHost:this.itemHost,w=T=>!!T&&T instanceof HTMLElement&&T.classList.contains("os-dock__item")&&T.dataset.zone===o&&!!T.dataset.navId&&T.dataset.navLocked===void 0,E=T=>{for(const R of Array.from(h.children))R instanceof HTMLElement&&R!==t&&w(R)&&T(R)},S=()=>{const T=[];for(const R of Array.from(h.children))w(R)&&T.push(R.dataset.navId);return T},O=T=>{E(R=>{const Y=T.get(R);if(!Y)return;const X=R.getBoundingClientRect(),oe=Y.left-X.left,N=Y.top-X.top;if(Math.abs(oe)<.5&&Math.abs(N)<.5)return;R.style.transition="none",R.style.transform=`translate(${oe}px, ${N}px)`,R.offsetHeight,R.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",R.style.transform="";const m=()=>{R.style.transition="",R.style.transform="",R.removeEventListener("transitionend",m)};R.addEventListener("transitionend",m)})},M=T=>{if(u!==-1&&T.pointerId!==u)return;if(!r){const D=T.clientX-a,$=T.clientY-l;if(D*D+$*$<5*5)return;r=!0,c=S(),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 R=T.clientX-a,Y=T.clientY-l;t.style.transform=`translate(${R}px, ${Y}px)`;const oe=document.elementFromPoint(T.clientX,T.clientY)?.closest(".os-dock__item");if(!oe||oe===t||!w(oe))return;const N=oe.getBoundingClientRect();let m;this.orientation==="bottom"?m=T.clientX<N.left+N.width/2:m=T.clientY<N.top+N.height/2;const k=new Map;E(D=>{k.set(D,D.getBoundingClientRect())});let I=!1;if(m?oe!==t.nextSibling&&(h.insertBefore(t,oe),I=!0):oe.nextSibling!==t&&(h.insertBefore(t,oe.nextSibling),I=!0),I){t.style.transform="";const D=t.getBoundingClientRect();a=D.left+D.width/2,l=D.top+D.height/2,t.style.transform=`translate(${T.clientX-a}px, ${T.clientY-l}px)`,O(k)}},b=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",M),document.removeEventListener("pointerup",j),document.removeEventListener("pointercancel",B),document.removeEventListener("keydown",V,!0),window.removeEventListener("blur",J),document.removeEventListener("visibilitychange",K),u=-1,f=null,r=!1,Pe.activeDragReset===v&&(Pe.activeDragReset=null)},W=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const T=()=>{t.style.transition="",t.removeEventListener("transitionend",T)};t.addEventListener("transitionend",T)},U=T=>{bA(T)},j=T=>{if(u!==-1&&T.pointerId!==u)return;if(!r){b();return}p=!0;const R=S();W(),b(),R.length===c.length&&R.every((X,oe)=>X===c[oe])||U(R),setTimeout(()=>{p=!1},200)},B=T=>{if(!(T&&u!==-1&&T.pointerId!==u)){if(r&&d!==void 0){const R=new Map;E(Y=>{R.set(Y,Y.getBoundingClientRect())}),h.insertBefore(t,d),O(R)}W(),b()}},V=T=>{T.key==="Escape"&&B()},J=()=>B(),K=()=>{document.visibilityState!=="visible"&&B()};t.addEventListener("pointerdown",T=>{if(!(T.button!==0||Pt())){if(Pe.activeDragReset){const R=Pe.activeDragReset;Pe.activeDragReset=null,R()}(r||u!==-1)&&v(),a=T.clientX,l=T.clientY,u=T.pointerId,r=!1,Pe.activeDragReset=v,document.addEventListener("pointermove",M),document.addEventListener("pointerup",j),document.addEventListener("pointercancel",B),document.addEventListener("keydown",V,!0),window.addEventListener("blur",J),document.addEventListener("visibilitychange",K)}}),t.addEventListener("click",T=>{p&&(T.preventDefault(),T.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=Ks(s);a!==null&&(t=a,i=!0),r=na(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if(Ei(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(Ei(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=Ga(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(t,n,o){const s=q(g.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=fi(n.url);if(o){this.prewarmNativeWindow(o);return}try{const i=new URL(n.url,window.location.href);if(i.origin!==window.location.origin||kA(i)||lo(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){this.windowManager.focus(o);return}window.wp?.os?.openWindow?.(t.windowId);return}if(Co(t.url)||Ze(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(Co(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=fi(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 de(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:fi(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?.(g.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(g.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(g.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?.(g.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(g.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(g.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 v=p.config.baseId||p.id;if(v===a||v===f||v===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)}};Pe.instanceCounter=0,Pe.activeDragReset=null;let ki=Pe;function Kp(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",re($t("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="os-dock__badge",s.textContent=o,s.setAttribute("aria-label",re($t("%d notification","%d notifications",t),t)),e.appendChild(s)}const qp=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),Va={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 ki(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[qp]: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 Yp(e){if(!e)return null;const n=e[qp];return n instanceof ki?n:null}function IA(){$d(Va)}const Xp="os-desktop-theme-css",AA="os-desktop-theme-inline-css",ja="data-os-desktop-theme-css",Zp="os-desktop-theme-changed";function Jp(){return document.getElementById("os-shell")}function Qp(){const e=[];for(const t of[Xp,AA]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${ja}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function Ka(){for(const e of Qp())e.remove()}function CA(e){const t=Jp();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:Qp().length>0}function eh(e){if(e.cssUrl!==""){const t=document.createElement("link");t.id=Xp,t.rel="stylesheet",t.href=e.cssUrl,t.setAttribute(ja,e.slug),document.head.appendChild(t)}else if(e.cssText!==""){const t=document.createElement("style");t.setAttribute(ja,e.slug),t.textContent=e.cssText,document.head.appendChild(t)}}function th(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 qa(e){const t=En(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:ea(o),i=s?s.slug:null;if(i===n)return;const r=Jp();if(!s)r?.removeAttribute("data-os-desktop-theme"),th(null),Ka(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!CA(s.slug))if(s.cssDeferred&&s.cssUrl===""&&s.cssText===""){const l=s.slug,c=()=>bu().then(()=>{if(En().state.activeId!==l)return;const d=ea(l);if(!d||d.cssDeferred)throw new Error(`theme "${l}" resolved without a stylesheet`);Ka(),eh(d)}).catch(d=>{En().state.activeId===l&&(ue({message:_("Could not load that desktop theme — the previous one is still showing."),action:{label:_("Retry"),onClick:()=>void c()},persistent:!0,dismissible:!0}),console.warn("[openstation] desktop theme stylesheet failed to load",d))});c()}else Ka(),eh(s);r?.setAttribute("data-os-desktop-theme",s.slug),th(s.slug),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};A(g.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(Zp,{detail:a}))}let jt=null,nh=!1,oh=!1,sh=!1,Ya=null,To=!1,Xa=[],Kt="pending";const LA=5e3,TA=3e3;function NA(e,t,n){if(oh)return;oh=!0;const o=typeof t.shellBuild=="string"?t.shellBuild:"",s=(r,a)=>{DA(r).then(l=>{if(!(o!==""&&l!==""&&l!==o)){a&&ih(r);return}a&&(Ya=r),!(sh||!n)&&(sh=!0,n({current:o,served:l}))})},i=r=>{!r||typeof r.addEventListener!="function"||r.addEventListener("statechange",()=>{r.state==="installed"&&navigator.serviceWorker.controller&&s(r,!0)})};e.waiting&&navigator.serviceWorker.controller&&s(e.waiting,!0),i(e.installing??null),typeof e.addEventListener=="function"&&e.addEventListener("updatefound",()=>{i(e.installing??null)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{if(Ya=null,To){To=!1;const a=Xa;Xa=[];for(const l of a)l();return}const r=navigator.serviceWorker.controller;r&&s(r,!1)})}function ih(e){To=!0;try{e.postMessage({type:"os-sw-skip-waiting"})}catch{To=!1}}function OA(){const e=Ya;return e?new Promise(t=>{let n=!1;const o=()=>{n||(n=!0,window.clearTimeout(s),t())},s=window.setTimeout(o,TA);Xa.push(o),ih(e),To||o()}):Promise.resolve()}function DA(e){return new Promise(t=>{let n=!1,o=0;const s=r=>{const a=r.data;a&&a.type==="os-sw-build"&&i(typeof a.shellBuild=="string"?a.shellBuild:"")},i=r=>{n||(n=!0,window.clearTimeout(o),navigator.serviceWorker.removeEventListener("message",s),t(r))};o=window.setTimeout(()=>i(""),LA),navigator.serviceWorker.addEventListener("message",s);try{e.postMessage({type:"os-sw-get-build"})}catch{i("")}})}const RA=5*6e4;let rh=null,Za=0;function xA(e){if(rh)return;Za=Date.now();const t=()=>{if(typeof document<"u"&&document.visibilityState==="hidden")return;const n=Date.now();if(!(n-Za<RA)){Za=n;try{e.update().catch(()=>{})}catch{}}};document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),rh=()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t)}}const MA=["/desktop-mode/sw.js"];function WA(e,t){if(e===t.swUrl||e===t.swFallbackUrl)return!0;try{const n=new URL(e);return n.pathname.endsWith("/openstation/sw.js")||n.searchParams.has("openstation_sw")?!0:MA.some(o=>n.pathname.endsWith(o))}catch{return!1}}function ah(){const e=window.openStationConfig?.pwa?.swConfig;UA({adminAssetCache:e?.adminAssetCache===!0,windowPrewarm:e?.windowPrewarm===!0})}async function PA(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return Kt="unsupported",null;if(jt||nh)return jt;if(!t.forceReplace){const s=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(i=>{const r=i.active?.scriptURL??i.installing?.scriptURL??"";return r!==""&&!WA(r,e)});if(s)return Kt="foreign-sw",typeof console<"u"&&console.warn("[openstation] another service worker is already registered ("+s.scope+"); skipping openstation SW. Set openstation_pwa_force_replace_sw=true to override."),null}const n=async o=>navigator.serviceWorker.register(o,{scope:e.swScope||"/",updateViaCache:"none"});try{try{jt=await n(e.swUrl)}catch(o){if(!e.swFallbackUrl||e.swFallbackUrl===e.swUrl)throw o;jt=await n(e.swFallbackUrl)}return Kt="registered",NA(jt,e,t.onShellUpdated),xA(jt),ah(),navigator.serviceWorker.addEventListener("controllerchange",ah),jt}catch(o){return nh=!0,Kt="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",o),null}}function $A(e){try{navigator.serviceWorker?.controller?.postMessage({type:"os-sw-set-prewarm",enabled:e})}catch{}}function UA(e){try{navigator.serviceWorker?.controller?.postMessage({type:"os-sw-config",...e})}catch{}}function BA(){return Kt}function FA(e={}){const t=e.deactivate??(()=>qa(""));return function(o){HE(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=En().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const HA="",GA="system-default",zA={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function ch(e,t,n={}){const o=t===HA,s=o?null:ea(t);if(!o&&!s)return{};const i=o?GA:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=WE(o?zA: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 lh(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}function VA(e,t){Ln({id:DE,label:_("Custom gradient"),type:"css",preview:lh(e()),description:_("Mix your own two-colour gradient and set the angle — your desk, your palette."),resolveValue:()=>lh(e())})}function jA(e){if(!e.customImage){Io(Gs)&&hp(Gs);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`,o=Io(Gs);o&&o.type==="css"&&o.value===n||Ln({id:Gs,label:_("Custom image"),type:"css",value:n,preview:n,description:_("Any image from your media library or an upload, sized to cover the whole desk.")})}function dh(e){return JSON.parse(JSON.stringify(e))}function KA(e,t){return e===t?!0:typeof e!="object"||typeof t!="object"||e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}class qA{constructor(t){this.listeners=new Set,this.baseState=null,this.overridePatch=null,this.layer=t,this.state=NI(),document.addEventListener("os-settings-save-lifecycle",n=>{const o=n.detail;!o||(window.wp?.os?.windowManager?.getById(vn)?.markActivity(o.phase,{error:o.error}),o.phase!=="failed"||!o.rolledBackTo)||(this.state=o.rolledBackTo,this.apply(),this.notify())}),VA(()=>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;yI(this.state.wallpaperSettings),jA(this.state);const n=Io(this.state.wallpaper)||Io(Xr())||Io(Yr)||xa()[0];n&&this.layer.apply(n);const o=zs(),s=o.find(p=>p.id===this.state.accent)??o[0],i=this.state.accent===pu?this.state.customAccent:s.value,r=Zr.find(p=>p.id===this.state.dockSize)??Zr[1],a=Jr.find(p=>p.id===this.state.windowRadius)??Jr[1],l=document.body;l.style.setProperty("--wp-admin-theme-color",i),l.style.setProperty("--os-ui-accent",i);const d=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;d===null?l.style.removeProperty("--os-ui-accent-dim"):l.style.setProperty("--os-ui-accent-dim",d),t.style.setProperty("--os-ui-accent",i),d===null?t.style.removeProperty("--os-ui-accent-dim"):t.style.setProperty("--os-ui-accent-dim",d),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 u=Vs.find(p=>p.id===this.state.adminBarMode)??Vs[0];for(const p of Vs)document.body.classList.toggle(`os-admin-bar-${p.id}`,p.id===u.id);const f=p=>(js.find(v=>v.id===p)??js[0]).id;document.getElementById(bI)?.setAttribute(Ao,f(this.state.dockBehavior)),document.getElementById(yp)?.setAttribute(Ao,f(this.state.sideDockBehavior)),CI(),wS(),t.setAttribute("data-os-layout",this.state.desktopLayout),tE(this.state.dockRailRenderer),qa(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=dh(t),this.state={...n,...dh(t)};this.apply(),this.notify()}save(t={}){$I(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))KA(o[r],s[r])&&(o[r]=i[r]);return o}update(t,n={}){const o={...t};delete o.appliedThemeRecommendations;const s=$a(o,this.state),i=Ip.filter(a=>a in o);let r=!1;i.includes("desktopTheme")&&s.desktopTheme!==this.state.desktopTheme&&(r=Object.keys(ch(s,s.desktopTheme)).length>0),Object.assign(this.state,s),typeof o.windowPrewarmEnabled=="boolean"&&$A(o.windowPrewarmEnabled),this.save(n),(r||i.some(a=>DI.has(a)))&&this.apply()}applyThemeRecommendations(t){const n=ch(this.state,t,{force:!0});return Object.keys(n).length>0&&(this.save(),this.apply()),n}reset(t={}){const n=Lp();n.wallpaper=Xr(),n.customImage=this.state.customImage,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 YA="os-network-admin";function XA(e,t){const n=e.networkAdmin;return!n||e.isNetworkAdmin?null:{id:YA,title:_("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 uh(e){return!!e&&(e.metaKey||e.ctrlKey||e.shiftKey||e.button===1)}function fh(e,t){if(uh(t)){window.open(e,"_blank","noopener,noreferrer");return}window.location.assign(e)}const ZA=220,JA=360,QA=4e3,Ja="openstation-hop-direction",Qa="os-shell--arriving",ph="os-shell--revealing";function ec(){return document.getElementById("os-shell")}function hh(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function e0(e){try{window.sessionStorage.setItem(Ja,e)}catch{}const t=ec();return!t||hh()?Promise.resolve():(t.classList.add(`os-shell--hop-out-${e}`),new Promise(n=>{window.setTimeout(n,ZA)}))}function t0(){try{const e=window.sessionStorage.getItem(Ja);return window.sessionStorage.removeItem(Ja),e==="next"||e==="prev"?e:null}catch{return null}}function n0(){const e=ec();if(!e||!e.classList.contains(Qa))return;const t=t0();t&&e.classList.add(`os-shell--arriving-${t}`),window.setTimeout(mh,QA)}function mh(){const e=ec();!e||!e.classList.contains(Qa)||(e.classList.remove(Qa,"os-shell--arriving-next","os-shell--arriving-prev"),!hh()&&(e.classList.add(ph),window.setTimeout(()=>e.classList.remove(ph),JA)))}function Dn(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function o0(e){return!!e&&e.__wpdHtml===!0}const s0="$$wpd$$",Ne=/\$\$wpd\$\$(\d+)\$\$/g,i0="$$wpd-node$$",r0=/^\$\$wpd-node\$\$(\d+)\$\$$/,a0=new Set(["style","script","textarea","title"]);function c0(e){let t="",n=!1,o=null,s=!1,i=null,r="",a=!1;for(let l=0;l<e.length;l++){const c=e[l];t+=c;for(let d=0;d<c.length;d++){const u=c[d];if(s){c.startsWith("-->",d)&&(s=!1,d+=2);continue}if(i!==null){u==="<"&&c[d+1]==="/"&&c.slice(d+2,d+2+i.length).toLowerCase()===i&&(d+=1+i.length,i=null,n=!0,a=!1,r="");continue}if(o!==null){u===o&&(o=null);continue}if(n){u==='"'||u==="'"?(o=u,a=!1):u===">"?(n=!1,a=!1,a0.has(r)&&(i=r),r=""):a&&(/[a-zA-Z0-9-]/.test(u)?r+=u.toLowerCase():a=!1);continue}if(c.startsWith("<!--",d)){s=!0,d+=3;continue}const f=c[d+1]??"";u==="<"&&/[a-zA-Z/!]/.test(f)&&(n=!0,r="",a=/[a-zA-Z]/.test(f))}l<e.length-1&&(t+=n||s||i!==null?`${s0}${l}$$`:`<!--${i0}${l}$$-->`)}return t}const wh=new WeakMap;function gh(e){const t=wh.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=c0(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,v=f.value,h=p[0];if(Ne.test(v))if(Ne.lastIndex=0,h==="@"){const w=Ne.exec(v);Ne.lastIndex=0,o.push({path:l,kind:"event",name:p.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(p)}else if(h==="."){const w=Ne.exec(v);Ne.lastIndex=0,o.push({path:l,kind:"prop",name:p.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(p)}else if(h==="?"){const w=Ne.exec(v);Ne.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(p)}else{const w=[],E=[];let S=0,O;for(Ne.lastIndex=0;(O=Ne.exec(v))!==null;)w.push(v.slice(S,O.index)),E.push(Number(O[1])),S=O.index+O[0].length;w.push(v.slice(S)),o.push({path:l,kind:"attr",name:p,template:w,valueIndices:E}),u.setAttribute(p,"")}}}const c=Array.from(a.childNodes);let d=0;for(let u=0;u<c.length;u++){const f=c[u],p=u+d;if(f.nodeType===Node.COMMENT_NODE){const v=r0.exec(f.data);if(v){const h=document.createTextNode("");f.parentNode.replaceChild(h,f),o.push({path:[...l,p],kind:"node",valueIndex:Number(v[1])})}continue}if(f.nodeType===Node.TEXT_NODE){const v=f.textContent||"";if(!Ne.test(v)){Ne.lastIndex=0;continue}Ne.lastIndex=0;const h=f.parentNode;let w=0,E;const S=[],O=[];for(Ne.lastIndex=0;(E=Ne.exec(v))!==null;){E.index>w&&S.push(document.createTextNode(v.slice(w,E.index)));const M=document.createTextNode("");S.push(M),O.push({path:[...l,p+S.length-1],kind:"node",valueIndex:Number(E[1])}),w=E.index+E[0].length}w<v.length&&S.push(document.createTextNode(v.slice(w)));for(const M of S)h.insertBefore(M,f);h.removeChild(f),d+=S.length-1,o.push(...O)}else s(f,[...l,p])}};s(n.content,[]);const r={template:n,buildParts:a=>{const l=[];for(const c of o){let d=a;for(const u of c.path)d=d.childNodes[u];c.kind==="node"?l.push({kind:"node",valueIndex:c.valueIndex,child:{anchor:d,state:null}}):c.kind==="attr"?l.push({kind:"attr",element:d,name:c.name,template:c.template,valueIndices:c.valueIndices}):c.kind==="event"?l.push({kind:"event",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="prop"?l.push({kind:"prop",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="bool"&&l.push({kind:"bool",valueIndex:c.valueIndex,element:d,name:c.name})}return l}};return wh.set(e,r),r}const yh=new WeakMap;function l0(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function d0(e,t){const n=yh.get(t);if(n&&n.strings===e.strings&&l0(n,t)){Ii(n.parts,e.values);return}const o=gh(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),Ii(i,e.values),yh.set(t,{strings:e.strings,parts:i,nodes:r})}function Ii(e,t){for(const n of e)if(n.kind==="node")Ai(n.child,t[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;s<n.valueIndices.length;s++)o+=vh(t[n.valueIndices[s]]),o+=n.template[s+1];o!==n.last&&(n.last=o,o===""?n.element.removeAttribute(n.name):n.element.setAttribute(n.name,o))}else if(n.kind==="event"){const o=t[n.valueIndex];o!==n.current&&(n.current&&n.element.removeEventListener(n.name,n.current),o&&n.element.addEventListener(n.name,o),n.current=o)}else if(n.kind==="prop"){const o=t[n.valueIndex];o!==n.last&&(n.last=o,n.element[n.name]=o)}else if(n.kind==="bool"){const o=!!t[n.valueIndex];o!==n.last&&(n.last=o,o?n.element.setAttribute(n.name,""):n.element.removeAttribute(n.name))}}function Ai(e,t){if(t==null||t===!1){e.state&&(Tt(e.state),e.state=null);return}if(Array.isArray(t)){h0(e,t);return}if(o0(t)){p0(e,t);return}if(t instanceof Node){u0(e,t);return}f0(e,vh(t))}function u0(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Tt(n),No(e,[t]),e.state={shape:"node",node:t})}function f0(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Tt(n);const o=document.createTextNode(t);No(e,[o]),e.state={shape:"text",node:o,text:t}}function p0(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){Ii(n.parts,t.values);return}n&&Tt(n);const o=gh(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);No(e,[s]),Ii(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function h0(e,t){const n=e.state;if(n?.shape==="array"){const s=Math.min(n.entries.length,t.length);for(let i=0;i<s;i++)Ai(n.entries[i],t[i]);if(t.length<n.entries.length){for(let i=t.length;i<n.entries.length;i++){const r=n.entries[i];r.state&&Tt(r.state),r.anchor.remove()}n.entries.length=t.length}else for(let i=n.entries.length;i<t.length;i++){const r=document.createTextNode("");No(e,[r]);const a={anchor:r,state:null};Ai(a,t[i]),n.entries.push(a)}return}n&&Tt(n);const o=[];for(const s of t){const i=document.createTextNode("");No(e,[i]);const r={anchor:i,state:null};Ai(r,s),o.push(r)}e.state={shape:"array",entries:o}}function No(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Tt(e){if(e.shape==="text"){e.node.remove();return}if(e.shape==="template"){for(const t of e.parts)t.kind==="node"&&t.child.state&&(Tt(t.child.state),t.child.state=null);for(const t of e.nodes)t.parentNode&&t.parentNode.removeChild(t);return}if(e.shape==="node"){e.node.parentNode&&e.node.parentNode.removeChild(e.node);return}for(const t of e.entries)t.state&&Tt(t.state),t.anchor.remove()}function vh(e){return e==null||e===!1?"":String(e)}const Wt=class Wt extends HTMLElement{constructor(){super(),this._renderScheduled=!1,this._propValues={},this.constructor.shadow?(this.attachShadow({mode:"open"}),this._renderRoot=this.shadowRoot):this._renderRoot=this,this._installPropAccessors()}static get observedAttributes(){return this.props.map(bh)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=m0(t);this._propValues[s]=o,this.requestUpdate()}get classNames(){return Array.from(this.classList)}set classNames(t){if(t==null){this.removeAttribute("class");return}const o=(Array.isArray(t)?t:String(t).split(/\s+/)).map(s=>String(s).trim()).filter(s=>s!=="");this.className=o.join(" ")}requestUpdate(){this._scheduleRender()}emit(t,n){return this.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!0,composed:!0}))}_installPropAccessors(){const t=this.constructor;for(const n of t.props){if(Object.getOwnPropertyDescriptor(this,n))continue;const o=bh(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&&d0(this.render(),this._renderRoot)}))}_adoptStyles(){const t=this.constructor;if(t.styles.length!==0)if(t.shadow&&this.shadowRoot){const n=t.styles.map(o=>o.sheet).filter(o=>o!==null);if(this.shadowRoot.adoptedStyleSheets=n,n.length!==t.styles.length){for(const o of t.styles)if(!o.sheet){const s=document.createElement("style");s.textContent=o.cssText,this.shadowRoot.appendChild(s)}}}else this._adoptLightStyles(t)}_adoptLightStyles(t){if(!Wt._lightStylesAdopted.has(t)){Wt._lightStylesAdopted.add(t);for(const n of t.styles){const o=document.createElement("style");o.dataset.osUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};Wt.props=[],Wt.styles=[],Wt.shadow=!0,Wt._lightStylesAdopted=new WeakSet;let qt=Wt;function Oo(e,t){customElements.get(e)||customElements.define(e,t)}function bh(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function m0(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const w0=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function Ae(e,...t){let n=e[0];for(let o=1;o<e.length;o++){const s=t[o-1];if(typeof s=="string"||typeof s=="number")n+=String(s);else if(s&&s.__wpdCss)n+=s.cssText;else throw new TypeError("[os-ui] css`` interpolations must be strings, numbers, or other css`` results. Got: "+typeof s);n+=e[o]}if(w0){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}const tc=Ae`:host{--_holo-fill:var( --os-ui-holo-fill,${"linear-gradient( 124deg, #afa2e8 0%, #f5a8ea 46%, #8ee9f7 100% )"} );--_holo-ink:var( --os-ui-holo-ink,#0c0b0f );--_holo-sheen:var( --os-ui-holo-sheen,linear-gradient( 124deg,rgba( 159,214,255,0.1 ) 0%,rgba( 236,155,255,0.12 ) 34%,rgba( 242,82,252,0.1 ) 58%,rgba( 147,240,198,0.09 ) 100% ) );--_holo-edge:var( --os-ui-holo-edge,linear-gradient( 124deg,rgba( 154,242,255,0.7 ) 0%,rgba( 236,155,255,0.85 ) 38%,rgba( 242,82,252,0.7 ) 62%,rgba( 159,152,255,0.6 ) 100% ) );--_holo-edge-quiet:var( --os-ui-holo-edge-quiet,linear-gradient( 124deg,rgba( 154,242,255,0.22 ) 0%,rgba( 236,155,255,0.28 ) 38%,rgba( 242,82,252,0.22 ) 62%,rgba( 159,152,255,0.2 ) 100% ) );--_holo-glow:var( --os-ui-holo-glow,0 0 0 1px rgba( 242,82,252,0.28 ),0 2px 10px rgba( 242,82,252,0.22 ) );--_holo-glow-strong:var( --os-ui-holo-glow-strong,0 0 0 1px rgba( 242,82,252,0.42 ),0 4px 18px rgba( 242,82,252,0.38 ),0 1px 3px rgba( 12,11,15,0.6 ) );--_holo-track:var( --os-ui-holo-track,rgba( 255,251,255,0.16 ) );--_holo-track-edge:var( --os-ui-holo-track-edge,#8c8f94 );--_holo-ring-color:var( --os-ui-accent-dim,#2271b1 );--_holo-focus:var( --os-ui-focus-ring,0 0 0 2px rgba( 12,11,15,0.9 ),0 0 0 4px #f252fc,0 0 12px 2px rgba( 242,82,252,0.45 ) );--_holo-focus-field:var( --os-ui-focus-ring-field,0 0 0 1px #f252fc,0 0 0 4px rgba( 242,82,252,0.18 ) );--_holo-t:var( --os-ui-holo-transition,220ms );--_holo-t-fast:var( --os-ui-motion-fast,140ms );--_holo-t-slow:var( --os-ui-motion-slow,340ms );--_holo-t-ambient:var( --os-ui-motion-ambient,12s );--_holo-spring:var( --os-ui-ease-spring,cubic-bezier( 0.32,1.5,0.55,1 ) );--_holo-ease:var( --os-ui-ease-out,cubic-bezier( 0.22,0.9,0.28,1 ) );--_holo-loop:var( --os-ui-ease-loop,cubic-bezier( 0.45,0,0.55,1 ) )}`,g0=Ae` .os-holo-fill{background-color:transparent;background-image:var( --_holo-fill );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;color:var( --_holo-ink );transition:background-position var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,filter var( --_holo-t ) ease}.os-holo-fill:hover{background-position:74% 66%}.os-holo-fill:active{background-position:88% 82%;filter:brightness( 0.94 )}@media ( prefers-reduced-motion:reduce ){.os-holo-fill{transition-duration:1ms}.os-holo-fill:hover,.os-holo-fill:active{background-position:22% 28%}}`,Eh=Ae` .os-holo-sheen{position:relative;isolation:isolate}.os-holo-sheen::before{content:'';position:absolute;inset:0;z-index:-1;border-radius:inherit;background-image:var( --_holo-sheen );background-size:200% 200%;background-position:20% 30%;opacity:0;pointer-events:none;transition:opacity var( --_holo-t ) ease,background-position var( --_holo-t ) ease}.os-holo-sheen:hover::before,.os-holo-sheen:focus-visible::before{opacity:1;background-position:76% 68%}@media ( prefers-reduced-motion:reduce ){.os-holo-sheen::before{transition-duration:1ms}.os-holo-sheen:hover::before,.os-holo-sheen:focus-visible::before{background-position:20% 30%}}`,y0=Ae` .os-holo-edge{position:relative}.os-holo-edge::after{content:'';position:absolute;inset:0;border-radius:inherit;padding:1px;background-image:var( --_holo-edge-quiet );opacity:0;pointer-events:none;-webkit-mask:linear-gradient( #000 0 0 ) content-box,linear-gradient( #000 0 0 );-webkit-mask-composite:xor;mask:linear-gradient( #000 0 0 ) content-box,linear-gradient( #000 0 0 );mask-composite:exclude;transition:opacity var( --_holo-t ) ease}.os-holo-edge:hover::after,.os-holo-edge:focus-visible::after{background-image:var( --_holo-edge );opacity:1}.os-holo-edge.is-lit::after{background-image:var( --_holo-edge );opacity:1}@media ( prefers-reduced-motion:reduce ){.os-holo-edge::after{transition-duration:1ms}}`,v0=Ae` .os-holo-glint{position:absolute;inset:0;border-radius:inherit;overflow:hidden;pointer-events:none}.os-holo-glint::before{content:'';position:absolute;top:-60%;bottom:-60%;width:45%;inset-inline-start:-60%;background:linear-gradient( 90deg,transparent 0%,rgba( 255,251,255,0.14 ) 45%,rgba( 255,251,255,0.22 ) 50%,rgba( 255,251,255,0.14 ) 55%,transparent 100% );transform:rotate( 18deg ) translateX( 0 );opacity:0}:hover>.os-holo-glint::before,:focus-visible>.os-holo-glint::before,:host(:hover )>.os-holo-glint::before,:host(:focus-visible )>.os-holo-glint::before{animation:os-holo-glint var( --_holo-t-slow ) var( --_holo-ease )}@keyframes os-holo-glint{0%{opacity:0;transform:rotate( 18deg ) translateX( 0 )}15%{opacity:1}85%{opacity:1}100%{opacity:0;transform:rotate( 18deg ) translateX( 240vw )}}@media ( prefers-reduced-motion:reduce ){:hover>.os-holo-glint::before,:focus-visible>.os-holo-glint::before,:host(:hover )>.os-holo-glint::before,:host(:focus-visible )>.os-holo-glint::before{animation:none}}`,b0=Ae` .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}}`,E0=Ae` .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%}}`,_0=Ae` .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}}`,S0=Ae` 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}}`,k0=Ae` 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-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-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-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}}`,I0=Ae` @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}}`;Ae` ${tc} ${g0} ${Eh} ${y0} ${v0} ${b0} ${E0} ${_0} ${S0} ${k0} ${I0} `;const A0=Ae` ${tc}: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}.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,var( --os-ui-accent,#2271b1 ) );background-image:var( --os-ui-segmented-selected-image,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}}`,C0=Ae` ${tc} ${Eh}:host{flex:1 1 auto;min-width:0}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 )}button:focus-visible{outline:none;box-shadow:var( --_holo-focus )}:host( [ aria-checked='true' ] ) button{color:var( --os-ui-segmented-selected-fg,var( --os-ui-fg-on-accent,#fff ) );transition-duration:var( --_holo-t-fast )}:host( [ aria-checked='true' ] ) button::before{display:none}`,Ls=class Ls extends qt{render(){return this.setAttribute("role","radio"),Dn`
3 <button
4 type="button"
5 class="os-holo-sheen"
6 @click=${()=>this._onPick()}
7 >
8 <slot></slot>
9 </button>
10 `}_onPick(){this.emit("os-segment-pick",{value:this.value})}};Ls.props=["value"],Ls.styles=[C0],Ls.help=void 0;let nc=Ls;Oo("os-segment",nc);const Ts=class Ts extends qt{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()}),Dn`<span class="os-segmented__thumb" aria-hidden="true"></span
11 ><slot></slot>`}};Ts.props=["value","label"],Ts.styles=[A0],Ts.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <os-segment> children where exactly one is active.",status:"stable",props:[{name:"value",type:"string",description:"Currently selected segment value. Mirrored onto child aria-checked."},{name:"label",type:"string",description:"aria-label for the radiogroup."}],slots:[{name:"(default)",description:'<os-segment value="…"> children.'}],events:[{name:"os-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--os-window-bg",description:"Pill background."},{name:"--os-ui-fg",description:"Active label colour."},{name:"--os-ui-fg-muted",description:"Inactive label colour."}],example:Dn`
12 <os-segmented value="md" label="Dock size">
13 <os-segment value="sm">Small</os-segment>
14 <os-segment value="md">Medium</os-segment>
15 <os-segment value="lg">Large</os-segment>
16 </os-segmented>
17 `};let oc=Ts;Oo("os-segmented",oc);const L0="openstation_overview";function _h(e){try{const t=new URL(e,window.location.href);return t.searchParams.set(L0,"1"),t.toString()}catch{return e}}function T0(e){const t=[];e.networkAdmin?.shellUrl&&t.push({value:"network",label:_("Network Admin"),shellUrl:e.networkAdmin.shellUrl});for(const n of e.sites??[])t.push({value:n.id,label:n.name,shellUrl:n.shellUrl});return t}function N0(e,t=fh){const n=T0(e);if(n.length<2)return null;const o=e.current??"",s=new Map(n.map(a=>[a.value,a])),i=document.createElement("os-segmented");i.className="os-site-switcher",i.setAttribute("label",_("Site")),i.setAttribute("value",o);for(const a of n){const l=document.createElement("os-segment");l.setAttribute("value",a.value),l.textContent=a.label,i.appendChild(l)}const r=a=>{if(!uh(a))return;const l=a.target?.closest("os-segment"),c=l?s.get(l.getAttribute("value")??""):void 0;c&&(a.preventDefault(),a.stopPropagation(),t(_h(c.shellUrl),a))};return i.addEventListener("click",r,!0),i.addEventListener("auxclick",r,!0),i.addEventListener("os-pick",a=>{const l=a.detail?.value,c=l?s.get(l):void 0;if(!c||l===o)return;const d=n.findIndex(f=>f.value===o),u=n.findIndex(f=>f.value===l);e0(u>d?"next":"prev").then(()=>t(_h(c.shellUrl)))}),i}const Ci=new Map;function Sh(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}Ci.set(e.id,e)}function O0(){return Array.from(Ci.keys())}async function sc(e){if(!e||e.length===0)return;const t=e.filter(n=>!Ci.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${O0().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=Ci.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():fe(o.url)}))}function kh(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:D0(),visible:!document.hidden,settings:gI(e)}}function D0(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class Ih{constructor(t,n){this.generation=0,this.active=null,this.suspendReasons=new Map,this.freezeOverlay=null,this.frozenCanvas=null,this.boundVisibilityChange=()=>{this.emitEffectiveVisibility()},this.element=t,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(t){const n=++this.generation;if(this.teardownActive(),t.type==="css"){this.applyCss(t);return}this.applyCanvas(t,n)}suspend(t){const n=this.isSuspended();this.suspendReasons.set(t,(this.suspendReasons.get(t)??0)+1),!n&&(this.installFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}resume(t){const n=this.suspendReasons.get(t);if(n!==void 0){if(n>1){this.suspendReasons.set(t,n-1);return}this.suspendReasons.delete(t),!this.isSuspended()&&(this.removeFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}}isSuspended(){return this.suspendReasons.size>0}teardownActive(){if(this.removeFreezeOverlay(),!this.active)return;const{id:t,teardown:n}=this.active;this.active=null,A(g.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){A(g.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(kh(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=kh(t.id,this.pluginUrl);A(g.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?sc(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},A(g.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(R0(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(g.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){A(g.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(g.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),A(g.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function R0(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const Ah=ie("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),Rn=Ah.state.seed,ic=Ah.state.listeners;function rc(e){Te("Game",Ut(e,Nh),e);const t=Rn.findIndex(n=>n.id===e.id);t>=0?Rn[t]=e:Rn.push(e),Lh()}function Ch(e){const t=Rn.findIndex(n=>n.id===e);t>=0&&(Rn.splice(t,1),Lh())}function x0(e){return ic.add(e),()=>{ic.delete(e)}}function Lh(){const e=Array.from(ic);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function Th(){const e=Rn.slice(),t=q(g.GAMES,e);return Array.isArray(t)?t.filter(M0):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function Li(e){return Th().find(t=>t.id===e)}const Nh=[{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 M0(e){return Ut(e,Nh).length===0}const Oh=new Set;function Ti(e){if(Oh.has(e))return;const n=window.openStationConfig?.deferredStyles?.[e];if(!n?.url)return;Oh.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 W0="desktop-mode/games";function P0(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function Do(e,t={},n={}){const{restUrl:o,restNonce:s}=P0(),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 $e(it(o,e),{...t,headers:i,credentials:"same-origin"},{source:W0,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok){const l=a?.message||`Games request failed (${r.status})`,c=new Error(l);throw c.status=r.status,c}return a}function $0(e,t,n={}){return Do(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function U0(){return Do("desktop-mode/v1/games/playtime")}function B0(e,t,n={}){return Do(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function F0(e){return Do(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function H0(e,t,n={}){return Do(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const G0=6e4;function z0(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,B0(e,l,{windowId:t.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,G0);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const xn=ie("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function V0(){return xn.state}function ac(e){const t=xn.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&&K0()}function j0(e){return xn.state.listeners.add(e),()=>{xn.state.listeners.delete(e)}}function K0(){for(const e of Array.from(xn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function q0(){return Array.from(xn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function Dh(){return window.wp?.os??{}}const Y0=760,X0=560,Z0=480,J0=380;function Q0(){const e=window.openStationConfig?.gameStyleHandles??[];for(const t of e)Ti(t)}async function eC(e){if(typeof e.render=="function")return e;const t=Dh().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,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 rc(s),s}async function Rh(e,t={}){const n=Dh(),o=Li(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);if(Q0(),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 v=a.config?.desktopId;v&&r?.switchDesktop&&v!==r?.getActiveDesktopId?.()&&r.switchDesktop(v),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=(v,h)=>{n.activity?.publish("os/game-score-recorded",{game:e,score:v.score,meta:v.meta??{},windowId:s,challengeId:h})},p=v=>{if(t.challenge){const h=t.challenge.id;return H0(h,v,{windowId:s}).then(({challenge:w})=>{ac([w]),f(v,h)})}return $0(e,v,{windowId:s}).then(()=>f(v))};try{await n.registerWindow({id:s,title:o.title,icon:o.icon,width:o.window?.width??Y0,height:o.window?.height??X0,minWidth:o.window?.minWidth??Z0,minHeight:o.window?.minHeight??J0,render:async v=>{const h=await eC(o),w=h.render;if(typeof w!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);const E={windowId:s,container:v,config:h.config??{},challenge:t.challenge,submitScore:p,close:()=>{n.windowManager?.getById(s)?.close()}};d=z0(e,{windowId:s});const S=w(E);return()=>{try{S?.()}finally{u(),c()}}}})}catch(v){throw u(),c(),v}}const xh={register:rc,unregister:Ch,list:Th,get:Li,subscribe:x0,launch:Rh,getPlaytime:()=>U0().then(e=>e.playtime)},Mn=ie("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function tC(e){Mn.state.pending.set(e.id,e)}function Ni(e){Mn.state.pending.delete(e)}function nC(e){return(window.openStationWallpapers||{})[e]??null}function Mh(e){const t=Mn.state.inflight.get(e);if(t)return t;const n=Mn.state.pending.get(e);if(!n)return Promise.resolve(null);const o=(async()=>{try{await fe(n.scriptUrl,{translations:n.scriptTranslations,l10n:n.scriptL10n,before:n.scriptBefore,after:n.scriptAfter})}catch(i){return A(g.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=nC(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return A(g.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{Ln(s)}catch(i){return A(g.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return Ni(n.id),s})().finally(()=>{Mn.state.inflight.delete(e)});return Mn.state.inflight.set(e,o),o}function oC(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 Mh(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await sc(o.needs),o.mount(t,n))}}}function sC(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},s=async r=>{if(n.has(r.id))return;const a=o(r);if(a){Ln(a),n.add(r.id),t.apply();return}if(!r.scriptUrl)return;tC(r);const l=r.preview!==""||r.value!=="";if(l){try{Ln(oC(r))}catch(c){A(g.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:c}),Ni(r.id);return}n.add(r.id)}if(!l||t.state.wallpaper===r.id){const c=await Mh(r.id);if(!l){if(!c){Ni(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(hp(r),Ni(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 iC(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}}function rC(){const e=new Set,t=o=>{try{const s=Li(o.id),i=iC(o);rc(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)&&(Ch(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 pt=ie("desktop-mode/heartbeat-bus",()=>({suppliers:new Map,subscribers:new Map,booted:!1})),Oe={contribute(e,t){return pt.state.suppliers.set(e,t),()=>{pt.state.suppliers.get(e)===t&&pt.state.suppliers.delete(e)}},subscribe(e,t){let n=pt.state.subscribers.get(e);return n||(n=new Set,pt.state.subscribers.set(e,n)),n.add(t),()=>{n.delete(t)}}};function aC(){if(pt.state.booted)return;pt.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 pt.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 pt.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 Oi=null,Di={installHintDismissed:!1,notificationsEnabled:!1};const cc=new Set;function Wh(e){if(!e){Oi=null;return}Oi=e,Di={...e.state},$h()}function Ro(){return{...Di}}function lc(e){if(Di={...Di,...e},$h(),!Oi)return Ro();const t=JSON.stringify(e),n=cC();return fetch(Oi.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)}),Ro()}function Ph(e){return cc.add(e),()=>{cc.delete(e)}}function $h(){const e=Ro();for(const t of Array.from(cc))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function cC(){return window.openStationConfig?.restNonce??""}const lC=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:Ro,initPwaState:Wh,subscribePwaState:Ph,updatePwaState:lc},Symbol.toStringTag,{value:"Module"}));function dc(e){const t=Ee.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}),Ee.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=Uh(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){lc({notificationsEnabled:!0}),o=Uh(t),o||r();return}r()}}),i)}function Uh(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 Ee.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function dC(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&lc({notificationsEnabled:!0}),e}function uC(){return typeof Notification>"u"?"unsupported":Notification.permission}function fC(e){return Li(e)?.title||e}const Bh=new Set,Fh=new Set;async function pC(e){const{challenge:t}=await F0(e.id);ac([t]),await Rh(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function hC(e){const t=re(_("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,fC(e.game),String(e.scoreToBeat));dc({title:_("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),ue({message:t,persistent:!0,dismissible:!0,action:{label:_("Accept & Play"),onClick:()=>{pC(e).catch(n=>{ue({message:n instanceof Error?n.message:_("Could not accept the challenge.")})})}}})}function mC(e){let t;e.result==="beaten"?t=_("%1$s beat your score: %2$s vs your %3$s."):t=_("%1$s did not beat your score: %2$s vs your %3$s.");const n=re(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));dc({title:_("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),ue({message:n})}function wC(e){const{currentUserId:t}=e;if(!t)return;Oe.contribute("openstation_games_subscribe",()=>({challengesVersion:V0().version})),Oe.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&ac(o.challenges)});const n=()=>{for(const o of q0())o.state==="pending"&&o.recipientId===t&&!Bh.has(o.id)&&(Bh.add(o.id),hC(o)),o.state==="completed"&&o.challengerId===t&&!Fh.has(o.id)&&(Fh.add(o.id),mC(o))};j0(n),n()}const Hh=/^[a-z0-9_/-]+$/,Gh=ie("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),Yt=Gh.state.registry,gC=Gh.state.listeners;function Wn(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)"):Hh.test(n)||t.push(`slug (must match ${Hh} — 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)")),Te("Command",t,e),Yt.set(n,{...e,slug:n}),uc()}function zh(e){Yt.delete(e.toLowerCase())&&uc()}function Ri(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Yt.entries()))o.owner===e&&(Yt.delete(n),t++);return t>0&&uc(),t}function Vh(){return Array.from(Yt.values())}function yC(){const e=[];for(const t of Yt.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function vC(e){return Yt.get(e.toLowerCase())??null}function uc(){const e=Array.from(gC);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function bC(){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 fe(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(g.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 Vh())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))zh(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const jh=ie("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),xo=jh.state.registry,EC=jh.state.listeners;function Kh(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}xo.set(t,{...e,id:t}),fc()}function qh(e){xo.delete(e.toLowerCase())&&fc()}function _C(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(xo.entries()))o.owner===e&&(xo.delete(n),t++);return t>0&&fc(),t}function Yh(){return Array.from(xo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function fc(){const e=Array.from(EC);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function SC(){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 fe(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(g.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=>{_C(r);const a=n.get(r);if(a){const l=new Set(Yh().map(c=>c.id));for(const c of a)l.has(c)&&qh(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 Xh=ie("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),Mo=Xh.state.registry,kC=Xh.state.listeners,Zh=/^[a-z0-9_/-]+$/;function xi(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Zh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Zh} — 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)")),Te("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();Mo.set(n,{...e,id:n}),Mi()}function IC(e){Mo.delete(e.toLowerCase())&&Mi()}function AC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Mo.entries()))o.owner===e&&(Mo.delete(n),t++);return t>0&&Mi(),t}function CC(){return Array.from(Mo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Mi(){const e=Array.from(kC);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"&&Mi()});function LC(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await fe(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(g.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)||(AC(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Jh=ie("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),Wo=Jh.state.registry,TC=Jh.state.listeners,Qh=/^[a-z0-9_/-]+$/;function pc(){for(const e of Array.from(TC))try{e()}catch{}}function em(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Qh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Qh} — 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)")),Te("WindowAction",t,e);const n=e.id.trim().toLowerCase();Wo.set(n,{...e,id:n}),pc()}function NC(e){Wo.delete(String(e||"").toLowerCase())&&pc()}function OC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Wo.entries()))o.owner===e&&(Wo.delete(n),t++);return t>0&&pc(),t}function DC(){return Array.from(Wo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function RC(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await fe(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(g.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)||(OC(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function tm(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function xC({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)=>tm(r[0])-tm(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 nm(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 om(e){const t=Je(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=q(g.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(nm):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(nm))}function hc(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function MC(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function WC(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=om(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=xC({items:s,onPick:c=>{r(),MC(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 PC({manager:e,openUrl:t}){xi({id:"desktop-mode/related-entities",label:_("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>om(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}WC(n,o,t)})}}),Z(g.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 mc="os-broadcast",sm="os-broadcast",im=window.location.origin;let wc=null;function $C(e){wc=e}function Wi(e,t){const n=String(q("os.broadcast.topic",e,{payload:t})??e),o=q("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(mc,{detail:s})),A(g.BROADCAST,s),Ee.publish(n,o),!wc)return;const i={type:sm,topic:n,payload:o};for(const r of wc._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,im)}catch{}}}function Pn(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(g.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(mc,n),()=>document.removeEventListener(mc,n)}function UC(){window.addEventListener("message",e=>{if(e.origin!==im)return;const t=e.data;!t||t.type!==sm||t._fromParent||typeof t.topic=="string"&&Wi(t.topic,t.payload)})}function rm(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||Wi(`os.${i}.changed`,{source:o,action:t,ids:s})}const BC=new Set(["saved","no-editor","not-dirty","error"]);let am=0;function cm(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function FC(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});am+=1;const o=`os-editor-preview-${Date.now()}-${am}`;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"&&BC.has(d.status)?d.status:"error",f=cm(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 Re=ie("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),HC=400,lm=1500;function Po(e){return e?`${e.type}:${e.id}`:""}function GC(e){for(const t of Re.state.pairings.values())if(t.previewWindowId===e)return t}function zC(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function VC(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 Pi(e,t,n,o){Re.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(um(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(g.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function gc(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||Je(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?.()},HC)}function jC(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=Pn(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||gc(e,t)})}let dm=0;function um(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 fm(e,t,n){um(e,t);const o=q(g.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:lm},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;dm+=1;const i=`${t.previewWindowId}-watch-${dm}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:lm},window.location.origin),t.watchId=i}catch{}}let KC=FC;async function qC(e,t){const n=Re.state.pairings.get(t.id);if(n){Pi(e,n,"toggled","close");return}if(Re.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=Je(t.id);if(!o?.previewUrl){ue({message:_("No preview is available for this content.")});return}Re.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=zC();s||t.applySnap?.("left");const i=KC(t);i.then(f=>{f.status==="error"&&ue({message:_("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{Re.state.busyEditors.delete(t.id),e.getById(t.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=_("Preview");o.label&&(a=re(_("Preview: %s"),o.label));let l={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=q(g.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)||Po(Je(t.id))!==Po(o)){e.getById(l.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:l.id,postKey:Po(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};jC(e,d,o),fm(e,d,o),Re.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(g.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Re.state.pairings.get(t.id)===d&&f.status==="saved"&&gc(e,d,f.previewUrl)})}function YC({manager:e}){xi({id:"desktop-mode/editor-preview",label:_("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!Je(t.id)?.previewUrl||VC(t)),render:(t,n)=>{if(!Je(n.id)?.previewUrl){const i=_("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:_("The preview opens once the post has been saved.")})});return}const o=Re.state.pairings.has(n.id),s=Re.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(),qC(e,n)})}}),Z(g.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Re.state.pairings.get(t.windowId);n&&Po(t.content)!==n.postKey&&Pi(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),Z(g.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Re.state.pairings.get(t.windowId);if(n){Pi(e,n,"editor-closed","destroy");return}const o=GC(t.windowId);o&&Pi(e,o,"preview-closed","none")}),Z(g.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Re.state.pairings.get(t.windowId);if(n){const o=Je(t.windowId);o&&Po(o)===n.postKey&&fm(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 Re.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){gc(e,o,cm(n.previewUrl));return}}})}const pm=16,Ge=16,XC=1100,ZC=860;function JC(e,t){const n=Math.max(0,t.width-Ge*2),o=Math.max(320,Math.min(XC,Math.round(n*.5))),s=Math.max(200,Math.min(ZC,Math.round(t.height*.8))),i=QC(e.y,Ge,Math.max(Ge,t.height-s-Ge)),r=e.x+e.width+pm;if(r+o+Ge<=t.width)return{x:r,y:i,width:o,height:s};const a=e.x-pm-o;if(a>=Ge)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(Ge,t.width-o-Ge):Ge,y:u?Math.max(Ge,t.height-s-Ge):Ge,width:o,height:s}}function QC(e,t,n){return Math.min(Math.max(e,t),n)}function eL(e){return`revisions-${String(e.type).replace(/\//g,"-")}-${e.id}`}function tL(e){const t=e?.revisionCount;return typeof t=="number"&&t>0?re(_("View revisions (%d)"),t):_("View revisions")}function nL(e,t,n){if(di(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?{}:JC({x:o.offsetLeft,y:o.offsetTop,width:o.offsetWidth,height:o.offsetHeight},{width:s.clientWidth,height:s.clientHeight})}async function oL(e,t){const n=Je(t.id);if(!n?.revisionsUrl){ue({message:_("No revisions are available for this content.")});return}const o=eL(n);let s=_("Revisions");n.label&&(s=re(_("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},...nL(e,t.id,o)};const r=q(g.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(g.REVISIONS_OPENED,a)}function sL({manager:e}){em({id:"desktop-mode/view-revisions",label:t=>tL(Je(t.id)),icon:"dashicons-backup",order:60,isVisible:t=>!!Je(t.id)?.revisionsUrl,onSelect:t=>{oL(e,t)}})}const hm="none",mm=ie("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),$o=mm.state.registry,yc=mm.state.listeners,wm=/^[a-z0-9_/-]+$/;function $i(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):wm.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===hm&&t.push('id ("none" is reserved)'):t.push(`id (must match ${wm} — 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)")),Te("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();$o.set(n,{...e,id:n}),bc()}function iL(e){$o.delete(e.toLowerCase())&&bc()}function rL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from($o.entries()))o.owner===e&&($o.delete(n),t++);return t>0&&bc(),t}function vc(){const e=Array.from($o.values()),t=q(g.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 gm(e){return vc().find(t=>t.id===e)}function aL(e){return yc.add(e),()=>{yc.delete(e)}}function bc(){const e=Array.from(yc);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}$i({id:"darken",label:_("Darken"),description:_("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),$i({id:"frost",label:_("Frost"),description:_("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"}),$i({id:"grayscale",label:_("Grayscale"),description:_("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 cL(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await fe(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(g.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)||(rL(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const lL="none",ym=ie("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),Uo=ym.state.registry,dL=ym.state.listeners,vm=/^[a-z0-9_/-]+$/;function bm(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):vm.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===lL&&t.push('id ("none" is reserved)'):t.push(`id (must match ${vm} — 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)")),Te("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();Uo.set(n,{...e,id:n}),_c()}function uL(e){Uo.delete(e.toLowerCase())&&_c()}function fL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Uo.entries()))o.owner===e&&(Uo.delete(n),t++);return t>0&&_c(),t}function Ec(){const e=Array.from(Uo.values()),t=q(g.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 _c(){const e=Array.from(dL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}function pL(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await fe(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(g.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)||(fL(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}let Xt=null;function Em(){if(Xt)return Xt;if(window.openStationWindowLinkVisuals)return Xt=Promise.resolve(!0),Xt;const t=window.openStationConfig?.windowLinkVisualsBundleUrl;return t?(Xt=fe(t).then(()=>!0).catch(n=>{throw Xt=null,n}),Xt):Promise.resolve(!1)}const Sc="svg-splines";function hL(){if(Ec().some(t=>t.id===Sc))return;const e=async t=>{if(!await Em())return;const o=Ec().find(s=>s.id===Sc);if(!(!o||o.mount===e))return o.mount(t)};bm({id:Sc,label:_("Splines"),description:_("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 kc="data-desktop-unfocus-effect",Ic="data-desktop-unfocus-effect-class";let _m=!1;function mL(e){return e.querySelector("canvas")!==null}function wL(e){return e.state==="snapped-left"||e.state==="snapped-right"}function gL({manager:e,osSettings:t}){if(_m)return;_m=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(Ic);l&&(r.classList.remove(l),r.removeAttribute(Ic));const c=r.getAttribute(kc);c&&gm(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(kc)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Ic,a.className)),r.setAttribute(kc,a.id),a.apply?.(r)},i=()=>{const r=n===hm?void 0:gm(n),a=vc();for(const l of e.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(wL(l)||mL(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()}),aL(()=>i()),i()}function yL(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await fe(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(g.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)||(Zb(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function vL(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,fe(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 Sm=ie("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),Bo=Sm.state.registry,bL=Sm.state.listeners,km=/^[a-z0-9_/-]+$/;function Im(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)"):km.test(e.id.trim().toLowerCase())||t.push(`id (must match ${km} — 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)")}Te("WindowTheme",t,e);const n=e.id.trim().toLowerCase();Bo.set(n,{...e,id:n}),Ac()}function Am(e){Bo.delete(e.toLowerCase())&&Ac()}function EL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Bo.entries()))o.owner===e&&(Bo.delete(n),t++);return t>0&&Ac(),t}function Cm(){return Array.from(Bo.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function Ac(){const e=Array.from(bL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function _L(){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 fe(l.scriptUrl,{translations:l.scriptTranslations,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){A(g.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 Cm())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{Im({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(g.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)Am(p),o.delete(p);EL(u),e.delete(u)}a(c);for(const u of l)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const Lm=ie("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),Fo=Lm.state.registry,SL=Lm.state.listeners,Tm=/^[a-z0-9_/-]+$/;function Ho(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Tm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Tm} — 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")')),Te("WindowControl",t,e);const n=e.id.trim().toLowerCase();Fo.set(n,{...e,id:n}),Cc()}function Nm(e){Fo.delete(e.toLowerCase())&&Cc()}function kL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Fo.entries()))o.owner===e&&(Fo.delete(n),t++);return t>0&&Cc(),t}function Om(){return Array.from(Fo.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Cc(){const e=Array.from(SL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function IL(){Ho({id:"core/minimize",label:_("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),Ho({id:"core/maximize",label:_("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),Ho({id:"core/focus-tab",label:_("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),Ho({id:"core/close",label:_("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function AL(){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 fe(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(g.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 Om())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))Nm(d);kL(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Dm=ie("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),Go=Dm.state.registry,CL=Dm.state.listeners,Rm=/^[a-z0-9_/-]+$/,xm=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Mm(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Rm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Rm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):xm.has(e.slot)||t.push(`slot (must be one of ${Array.from(xm).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Te("WindowSlot",t,e);const n=e.id.trim().toLowerCase();Go.set(n,{...e,id:n}),Tc()}function Lc(e){Go.delete(e.toLowerCase())&&Tc()}function LL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Go.entries()))o.owner===e&&(Go.delete(n),t++);return t>0&&Tc(),t}function Wm(){return Array.from(Go.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Tc(){const e=Array.from(CL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function TL(){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 fe(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(g.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 Wm())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))Lc(d);LL(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const NL="desktop-mode-notice-dismissed";function OL(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function Pm(){return`${NL}:${OL()}`}function Nc(){try{const e=window.localStorage.getItem(Pm());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function $m(e){try{window.localStorage.setItem(Pm(),JSON.stringify(e))}catch{}}function Ui(e){return e?Nc()[e]===!0:!1}function Bi(e){if(!e)return;const t=Nc();t[e]=!0,$m(t)}function Um(e){if(!e)return;const t=Nc();t[e]&&(delete t[e],$m(t))}const DL=Ae`: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 ) )}`,Ns=class Ns extends qt{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&Ui(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&Bi(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&Um(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return Dn`
18 <span
19 class="os-notice__icon dashicons ${t??""}"
20 ?hidden=${!t}
21 aria-hidden="true"
22 ></span>
23 <span class="os-notice__label"><slot></slot></span>
24 <button
25 type="button"
26 class="os-notice__close"
27 ?hidden=${!n}
28 aria-label=${_("Dismiss notice")}
29 @click=${o=>this._onDismiss(o)}
30 >
31 ${Dd("close",{size:null})}
32 </button>
33 `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};Ns.props=["tone","notDismissible","icon","noticeId"],Ns.styles=[DL],Ns.help=void 0;let Oc=Ns;Oo("os-notice",Oc);const zo=ie("desktop-mode/window-notices",()=>({entries:new Map})),RL=/^[a-z0-9_/-]+$/;function Bm(e){return`os-notice/${e.toLowerCase()}`}function xL(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 Fm(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!RL.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};zo.state.entries.set(t,n);const o=Bm(t);return Mm({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=zo.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=zo.state.entries.get(t);i&&s.appendChild(xL(i))}}),()=>Dc(t)}function Dc(e){const t=String(e??"").trim().toLowerCase();t&&zo.state.entries.delete(t)&&Lc(Bm(t))}function Hm(){return Array.from(zo.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 ML(e){const t=String(e??"").trim().toLowerCase();t&&Bi(t)}function WL(e){const t=String(e??"").trim().toLowerCase();t&&Um(t)}function PL(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 Gm(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),Fm({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:PL(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of Hm())n.owner==="__server__"&&(t.has(n.id)||Dc(n.id))}const zm=ie("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),Vo=zm.state.registry,$L=zm.state.listeners,Vm=/^[a-z0-9_/-]+$/;function UL(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Vm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Vm} — 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)")),Te("WindowChrome",t,e);const n=e.id.trim().toLowerCase();Vo.set(n,{...e,id:n}),Rc()}function jm(e){Vo.delete(e.toLowerCase())&&Rc()}function BL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Vo.entries()))o.owner===e&&(Vo.delete(n),t++);return t>0&&Rc(),t}function Km(){return Array.from(Vo.values()).sort((e,t)=>e.id.localeCompare(t.id))}function Rc(){const e=Array.from($L);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function FL(){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 fe(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(g.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 Km())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))jm(d);BL(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const xc=window.location.origin,Ce=ie("desktop-mode/connection",()=>({connSeq:0,connections:new Map,connectionsByTarget:new Map,syntheticIframes:new Map}));function HL(e,t){const{syntheticIframes:n}=Ce.state;return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function GL(){return`os-conn-${++Ce.state.connSeq}`}function zL(e){const t=(l,c)=>{try{l.contentWindow?.postMessage(c,xc)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=GL(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let v=!1,h=!1;const w=()=>{const U=Ce.state.syntheticIframes.get(l);return U||(e.getById(l)?.iframe??null)},E=()=>{if(w())return!1;const U=e.getById(l);return!!U&&U.config?.native===!0},S=[],O=()=>{const U=w();if(U)for(;p.length;){const j=p.shift();t(U,{type:"os-bridge-publish",connectionId:d,topic:j.topic,payload:j.payload})}},M={id:d,target:l,isOpen:()=>v,subscribe(U,j){const B=j;if(E()){const J=KE(l,U,(K,T)=>{A(g.CONNECTION_MESSAGE,{connectionId:d,topic:T.channel,direction:"in"});try{B(K,{topic:T.channel})}catch(R){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",R)}});return S.push(J),J}let V=f.get(U);return V||(V=new Set,f.set(U,V)),V.add(B),()=>{V?.delete(B)}},send(U,j){if(h)return;if(A(g.CONNECTION_MESSAGE,{connectionId:d,topic:U,direction:"out"}),E()){YE(l,U,j);return}if(!v){p.push({topic:U,payload:j});return}const B=w();B&&t(B,{type:"os-bridge-publish",connectionId:d,topic:U,payload:j})},disconnect(){M._destroy("disconnect")},_targetWindow:w,_handleIframeMessage(U){if(!U||typeof U!="object")return;const j=U;if(j.type==="os-bridge-handshake-ack"){if(v)return;v=!0,A(g.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:M});try{c.onOpen?.()}catch(B){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",B)}O();return}if(j.type==="os-bridge-publish"){const B=U,V=typeof B.topic=="string"?B.topic:"";if(!V)return;A(g.CONNECTION_MESSAGE,{connectionId:d,topic:V,direction:"in"});const J=f.get(V);if(J)for(const T of Array.from(J))try{T(B.payload,{topic:V})}catch(R){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",R)}const K=f.get("*");if(K)for(const T of Array.from(K))try{T(B.payload,{topic:V})}catch(R){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",R)}return}j.type==="os-bridge-disconnect"&&M._destroy("disconnect")},_destroy(U){if(h)return;h=!0;const j=v;v=!1,Ce.state.connections.delete(d);const B=Ce.state.connectionsByTarget.get(l);B&&(B.delete(d),B.size===0&&Ce.state.connectionsByTarget.delete(l));for(const V of S.splice(0))try{V()}catch{}if(j){const V=w();V&&t(V,{type:"os-bridge-disconnect",connectionId:d})}A(g.CONNECTION_CLOSED,{connectionId:d,reason:U});try{c.onClose?.(U)}catch(V){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",V)}}};Ce.state.connections.set(d,M);let b=Ce.state.connectionsByTarget.get(l);if(b||(b=new Set,Ce.state.connectionsByTarget.set(l,b)),b.add(d),E())return Promise.resolve().then(()=>{if(!(h||v)){v=!0,A(g.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(U){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",U)}}}),M;const W=w();return W&&t(W,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),M},o=(l,c)=>{if(!l||typeof l!="object")return;const d=l;if(typeof d.type!="string"||!d.type.startsWith("os-bridge-"))return;if(d.type==="os-bridge-connection-request"&&typeof d.requestId=="string"&&typeof c=="string"&&c!==""){s(c,d.requestId,Array.isArray(d.topics)?d.topics:[]);return}if(typeof d.connectionId!="string")return;Ce.state.connections.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=Ce.state.syntheticIframes.get(l)??e.getById(l)?.iframe??null;if(!f)return;const p=q(g.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"},xc)}catch{}return}const v=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,h=n(l,{topics:v});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:h.id},xc)}catch{}};return{connect:n,getConnection:l=>Ce.state.connections.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=Ce.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c)){const u=Ce.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=Ce.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c))Ce.state.connections.get(d)?._destroy("window-closed")}}}const VL={};function jL(...e){(typeof{url:Or&&Or.tagName.toUpperCase()==="SCRIPT"&&Or.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&VL?"production":void 0)!=="production"&&console.log(...e)}const KL="iframe:";function Mc(e){return KL+e}function qm(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function qL(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const YL=250;class XL{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"&&(Ri(Mc(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&&Ri(Mc(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()},YL)}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){jL("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=Mc(t);Ri(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=qL(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?kd(s.iconSvg):"",a={slug:i,label:s.label,icon:qm(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,qm(s)):this.runProxy(t,s.name)};try{Wn(a)}catch(l){console.error("[openstation] iframe-bridge: dropping bad command",a,l)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Ze(t))return;const r=de(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runProxy(t,n){return(o,s)=>{s.close();const i=this.manager.getById(t);if(!(!i||!i.iframe||!i.iframe.contentWindow)){try{i.iframe.contentWindow.postMessage({type:"os-commands-invoke",name:n},window.location.origin)}catch{}this.manager.focus(i)}}}}function ZL(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 Ym="global",JL=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,QL=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,eT=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,tT=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,nT=/getSiteEditorPage\s*\(|site-editor\.php/,oT=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function sT(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 iT{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 w=new Array(h.length);for(let E=0;E<h.length;E++){const S=h[E];w[E]=S&&S.name?S.name:""}return w.join("|")},f=()=>{let h=[];for(const w of d.loadersList){const E=d.perLoader[w];Array.isArray(E)&&(h=h.concat(E))}Array.isArray(d.statics)&&(h=h.concat(d.statics)),this.callbackCache=Object.create(null);for(const w of h)w&&w.name&&typeof w.callback=="function"&&(this.callbackCache[w.name]=w.callback);this.publish(h)},p=h=>{const w=h.loader;let E=null;try{E=w.hook({search:""})}catch{}const S=E&&Array.isArray(E.commands)?E.commands:[],O=a(()=>u(S),[S]);return i(()=>{d.perLoader[w.name]=S,f()},[O]),i(()=>()=>{delete d.perLoader[w.name],f()},[]),null},v=()=>{const h=l(b=>{const W=b("core/commands");return!W||typeof W.getCommandLoaders!="function"?[]:[...W.getCommandLoaders(!1)||[],...W.getCommandLoaders(!0)||[]]},[]),w=l(b=>{const W=b("core/commands");return!W||typeof W.getCommands!="function"?[]:[...W.getCommands(!1)||[],...W.getCommands(!0)||[]]},[]),E=a(()=>Array.isArray(h)?h.map(b=>b&&b.name||""):[],[h]),S=E.join("|");i(()=>{d.loadersList=E,f()},[S]);const O=a(()=>u(Array.isArray(w)?w:[]),[w]);if(i(()=>{d.statics=Array.isArray(w)?w:[],f()},[O]),!Array.isArray(h)||h.length===0)return null;const M=[];for(const b of h)!b||typeof b.hook!="function"||M.push(s(p,{key:b.name,loader:b}));return s(n.Fragment||"div",null,M)};try{this.root=n.createRoot(c),this.root.render(s(v))}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||""}
34 `;if(s!==this.lastFingerprint){this.lastFingerprint=s,Ri(Ym);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,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?kd(i.iconSvg):void 0,owner:Ym,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name)};try{Wn(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=sT(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(JL)||i.match(QL)||i.match(eT);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(tT.test(i)){const l=nT.test(i)?n.name.match(oT):null;if(l){const c=l[1],d=l[2],u=`/${c}/${d}`;try{const f=new URL("site-editor.php",this.adminUrl);f.searchParams.set("p",u),f.searchParams.set("canvas","edit"),n.url=f.toString(),n.kind="navigate"}catch{n.kind="skip"}}else n.kind="skip"}}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}renderIcon(t){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(t);if(typeof o=="string"&&o.toLowerCase().startsWith("<svg"))return o}catch{}return""}iconFor(t){return t.icon&&t.icon.startsWith("dashicons-")?t.icon:t.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Ze(t))return;const r=de(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(re(_("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 Xm="os-command-palette-ready";let jo=null;function rT(){const t=window.openStationConfig?.commandPalette;return!t||!Array.isArray(t.scripts)?null:t}function aT(){const e=window.wp;try{return!!e?.data?.select?.("core/commands")}catch{return!1}}function cT(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 lT(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 dT(){const e=rT();if(!e||e.scripts.length===0)return aT();for(const s of e.styles??[])cT(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||!za(s));for(const s of o)s.url&&lT(s.url);for(const s of o)if(s.url)await fe(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!==""&&Wp(i);return document.dispatchEvent(new CustomEvent(Xm)),!0}function uT(){return jo||(jo=dT().catch(e=>{throw jo=null,e}),jo)}const $n=[];function Wc(e){Te("Widget",Ut(e,Zm),e);const t=$n.findIndex(n=>n.id===e.id);t>=0?$n[t]=e:$n.push(e)}function fT(e){const t=$n.findIndex(n=>n.id===e);t>=0&&$n.splice(t,1)}function Pc(){const e=$n.slice(),t=q(g.WIDGETS,e);return Array.isArray(t)?t.filter(pT):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function Un(e){return Pc().find(t=>t.id===e)}const Zm=[{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 pT(e){return Ut(e,Zm).length===0}let Qe=null;function hT(e){if(Qe)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",_("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=_("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),Jm(o,e),document.body.appendChild(t),mT(t,e.anchor);const s=a=>{const l=a.target;l&&(t.contains(l)||e.anchor.contains(l)||$c())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&$c()};document.addEventListener("keydown",i),Qe={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function Ko(){if(!Qe)return;const e=Qe.panel.querySelector(".os-widget-picker__list");e&&Jm(e,Qe.options)}function $c(){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 Jm(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=_("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=re(_("%s (already added)"),s.label):a=re(_("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=_("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function mT(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 Fi="os-widgets__card--floating",wT="os-widgets__card--movable",gT="os-widgets__card--resizable",Qm="os-widgets__card--dragging",ew="os-widgets__card--resizing",yT=160,tw=80,vT=280,bT=180,Bn=20,Zt=20,nw=5,ET=nw*nw,_T='input, textarea, select, button, a, [contenteditable="true"]';function ST(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(wT),i&&o.classList.add(gT),s?o.appendChild(kT(e,n.onRemove,n.onRedock)):o.appendChild(AT(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(Hi(o,iw(t.geometry,t.floatingParent)),o.classList.add(Fi)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${OT(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(Fi),l=[];if(i)for(const d of TT()){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(LT(o,u,d,e,t,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=CT(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 kT(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(IT(e,n));const r=ow(e,t);return o.appendChild(r),o}function IT(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",re(_("Dock %s back to widget column"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2 6h6M5.5 3.5L8 6l-2.5 2.5M10 2.5v7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n.dataset.noDrag="true",n}function AT(e,t){const n=ow(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function ow(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",re(_("Remove %s"),e.label)),n.innerHTML=bt("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function CT(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 w=h.target;w&&w.closest(_T)||(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(Fi)){const h=o.floatingParent.getBoundingClientRect(),w=e.getBoundingClientRect(),E={x:w.left-h.left,y:w.top-h.top,width:w.width||n.defaultWidth||vT,height:w.height||n.defaultHeight||bT};Hi(e,E),e.classList.add(Fi),s.onLiberate(E),l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(Qm)},p=h=>{if(i===null||h.pointerId!==i)return;const w=h.clientX-r,E=h.clientY-a;if(!d){if(w*w+E*E<ET)return;d=!0,f()}const S=aw(Fn(l+w),Fn(c+E),e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${rw(S.x)}px`,e.style.top=`${rw(S.y)}px`},v=h=>{if(!(i===null||h.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(Qm),s.onGeometryChanged(sw(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",v),t.addEventListener("pointercancel",v),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",v),t.removeEventListener("pointercancel",v)}}function LT(e,t,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const v=E=>{if(E.button!==0||!r()&&!NT(n))return;E.preventDefault(),E.stopPropagation(),a=E.pointerId,l=E.clientX,c=E.clientY;const S=e.getBoundingClientRect(),O=s.floatingParent.getBoundingClientRect();d=S.left-O.left,u=S.top-O.top,f=S.width,p=S.height,t.setPointerCapture(a),e.classList.add(ew)},h=E=>{if(a===null||E.pointerId!==a)return;const S=E.clientX-l,O=E.clientY-c,M=DT(n,S,O,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${M.x}px`,e.style.top=`${M.y}px`,e.style.width=`${M.width}px`),e.style.height=`${M.height}px`},w=E=>{if(!(a===null||E.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(ew),r()?i.onGeometryChanged(sw(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",v),t.addEventListener("pointermove",h),t.addEventListener("pointerup",w),t.addEventListener("pointercancel",w),()=>{t.removeEventListener("pointerdown",v),t.removeEventListener("pointermove",h),t.removeEventListener("pointerup",w),t.removeEventListener("pointercancel",w)}}function TT(){return["n","e","s","w","ne","nw","se","sw"]}function NT(e){return e==="s"}function Hi(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 sw(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function OT(e,t){return Hn(e,t.minHeight??tw,t.maxHeight??1/0)}function iw(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=aw(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function Fn(e){return Math.round(e/Zt)*Zt}function rw(e){const t=Math.floor(e/Zt)*Zt;return t>=Bn?t:Math.min(e,Bn)}function aw(e,t,n,o,s){const i=he(s),r=i.x+Bn,a=i.y+Bn,l=Math.max(i.x,i.x+i.width-n-Bn),c=Math.max(i.y,i.y+i.height-o-Bn);return{x:Math.min(Math.max(r,e),l),y:Math.min(Math.max(a,t),c)}}function DT(e,t,n,o,s,i,r,a,l,c){const d=a.minWidth??yT,u=a.minHeight??tw,f=a.maxWidth??1/0,p=a.maxHeight??1/0,v=he(l),h=v.x+v.width,w=v.y+v.height;let E=o,S=s,O=i,M=r;if((e==="e"||e==="ne"||e==="se")&&(c?O=Gi(Fn(o+i+t),o+d,Math.min(o+f,h))-o:O=Hn(i+t,d,Math.min(f,h-o))),e==="w"||e==="nw"||e==="sw"){const b=o+i;if(c)E=Gi(Fn(o+t),Math.max(0,b-Math.min(f,b)),b-d),O=b-E;else{const W=Hn(i-t,d,Math.min(f,b));E=o+(i-W),O=W}}if((e==="s"||e==="se"||e==="sw")&&(c?M=Gi(Fn(s+r+n),s+u,Math.min(s+p,w))-s:M=Hn(r+n,u,Math.min(p,w-s))),e==="n"||e==="ne"||e==="nw"){const b=s+r;if(c)S=Gi(Fn(s+n),Math.max(0,b-Math.min(p,b)),b-u),M=b-S;else{const W=Hn(r-n,u,Math.min(p,b));S=s+(r-W),M=W}}return c||(O=i,E=o),{x:E,y:S,width:O,height:M}}function Gi(e,t,n){const o=Hn(e,t,n),s=Math.floor(o/Zt)*Zt;if(s>=t)return s;const i=s+Zt;return i<=n?i:o}function Hn(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const cw="desktop-mode-widgets",lw="desktop-mode-widgets-geometry",dw="desktop-mode-widgets-docked-heights";function uw(){try{return window.localStorage.getItem(cw)}catch{return null}}function RT(){const e=uw();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Uc(e){try{window.localStorage.setItem(cw,JSON.stringify(e))}catch{}}function xT(){try{const e=window.localStorage.getItem(lw);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=WT(s);i&&(n[o]=i)}return n}catch{return{}}}function Bc(e){try{window.localStorage.setItem(lw,JSON.stringify(e))}catch{}}function MT(){try{const e=window.localStorage.getItem(dw);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 fw(e){try{window.localStorage.setItem(dw,JSON.stringify(e))}catch{}}function WT(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 PT=120,$T="os-inline-loader",pw="os-inline-loader-keyframes";function UT(){return typeof customElements<"u"&&!!customElements.get("os-spinner")}function BT(){if(document.getElementById(pw))return;const e=document.createElement("style");e.id=pw,e.textContent="@keyframes os-inline-loader-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function FT(){if(UT()){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||(BT(),e.style.animation="os-inline-loader-spin 0.7s linear infinite"),e}function HT(e,t={}){const n=t.label??_("Loading…");let o=null,s=!1;const i=()=>{if(s||o||!e.isConnected)return;o=document.createElement("div"),o.className=$T,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(FT()),o.appendChild(l),e.appendChild(o)},r=t.immediate?null:window.setTimeout(i,PT);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=_("Retry"),u.className="button button-small",u.addEventListener("click",()=>{o?.remove(),o=null,s=!1,c()}),o.appendChild(u)}}}}function GT(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 zT=["clock"],zi=40,VT=12;class jT{constructor(t,n,o){this.override=null,this.mounted=new Map,this.generation=0,this.unwatchPointer=null,this.root=t,this.pluginUrl=n,this.enabledIds=RT(),this.geometry=xT(),this.dockedHeights=MT(),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),this.paintEmptyState(),this.watchPointerProximity()}visibleIds(){return this.override??this.enabledIds}hydrate(){uw()===null&&(this.enabledIds=zT.filter(t=>!!Un(t)),Uc(this.enabledIds));for(const t of this.visibleIds())this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){if(Un(t)){if(this.override){if(this.override.includes(t))return;this.override=[...this.override,t],this.mountById(t),this.paintEmptyState(),A(g.WIDGET_ADDED,{id:t});return}this.enabledIds.includes(t)||(this.enabledIds.push(t),Uc(this.enabledIds),this.mountById(t),this.paintEmptyState(),A(g.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(g.WIDGET_REMOVED,{id:t}),Ko();return}const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(Uc(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],Bc(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],fw(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),A(g.WIDGET_REMOVED,{id:t}),Ko())}getEnabledIds(){return[...this.enabledIds]}getMountedIds(){return Array.from(this.mounted.keys())}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),hT({anchor:this.addTile,registry:()=>Pc(),enabledIds:()=>[...this.enabledIds],onAdd:t=>{this.add(t),$c(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){Un(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 Un(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)||!Un(o)||this.mountById(o);this.paintEmptyState()}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t);this.unwatchPointer?.(),this.unwatchPointer=null}mountById(t){const n=Un(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=ST(n,{floatingParent:this.floatingHost,geometry:s,dockedHeight:this.dockedHeights[t]},{onRemove:()=>this.remove(t),onGeometryChanged:u=>this.persistGeometry(t,u),onDockedHeightChanged:u=>this.persistDockedHeight(t,u),onLiberate:u=>this.liberate(t,u),onRedock:()=>this.redock(t)}),r=!!s,a={id:t,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(t,a),this.placeCard(i.card,r);const l={id:t,pluginUrl:this.pluginUrl,storage:GT(t)};A(g.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(g.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(KT(d)){const u=HT(i.body,{label:_("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(g.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){A(g.SHELL_ERROR,{scope:"widget-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" teardown threw:`,o)}this.generation++,n.frame.dispose(),this.mounted.delete(t)}}handleMountFailure(t,n){const o=this.mounted.get(t);o&&(o.frame.dispose(),this.mounted.delete(t)),A(g.WIDGET_MOUNT_FAILED,{id:t,error:n}),A(g.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",_("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=_("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-zi&&c.clientX<=t.right+zi&&c.clientY>=t.top-zi&&c.clientY<=t.bottom+zi;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=ti(()=>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),Hi(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],Bc(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=iw(o,this.floatingHost);s.x===o.x&&s.y===o.y||(Hi(n.frame.card,s),this.persistGeometry(t,s))}}persistGeometry(t,n){this.geometry[t]=n,Bc(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)<t.width/2||(n=Math.max(n,r.bottom-t.top+this.root.scrollTop))}const o=t.height+this.root.scrollTop-this.addTile.offsetHeight,s=Math.max(0,Math.min(n+VT,o));this.addTile.style.top!==`${s}px`&&(this.addTile.style.top=`${s}px`)}persistDockedHeight(t,n){!Number.isFinite(n)||n<=0||(this.dockedHeights[t]=n,fw(this.dockedHeights))}paintEmptyState(){let t=0;for(const n of this.mounted.values())n.floating||t++;this.root.classList.toggle("os-widgets--has-widgets",t>0),this.positionAddTile()}}function KT(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const qT=280,YT=220,XT=520,ZT=400;function JT(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function QT(e,t,n){return o=>{const s=JT(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=HL(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 v=f.createElement("script");v.src=p,v.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(v)}}}catch{}XE(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!==""&&qE(s,p.channel,p.payload);try{e.onMessage?.(f.data)}catch(v){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",v)}};return window.addEventListener("message",u),t.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),c}}function eN(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=QT(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??XT,height:t.height??ZT,minWidth:t.minWidth??qT,minHeight:t.minHeight??YT,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let tN=0;function nN(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++tN}`,s=n.persistent===!0,i=[["opened",g.WINDOW_OPENED],["reopened",g.WINDOW_REOPENED],["focused",g.WINDOW_FOCUSED],["blurred",g.WINDOW_BLURRED],["closing",g.WINDOW_CLOSING],["closed",g.WINDOW_CLOSED],["minimized",g.WINDOW_MINIMIZED],["restored",g.WINDOW_RESTORED],["maximized",g.WINDOW_MAXIMIZED],["unmaximized",g.WINDOW_UNMAXIMIZED],["fullscreenEntered",g.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",g.WINDOW_FULLSCREEN_EXITED],["resized",g.WINDOW_RESIZED],["bodyResized",g.WINDOW_BODY_RESIZED],["boundsChanged",g.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const l=()=>{if(!a){a=!0;for(const c of r)ao(c,o)}};for(const[c,d]of i){const u=t[c];u&&(r.push(d),Z(d,o,f=>{const p=f;if(p.windowId!==e)return;const{windowId:v,...h}=p;u(h),c==="closed"&&!s&&l()}))}return l}function oN(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function sN(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&K_(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function hw(e,t){const n=t??{};return e.map(o=>{const s=o.scriptHandle?n[o.scriptHandle]:void 0,i=[];for(const a of o.companionScripts??[]){if(typeof a!="string"){i.push(a);continue}const l=n[a];l?.url&&i.push({scriptUrl:l.url,scriptHandle:a,scriptBefore:l.before,scriptAfter:l.after,scriptL10n:l.l10n,scriptTranslations:l.translations})}const r=(o.tabs??[]).map(a=>{if(typeof a.scriptUrl=="string")return a;const l=a.scriptHandle?n[a.scriptHandle]:void 0;return{...a,scriptUrl:l?.url??"",scriptBefore:l?.before,scriptAfter:l?.after,scriptL10n:l?.l10n,scriptTranslations:l?.translations}});return{...o,scriptUrl:o.scriptUrl??s?.url??"",scriptBefore:o.scriptBefore??s?.before,scriptAfter:o.scriptAfter??s?.after,scriptL10n:o.scriptL10n??s?.l10n,scriptTranslations:o.scriptTranslations??s?.translations,companionScripts:i,tabs:r}})}function iN(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=m=>{const k=di(m.id);return k?{width:Math.max(k.width,m.minWidth),height:Math.max(k.height,m.minHeight)}:{width:m.width,height:m.height}},u=m=>{if(i.has(m.templateId))return;if(document.getElementById(m.templateId)){i.add(m.templateId);return}if(!m.templateHtml)return;const k=document.createElement("template");k.id=m.templateId,k.innerHTML=m.templateHtml,document.body.appendChild(k),i.add(m.templateId)},f=m=>{const k=m.styleUrl;if(!k||l.has(k))return;const I=k.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${I}"]`)){const $=document.createElement("link");$.rel="stylesheet",$.href=k,m.styleHandle&&($.dataset.osStyleHandle=m.styleHandle),document.head.appendChild($)}if(Array.isArray(m.styleInline))for(const $ of m.styleInline){if(typeof $!="string"||$==="")continue;const x=document.createElement("style");m.styleHandle&&(x.dataset.osStyleHandle=m.styleHandle),x.textContent=$,document.head.appendChild(x)}l.add(k)},p=m=>{f(m)},v=m=>{for(const k of m.companionStyles??[])f(k)},h=new Set,w=(m,k)=>{if(h.has(m))return;h.add(m);const I=[k.scriptTranslations??"",...k.scriptL10n??[],...k.scriptBefore??[],...k.scriptAfter??[]];for(const D of I)typeof D=="string"&&D!==""&&Wp(D)},E=(m,k)=>{const I=k.scriptUrl,D=`${m}|${I}`;if(r.has(I))return w(D,k),Promise.resolve();const $=a.get(I);if($)return $.then(()=>w(D,k));h.add(D);const x=fe(I,{translations:k.scriptTranslations,l10n:k.scriptL10n,before:k.scriptBefore,after:k.scriptAfter}).catch(C=>{A(g.SHELL_ERROR,{scope:"native-window-script-load",id:m,error:C})}).then(()=>{r.add(I),a.delete(I)});return a.set(I,x),x},S=async m=>{v(m);for(const k of m.companionScripts??[])k.scriptUrl&&await E(m.id,k);m.scriptUrl&&await E(m.id,m)},O=async m=>{m.preloadScript&&await S(m)},M=new Set,b=(m,k)=>{if(!m||M.has(m)||r.has(m)||l.has(m))return;M.add(m);const I=document.createElement("link");I.rel="prefetch",I.as=k,I.href=m,document.head.appendChild(I)},W=()=>{const m=navigator.connection;if(!(m?.saveData||/2g$/.test(m?.effectiveType??""))){for(const k of c.values())if(!k.preloadScript){for(const I of k.companionScripts??[])b(I.scriptUrl,"script");b(k.scriptUrl,"script");for(const I of k.companionStyles??[])b(I.styleUrl,"style")}}};let U=!1;const j=()=>{if(U)return;U=!0;const m=()=>{U=!1,W()};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(m,{timeout:4e3}):window.setTimeout(m,1500)},B=m=>async(k,I)=>{k.appendChild(mw(m.templateId)),sN(k,m),await S(m);const D=oN()[m.id];return D?.(k,I)},V=(m,k)=>{const I=B(m),D=d(m);t.open({id:m.id,baseId:m.id,native:!0,url:`#${m.id}`,title:m.title,icon:m.icon,width:D.width,height:D.height,minWidth:m.minWidth,minHeight:m.minHeight,render:I,autofocus:m.autofocus,ownerHandle:m.ownerHandle||m.scriptHandle,...k?{params:k}:{}})},J=(m,k)=>{const I=B(m),D=d(m);t.openNew({id:m.id,baseId:m.id,native:!0,url:`#${m.id}`,title:m.title,icon:m.icon,width:D.width,height:D.height,minWidth:m.minWidth,minHeight:m.minHeight,initialState:"normal",render:I,autofocus:m.autofocus,ownerHandle:m.ownerHandle||m.scriptHandle,...k?{params:k}:{}})},K=async m=>{if(!s.has(m.id)){if(m.placement==="none"){u(m),p(m),await O(m),s.add(m.id);return}u(m),p(m),await O(m),n({id:m.id,title:m.title,icon:m.icon,windowId:m.id,navKind:m.navKind==="control"?"control":"app",defaultPlacement:"rail",order:m.dockOrder,placeable:m.placeable===!0,isOpen:()=>!!t.getById(m.id),onOpen:()=>V(m)}),A(g.DOCK_ITEM_APPENDED,{id:m.id}),s.add(m.id)}},T=m=>{s.has(m)&&(o(m),s.delete(m),c.delete(m))},R=async m=>{const k=new Set;for(const I of m)k.add(I.id),c.set(I.id,I);for(const I of Array.from(s))k.has(I)||T(I);for(const I of m)s.has(I.id)||await K(I);j()},Y=(m,k={})=>{const I=c.get(m);return I?(Ee.publish("os/open-requested",{windowId:m,source:k.source??"api"}),V(I,k.params),!0):!1},X=(m,k={})=>{const I=c.get(m);return I?(Ee.publish("os/open-requested",{windowId:m,source:k.source??"api"}),J(I,k.params),!0):!1};return Z(g.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",m=>{const k=m,I=k?.windowId,D=k?.width,$=k?.height;if(!I||typeof D!="number"||typeof $!="number")return;const x=t.getById(I);if(!x||x.state!=="normal")return;const C=x.config.baseId||x.id;Bf(C,{width:D,height:$}),x.element&&Ff(C,{x:x.element.offsetLeft,y:x.element.offsetTop})}),Z(g.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",m=>{const k=m?.windowId;if(!k)return;const I=t.getById(k);if(!I||I.state!=="normal"||!I.element)return;const D=I.config.baseId||I.id;Bf(D,{width:I.element.offsetWidth,height:I.element.offsetHeight}),Ff(D,{x:I.element.offsetLeft,y:I.element.offsetTop})}),Z(g.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",m=>{const k=m?.windowId;if(!k||Pt())return;const I=t.getById(k);if(!I)return;const D=I.config.baseId||I.id,$=c.get(D),x=$?{width:$.width,height:$.height}:{width:I.config.width,height:I.config.height};Hf(D,"maximized",x)}),Z(g.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",m=>{const k=m?.windowId;if(!k)return;const I=t.getById(k);if(!I)return;const D=I.config.baseId||I.id;Hf(D,null)}),{sync:R,openById:Y,openNewById:X,loadScriptById:async m=>{const k=c.get(m);return k?(await S(k),!0):!1},prewarmById:async m=>{const k=c.get(m);return!k||t.getById(m)?!1:(await S(k),window.wp?.os?.apps?.prewarm?.(m)===!0)}}}function mw(e){let t=null;if(typeof e=="string"){const n=document.getElementById(e);n instanceof HTMLTemplateElement&&(t=n)}else t=e;if(!t)throw new Error(`[openstation] cloneTemplate: no <template> found for ${typeof e=="string"?`#${e}`:"<reference>"}`);return t.content.cloneNode(!0)}function Vi(e){const t=window.wp?.os,n=window.openStationConfig,o=t?.config?.adminUrl??n?.adminUrl;if(!o)return null;const s=t?.getMenuItems?.()??n?.dockItems??[],i=de(e,o);return s.find(r=>de(r.url,o)===i||(r.submenu??[]).some(a=>de(a.url,o)===i))??null}const ww="data:image/svg+xml;base64,",ji=new Map;function rN(e){const t=ji.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(ww.length)).includes("currentColor")}catch{}return ji.size>=256&&ji.clear(),ji.set(e,n),n}function Gn(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const l=Ks(t.slot);l!==null&&(e=l),s=na(t.slot)}if(typeof e=="string"&&e.startsWith("dashicons-")){const l=document.createElement("span");return l.className=`dashicons ${e} ${n}`.trim(),l.setAttribute("aria-hidden","true"),s!==null&&(l.style.color=s),l}if(s!==null&&typeof e=="string"){const l=document.createElement("span");if(l.className=n,l.setAttribute("aria-hidden","true"),l.style.display="inline-block",Ei(l,e,s))return l}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const l=e.slice(ww.length);if(/^[A-Za-z0-9+/=]+$/.test(l)){const c=document.createElement("span");return c.className=n,c.setAttribute("aria-hidden","true"),c.style.display="inline-block",rN(e)&&Ei(c,e,"currentColor")||(c.style.backgroundImage=`url("${e}")`,c.style.backgroundRepeat="no-repeat",c.style.backgroundPosition="center",c.style.backgroundSize="contain"),c}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const l=e.indexOf(","),c=l>=0?e.slice(l+1):"";if(/^[A-Za-z0-9+/=]+$/.test(c))return gw(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return gw(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=aN(o);i.textContent=r;const a=Ga(o);return i.style.backgroundColor=`hsl( ${a}, 60%, 45% )`,i.style.color="#fff",i.style.display="inline-flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.fontWeight="600",i.style.borderRadius="4px",i}function gw(e,t){const n=document.createElement("img");return n.className=t,n.src=e,n.alt="",n.setAttribute("aria-hidden","true"),n.draggable=!1,n}function aN(e){const t=(e??"").trim();if(t==="")return"?";const n=t.split(/\s+/);if(n.length>=2)return(n[0][0]+n[1][0]).toUpperCase();const o=n[0];return o.length>=2?o.slice(0,2).toUpperCase():o.toUpperCase()}const yw="os-icon__badge",qo=new Map,Yo=new Map;function cN(e){return Math.max(0,Math.floor(Number(e)||0))}function vw(e,t){if(!e)return;const n=Sw(e);if(!n)return;const o=cN(t),s=qo.get(e)??0;o!==s&&(o===0?qo.delete(e):qo.set(e,o),kw(n,o),Ee.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),A(g.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function lN(e){vw(e,0)}function dN(e){return qo.get(e)??0}function uN(e,t){if(e){if(!t){Yo.delete(e);return}Yo.get(e)!==t&&(Yo.set(e,t),pN(e,t),Ee.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function bw(e){return Yo.get(e)??""}function fN(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function pN(e,t){const o=Sw(e)?.querySelector(".os-icon__image");if(o){const s=Gn(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${fN(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const Fc={setBadge:vw,clearBadge:lN,getBadge:dN,setArt:uN,getArt:bw};function hN(e){return!e||e.length===0?"":`${ta()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let Ew="";function _w(e,t,n){const o=hN(t);if(o===Ew&&e.querySelector(":scope > .os-icons"))return;Ew=o;const s=e.querySelector(":scope > .os-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="os-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",_("Desktop icons"));const r=[...t].sort((l,c)=>{const d=l.pinned?0:1,u=c.pinned?0:1;return d-u}),a=new Map;for(const l of r){const c=wN(l,n),d=qo.get(l.id)??0;d>0&&kw(c,d);const u=Yo.get(l.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(Gn(u,{className:"os-icon__image",title:""}))}i.appendChild(c),a.set(l.id,c)}e.appendChild(i),A(g.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(l=>l.id),container:i,tiles:a})}function Sw(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${mN(e)}"]`):null}function kw(e,t){const n=e.querySelector(`:scope > .${yw}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=re($t("%d notification","%d notifications",t),t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",s);return}const i=document.createElement("span");i.className=yw,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function mN(e){const t=window.CSS;return t?.escape?t.escape(e):e}function wN(e,t){const n=document.createElement("button");n.type="button",n.className=e.pinned?"os-icon os-icon--pinned":"os-icon",n.dataset.iconId=e.id,e.pinned&&(n.dataset.pinned="1"),n.setAttribute("role","listitem"),n.setAttribute("aria-label",e.title);const o=Gn(e.icon,{title:e.title,className:"os-icon__image",slot:qs(e.id)});n.appendChild(o);const s=document.createElement("span");return s.className="os-icon__label",s.textContent=e.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),A(g.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),gN(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),Up({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function gN(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(Co(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=Vi(n.toString());t.manager.open({id:o,baseId:o,url:n.toString(),parentUrl:s?.url??n.toString(),title:e.title,icon:e.icon,submenu:s?.submenu,selfLabel:s?.selfLabel,multi:!!s?.multi})}catch{}}}function yN(e){const t=[],n=new Map,o=s=>{t.push(s),n.set(s.id,s)};for(const s of e.menuItems)n.has(s.id)||o({id:s.id,kind:s.isCore?"core":"plugin",title:s.title,icon:s.icon,windowId:e.resolveMenuWindowId?.(s)||void 0,menu:s});for(const s of e.systemTiles){const i=n.get(s.item.id);if(i){i.tile=s.item;continue}const a=(s.item.submenu??[]).map(l=>l.windowId).filter(l=>!!l);o({id:s.item.id,kind:s.kind,title:s.item.title,icon:s.item.icon,locked:s.locked,defaultPlacement:s.item.defaultPlacement,windowId:s.item.windowId,answersFor:a.length>0?a:void 0,order:s.item.order,tile:s.item})}for(const s of e.icons){const i=s.window?n.get(s.id)??n.get(s.window):n.get(s.id);if(i){i.entry=s,s.window&&(i.windowId=s.window);continue}o({id:s.id,kind:"app",title:s.title,icon:s.icon,windowId:s.window||void 0,entry:s})}return t}const Iw="os-side-dock";function vN(e,t,n,o,s="bottom"){let i=t,r=s,a=n,l=o??[],c=null,d=null,u=null,f=null,p=null;const v=new Map;let h=[],w=Vp({items:[],config:{placement:{},order:[]},layout:i,openWindows:[]});const E=()=>e.getSettings?.()??{navPlacement:{},navOrder:[]},S=()=>{const C=e.windowManager.getActiveDesktopId(),H=[],P=new Set;for(const ce of e.windowManager.getAll()){if((ce.config.desktopId||C)!==C)continue;const z=ce.config.baseId||ce.id;P.has(z)||(P.add(z),H.push({id:z,title:ce.config.title||z,icon:ce.config.icon||"dashicons-admin-generic",fromAdminUrl:ce.config.native!==!0}))}return H},O=C=>C.windowId?C.windowId:fi(C.url)??de(C.url,e.adminUrl),M=()=>{const C=[];for(const P of v.values())C.push({item:P,kind:P.navKind??"app",locked:P.locked});h=yN({menuItems:a,systemTiles:C,icons:l,resolveMenuWindowId:O});const H=E();w=Vp({items:h,config:{placement:XS(H.navPlacement,h,e.getWorkspaceProfile?.()??null),order:H.navOrder},layout:i,openWindows:S()})},b=C=>C.tile?{type:"system",item:C.tile}:C.menu?{type:"menu",item:C.windowId?{...C.menu,windowId:C.windowId}:C.menu}:{type:"menu",item:{id:C.id,title:C.title,icon:C.icon,url:C.entry?.url||"",windowId:C.windowId,badge:0,submenu:[],isCore:!1}},W=C=>!!C.entry||!!C.windowId||!!C.menu?.url,U=(C,H)=>C.entry?C.entry:{id:C.id,title:C.title,icon:C.icon,window:C.windowId??"",url:C.menu?.url||"",position:2e3+H},j=C=>({core:(C.core??[]).map(b),apps:(C.apps??[]).map(b),controls:(C.controls??[]).map(b)}),B=(C,H,P)=>{if(!C)return;if(C.setZones){C.setZones(H),P.clear();for(const ee of at)for(const le of H[ee])le.type==="system"&&P.add(le.item.id);return}const ce=[],z=new Set;for(const ee of at)for(const le of H[ee])le.type==="menu"?ce.push(le.item):z.add(le.item.id);C.replaceItems(ce);for(const ee of Array.from(P))z.has(ee)||(C.removeSystemItem(ee),P.delete(ee));for(const ee of at)for(const le of H[ee])le.type==="system"&&!P.has(le.item.id)&&(C.appendSystemItem(le.item),P.add(le.item.id))},V=new Set,J=new Set,K=()=>{M(),B(c,j(w.dock),V),B(d,{core:w.sidebar.map(b),apps:[],controls:[]},J),e.renderIcons(w.desktop.filter(W).map(U))},T=()=>Array.from(w.ephemeral).sort().join(","),R=()=>{const C=document.getElementById(Iw);if(C)return C;const H=document.createElement("nav");return H.id=Iw,H.className="os-dock",H.setAttribute("role","toolbar"),H.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(H,e.shellBody.firstChild),H},Y=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},X=()=>{if(c){try{c.destroy()}catch(C){A(g.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:C})}c=null,u=null}if(d){try{d.destroy()}catch(C){A(g.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:C})}d=null,f=null}V.clear(),J.clear()},oe=C=>{const H=Fr();if(!H)return A(g.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return H.mount(C)}catch(P){if(A(g.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:H.id,error:P}),H===Va)return null;try{return Va.mount(C)}catch{return null}}},N=(C,H)=>({container:C,items:[],fullMenu:a.slice(),fullSystemTiles:h.filter(P=>!!P.tile).filter(P=>m(P.id)).map(P=>P.tile),orientation:H,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:P=>{const ce=de(P.url,e.adminUrl);e.windowManager.open({id:ce,baseId:ce,url:P.url,parentUrl:P.url,title:P.title,icon:P.icon.startsWith("dashicons-")?P.icon:"dashicons-admin-generic",submenu:P.submenu,selfLabel:P.selfLabel,multi:!!P.multi})},openSubmenuPick:(P,ce)=>{Co(ce.url)||e.windowManager.open({id:de(ce.url,e.adminUrl),baseId:de(P.url,e.adminUrl),url:ce.url,parentUrl:P.url,title:P.title,icon:P.icon.startsWith("dashicons-")?P.icon:"dashicons-admin-generic",submenu:P.submenu,selfLabel:P.selfLabel,multi:!!P.multi})},openSystemItem:P=>P.onOpen()}),m=C=>{for(const H of at)if(w.dock[H].some(P=>P.id===C))return!0;return w.sidebar.some(H=>H.id===C)},k=()=>i==="classic"?"bottom":r,I=()=>{X(),M(),i==="classic"?(p=R(),d=oe(N(p,"left")),f=Yp(d)):Y(),c=oe(N(e.bottomDockEl,k())),u=Yp(c),K()},D=()=>{document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:k(),primary:u,side:f}}))},$={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:C=>{C!==i&&(i=C,e.shellRoot.setAttribute("data-os-layout",C),I(),D())},getDockPlacement:()=>r,setDockPlacement:C=>{if(C===r)return;const H=k();r=C,k()!==H&&(I(),D())},applyDockItems:C=>{a=C,K()},applyDesktopIcons:C=>{l=C??[],K()},appendSystemTile:C=>{v.set(C.id,C),K()},removeSystemTile:C=>{v.delete(C)&&K()},listSystemTiles:()=>Array.from(v.values()).map(C=>({id:C.id,title:C.title,icon:C.icon,navKind:C.navKind??"app",placeable:C.placeable===!0,locked:C.locked===!0})),getSystemTile:C=>v.get(C)??null,getMenuItems:()=>a.slice(),getNavItems:()=>h.slice(),getNav:()=>w,refresh:K,destroy:()=>{X(),Y()}};for(const C of["os-window-opened","os-window-closed"])document.addEventListener(C,()=>{const H=T();M(),T()!==H&&K()});e.shellRoot.setAttribute("data-os-layout",i),I();let x=Fr()?.id??null;return eE(()=>{const C=Fr()?.id??null;C!==x&&(x=C,I(),D())}),$}const Aw="os-ai-loading",Cw="os-ai-loading-keyframes";let zn=null,Xo=null;function bN(){if(document.getElementById(Cw))return;const e=document.createElement("style");e.id=Cw,e.textContent="@keyframes os-ai-loading-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function EN(e){if(zn&&zn.isConnected)return;Xo=r=>{r.key==="Escape"&&(Ki(),e?.())},document.addEventListener("keydown",Xo);const t=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=document.createElement("div");n.id=Aw,n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.style.cssText=["position:fixed","inset:0","z-index:10000","display:flex","align-items:flex-start","justify-content:center","padding-top:clamp(60px,16vh,180px)","padding-inline:16px","pointer-events:none"].join(";");const o=document.createElement("div");o.style.cssText=["display:flex","align-items:center","gap:12px","width:100%","max-width:600px","box-sizing:border-box","padding:20px 22px","border-radius:16px","font-size:14px","font-family:inherit","background:var(--os-ai-panel-bg,var(--os-ui-surface,rgba(255,255,255,0.97)))","color:var(--os-ui-fg,#1d2327)","box-shadow:0 12px 40px rgba(0,0,0,0.22)"].join(";");const s=document.createElement("span");s.setAttribute("aria-hidden","true"),s.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(";"),t||(bN(),s.style.animation="os-ai-loading-spin 0.7s linear infinite");const i=document.createElement("span");i.textContent=_("Starting the command palette…"),o.appendChild(s),o.appendChild(i),n.appendChild(o),document.body.appendChild(n),zn=n}function Ki(){Xo&&(document.removeEventListener("keydown",Xo),Xo=null),zn&&(zn.remove(),zn=null),document.getElementById(Aw)?.remove()}function _N(e){return window.openStationCreateAiAssistant?Promise.resolve(window.openStationCreateAiAssistant):new Promise((t,n)=>{const o=document.querySelector('script[data-os-ai="1"]'),s=()=>{const r=window.openStationCreateAiAssistant;if(!r){n(new Error("[openstation] ai-assistant bundle loaded but did not register openStationCreateAiAssistant"));return}t(r)};if(o){window.openStationCreateAiAssistant?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osAi="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load ai-assistant bundle"))),document.head.appendChild(i)})}class SN{constructor(t,n){this._real=null,this._loadPromise=null,this._pendingAsk=null,this._intendOpen=!1,this.ask=(...o)=>this._ensure().then(s=>s.ask(...o)),this._config=t,this._scriptUrl=n}_ensure(){return uT().catch(t=>{console.warn("[openstation] command-palette runtime failed to load",t)}),this._loadPromise?this._loadPromise:(Ti("desktop-mode-ai-assistant"),this._loadPromise=_N(this._scriptUrl).then(t=>{const n=t(this._config);return this._pendingAsk&&n.attachAsk(this._pendingAsk),this._real=n,n}),this._loadPromise)}open(){this._intendOpen=!0,this._real||EN(()=>this.close()),this._ensure().then(t=>{Ki(),this._intendOpen&&t.open()}).catch(t=>{Ki(),console.warn("[openstation] command palette failed to load",t)})}close(){this._intendOpen=!1,Ki(),this._real&&this._real.close()}toggle(){this.isOpen?this.close():this.open()}get isOpen(){return this._real?this._real.isOpen:this._intendOpen}attachAsk(t){this._pendingAsk=t,this._real&&this._real.attachAsk(t)}}const Lw=e=>!e||typeof e!="object"?!1:e.name==="AbortError",kN=e=>{if(!e)return[];const t=yC();if(e===!0||e==="aiCallable")return t;if(Array.isArray(e)){const n=new Set(e.map(o=>o.toLowerCase()));return t.filter(o=>n.has(o.slug))}return typeof e=="function"?t.filter(n=>{try{return e(n.slug)===!0}catch{return!1}}):[]},IN=e=>e?typeof e=="string"?{text:e,mode:"append"}:typeof e=="object"&&typeof e.text=="string"&&e.text!==""?{text:e.text,mode:e.mode==="replace"?"replace":"append"}:null:null;function AN(e,t){const n=e??"";return n!==""?n:typeof t=="string"&&t!==""?t:t&&typeof t=="object"&&"message"in t&&typeof t.message=="string"?t.message:""}function CN(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function LN(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",l=r.restNonce??"";if(!a||!l)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await $e(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":l},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw Lw(c)?c:new Error(`[openstation] wp.os.ai.ask: network error — ${String(c?.message??c)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",l=vC(r);if(!l)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??e.fallbackContext();let d;try{d=await Promise.resolve(l.run(a,c))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:d}},o=async(s,i,r,a,l,c)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:CN(a)}};l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);let u;try{u=await t(d,c)}catch(v){if(Lw(v))throw v;return null}if(!u.ok)return null;const f=await u.json().catch(()=>({}));return(typeof f.message=="string"?f.message.trim():"")!==""?f.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[openstation] wp.os.ai.ask: empty query passed with non-default options — likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const l=kN(r.tools),c=IN(r.systemPrompt),d={query:a};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),l.length>0&&(d.command_tools=l),c&&(d.system_prompt_text=c.text,d.system_prompt_mode=c.mode);const u=await t(d,r.signal);if(!u.ok){const S=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[openstation] wp.os.ai.ask: HTTP ${u.status} — ${S.message??u.statusText}`)}const f=await u.json();if(f.answer_type!=="tool_call"||!f.tool)return{answer_type:f.answer_type,message:f.message??"",entity:f.entity??null,admin_links:f.admin_links??null,request_id:f.request_id,continue:f.continue??null};const p=await n(f,r);if(!p.ok)return p.response;const{slug:v,args:h,result:w}=p;let E=AN(f.message,w);if(r.followUp===!0){const S=await o(a,v,h,w,c,r.signal);S!==null&&(E=S)}return{answer_type:"tool_call",message:E,entity:null,admin_links:null,toolCall:{slug:v,args:h,result:w},request_id:f.request_id}}}const Tw="[os-bin badge]";function ct(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(Tw,...e)}catch{}}function qi(...e){console.warn(Tw,...e)}const Zo="desktop-mode-recycle-bin",TN="openstation_recycle_bin_seen_ts";function NN(){return window.wp?.os}const me=ie("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function Jo(e){const t=Math.max(0,Math.floor(e)),n=me.state.current;me.state.current=t,ct("setRecycleBinCount",{prev:n,next:t}),Hc(t)}function Nw(e){Jo(me.state.current+e)}function ON(){return me.state.current}function Hc(e){const t=e>0?me.state.fullArt:me.state.emptyArt;if(ct("paintIconState",{count:e,full:e>0,hasArt:!!t}),!t)return;const n=NN();n?.dock?.setArt?.(Zo,t),n?.taskbar?.setArt?.(Zo,t),n?.icons?.setArt?.(Zo,t)}function DN(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;me.state.emptyArt=String(o?.recycleBinIconEmpty??""),me.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;ct("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:me.state.started,cfgCount:s,cfgUrl:i,cfgDebug:r,readyState:document.readyState});const a=Number(s);if((typeof s=="number"||typeof s=="string")&&Number.isFinite(a)||qi("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),me.state.started){Jo(n);return}me.state.started=!0,me.state.countUrl=t,me.state.seenTs=Date.now(),Jo(n),RN(),xN(),MN(),WN(),PN()}function RN(){Z(g.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===Zo&&Hc(me.state.current)})}function xN(){Z(g.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(Zo)&&Hc(me.state.current)})}function MN(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":Nw(+r);break;case"untrashed":case"deleted":Nw(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])Pn(`os.${s}.changed`,e)}function WN(){const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;if(!n||n.type!=="os-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=me.state.seenTs){ct("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:me.state.seenTs});return}ct("postMessage triggers refetch",{ts:o,prevSeenTs:me.state.seenTs}),me.state.seenTs=o,$N()})}function PN(){const e=window.jQuery;if(!e){qi("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}ct("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[TN]=me.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;ct("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>me.state.seenTs&&(me.state.seenTs=o.ts),typeof o.count=="number"&&Jo(o.count))})}async function $N(){if(!me.state.countUrl){ct("refetchCount: no countUrl, skip");return}ct("refetchCount: hitting",me.state.countUrl);try{const e=await fetch(me.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){qi("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();ct("refetchCount: response",t),typeof t.count=="number"&&Jo(t.count)}catch(e){qi("refetchCount: fetch failed",e)}}const UN="desktop-mode-os-settings",BN="desktop-mode-recycle-bin";function FN(e){const t=zN();t&&t.addFilter("os.dock.peek-card-content","desktop-mode/built-in-peek-renderers",(n,o)=>{const s=o,i=s.window.id;return i===UN?HN():i===BN?GN(s,e.getRecycleBinCount):n})}function HN(e){const t=document.createElement("span");t.className="os-dock-peek__card-body os-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="os-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="os-dock-peek__os-subtitle",o.textContent=_("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="os-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`os-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function GN(e,t){const n=document.createElement("span");n.className="os-dock-peek__card-body os-dock-peek__card-body--recycle-bin",n.setAttribute("aria-hidden","true");const o=Math.max(0,Math.floor(t()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="os-dock-peek__bin-stage";const i=document.createElement("span");i.className="os-dock-peek__bin-stack";for(let l=0;l<3;l++){const c=document.createElement("span");c.className="os-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="os-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="os-dock-peek__bin-label",o===0?a.textContent=_("Trash — empty"):o===1?a.textContent=_("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function zN(){return window.wp?.hooks??null}const Qo="desktop-mode-bug-report",VN="WordPress",jN="openstation",Ow=6e3;function KN(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="os-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="os-bug-report__intro",n.textContent=_("Found a bug or have a feature idea? Fill this in and we will open a pre-filled GitHub issue for you to review and submit."),t.appendChild(n),t.appendChild(qN()),t.appendChild(YN("title",_("Title"),{placeholder:_("A short summary"),required:!0})),t.appendChild(Dw("description",_("What happened? What did you expect?"),{placeholder:_("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(Dw("steps",_("Steps to reproduce (bug only)"),{placeholder:_("One step per line"),rows:4}));const o=XN();t.appendChild(o);const s=document.createElement("div");s.className="os-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="os-bug-report__submit",i.textContent=_("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=_("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const l=JN(t);if(!l.title.trim()||!l.description.trim()){ZN(t,_("Title and description are both required."));return}const c=QN(l);window.open(c,"_blank","noopener")}),e.appendChild(t)}function qN(){const e=document.createElement("div");e.className="os-bug-report__field os-bug-report__field--type";const t=document.createElement("span");t.className="os-bug-report__label",t.textContent=_("Type"),e.appendChild(t);const n=document.createElement("div");n.className="os-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:_("Bug"),checked:!0},{value:"feature",label:_("Feature request")},{value:"question",label:_("Question")}];for(const s of o){const i=document.createElement("label");i.className="os-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const a=document.createElement("span");a.textContent=s.label,i.appendChild(a),n.appendChild(i)}return e.appendChild(n),e}function YN(e,t,n={}){const o=document.createElement("div");o.className="os-bug-report__field";const s=document.createElement("label");s.className="os-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("input");return i.type="text",i.name=e,i.className="os-bug-report__input",n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function Dw(e,t,n={}){const o=document.createElement("div");o.className="os-bug-report__field";const s=document.createElement("label");s.className="os-bug-report__label",s.textContent=t,o.appendChild(s);const i=document.createElement("textarea");return i.name=e,i.className="os-bug-report__textarea",i.rows=n.rows??4,n.placeholder&&(i.placeholder=n.placeholder),n.required&&i.setAttribute("aria-required","true"),s.appendChild(i),o}function XN(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=_("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=xw(Rw()),e.appendChild(n),e}function ZN(e,t){let n=e.querySelector(".os-bug-report__error");n||(n=document.createElement("div"),n.className="os-bug-report__error",n.setAttribute("role","alert"),e.prepend(n)),n.textContent=t}function JN(e){const t=new FormData(e);return{type:t.get("type")??"bug",title:t.get("title")??"",description:t.get("description")??"",steps:t.get("steps")??""}}function QN(e){const t=eO(e.type),n=tO(e),o=new URLSearchParams;return o.set("title",e.title.trim()),o.set("body",n),t.length&&o.set("labels",t.join(",")),`https://github.com/${VN}/${jN}/issues/new?${o.toString()}`}function eO(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function tO(e){const t=[];t.push(e.description.trim()),e.type==="bug"&&e.steps.trim()&&(t.push(""),t.push("## Steps to reproduce"),t.push(""),t.push(e.steps.trim())),t.push(""),t.push("<details><summary>Environment</summary>"),t.push(""),t.push("```"),t.push(xw(Rw())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(`
35 `);return n.length>Ow&&(n=n.slice(0,Ow)+`
36
37 …(truncated to fit GitHub URL length limit)`),n}function Rw(){const e=window.wp?.os?.config;return{pluginVersion:e?.pluginVersion??"unknown",wordpressVersion:e?.wordpressVersion??"unknown",userAgent:navigator.userAgent,viewport:`${window.innerWidth}x${window.innerHeight}`,platform:navigator.platform||"unknown",currentUrl:window.location.href}}function xw(e){return[`Plugin version: ${e.pluginVersion}`,`WordPress version: ${e.wordpressVersion}`,`User agent: ${e.userAgent}`,`Viewport: ${e.viewport}`,`Platform: ${e.platform}`,`Current URL: ${e.currentUrl}`].join(`
38 `)}const nO="os-pwa-install";function Mw(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Ww(){if(Mw())return!0;const e=window.navigator;if(typeof e.getInstalledRelatedApps!="function")return!1;try{const t=await e.getInstalledRelatedApps();return Array.isArray(t)&&t.length>0}catch{return!1}}let Nt=null;function oO(e,t){if(typeof window>"u")return;window.removeEventListener("beforeinstallprompt",n),window.addEventListener("beforeinstallprompt",n),window.removeEventListener("appinstalled",o),window.addEventListener("appinstalled",o);function n(s){s.preventDefault(),Nt=s}function o(){Nt=null,t({message:re(_("Installed %s as an app."),e)})}}function sO(e,t){return{id:nO,title:_("Install web app"),icon:"dashicons-download",onOpen:()=>{iO(e,t)}}}async function iO(e,t){if(Nt){const n=Nt;Nt=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:_("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await Ww()){t({message:re(_("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(BA()==="foreign-sw"){t({message:_("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the openstation_pwa_force_replace_sw filter to true.")});return}t({message:_("Install isn't available right now. Keep using the page; if it still doesn't appear, the app may already be installed in this browser.")})}async function rO(){if(!Nt)return"unavailable";const e=Nt;Nt=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function aO(){Promise.resolve().then(()=>lC).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function cO(e,t,n){if(!e.pwa)return;Wh(e.pwa),oO(e.pwa.appName||"WordPress",t);const o=n?()=>{t({message:_("A new version of OpenStation is available."),action:{label:_("Reload"),onClick:()=>{OA().then(()=>n())}},persistent:!0,dismissible:!0})}:void 0;PA(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw,onShellUpdated:o})}const Vn={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function lO(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function dO(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function uO(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function fO(e){const t=e;return t.kind!==void 0&&t.kind!==null?e:typeof t.id=="number"&&typeof t.url=="string"&&typeof t.mime=="string"?{kind:"attachment",id:t.id,url:t.url,title:typeof t.title=="string"?t.title:"",alt:typeof t.alt=="string"?t.alt:"",mime:t.mime,thumbnailUrl:typeof t.thumbnailUrl=="string"?t.thumbnailUrl:void 0,sizes:t.sizes&&typeof t.sizes=="object"?t.sizes:void 0}:e}class pO{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(lO(n)){this._startDrag(n.payload);return}if(dO(n)){this._endDrag();return}if(uO(n)&&this._payload&&t.source)try{t.source.postMessage({type:"os-drag-payload",payload:this._payload},this._origin)}catch{}},this._origin=window.location.origin,window.addEventListener("message",this._onMessage)}getPayload(){return this._payload}isDragging(){return this._payload!==null}start(t){this._payload!==t&&this._startDrag(t)}end(){this._endDrag()}_startDrag(t){const n=fO(t);this._payload=n,document.dispatchEvent(new CustomEvent(Vn.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(Vn.END,{detail:{payload:t}}))}}class hO{constructor(){this._targets=new Map,this._byElement=new Map}register(t){const n=this._targets.get(t.id);return n&&this._byElement.delete(n.element),this._targets.set(t.id,t),this._byElement.set(t.element,t),()=>{this._targets.get(t.id)===t&&(this._targets.delete(t.id),this._byElement.delete(t.element))}}list(){return Array.from(this._targets.values())}clear(){this._targets.clear(),this._byElement.clear()}hitTest(t){let n=t;for(;n;){if(n instanceof HTMLElement){const o=this._byElement.get(n);if(o)return o;if(n.classList.contains("os-window"))return null}n=n.parentElement}return null}hitTestPoint(t,n){const o=document.elementFromPoint(t,n);return{target:this.hitTest(o),element:o,accepted:!1}}}const mO="os-drag-ghost",Pw="os-drag-ghost--accept",$w="os-drag-ghost--reject",wO="os-drag-hint",Uw="os-drag-hint--accept",Bw="os-drag-hint--reject",Fw="os-drag-hint--neutral",gO=16,yO=18;function vO(e,t,n){const o=IO(e),s=e.ghost?.offsetX??AO(e.source),i=e.ghost?.offsetY??CO(e.source);o.classList.add(mO),o.setAttribute("aria-hidden","true"),o.style.position="fixed",o.style.left="0",o.style.top="0",o.style.margin="0",o.style.pointerEvents="none",o.style.zIndex="2147483647",o.style.willChange="transform",document.body.appendChild(o);const r=EO(e),a=r?bO():null;a&&document.body.appendChild(a);const l={get element(){return o},moveTo(c,d){o.style.transform=`translate3d(${c-s}px, ${d-i}px, 0)`,a&&(a.style.transform=`translate3d(${c+gO}px, ${d+yO}px, 0)`)},setMode(c,d){o.classList.remove(Pw,$w),c==="accept"?o.classList.add(Pw):c==="reject"&&o.classList.add($w),a&&r&&(a.classList.remove(Uw,Bw,Fw),c==="accept"?(a.classList.add(Uw),a.textContent=d?.acceptLabel??r.accept):c==="reject"?(a.classList.add(Bw),a.textContent=r.reject):(a.classList.add(Fw),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(c){const d=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return c()}finally{o.style.visibility=d,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return l.moveTo(t,n),l.setMode("neutral"),l}function bO(){const e=document.createElement("div");return e.className=wO,e.setAttribute("aria-hidden","true"),e.setAttribute("role","presentation"),e.style.position="fixed",e.style.left="0",e.style.top="0",e.style.margin="0",e.style.pointerEvents="none",e.style.zIndex="2147483647",e.style.willChange="transform",e}function EO(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??_O(e),reject:t?.reject??SO(),neutral:t?.neutral??kO(e)}}function _O(e){return e.type==="shortcut"?_("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?_("Drop here to move","desktop-mode"):_("Drop here","desktop-mode")}function SO(e){return _("Can’t drop here","desktop-mode")}function kO(e){return e.type==="shortcut"?_("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?_("Drop in a folder","desktop-mode"):""}function IO(e){if(e.ghost?.element)return e.ghost.element;const t=e.source.cloneNode(!0);t.removeAttribute("id");const n=e.source.getBoundingClientRect();return t.style.width=`${n.width}px`,t.style.height=`${n.height}px`,t}function AO(e){return e.offsetWidth/2}function CO(e){return e.offsetHeight/2}let Hw=!1;function LO(e){Hw||(Hw=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const Gw=4,ke={START:"os.drag.start",MOVE:"os.drag.move",ENTER:"os.drag.enter",LEAVE:"os.drag.leave",REJECTED:"os.drag.rejected",COMMIT:"os.drag.commit",CANCEL:"os.drag.cancel",END:"os.drag.end"},Yi="os-file-tile--dragging",zw="os-file-tile--drop-target",Vw="data-os-trash-drop-active",jw="data-files-drop-active",Kw="data-os-dragging",qw="data-os-drag-type",Gc="data-os-drag-mode";class TO{constructor(){this._registry=new hO,this._active=null,this._docListenersAttached=!1,this._lastLiftedEndAt=0,this._onPointerMove=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;const o=t.clientX-n._origin.clientX,s=t.clientY-n._origin.clientY;if(!n._lifted){if(Math.abs(o)<Gw&&Math.abs(s)<Gw)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),ht(ke.MOVE,{payload:n.payload,clientX:t.clientX,clientY:t.clientY}))},this._onPointerUp=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;if(!n._lifted){n._finished=!0,this._active=null;try{n._callbacks.onClickOnly?.()}catch(s){console.error("[openstation] drag onClickOnly threw:",s)}return}const o=this._hitTestNow(n,t.clientX,t.clientY);if(o&&o.accepted&&o.target){this._commit(n,o.target,t.clientX,t.clientY);return}this._cancel(n,o&&o.target?"rejected":"no-target")},this._onPointerCancel=t=>{const n=this._active;!n||n._pointerId!==t.pointerId||this._cancel(n,"pointercancel")}}start(t){if(this._active||t.origin.button!==0||Pt())return null;const n={payload:t.payload,isFinished:()=>n._finished,cancel:o=>this._cancel(n,o??"caller"),_origin:t.origin,_pointerId:t.origin.pointerId,_lifted:!1,_finished:!1,_callbacks:{onClickOnly:t.onClickOnly,onCancel:t.onCancel,onCommit:t.onCommit},_ghost:null,_currentTarget:null,_currentAccepted:!1};return this._active=n,this._ensureDocListeners(),LO(o=>{this._active&&this._cancel(this._active,o)}),n}registerDropTarget(t){return this._registry.register(t)}isDragging(){return this._active!==null&&this._active._lifted}recentlyEndedDrag(t=500){return this._lastLiftedEndAt===0?!1:Date.now()-this._lastLiftedEndAt<t}getActive(){return this._active}debug(){return{findOrphans:()=>Yw(),listTargets:()=>this._registry.list()}}_ensureDocListeners(){this._docListenersAttached||(this._docListenersAttached=!0,document.addEventListener("pointermove",this._onPointerMove,!0),document.addEventListener("pointerup",this._onPointerUp,!0),document.addEventListener("pointercancel",this._onPointerCancel,!0))}_lift(t,n){t._lifted=!0,t.payload.source.classList.add(Yi),t._ghost=vO(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(Kw,""),document.body.setAttribute(qw,String(t.payload.type)),document.body.setAttribute(Gc,"neutral")),ht(ke.START,{payload:t.payload})}_hitTestNow(t,n,o){const s=()=>{const i=document.elementFromPoint(n,o),r=this._registry.hitTest(i);if(!r)return{target:null,accepted:!1};let a=!1;try{a=r.accept(t.payload)}catch(l){console.error("[openstation] drop target accept() threw:",r.id,l)}return{target:r,accepted:a}};return t._ghost?t._ghost.withHidden(s):s()}_updateHover(t,n,o){const s=this._hitTestNow(t,n,o),i=t._currentTarget;if(s.target===i&&s.accepted===t._currentAccepted)return;i&&zc(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(NO(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),ht(ke.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Gc,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),zc(n,t),this._cleanupDom(t);const i=this._active;this._active=null;try{n.onDrop(t,{clientX:o,clientY:s})}catch(r){console.error("[openstation] drop target onDrop threw:",n.id,r)}try{t._callbacks.onCommit?.(n)}catch(r){console.error("[openstation] drag onCommit threw:",r)}ht(ke.COMMIT,{payload:t.payload,targetId:n.id}),ht(ke.END,{payload:t.payload,reason:"commit"}),this._active===i&&(this._active=null)}_cancel(t,n){if(!t._finished){t._finished=!0,t._lifted&&(this._lastLiftedEndAt=Date.now()),t._currentTarget&&zc(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}ht(ke.CANCEL,{payload:t.payload,reason:n}),ht(ke.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(Yi)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(Kw),document.body.removeAttribute(qw),document.body.removeAttribute(Gc)),OO()}}function ht(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function NO(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}ht(ke.ENTER,{payload:t.payload,targetId:e.id})}function zc(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}ht(ke.LEAVE,{payload:t.payload,targetId:e.id})}function Yw(){if(typeof document>"u")return[];const e=[];for(const t of[`.${Yi}`,`.${zw}`,`[${Vw}]`,`[${jw}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function OO(){for(const e of Yw())e.classList.remove(Yi,zw),e.removeAttribute(Vw),e.removeAttribute(jw)}const DO=".os-window",Xw="wp-window-";function Zw(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(DO);return o instanceof HTMLElement?o:null}function RO(e){if(!e.id.startsWith(Xw))return null;const t=e.id.slice(Xw.length);return t.length>0?t:null}const xO="desktop-mode-iframe-drop-",Xi="iframe.os-window__iframe",Vc="data-os-iframe-drop-active";let jc=!1,Jw=null;const ze=new Map,Jt=new Map;let mt=null,Qt=null;function MO(){document.querySelectorAll(Xi).forEach(t=>{ze.has(t)||(ze.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function WO(){ze.forEach((e,t)=>{t.style.pointerEvents=e}),ze.clear()}function Qw(e,t){const n=Zw(e,t);if(!n)return null;const o=n.querySelector(Xi);return o instanceof HTMLIFrameElement?o:null}const eg=e=>{if(!mt)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=Qw(e.clientX,e.clientY);t!==Qt&&(Qt&&en(Qt,{type:"os-drag-leave"}),Qt=t,t&&en(t,{type:"os-drag-over",payload:mt}))},tg=e=>{if(!mt)return;const t=Qw(e.clientX,e.clientY);if(!t){e.preventDefault(),Zi();return}e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const n=mt;Zi();const o=t.getBoundingClientRect();en(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},ng=()=>{Zi()};function PO(e){if(mt){mt=e;return}mt=e,MO(),document.addEventListener("dragover",eg,!0),document.addEventListener("drop",tg,!0),document.addEventListener("dragend",ng,!0)}function Zi(){mt&&(mt=null,Qt&&(en(Qt,{type:"os-drag-leave"}),Qt=null),document.removeEventListener("dragover",eg,!0),document.removeEventListener("drop",tg,!0),document.removeEventListener("dragend",ng,!0),WO())}function Ji(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function en(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function $O(e,t,n,o){return e.registerDropTarget({id:`${xO}${o}`,element:n,accept:s=>!!Ji(s),onEnter:s=>{const i=Ji(s.payload);i&&(n.setAttribute(Vc,""),en(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(Vc),en(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(Vc);const r=Ji(s.payload);if(!r)return;const a=t.getBoundingClientRect();en(t,{type:"os-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function og(e){let t=e.parentElement;for(;t;){if(t.id.startsWith("wp-window-"))return t.id.slice(10);t=t.parentElement}return`unknown-${Math.random().toString(36).slice(2,10)}`}function UO(e,t,n){try{if(!window.localStorage?.getItem("openStationDragDebug"))return}catch{return}console.info("[openstation] drag-start: suppressing %d iframe(s); bridgeable=%s",e,t,n)}function BO(e){const t=Jw;if(!t)return;const n=document.querySelectorAll(Xi),o=!!Ji(e);UO(n.length,o,e),n.forEach(s=>{if(ze.has(s)||(ze.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||Jt.has(s))return;const i=s.parentElement;if(!i)return;const r=og(s),a=$O(t,s,i,r);Jt.set(s,a)})}function FO(){ze.forEach((e,t)=>{t.style.pointerEvents=e}),ze.clear(),Jt.forEach(e=>{try{e()}catch{}}),Jt.clear()}function HO(e){jc||(jc=!0,Jw=e,document.addEventListener(ke.START,t=>{const n=t.detail;BO(n?.payload)}),document.addEventListener(ke.END,()=>{FO()}),document.addEventListener(Vn.START,t=>{const n=t.detail;n?.payload&&PO(n.payload)}),document.addEventListener(Vn.END,()=>{Zi()}),Z(g.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(ze))t.isConnected||ze.delete(t);for(const[t,n]of Array.from(Jt))if(!t.isConnected){try{n()}catch{}Jt.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:jc,iframesInDom:document.querySelectorAll(Xi).length,suppressedCount:ze.size,registeredCount:Jt.size,suppressedIframeIds:Array.from(ze.keys()).map(og)}))}const GO=250,zO=1e3,VO="os-drag-hover";let sg=!1,Kc=null,qc=null,es=null,ts=null,Yc=null;function ig(){es!==null&&(clearTimeout(es),es=null)}function rg(){ts!==null&&(clearTimeout(ts),ts=null)}function ns(){ig(),rg(),qc=null}function ag(){rg(),ts=setTimeout(()=>{ts=null,ns()},zO)}function jO(e,t){const n=Kc?.getById(e);if(!(!n||n.isFocused()||!q(g.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{Kc?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function cg(e,t){e!==qc&&(ig(),qc=e,e!==null&&(es=setTimeout(()=>{es=null,jO(e,t)},GO)))}function lg(e,t,n){const o=Zw(e,t);cg(o?RO(o):null,n)}const KO=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||lg(t.clientX,t.clientY,t.payload?.type??"")},qO=()=>{ns()};function YO(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;return typeof n.includes=="function"?n.includes("Files"):typeof n.contains=="function"&&n.contains("Files")}const XO=e=>{ag();const t=Yc??(YO(e)?"os-file":"external");lg(e.clientX,e.clientY,t)},dg=()=>{ns()},ZO=e=>{e.relatedTarget===null&&ns()};function JO(e){if(!e)return null;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e)return n.closest("[data-window-id]")?.getAttribute("data-window-id")||null;return null}const QO=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==VO)return;const n=JO(e.source);n&&(ag(),cg(n,typeof t.payloadType=="string"?t.payloadType:"external"))},eD=e=>{const t=e.detail;t?.payload&&(Yc=t.payload.kind??"")},tD=()=>{Yc=null,ns()};function nD(e){sg||(sg=!0,Kc=e,document.addEventListener(ke.MOVE,KO),document.addEventListener(ke.END,qO),document.addEventListener(Vn.START,eD),document.addEventListener(Vn.END,tD),document.addEventListener("dragover",XO,!0),document.addEventListener("drop",dg,!0),document.addEventListener("dragend",dg,!0),document.addEventListener("dragleave",ZO,!0),window.addEventListener("message",QO))}function ug(){const e=window.wp?.os;if(!e)return[];const t=e.windowManager,n=e.config;if(!t||!n)return[];const o=[],s=(r,a)=>({id:r.id,label:r.title,description:a,icon:r.icon,open:()=>t.open({id:r.id,baseId:r.id,url:r.url,title:r.title,icon:r.icon})});for(const r of n.dockItems??[])o.push(s(r,"Admin menu"));const i=q("os.open-command.items",o);return Array.isArray(i)?i:o}const oD={slug:"open",label:"Open",description:"Open an admin page or registered window.",hint:"[window]",icon:"dashicons-external",suggest(e){const t=e.trim().toLowerCase(),n=ug();return(t===""?n:n.filter(s=>s.label.toLowerCase().includes(t)||s.id.toLowerCase().includes(t))).slice(0,12).map(s=>({value:s.label,label:s.label,description:s.description,icon:s.icon??"dashicons-external"}))},run(e,t){const n=e.trim();if(!n)return"Type the name of a window to open, for example `/open Posts`.";const o=ug(),s=n.toLowerCase(),i=o.find(r=>r.label.toLowerCase()===s||r.id.toLowerCase()===s)??o.find(r=>r.label.toLowerCase().includes(s)||r.id.toLowerCase().includes(s));if(!i)return`No window matching **${n}** — try \`/open\` alone to see available options.`;i.open(),t.close()}};function sD(){Wn(oD)}const _e=[],iD=new Set;function fg(e){if(!e||typeof e.id!="string"||e.id==="")return()=>{};if(typeof e.open!="function"||typeof e.close!="function"||typeof e.isOpen!="function")return()=>{};const t=_e.findIndex(n=>n.id===e.id);return t>=0?_e[t]=e:_e.push(e),Xc(),()=>{const n=_e.findIndex(o=>o.id===e.id);n>=0&&(_e.splice(n,1),Xc())}}function rD(e){const t=_e.findIndex(n=>n.id===e);t>=0&&(_e.splice(t,1),Xc())}function aD(){return _e.slice()}function Xc(){for(const e of Array.from(iD))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",t)}}function os(e,t){try{document.dispatchEvent(new CustomEvent(t?"os-palette-opened":"os-palette-closed",{detail:{id:e}}))}catch{}}function pg(){if(_e.length===0)return;const e=_e.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{_e[0].open(),os(_e[0].id,!0)}catch{}return}try{_e[e].close(),os(_e[e].id,!1)}catch{}const t=e+1;if(t<_e.length)try{_e[t].open(),os(_e[t].id,!0)}catch{}}function Zc(e){const t=_e.find(n=>n.id===e);if(t){for(const n of _e)if(n.id!==e)try{n.isOpen()&&(n.close(),os(n.id,!1))}catch{}try{t.open(),os(t.id,!0)}catch{}}}let hg=!1;function cD(){if(hg)return;hg=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),pg())},!0);const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;n&&n.type==="os-palette-cycle"&&pg()})}const et=ie("os/presence",()=>({byUser:new Map,serverTimeMs:0})),lD=5*60*1e3;let mg=Date.now(),wg=!1;function Qi(){mg=Date.now()}function dD(e){if(!e||!e.snapshot)return;const t=et.state.byUser,n=new Map(t),o=[];for(const[s,i]of Object.entries(e.snapshot)){const r=Number(s);if(!Number.isFinite(r)||r<=0)continue;const l={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=t.get(r);n.set(r,l),(!c||c.status!==l.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:l.status,entry:l})}et.state.byUser=n,typeof e.serverTimeMs=="number"&&(et.state.serverTimeMs=e.serverTimeMs),et.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),Ee.publish("os/presence-changed",i)}Ee.publish("os/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function uD(){wg||(wg=!0,document.addEventListener("pointerdown",Qi,{capture:!0,passive:!0}),window.addEventListener("keydown",Qi,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||Qi()}),Oe.contribute("openstation_presence_active",()=>!0),Oe.contribute("openstation_user_active",()=>Date.now()-mg<lD),Oe.subscribe("openstation_presence",e=>{dD(e)}))}function fD(e){const t=et.state.byUser.get(e);return t?t.status:"offline"}function pD(){return new Map(et.state.byUser)}function hD(e){return et.state.byUser.get(e)??null}function mD(e){return et.subscribe(t=>e(t))}function wD(){Qi()}function gD(e){if(!Array.isArray(e)||e.length===0)return;const t=et.state.byUser,n=new Map(t),o=[];for(const s of e){const i=Number(s.userId);if(!Number.isFinite(i)||i<=0)continue;const r=t.get(i),a={status:s.status,lastSeenMs:typeof s.lastSeenMs=="number"?s.lastSeenMs:r?.lastSeenMs??0,lastActiveMs:typeof s.lastActiveMs=="number"?s.lastActiveMs:r?.lastActiveMs??0};n.set(i,a),(!r||r.status!==a.status)&&o.push({userId:i,oldStatus:r?r.status:null,newStatus:a.status,entry:a})}if(!(o.length===0&&n.size===t.size)){et.state.byUser=n,et.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),Ee.publish("os/presence-changed",i)}Ee.publish("os/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const yD=Object.freeze({getStatus:fD,getAll:pD,getEntry:hD,subscribe:mD,markActive:wD,applyBatch:gD});function gg(e){const t=new Set;let n=null;const o=new Set;e.onChange&&o.add(e.onChange);const s=()=>e.order().filter(a=>t.has(a)),i=()=>{const a=s();for(const l of o)try{l(a)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=a=>{const l=t.size,c=Array.from(t);a(),!(t.size===l&&c.every(d=>t.has(d)))&&i()};return{keys:s,has:a=>t.has(a),size:()=>t.size,anchor:()=>n,set(a){r(()=>{t.clear();for(const l of a)t.add(l)}),n=a.length>0?a[a.length-1]:null},add(a){r(()=>{t.add(a)}),n=a},remove(a){r(()=>{t.delete(a)}),n===a&&(n=null)},toggle(a){r(()=>{t.has(a)?t.delete(a):t.add(a)}),n=a},selectRange(a,l=!1){const c=e.order(),d=c.indexOf(a),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{l||t.clear(),t.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{l||t.clear();for(let v=f;v<=p;v+=1)t.add(c[v])})},selectAll(){const a=e.order();r(()=>{for(const l of a)t.add(l)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const a=new Set(e.order());let l=!1;return r(()=>{for(const c of Array.from(t))a.has(c)||(t.delete(c),l=!0)}),n!==null&&!a.has(n)&&(n=null),l},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const vD=".os-file-tile",bD="os-file-tile--selected",ED="os-selection-marquee",yg=4,vg=36,bg=12,Eg="data-os-marquee";function _D(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function SD(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(Eg,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(Eg)}}const kD=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note, .os-mobile-home, .os-mobile-edge",ID="os-area--overview";function AD(e,t){const n=t.itemSelector??vD,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??kD,r=()=>Array.from(e.querySelectorAll(n)).filter(m=>t.keyOf(m)!==null),a=()=>{const m=[],k=new Map;r().forEach((D,$)=>{const x=D.parentElement??e;let C=k.get(x);C||(C=[],k.set(x,C),m.push(x)),C.push({key:t.keyOf(D),top:parseFloat(D.style.top)||0,left:parseFloat(D.style.left)||0,index:$})});const I=[];for(const D of m){const $=k.get(D)??[];$.sort((x,C)=>x.top!==C.top?x.top-C.top:x.left!==C.left?x.left-C.left:x.index-C.index);for(const x of $)I.push(x.key)}return I},l=t.order??a,c=gg({order:l,onChange:m=>{p(),t.onChange?.(m),u(m)}}),d={},u=m=>{typeof document>"u"||(jn={surface:t.surface??"",scope:t.scope??"",keys:m.slice(),count:m.length},Qc=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:jn})))},f=m=>r().find(k=>t.keyOf(k)===m)??null,p=()=>{for(const m of r()){const k=t.keyOf(m),I=c.has(k);I!==m.hasAttribute("selected")&&(I?m.setAttribute("selected",""):m.removeAttribute("selected")),m.classList.toggle(bD,I),m.hasAttribute("selectable")||m.setAttribute("selectable","");const D=I?"true":"false";m.getAttribute("aria-selected")!==D&&m.setAttribute("aria-selected",D)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let v=null;const h=m=>{if(!(m.target instanceof Element))return;const k=m.target.closest(n);if(k&&e.contains(k)){const I=t.keyOf(k);if(I===null)return;if(v=I,m.stopPropagation(),m.shiftKey){c.selectRange(I,m.ctrlKey||m.metaKey);return}if(m.ctrlKey||m.metaKey){c.toggle(I);return}c.set([I]);return}if(M){M=!1;return}c.clear()};o.addEventListener("click",h);let w=null,E=null,S=null,O=[],M=!1,b=0,W=null,U=null;const j=m=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(m),U=m}catch{}},B=()=>{if(U===null||typeof o.releasePointerCapture!="function"){U=null;return}try{o.hasPointerCapture?.(U)&&o.releasePointerCapture(U)}catch{}U=null},V=(m,k)=>{const I=o.getBoundingClientRect();return{x:m-I.left+o.scrollLeft,y:k-I.top+o.scrollTop}},J=()=>{w?.remove(),w=null,E=null,S=null,W?.(),W=null,B(),b&&(cancelAnimationFrame(b),b=0),document.removeEventListener("pointermove",R),document.removeEventListener("pointerup",Y),document.removeEventListener("pointercancel",X),o.removeEventListener("lostpointercapture",X),o.removeEventListener("scroll",K),window.removeEventListener("blur",X)};function K(){if(!E||!S)return;const m=V(S.x,S.y),k=m.x-E.x,I=m.y-E.y;if(!w&&Math.abs(k)<yg&&Math.abs(I)<yg)return;w||(w=document.createElement("div"),w.className=ED,w.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(w),M=!0,W=SD(o),T());const D=Math.min(E.x,m.x),$=Math.min(E.y,m.y),x=Math.abs(k),C=Math.abs(I);w.style.left=`${D}px`,w.style.top=`${$}px`,w.style.width=`${x}px`,w.style.height=`${C}px`;const H=o.getBoundingClientRect(),P=H.left-o.scrollLeft,ce=H.top-o.scrollTop,z={left:D+P,top:$+ce,right:D+x+P,bottom:$+C+ce},ee=[];for(const le of r()){const ye=le.getBoundingClientRect();ye.left<z.right&&ye.right>z.left&&ye.top<z.bottom&&ye.bottom>z.top&&ee.push(t.keyOf(le))}c.set(Array.from(new Set([...O,...ee])))}function T(){if(b||typeof requestAnimationFrame!="function")return;const m=()=>{if(b=0,!w||!S)return;const k=o.getBoundingClientRect();if(_D(o)){let D=0;if(S.y<k.top+vg?D=-bg:S.y>k.bottom-vg&&(D=bg),D!==0){const $=o.scrollTop;o.scrollTop+=D,o.scrollTop!==$&&K()}}b=requestAnimationFrame(m)};b=requestAnimationFrame(m)}const R=m=>{E&&(S={x:m.clientX,y:m.clientY},K())},Y=()=>{w&&(Jc=Date.now()),J()},X=()=>{J()},oe=m=>{if(!s||m.button!==0||!(m.target instanceof Element)||o.classList.contains(ID)||m.target.closest(n))return;const k=m.target.closest(i);k&&k!==o&&o.contains(k)||(E=V(m.clientX,m.clientY),S={x:m.clientX,y:m.clientY},typeof m.pointerId=="number"&&j(m.pointerId),O=m.ctrlKey||m.metaKey||m.shiftKey?c.keys():[],O.length===0&&c.clear(),document.addEventListener("pointermove",R),document.addEventListener("pointerup",Y),document.addEventListener("pointercancel",X),o.addEventListener("lostpointercapture",X),window.addEventListener("blur",X),o.addEventListener("scroll",K,{passive:!0}))};o.addEventListener("pointerdown",oe);const N=m=>{if(m.key==="a"&&(m.ctrlKey||m.metaKey)){m.preventDefault(),c.selectAll();return}if(m.key==="Escape"){if(w||E){J();return}c.size()>0&&c.clear();return}const k=m.key==="ArrowRight"||m.key==="ArrowDown",I=m.key==="ArrowLeft"||m.key==="ArrowUp";if(!k&&!I)return;const D=k?1:-1,$=l();if($.length===0)return;const x=v??c.anchor(),C=x===null?-1:$.indexOf(x),H=Math.min($.length-1,Math.max(0,C<0?0:C+D));m.preventDefault();const P=$[H];v=P,m.shiftKey?c.selectRange(P):c.set([P]),f(P)?.focus()};return e.addEventListener("keydown",N),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){J(),o.removeEventListener("click",h),o.removeEventListener("pointerdown",oe),e.removeEventListener("keydown",N),Qc===d&&(jn=null,Qc=null)}}}let Jc=0;function CD(){return Jc>0&&Date.now()-Jc<500}let jn=null,Qc=null;function LD(){return jn?{...jn,keys:jn.keys.slice()}:null}function el(e){return typeof e.sort=="number"?e.sort:100}function TD(e,t){return re(_("%1$s (%2$d items)","desktop-mode"),e,t)}function _g(e,t){if(e.length===0)return[];const n=e.map(a=>{const l=t(a);return Array.isArray(l)?l:[]});if(e.length===1)return n[0];const o=e.length,s=[],i=a=>a.multiId??a.id;for(const a of n[0]){const l=i(a),c=[];let d=!1;for(const p of n){const v=p.find(h=>i(h)===l);if(!v||v.multi!==!0){d=!0;break}c.push(v)}if(d||s.some(p=>p.id===l))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):TD(u.label,o);s.push({id:l,label:f,icon:u.icon,disabled:c.some(p=>p.disabled===!0),danger:c.some(p=>p.danger===!0),sort:Math.min(...c.map(el)),multi:!0,onClick:async p=>{const v=new Map,h=[];c.forEach((w,E)=>{const S=w.bulk;if(typeof S!="function"){h.push(w);return}const O=v.get(S);O?O.push(e[E]):v.set(S,[e[E]])});for(const[w,E]of v)try{await w(E)}catch(S){console.error(`[openstation] selection action '${l}' failed for a batch:`,S)}for(const w of h)try{await w.onClick(p)}catch(E){console.error(`[openstation] selection action '${l}' failed for one item:`,E)}}})}s.sort((a,l)=>{const c=el(a),d=el(l);return c!==d?c-d:a.label.localeCompare(l.label)});const r=q("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function Sg(e,t){const n=s=>{if(!(s.target instanceof Node&&e.contains(s.target))){if(s.target instanceof Node)for(const i of t.siblingSelectors??[]){const r=Array.from(document.querySelectorAll(i));for(const a of r)if(a.contains(s.target))return}t.excludeOutsideTarget&&s.target instanceof Node&&t.excludeOutsideTarget.contains(s.target)||t.close()}},o=s=>{s.key==="Escape"&&t.close()};return document.addEventListener("mousedown",n,{capture:!0}),document.addEventListener("keydown",o),()=>{document.removeEventListener("mousedown",n,{capture:!0}),document.removeEventListener("keydown",o)}}const tl=8;function kg(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function nl(e){kg(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-tl)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-tl)}px`)})}function Ig(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,kg(e,o=>{o.right>window.innerWidth&&(e.style.left=`${Math.max(0,n.left-o.width)}px`),o.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-o.height-tl)}px`)})}const ND="os-wallpaper-menu";let Kn=null,ol=null,Ag=0;function sl(){if(!Kn)return;const e=Kn.dataset.menuScope??"selection",t=ol;Kn.dispatchEvent(new CustomEvent("tile-menu-closed")),Kn.remove(),Kn=null,ol=null,t?.(),A(`os.${e}.menu.closed`,{})}function OD(e,t){sl();const n=++Ag;$s(()=>n===Ag,()=>DD(e,t))}function DD(e,{actions:t,dataset:n,className:o,scope:s="selection",onOpened:i,onClosed:r}){if(t.length===0)return;const a=document.createElement("os-context-menu");a.setAttribute("open",""),a.classList.add(ND),o&&a.classList.add(o),a.dataset.menuScope=s;for(const[u,f]of Object.entries(n??{}))a.dataset[u]=f;a.style.left=`${e.x}px`,a.style.top=`${e.y}px`;const l=new Map;for(const u of t){l.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.danger&&f.setAttribute("danger",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",RD(u.icon)),f.textContent=u.label,a.appendChild(f)}a.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=l.get(f.id);p&&(sl(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(v=>{console.error(`[openstation] menu action '${p.id}' threw:`,v)}))}),document.body.appendChild(a),Kn=a,ol=r??null,nl(a);const c=Sg(a,{close:()=>sl()});a.addEventListener("tile-menu-closed",c);const d=t.map(u=>u.id);i?.(d),A(`os.${s}.menu.opened`,{items:d,count:t.length})}function RD(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const xD={active:LD,resolveCommonActions:_g,createModel:gg};let ss=null;function MD(){Oe.contribute("openstation_content_changes_seen_ts",()=>ss===null?0:ss),Oe.subscribe("openstation_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=ss===null,n=ss??0;let o=Math.max(n,e.ts);if(!t&&Array.isArray(e.entries))for(const s of e.entries)!s||typeof s.ts!="number"||s.ts<=n||typeof s.type!="string"||s.type===""||(Wi(`os.${s.type}.changed`,{source:"heartbeat",action:typeof s.action=="string"&&s.action!==""?s.action:"updated",ids:Array.isArray(s.ids)?s.ids.map(Number).filter(i=>i>0):[]}),s.ts>o&&(o=s.ts));ss=o})}const WD="desktop_mode_nonces",il=new Map;let Cg=!1;function rl(e,t){if(typeof e!="string"||e==="")return()=>{};let n=il.get(e);return n||(n=new Set,il.set(e,n)),n.add(t),()=>{n.delete(t)}}function PD(){Cg||(Cg=!0,Oe.subscribe(WD,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=il.get(t);if(o)for(const s of o)try{s(n)}catch(i){console.error(`[desktop-mode/nonce-refresh] updater for "${t}" threw:`,i)}}}),$D())}function $D(){rl("wp_rest",UD),rl("desktop-mode-plugins",e=>{Lg("desktop-mode-plugins","ajaxNonce",e)}),rl("updates",e=>{Lg("desktop-mode-plugins","updatesNonce",e)})}function UD(e){const t=BD();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=Tg();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Lg(e,t,n){const s=Tg()?.[e];if(!s||typeof s!="object")return;const i=s,r=i.extra;let a=!1;r&&typeof r=="object"&&t in r&&(r[t]=n,a=!0),(t in i||!a)&&(i[t]=n)}function BD(){if(!(typeof window>"u"))return window.openStationConfig}function Tg(){if(!(typeof window>"u"))return window.openStationWindowConfig}const FD="desktop_mode_auth",HD=5e3,Ng=1e3,GD=1e4;let Og=!1,er=!1,al=!1,tr=0,Dg=0,is=0,qn=null,Rg=0,xg=null,Mg=null,Wg=()=>{try{window.location.reload()}catch{}};function cl(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function ll(e=Ng){const t=Date.now();if(t<is){qn===null&&(qn=window.setTimeout(()=>{qn=null,is=Date.now()+Ng,cl()},is-t));return}is=t+e,cl()}function zD(){er=!0,!al&&(al=!0,A(g.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function VD(){for(const e of jD())try{e.contentWindow?.location.reload()}catch{}}function jD(){let e;try{e=document.querySelectorAll("iframe")}catch{return[]}return Array.from(e).filter(t=>t.id!=="wp-auth-check-frame"&&!t.closest("#wp-auth-check-wrap"))}function dl(){const e=Date.now();e-Rg<GD||(Rg=e,er=!1,al=!1,qn!==null&&(window.clearTimeout(qn),qn=null),is=0,ll(),VD(),A(g.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function KD(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(tr<=0){tr=t;return}t!==tr&&Wg()}}function qD(e,t){if(e!==401&&e!==403)return;let n;try{n=new URL(String(t||""),window.location.href)}catch{return}if(n.origin!==window.location.origin||n.pathname.indexOf("/wp-admin/admin-ajax.php")!==-1&&/(?:^|&|\?)action=heartbeat(?:&|$)/.test(n.search)||n.pathname.indexOf("/wp-login.php")!==-1)return;const o=Date.now();o<Dg||(Dg=o+HD,cl())}function YD(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");Mg=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&ll(),t=n}),Mg.observe(e,{attributes:!0,attributeFilter:["class"]})}function XD(e={}){Og||(Og=!0,tr=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(Wg=e.reloadShell),Oe.subscribe("wp-auth-check",t=>{if(t===!1){zD();return}t===!0&&er&&dl()}),Oe.subscribe("nonces_expired",()=>{if(er){dl();return}ll()}),Oe.subscribe(FD,KD),xg=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&dl()},window.addEventListener("message",xg),YD())}const Yn=12;function ul(e,t){return Pg(de(e,t.adminUrl),t)}function Pg(e,t){if(e)return(t.dockItems||[]).find(n=>de(n.url,t.adminUrl)===e||(n.submenu||[]).some(o=>de(o.url,t.adminUrl)===e))}function $g(e,t){const n=t.x??0,o=t.y??0,s=Math.max(200,t.width-Yn*2),i=Math.max(200,t.height-Yn*2),r=Math.min(e.width,s),a=Math.min(e.height,i),l=n+Math.max(0,t.width-r-Yn),c=o+Math.max(0,t.height-a-Yn),d=Math.max(n+Yn,Math.min(e.x,l)),u=Math.max(o+Yn,Math.min(e.y,c));return{x:d,y:u,width:r,height:a}}const Ug=window.location.origin;function ZD(e,t){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let l;try{l=new URL(a,window.location.href)}catch(w){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",a,w);return}if(l.origin!==Ug)return;let c;try{c=new URL(t.adminUrl).pathname}catch(w){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,w),c="/wp-admin/"}if(!l.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(l.pathname)||l.searchParams.has("action")&&l.searchParams.get("action")==="logout"||l.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Ze(l.href)))return;const d=de(l.href,t.adminUrl),u=ul(l.href,t),f=(i.dataset.osWindowTitle||"").trim(),p=(i.textContent||"").trim()||u?.title||"",v=!!i.closest("#wp-admin-bar-new-content"),h={id:d,baseId:d,multi:!!u?.multi||v,url:l.href,parentUrl:u?.url??l.href,title:f||u?.title||p,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu,selfLabel:u?.selfLabel};if(v){e.openNew(h);return}e.open(h)},!0)}function JD(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.total!="number"||!Number.isFinite(t.total)?null:{total:Math.max(0,Math.floor(t.total)),formatted:typeof t.formatted=="string"&&t.formatted!==""?t.formatted:String(t.total),text:typeof t.text=="string"?t.text:"",url:typeof t.url=="string"?t.url:""}}function QD(e){if(!e.url)return null;const t=document.createElement("li");t.id="wp-admin-bar-updates";const n=document.createElement("a");n.className="ab-item",n.href=e.url;const o=document.createElement("span");o.className="ab-icon",o.setAttribute("aria-hidden","true");const s=document.createElement("span");s.className="ab-label",s.setAttribute("aria-hidden","true");const i=document.createElement("span");return i.className="screen-reader-text updates-available-text",n.append(o,s,i),t.appendChild(n),t}function eR(e){const t=JD(e);if(!t)return;let n=document.getElementById("wp-admin-bar-updates");if(t.total<=0){n&&(n.style.display="none");return}if(!n){const i=document.getElementById("wp-admin-bar-root-default");if(!i||(n=QD(t),!n))return;const r=document.getElementById("wp-admin-bar-comments");r&&r.parentNode===i?i.insertBefore(n,r):i.appendChild(n)}n.style.display="";const o=n.querySelector(".ab-label");o&&(o.textContent=t.formatted);const s=n.querySelector(".updates-available-text");s&&(s.textContent=t.text)}const tR="os-registry-changed";function nR(e,t){const n=new Set;if(Array.isArray(e))for(const r of e)r&&typeof r.id=="string"&&n.add(r.id);const o=new Set;for(const r of t)r&&typeof r.id=="string"&&o.add(r.id);const s=[];for(const r of o)n.has(r)||s.push(r);const i=[];for(const r of n)o.has(r)||i.push(r);return{added:s,removed:i}}function fl(e,t,n){const{added:o,removed:s}=nR(t,n);if(o.length===0&&s.length===0||typeof document>"u")return;const i={registry:e,added:o,removed:s};document.dispatchEvent(new CustomEvent(tR,{detail:i}))}function oR(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:l,syncServerWindowActions:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:v,renderIcons:h,applyDesktopIcons:w,refreshRootPlacements:E,syncShortcuts:S}=e,O=M=>(M??[]).map(b=>String(b?.id??"")).sort().join(`
39 `);return function(b){const W=b.dockItems,U=b.nativeWindows,j=b.serverWidgets,B=b.serverWallpapers,V=b.serverCommandScripts,J=b.serverCommands,K=b.serverSettingsTabScripts,T=b.serverSettingsTabs,R=b.serverDockRailRendererScripts,Y=b.serverTitleBarButtonScripts,X=b.serverWindowActionScripts,oe=b.serverUnfocusEffectScripts,N=b.serverWindowLinkRendererScripts,m=b.serverWindowNotices,k=b.serverGames,I=b.serverDesktopThemes,D=b.desktopIcons;if(!Array.isArray(W)||W.length===0)return;const $=n.dockItems;if(t(W),n.dockItems=W,fl("dock-items",$,W),S?.(),Array.isArray(U)){const x=n.nativeWindows;o(hw(U,b.nativeWindowScriptData)),n.nativeWindows=U,b.nativeWindowScriptData&&(n.nativeWindowScriptData=b.nativeWindowScriptData),fl("native-windows",x,U)}if(Array.isArray(j)&&(s(j),n.serverWidgets=j),Array.isArray(B)&&(i(B),n.serverWallpapers=B),Array.isArray(k)&&(p(k),n.serverGames=k),Array.isArray(I)&&(v?.(I),n.serverDesktopThemes=I),Array.isArray(V)&&(r(V,Array.isArray(J)?J:void 0),n.serverCommandScripts=V,Array.isArray(J)&&(n.serverCommands=J)),Array.isArray(K)&&(a(K,Array.isArray(T)?T:void 0),n.serverSettingsTabScripts=K,Array.isArray(T)&&(n.serverSettingsTabs=T)),Array.isArray(Y)&&(l(Y),n.serverTitleBarButtonScripts=Y),Array.isArray(X)&&(c(X),n.serverWindowActionScripts=X),Array.isArray(oe)&&(d(oe),n.serverUnfocusEffectScripts=oe),Array.isArray(N)&&(u(N),n.serverWindowLinkRendererScripts=N),Array.isArray(R)&&(f(R),n.serverDockRailRendererScripts=R),Array.isArray(m)&&(Gm(m),n.serverWindowNotices=m),Array.isArray(D)){const x=n.desktopIcons;h(D),w?.(D),S?.(),O(x)!==O(D)&&E?.(),n.desktopIcons=D,fl("desktop-icons",x,D)}eR(b.updateCounts)}}const sR=8e3,iR=600;function rR(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:v,syncServerDesktopThemes:h,renderIcons:w,refreshRootPlacements:E,syncShortcuts:S}=e,O=oR({applyDockItems:K=>t?.applyDockItems(K),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:v,syncServerDesktopThemes:h,renderIcons:w,applyDesktopIcons:K=>t?.applyDesktopIcons(K),refreshRootPlacements:E,syncShortcuts:S});let M=typeof o.menuSig=="string"?o.menuSig:"",b=!1,W=null,U=!1,j=!1;const B=()=>{if(!o.adminUrl)return Promise.resolve();const K=(()=>{try{const T=new URL("admin.php",o.adminUrl);return T.searchParams.set("openstation_chromeless","1"),T.searchParams.set("openstation_menu_refresh","1"),T.toString()}catch{return null}})();return K?new Promise(T=>{const R=document.createElement("iframe");R.setAttribute("aria-hidden","true"),R.tabIndex=-1,R.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",R.src=K;let Y=!1;const X=()=>{Y||(Y=!0,window.clearTimeout(N),window.removeEventListener("message",oe),R.parentNode&&R.parentNode.removeChild(R),T())},oe=m=>{if(m.source!==R.contentWindow)return;const k=m.data;!k||k.type!=="os-plugins-changed"||X()},N=window.setTimeout(()=>{A(g.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),X()},sR);window.addEventListener("message",oe),document.body.appendChild(R)}):Promise.resolve()},V=()=>{if(U){j=!0;return}U=!0,B().finally(()=>{U=!1,j&&(j=!1,V())})},J=()=>{W!==null&&window.clearTimeout(W),W=window.setTimeout(()=>{W=null,V()},iR)};return window.addEventListener("message",K=>{if(K.origin!==Ug)return;const T=K.data;if(T){if(T.type==="os-plugins-changed"){T.payload&&(O(T.payload),typeof T.payload.menuSig=="string"&&(M=T.payload.menuSig));return}if(T.type==="os-updates-changed"){J();return}if(T.type==="os-menu-signature"){const R=T.sig;typeof R=="string"&&R!==""&&R!==M&&!b&&(b=!0,B().finally(()=>{b=!1}))}}}),B}function Bg(e,t){const n=$g(e,t);return{x:n.x,y:n.y,width:n.width,height:n.height,initialState:e.state}}function aR(e){if(!e)return!1;if(Array.isArray(e.windows)&&e.windows.length>0)return!0;if(typeof e.updated!="number"||e.updated<=0||!Array.isArray(e.desktops)||e.desktops.length===0)return!1;if(e.desktops.length>1)return!0;const t=e.desktops[0];return t?.id&&t.id!=="desktop-1"?!0:!!e.activeDesktop&&e.activeDesktop!=="desktop-1"}function cR(e,t,n=5e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=l=>{window.clearTimeout(a),document.removeEventListener("os-window-opened",r),s(l)},r=l=>{l.detail?.windowId===t&&i(e.getById(t)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function lR(e,t,n,o){const s=he(n);Array.isArray(t.session.desktops)&&t.session.desktops.length>0&&e.seedDesktops(t.session.desktops,t.session.activeDesktop||t.session.desktops[0].id);const i={};for(const r of t.session.windows)r.native&&(i[r.id]={desktopId:r.desktopId,...r.unplaced?{}:Bg(r,s),...r.params?{params:r.params}:{},...r.gridSpan?{gridSpan:r.gridSpan}:{}});Object.keys(i).length>0&&e.seedWindowRestoreState(i);for(const r of t.session.windows){if(r.native){if(!o?.(r.id))continue;await cR(e,r.id);continue}if(lo(r.url,t.adminUrl))continue;const a=ul(r.url,t)??Pg(r.baseId||r.id,t),l=await e.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!a?.multi,url:r.url,parentUrl:a?.url??r.url,title:r.title,icon:r.icon||"dashicons-admin-generic",...r.unplaced?{}:Bg(r,s),submenu:a?.submenu,selfLabel:a?.selfLabel,...r.gridSpan?{gridSpan:r.gridSpan}:{}});if(Array.isArray(r.externalTabs))for(const c of r.externalTabs)c&&typeof c.url=="string"&&c.url!==""&&l.addExternalTab(c.url,typeof c.label=="string"&&c.label!==""?c.label:c.url)}if(t.session.focused){const r=e.getById(t.session.focused);r&&e.focus(r)}}async function dR(e,t){if(lo(t.currentPage,t.adminUrl)||Ze(t.currentPage))return;const n=de(t.currentPage,t.adminUrl),o=ul(t.currentPage,t);await e.open({id:n,baseId:n,multi:!!o?.multi,url:t.currentPage,parentUrl:o?.url??t.currentPage,title:t.currentTitle||o?.title||"",icon:t.currentIcon,submenu:o?.submenu,selfLabel:o?.selfLabel})}function uR(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function pl(e,t,n,o){const s=Pd(t,n),i=window.fetch(t,s);if(i.then(a=>{if(a.status===401||a.status===403){let l;typeof t=="string"?l=t:t instanceof URL?l=t.href:l=t.url,qD(a.status,l)}},()=>{}),o?.silent)return i;let r=o?.window;return!r&&o?.windowId&&(r=e.getById(o.windowId)??null),r||(r=e.getFocused()),r&&typeof r.trackActivity=="function"&&r.trackActivity(i.then(a=>{if(!a.ok)throw new Error(fR(a));return a})).catch(()=>{}),i}function fR(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return re(_("Request failed (HTTP %s)."),t)}const pR="os-remember-session";function hR(e){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!navigator.serviceWorker.controller)return;const t=[];for(const n of e)try{const o=new URL(n,window.location.href);o.origin===window.location.origin&&t.push(o.toString())}catch{}try{navigator.serviceWorker.controller.postMessage({type:pR,urls:t})}catch{}}const mR=500,wR=1500;function Fg(e){const{updated:t,...n}=e;return JSON.stringify(n)}function Hg(e){try{if(!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled)return;hR(e.windows.filter(n=>!n.native&&n.url).map(n=>J_(n.url)||"").filter(Boolean))}catch{}}function gR(e,t){let n=null,o=!1,s=!1,i=null,r=0,a=null;const l=()=>{if(o)return s=!0,Promise.resolve();const f=e.snapshot(),p=Fg(f);return p===a?Promise.resolve():(o=!0,r=Date.now(),Hg(f),i=(async()=>{try{(await pl(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:f}),keepalive:!0},{silent:!0}))?.ok&&(a=p)}catch(v){A(g.SHELL_ERROR,{scope:"session-save",error:v})}finally{o=!1,i=null,s&&(s=!1,u())}})(),i)},c=async()=>{for(n!==null&&(clearTimeout(n),n=null);i;)await i;s=!1,await l()},d=()=>{n!==null&&(clearTimeout(n),n=null),s=!1;const f=e.snapshot(),p=Fg(f);if(p===a)return;Hg(f);const v=new Blob([JSON.stringify({session:f})],{type:"application/json"}),h=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);if(navigator.sendBeacon&&navigator.sendBeacon(h,v)){a=p;return}l()},u=()=>{n!==null&&clearTimeout(n);let f=mR;if(r!==0){const p=Date.now()-r;f=Math.max(f,wR-p)}n=window.setTimeout(()=>{n=null,l()},f)};return window.addEventListener("pagehide",d),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&d()}),Object.assign(u,{flush:c})}const yR=120;function vR(e){document.addEventListener("os-window-opened",e),document.addEventListener("os-window-closed",e),document.addEventListener("os-window-focused",e),document.addEventListener("os-window-changed",e),Z(g.DESKTOP_CREATED,"desktop-mode/session-save",e),Z(g.DESKTOP_CLOSED,"desktop-mode/session-save",e),Z(g.DESKTOP_SWITCHED,"desktop-mode/session-save",e),Z(g.DESKTOP_RENAMED,"desktop-mode/session-save",e),Z(g.WORKSPACE_UPDATED,"desktop-mode/session-save",e),Z(g.WORKSPACE_PROVISIONED,"desktop-mode/session-save",e)}function bR(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;A(g.SHELL_RESIZED,{width:o?Math.round(o.width):window.innerWidth,height:o?Math.round(o.height):window.innerHeight})};window.addEventListener("resize",()=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(n,yR)}),document.addEventListener("visibilitychange",()=>{A(g.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function ER(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return q(g.DOCK_TILE_CLASS,e,o)}function _R(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return q(g.DOCK_TILE_ELEMENT,e,o)}function SR(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return q(g.DOCK_TILE_TOOLTIP,e,o)}function kR(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};A(g.DOCK_TILE_RENDERED,{...o,el:e})}const IR=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),hl=new Set;function AR(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(IR))return!0;for(const n of hl)if(t.closest(n))return!0;return!1}function CR(e){return typeof e!="string"||e.trim()===""?()=>{}:(hl.add(e),()=>{hl.delete(e)})}const wt=new Map,LR=window.location.origin;function Gg(e){let t=wt.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},wt.set(e,t)),TR(e,t),t}function TR(e,t){const n=ml(e);if(!n||t.loadHandlerTarget===n&&t.loadHandler||(t.loadHandlerTarget&&t.loadHandler&&typeof t.loadHandlerTarget.removeEventListener=="function"&&t.loadHandlerTarget.removeEventListener("load",t.loadHandler),typeof n.addEventListener!="function"))return;const o=()=>{queueMicrotask(()=>Xn(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function NR(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function ml(e){const t=window.wp?.os?.windowManager;if(t&&typeof t.getById=="function"){const o=t.getById(e);if(o?.iframe)return o.iframe;if(o?.element){const s=o.element.querySelector("iframe");if(s)return s}}return document.getElementById(`wp-window-${e}`)?.querySelector("iframe")??null}function OR(e){const t={};for(const[n,o]of e.headers){const s=[];for(const i of o){let r;try{r=typeof i.value=="function"?i.value():i.value}catch{continue}typeof r=="string"&&r!==""&&s.push(r)}s.length>0&&(t[n]=s.join(", "))}return t}function Xn(e){const t=ml(e);if(!t||!t.contentWindow)return;const n=wt.get(e),o=n?OR(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},LR)}catch{}}Z(g.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&wt.has(t.windowId)&&Xn(t.windowId)}),Z(g.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=wt.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const Ot=new Map,DR=1e3;function zg(e,t,n){const o=Ot.get(e);if(!o||o.inflight)return;o.inflight=!0;const s=new URL(t+"desktop-mode/v1/debug",window.location.origin);s.searchParams.set("sessionId",e),s.searchParams.set("since",String(o.cursor));for(const r of o.channels.keys())s.searchParams.append("channels[]",r);const i=s.toString();fetch(i,{credentials:"same-origin",headers:{"X-WP-Nonce":n}}).then(r=>r.ok?r.json():{events:[],cursor:o.cursor}).then(r=>{if(o.inflight=!1,!!Ot.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const l=o.channels.get(a.channel);if(l)for(const c of l)try{c(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=Ot.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>zg(e,t,n),DR))})}function RR(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function xR(e,t){const n=Ot.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let MR=0;const Vg={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=Gg(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),Xn(e),()=>{const r=wt.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const l=a.indexOf(s);l>=0&&a.splice(l,1),a.length===0&&r.headers.delete(t),Xn(e),jg(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=Gg(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,Xn(e)),()=>{const i=wt.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),Xn(e)),jg(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=ml(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=Vg.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",l=new URL(a,window.location.origin);l.searchParams.set(i,t),o.src=l.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const e=window.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(e,t,n){xR(e,{id:++MR,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=Ot.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},Ot.set(e,o));let i=o.channels.get(t);if(i||(i=new Set,o.channels.set(t,i)),i.add(n),s){const r=RR();r&&zg(e,r.restUrl,r.restNonce)}return()=>{const r=Ot.get(e);if(!r)return;const a=r.channels.get(t);a&&(a.delete(n),a.size===0&&r.channels.delete(t)),r.channels.size===0&&(r.timer&&clearTimeout(r.timer),Ot.delete(e))}}}};function jg(e){const t=wt.get(e);t&&t.headers.size===0&&t.observers.size===0&&(NR(t),wt.delete(e))}function WR(e){const t=[];for(const l of e.getVisibleRects()){if(l.state==="minimized"||l.element.offsetParent===null)continue;const c=l.element.getBoundingClientRect();t.push({id:`window:${l.windowId}`,kind:"window",rect:Kg(c),face:"top",element:l.element})}const n=document.getElementById("os-shell");if(n){const l=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:l.left,y:l.bottom-1,width:l.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const l of Array.from(o)){const c=l.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const d=l.getAttribute("data-os-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,d==="bottom"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:c.width,height:1},face:"top",element:l}):d==="right"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:l}):t.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:l})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(l=>{const c=l.getBoundingClientRect();if(c.width===0&&c.height===0)return;const d=l.dataset.widgetId??String(r++);t.push({id:`widget:${d}`,kind:"widget",rect:Kg(c),face:"top",element:l})});const a=q(g.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function Kg(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const PR="__openstationKeyedListKey",$R="__openstationKeyedListData";function UR(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function BR(e,t,n){const o=UR(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const l of t){const c=String(n.keyOf(l));a.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),a.add(c);const d=s.get(c);if(d){const f=d.data;n.updateItem?.(d.el,l,f),d.data=l,i.set(c,d),r.push(d.el);continue}const u=n.buildItem(l);u[PR]=c,u[$R]=l,i.set(c,{el:u,data:l}),r.push(u)}for(const[l,c]of s)i.has(l)||c.el.remove();for(let l=0;l<r.length;l++){const c=r[l],d=e.children[l];d!==c&&e.insertBefore(c,d??null)}o.byKey=i}function FR(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function HR(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:l=j=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",j)}}=e;let c=e.sentinel??null;c||(c=document.createElement("div"),c.dataset.osInfiniteListSentinel="",c.style.height="1px",t.appendChild(c));const d=new Set;let u=r,f=!0,p=!1,v=null,h=0,w=!1,E=null;const S=j=>{if(p!==j){p=j;try{a(j)}catch(B){l(B)}}},O=()=>{E&&(E.disconnect(),E=null)},M=()=>{E||!c||w||(E=new IntersectionObserver(j=>{for(const B of j)B.isIntersecting&&b()},{rootMargin:i}),E.observe(c))},b=async()=>{if(w||p||!f)return;S(!0),v=new AbortController;const j=v;try{const B=await n(u,j.signal);if(w||j!==v)return;let V=0;const J=document.createDocumentFragment();for(const K of B.items??[]){const T=String(o(K));if(d.has(T))continue;d.add(T);const R=s(K,h+V);J.appendChild(R),V++}V>0&&(c&&c.parentNode===t?t.insertBefore(J,c):t.appendChild(J),h+=V),u=B.nextCursor??null,u||(f=!1,O())}catch(B){if(B?.name==="AbortError")return;l(B)}finally{j===v&&(S(!1),v=null)}},W=()=>{if(w)return;v?.abort(),v=null,d.clear(),u=r,f=!0,h=0;const j=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);j&&c&&t.appendChild(c),S(!1),M(),b()},U=()=>{w||(w=!0,O(),v?.abort(),v=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,S(!1))};return M(),b(),{reset:W,loadMore:b,hasMore:()=>f,isLoading:()=>p,destroy:U}}const GR=520,zR=720,VR=500;function jR(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=qR(),o=YR();return $e(it(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:e})},{source:"desktop-mode/oauth-start"}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`[openstation] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>KR(s,e,t))}function KR(e,t,n){return new Promise((o,s)=>{const i=n.width??GR,r=n.height??zR,a=Math.max(0,Math.floor((window.screen.width-i)/2)),l=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${l}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(e.authorize_url,`os-oauth-${t}`,c);if(!d){s(new Error("[openstation] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let f=null,p=!1;const v=()=>{p||(p=!0,window.removeEventListener("message",h),f!==null&&(window.clearInterval(f),f=null))},h=w=>{if(w.origin!==u)return;const E=w.data;if(!E||E.type!=="os-oauth-callback")return;const S=E.payload;if(v(),S&&S.ok)o(S);else{const O=S?.reason??"unknown",M=S?.message??"OAuth flow failed",b=new Error(`[openstation] startOAuth(${t}) failed: ${O} — ${M}`);b.cause=S,s(b)}};window.addEventListener("message",h),f=window.setInterval(()=>{d.closed&&(v(),s(new Error(`[openstation] startOAuth(${t}) cancelled — popup closed before completing.`)))},VR)})}function qg(){return window.openStationConfig??{}}function qR(){const e=qg().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function YR(){const e=qg().restNonce;return typeof e=="string"&&e!==""?e:null}const nr=["os-section","os-button","os-swatch","os-swatch-grid","os-segmented","os-segment","os-select","os-option","os-multiselect","os-color-field","os-range-field","os-text-field","os-number-field","os-checkbox","os-checkbox-label","os-switch","os-toast","os-toast-container","os-tabs","os-tab","os-tabpanel","os-window-button","os-menu","os-menu-item","os-context-menu","os-context-menu-option","os-confirm-dialog","os-modal","os-user-search","os-role-picker","os-flyout","os-tab-chip","os-stack","os-cluster","os-icon","os-body","os-panel","os-row","os-grid","os-display","os-disclosure","os-empty-state","os-key","os-code","os-badge","os-ribbon","os-tile","os-log","os-steps","os-step","os-table","os-spinner","os-relative-time","os-histogram","os-stat","os-avatar","os-textarea","os-chip","os-tag-input","os-form","os-save-status","os-category-picker","os-crumb-chain","os-card","os-rating-summary","os-notice","os-progress-bar","os-field-row","os-repeater","os-token-field"],Yg=new Set(nr);let or=null;function wl(){return!!window.openStationComponents}function XR(){return window.openStationConfig?.componentsBundleUrl??""}function ZR(e){return new Promise((t,n)=>{const o=()=>{if(wl()){t();return}n(new Error("[openstation] component kit loaded but did not set `window.openStationComponents`."))},s=document.querySelector('script[data-os-components="1"]');if(s){wl()?o():(s.addEventListener("load",o),s.addEventListener("error",()=>n(new Error("failed to load component kit"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osComponents="1",i.addEventListener("load",o),i.addEventListener("error",()=>n(new Error("failed to load component kit"))),document.head.appendChild(i)})}function JR(e){const t=e.filter(n=>!Yg.has(n));t.length===0||typeof console>"u"||console.error(`[openstation] wp.os.loadComponents(): not a component — ${t.map(n=>`<${n}>`).join(", ")}. The kit registers ${nr.length} tags; see docs/components-reference.md for the list. The others in this call still loaded.`)}async function QR(e){if(e){if(JR(e),e.filter(o=>Yg.has(o)&&!customElements.get(o)).length===0)return}else if(wl())return;const t=XR();t&&(or||(or=ZR(t).catch(n=>{throw or=null,n})),await or)}const ex=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","dockPlacement","icons","iconSet","files","confirm","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","openNewWindow","cloneTemplate","onWindow","createInfiniteList","startOAuth","repaintLoadingOverlays","loadVendorScript","getWallpaperSurfaces","wallpaper","games","mode","registerModule","loadModules","whenReady","ready","isReady","setDefaultWindow","refreshMenu","config","ai","dragBridge","dragManager","registerCommand","unregisterCommand","listCommands","registerDestructiveAdminAction","unregisterDestructiveAdminAction","listDestructiveAdminActions","registerSettingsTab","unregisterSettingsTab","listSettingsTabs","registerDockRailRenderer","unregisterDockRailRenderer","listDockRailRenderers","openOsSettings","getOsSettings","subscribeOsSettings","updateOsSettings","resetOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","getNavItems","getNav","renderIcon","applyTileClasses","applyTileElement","applyTileTooltip","dispatchTileRendered","isDockElement","registerDockSelector","registerTitleBarButton","unregisterTitleBarButton","listTitleBarButtons","registerWindowAction","unregisterWindowAction","listWindowActions","registerUnfocusEffect","unregisterUnfocusEffect","listUnfocusEffects","registerWindowReveal","unregisterWindowReveal","listWindowReveals","relations","registerWindowLinkRenderer","unregisterWindowLinkRenderer","listWindowLinkRenderers","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","desktopThemes","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","getConnection","broadcast","subscribe","announceContentChange","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","workArea","selection","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","getWindowParams","debug","registerNativeUrlRemap","fetch"]);function tx(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:l,registerWindow:c,openWindowById:d,openNewWindowById:u,loadWindowScriptById:f,prewarmWindowById:p,placeSystemTile:v,setDefaultWindow:h,refreshMenu:w,openOsSettings:E,aiAssistant:S,dragBridge:O,dragManager:M,connect:b,getConnection:W,wallpaperSuspend:U,mio:j,mode:B,workspaces:V,config:J}=e,K={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,iconSet:Bb,files:r,confirm:An,saveSession:a,hooks:gb(),HOOKS:g,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:T=>{Ln(T),s.apply()},registerWidget:T=>{Wc(T)},widgetLayer:l,widgets:{redock:T=>{l?.redock(T)}},loadVendorScript:fe,getWallpaperSurfaces:()=>WR(t),wallpaper:U,mio:j,mode:B,games:xh,registerWindow:c,openWindow:d,openNewWindow:u,loadWindowScript:f,prewarmWindow:p,loadComponents:QR,fetch:(T,R,Y)=>pl(t,T,R,Y),repaintLoadingOverlays:ip,cloneTemplate:mw,onWindow:nN,createInfiniteList:HR,startOAuth:jR,registerSystemTile:T=>{v(T),A(g.DOCK_ITEM_APPENDED,{id:T.id})},registerModule:Sh,loadModules:sc,whenReady:vd,ready:vd,isReady:vb,setDefaultWindow:h,refreshMenu:w,config:J,ai:S,dragBridge:O,dragManager:M,registerCommand:Wn,unregisterCommand:zh,listCommands:Vh,registerDestructiveAdminAction:eI,unregisterDestructiveAdminAction:rp,listDestructiveAdminActions:tI,registerSettingsTab:Kh,unregisterSettingsTab:qh,listSettingsTabs:Yh,registerDockRailRenderer:$d,unregisterDockRailRenderer:Xb,listDockRailRenderers:Qb,openOsSettings:E,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:T=>s.subscribeOsSettings(T),updateOsSettings:(T,R={})=>{s.update(T,R),(T.navPlacement||T.navOrder)&&o?.refresh()},resetOsSettings:(T={})=>{s.reset(T),o?.refresh()},deriveWindowId:(T,R)=>de(T,R??J.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:T=>o?.getSystemTile(T)??null,getMenuItems:()=>o?.getMenuItems()??[],getNavItems:()=>o?.getNavItems()??[],getNav:()=>o?.getNav()??null,renderIcon:Gn,applyTileClasses:ER,applyTileElement:_R,applyTileTooltip:SR,dispatchTileRendered:kR,isDockElement:AR,registerDockSelector:CR,registerTitleBarButton:xi,unregisterTitleBarButton:IC,listTitleBarButtons:CC,registerWindowAction:em,unregisterWindowAction:NC,listWindowActions:DC,registerUnfocusEffect:$i,unregisterUnfocusEffect:iL,listUnfocusEffects:vc,registerWindowReveal:Ue,unregisterWindowReveal:NE,listWindowReveals:lu,relations:uI,registerWindowLinkRenderer:bm,unregisterWindowLinkRenderer:uL,listWindowLinkRenderers:Ec,registerWindowTheme:Im,unregisterWindowTheme:Am,listWindowThemes:Cm,desktopThemes:{list:BE,getActive:ta,setActive:qa,ensureFull:bu,subscribe:GE,resolveIcon:Ks,resolveIconColor:na,applyRecommendedOsSettings:T=>{const R=T??ta()??"";return R===""?{}:s.applyThemeRecommendations(R)}},applyWindowTheme:(T,R)=>{const Y=t.getById(T);Y&&Y.setAppearanceTheme(R)},registerWindowControl:Ho,unregisterWindowControl:Nm,listWindowControls:Om,applyWindowControls:(T,R)=>{const Y=t.getById(T);Y&&Y.setAppearanceControls(R)},registerWindowSlot:Mm,unregisterWindowSlot:Lc,listWindowSlots:Wm,applyWindowSlot:(T,R,Y)=>{const X=t.getById(T);X&&X.setAppearanceSlot(R,Y)},registerWindowNotice:Fm,unregisterWindowNotice:Dc,listWindowNotices:Hm,dismissWindowNotice:ML,undismissWindowNotice:WL,registerWindowChrome:UL,unregisterWindowChrome:jm,listWindowChromes:Km,applyWindowChrome:(T,R)=>{const Y=t.getById(T);Y&&Y.setAppearanceChrome(R)},connect:b,getConnection:W,broadcast:Wi,subscribe:Pn,announceContentChange:rm,registerPalette:fg,unregisterPalette:rD,listPalettes:aD,openPalette:Zc,devtools:Vg,createSharedStore:ie,presence:yD,workArea:gS,workspaces:V,selection:xD,activity:Ee,heartbeat:Oe,showToast:ue,notify:dc,pwa:{promptInstall:rO,undismissInstallHint:aO,getState:Ro,subscribe:Ph,requestNotificationPermission:dC,getNotificationPermission:uC},renderKeyedList:BR,clearKeyedList:FR,registerNamespace:(T,R)=>{if(typeof T!="string"||T===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!R||typeof R!="object"){console.warn(`[openstation] registerNamespace("${T}"): api must be an object`);return}if(ex.has(T)){console.warn(`[openstation] registerNamespace("${T}"): name is reserved by the shell — pick a plugin-specific key`);return}K[T]=R;const Y=window.wp?.os;Y&&Y!==K&&(Y[T]=R)},getWindowConfig:T=>{const R=window.openStationWindowConfig;if(!R||typeof R!="object")return;const Y=R[T];return Y===void 0?void 0:Y},getWindowParams:T=>{const R=t.getById(T);if(R)return{...R.config.params??{}}},registerNativeUrlRemap:Ct,debug:{window:T=>{const R=(J.nativeWindows??[]).find(k=>k.id===T);if(!R)return null;const Y=R.scriptUrl||(R.scriptHandle?J.nativeWindowScriptData?.[R.scriptHandle]?.url??"":"");let X="unknown",oe=!1;Y&&(document.querySelector(`script[data-os-vendor="${Y.replace(/"/g,'\\"')}"]`)?(X="lazy",oe=!0):Array.from(document.querySelectorAll("script[src]")).find(D=>D.src===Y)&&(X="eager",oe=!0));const N=window.openStationWindowConfig,m=!!(N&&typeof N=="object"&&Object.prototype.hasOwnProperty.call(N,T));return{id:T,scriptHandle:R.scriptHandle||"",scriptUrl:Y,loadPath:X,tagInDom:oe,configPresent:m,extras:{hasTranslations:!!R.scriptTranslations,l10nCount:(R.scriptL10n??[]).length,beforeCount:(R.scriptBefore??[]).length,afterCount:(R.scriptAfter??[]).length}}}}};return K}function nx(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const gl=ie("desktop-mode/layout",()=>({layout:"classic"}));function Xg(e){gl.state.layout!==e&&(gl.state.layout=e,gl.notify())}class Zg{constructor(t){this.shape=t}title(){return this.shape.title}icon(){return this.shape.icon}previewUrl(){return this.shape.previewUrl}ref(){return this.shape.ref}exists(){return this.shape.exists}}class ox extends Zg{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const rs=new Map,yl=new Set;function Ve(e){if(!e.type)throw new Error("[openstation] registerType: `type` is required.");if(!e.label)throw new Error("[openstation] registerType: `label` is required.");rs.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),A("os.files.type-registered",e.type,e),Qg()}function sx(e){rs.delete(e)&&(A("os.files.type-unregistered",e),Qg())}function ix(e){const t=rs.get(e);return t||null}function Jg(){const e=Array.from(rs.values()).slice(),t=q("os.files.types",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>o.sort!==s.sort?o.sort-s.sort:o.label.localeCompare(s.label)),n}function Dt(e){const t=rs.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new ox(e,e.type)}function rx(e){return yl.add(e),()=>yl.delete(e)}function Qg(){for(const e of yl)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const sr=new Map,vl=new Set;let bl={};function ey(e){bl={...e},kl()}function El(){return{...bl}}function Be(e){if(!e.id)throw new Error("[openstation] registerOpener: `id` is required.");if(!e.label)throw new Error("[openstation] registerOpener: `label` is required.");if(!Array.isArray(e.types)||e.types.length===0)throw new Error("[openstation] registerOpener: `types` must be a non-empty array.");if(!e.handler||typeof e.handler!="object")throw new Error("[openstation] registerOpener: `handler` is required.");sr.set(e.id,{id:e.id,label:e.label,types:e.types.slice(),isDefault:!!e.isDefault,sort:typeof e.sort=="number"?e.sort:100,appliesTo:typeof e.appliesTo=="function"?e.appliesTo:void 0,handler:e.handler}),A("os.files.opener-registered",e.id,e),kl()}function ax(e){sr.delete(e)&&(A("os.files.opener-unregistered",e),kl())}function cx(e){return sr.get(e)??null}function ty(){const e=Array.from(sr.values()).slice(),t=q("os.files.openers",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>{const i=typeof o.sort=="number"?o.sort:100,r=typeof s.sort=="number"?s.sort:100;return i!==r?i-r:o.label.localeCompare(s.label)}),n}function _l(e,t){return ty().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function Sl(e,t){const n=_l(e,t);if(n.length===0)return null;const o=bl[e];let s=null;return o&&(s=n.find(r=>r.id===o)??null),s||(s=n.find(r=>r.isDefault)??null),s||(s=n[0]),q("os.files.resolve-opener",s,e)??null}function ny(e){return vl.add(e),()=>vl.delete(e)}function kl(){for(const e of vl)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let as=null;function lx(e){as=e}async function cs(e,t){if(!as)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=Sl(e.type(),e);if(!n)return A("os.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;A("os.files.opening",{file:e,openerId:n.id});try{const o=n.handler;if(o.kind==="url"){const s=await o.url(e);if(!s)return!1;const i=o.windowId?o.windowId(e):as.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),l=as.openUrl({id:i,url:s,title:r,icon:a});return A("os.files.opened",{file:e,openerId:n.id,kind:"url"}),l}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=as.openNativeWindow(o.windowId,s);return A("os.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),A("os.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return A("os.files.open-failed",{reason:"handler-threw",type:e.type(),ref:e.ref(),openerId:n.id,error:o}),console.error("[openstation] file opener threw:",o),!1}}const dx="dashicons-portfolio";function ux(){Ve({type:"shortcut",label:"Plugin shortcut",sort:1}),Ve({type:"folder",label:"Folder",sort:5}),Ve({type:"post",label:"Post",sort:10}),Ve({type:"attachment",label:"Media",sort:20}),Ve({type:"upload",label:"Uploaded file",sort:25}),Ve({type:"user",label:"User",sort:30}),Ve({type:"term",label:"Taxonomy term",sort:40}),Ve({type:"comment",label:"Comment",sort:50}),Ve({type:"bookmark",label:"Bookmark",sort:60}),Ve({type:"link",label:"Web link",sort:70}),Ve({type:"embed",label:"Embedded web window",sort:80})}const je=ie("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function oy(e){je.state.activeAgent=e,je.state.transcripts[e.id]||(je.state.transcripts[e.id]=[]),je.state.conversationIds||(je.state.conversationIds={},je.state.conversationsRev=0),je.notify()}const sy="desktop-mode/v1/agents/conversations";async function iy(e,t,n={}){const o=await $e(it(e.restRoot,t),{...n,headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce,...n.headers??{}}},{source:"desktop-mode/agents",silent:!0}),s=await o.json().catch(()=>null);if(!o.ok){const i=s&&typeof s=="object"&&typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new Error(i)}return s}function fx(e){return e.filter(t=>!t.pending)}async function px(e,t){const n=je.state,o=fx(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await iy(t,`${sy}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await iy(t,sy,{method:"POST",body:JSON.stringify({agentId:e.id,messages:o})});n.conversationIds[e.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,je.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const ry={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function ay(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function cy(e){if(e.type==="shortcut"){const t=e.data;let n=ry[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=ay(t.ref);return!n||!o?null:{kind:n,id:o,title:String(t.title??"")||`#${o}`}}if(e.type==="desktop-file"){const n=e.data.placement?.file;if(!n)return null;const o=ry[String(n.type??"")],s=ay(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function hx(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function mx(e){return re(_('The user dropped the %1$s "%2$s" (id %3$s) onto you. Handle it according to your instructions, using your tools as needed.',"desktop-mode"),e.kind,e.title,String(e.id))}function wx(e){return{kind:e.kind,id:e.id,title:e.title}}function ly(e,t="agents"){oy(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function gx(e,t,n,o,s){oy(e);const i=je.state.transcripts[e.id],r=i.filter(l=>!l.pending&&l.role!=="error").map(l=>({role:l.role,text:l.text}));i.push({role:"user",text:t,at:Date.now(),attachment:s});const a={role:"agent",text:_("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(a),je.notify();try{const l=await $e(it(n.restRoot,`desktop-mode/v1/agents/${e.id}/invoke`),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":n.restNonce},body:JSON.stringify({message:t,source:o,history:r})},{source:"desktop-mode/agents"}),c=await l.json().catch(()=>null);if(!l.ok){if(l.status===504)throw new Error(_("The agent took too long to reply, so the answer never arrived. It may still be finishing the work: give it a moment before asking again.","desktop-mode"));const u=c&&typeof c=="object"&&typeof c.message=="string"?c.message:`HTTP ${l.status}`;throw new Error(u)}const d=c;a.text=d.text||_("The agent finished without a text answer.","desktop-mode"),a.toolCalls=d.toolCalls,Array.isArray(d.callToActions)&&d.callToActions.length>0&&(a.callToActions=d.callToActions)}catch(l){a.role="error",a.text=l instanceof Error?l.message:String(l)}a.pending=!1,je.notify(),px(e,n)}function yx(e,t,n){return ly(e,"agents-drop"),gx(e,mx(t),n,"drag",wx(t))}let Il=null;function dy(e){Il=e}function ls(){if(!Il)throw new Error("[openstation] files REST client called before installRestDeps().");return Il}function vx(){return ls()}class Al extends Error{constructor(t){super(`Row was changed by ${t.actor.name||"another session"} (parent="${t.current.parentName}")`),this.name="FilesConflictError",this.status=409,this.detail=t}}async function we(e,t){const{baseUrl:n,nonce:o}=ls(),s=it(n,e),i=new Headers(t.headers??{});i.set("X-WP-Nonce",o),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await $e(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),a=await r.text();let l=null,c=null;if(a)try{l=JSON.parse(a)}catch(d){l=null,c=d}if(!r.ok){if(r.status===409){const u=l?.data?.data??l?.data;if(u&&typeof u=="object")throw new Al(u)}const d=l;throw new Error(`[openstation] files REST ${r.status}: ${d?.code??""} ${d?.message??""}`.trim())}if(l===null){if(c&&a){const d=a.slice(0,120).replace(/\s+/g," ");throw new Error(`[openstation] files REST ${r.status} returned non-JSON body — ${c.message}. First 120 chars: ${d}`)}throw new Error(`[openstation] files REST ${r.status}: empty or unparseable body.`)}return l}function xe(e=0){return we(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function ds(e){return we("/placements",{method:"POST",body:JSON.stringify(e)})}function Zn(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),we(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Cl(e){return we(`/placements/${e}`,{method:"DELETE"})}async function ir(e,t){const{baseUrl:n,nonce:o}=ls(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await $e(i,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o},credentials:"same-origin",body:JSON.stringify({items:[{id:e,type:t}]})},{source:"desktop-mode/files"});if(!r.ok)throw new Error(`[openstation] restore ${r.status}`);return await r.json()}function uy(){return we("/folders",{method:"GET"})}function Ll(e){return we("/folders",{method:"POST",body:JSON.stringify(e)})}function fy(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),we(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Tl(e){return we(`/folders/${e}`,{method:"DELETE"})}function py(e){return we("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function bx(e){return we(`/folders/${e}/shares`,{method:"GET"})}function Ex(e,t){return we(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function _x(e,t,n){return we(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function Sx(e,t){return we(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function kx(e,t){return we(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function Ix(e,t){return we(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function hy(e){return we(`/folders/${e}/leave`,{method:"POST"})}function Ax(){return we("/folder-sharing-tables/purge",{method:"POST"})}function Cx(e){return we(`/uploads/${e}/shares`,{method:"GET"})}function Lx(e,t){return we(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function Tx(e,t){return we(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function Nx(e,t){return we(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function Ox(e,t){return we(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function my(e){return we(`/uploads/${e}/leave`,{method:"POST"})}function Dx(e,t){return we(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function Rx(e,t){return we("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function tn(e){const{baseUrl:t,nonce:n}=ls(),o=it(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function wy(e){const{baseUrl:t,nonce:n}=ls(),o=it(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const xx=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:Al,acceptFileShare:Nx,acceptShare:kx,createFolder:Ll,createPlacement:ds,deleteFolder:Tl,deletePlacement:Cl,denyFileShare:Ox,denyShare:Ix,ensureUploadPath:Rx,getFilesRestDeps:vx,getFolderZipUrl:wy,getUploadDownloadUrl:tn,installRestDeps:dy,inviteFileShare:Lx,inviteShare:Ex,leaveFileShare:my,leaveShare:hy,listFileShares:Cx,listFolders:uy,listPlacements:xe,listShares:bx,purgeFolderSharingTables:Ax,renameUpload:Dx,restoreTrashedItem:ir,revokeFileShare:Tx,revokeShare:Sx,saveAssociations:py,updateFolder:fy,updatePlacement:Zn,updateShareCapability:_x},Symbol.toStringTag,{value:"Module"})),Mx="desktop-mode/files";function tt(){return ie(Mx,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function Jn(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function nn(e,t){const n=tt(),o=new Map(n.state.placementsByFolder);o.set(e,t.slice());const s=new Set(n.state.hydratedFolders);s.add(e),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),Jn({kind:"placements-set",folderId:e})}function Nl(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=tt(),o=new Map(n.state.placementsByFolder);for(const[a,l]of o)if(l.findIndex(d=>d&&d.id===e.id)>=0&&a!==e.parentId){const d=l.filter(Boolean),u=d.findIndex(f=>f.id===e.id);u>=0&&d.splice(u,1),o.set(a,d)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),Jn({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function us(e,t="local"){const n=tt(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(l=>l&&l.id===e)>=0){const l=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,l),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),Jn({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function Ol(e){const t=tt(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),Jn({kind:"folders-set"})}function Dl(e,t="local"){const n=tt(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),Jn({kind:"folder-upserted",folderRowId:e.id,source:t})}function Rl(e,t="local"){const n=tt(),o=new Map(n.state.folders);o.delete(e);const s=new Map(n.state.placementsByFolder);s.delete(e),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),Jn({kind:"folder-removed",folderRowId:e,source:t})}function xl(e){return tt().subscribe(e)}function Rt(){return tt().getState()}function gy(e){const t=Rt(),n=t.placementsByFolder.get(e.parentId)?.find(o=>o&&o.id===e.id);if(n)return n;for(const o of t.placementsByFolder.values()){const s=o.find(i=>i&&i.id===e.id);if(s)return s}return e}const se={getState:Rt,subscribe:xl,setFolderPlacements:nn,upsertPlacement:Nl,upsertFolder:Dl,removePlacement:us,removeFolder:Rl,currentPlacement:gy},Wx=Ae`:host{display:inline-block}`,Px=Ae`:host{position:absolute;width:var( --os-ui-ribbon-size,90px );height:var( --os-ui-ribbon-size,90px );overflow:hidden;pointer-events:none;z-index:var( --os-ui-ribbon-z,2 )}:host( [ hidden ] ){display:none}.banner{position:absolute;display:block;width:var( --os-ui-ribbon-banner-width,140px );padding:var( --os-ui-ribbon-padding,4px 0 );text-align:center;font:var( --os-ui-ribbon-font,700 10px/1.4 var( --os-font,system-ui ) );letter-spacing:var( --os-ui-ribbon-tracking,0.06em );text-transform:uppercase;color:var( --os-ui-ribbon-fg,var( --os-ui-fg-on-accent,#fff ) );background:var( --os-ui-ribbon-bg,var( --wp-admin-theme-color,#2271b1 ) );background-size:260% 260%;background-position:30% 40%;box-shadow:var( --os-ui-ribbon-shadow,0 2px 4px rgba( 0,0,0,0.2 ) )}:host(:not( [ placement ] ) ),:host( [ placement='top-end' ] ){inset-block-start:0;inset-inline-end:0}:host(:not( [ placement ] ) ) .banner,:host( [ placement='top-end' ] ) .banner{inset-block-start:var( --os-ui-ribbon-banner-offset,20px );inset-inline-end:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host( [ placement='top-start' ] ){inset-block-start:0;inset-inline-start:0}:host( [ placement='top-start' ] ) .banner{inset-block-start:var( --os-ui-ribbon-banner-offset,20px );inset-inline-start:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-end' ] ){inset-block-end:0;inset-inline-end:0}:host( [ placement='bottom-end' ] ) .banner{inset-block-end:var( --os-ui-ribbon-banner-offset,20px );inset-inline-end:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-start' ] ){inset-block-end:0;inset-inline-start:0}:host( [ placement='bottom-start' ] ) .banner{inset-block-end:var( --os-ui-ribbon-banner-offset,20px );inset-inline-start:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host(:not( [ placement ] ) ) .banner,:host-context( [ dir='rtl' ] ):host( [ placement='top-end' ] ) .banner{transform:rotate( -45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='top-start' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-end' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-start' ] ) .banner{transform:rotate( -45deg )}:host( [ tone='success' ] ) .banner{background:var( --os-ui-ribbon-success,var( --os-ui-success-fg,#1a7f37 ) )}:host( [ tone='warning' ] ) .banner{background:var( --os-ui-ribbon-warning,var( --os-ui-warning-bg,#9a6700 ) )}:host( [ tone='danger' ] ) .banner{background:var( --os-ui-ribbon-danger,var( --os-ui-danger,#cf222e ) )}:host( [ tone='info' ] ) .banner{background:var( --os-ui-ribbon-info,var( --os-ui-info-bg,#0969da ) )}:host( [ tone='neutral' ] ) .banner{background:var( --os-ui-ribbon-neutral,var( --os-ui-surface,#57606a ) )}`,Os=class Os extends qt{render(){return Dn`<span class="banner" part="banner"><slot></slot></span>`}};Os.props=["placement","tone"],Os.styles=[Px],Os.help=void 0;let Ml=Os;Oo("os-ribbon",Ml);const ae="os-file-tile",yy={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function $x(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function Ux(){return window.wp?.os?.dragManager??null}const Bx=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],io=class io extends qt{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null,this._onSettingsSave=t=>{t.detail?.phase==="saved"&&this._paint()}}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this.click())},this.addEventListener("keydown",this._keydownHandler)),document.addEventListener("os-settings-save-lifecycle",this._onSettingsSave),this._paint()}disconnectedCallback(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null),this._keydownHandler&&(this.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),document.removeEventListener("os-settings-save-lifecycle",this._onSettingsSave)}requestUpdate(){this.isConnected&&this._paint()}attributeChangedCallback(t,n,o){if(n!==o){if(t==="selected"||t==="selectable"||t==="aria-selected"){this._paintSelection();return}super.attributeChangedCallback(t,n,o)}}_paintSelection(){const t=this.hasAttribute("selected"),n=this.hasAttribute("selectable");if(this.classList.toggle(`${ae}--selected`,t),this.setAttribute("role",n?"option":"listitem"),n){const o=t?"true":"false";this.getAttribute("aria-selected")!==o&&this.setAttribute("aria-selected",o)}else this.removeAttribute("aria-selected")}render(){return Dn``}_paint(){const t=this.getAttribute("type")??"",n=this.getAttribute("ref")??"",o=this.getAttribute("label")??"",s=this.getAttribute("icon")??"",i=this.getAttribute("thumbnail")??"",r=this.getAttribute("kind")??"entry",a=this.getAttribute("status")??"",l=this.hasAttribute("selected"),c=this.hasAttribute("selectable"),d=this.hasAttribute("missing"),u=this.hasAttribute("access-gated"),f=[ae,`${ae}--folder`,`${ae}--missing`,`${ae}--access-gated`,`${ae}--selected`];for(const E of f)this.classList.remove(E);this.classList.add(ae),r==="folder"&&this.classList.add(`${ae}--folder`),d&&this.classList.add(`${ae}--missing`),u&&this.classList.add(`${ae}--access-gated`),l&&this.classList.add(`${ae}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",c?"option":"listitem"),c?this.setAttribute("aria-selected",l?"true":"false"):this.removeAttribute("aria-selected"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const v=[`${ae}__visual`,`${ae}__label`,`${ae}__lock`];for(const E of v)this.querySelectorAll(`:scope > .${E}`).forEach(S=>S.remove());this.querySelectorAll(":scope > os-ribbon").forEach(E=>E.remove());const h=document.createElement("span");if(h.className=`${ae}__visual`,i){const E=document.createElement("img");E.src=i,E.alt="",E.loading="lazy",E.decoding="async",E.className=`${ae}__preview`,E.draggable=!1,h.appendChild(E)}else if(s){const E=Gn(s,{title:o,className:`${ae}__icon`});h.appendChild(E)}this.appendChild(h);const w=document.createElement("span");if(w.className=`${ae}__label`,w.textContent=o,this.appendChild(w),u){const E=document.createElement("span");E.className=`${ae}__lock dashicons dashicons-lock`,E.setAttribute("aria-hidden","true"),this.appendChild(E)}if(a&&a!=="publish"&&yy[a]&&$x()){const E=document.createElement("os-ribbon");E.setAttribute("placement","top-end"),E.setAttribute("tone",Fx(a)),E.textContent=yy[a],this.appendChild(E)}kb(this),A("os.tile.rendered",{tile:this}),this._wireDragOut()}_wireDragOut(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null);const t=this.getAttribute("drag-kind");if(!t)return;const n=o=>{if(o.button!==0)return;const s=Ux();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,a=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,l=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-l.left,offsetY:o.clientY-l.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};io.shadow=!1,io.props=Bx,io.styles=[Wx],io.help=void 0;let Wl=io;function Fx(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}Oo("os-tile",Wl);function Hx(e){const t=document.createElement("os-tile");if(t.setAttribute("type",e.type),t.setAttribute("ref",e.ref),t.setAttribute("label",e.label),e.icon&&t.setAttribute("icon",e.icon),e.thumbnail&&t.setAttribute("thumbnail",e.thumbnail),e.role&&t.setAttribute("kind",e.role),e.status&&t.setAttribute("status",e.status),e.missing&&t.setAttribute("missing",""),e.accessGated&&t.setAttribute("access-gated",""),e.dataset)for(const[o,s]of Object.entries(e.dataset))s!=null&&(t.dataset[o]=String(s));if(Array.isArray(e.extraClasses))for(const o of e.extraClasses)o&&t.classList.add(o);const n=q("os.tile.class",t.className,e);return n&&n!==t.className&&(t.className=n),typeof e.x=="number"&&typeof e.y=="number"&&(t.style.position="absolute",t.style.left=`${e.x}px`,t.style.top=`${e.y}px`),t}function Gx(e,t){const n=document.createElement("div");n.className="os-drag-stack";const o=e.getBoundingClientRect();n.style.width=`${o.width}px`,n.style.height=`${o.height}px`;const s=e.cloneNode(!0);s.removeAttribute("id"),s.removeAttribute("selected"),s.removeAttribute("aria-selected"),s.classList.remove(`${ae}--selected`),s.style.left="0px",s.style.top="0px",s.style.position="relative",n.appendChild(s);const i=document.createElement("span");return i.className="os-drag-stack__count",i.textContent=String(t),n.appendChild(i),n}function vy(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:Dt(e.file).title()}function zx(e,t){const n=Dt(e.file),o=n.previewUrl(),s=vy(e),i=e.meta&&typeof e.meta.iconUrl=="string"?e.meta.iconUrl.trim():"";return{type:e.file.type,ref:e.file.ref,label:s,thumbnail:o||void 0,icon:o?void 0:bw(e.file.ref)||i||Ks(jE(e.file.type))||n.icon(),x:e.x,y:e.y,dataset:{placementId:e.id,folderId:t},meta:e.meta,missing:!e.file.exists,accessGated:!!e.accessGated,ariaLabel:s}}function Vx(e,t){const n=Hx(zx(e,t)),o=q("os.files.tile-class",ae,e);o&&o!==ae&&(n.className=o);const s=q("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=gy(e),a=Dt(r.file);if(r.accessGated){ue({message:`You don’t have permission to open "${r.file.title||a.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}cs(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),A("os.files.tile-rendered",{tile:n,placement:e}),n}function on(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const jx=ie("desktop-mode/tile-payload-handlers",()=>({handlers:new Map}));function fs(){return jx.state.handlers}function Pl(e,t){const n=fs().get(e);return n?n.push(t):fs().set(e,[t]),()=>{const o=fs().get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&fs().delete(e)}}function $l(e,t){const n=fs().get(e);if(n)return n.find(o=>o.appliesTo(t))}function Kx(e,t){return $l(e,t)?.acceptLabel}function qx(e,t){const n=$l(e.type,t);return n?n.accept(e.data,t):!1}function Yx(e,t,n){const o=$l(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function Xx(e,t,n){const o=t.slice().sort((s,i)=>{const r=typeof s.sort=="number"?s.sort:100,a=typeof i.sort=="number"?i.sort:100;return r!==a?r-a:s.label.localeCompare(i.label)});o.length!==0&&OD(e,{actions:o,scope:"files.tile",dataset:{placementId:String(n.placementIds[0]??""),placementIds:n.placementIds.join(",")},onOpened:s=>{A("os.files.tile-menu.opened",{placementId:n.placementIds[0],placementIds:n.placementIds.slice(),items:s})},onClosed:()=>{A("os.files.tile-menu.closed",{})}})}const Zx="my-wordpress",Qn=ie("desktop-mode/my-wordpress/open-target",()=>({kind:null,entityId:"",id:0,title:"",requestedAt:0}));function Jx(e){Qn.state.kind=e.kind,Qn.state.entityId=e.entityId,Qn.state.id=e.id,Qn.state.title=e.title,Qn.state.requestedAt=Date.now(),Qn.notify()}function Qx(e){const t=window.wp?.os?.openWindow;t?.(Zx,{source:e})}function by(e){const t=Number(e.postId);!Number.isFinite(t)||t<=0||(Jx({kind:"detail",entityId:e.entityId||"posts",id:t,title:e.postTitle??""}),Qx("my-wordpress/open-detail"))}function eM(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function Ul(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function Bl(e){const t=()=>{const n=e.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};t()||queueMicrotask(()=>void t())}const Me="os-create-folder-dialog";let ps=null;function Fl(){ps&&(ps.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),ps.remove(),ps=null,A("os.files.create-folder.closed",{}))}function Hl(e){if(Fl(),q("os.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${Me}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=Me,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${Me}-title`);const i=document.createElement("h2");i.id=`${Me}-title`,i.className=`${Me}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${Me}__field`,r.id=`${Me}-input`,r.setAttribute("label",e.label??"Folder name"),r.setAttribute("value",n),r.setAttribute("autocomplete","off"),r.setAttribute("spellcheck","false"),s.appendChild(r);const a=document.createElement("p");a.className=`${Me}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const l=document.createElement("div");l.className=`${Me}__actions`;const c=document.createElement("os-button");c.className=`${Me}__btn ${Me}__btn--secondary`,c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className=`${Me}__btn ${Me}__btn--primary`,d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(d),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),ps=o,Bl(r),A("os.files.create-folder.opened",{});const u=w=>{Ul(r,w),Ul(c,w),Ul(d,w),s.classList.toggle(`${Me}--busy`,w)},f=w=>{a.textContent=w,a.hidden=!1},p=()=>{Fl(),e.onCancel?.()},v=async()=>{const w=eM(r).trim();if(!w){f("Please enter a name."),Bl(r);return}a.hidden=!0,u(!0);try{await e.onSubmit(w),Fl()}catch(E){u(!1),f(E instanceof Error?E.message:"Could not create the folder."),Bl(r)}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void v()),o.addEventListener("click",w=>{w.target===o&&p()});const h=w=>{w.key==="Escape"?(w.preventDefault(),p()):w.key==="Enter"&&!w.isComposing&&(w.preventDefault(),v())};s.addEventListener("keydown",h),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",h)})}function rr(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function tM(e){return e.id<=0||rr(e)!==null}function Ey(e){e.length!==0&&vA(e)}function eo(e,t,n){rm(e,t,n,"desktop-files")}function ar(e){const t=window.wp?.os;if(!t?.showToast)return;const o=(e instanceof Error?e.message:String(e)).replace(/^\[openstation\][^:]*:\s*/,"").replace(/^openstation_files_[a-z_]+\s*/,"");t.showToast({message:o||"Could not move this item to the recycle bin.",duration:5e3})}function Gl(e,t){const n=window.wp?.os;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function _y(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";se.removePlacement(t);try{await Cl(t),eo(s,"trashed",[t]),Gl(`"${o}" moved to Trash`,async()=>{try{await ir(t,"placement");const i=await xe(n);se.setFolderPlacements(n,i.placements),eo(s,"untrashed",[t])}catch(i){console.error("[openstation] restore failed:",i)}})}catch(i){console.error("[openstation] deletePlacement failed:",i),ar(i),xe(n).then(r=>{se.setFolderPlacements(n,r.placements)})}}async function Sy(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";se.removePlacement(n),se.removeFolder(t);try{await Tl(t),eo("folder","trashed",[t]),Gl(`"${s}" moved to Trash`,async()=>{try{await ir(t,"folder");const i=await xe(o);se.setFolderPlacements(o,i.placements),eo("folder","untrashed",[t])}catch(i){console.error("[openstation] restore folder failed:",i)}})}catch(i){console.error("[openstation] deleteFolder failed:",i),ar(i),xe(o).then(r=>{se.setFolderPlacements(o,r.placements)})}}async function ky(e){if(e.length===0)return;if(e.length===1)return nM(e[0]);const t=new Set;for(const l of e)if(t.add(l.parentId),se.removePlacement(l.id),l.file?.type==="folder"){const c=parseInt(l.file.ref,10);c&&se.removeFolder(c)}const n=async()=>{for(const l of t)try{const c=await xe(l);se.setFolderPlacements(l,c.placements)}catch(c){console.error("[openstation] files: re-hydrate failed:",c)}},o=await Promise.allSettled(e.map(async l=>{if(l.file?.type==="folder"){const c=parseInt(l.file.ref,10);if(!c)throw new Error("folder placement without a folder id");return await Tl(c),{id:c,kind:"folder",restoreId:c,restoreKind:"folder"}}return await Cl(l.id),{id:l.id,kind:l.file?.type==="shortcut"?"shortcut":"placement",restoreId:l.id,restoreKind:"placement"}})),s=[];let i=0;for(const l of o)l.status==="fulfilled"?s.push(l.value):(i+=1,console.error("[openstation] trash (bulk) failed for one item:",l.reason));if(i>0&&n(),s.length===0){ar(o.find(l=>l.status==="rejected")?.reason);return}for(const l of["placement","shortcut","folder"]){const c=s.filter(d=>d.kind===l).map(d=>d.id);c.length>0&&eo(l,"trashed",c)}const r=s.length===1?"item":"items",a=i>0?`${s.length} ${r} moved to Trash · ${i} could not be moved`:`${s.length} ${r} moved to Trash`;Gl(a,async()=>{const l=await Promise.allSettled(s.map(u=>ir(u.restoreId,u.restoreKind)));await n();const c=s.filter((u,f)=>l[f].status==="fulfilled"),d=s.length-c.length;for(const u of l)u.status==="rejected"&&console.error("[openstation] restore (bulk) failed for one item:",u.reason);for(const u of["placement","shortcut","folder"]){const f=c.filter(p=>p.kind===u).map(p=>p.id);f.length>0&&eo(u,"untrashed",f)}d>0&&ar(new Error(`${d} of ${s.length} items could not be restored.`))})}function nM(e){return e.file?.type==="folder"?Sy(e):_y(e)}const oM=5,Iy=e=>ky(e);async function sM(e){if(!(e.length>oM&&!await An({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await cs(Dt(t.file))}function iM(e){const t=parseInt(e.file.ref,10);t&&Hl({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:e.file.title,onSubmit:async n=>{const o=n.trim();if(!o||o===e.file.title)return;const s=e.file.title,i={...e,file:{...e.file,title:o}};se.upsertPlacement(i);try{const r=se.getState().folders.get(t)?.updatedAtMs??0,a=await fy(t,{name:o},r);se.upsertFolder(a);const l=await xe(e.parentId);se.setFolderPlacements(e.parentId,l.placements)}catch(r){console.error("[openstation] rename folder failed:",r),se.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function rM(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=typeof e.file.postType=="string"?e.file.postType:"post";by({entityId:n==="page"?"pages":"posts",postId:t,postTitle:e.file.title||`#${t}`})}function aM(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>sM(i),onClick:()=>{cs(Dt(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>rM(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>iM(e)}),e.canTrash!==!1&&t.push({id:"delete-folder",multiId:"trash",label:"Move folder to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:i=>`Move ${i} items to Trash`,bulk:Iy,onClick:()=>Sy(e)});else{const i=rr(e),r=e.file.type==="shortcut";if(i||r){const a=i??e.file.ref;t.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,multi:!0,bulkLabel:l=>`Hide ${l} items from desktop`,bulk:l=>{Ey(l.map(c=>rr(c)??c.file.ref).filter(c=>!!c))},onClick:()=>Ey([a])})}else e.canTrash!==!1&&t.push({id:"remove",multiId:"trash",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:a=>`Move ${a} items to Trash`,bulk:Iy,onClick:()=>_y(e)})}const o=q("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const xt=16,Ay=88,Cy=104,cM=20,lM=16,zl=Ay+cM,Vl=Cy+lM;function hs(e,t){const n=Math.max(0,Math.round((e-xt)/zl)),o=Math.max(0,Math.round((t-xt)/Vl));return sn(n,o)}function sn(e,t){return{col:e,row:t,x:xt+e*zl,y:xt+t*Vl}}const dM=5,uM=4;function ms(e){if(!e)return{width:0,height:0};if(typeof HTMLElement<"u"&&e instanceof HTMLElement)return{width:e.clientWidth,height:e.clientHeight};const t=e;return{width:typeof t.width=="number"?t.width:0,height:typeof t.height=="number"?t.height:0}}function fM(e){const t=ms(e).height;return t<=0?dM:Math.max(1,Math.floor((t-xt)/Vl))}function pM(e){const t=ms(e).width;return t<=0?uM:Math.max(1,Math.floor((t-xt)/zl))}const Ly=999;function cr(e,t="column",n){if(t==="row"){const s=pM(n);for(let i=0;i<Ly;i++)for(let r=0;r<s;r++)if(!e.has(Ie(r,i)))return sn(r,i);return sn(0,0)}const o=fM(n);for(let s=0;s<Ly;s++)for(let i=0;i<o;i++)if(!e.has(Ie(s,i)))return sn(s,i);return sn(0,0)}function Ty(e,t,n="column",o){const s=new Set(t),i=[];for(let r=0;r<e;r++){const a=cr(s,n,o);s.add(Ie(a.col,a.row)),i.push(a)}return i}function Mt(e,t,n,o,s="column"){const i=hs(e,t);return n.has(Ie(i.col,i.row))?cr(n,s,o):i}function Ny(e,t){const n=new Set;for(const o of e){const s=hs(o.x,o.y);n.add(Ie(s.col,s.row))}return n}function Ie(e,t){return`${e},${t}`}function hM(e){const t=String(e),{placementsByFolder:n}=tt().state;for(const o of n.values())for(const s of o)if(s.file?.type==="folder"&&s.file.ref===t)return s.file}function mM(e,t){const n=hM(e);if(n)return Dt(n);const o=tt().state.folders.get(e);return Dt({type:"folder",ref:String(e),title:o?.name||t||"Folder",icon:dx,previewUrl:"",exists:!0})}function Oy(e){return e instanceof Al}function wM(e){const t=e.detail.actor.name||"Someone else",n=e.detail.current.parentName||"another folder";return e.detail.reason==="trashed"?"This item is in the recycle bin.":e.detail.reason==="forbidden"?"You no longer have access.":e.detail.reason==="gone"?"This item was deleted.":`${t} moved this to "${n}".`}function Dy(e){const t=wM(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{cs(mM(n,e.detail.current.parentName))}}),ue({message:t,action:o,duration:7e3})}const gM=ie("desktop-mode/canvas-payload-handlers",()=>({handlers:new Map}));function Ry(){return gM.state.handlers}function yM(e,t){const n=Ry().get(e.type);return n?n.accept(e.data,t):!1}function vM(e,t,n){const o=Ry().get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function to(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function lr(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}const xy="application/x-wp-media-attachment",My="data-files-drop-active";function Wy(){const e=window.wp?.os?.dragBridge;if(!e)return null;try{return e.getPayload()}catch{return null}}function Py(e){if(!e||typeof e.id!="number")return null;switch(e.kind){case"attachment":case"post":case"user":return{kind:e.kind,ref:String(e.id),title:e.title};default:return null}}function bM(e){if(!e)return null;let t="";try{t=e.getData(xy)}catch{return null}if(!t)return null;try{const n=JSON.parse(t),o=typeof n.id=="number"?n.id:Number(n.id);return!Number.isFinite(o)||o<=0?null:{kind:"attachment",ref:String(o),title:typeof n.title=="string"?n.title:void 0}}catch{return null}}function $y(e){const t=e.dataTransfer?.types,n=t?Array.from(t):[];return n.includes("Files")?!1:n.includes(xy)?!0:Py(Wy())!==null}function Uy(e,t,n){if(!(e instanceof Element)||!t.contains(e))return!1;let o=e;for(;o&&o!==t;){if(o===n)return!0;if(o.classList.contains("wp-window")||o.id==="os-widgets")return!1;o=o.parentElement}return o===t}function By(e,t){if(!(e instanceof Element))return null;const n=e.closest(`.${ae}`);return!(n instanceof HTMLElement)||!t.contains(n)?null:n.dataset.fileType==="folder"?n:null}function EM(e){const{host:t,container:n,folderId:o}=e;let s=null;const i=()=>{t.removeAttribute(My),s&&(s.classList.remove(`${ae}--drop-target`),s=null)},r=c=>{if(!$y(c))return;if(!Uy(c.target,t,n)){i();return}c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),t.setAttribute(My,"");const d=By(c.target,n);d!==s&&(s?.classList.remove(`${ae}--drop-target`),d?.classList.add(`${ae}--drop-target`),s=d)},a=c=>{const d=c.relatedTarget;d instanceof Node&&t.contains(d)||i()},l=c=>{if(!$y(c))return;if(!Uy(c.target,t,n)){i();return}i(),c.preventDefault(),c.stopPropagation();const d=Py(Wy())??bM(c.dataTransfer);if(!d)return;const u=By(c.target,n);let f=o;if(u){const p=parseInt(u.getAttribute("ref")??"",10);!Number.isNaN(p)&&p>0&&(f=p)}e.fileEntities([d],f)};return t.addEventListener("dragover",r),t.addEventListener("dragleave",a),t.addEventListener("drop",l),()=>{i(),t.removeEventListener("dragover",r),t.removeEventListener("dragleave",a),t.removeEventListener("drop",l)}}function _M(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o}}function ws(){return window.wp?.os?.dragManager??null}const SM="os-files-layer";function dr(e){return e===0?"column":"row"}function kM(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function Fy(e,t){return t!==0||!e?e:{get width(){return he(e).width},get height(){return he(e).height}}}function Hy(e,t=0){const n=dr(t),o=Fy(e,t),s=document.createElement("div");s.className=SM,s.setAttribute("role","list"),s.dataset.folderId=String(t),e.appendChild(s);let i="";const r=N=>{const m=se.getState().placementsByFolder.get(t)??[],k=new Map;for(const I of m)I&&k.set(String(I.id),I);return N.map(I=>k.get(I)).filter(I=>!!I)},a=new Set,l=new Set,c=AD(s,{itemSelector:`.${ae}`,background:e,surface:"files",scope:String(t),keyOf:N=>N.dataset.placementId??null,onChange:N=>{const m=r(N),k=m.length===1?m[0]:null;for(const I of a)try{I(k)}catch(D){console.error("[openstation] files: selection listener threw:",D)}for(const I of l)try{I(m)}catch(D){console.error("[openstation] files: selection listener threw:",D)}}}),d=()=>r(c.keys()),u=N=>{const m=new Map,k=new Set;let I=0;for(const $ of N){if(!We($))continue;const x=sn(0,I);m.set($.id,{x:x.x,y:x.y}),k.add(Ie(x.col,x.row)),I+=1}const D=new Map;for(const $ of N){if(m.has($.id))continue;const x=hs($.x,$.y),C=Ie(x.col,x.row);if(!k.has(C)){k.add(C);continue}const H=Mt($.x,$.y,k,o,n);k.add(Ie(H.col,H.row)),D.set($.id,{x:H.x,y:H.y})}return{pinnedSlots:m,displaced:D}},f=(N,m,k,I)=>{const D=k.get(m.id),$=I.get(m.id);D?on(N,D.x,D.y):$?on(N,$.x,$.y):on(N,m.x,m.y)},p=(N,m,k)=>{const I=Vx(N,t),D=m.get(N.id);if(D){if(on(I,D.x,D.y),I.classList.add(`${ae}--pinned`),Ky(I,N,c,d),Gy(N)){const x=ws();x&&S.set(N.id,jy(x,I,N))}return I}const $=k.get(N.id);if($&&on(I,$.x,$.y),NM(I,N,t,c,d),Ky(I,N,c,d),N.file.type==="folder"){const x=parseInt(N.file.ref,10);if(x>0){const C=ws();if(C){const H=TM(C,I,x);E.set(N.id,H)}}}else if(Gy(N)){const x=ws();x&&S.set(N.id,jy(x,I,N))}return I},v=N=>{const m=new Map;for(const $ of s.querySelectorAll("[data-placement-id]")){const x=$.dataset.placementId??"",C=parseInt(x,10);if(x===""||Number.isNaN(C)&&x!=="-0")return!1;m.set(C,$)}const k=new Set;for(const $ of N)k.add($.id);for(const $ of N){const x=m.get($.id);if(!x)continue;if(x.dataset.fileType!==$.file.type||x.dataset.fileRef!==$.file.ref||x.classList.contains(`${ae}--pinned`)!==We($))return!1}for(const[$,x]of m){if(k.has($))continue;const C=E.get($);if(C){try{C()}catch{}E.delete($)}const H=S.get($);if(H){try{H()}catch{}S.delete($)}x.remove()}const{pinnedSlots:I,displaced:D}=u(N);for(const $ of N){const x=m.get($.id);if(x){f(x,$,I,D),Vy(x,$);continue}s.appendChild(p($,I,D))}return c.refresh(),A("os.files.grid-rendered",{folderId:t,count:N.length}),!0},h=N=>{const k=(N.placementsByFolder.get(t)??[]).slice().sort((x,C)=>{const H=We(x)?0:1,P=We(C)?0:1;return H-P}),I=IM(k);if(I===i||(i=I,LM(k,s,o,n))||v(k))return;s.replaceChildren();for(const[,x]of E)try{x()}catch{}E.clear();for(const[,x]of S)try{x()}catch{}S.clear();const{pinnedSlots:D,displaced:$}=u(k);for(const x of k)s.appendChild(p(x,D,$));c.refresh(),A("os.files.grid-rendered",{folderId:t,count:k.length})},w=[],E=new Map,S=new Map;let O=null,M=null;const b=N=>{if(O||N.payload.type!=="desktop-file")return;const m=document.createElement("div");m.className="os-files-drop-preview",m.setAttribute("aria-hidden","true"),s.appendChild(m),O=m;const k=N.payload.ghost,I=k?.offsetX??0,D=k?.offsetY??0,x=N.payload.data?.placement?.id,C=(ce,z)=>{const ee=s.getBoundingClientRect(),le=Math.max(0,ce-ee.left-I),ye=Math.max(0,z-ee.top-D),De=se.getState().placementsByFolder.get(t)??[],Ds=fr(De,x),Le=Mt(le,ye,Ds,o,n);m.style.transform=`translate3d(${Le.x}px, ${Le.y}px, 0)`},H=N.payload.source.getBoundingClientRect();C(H.left+I,H.top+D);const P=ce=>{C(ce.clientX,ce.clientY)};document.addEventListener("pointermove",P),M=P},W=()=>{M&&(document.removeEventListener("pointermove",M),M=null),O&&(O.remove(),O=null)},U={id:`os-files-canvas-${t}`,element:e,accept:N=>{if(N.type!=="desktop-file"&&N.type!=="shortcut")return yM(N,{folderId:t,host:e});if(t>0&&N.type==="desktop-file"){const m=N.data;for(const k of to(m)){if(k.file?.type!=="folder")continue;const I=parseInt(k.file.ref,10);if(!Number.isNaN(I)&&zy(I,t))return!1}}return!0},onEnter:N=>{e.setAttribute("data-files-drop-active",""),(N.payload.type==="desktop-file"||N.payload.type==="shortcut")&&b(N)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),W()},onDrop:(N,m)=>{if(e.removeAttribute("data-files-drop-active"),W(),N.payload.type!=="desktop-file"&&N.payload.type!=="shortcut"){vM(N,m,{folderId:t,host:e});return}const k=s.getBoundingClientRect(),I=N.payload.ghost,D=I?.offsetX??0,$=I?.offsetY??0,x=Math.max(0,m.clientX-k.left-D),C=Math.max(0,m.clientY-k.top-$),H=se.getState().placementsByFolder.get(t)??[];if(N.payload.type==="desktop-file"){const P=N.payload.data,ce=to(P),z=new Set(ce.map(ye=>ye.id)),ee=fr(H,z),le=Mt(x,C,ee,o,n);ee.add(Ie(le.col,le.row));for(const ye of ce){let De=le;if(ye.id!==P.placement.id){const Le=ye.x-P.placement.x,Rs=ye.y-P.placement.y;De=Mt(Math.max(0,le.x+Le),Math.max(0,le.y+Rs),ee,o,n),ee.add(Ie(De.col,De.row))}const Ds={...ye,x:De.x,y:De.y,parentId:t};if(se.upsertPlacement(Ds),A("os.files.tile-manually-placed",{folderId:t,placementId:ye.id}),ur(ye)){const Le=rr(ye);Le&&CM(Le,De.x,De.y);continue}Zn(ye.id,{x:De.x,y:De.y,parentId:t},ye.updatedAtMs).then(Le=>{se.upsertPlacement(Le,"remote")}).catch(Le=>{Oy(Le)?Dy(Le):console.error("[openstation] files: drag persist failed",Le),se.upsertPlacement(ye)})}return}if(N.payload.type==="shortcut"){const P=N.payload.data;jl(lr(P),t,e)}}},j=ws();if(j&&w.push(j.registerDropTarget(U)),w.push(EM({host:e,container:s,folderId:t,fileEntities:(N,m)=>{jl(N,m,m===t?e:null)}})),!se.getState().hydratedFolders.has(t)){const N=kM(t);N&&se.setFolderPlacements(t,N)}h(se.getState()),queueMicrotask(()=>Y());const B=se.subscribe(N=>{h(N),Y()});let V=()=>{};const J=new Promise(N=>{V=N});se.getState().hydratedFolders.has(t)?queueMicrotask(V):xe(t).then(N=>{se.setFolderPlacements(t,N.placements)}).catch(N=>{console.error("[openstation] files: failed to hydrate folder",t,N)}).finally(()=>{V()});const K=N=>{const m=new Set;for(let k=0;k<N;k+=1)m.add(Ie(0,k));return m},T=(N,m)=>{const k=N.slice();switch(m){case"name-asc":k.sort((I,D)=>I.file.title.localeCompare(D.file.title));break;case"name-desc":k.sort((I,D)=>D.file.title.localeCompare(I.file.title));break;case"date-asc":k.sort((I,D)=>I.updatedAtMs-D.updatedAtMs);break;case"date-desc":k.sort((I,D)=>D.updatedAtMs-I.updatedAtMs);break}return k},R=N=>{const m=se.getState().placementsByFolder.get(t);if(!m||m.length===0)return;const k=m.filter(x=>We(x)),I=m.filter(x=>!We(x)),D=T(I,N),$=Ty(D.length,K(k.length),n,o);D.forEach((x,C)=>{const{x:H,y:P}=$[C],ce={...x,x:H,y:P,sortOrder:C};se.upsertPlacement(ce),!ur(x)&&Zn(x.id,{x:H,y:P,sortOrder:C}).catch(z=>{console.error("[openstation] files: sort persist failed",z)})})},Y=()=>{const N=se.getState().placementsByFolder.get(t);if(!N||N.length===0)return;const m=ms(o),k=m.width>0?m.width:1/0,I=m.height>0?m.height:1/0;if(!N.some(H=>H.x+Ay>k||H.y+Cy>I))return;const $=N.filter(H=>We(H)),x=N.filter(H=>!We(H)),C=Ty(x.length,K($.length),n,o);x.forEach((H,P)=>{const ce=s.querySelector(`[data-placement-id="${H.id}"]`);ce&&on(ce,C[P].x,C[P].y)})};let X=ms(o),oe=null;return typeof ResizeObserver<"u"&&(oe=new ResizeObserver(()=>{const N=ms(o);N.width===X.width&&N.height===X.height||(X=N,Y())}),oe.observe(e)),{host:e,folderId:t,onSelectionChange(N){return a.add(N),()=>{a.delete(N)}},onSelectionChanged(N){return l.add(N),()=>{l.delete(N)}},getSelection:d,selectAll:()=>c.model.selectAll(),clearSelection:()=>c.model.clear(),sort:R,reflow:Y,hydrated:J,dispose(){B(),oe?.disconnect(),oe=null;for(const N of w)try{N()}catch{}w.length=0;for(const N of E.values())try{N()}catch{}E.clear();for(const N of S.values())try{N()}catch{}S.clear(),c.destroy(),a.clear(),l.clear(),s.remove()}}}function IM(e){if(e.length===0)return"0";const t=[];for(const n of e)t.push(`${n.id}:${n.parentId}:${n.x}:${n.y}:${n.sortOrder}:${n.updatedAtMs}:${n.file.type}:${n.file.ref}:${n.file.title}:${n.file.icon}:${We(n)?1:0}`);return t.join("|")}function We(e){return!!e.file.pinned}function ur(e){return tM(e)}const AM="desktop-mode-recycle-bin";function Gy(e){return!(e.file?.type==="folder"||e.file?.ref===AM)}function fr(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,a)=>{const l=We(r)?0:1,c=We(a)?0:1;return l-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(We(r))s.add(Ie(0,i)),i+=1;else{const a=hs(r.x,r.y);s.add(Ie(a.col,a.row))}return s}function jl(e,t,n){const o=se.getState().placementsByFolder.get(t)??[],s=fr(o),i=dr(t);for(const r of e){const a=cr(s,i,Fy(n,t));s.add(Ie(a.col,a.row)),ds({parentId:t,type:r.kind,ref:r.ref,x:a.x,y:a.y}).then(l=>{se.upsertPlacement(l),A("os.files.shortcut-dropped",{folderId:t,placement:l})}).catch(l=>{console.error("[openstation] shortcut drop failed:",l)})}}function zy(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=se.getState();for(const a of o.placementsByFolder.values())for(const l of a){if(l.file?.type!=="folder")continue;const c=parseInt(l.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,l.parentId)}const s=new Set;let i=t,r=256;for(;i>0&&r-- >0;){if(i===e||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function CM(e,t,n){const o=window.wp?.os;if(!o?.getOsSettings||!o?.updateOsSettings)return;const s=o.getOsSettings().dockPromotedPositions??{};o.updateOsSettings({dockPromotedPositions:{...s,[e]:{x:t,y:n}}})}function LM(e,t,n,o){const s=Array.from(t.querySelectorAll("[data-placement-id]"));if(s.length!==e.length)return!1;const i=new Map;for(const d of s){const u=d.dataset.placementId??"",f=parseInt(u,10);if(u===""||Number.isNaN(f)&&u!=="-0")return!1;i.set(f,d)}for(const d of e){const u=i.get(d.id);if(!u||u.dataset.fileType!==d.file.type||u.dataset.fileRef!==d.file.ref||u.classList.contains(`${ae}--pinned`)!==We(d))return!1}const r=new Map,a=new Set;let l=0;for(const d of e){if(!We(d))continue;const u=sn(0,l);r.set(d.id,{x:u.x,y:u.y}),a.add(Ie(u.col,u.row)),l+=1}const c=new Map;for(const d of e){if(r.has(d.id))continue;const u=hs(d.x,d.y),f=Ie(u.col,u.row);if(!a.has(f)){a.add(f);continue}const p=Mt(d.x,d.y,a,n,o);a.add(Ie(p.col,p.row)),c.set(d.id,{x:p.x,y:p.y})}for(const d of e){const u=i.get(d.id);if(!u)continue;const f=r.get(d.id)??c.get(d.id)??{x:d.x,y:d.y};on(u,f.x,f.y),Vy(u,d)}return!0}function Vy(e,t){const n=vy(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function jy(e,t,n){const o={placement:n};let s=null;return e.registerDropTarget({id:`os-files-tile-${n.id}-reject`,element:t,get acceptLabel(){return s?Kx(s,o):void 0},accept:i=>(s=i.type,qx(i,o)),onEnter:()=>{t.classList.add(`${ae}--drop-target`)},onLeave:()=>{t.classList.remove(`${ae}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${ae}--drop-target`),Yx(i,r,o)}})}function TM(e,t,n,o){const s={id:`os-files-folder-${n}-tile-${t.dataset.placementId??"?"}`,element:t,accept:i=>{if(i.type!=="desktop-file"&&i.type!=="shortcut")return!1;if(i.type==="desktop-file"){const r=i.data;for(const a of to(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||ur(a))return!1;if(a.file.type==="folder"){const l=parseInt(a.file.ref,10);if(!Number.isNaN(l)&&zy(l,n))return!1}}}return!0},onEnter:()=>{t.classList.add(`${ae}--drop-target`)},onLeave:()=>{t.classList.remove(`${ae}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${ae}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a=se.getState().placementsByFolder.get(n)??[],l=fr(a),c=dr(n);for(const d of to(r)){const u=cr(l,c);l.add(Ie(u.col,u.row)),se.upsertPlacement({...d,x:u.x,y:u.y,parentId:n}),Zn(d.id,{x:u.x,y:u.y,parentId:n},d.updatedAtMs).then(f=>{se.upsertPlacement(f,"remote")}).catch(f=>{Oy(f)?Dy(f):console.error("[openstation] files: move-into-folder persist failed",f),se.upsertPlacement(d)})}return}if(i.payload.type==="shortcut"){const r=i.payload.data;jl(lr(r),n)}}};return e.registerDropTarget(s)}function NM(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=ws();if(!r)return;const l=se.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||l.x,parseFloat(e.style.top)||l.y;const c=o.model.has(String(l.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===l.id)?d:[l];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(l.id)])};document.addEventListener("os.drag.start",f);const p=()=>{document.removeEventListener("os.drag.start",f),document.removeEventListener("pointerup",p)};document.addEventListener("pointerup",p)}if(u.length>1){const f=[],p=()=>{for(const h of f)h.classList.remove(`${ae}--dragging`);f.length=0,document.removeEventListener("os.drag.start",v),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},v=()=>{for(const h of u){const w=e.parentElement?.querySelector(`[data-placement-id="${h.id}"]`);w&&w!==e&&(w.classList.add(`${ae}--dragging`),f.push(w))}};document.addEventListener("os.drag.start",v),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:e,data:{placement:l,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:_M(l)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?Gx(e,u.length):void 0,hint:u.length>1?{accept:`Move ${u.length} items here`,reject:`Can’t drop ${u.length} items here`,neutral:`Moving ${u.length} items`}:void 0}},origin:i})})}function Ky(e,t,n,o){e.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=se.currentPlacement(t);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),a=r.length>0?r:[i],l=_g(a,aM);Xx({x:s.clientX,y:s.clientY},l,{placementIds:a.map(c=>c.id)})})}function qy(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,o=0;for(;n>=1024&&o<t.length-1;)n/=1024,o++;const s=n>=100||o===0?0:1;return`${n.toFixed(s)} ${t[o]}`}const no="os-folder-status-bar";function OM(e,t,n={}){const o=document.createElement("div");o.className=no,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const a=Rt().placementsByFolder.get(t)??[],l=a.filter(p=>p.file.type==="folder").length,c=a.length-l;let d=0;for(const p of a)if(p.file.type==="upload"){const v=Number(p.file.sizeBytes??0);Number.isFinite(v)&&v>0&&(d+=v)}const u={folderId:t,selectedCount:n.selection?.count()??0,totals:{files:c,folders:l,total:a.length,bytes:d}},f=DM(u);RM(o,f)};s();const i=xl(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function DM(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:Xy(n,"file","files")+(t>0?`, ${Xy(t,"folder","folders")}`:"")+(o>0?` (${qy(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=q("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function RM(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,l=typeof r.sort=="number"?r.sort:100;return a!==l?a-l:i.label.localeCompare(r.label)},o=t.filter(i=>(i.align??"start")==="start").sort(n),s=t.filter(i=>i.align==="end").sort(n);e.replaceChildren(),e.appendChild(Yy("start",o)),e.appendChild(Yy("end",s))}function Yy(e,t){const n=document.createElement("div");n.className=`${no}__cluster ${no}__cluster--${e}`;for(const o of t)n.appendChild(xM(o));return n}function xM(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${no}__segment`,n.dataset.segmentId=e.id,t&&(n.type="button",n.addEventListener("click",s=>e.onClick(s))),e.icon){const s=document.createElement("span");s.className=`${no}__icon dashicons ${e.icon.replace(/[^a-zA-Z0-9_-]/g,"")}`,s.setAttribute("aria-hidden","true"),n.appendChild(s)}const o=document.createElement("span");return o.className=`${no}__label`,o.textContent=e.label,n.appendChild(o),n}function Xy(e,t,n){return`${e} ${e===1?t:n}`}const pr="os-icon-canvas-menu";let gs=null,hr=null,Kl=null,ys=null,vs=null;function MM(e,t){t.openOnBackgroundClick;const n=i=>{WM(i.target)||Zy(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(Kl===e&&gs){rn();return}const a=PM(t),l=q("os.icon-canvas.menu",a,t.scope),c=Array.isArray(l)?l:a,d=++o;$s(()=>d===o,()=>$M(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),rn()}}}function WM(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function Zy(e){return e instanceof Element?e.closest(`.${pr}`)!==null:!1}function PM(e){const n=[{id:"sort-by",label:_("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:_("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:_("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:_("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:_("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function Jy(e){return e.slice().sort((t,n)=>{const o=typeof t.sort=="number"?t.sort:100,s=typeof n.sort=="number"?n.sort:100;return o!==s?o-s:t.label.localeCompare(n.label)})}function $M(e,t,n){if(rn(),e.length===0)return;Kl=n;const o=Jy(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(pr),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;for(const r of o){i.set(r.id,r);const a=Qy(s,r);mr(r)&&a.addEventListener("mouseenter",()=>{ev(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,l=i.get(a.id);if(l){if(mr(l)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${l.id}"]`);c&&ev(l,c);return}rn(),l.onClick?.()}}),document.body.appendChild(s),gs=s,nl(s),queueMicrotask(()=>{ys=r=>{Zy(r.target)||rn()},vs=r=>{r.key==="Escape"&&rn()},document.addEventListener("mousedown",ys),document.addEventListener("keydown",vs)})}function Qy(e,t){const n=document.createElement("os-context-menu-option");return n.dataset.menuItemId=t.id,n.setAttribute("value",t.id),t.heading&&n.setAttribute("heading",""),t.disabled&&n.setAttribute("disabled",""),t.icon&&n.setAttribute("icon",UM(t.icon)),mr(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function ev(e,t){if(tv(),!mr(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(pr,`${pr}--flyout`);const o=new Map;for(const s of Jy(e.children??[]))o.set(s.id,s),Qy(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),rn(),r.onClick?.())}),document.body.appendChild(n),hr=n,Ig(n,t)}function mr(e){return Array.isArray(e.children)&&e.children.length>0}function tv(){hr&&(hr.remove(),hr=null)}function rn(){tv(),gs&&(gs.remove(),gs=null),Kl=null,ys&&(document.removeEventListener("mousedown",ys),ys=null),vs&&(document.removeEventListener("keydown",vs),vs=null)}function UM(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const an="os-breadcrumbs";function BM(e,t,n={}){if(e.replaceChildren(),e.classList.add(an),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${an}__back`,s.setAttribute("aria-label",_("Back","desktop-mode")),s.title=_("Back","desktop-mode");const i=document.createElement("span");i.className="dashicons dashicons-arrow-left-alt2",i.setAttribute("aria-hidden","true"),s.appendChild(i),n.backDisabled&&(s.disabled=!0);const r=n.onBack;s.addEventListener("click",()=>{s.disabled||r()}),e.appendChild(s)}const o=document.createElement("nav");o.className=`${an}__crumbs`,o.setAttribute("aria-label",_("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const l=document.createElement("span");l.className=`${an}__sep`,l.setAttribute("aria-hidden","true"),l.textContent="›",o.appendChild(l)}if(!s.onClick){const l=document.createElement("span");l.className=`${an}__crumb ${an}__crumb--current`,l.setAttribute("aria-current","page"),l.textContent=s.label,o.appendChild(l);return}const r=document.createElement("button");r.type="button",r.className=`${an}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}function wr(e){const t=document.createElement("a");t.href=e,t.setAttribute("download",""),t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async function bs(e,t={}){const n=await $e(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":FM(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function FM(){return window.wp?.os?.config?.restNonce??""}function HM(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function Es(e){return it(HM(),e)}function GM(e,t){const n=q("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(zM(e));return}t.replaceChildren(t1()),VM(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(n1(o))})}function zM(e){const t=document.createElement("div");t.className="os-files__access-gated";const n=document.createElement("div");n.className="os-files__access-gated-ring";const o=document.createElement("span");o.className="dashicons dashicons-lock os-files__access-gated-glyph",o.setAttribute("aria-hidden","true"),n.appendChild(o),t.appendChild(n);const s=document.createElement("h2");s.className="os-files__access-gated-title",s.textContent="No permission to view",t.appendChild(s);const i=document.createElement("p");i.className="os-files__access-gated-sub";const r=e.file.title||e.file.type;i.textContent=`You don’t have access to "${r}". The folder owner shared this folder with you, but your role doesn’t include permission to open this item.`,t.appendChild(i);const a=document.createElement("p");return a.className="os-files__access-gated-hint",a.textContent="Ask the owner to grant access on the underlying item, or to remove it from the shared folder.",t.appendChild(a),t}async function VM(e){const t=e.file;switch(t.type){case"post":return jM(t.ref,t);case"folder":return JM(t);case"shortcut":return QM(t);case"attachment":return XM(t.ref,t);case"upload":return ZM(t);case"user":return KM(t.ref,t);case"term":return qM(t);case"comment":return YM(t.ref,t);case"bookmark":return e1(t);default:return nt(t)}}async function jM(e,t){const n=parseInt(e,10);if(!n)return nt(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await bs(Es(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return nt(t);const s=lt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=gr(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="os-my-wordpress__article-meta";const a=[];if(a.push(nv(o.date)),o.status&&o.status!=="publish"&&a.push(o.status),r.textContent=a.join(" · "),s.appendChild(r),o.content?.rendered){const u=document.createElement("div");u.className="os-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const c=document.createElement("os-button");c.setAttribute("variant","secondary"),c.textContent=_("Explore details","desktop-mode"),c.title=_("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),c.addEventListener("click",()=>{const u=typeof t.postType=="string"?t.postType:"post";by({entityId:u==="page"?"pages":"posts",postId:n,postTitle:gr(o.title.rendered)||`#${n}`})}),l.appendChild(c);const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=_("Open in editor","desktop-mode"),d.addEventListener("click",()=>{const u=window.wp?.os?.config?.adminUrl;if(!u)return;const f=`${u}post.php?post=${n}&action=edit`,p=window.wp?.os?.windowManager,h=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${h}-edit-${n}`,url:f,title:gr(o.title.rendered),icon:t.icon})}),l.appendChild(d),s.appendChild(l),s}async function KM(e,t){const n=parseInt(e,10);if(!n)return nt(t);let o=null;try{o=await bs(Es(`desktop-mode/v1/user-stats/${n}`))}catch{return nt(t)}const s=lt("os-my-wordpress__user"),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.profile.avatarUrl){const c=document.createElement("img");c.className="os-my-wordpress__user-avatar",c.src=o.profile.avatarUrl,c.alt="",i.appendChild(c)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");if(a.className="os-my-wordpress__article-title",a.textContent=o.profile.name||t.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const c=document.createElement("div");c.className="os-my-wordpress__user-roles";for(const d of o.profile.roleLabels){const u=document.createElement("span");u.className="os-my-wordpress__user-role",u.textContent=d,c.appendChild(u)}r.appendChild(c)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const c=document.createElement("div");c.className="os-my-wordpress__user-bio",c.textContent=o.profile.description,s.appendChild(c)}const l=document.createElement("div");return l.className="os-my-wordpress__user-stats",l.appendChild(oo(o.counts.posts.total.toLocaleString(),_("Posts","desktop-mode"))),l.appendChild(oo(o.counts.pages.total.toLocaleString(),_("Pages","desktop-mode"))),l.appendChild(oo(o.counts.commentsReceived.toLocaleString(),_("Comments received","desktop-mode"))),s.appendChild(l),s}async function qM(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return nt(e);let o=null;try{o=await bs(Es(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return nt(e)}const s=lt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=o.profile.name||e.title||`#${t}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const l=document.createElement("div");l.className="os-my-wordpress__article-content",l.innerHTML=o.profile.description,s.appendChild(l)}const a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(oo(o.counts.posts.total.toLocaleString(),_("Posts","desktop-mode"))),a.appendChild(oo(o.counts.commentsReceived.toLocaleString(),_("Comments","desktop-mode"))),a.appendChild(oo(o.counts.distinctAuthors.toLocaleString(),_("Authors","desktop-mode"))),s.appendChild(a),s}async function YM(e,t){const n=parseInt(e,10);if(!n)return nt(t);let o=null;try{o=await bs(Es(`desktop-mode/v1/comment-stats/${n}`))}catch{return nt(t)}const s=lt(),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.author.avatarUrl){const d=document.createElement("img");d.className="os-my-wordpress__user-avatar",d.src=o.author.avatarUrl,d.alt="",i.appendChild(d)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");a.className="os-my-wordpress__article-title",a.textContent=o.author.name,r.appendChild(a);const l=document.createElement("p");l.className="os-my-wordpress__article-meta",l.textContent=`${nv(o.comment.date)} · ${o.comment.status}`,r.appendChild(l),i.appendChild(r),s.appendChild(i);const c=document.createElement("div");if(c.className="os-my-wordpress__article-content",c.innerHTML=o.comment.rendered,s.appendChild(c),o.post){const d=document.createElement("div");d.className="os-my-wordpress__comment-post";const u=document.createElement("a");u.className="os-my-wordpress__comment-post-title",u.href=o.post.link,u.target="_blank",u.rel="noopener noreferrer",u.textContent=o.post.title,d.appendChild(u),s.appendChild(d)}return s}async function XM(e,t){const n=parseInt(e,10);if(!n)return nt(t);let o=null;try{o=await bs(Es(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return nt(t)}const s=lt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=gr(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="os-my-wordpress__article-hero";const l=o.media_details?.sizes;a.src=l?.large?.source_url??l?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),l=document.createElement("a");l.href=o.source_url,l.textContent=o.source_url,l.target="_blank",l.rel="noopener noreferrer",a.appendChild(l),s.appendChild(a)}return s}function ZM(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||_("Uploaded file","desktop-mode"),t.appendChild(n);const o=typeof e.mime=="string"?e.mime:"",s=typeof e.sizeBytes=="number"?e.sizeBytes:0,i=typeof e.kind=="string"?e.kind:"file",r=document.createElement("p");r.className="os-my-wordpress__article-meta",r.textContent=[o,s>0?qy(s):""].filter(Boolean).join(" · "),t.appendChild(r);const a=parseInt(e.ref,10),l=()=>{const c=document.createElement("p");return c.className="os-my-wordpress__article-meta os-files__no-preview",c.textContent=_("No preview available for this file type.","desktop-mode"),c};if(a>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=tn(a),c.alt=e.title||"",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="video"){const c=document.createElement("video");c.className="os-my-wordpress__article-hero",c.controls=!0,c.preload="metadata",c.src=tn(a),c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="audio"){const c=document.createElement("audio");c.controls=!0,c.preload="metadata",c.src=tn(a),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else t.appendChild(l());if(a>0){const c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=_("Download","desktop-mode"),d.addEventListener("click",()=>{wr(tn(a))}),c.appendChild(d),t.appendChild(c)}return t}function JM(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||_("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=_("Double-click to open.","desktop-mode"),t.appendChild(o),t}function QM(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||_("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=_("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function e1(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||_("Bookmark","desktop-mode"),t.appendChild(n);const o=typeof e.url=="string"?e.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",t.appendChild(s)}return t}function nt(e){const t=lt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||e.type,t.appendChild(n);const o=document.createElement("p");if(o.className="os-my-wordpress__article-meta",o.textContent=re(_("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="os-my-wordpress__article-meta",s.textContent=_("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function lt(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function oo(e,t){const n=document.createElement("div");n.className="os-my-wordpress__user-stat";const o=document.createElement("span");o.className="os-my-wordpress__user-stat-value",o.textContent=e,n.appendChild(o);const s=document.createElement("span");return s.className="os-my-wordpress__user-stat-label",s.textContent=t,n.appendChild(s),n}function t1(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function n1(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:_("Unknown error.","desktop-mode"),t}function gr(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function nv(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function ov(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=_("Select an item to preview it here.","desktop-mode"),e}function o1(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=re(_("%d items selected","desktop-mode"),e.length),t.appendChild(n);const o=new Map;for(const i of e){const r=i.file?.type||"item";o.set(r,(o.get(r)??0)+1)}const s=Array.from(o.entries()).sort((i,r)=>r[1]-i[1]||i[0].localeCompare(r[0])).map(([i,r])=>`${r} × ${i}`).join(" · ");if(s){const i=document.createElement("div");i.className="os-files-preview__selection-breakdown",i.textContent=s,t.appendChild(i)}return t}const yr="desktop-mode-embed-",s1=800,i1=600,ql=360,Yl=240,vr=16,Xl=new Map;function r1(e,t){const n=e.ref();if(!n)return;const o=window.wp?.os?.windowManager;if(!o)return;const s=t?.placement,i=s?.meta??null,r=s?`${yr}${s.id}`:`${yr}anon-${d1(n)}`,a=i?.name?.trim()??"",l=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:l,icon:e.icon(),minWidth:ql,minHeight:Yl},d=i?.window,u=document.getElementById("os-area"),f=u?he(u):{x:0,y:0,width:window.innerWidth,height:window.innerHeight};if(d&&Number.isFinite(d.width)&&Number.isFinite(d.height)){const{x:p,y:v,width:h,height:w}=l1(d,f);c.x=p,c.y=v,c.width=h,c.height=w}else c.width=Math.min(s1,Math.max(ql,f.width-vr*2)),c.height=Math.min(i1,Math.max(Yl,f.height-vr*2));s&&d&&Xl.set(r,{...d}),o.open(c)}let sv=!1;function a1(){if(sv)return;sv=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(yr))return;const s=o.slice(yr.length),i=parseInt(s,10);if(!i)return;const l=window.wp?.os?.windowManager?.getById?.(o)?.element;if(!l)return;const c={x:l.offsetLeft,y:l.offsetTop,width:l.offsetWidth,height:l.offsetHeight},d=Xl.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(Xl.set(o,c),c1(i,c))};Z(g.WINDOW_DRAG_END,"os-embed-persist",e),Z(g.WINDOW_RESIZE_END,"os-embed-persist",e)}async function c1(e,t){try{const i={...(await xe(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await Zn(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function l1(e,t){const n=Math.max(ql,Math.min(e.width,t.width-vr)),o=Math.max(Yl,Math.min(e.height,t.height-vr)),s=t.x+Math.max(0,t.width-n),i=t.y+Math.max(0,t.height-o),r=Math.max(t.x,Math.min(e.x,s)),a=Math.max(t.y,Math.min(e.y,i));return{x:r,y:a,width:n,height:o}}function d1(e){let t=0;for(let n=0;n<e.length;n++)t=(Math.imul(t,31)+e.charCodeAt(n))%2147483647;return Math.abs(t).toString(36)}function _s(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function iv(e){const t=typeof e.shape.url=="string"?e.shape.url:"";if(!t)return"";try{const n=new URL(t,window.location.href);if(n.protocol!=="http:"&&n.protocol!=="https:")return""}catch{return""}return t}function u1(){Be({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_s()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Be({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_s()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Be({id:"agent-chat",label:_("Agent chat","desktop-mode"),types:["user"],isDefault:!0,sort:5,appliesTo:e=>e.shape.isAgent===!0,handler:{kind:"js",open:e=>{const t=e.shape;ly({id:Number.parseInt(t.ref,10),name:t.title,description:t.agentDescription??"",avatarUrl:t.previewUrl??""},"agents-open")}}}),Be({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_s()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),Be({id:"wp-term-editor",label:"Term editor",types:["term"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>{const[t,n]=e.ref().split(":");return`${_s()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Be({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${_s()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),Be({id:"desktop-mode-upload-download",label:"Download",types:["upload"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);t&&wr(tn(t))}}}),Be({id:"desktop-mode-folder-window",label:"Open folder",types:["folder"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);if(!t)return;const n=window.wp?.os?.windowManager;if(!n)return;const o=`os-folder-${t}`,s=se.getState().folders.get(t),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),l=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:l,icon:e.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window"),Ti("desktop-mode-my-wordpress");const d=[{folderId:t,title:e.title()}];let u=null;const f=document.createElement("header");c.appendChild(f);const p=document.createElement("div");p.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",c.appendChild(p);const v=()=>{const w=d.map((E,S)=>S===d.length-1?{label:E.title}:{label:E.title,onClick:()=>{d.length=S+1,h()}});BM(f,w,{onBack:()=>{d.length<=1||(d.pop(),h())},backDisabled:d.length<=1})},h=()=>{u?.(),u=null,p.replaceChildren();const w=document.createElement("div");w.className="os-folder-window__split",p.appendChild(w);const E=document.createElement("div");E.className="os-folder-window__layer",w.appendChild(E);const S=document.createElement("div");S.className="os-folder-window__preview",S.appendChild(ov()),w.appendChild(S);const O=d[d.length-1],M=Hy(E,O.folderId),b=M.onSelectionChanged(B=>{if(B.length===0){S.replaceChildren(ov());return}if(B.length>1){S.replaceChildren(o1(B));return}GM(B[0],S)}),W=B=>{if(!(B.target instanceof Element))return;const V=B.target.closest(".os-file-tile");if(!V||V.dataset.fileType!=="folder")return;const J=parseInt(V.dataset.fileRef??"",10);if(!J)return;B.preventDefault(),B.stopPropagation();const K=V.querySelector(".os-file-tile__label")?.textContent??`#${J}`;d.push({folderId:J,title:K}),h()};E.addEventListener("dblclick",W,!0);const U=MM(E,{scope:`os-folder:${O.folderId}`,onSort:B=>M.sort(B),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{Hl({onSubmit:async B=>{const V=await Ll({name:B}),J=se.getState().placementsByFolder.get(O.folderId)??[],K=Ny(J),T=Mt(xt,xt,K,E,dr(O.folderId)),R=await ds({type:"folder",ref:String(V.id),parentId:O.folderId,x:T.x,y:T.y});se.upsertFolder(V),se.upsertPlacement(R)}})}}]}),j=OM(p,O.folderId,{selection:{count:()=>M.getSelection().length,subscribe:B=>M.onSelectionChanged(()=>B())}});u=()=>{b(),U.dispose(),j.dispose(),E.removeEventListener("dblclick",W,!0),M.dispose()},v()};h()},width:720,height:480,minWidth:360,minHeight:240})}}}),Be({id:"desktop-mode-shortcut-opener",label:"Open shortcut",types:["shortcut"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=e.shape,n=window.wp?.os;if(n){if(t.shortcutSystemTile&&n.getSystemTile){n.getSystemTile(t.shortcutSystemTile)?.onOpen();return}if(t.shortcutWindow&&n.openWindow){n.openWindow(t.shortcutWindow);return}if(t.shortcutUrl&&n.windowManager)try{const o=new URL(t.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}if(Ze(o.toString()))return;const s=n.config?.adminUrl,i=s?de(o.toString(),s):`desktop-icon-${e.ref()}`,r=Vi(o.toString());n.windowManager.open({id:i,baseId:i,url:o.toString(),parentUrl:r?.url??o.toString(),title:e.title(),icon:e.icon(),submenu:r?.submenu,selfLabel:r?.selfLabel,multi:!!r?.multi})}catch{}}}}}),Be({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=iv(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=iv(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{r1(e,t)}}})}const f1="os-file-associations";let cn=null;function p1(){Kh({id:f1,label:"File Associations",order:50,render(e){cn&&(cn(),cn=null),rv(e),cn=ny(()=>{if(!e.isConnected){cn&&(cn(),cn=null);return}rv(e)})}})}function rv(e){e.replaceChildren();const t=Jg();if(t.length===0){const i=document.createElement("p");i.className="os-file-associations__empty",i.textContent="No file types are registered.",e.appendChild(i);return}const n=document.createElement("p");n.className="os-file-associations__intro",n.textContent="Pick which app opens each kind of file when you double-click it on the desktop.",e.appendChild(n);const o=El(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(h1(i.type,i.label,o));e.appendChild(s)}function h1(e,t,n){const o=document.createElement("div");o.className="os-file-associations__row",o.setAttribute("role","listitem"),o.dataset.fileType=e;const s=document.createElement("label");s.className="os-file-associations__label",s.textContent=t,o.appendChild(s);const i=_l(e);if(i.length===0){const c=document.createElement("span");return c.className="os-file-associations__none",c.textContent="No app available",o.appendChild(c),o}const r=Sl(e),a=n[e]??r?.id??"",l=document.createElement("os-select");l.setAttribute("value",a),l.setAttribute("aria-label",`Default app for ${t}`),l.className="os-file-associations__select",s.htmlFor=`assoc-${e}`,l.id=`assoc-${e}`;for(const c of i){const d=document.createElement("os-option");d.setAttribute("value",c.id),d.textContent=c.isDefault?`${c.label} (default)`:c.label,l.appendChild(d)}return l.addEventListener("os-pick",c=>{const d=c.detail?.value;if(!d)return;const u={...El(),[e]:d};ey(u),py(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(l),o}function m1(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,Ol(t),!0)}function w1(){return window.openStationConfig?.filesOverlaysBundleUrl??""}async function Ss(){if(window.openStationFilesOverlays)return window.openStationFilesOverlays;const e=w1();if(!e)return null;try{await fe(e)}catch(t){return console.warn("[openstation] files-overlays bundle failed to load",t),null}return window.openStationFilesOverlays??null}async function av(...e){await(await Ss())?.openShareSettingsModal(...e)}async function g1(...e){await(await Ss())?.openFileShareModal(...e)}async function y1(...e){return(await Ss())?.openPendingFileInviteModal(...e)}async function v1(...e){return(await Ss())?.openPendingInviteModal(...e)}function b1(...e){Ss().then(t=>t?.openUrlDialog(...e))}function cv(){return Number(window.openStationConfig?.currentUserId??0)}function E1(e){window.wp?.os?.windowManager?.getById?.(e)?.close?.()}function Zl(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function lv(e){const t=Rt().folders.get(e);return t?Number(t.ownerId):0}function dv(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function _1(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function S1(e){return Number(e.file.ownerId??0)}function k1(){yt("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!Zl())return e;const n=_1(t);if(n===null)return e;const o=lv(n)||S1(t),s=cv();if(o===s){const r=!!t.file.shareSummary?.shared?"Manage sharing…":"Share folder…";e.push({id:"desktop-mode/folder-share",label:r,icon:"dashicons-share",sort:30,onClick:()=>{av({folderId:n,folderName:t.file.title||`Folder ${n}`})}})}else o>0&&e.push({id:"desktop-mode/folder-leave",label:"Leave shared folder",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await An({title:"Leave this folder?",message:"The folder will be removed from your desktop. The original and its contents are not deleted; the owner keeps them.",confirmLabel:"Leave",danger:!0}))try{await hy(n),us(t.id);try{const a=await xe(0);nn(0,a.placements)}catch{}const r=`os-folder-${n}`;E1(r),ue({message:"You left the shared folder."})}catch(r){ue({message:`Could not leave: ${r.message}`})}}});return e}),xi({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!Zl())return!1;const t=e.config.baseId??e.id,n=dv(t);return n===null?!1:lv(n)===cv()},onClick:e=>{if(!Zl())return;const t=e.config.baseId??e.id,n=dv(t);n!==null&&av({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),Z("os.files.tile-rendered","desktop-mode/folder-share",e=>{const{tile:t,placement:n}=e;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||t.querySelector(".os-file-tile__share-badge"))return;const s=document.createElement("span");s.className="os-file-tile__share-badge dashicons dashicons-share",s.setAttribute("aria-label","Shared folder"),s.title="Shared folder",s.style.cssText=["position:absolute","top:6px","inset-inline-end:6px","background:rgba(0,0,0,0.55)","color:#fff","border-radius:50%","width:18px","height:18px","font-size:12px","line-height:18px","text-align:center","pointer-events:none"].join(";"),t.appendChild(s)})}let Jl=null;function br(){return Jl||(Jl=ie("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),Jl}function I1(e,t){return e.id===t.id&&e.folderId===t.folderId&&e.capability===t.capability&&e.invitedAtMs===t.invitedAtMs&&e.folderName===t.folderName&&e.fileName===t.fileName&&e.ownerName===t.ownerName}function uv(e){const t=br(),n=new Map(t.state.pending.map(s=>[s.id,s]));let o=!1;for(const s of e){const i=s.targetType==="file"&&typeof s.folderId!="number"?{...s,folderId:0}:s;if(i.targetType==="file"){if(typeof i.fileId=="number"&&t.state.deniedFiles.has(i.fileId))continue}else if(t.state.deniedFolders.has(i.folderId))continue;const r=n.get(i.id);if(r){if(I1(r,i))continue;t.state.pending=t.state.pending.map(a=>a.id===i.id?i:a)}else t.state.pending.push(i);i.invitedAtMs>t.state.sharesVersion&&(t.state.sharesVersion=i.invitedAtMs),o=!0}o&&t.notify()}function Er(e,t={}){const n=br();n.state.pending=n.state.pending.filter(o=>o.id!==e),t.denied&&typeof t.folderId=="number"&&n.state.deniedFolders.add(t.folderId),t.denied&&typeof t.fileId=="number"&&n.state.deniedFiles.add(t.fileId),n.notify()}const fv=new Set;function A1(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function C1(){const e=br(),t=n=>{if(A1()){for(const o of n.pending)if(!fv.has(o.id)){if(fv.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;y1({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?Er(o.id):i==="denied"&&Er(o.id,{denied:!0,fileId:s})});continue}v1({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Er(o.id):s==="denied"&&Er(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function L1(){return Number(window.openStationConfig?.currentUserId??0)}function pv(){return window.openStationConfig?.desktopStorage??{}}function T1(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function N1(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function O1(){yt("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&pv().zipAvailable){const i=Number(t.file.ref);return Number.isFinite(i)&&i>0&&e.push({id:"desktop-mode/folder-zip-download",label:"Download as .zip",icon:"dashicons-download",sort:45,onClick:()=>{wr(wy(i))}}),e}const n=N1(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{wr(tn(n))}});const o=Number(t.file.ownerId??0),s=L1();return o===s&&T1()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{g1({fileId:n,fileName:t.file.title||`File ${n}`})}}):o>0&&o!==s&&t.parentId===0&&e.push({id:"desktop-mode/upload-leave",label:"Leave shared file",icon:"dashicons-exit",sort:80,danger:!0,onClick:async()=>{if(await An({title:"Leave this shared file?",message:"The file will be removed from your desktop. The owner keeps the original.",confirmLabel:"Leave",danger:!0}))try{await my(n),us(t.id);try{const r=await xe(0);nn(0,r.placements)}catch{}ue({message:"You left the shared file."})}catch(r){ue({message:`Could not leave: ${r.message}`})}}}),e}),yt("os.wallpaper-context-menu","desktop-mode/uploads",e=>(pv().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>hv(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>hv(!0)})),e))}function hv(e){const t=document.createElement("input");t.type="file",e?t.setAttribute("webkitdirectory",""):t.multiple=!0,t.style.display="none",document.body.appendChild(t),t.addEventListener("change",()=>{const n=t.files?Array.from(t.files):[];t.remove(),n.length!==0&&D1(n,e)}),t.click()}async function D1(e,t){const n=window.openStationConfig?.fileDropBundleUrl;if(n){try{await fe(n)}catch{ue({message:"Upload machinery failed to load — try again."});return}await window.openStationFileDrop?.routePickedFiles(e,t)}}ux(),u1(),a1(),p1(),m1(),k1(),O1();const Ql=window.openStationConfig?.serverPendingShares;Array.isArray(Ql)&&Ql.length>0&&uv(Ql),C1();const Fe={DesktopFile:Zg,registerType:Ve,unregisterType:sx,getType:ix,getTypes:Jg,resolve:Dt,subscribe:rx,registerOpener:Be,unregisterOpener:ax,getOpener:cx,getOpeners:ty,getOpenersForType:_l,resolveOpener:Sl,subscribeOpeners:ny,getUserAssociations:El,open:cs,registerTilePayloadHandler:Pl,rest:xx,store:{get:tt,getState:Rt,subscribe:xl,setFolderPlacements:nn,upsertPlacement:Nl,removePlacement:us,setFolders:Ol,upsertFolder:Dl,removeFolder:Rl}},mv="__synthFromDockItem";function R1(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function x1(e,t){const n=!!e.tile,o=t[e.id];return{id:R1(e.id),parentId:0,x:o?o.x:0,y:o?o.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[mv]:e.id},file:{type:"shortcut",ref:n?e.id:`dock-promoted:${e.id}`,title:e.title,icon:e.icon,previewUrl:"",exists:!0,...n?{shortcutSystemTile:e.id}:{shortcutUrl:e.menu?.url??""}}}}let ed=!1;const td=new Map;function M1(e){const t=window.wp?.os;if(!t?.getOsSettings||!t?.updateOsSettings)return;const o={...t.getOsSettings().dockPromotedPositions??{}};let s=!1;for(const i of e)i in o&&(delete o[i],s=!0);s&&t.updateOsSettings({dockPromotedPositions:o})}function W1(e,t,n={}){if(!ed){ed=!0;try{const s=Fe.store.getState().placementsByFolder.get(0)??[],i=new Set(e.map(d=>d.id)),r=new Map;for(const d of s){const u=d.meta&&typeof d.meta=="object"?d.meta[mv]:null;typeof u=="string"&&r.set(u,d)}const a=new Set;for(const d of t)d.entry&&a.add(d.entry.id);const l=new Map;for(const d of s){const u=d?.file?.ref;typeof u=="string"&&a.has(u)&&l.set(u,d)}for(const d of e)d.entry||r.has(d.id)||Fe.store.upsertPlacement(x1(d,n));const c=[];for(const[d,u]of r)i.has(d)||(Fe.store.removePlacement(u.id),n[d]&&c.push(d));c.length>0&&M1(c);for(const d of t){const u=d.entry;if(!u)continue;const f=l.get(u.id);if(!i.has(d.id)){f&&(td.set(u.id,f),Fe.store.removePlacement(f.id));continue}if(!f){const p=td.get(u.id);p&&(Fe.store.upsertPlacement(p),td.delete(u.id))}}}finally{ed=!1}}}function P1(e){queueMicrotask(e);const t=Fe.store.subscribe(e),n="desktop-mode/shortcuts-sync";return Z(g.DOCK_ITEM_APPENDED,n,e),()=>{t(),ao(g.DOCK_ITEM_APPENDED,n)}}const _r="os-note-created",$1="openstation_notes";function U1(e){if(!e.bundleUrl)return()=>{};let t=null;const n=[];let o=null;const s=()=>(t||(t=fe(e.bundleUrl).then(()=>{const a=window.openStationNotes;if(!a)return null;const l=a.boot({host:e.host,config:e.config,onError:e.onError});document.removeEventListener(_r,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(ke.START,r);for(const c of n.splice(0))document.dispatchEvent(c);return l}).catch(a=>(t=null,console.warn("[openstation] notes bundle failed to load",a),null))),t),i=a=>{n.push(new CustomEvent(_r,{detail:a.detail})),s()};document.addEventListener(_r,i);const r=()=>{s()};return window.addEventListener("dragstart",r,!0),document.addEventListener(ke.START,r),yt("os.wallpaper-context-menu","desktop-mode/notes-sentinel",(a,l)=>{if(!Array.isArray(a)||a.some(u=>u.id==="new-note"))return a;const{x:c,y:d}=l??{x:0,y:0};return[...a,{id:"new-note",label:_("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{s().then(u=>{if(!u)return;const f=u.normalizedFromClient(c,d);u.createNoteAt({...f,focus:!0})})}}]}),e.hasNotes?(typeof requestIdleCallback=="function"?requestIdleCallback:l=>window.setTimeout(l,200))(()=>void s()):o=Oe.subscribe($1,a=>{a&&(o?.(),o=null,s())}),()=>{document.removeEventListener(_r,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(ke.START,r),o?.(),o=null}}const B1={id:"clock",get label(){return _("Clock")},get description(){return _("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("os-widget-clock");const t=document.createElement("div");t.className="os-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="os-widget-clock__date",e.appendChild(n);const o=()=>{const a=new Date;t.textContent=a.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=a.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})};o();const s=1e3-Date.now()%1e3;let i=null;const r=window.setTimeout(()=>{o(),i=window.setInterval(o,1e3)},s);return()=>{window.clearTimeout(r),i!==null&&window.clearInterval(i)}}};function F1(){Wc(B1)}async function H1(){const e=window;if(e.openStationReleaseCard)return e.openStationReleaseCard;const t=e.openStationConfig?.releaseCardBundleUrl??"";if(!t)return null;try{await fe(t)}catch{return null}return e.openStationReleaseCard??null}function wv(e,t){if(t){const o=_('WordPress %1$s "%2$s" is available.');return re(o,e,t)}const n=_("WordPress %s is available.");return re(n,e)}async function G1(e){const{update:t,openUrl:n}=e;if(!t||typeof t.version!="string"||!t.version||typeof t.url!="string"||!t.url)return;const o=t.version,s=typeof t.branch=="string"&&t.branch?t.branch:o,i=t.crossing===!0,a=`desktop-mode/core-update:${typeof t.available=="string"&&t.available?t.available:o}`;if(Ui(a))return;const l=`${a}:no-art`,c=()=>n({url:t.url,title:_("WordPress Updates")}),u=e.resolveArt&&e.loadImage&&e.showCard?null:await H1(),f=e.resolveArt??u?.resolveReleaseArt,p=e.loadImage??u?.preloadImage,v=e.showCard??u?.showReleaseCard,h=f?await f(s,i):null;if(h&&h.artUrl&&p&&v&&await p(h.artUrl)){v({message:wv(o,i?h.name:""),artUrl:h.artUrl,dismissKey:a,onUpdate:c});return}Ui(l)||ue({message:wv(o,""),persistent:!0,dismissible:!0,onDismiss:()=>Bi(l),action:{label:_("Update now"),onClick:c}})}function gv(e){const{notices:t,openUrl:n,keyPrefix:o="core-notice"}=e;if(Array.isArray(t))for(const s of t){if(!s||typeof s.id!="string"||!s.id||typeof s.message!="string"||!s.message)continue;const i=`desktop-mode/${o}:${s.id}`;if(Ui(i))continue;const r=s.actionLabel,a=s.actionUrl,l=s.title||r||"";let c;r&&a&&(c={label:r,onClick:()=>n({url:a,title:l})}),ue({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>Bi(i),action:c})}}const nd="desktop-mode/starter",z1="desktop-mode/dev-mode-gate";let yv=!1;function V1({osSettings:e,layer:t}){if(yv)return;yv=!0,yt(g.WIDGETS,z1,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==nd));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(nd):t.unmount(nd),Ko())})}function j1(e){const{layer:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await fe(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter,deps:c.scriptDeps})}catch(d){A(g.SHELL_ERROR,{scope:"widget-script-load",id:c.id,error:d});return}o.add(c.scriptUrl)}},i=c=>(window.openStationWidgets||{})[c]??null,r=c=>({id:c.id,label:c.label,description:c.description,icon:c.icon,movable:c.movable,resizable:c.resizable,minWidth:c.minWidth||void 0,minHeight:c.minHeight||void 0,maxWidth:c.maxWidth||void 0,maxHeight:c.maxHeight||void 0,defaultWidth:c.defaultWidth||void 0,defaultHeight:c.defaultHeight||void 0,mount:async(d,u)=>{await s(c);const f=i(c.id);if(!f){const p=new Error(`[openstation] No mount callback on window.openStationWidgets["${c.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`);throw A(g.SHELL_ERROR,{scope:"widget-missing-mount",id:c.id,error:p}),p}return f(d,u)}}),a=async c=>{if(n.has(c.id))return;const d=r(c);try{Wc(d)}catch(u){A(g.SHELL_ERROR,{scope:"widget-register",id:c.id,error:u});return}n.add(c.id),Ko(),t&&t.mountIfEnabled(c.id)},l=c=>{n.has(c)&&(t?.unmount(c),fT(c),n.delete(c),Ko())};return async c=>{const d=new Set;for(const u of c)d.add(u.id);for(const u of Array.from(n))d.has(u)||l(u);for(const u of c)n.has(u.id)||await a(u)}}const vv=new Set(nr),K1=2e3,od=new Set,bv=new WeakSet;let Ev=!1;function q1(e,t){const n=e.length,o=t.length;if(n===0)return o;if(o===0)return n;const s=new Array(o+1);for(let i=0;i<=o;i++)s[i]=i;for(let i=1;i<=n;i++){let r=s[0];s[0]=i;for(let a=1;a<=o;a++){const l=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=l}}return s[o]}function Y1(e){let t=null,n=1/0;for(const o of vv){const s=q1(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function X1(e){return e.startsWith("os-")?e.slice(4):e}function Z1(e,t){if(od.has(e))return;if(od.add(e),vv.has(e)){const s=X1(e);console.error(`[wp.os] <${e}> is in the DOM but its module was never imported, so the tag will not upgrade and the component will render as inert HTML.
40
41 Fix — side-effect-import the component module from wherever you render it:
42
43 import '<rel>/ui/components/${s}/${s}';
44
45 Or pull every os-* component in one go (heavier — only do this from an entry bundle):
46
47 import '<rel>/ui/components';
48
49 See docs/components-reference.md for the full list.`,`
50 First offending element:`,t);return}const o=Y1(e);if(o){console.error(`[wp.os] <${e}> is not a registered os-* component. Did you mean <${o}>?
51
52 If the typo is in your template, update it. If you meant to ship a new component, register it via 'src/ui/components/<name>/<name>.ts' and add it to 'src/ui/components/tags.ts' + 'src/ui/components/index.ts'.`,`
53 First offending element:`,t);return}console.error(`[wp.os] <${e}> looks like a os-* tag but no component by that name exists.
54
55 See 'src/ui/components/index.ts' (or docs/components-reference.md) for the canonical list. If you intended to register a new component, add it to 'tags.ts' and side-effect-import its module.`,`
56 First offending element:`,t)}function _v(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||od.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||Z1(t,e)},K1)}function Sv(e){e instanceof Element&&(_v(e),e.shadowRoot&&Sr(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];_v(o),o.shadowRoot&&Sr(o.shadowRoot)}}function Sr(e){if(bv.has(e))return;bv.add(e),Sv(e),new MutationObserver(n=>{for(let o=0;o<n.length;o++){const s=n[o].addedNodes;for(let i=0;i<s.length;i++){const r=s[i];r.nodeType===1&&Sv(r)}}}).observe(e,{childList:!0,subtree:!0})}function J1(){const e=Element.prototype,t=e.attachShadow;if(t.__wpdPatched)return;const n=function(o){const s=t.call(this,o);return s.mode==="open"&&Sr(s),s};n.__wpdPatched=!0,e.attachShadow=n}function Q1(){Ev||typeof document>"u"||(Ev=!0,J1(),Sr(document))}const kv={appearance:{radius:56,bodyColor:789263,bodyAlpha:1,hueStart:296.5,hueSpan:-52.5,hueAngle:225,hueDrift:0,hueSpin:0,hueLoop:!0,saturation:1,lightness:.75,iridescence:0,outlineWidth:4,linerWidth:2,linerColor:16776191,glow:10,glowBlur:!0,eyeColor:16776191,eyeScale:.3},physics:{points:12,shapePreset:"blob",shapeLobes:3,shapeAmount:1,shapeAngle:0,shapeShuffle:60,radialStiffness:460,edgeStiffness:540,bendStiffness:170,pressure:2400,damping:9,airDamping:.5,magnetStrength:2200,magnetRange:260,magnetGrip:.24,magnetDamping:7,floatAmplitude:10,floatSpeed:1.1,idleWobble:.085,idleWobbleSpeed:.55,speedStretch:.3,friction:.86,restitution:.2,dragStiffness:480,throwBoost:1,minStretch:.55,maxStretch:1.7,minAngularGap:.25,limitIterations:3,dragMaxAccel:9e3,subStep:1/240,maxSubSteps:8}},te={radius:[16,220],bodyAlpha:[0,1],hueStart:[-720,720],hueSpan:[-360,360],hueDrift:[-180,180],hueAngle:[-360,360],hueSpin:[-180,180],saturation:[0,1],lightness:[.15,1],iridescence:[0,2],outlineWidth:[.5,24],linerWidth:[0,12],glow:[0,20],eyeScale:[.05,.6],points:[12,128],shapeLobes:[0,8],shapeAmount:[0,1.4],shapeAngle:[-360,360],shapeShuffle:[0,3600],radialStiffness:[0,2e3],edgeStiffness:[0,4e3],bendStiffness:[0,2e3],pressure:[0,8e3],damping:[0,30],airDamping:[0,20],magnetStrength:[0,8e3],magnetRange:[0,2e3],magnetGrip:[0,.6],magnetDamping:[0,40],floatAmplitude:[0,200],floatSpeed:[0,20],idleWobble:[0,.4],idleWobbleSpeed:[0,8],speedStretch:[0,.8],friction:[0,1],restitution:[0,1],dragStiffness:[1,4e3],throwBoost:[0,4],minStretch:[.1,1],maxStretch:[1,4],minAngularGap:[0,.9],limitIterations:[0,8],dragMaxAccel:[100,2e5],subStep:[1/1e3,1/30],maxSubSteps:[1,32]};function ne(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function sd(e,t){if(typeof e=="number"&&Number.isFinite(e))return Math.min(16777215,Math.max(0,Math.floor(e)));if(typeof e=="string"){const n=e.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{6}$/.test(n))return Number.parseInt(n,16);if(/^[0-9a-fA-F]{3}$/.test(n)){const[o,s,i]=n.split("");return Number.parseInt(`${o}${o}${s}${s}${i}${i}`,16)}}return t}function Iv(e,t){return typeof e=="boolean"?e:t}const eW=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function tW(e,t){return eW.includes(e)?e:t}function ks(e,t=kv){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:ne(o.radius,t.appearance.radius,te.radius),bodyColor:sd(o.bodyColor,t.appearance.bodyColor),bodyAlpha:ne(o.bodyAlpha,t.appearance.bodyAlpha,te.bodyAlpha),hueStart:ne(o.hueStart,t.appearance.hueStart,te.hueStart),hueSpan:ne(o.hueSpan,t.appearance.hueSpan,te.hueSpan),hueDrift:ne(o.hueDrift,t.appearance.hueDrift,te.hueDrift),hueLoop:Iv(o.hueLoop,t.appearance.hueLoop),hueAngle:ne(o.hueAngle,t.appearance.hueAngle,te.hueAngle),hueSpin:ne(o.hueSpin,t.appearance.hueSpin,te.hueSpin),saturation:ne(o.saturation,t.appearance.saturation,te.saturation),lightness:ne(o.lightness,t.appearance.lightness,te.lightness),iridescence:ne(o.iridescence,t.appearance.iridescence,te.iridescence),outlineWidth:ne(o.outlineWidth,t.appearance.outlineWidth,te.outlineWidth),linerWidth:ne(o.linerWidth,t.appearance.linerWidth,te.linerWidth),linerColor:sd(o.linerColor,t.appearance.linerColor),glow:ne(o.glow,t.appearance.glow,te.glow),glowBlur:Iv(o.glowBlur,t.appearance.glowBlur),eyeColor:sd(o.eyeColor,t.appearance.eyeColor),eyeScale:ne(o.eyeScale,t.appearance.eyeScale,te.eyeScale)},r={points:Math.round(ne(s.points,t.physics.points,te.points)),shapePreset:tW(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(ne(s.shapeLobes,t.physics.shapeLobes,te.shapeLobes)),shapeAmount:ne(s.shapeAmount,t.physics.shapeAmount,te.shapeAmount),shapeAngle:ne(s.shapeAngle,t.physics.shapeAngle,te.shapeAngle),shapeShuffle:ne(s.shapeShuffle,t.physics.shapeShuffle,te.shapeShuffle),radialStiffness:ne(s.radialStiffness,t.physics.radialStiffness,te.radialStiffness),edgeStiffness:ne(s.edgeStiffness,t.physics.edgeStiffness,te.edgeStiffness),bendStiffness:ne(s.bendStiffness,t.physics.bendStiffness,te.bendStiffness),pressure:ne(s.pressure,t.physics.pressure,te.pressure),damping:ne(s.damping,t.physics.damping,te.damping),airDamping:ne(s.airDamping,t.physics.airDamping,te.airDamping),magnetStrength:ne(s.magnetStrength,t.physics.magnetStrength,te.magnetStrength),magnetRange:ne(s.magnetRange,t.physics.magnetRange,te.magnetRange),magnetGrip:ne(s.magnetGrip,t.physics.magnetGrip,te.magnetGrip),magnetDamping:ne(s.magnetDamping,t.physics.magnetDamping,te.magnetDamping),floatAmplitude:ne(s.floatAmplitude,t.physics.floatAmplitude,te.floatAmplitude),floatSpeed:ne(s.floatSpeed,t.physics.floatSpeed,te.floatSpeed),idleWobble:ne(s.idleWobble,t.physics.idleWobble,te.idleWobble),idleWobbleSpeed:ne(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,te.idleWobbleSpeed),speedStretch:ne(s.speedStretch,t.physics.speedStretch,te.speedStretch),friction:ne(s.friction,t.physics.friction,te.friction),restitution:ne(s.restitution,t.physics.restitution,te.restitution),dragStiffness:ne(s.dragStiffness,t.physics.dragStiffness,te.dragStiffness),throwBoost:ne(s.throwBoost,t.physics.throwBoost,te.throwBoost),minStretch:ne(s.minStretch,t.physics.minStretch,te.minStretch),maxStretch:ne(s.maxStretch,t.physics.maxStretch,te.maxStretch),minAngularGap:ne(s.minAngularGap,t.physics.minAngularGap,te.minAngularGap),dragMaxAccel:ne(s.dragMaxAccel,t.physics.dragMaxAccel,te.dragMaxAccel),limitIterations:Math.round(ne(s.limitIterations,t.physics.limitIterations,te.limitIterations)),subStep:ne(s.subStep,t.physics.subStep,te.subStep),maxSubSteps:Math.round(ne(s.maxSubSteps,t.physics.maxSubSteps,te.maxSubSteps))};return{appearance:i,physics:r}}const Av="desktop-mode-mio-position",Cv="os-mio",nW="os-mio-toggle",oW=`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
57 <defs><linearGradient id="mio" x1="19" y1="19" x2="5" y2="5" gradientUnits="userSpaceOnUse">
58 <stop offset="0" stop-color="#3f6dff"/><stop offset=".5" stop-color="#a855f7"/><stop offset="1" stop-color="#ff4fd8"/>
59 </linearGradient></defs>
60 <circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/>
61 <rect x="8" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/>
62 <rect x="13.1" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/>
63 </svg>`)}`;class sW{constructor(t){this.layer=null,this.handle=null,this.parked=null,this.generation=0,this.loading=null,this.look=Wa(),this.options=t,this.enabled=t.enabled,this.look=Sp(t.savedLook),this.config=this.resolveConfig()}boot(){this.enabled&&this.mount()}api(){return{isEnabled:()=>this.enabled,enable:()=>this.setEnabled(!0),disable:()=>{this.setEnabled(!1)},toggle:()=>this.setEnabled(!this.enabled),getPosition:()=>this.handle?.getPosition()??null,setPosition:(t,n)=>this.handle?.setPosition(t,n),getConfig:()=>this.config,setConfig:t=>{this.config=ks(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=TI(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=ks({appearance:n.appearance,physics:n.physics},this.config),this.handle?.applyConfig(this.config),this.commitLook()},getLook:()=>({appearance:{...this.look.appearance},physics:{...this.look.physics}}),commitStyle:()=>this.commitLook(),resetStyle:()=>{this.look=Wa(),this.config=this.resolveConfig(),this.handle?.applyConfig(this.config),this.commitLook()}}}async setEnabled(t){t!==this.enabled&&(this.enabled=t,this.generation++,this.options.persist(t),A(t?"os.mio.enabled":"os.mio.disabled",{}),A(g.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount())}resolveConfig(){const t=ks(this.options.serverConfig,kv),n=q("os.mio.config",t),o=ks(n,t);return ks({appearance:this.look.appearance,physics:this.look.physics},o)}commitLook(){this.options.persistLook?.({appearance:{...this.look.appearance},physics:{...this.look.physics}})}ensureLayer(){if(this.layer&&this.layer.isConnected)return this.layer;const t=document.getElementById(Cv);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=Cv,n.className="os-mio",n.setAttribute("aria-hidden","true"),this.options.shell.appendChild(n),this.layer=n,n}async mount(){const t=this.generation;if(this.handle)return;const n=this.parked;if(n){this.parked=null,n.layer.style.removeProperty("display"),n.handle.applyConfig(this.config),n.handle.setAnimating(!0),this.handle=n.handle,this.layer=n.layer;return}try{await this.loadBundle()}catch(i){console.warn("[desktop-mode/mio] bundle failed to load.",i);return}if(t!==this.generation||!this.enabled)return;const o=window.openStationMountMio;if(typeof o!="function"){console.warn("[desktop-mode/mio] bundle loaded but did not publish window.openStationMountMio.");return}const s=await o({host:this.ensureLayer(),config:this.config,position:iW(),savePosition:Lv});if(!s){this.layer?.remove(),this.layer=null;return}if(t!==this.generation||!this.enabled){const i=this.layer;this.layer=null,s.setAnimating(!1),i?(i.style.display="none",this.parked={handle:s,layer:i}):s.destroy();return}this.handle=s}unmount(){const t=this.handle,n=this.layer;if(this.handle=null,this.layer=null,!t||!n){n?.remove();return}const o=t.getPosition();o&&Lv(o),t.setAnimating(!1),n.style.display="none",this.parked={handle:t,layer:n}}loadBundle(){if(typeof window.openStationMountMio=="function")return Promise.resolve();if(!this.loading){if(!this.options.bundleUrl)return Promise.reject(new Error("No Mio bundle URL in the shell config."));this.loading=fe(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function iW(){try{const e=window.localStorage.getItem(Av);if(!e)return null;const t=JSON.parse(e);return typeof t?.x!="number"||typeof t?.y!="number"||!Number.isFinite(t.x)||!Number.isFinite(t.y)?null:{x:t.x,y:t.y}}catch{return null}}function Lv(e){try{window.localStorage.setItem(Av,JSON.stringify(e))}catch{}}const rW='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 4c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8Zm0 1.5c3.4 0 6.2 2.7 6.5 6l-1.2-.6-.8-.4c-.1 0-.2 0-.3-.1H16c-.1-.2-.4-.2-.7 0l-2.9 2.1L9 11.3h-.7L5.5 13v-1.1c0-3.6 2.9-6.5 6.5-6.5Zm0 13c-2.7 0-5-1.7-6-4l2.8-1.7 3.5 1.2h.4s.2 0 .4-.2l2.9-2.1.4.2c.6.3 1.4.7 2.1 1.1-.5 3.1-3.2 5.4-6.4 5.4Z"/></svg>',aW=2400,Tv="os-notch";function cW(e,t){document.getElementById(Tv)?.remove();const n=document.createElement("button");n.type="button",n.id=Tv,n.className="os-notch",n.setAttribute("aria-label",_("Open the site assistant"));const o=document.createElement("span");o.className="os-notch__glyph",o.setAttribute("aria-hidden","true"),o.innerHTML=rW,n.appendChild(o);const s=document.createElement("span");s.className="os-notch__label",s.setAttribute("aria-hidden","true"),s.textContent=_("Site assistant"),n.appendChild(s);const i=document.createElement("span");i.className="os-notch__message",i.setAttribute("aria-live","polite"),n.appendChild(i),n.addEventListener("click",t);let r=null;const a=l=>{r!==null&&window.clearTimeout(r),i.textContent=l,n.classList.add("os-notch--speaking"),r=window.setTimeout(()=>{r=null,n.classList.remove("os-notch--speaking"),window.setTimeout(()=>{n.classList.contains("os-notch--speaking")||(i.textContent="")},200)},aW)};return e.appendChild(n),{say:a,destroy:()=>{r!==null&&window.clearTimeout(r),n.remove()}}}const id="--os-admin-bar-height",lW="wpadminbar";function dW(e){const t=e.getBoundingClientRect();return t.height<=0||t.top<0?null:Math.round(t.bottom*100)/100}function uW(e={}){const t=e.bar===void 0?document.getElementById(lW):e.bar,n=e.root??document.documentElement,o={refresh:()=>{},destroy:()=>{}};if(!t)return o;let s,i=!1;const r=()=>{if(i)return;const c=dW(t);c!==s&&(s=c,c===null?n.style.removeProperty(id):n.style.setProperty(id,`${c}px`))};let a=null;typeof ResizeObserver<"u"&&(a=new ResizeObserver(r),a.observe(t,{box:"border-box"}));let l=null;return typeof MutationObserver<"u"&&document.body&&(l=new MutationObserver(r),l.observe(document.body,{attributes:!0,attributeFilter:["class"]})),window.addEventListener("resize",r),r(),{refresh:r,destroy:()=>{i=!0,a?.disconnect(),l?.disconnect(),window.removeEventListener("resize",r),n.style.removeProperty(id)}}}const fW="New: ",pW=_("Edit this workspace…"),hW=_("New desktop…"),Nv=_("Keep this desk"),Ov=_("Make this workspace open the way the desk is now — these windows where they are, these widgets, these apps.");function mW(e,t,n=()=>{},o=()=>!1){const s=()=>{const i=e.manager.getActiveDesktopId(),r=c=>e.manager.getAll().filter(d=>(d.config.desktopId||i)===c).length,a=c=>c===i?_("You are here"):re(_("%d open"),r(c)),l=e.manager.getDesktops().map(c=>({label:c.label,description:a(c.id),icon:c.profile?.icon||"dashicons-desktop",run:()=>e.manager.switchDesktop(c.id)}));for(const c of bo())l.push({label:`${fW}${c.label}`,description:c.description,icon:c.icon,run:()=>{Ea(e,{preset:c.id})}});return l.push({label:hW,description:_("Blank, or set up for a job — the wizard asks."),icon:"dashicons-plus-alt2",run:n}),l.push({label:pW,description:_("Name, apps, widgets, look and windows."),icon:"dashicons-admin-generic",run:()=>t(e.manager.getActiveDesktopId())}),l.push({label:Nv,description:Ov,icon:"dashicons-saved",run:()=>{o(e.manager.getActiveDesktopId())}}),l};Wn({slug:"keep-desk",label:Nv,description:Ov,icon:"dashicons-saved",run(i,r){if(!o(e.manager.getActiveDesktopId()))return _("There is no desk to keep.");r.close()}}),Wn({slug:"workspace",label:_("Workspace"),description:_("Switch, create or edit a workspace."),hint:"[name]",icon:"dashicons-desktop",suggest(i){const r=i.trim().toLowerCase();return s().filter(c=>!r||c.label.toLowerCase().includes(r)).slice(0,12).map(c=>({value:c.label,label:c.label,description:c.description,icon:c.icon}))},run(i,r){const a=i.trim();if(!a)return _("Type a workspace name to switch to it, or pick a template to create one.");const l=a.toLowerCase(),c=s(),d=c.find(u=>u.label.toLowerCase()===l)??c.find(u=>u.label.toLowerCase().includes(l));if(!d)return re(_("No workspace matching **%s** — try `/workspace` alone to see them all."),a);d.run(),r.close()}})}let Dv=0;function Rv(){return window.openStationWorkspaceWizard??null}function wW(){return window.openStationConfig?.workspaceWizardBundleUrl??""}function xv(e){const t=Rv();if(t){t.openWorkspaceWizard(e);return}const n=wW();if(!n)return;const o=++Dv;fe(n).then(()=>{o===Dv&&Rv()?.openWorkspaceWizard(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] workspace-wizard bundle failed to load; wizard suppressed:",s)})}function gW(e,t,n=()=>({}),o=()=>{},s=()=>!1){return{list:()=>e.manager.getDesktops(),active:()=>{const i=e.manager.getActiveDesktopId();return e.manager.getDesktops().find(r=>r.id===i)??null},getProfile:i=>Ht(e.manager,i),setProfile:(i,r)=>In(e,i,r),create:i=>Ea(e,i),switchTo:i=>e.manager.switchDesktop(i),arrange:i=>mf(e.manager,i),provision:(i,r)=>_a(e,i,r),capture:i=>Sa(e.manager,i),captureAppearance:n,edit:t,openCreator:o,saveDesk:s,presets:bo,registerPreset:df,unregisterPreset:va}}const Mv="desktop-mode/workspace-presets";let kr=null;const ln=new Set;function yW(e){const t=qS.includes(e.layout)?e.layout:"free";return{id:e.id,label:e.label||e.id,description:e.description||"",icon:e.icon||"dashicons-desktop",color:e.color||"",apps:Array.isArray(e.apps)?e.apps.slice():[],widgets:Array.isArray(e.widgets)?e.widgets.slice():[],appearance:hf(e.appearance??{}),windows:Array.isArray(e.windows)?e.windows.map(n=>({...n})):[],layout:t,order:typeof e.order=="number"?e.order:0}}function vW(e){if(!Array.isArray(e))return;const t=new Set(e.map(o=>o.id).filter(Boolean)),n=new Set(bo().filter(o=>!ln.has(o.id)).map(o=>o.id));for(const o of e)!o?.id||n.has(o.id)||(df(yW(o)),ln.add(o.id));for(const o of[...ln])t.has(o)||(va(o),ln.delete(o));kr=t}function bW(){return yt(g.WORKSPACE_PRESETS,Mv,e=>kr?e.filter(t=>ln.has(t.id)||kr?.has(t.id)):e),()=>{wb(g.WORKSPACE_PRESETS,Mv),kr=null;for(const e of ln)va(e);ln.clear()}}function EW(){return document.fullscreenElement!==null}function _W(){if(EW()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function Wv(e){const t=document.createElement("span");return t.className="os-shortcuts__chord",e.forEach((n,o)=>{if(o>0){const i=document.createElement("span");i.className="os-shortcuts__plus",i.textContent="+",t.appendChild(i)}const s=document.createElement("kbd");s.className="os-shortcuts__kbd",s.textContent=n,t.appendChild(s)}),t}function SW(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const c=document.createElement("h2");c.className="os-shortcuts__heading",c.textContent=e.heading,t.appendChild(c)}const n=document.createElement("div");n.className="os-shortcuts__scroller";const o=document.createElement("table");o.className="os-shortcuts__table";const s=e.headers??{},i=["key","outside","inside","showDesktop"],r=document.createElement("thead"),a=document.createElement("tr");for(const c of i){const d=document.createElement("th");d.scope="col",d.textContent=s[c]??"",a.appendChild(d)}r.appendChild(a),o.appendChild(r);const l=document.createElement("tbody");for(const c of e.rows??[]){const d=document.createElement("tr"),u=document.createElement("td");if(u.className="os-shortcuts__key-cell",u.appendChild(Wv(c.keys??[])),c.note){const f=document.createElement("span");f.className="os-shortcuts__note",f.textContent=c.note,u.appendChild(f)}d.appendChild(u);for(const f of["outside","inside","showDesktop"]){const p=document.createElement("td");p.textContent=c[f]??"",d.appendChild(p)}l.appendChild(d)}return o.appendChild(l),n.appendChild(o),t.appendChild(n),t}function kW(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const o=document.createElement("h2");o.className="os-shortcuts__heading",o.textContent=e.heading,t.appendChild(o)}const n=document.createElement("ul");n.className="os-shortcuts__list";for(const o of e.items??[]){const s=document.createElement("li");s.className="os-shortcuts__item",s.appendChild(Wv(o.keys??[]));const i=document.createElement("span");i.className="os-shortcuts__description",i.textContent=o.description??"",s.appendChild(i),n.appendChild(s)}return t.appendChild(n),t}function IW(e){e.innerHTML="";const t=document.createElement("div");t.className="os-shortcuts";const n=window.openStationAdminBar?.shortcuts;if(!n){const o=document.createElement("p");o.className="os-shortcuts__empty",o.textContent="Keyboard shortcuts are unavailable.",t.appendChild(o),e.appendChild(t);return}n.contextual&&t.appendChild(SW(n.contextual)),n.general&&t.appendChild(kW(n.general)),e.appendChild(t)}const rd="openstation-shortcuts",AW=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round"><rect x="5" y="14" width="54" height="36" rx="7"/><path d="M17 26h2M27 26h2M37 26h2M47 26h2M22 39h20"/></svg>')}`;function CW(e){e({id:rd,baseId:rd,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:AW,native:!0,render:IW,width:760,height:560,minWidth:480,minHeight:360})}const Pv="openstation-rebrand",LW=1200,TW="a[href], button:not([disabled])";async function NW(e){const t=e.seenIntrosUrl;if(t)try{await $e(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:Pv})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function OW(){const e=document.createElement("div");e.className="os-announce",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","os-announce-title"),e.setAttribute("aria-describedby","os-announce-desc");const t=document.createElement("div");t.className="os-announce__card",e.appendChild(t);const n=document.createElement("div");n.className="os-announce__hero",t.appendChild(n);const o=document.createElement("span");o.className="os-announce__eyebrow";const s=document.createElement("span");s.className="os-announce__eyebrow-dot",s.setAttribute("aria-hidden","true"),o.appendChild(s),o.appendChild(document.createTextNode(_("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=_("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=_("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",t.appendChild(a);const l=document.createElement("p");l.id="os-announce-desc",l.textContent=_("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),a.appendChild(l);const c=document.createElement("p");c.textContent=_("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=_("Everything is already set up. You don't need to install any new plugins, so you can keep using the same features as before."),a.appendChild(d);const u=document.createElement("div");u.className="os-announce__actions",t.appendChild(u);const f=document.createElement("button");return f.type="button",f.className="os-announce__btn os-announce__btn--primary",f.dataset.rebrandDismiss="",f.textContent=_("Got it"),u.appendChild(f),e}async function DW(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(Pv))return;await new Promise(c=>window.setTimeout(c,LW));const n=OW(),o=n.querySelector(".os-announce__card"),i=document.activeElement;let r=!1;const a=()=>{r||(r=!0,document.removeEventListener("keydown",l,!0),n.remove(),i?.focus?.(),NW(t))};function l(c){if(!n.isConnected){document.removeEventListener("keydown",l,!0);return}if(c.key==="Escape"){c.preventDefault(),a();return}if(c.key!=="Tab")return;const d=Array.from(n.querySelectorAll(TW));if(d.length===0)return;const u=d[0],f=d[d.length-1],p=n.ownerDocument.activeElement;c.shiftKey&&(p===u||!n.contains(p))?(c.preventDefault(),f.focus()):!c.shiftKey&&(p===f||!n.contains(p))&&(c.preventDefault(),u.focus())}n.addEventListener("click",c=>{o&&!o.contains(c.target)&&a()});for(const c of n.querySelectorAll("[data-rebrand-dismiss]"))c.addEventListener("click",a);document.addEventListener("keydown",l,!0),document.body.appendChild(n),n.querySelector(".os-announce__btn--primary")?.focus()}const RW="(display-mode: standalone)";function $v(e,t){return e||t?.standalone===!0?"standalone":"browser"}const xW=["auto","desktop","mobile"],Ir={mobile:767,tablet:1024};function Ar(e){return xW.includes(e)?e:"auto"}function MW(e){const t=e&&typeof e=="object"?e:{},n=(i,r)=>{const a=typeof i=="number"?i:Number(i);return Number.isFinite(a)&&a>0?Math.floor(a):r},o=n(t.mobile,Ir.mobile),s=Math.max(o+1,n(t.tablet,Ir.tablet));return{mobile:o,tablet:s}}function Uv(e,t="auto",n=Ir){return t==="mobile"?"mobile":t==="desktop"?"desktop":e<=n.mobile?"mobile":e<=n.tablet?"tablet":"desktop"}function WW(e={}){const t=e.root??document.documentElement,n=e.win??window,o=MW({...Ir,...e.breakpoints??{}});let s=Ar(e.preference);const i=new Set,r=()=>typeof n.innerWidth=="number"&&n.innerWidth>0?n.innerWidth:Number.POSITIVE_INFINITY;let a=Uv(r(),s,o);bd(t,a);const l=e.nav??(typeof navigator<"u"?navigator:void 0),c=typeof n.matchMedia=="function"?n.matchMedia(RW):null;let d=$v(!!c?.matches,l);Ed(t,d);const u=()=>{d=$v(!!c?.matches,l),Ed(t,d)},f=()=>{const h=Uv(r(),s,o);if(h===a)return;const w={mode:h,previous:a,preference:s};a=h,bd(t,a),A(g.MODE_CHANGED,w),document.dispatchEvent(new CustomEvent("os-mode-changed",{detail:w}));for(const E of i)try{E(w)}catch(S){console.error("[openstation] mode listener threw:",S)}},p=[];if(typeof n.matchMedia=="function")for(const h of[o.mobile,o.tablet]){const w=n.matchMedia(`(max-width: ${h}px)`);typeof w.addEventListener=="function"?w.addEventListener("change",f):typeof w.addListener=="function"&&w.addListener(f),p.push(w)}return c&&(typeof c.addEventListener=="function"?c.addEventListener("change",u):typeof c.addListener=="function"&&c.addListener(u)),{api:{get:()=>a,getPreference:()=>s,getBreakpoints:()=>({...o}),isMobile:()=>a==="mobile",getDisplay:()=>d,isStandalone:()=>d==="standalone",subscribe(h,w){return i.add(h),w?.immediate&&h({mode:a,previous:a,preference:s}),()=>{i.delete(h)}}},setPreference(h){const w=Ar(h);w!==s&&(s=w,f())},dispose(){for(const h of p)typeof h.removeEventListener=="function"?h.removeEventListener("change",f):typeof h.removeListener=="function"&&h.removeListener(f);c&&(typeof c.removeEventListener=="function"?c.removeEventListener("change",u):typeof c.removeListener=="function"&&c.removeListener(u)),i.clear()}}}function PW(e){return Pt(e)||bb(e)}function $W(e={}){const t=e.root??document.documentElement,n=e.doc??document,o=a=>{PW(t)&&a.cancelable&&a.preventDefault()},s=a=>{a.touches?.length>1&&o(a)},i=a=>{a.ctrlKey&&o(a)},r={passive:!1};return n.addEventListener("gesturestart",o,r),n.addEventListener("gesturechange",o,r),n.addEventListener("gestureend",o,r),n.addEventListener("touchmove",s,r),n.addEventListener("wheel",i,r),()=>{n.removeEventListener("gesturestart",o),n.removeEventListener("gesturechange",o),n.removeEventListener("gestureend",o),n.removeEventListener("touchmove",s),n.removeEventListener("wheel",i)}}const dn="openstation/mobile";function UW(e){const t=Array.isArray(e?.windows)?e.windows:[],n=e?.focused??"",o=t.find(s=>s.id===n);return{restore:o?[o]:[],recents:t.filter(s=>s!==o)}}function BW(e){const{manager:t,mode:n}=e,o=new Map,s=new Map;let i=[];const r=new Set,a=()=>{for(const h of r)h()},l=h=>{if(!n.isMobile())return;const w=t.getById(h);if(!(!w||w.isMinimized()||w.isMaximized()||w.isFullscreen())){if(!o.has(w.id)){const E=w.getSnapshot();o.set(w.id,{x:E.x,y:E.y,width:E.width,height:E.height,state:E.state,unplaced:!1})}w.maximize()}},c=h=>{if(!n.isMobile())return;const w=t.getById(h);if(!w)return;const E=t.getActiveDesktopId(),S=w.config.desktopId||E;S!==E&&(s.has(h)||s.set(h,S),t.moveWindowToDesktop(h,E))},d=()=>{if(s.size===0)return;const h=new Set(t.getDesktops().map(S=>S.id));for(const[S,O]of s)h.has(O)&&t.moveWindowToDesktop(S,O);s.clear();const w=t.getActiveDesktopId(),E=t.getFocused();if(E&&(E.config.desktopId||w)!==w){const S=[...t.getAll()].reverse().find(O=>(O.config.desktopId||w)===w&&!O.isMinimized());S&&t.focus(S)}},u=h=>{const w=he();if(w.width<=0||w.height<=0)return null;const E=12,S=Math.min(Math.round(w.width*.8),1200),O=Math.min(Math.round(w.height*.8),800),M=40+h%8*30;return{x:Math.max(w.x+E,Math.min(w.x+M,w.x+w.width-S-E)),y:Math.max(w.y+E,Math.min(w.y+M,w.y+w.height-O-E)),width:S,height:O}};yt(g.WINDOW_GEOMETRY,dn,(h,w)=>!n.isMobile()||h.state==="minimized"?h:(o.set(w.windowId,{x:h.x,y:h.y,width:h.width,height:h.height,state:h.state??"normal",unplaced:!w.hasSavedGeometry&&!w.callerPinned}),{...h,state:"maximized"}));const f=h=>{const w=h?.windowId;w&&l(w)};Z(g.WINDOW_RESTORED,dn,f),Z(g.WINDOW_UNMAXIMIZED,dn,f),Z(g.WINDOW_OPENED,dn,h=>{const w=h?.windowId;w&&(c(w),l(w))}),Z(g.WINDOW_CLOSED,dn,h=>{const w=h?.windowId;w&&(o.delete(w),s.delete(w))});const p=n.subscribe(h=>{if(h.mode==="mobile"){for(const E of t.getAll())c(E.id),l(E.id);return}if(h.previous!=="mobile")return;d();let w=0;for(const E of t.getAll()){const S=o.get(E.id);if(!(!S||!E.isMaximized())){if(S.unplaced){const O=u(w++);O&&(E._savedGeometry=O)}E.toggleMaximize()}}o.clear()});yt(g.SESSION_SNAPSHOT,dn,h=>{const w=new Set(h.windows.map(O=>O.id)),E=h.windows.map(O=>{const M=o.get(O.id),b=s.get(O.id);return!n.isMobile()||!M&&!b?O:{...O,...M?{x:M.x,y:M.y,width:M.width,height:M.height,state:M.state,...M.unplaced?{unplaced:!0}:{}}:{},...b?{desktopId:b}:{}}}),S=i.filter(O=>!w.has(O.id));return S.length?{...h,windows:[...E,...S]}:{...h,windows:E}});const v={list:()=>i.slice(),forget(h){const w=i.filter(E=>E.id!==h);w.length!==i.length&&(i=w,a())},open(h){if(v.forget(h.id),h.native)return t.seedWindowRestoreState({[h.id]:{desktopId:h.desktopId,...h.params?{params:h.params}:{}}}),e.openNative(h.id),void 0;const w=Vi(h.url);t.openNew({id:h.id,baseId:h.baseId||h.id,url:h.url,parentUrl:w?.url??h.url,title:h.title,icon:h.icon||"dashicons-admin-generic",desktopId:h.desktopId,x:h.x,y:h.y,width:h.width,height:h.height,submenu:w?.submenu,selfLabel:w?.selfLabel,multi:!!w?.multi}).then(E=>{for(const S of h.externalTabs??[])E.addExternalTab(S.url,S.label)}).catch(E=>{console.error("[openstation] could not reopen a recent window:",E)})},subscribe(h){return r.add(h),()=>{r.delete(h)}}};return Z(g.WINDOW_OPENED,dn,h=>{const w=h?.windowId;w&&v.forget(w)}),{recents:v,trimSessionForMobile(h){const{restore:w,recents:E}=UW(h.session);return i=E,a(),{...h,session:{...h.session,windows:w}}},forcedIds:()=>Array.from(o.keys()),foldedIds:()=>Array.from(s.keys()),dispose(){p(),r.clear()}}}let Cr=null;function ad(){return window.openStationMobile}function FW(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-mobile="1"]'),s=()=>{const a=ad();if(a){t(a);return}n(new Error("[openstation] mobile bundle loaded but did not set `window.openStationMobile`."))},i=()=>n(new Error("failed to load the mobile bundle"));if(o){ad()?s():(o.addEventListener("load",s),o.addEventListener("error",i));return}const r=document.createElement("script");r.src=e,r.async=!0,r.dataset.osMobile="1",r.addEventListener("load",s),r.addEventListener("error",i),document.head.appendChild(r)})}function HW(e){const t=ad();return t?Promise.resolve(t):e?(Cr||(Cr=FW(e).catch(n=>{throw Cr=null,n})),Cr):Promise.reject(new Error("[openstation] no `mobileBundleUrl` in the shell config — is `mobile[.min].js` built and the config key wired?"))}function GW(e){const{manager:t,adminUrl:n,openNative:o}=e;return s=>{if(s.windowId){const u=t.getById(s.windowId);if(u)return u.isMinimized()&&u.restore(),t.focus(u),!0;if(o(s.windowId))return!0}if(s.tile)return s.tile.onOpen(),!0;const i=s.menu?.url||s.entry?.url||"";if(!i)return!1;if(Co(i)||Ze(i))return!0;let r;try{r=new URL(i,window.location.origin)}catch{return!1}const a=r.toString(),l=de(a,n),c=s.menu??Vi(a)??null,d=s.icon||c?.icon||"dashicons-admin-generic";return t.open({id:l,baseId:l,url:a,parentUrl:c?.url??a,title:s.title,icon:d.startsWith("dashicons-")||d.startsWith("data:")||/^https?:/.test(d)?d:"dashicons-admin-generic",submenu:c?.submenu,selfLabel:c?.selfLabel,multi:!!c?.multi}),!0}}function zW(){return window.wp?.os?.config??{}}async function VW(e,t){const{restUrl:n,restNonce:o}=zW();if(!n||!e||!(t>0))throw new Error("[openstation] trashByRestPath: missing REST config or target.");const s=await $e(it(n,`${e.replace(/\/+$/,"")}/${t}`),{method:"DELETE",credentials:"same-origin",headers:{"X-WP-Nonce":String(o??""),Accept:"application/json"}},{source:"my-wordpress/trash"});if(!s.ok){let i=`Failed to move to trash (${s.status})`;try{const r=await s.json();r?.message&&(i=r.message)}catch{}throw new Error(i)}}const jW=ie("desktop-mode/recycle-bin-payload-handlers",()=>({handlers:new Map}));function Bv(){return jW.state.handlers}function KW(e){const t=Bv().get(e.type);return t?t.accept(e.data):!1}function qW(e,t){const n=Bv().get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}const YW=new Set(["user","attachment"]),cd="data-os-trash-drop-active",un="desktop-mode-recycle-bin",XW=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${un}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${un}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${un}"]`}];let Fv=!1;const ld=new Map;let Is=null,Hv=null;function ZW(e){return e.payload.type==="desktop-file"}function JW(e){return e.payload.type==="shortcut"}function QW(e){if(!e.kind||!e.ref||!e.restPath||YW.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return Number.isFinite(t)&&t>0}function Gv(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:_("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const s=o.data,i=s?.placement;if(!i)return!1;const r=to(s);return r.length>1?r.every(a=>a.file?.ref!==un&&a.canTrash!==!1):i.file?.ref===un?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=lr(s);return i.length>0&&i.every(r=>QW(r))}return KW(o)},onEnter:()=>{n.setAttribute(cd,"")},onLeave:()=>{n.removeAttribute(cd)},onDrop:(o,s)=>{if(n.removeAttribute(cd),ZW(o)){ky(to(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&qW(o,s))&&JW(o)){const r=lr(o.payload.data).map(a=>({restPath:a.restPath,kind:a.kind,ref:Number.parseInt(a.ref,10)})).filter(a=>!!a.restPath&&Number.isFinite(a.ref)&&a.ref>0);if(r.length===0)return;Promise.allSettled(r.map(a=>VW(a.restPath,a.ref))).then(a=>{const l=a.filter(f=>f.status==="rejected");for(const f of l)console.error("[openstation] recycle-bin: shortcut trash failed:",f.reason);const c=r.filter((f,p)=>a[p]?.status==="fulfilled").reduce((f,p)=>{var v;return(f[v=p.kind]??(f[v]=[])).push(p.ref),f},{}),d=window.wp?.os?.announceContentChange;for(const[f,p]of Object.entries(c))d?.(f,"trashed",p,"recycle-bin");const u=r.length-l.length;(u>1||l.length>0)&&ue({message:l.length>0?`${u} moved to Trash · ${l.length} could not be moved`:`${u} items moved to Trash`,duration:l.length>0?6e3:4e3})})}}})}function eP(e){if(Fv)return;Fv=!0;const t=()=>{for(const{id:n,selector:o}of XW){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=ld.get(n);if(!i){r?.deregister(),ld.delete(n);continue}r&&r.el===i||(r?.deregister(),ld.set(n,{el:i,deregister:Gv(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),Z(g.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),Z(g.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){Hv=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;Hv.observe(n,{childList:!0,subtree:!0})}Z(g.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==un)return;Is?.(),Is=null;const o=document.querySelector("[data-os-recycle-bin-root]");o instanceof HTMLElement&&(Is=Gv(e,"recycle-bin-window",o))}),Z(g.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===un&&(Is?.(),Is=null)})}function dd(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function tP(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function zv(e){return{appliesTo(t){return dd(t)!==null},accept(t,n){const o=dd(n);if(!o)return!1;const s=cy({type:e,data:t});return hx(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:_("Send to agent","desktop-mode"),onDrop(t,n,o){const s=dd(o);if(!s)return;const i=cy({type:t.payload.type,data:t.payload.data}),r=tP();!i||!r||yx({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let Vv=!1;function nP(){Vv||(Vv=!0,Pl("shortcut",zv("shortcut")),Pl("desktop-file",zv("desktop-file")))}let jv=!1,fn=0;function oP(){jv||(jv=!0,Oe.contribute("openstation_files_subscribe",()=>{const e=Rt(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:fn,sharesVersion:br().state.sharesVersion}}),Oe.subscribe("openstation_files",e=>{sP(e)}))}function sP(e){const t=e.folders??[];for(const i of t)Dl(i,"remote"),i.updatedAtMs>fn&&(fn=i.updatedAtMs);const n=e.placements??[];for(const i of n)Nl(i,"remote"),i.updatedAtMs>fn&&(fn=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])Rl(i,"remote");for(const i of o.placements??[])us(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>fn&&(fn=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&uv(s),e.truncated){const i=Array.from(Rt().hydratedFolders);for(const r of i)xe(r).then(a=>{nn(r,a.placements)}).catch(()=>{})}}let Kv=!1;const iP=[];function rP(){if(Kv)return;Kv=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||aP()};iP.push(Pn("os.placement.changed",e),Pn("os.shortcut.changed",e),Pn("os.folder.changed",e))}function aP(){uy().then(t=>{Ol(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from(Rt().hydratedFolders);for(const t of e)xe(t).then(n=>{nn(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const As="os-wallpaper-menu";let so=null;function qv(){return so!==null}let Yv=0;function cP(e,t,n,o={}){Cs();const s=++Yv;$s(()=>s===Yv,()=>lP(e,t,n,o))}function lP(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,v=typeof f.sort=="number"?f.sort:100;return p!==v?p-v:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(As),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const l=()=>{r&&(r.remove(),r=null,a=null)};for(const u of n){i.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.heading&&f.setAttribute("heading",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",Xv(u.icon));const p=Array.isArray(u.children)&&u.children.length>0;p&&f.setAttribute("has-children",""),f.textContent=u.label,f.addEventListener("mouseenter",()=>{if(p){c(u,f);return}l()}),s.appendChild(f)}s.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=i.get(f.id)??null;if(p){if(Array.isArray(p.children)&&p.children.length>0){if(u.stopPropagation(),a&&a.id===p.id){l();return}const v=s.querySelector(`[data-menu-item-id="${p.id}"]`);v&&c(p,v);return}Cs(),p.onClick(new MouseEvent("click"))}});function c(u,f){l();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(As,`${As}--flyout`),p.dataset.parentId=u.id;const v=(u.children??[]).slice().sort((h,w)=>{const E=typeof h.sort=="number"?h.sort:100,S=typeof w.sort=="number"?w.sort:100;return E!==S?E-S:h.label.localeCompare(w.label)});for(const h of v){const w=document.createElement("os-context-menu-option");w.dataset.menuItemId=h.id,w.setAttribute("value",h.id),h.icon&&w.setAttribute("icon",Xv(h.icon)),h.disabled&&w.setAttribute("disabled",""),h.checked&&w.setAttribute("checked",""),w.textContent=h.label,w.addEventListener("os-context-menu-pick",E=>{E.stopPropagation(),Cs(),h.onClick(new MouseEvent("click"))}),p.appendChild(w)}document.body.appendChild(p),r=p,a=u,Ig(p,f)}e.appendChild(s),so=s,nl(s);const d=Sg(s,{close:()=>Cs(),siblingSelectors:[`.${As}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),A("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function Cs(){so&&(document.querySelectorAll(`.${As}--flyout`).forEach(e=>e.remove()),so.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),so.remove(),so=null,A("os.wallpaper-menu.closed",{}))}function dP(e){const t=[{id:"create-folder",label:e.labels.createFolder,icon:"dashicons-portfolio",sort:10,onClick:()=>e.createFolder()},{id:"new-url",label:e.labels.newUrl,icon:"dashicons-admin-links",sort:12,onClick:()=>e.createUrl()},{id:"add-widget",label:e.labels.addWidget,icon:"dashicons-screenoptions",sort:15,onClick:()=>e.addWidget()},{id:"sort-by",label:e.labels.sortHeading,icon:"dashicons-sort",sort:16,onClick:()=>{},children:[{id:"sort-name-asc",label:e.labels.sortNameAsc,sort:10,checked:e.currentSortMode==="name-asc",onClick:()=>e.sortIcons("name-asc")},{id:"sort-name-desc",label:e.labels.sortNameDesc,sort:20,checked:e.currentSortMode==="name-desc",onClick:()=>e.sortIcons("name-desc")},{id:"sort-date-desc",label:e.labels.sortDateDesc,sort:30,checked:e.currentSortMode==="date-desc",onClick:()=>e.sortIcons("date-desc")},{id:"sort-date-asc",label:e.labels.sortDateAsc,sort:40,checked:e.currentSortMode==="date-asc",onClick:()=>e.sortIcons("date-asc")}]},...e.includeShowDesktop===!1?[]:[{id:"show-desktop",label:e.labels.showDesktop,icon:"dashicons-desktop",sort:20,onClick:()=>e.toggleShowDesktop()}],{id:"os-settings",label:e.labels.osSettings,icon:"dashicons-admin-generic",sort:30,onClick:()=>e.openOsSettings()}],n=(e.serverItems??[]).map(i=>uP(i,e)),o=[...t,...n],s=q("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function uP(e,t){return{id:e.id,label:e.label,icon:e.icon,sort:e.sort,disabled:e.disabled,onClick:()=>{if(e.callbackId){const n=t.serverCallbacks?.[e.callbackId];if(typeof n=="function")return n()}A("os.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function Xv(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function ud(e){const t=e.dataTransfer?.types;return t?Array.from(t).includes("Files"):!1}function fP(e){if(!e.bundleUrl||Pt())return()=>{};let t=null,n=!1;const o=[],s=()=>{window.removeEventListener("dragenter",r,!0),window.removeEventListener("dragover",a),window.removeEventListener("drop",l)},i=()=>(t||(t=fe(e.bundleUrl).then(()=>{const c=window.openStationFileDrop;if(c){c.boot(e.boot),n=!0,s();for(const d of o.splice(0))c.replayCapturedDrop(d)}}).catch(c=>{t=null,console.warn("[openstation] file-drop bundle failed to load",c),o.length>0&&(o.length=0,ue({message:_("That drop could not be processed — please try again.","desktop-mode")}))})),t),r=c=>{ud(c)&&i()},a=c=>{!n&&ud(c)&&(c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"))},l=c=>{if(n||!ud(c))return;const d=c.defaultPrevented;c.preventDefault(),o.push({files:c.dataTransfer?Array.from(c.dataTransfer.files):[],clientX:c.clientX,clientY:c.clientY,target:c.target,alreadyClaimed:d}),i()};return window.addEventListener("dragenter",r,!0),window.addEventListener("dragover",a),window.addEventListener("drop",l),s}const Zv=[];let fd=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(fd){Promise.resolve().then(o);return}Zv.push(o)}},ready(o){n.whenReady(o)},isReady(){return fd}};t.wp.os=n})();let pd=[],Lr=Number.POSITIVE_INFINITY,hd=!1;function Ke(e,t=1500){if(pd.push(e),t<Lr&&(Lr=t),hd)return;hd=!0;const n=()=>{const o=pd;pd=[],Lr=Number.POSITIVE_INFINITY,hd=!1;for(const s of o)try{s()}catch(i){typeof console<"u"&&console.error("[openstation] scheduleIdleBoot callback threw:",i)}};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(n,{timeout:Lr}):window.setTimeout(n,0)}function Jv(){const e=window.openStationConfig;if(!e)return;const t=document.getElementById("os-area");if(!t)return;const n=zb(window.location.href);if(n)try{window.history.replaceState(window.history.state,"",n)}catch{}n0();const o=new Nk(t),s=document.getElementById("os-wallpaper"),i=e.pluginUrl||"";let r=null;s&&(r=new Ih(s,i));const a=document.getElementById("os-widgets");let l=null;F1(),IA(),a&&(l=new jT(a,i)),Sh({id:"pixijs",url:`${i}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const c=new qA(r??new Ih(document.createElement("div"),i));c.apply();const d=WW({preference:Ar(c.getOsSettingsSnapshot().mobileLayout??e.mode?.preference),breakpoints:e.mode?.breakpoints});c.subscribeOsSettings(y=>{d.setPreference(Ar(y.mobileLayout))}),$W();const u=BW({manager:o,mode:d.api,openNative:y=>x(y)}),f=document.getElementById("os-shell"),p=new sW({shell:f??document.body,bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:c.state.mioEnabled,persist:y=>{c.state.mioEnabled=y,c.save()},savedLook:c.state.mioStyle,persistLook:y=>{c.state.mioStyle=y,c.save()}}),v=p.api();if(!d.api.isMobile())p.boot();else{const y=d.api.subscribe(L=>{L.mode!=="mobile"&&(y(),p.boot())})}l&&V1({osSettings:c,layer:l});const h=new SN({aiSearchUrl:e.aiSearchUrl??"",restNonce:e.restNonce,adminUrl:e.adminUrl,isAiAvailable:()=>e.aiAssistant?.available===!0&&e.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>c.getOsSettingsSnapshot().ai.enabled!==!1},e.aiAssistantBundleUrl??"");h.attachAsk(LN({config:()=>e,fallbackContext:()=>({close:()=>h.close(),openInWindow:(y,L,G)=>{o.open({url:y,title:L,icon:G??"dashicons-admin-generic"})},confirm:y=>An({message:y})})}));const w=new pO,E=new TO;document.addEventListener(ke.START,y=>{const G=y.detail?.payload;if(!G||G.type!=="shortcut"&&G.type!=="desktop-file")return;const F=G.data?.bridgePayload;F&&w.start(F)}),document.addEventListener(ke.END,()=>{w.end()}),Ke(()=>HO(E)),Ke(()=>nD(o)),window.addEventListener("message",y=>{if(y.origin!==window.location.origin)return;const L=y.data;!L||L.type!=="os-drop-failed"||ue({message:"Could not insert into the editor."})}),fg({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>h.open(),close:()=>h.close(),isOpen:()=>h.isOpen}),xk(),cD(),Dk(o),Uk(o),Vk(o,{shouldAsk:()=>c.state.confirmCloseAllWindows,setAsk:y=>{c.state.confirmCloseAllWindows=y,c.save()}}),Ke(()=>{new XL({manager:o,adminUrl:e.adminUrl}).install(),ZL(o);const y=new iT({manager:o,adminUrl:e.adminUrl});y.install(),document.addEventListener(Xm,()=>y.install(),{once:!0})}),document.addEventListener("os-open-ai",()=>{Zc("desktop-mode-ai-assistant")}),document.addEventListener("click",y=>{const L=y.target;!(L instanceof Element)||!L.closest("#wp-admin-bar-command-palette")||(y.preventDefault(),y.stopImmediatePropagation(),Zc("desktop-mode-ai-assistant"))},!0);const S=document.getElementById("os-dock"),O=document.getElementById("os-shell"),M=O?.querySelector(".os-shell__body");let b=null,W=null;const U=(y,L)=>{if(d.api.isMobile()){y.setAppearance?.(null),y.setVisibleWidgets?.(null);return}ba(y,L)},j=(y,L)=>{d.api.isMobile()||_a(y,L)};let B=!1;const V=()=>hf(c.getOsSettingsSnapshot()),J=y=>({presets:bo(),apps:y.getNavItems().map(L=>({id:L.id,title:L.title,kind:L.kind,locked:L.locked,url:L.menu?.url||L.entry?.url||void 0,windowId:L.windowId})),widgets:Pc().map(L=>({id:L.id,label:L.label||L.id,description:L.description})),enabledWidgetIds:l?.getEnabledIds()??[],wallpapers:xa().map(L=>({id:L.id,label:L.label,preview:L.preview})),accents:zs().map(L=>({id:L.id,label:L.label,value:L.value})),resolvePreset:L=>uf(L,y.getNavItems()),captureAppearance:V}),K=()=>{if(!W)return;const y=W;xv({mode:"create",...J(y),onCreate:L=>{Ea(y,{label:L.label||void 0,...L.preset?{preset:L.preset}:{profile:L.profile??void 0}})}})},T=(y=o.getActiveDesktopId())=>{if(!W)return!1;const L=b?.getNav();let G;L&&(G=[...L.dock.core,...L.dock.apps,...L.dock.controls,...L.sidebar,...L.desktop].filter(be=>!L.ephemeral.has(be.id)).map(be=>be.id));const F=ik(W,y,{visibleAppIds:G,mountedWidgetIds:l?.getMountedIds()});if(!F)return!1;const pe=o.getDesktops().find(ve=>ve.id===y)?.label??"",qe=o.getAll().filter(ve=>(ve.config.desktopId||y)===y).length,ot=F.windows.length;let Q;return qe>ot?Q=re(_("%1$s will open like this — the top %2$d of %3$d windows, where they are."),pe,ot,qe):Q=re(_("%1$s will open like this — %2$d windows, where they are."),pe,ot),ue({message:Q}),!0},R=y=>{if(!W)return;const L=o.getDesktops().find(F=>F.id===y);if(!L)return;const G=W;xv({mode:"edit",desktopId:y,label:L.label,profile:L.profile??pf(),...J(G),onSave:F=>{F.label&&o.renameDesktop(y,F.label),In(G,y,F.profile)},captureWindows:()=>Sa(o,y),onDelete:o.getDesktops().length>1?()=>o.closeDesktop(y):void 0})},Y=y=>y.some(L=>!!L.windowId&&o.getAllByBaseIdOnActiveDesktop(L.windowId).length>0),X=iN({manager:o,appendSystemTile:y=>b?.appendSystemTile(y),removeSystemTile:y=>b?.removeSystemTile(y)}),oe=X.sync;Xk({getSnapshot:()=>c.getOsSettingsSnapshot(),openById:(y,L)=>X.openById(y,L),adminUrl:e.adminUrl});const N=y=>{const L=de(y,e.adminUrl),G=b?b.getMenuItems():e.dockItems??[];for(const F of G){if(de(F.url,e.adminUrl)===L)return{title:F.title,icon:F.icon,url:F.url,submenu:F.submenu,selfLabel:F.selfLabel,multi:F.multi};for(const pe of F.submenu??[])if(de(pe.url,e.adminUrl)===L)return{title:pe.title,icon:F.icon,url:F.url,multi:F.multi}}return null},m=fh;if(pk(()=>e.multisite?N0(e.multisite):null),hI({adminUrl:e.adminUrl,deriveSlug:y=>de(y,e.adminUrl),openWindow:y=>{o.open(y)},findDockEntry:N,openOtherAdmin:m}),Ct({id:"desktop-mode-dashboard",nativeWindowId:"desktop-mode-dashboard",matches:(y,L)=>Qk(L),enabled:y=>y.stationHomeEnabled===!0}),Ct({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(y,L)=>{if(!L.pathname.endsWith("/edit.php"))return!1;const G=L.searchParams.get("post_type");return!G||G==="post"},enabled:y=>y.nativePostsEnabled===!0}),Ct({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(y,L)=>L.pathname.endsWith("/edit.php")?L.searchParams.get("post_type")==="page":!1,enabled:y=>y.nativePagesEnabled===!0}),Ct({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(y,L)=>L.pathname.endsWith("/users.php"),enabled:y=>y.nativeUsersEnabled===!0}),Ct({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(y,L)=>{if(Yk(L))return!1;const G=L.pathname;return G.endsWith("/profile.php")?!0:G.endsWith("/user-edit.php")?L.searchParams.has("user_id"):!1},enabled:y=>y.nativeUsersEnabled===!0,params:(y,L)=>{const G=parseInt(L.searchParams.get("user_id")??"0",10);return{userId:G>0?G:0}}}),Ct({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(y,L)=>L.pathname.endsWith("/edit-comments.php"),enabled:y=>y.nativeCommentsEnabled===!0,params:(y,L)=>{const G=parseInt(L.searchParams.get("p")??"0",10);return{post:G>0?G:0}}}),Ct({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(y,L)=>{const G=L.pathname;return G.endsWith("/plugins.php")||G.endsWith("/plugin-install.php")},enabled:y=>y.nativePluginsEnabled===!0,params:(y,L)=>({tab:L.pathname.endsWith("/plugin-install.php")?"browse":"installed"})}),S&&O&&M&&e.dockItems){t.classList.add("os-area--with-dock");const y=c.getOsSettingsSnapshot(),L=y.desktopLayout,G=y.dockPlacement,F=Q=>{_w(t,Q,{openWindow:X.openById,manager:o,deriveWindowId:ve=>de(ve,e.adminUrl)})};b=vN({shellRoot:O,shellBody:M,bottomDockEl:S,desktopArea:t,windowManager:o,adminUrl:e.adminUrl,renderIcons:F,getSettings:()=>{const Q=c.getOsSettingsSnapshot();return{navPlacement:Q.navPlacement,navOrder:Q.navOrder}},getWorkspaceProfile:()=>d.api.isMobile()?null:ek(o)},L,e.dockItems,e.desktopIcons,G),uW(),mS({shell:O,shellBody:M,area:t}),FS(o),AI({shellBody:M,getBehaviors:()=>({dock:c.state.dockBehavior,sidebar:c.state.sideDockBehavior})}),vL({bundleUrl:e.dockConstellationBundleUrl??"",deps:{windowManager:o,adminUrl:e.adminUrl,getMenuItems:()=>b?.getMenuItems()??[],getSystemItem:Q=>b?.getSystemTile(Q)??null}}),cW(O,()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))}),W={manager:o,getNavItems:()=>b?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:Q=>de(Q,e.adminUrl),openNative:X.openById,refreshLayout:()=>b?.refresh(),setVisibleWidgets:Q=>l?.setVisibleIds(Q),setAppearance:Q=>c.setWorkspaceAppearance(Q)},bW(),vW(e.workspacePresets),mW(W,R,K,T),rk({...W,openCreator:K,openEditor:R}),Z(g.DESKTOP_SWITCHED,"desktop-mode/workspace-provision",Q=>{!W||!Q?.to||(U(W,Q.to),j(W,Q.to))});const pe=(Q,ve)=>{if(!W||!ve)return;const be=o.getActiveDesktopId(),Ye=Ht(o,be);if(!Ye||Ye.widgets?.mode!=="only")return;const Ws=QS(Ye,Q,ve);Ws!==Ye&&In(W,be,Ws)};if(Z(g.WIDGET_ADDED,"desktop-mode/workspace-widgets",Q=>pe(Q.id,!0)),W){const Q=o.getActiveDesktopId();U(W,Q),j(W,Q)}const qe=sO(e.pwa?.appName||"WordPress",ue),ot={id:l_,title:"System",icon:u_,navKind:"control",placeable:!0,order:Zs.system,onOpen:()=>k(),get submenu(){const Q=[{title:"OpenStation Preferences",url:"",windowId:vn,onSelect:()=>k()}];return e.homeUrl&&Q.push({title:"View site",url:e.homeUrl}),Q.push({title:"Fullscreen",url:"",onSelect:_W},{title:"Keyboard shortcuts",url:"",windowId:rd,onSelect:()=>CW(ve=>{o.open(ve)})},{title:"Report a bug",url:"",windowId:Qo,onSelect:()=>I()}),!Mw()&&!B&&Q.push({title:qe.title,url:"",onSelect:qe.onOpen}),e.logoutUrl&&Q.push({title:"Log out",url:"",onSelect:()=>{window.location.assign(e.logoutUrl)}}),Q},isOpen:()=>Y(ot.submenu??[])};b.appendSystemTile(ot),Ww().then(Q=>{B=Q})}function k(y={}){const L={extended:"features",effects:"windows"},G=y.tabId?L[y.tabId]:void 0;G&&(y={...y,tabId:G});const F=!!o.getById(vn);X.openById(vn,{source:"os-settings",...y.tabId?{params:{tab:y.tabId}}:{}}),y.tabId&&F&&window.wp?.os?.apps?.local(vn,"tab",{value:y.tabId})}function I(){Ti("desktop-mode-bug-report"),o.open({id:Qo,baseId:Qo,url:`#${Qo}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:y=>KN(y),width:560,height:620,minWidth:420,minHeight:480})}if(document.addEventListener("os-open-bug-report",()=>{I()}),b){if(b.appendSystemTile(p_()),e.multisite){const y=XA(e.multisite,m);y&&b.appendSystemTile(y)}b.appendSystemTile({id:nW,title:"Mio",icon:oW,navKind:"control",placeable:!0,order:Zs.mio,isOpen:()=>v.isEnabled(),onOpen:()=>{v.toggle()}}),b.appendSystemTile({id:c_,title:"Overview",icon:d_,navKind:"control",placeable:!0,order:Zs.overview,isOpen:()=>o._overviewActive,onOpen:()=>{o._overviewActive?o.exitOverview():o.enterOverview()}})}const D=b?.getPrimary()??null;oe(hw(Array.isArray(e.nativeWindows)?e.nativeWindows:[],e.nativeWindowScriptData));const $=aR(e.session);function x(y){return y==="desktop-mode-dashboard"&&c.getOsSettingsSnapshot().stationHomeEnabled!==!0?!1:y===Qo?(I(),!0):X.openById(y)}const C=typeof e.soloWindow=="string"?e.soloWindow:"";C&&queueMicrotask(()=>{if(x(C))return;const y=C.startsWith("os-game-")?C.slice(8):"";if(y){xh.launch(y).catch(L=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",L)});return}typeof console<"u"&&console.error(`[openstation] solo window "${C}" is not registered; nothing to paint.`)});const H=d.api.isMobile()?u.trimSessionForMobile(e):e,P=$&&!C?lR(o,H,t,x).catch(y=>{typeof console<"u"&&console.error("[openstation] session restore failed:",y)}):Promise.resolve(),ce=e.defaultWindow?.enabled!==!1,z=e.defaultWindow?.url??"",ee=typeof z=="string"&&z.startsWith("native:");let le=P;if(!C&&uR({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:$,defaultEnabled:ce,isNativeDefault:ee})&&(le=P.then(()=>dR(o,e).catch(y=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",y)}))),e.landInOverview&&!C&&le.then(()=>{o.enterOverview(),mh()}),!C&&W){const y=W;P.then(()=>{const L=o.getActiveDesktopId();d.api.isMobile()||ok(y,L),U(y,L)})}const ye=gR(o,e);vR(ye);const De=async y=>{try{const L=await pl(o,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:y})},{source:"desktop-mode/default-window"});if(!L.ok)throw new Error(`HTTP ${L.status}`);const G=await L.json();e.defaultWindow=G,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:G}))}catch(L){A(g.SHELL_ERROR,{scope:"default-window-save",error:L}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",L)}};if(o.onToggleStartupRequested=y=>{const L=e.defaultWindow,G=!!y.config.native,F=G?`native:${y.id}`:y.getCurrentUrl(),pe=G?L?.url===F:Sd(L?.url??"")===Sd(F),qe=!!L?.enabled&&pe;De(qe?null:F)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!$&&ee){const y=z.slice(7);queueMicrotask(()=>{x(y)})}const Ds=y=>{b?.appendSystemTile(y)},Le=j1({layer:l});Le(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const Rs=sC({osSettings:c});Rs(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),Z(g.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",y=>{const L=y?.wallpapers;Array.isArray(L)&&Rs(L)});const Qv=rC();Qv(Array.isArray(e.serverGames)?e.serverGames:[]);const eb=FA();eb(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const tb=bC();tb(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const nb=SC();nb(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const ob=LC();ob(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const sb=RC();sb(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const ib=cL();ib(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const rb=pL();rb(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),gL({manager:o,osSettings:c}),N_({osSettings:c}),fI({manager:o}),hL();{let y=!1;Z(g.WINDOW_LINK_GROUPS_CHANGED,"desktop-mode/window-link-visuals-sentinel",()=>{y||(y=!0,Em().then(L=>{L&&window.openStationWindowLinkVisuals?.start({manager:o,osSettings:c})}).catch(()=>{y=!1}))})}PC({manager:o,openUrl:y=>{if(y.windowId&&X.openById(y.windowId,{source:"related-entities",...y.params?{params:y.params}:{}})||!y.url||Ze(y.url))return;const L=de(y.url,e.adminUrl);o.open({id:L,baseId:L,url:y.url,title:y.label,icon:y.icon||"dashicons-admin-links"})}}),YC({manager:o}),sL({manager:o});const ab=yL();ab(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),_L()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),IL(),AL()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),TL()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),Gm(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),FL()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const xs=zL(o);$C(o),Ke(()=>UC()),jk(),Z("os.shell.toast","desktop-mode/shell-toast",y=>{!y||typeof y.message!="string"||ue({message:y.message,action:y.action,duration:y.duration})});const md=e,pP=md.recycleBinCount;DN(Number(pP)||0,typeof md.recycleBinCountUrl=="string"?md.recycleBinCountUrl:""),FN({getRecycleBinCount:ON}),window.__openStationConnectionBridge=xs,Z(g.WINDOW_CLOSED,"desktop-mode/connection-cleanup",y=>{y?.windowId&&xs.onWindowClosed(y.windowId)}),Z(g.IFRAME_READY,"desktop-mode/connection-rearm",y=>{y?.windowId&&xs.onIframeReady(y.windowId)});const hP=eN(o),mP=y=>{if(b){b.applyDesktopIcons(y);return}_w(t,y,{openWindow:X.openById,manager:o,deriveWindowId:L=>de(L,e.adminUrl)})},wd=()=>{b&&W1(b.getNav().desktop,b.getNavItems(),c.getOsSettingsSnapshot().dockPromotedPositions)},wP=rR({layoutDispatcher:b,desktopArea:t,config:e,syncNativeWindows:oe,syncServerWidgets:Le,syncServerWallpapers:Rs,syncServerCommands:tb,syncServerSettingsTabs:nb,syncServerTitleBarButtons:ob,syncServerWindowActions:sb,syncServerUnfocusEffects:ib,syncServerWindowLinkRenderers:rb,syncServerDockRailRenderers:ab,syncServerGames:Qv,syncServerDesktopThemes:eb,renderIcons:mP,refreshRootPlacements:()=>{xe(0).then(y=>{nn(0,y.placements)}).catch(()=>{})},syncShortcuts:wd});document.addEventListener(Zp,()=>{b&&b.setLayout(b.getLayout());for(const y of o._stack)try{y.repaintWindowControls(),y.repaintThemedChrome()}catch(L){A(g.SHELL_ERROR,{scope:"desktop-theme-repaint",id:y.id,error:L})}}),c.subscribeOsSettings(y=>{if(!b)return;const L=b.getLayout(),G=b.getDockPlacement();b.setDockPlacement(y.dockPlacement),b.setLayout(y.desktopLayout),Ms.dock=b.getPrimary(),Ms.sideDock=b.getSide(),Ms.desktopLayout=y.desktopLayout,Ms.dockPlacement=b.getDockPlacement(),L===y.desktopLayout&&G===y.dockPlacement&&b.refresh(),wd(),Xg(y.desktopLayout)}),P1(wd),Xg(c.getOsSettingsSnapshot().desktopLayout);const Ms=tx({manager:o,dock:D,layoutDispatcher:b,osSettings:c,iconsApi:Fc,filesApi:Fe,saveSession:ye,widgetLayer:l,registerWindow:hP,openWindowById:X.openById,openNewWindowById:X.openNewById,loadWindowScriptById:X.loadScriptById,prewarmWindowById:X.prewarmById,placeSystemTile:Ds,setDefaultWindow:De,refreshMenu:wP,openOsSettings:k,aiAssistant:h,dragBridge:w,dragManager:E,connect:xs.connect,getConnection:xs.getConnection,mio:v,mode:d.api,workspaces:gW(W??{manager:o,getNavItems:()=>b?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:y=>de(y,e.adminUrl),openNative:X.openById,refreshLayout:()=>b?.refresh()},R,V,K,T),wallpaperSuspend:{suspend:y=>r?.suspend(y),resume:y=>r?.resume(y),isSuspended:()=>r?.isSuspended()??!1},config:e});nx(Ms);let ro=null,cb=0;const gP=GW({manager:o,adminUrl:e.adminUrl,openNative:x}),lb=()=>{const y=++cb;if(!d.api.isMobile()){ro&&(ro.unmount(),ro=null);return}if(ro||!O)return;const L=O;HW(e.mobileBundleUrl??"").then(G=>{y!==cb||!d.api.isMobile()||ro||(ro=G.mount({manager:o,shell:L,area:t,mode:d.api,getNav:()=>b?.getNav()??null,openNavItem:gP,getBadge:F=>Math.max(F.menu?.badge??0,Fc.getBadge(F.id)),getPinnedTabIds:()=>{const F=c.getOsSettingsSnapshot().mobileTabs;return Array.isArray(F)&&F.length>0?F:e.mode?.tabBar??[]},subscribeNav:F=>{const pe=c.subscribeOsSettings(F);return document.addEventListener("os-layout-changed",F),document.addEventListener("os-registry-changed",F),()=>{pe(),document.removeEventListener("os-layout-changed",F),document.removeEventListener("os-registry-changed",F)}},wallpaper:{suspend:F=>r?.suspend(F),resume:F=>r?.resume(F)},openExternal:F=>{window.open(F,"_blank","noopener")},adminUrl:e.adminUrl,renderIcon:(F,pe)=>Gn(F,pe),getArt:F=>Fc.getArt(F.id)||D?.getArt(F.id)||"",subscribeArt:F=>Ee.subscribe("os/art-changed",()=>F())}))}).catch(G=>{typeof console<"u"&&console.error("[openstation] the phone layer failed to load:",G)})};lb(),d.api.subscribe(lb),d.api.subscribe(y=>{if(y.mode!=="mobile"&&y.previous!=="mobile"||(b?.refresh(),!W))return;const L=o.getActiveDesktopId();U(W,L),j(W,L)}),Ke(()=>eP(E)),Ke(()=>nP()),aC(),k_(),e.gamesEnabled!==!1&&wC({currentUserId:Number(e.currentUserId)||0}),Ke(()=>MD()),Ke(()=>PD()),Ke(()=>XD({currentUserId:Number(e.currentUserId)||0})),U1({bundleUrl:e.notesBundleUrl??"",hasNotes:!!e.hasNotes,host:t,config:e,onError:y=>{ue({message:y})}}),lx({openUrl:({id:y,url:L,title:G,icon:F})=>(Ze(L)||o.open({id:y,baseId:y,url:L,title:G,icon:F}),!0),openNativeWindow:y=>X.openById(y),deriveWindowId:y=>de(y,e.adminUrl)}),ey(e.userFileAssociations??{}),G1({update:e.coreUpdate,openUrl:({url:y,title:L})=>{Ze(y)||o.open({id:"update-core",baseId:"update-core",url:y,title:L,icon:"dashicons-update"})}});const db=({url:y,title:L})=>{if(Ze(y))return;const G=de(y,e.adminUrl);o.open({id:G,baseId:G,url:y,title:L,icon:"dashicons-info"})};if(gv({notices:e.coreNotices,openUrl:db}),gv({notices:e.pluginNotices,openUrl:db,keyPrefix:"plugin-notice"}),DW({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){dy({baseUrl:e.filesUrl,nonce:e.restNonce});const y=document.getElementById("os-area");if(y){const L=Hy(y,0),G=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},F=setTimeout(G,2e3);L.hydrated.then(()=>{clearTimeout(F),G()})}}Ke(()=>oP()),Ke(()=>rP()),Ke(()=>uD()),A(g.COMPONENTS_REGISTERED,{tags:[...nr]}),sD(),cO(e,ue,async()=>{await ye.flush(),window.location.reload()});const ub=()=>{Lb(e.shellOverlaysBundleUrl??""),Ab(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(ub,{timeout:1500}):window.setTimeout(ub,0),A(g.INIT,{config:e}),fd=!0;const yP=Zv.splice(0);for(const y of yP)try{y()}catch(L){A(g.SHELL_ERROR,{scope:"when-ready-cb",error:L}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",L)}if(c.apply(),!d.api.isMobile())l?.hydrate();else{const y=d.api.subscribe(L=>{L.mode!=="mobile"&&(y(),l?.hydrate())})}window.addEventListener("pagehide",()=>{r?.teardownActive(),l?.disposeAll()}),bR(),ZD(o,e);const fb=(y,L=!0)=>{const G=Fe.store.getState().placementsByFolder.get(0)??[],F=y(G),pe=he(t),qe=Math.max(1,Math.floor((pe.height-16)/110)),ot=new Set;let Q=0;for(const ve of F){const be=Mt(16+Math.floor(Q/qe)*96,16+Q%qe*110,ot,pe);ot.add(`${be.col},${be.row}`),Q++,!(ve.x===be.x&&ve.y===be.y)&&(Fe.store.upsertPlacement({...ve,x:be.x,y:be.y,sortOrder:Q}),!(!L||ur(ve))&&Zn(ve.id,{x:be.x,y:be.y,sortOrder:Q}).catch(Ye=>{console.error("[openstation] relayout persist failed",Ye)}))}},pb=y=>L=>{const G=L.slice();switch(y){case"name-asc":G.sort((F,pe)=>F.file.title.localeCompare(pe.file.title));break;case"name-desc":G.sort((F,pe)=>pe.file.title.localeCompare(F.file.title));break;case"date-asc":G.sort((F,pe)=>F.updatedAtMs-pe.updatedAtMs);break;case"date-desc":G.sort((F,pe)=>pe.updatedAtMs-F.updatedAtMs);break}return G},gd="desktop-mode:root-sort-mode",vP=y=>y==="name-asc"||y==="name-desc"||y==="date-asc"||y==="date-desc";let Tr=(()=>{try{const y=window.localStorage.getItem(gd);return vP(y)?y:null}catch{return null}})();const hb=y=>{Tr=y;try{y?window.localStorage.setItem(gd,y):window.localStorage.removeItem(gd)}catch{}};Z("os.files.tile-manually-placed","desktop-mode/root-sort-clear",y=>{y?.folderId===0&&hb(null)});{let y=he(t);const L=()=>{if(!Tr)return;const G=he(t);G.width===y.width&&G.height===y.height||(y=G,fb(pb(Tr),!1))};typeof ResizeObserver<"u"&&new ResizeObserver(L).observe(t),ti(L)}let mb=!1;t.addEventListener("pointerdown",y=>{y.isPrimary&&(mb=y.target===t)}),t.addEventListener("click",y=>{c.state.showDesktopOnWallpaperClick&&y.target===t&&mb&&(t.classList.contains("os-area--overview")||qv()||E.recentlyEndedDrag()||CD()||o.toggleShowDesktop())}),t.addEventListener("contextmenu",y=>{if(y.target!==t)return;y.preventDefault();const L=y.clientX,G=y.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(qv()){Cs();return}const F={x:L,y:G},pe=()=>{const Q=t.getBoundingClientRect(),ve=Math.max(0,F.x-Q.left),be=Math.max(0,F.y-Q.top),Ye=Ny(Fe.store.getState().placementsByFolder.get(0)??[]);return Mt(ve,be,Ye,he(t))},qe=(Q,ve)=>{b1({title:Q,description:ve,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:be,url:Ye})=>{const Ws=pe(),bP=await ds({type:"link",ref:Ye,parentId:0,x:Ws.x,y:Ws.y,meta:be?{name:be}:void 0});Fe.store.upsertPlacement(bP)}})},ot=dP({createFolder:()=>{Hl({onSubmit:async Q=>{const ve=await Ll({name:Q}),be=pe(),Ye=await ds({type:"folder",ref:String(ve.id),parentId:0,x:be.x,y:be.y});Fe.store.upsertFolder(ve),Fe.store.upsertPlacement(Ye)}})},createUrl:()=>qe("New URL","Opens the URL in a new browser tab."),addWidget:()=>l?.openPicker(),toggleShowDesktop:()=>o.toggleShowDesktop(),openOsSettings:()=>k(),sortIcons:Q=>{hb(Q),fb(pb(Q))},currentSortMode:Tr,includeShowDesktop:!c.state.showDesktopOnWallpaperClick,position:{x:L,y:G},labels:{createFolder:"New folder",showDesktop:"Show desktop",osSettings:"OpenStation Preferences",sortHeading:"Sort by",sortNameAsc:"Name (A → Z)",sortNameDesc:"Name (Z → A)",sortDateAsc:"Date (oldest first)",sortDateDesc:"Date (newest first)",newUrl:"New URL",addWidget:"Add widget"},serverItems:e.serverWallpaperMenuItems??[]});cP(document.body,{x:L,y:G},ot)})()}),fP({bundleUrl:e.fileDropBundleUrl??"",boot:{config:e.dropConfig,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.desktopStorage}}),document.dispatchEvent(new CustomEvent("os-init",{detail:{config:e,restored:$}}))}return Q1(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Jv):Jv(),Nr.clampGeometryToViewport=$g,Object.defineProperty(Nr,Symbol.toStringTag,{value:"Module"}),Nr}({});
64