PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.10
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.10
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 0.8.7 All 34 releases
desktop-mode / assets / js / desktop.min.js

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

69 lines 657.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var openStation=function(zr){"use strict";var jr=typeof document<"u"?document.currentScript:null;function Et(){const e=window.wp?.hooks;if(!e)throw new Error("[openstation] `window.wp.hooks` is not available. The plugin declares `wp-hooks` as a script dependency; if you are seeing this error, verify the enqueue order.");return e}function pt(e,t,n,o){Et().addFilter(e,t,n,o)}function ee(e,t,n,o){Et().addAction(e,t,n,o)}function yo(e,t){return Et().removeAction(e,t)}function oE(e,t){return Et().removeFilter(e,t)}function X(e,t,...n){return Et().applyFilters(e,t,...n)}function C(e,...t){Et().doAction(e,...t)}function Hd(e){return Et().didAction(e)}function sE(){return Et()}const y={INIT:"os.init",WALLPAPERS:"os.wallpapers",GAMES:"os.games",UNFOCUS_EFFECTS:"os.unfocus-effects",WINDOW_REVEALS:"os.window-reveals",WALLPAPER_MOUNTING:"os.wallpaper.mounting",WALLPAPER_MOUNTED:"os.wallpaper.mounted",WALLPAPER_UNMOUNTING:"os.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"os.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"os.wallpaper.visibility",WALLPAPER_SUSPEND:"os.wallpaper.suspend",WALLPAPER_PREVIEW_PARAMS:"os.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"os.wallpaper.settings-changed",IFRAME_READY:"os.iframe.ready",IFRAME_ERROR:"os.iframe.error",IFRAME_NETWORK_COMPLETED:"os.iframe.network-completed",SHELL_ERROR:"os.shell.error",BROADCAST:"os.broadcast",MONITOR_ENTRY:"os.monitor.entry",WALLPAPER_SURFACES:"os.wallpaper.surfaces",DESKTOP_THEME_CHANGED:"os.os-theme.changed",DESKTOP_THEME_ICON:"os.os-theme.icon",DESKTOP_THEME_ICON_COLOR:"os.os-theme.icon-color",WALLPAPERS_SERVER_CHANGED:"os.wallpapers.server-changed",EXTENDED_OPTIONS_CHANGED:"os.extended-options.changed",WINDOW_GEOMETRY:"os.window.geometry",WINDOW_OPENED:"os.window.opened",WINDOW_CONTENT_LOADING:"os.window.content-loading",WINDOW_CONTENT_LOADED:"os.window.content-loaded",WINDOW_LOADING_OVERLAY:"os.window.loading-overlay",WINDOW_REOPENED:"os.window.reopened",WINDOW_MENU_OPENED:"os.window.menu-opened",WINDOW_CLOSING:"os.window.closing",WINDOW_CLOSED:"os.window.closed",WINDOW_FOCUSED:"os.window.focused",WINDOW_BLURRED:"os.window.blurred",WINDOW_MINIMIZED:"os.window.minimized",WINDOW_RESTORED:"os.window.restored",WINDOW_CHILD_BLOCKED:"os.window.child-blocked",WINDOW_MAXIMIZED:"os.window.maximized",WINDOW_UNMAXIMIZED:"os.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"os.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"os.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"os.window.auto-exit-fullscreen",WINDOW_FOCUS_ON_DRAG_HOVER:"os.window.focus-on-drag-hover",WINDOW_BOUNDS_CHANGED:"os.window.bounds-changed",WINDOW_MOVED:"os.window.moved",WINDOW_RESIZED:"os.window.resized",WINDOW_DRAG_START:"os.window.drag-start",WINDOW_DRAG_END:"os.window.drag-end",WINDOW_RESIZE_START:"os.window.resize-start",WINDOW_RESIZE_END:"os.window.resize-end",WINDOW_DETACHED:"os.window.detached",WINDOW_RELOADED:"os.window.reloaded",WINDOW_TITLE_CHANGED:"os.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"os.window.highlight-changed",WINDOW_BODY_RESIZED:"os.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"os.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"os.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"os.native-window.before-close",WINDOW_CHROME_THEME:"os.window.chrome.theme",WINDOW_CHROME_CONTROLS:"os.window.chrome.controls",WINDOW_CHROME_SLOT:"os.window.chrome.slot",WINDOW_CHROME_RENDER:"os.window.chrome.render",WINDOW_CHROME_APPLIED:"os.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"os.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"os.os-icon.clicked",DESKTOP_ICONS_RENDERED:"os.os-icons.rendered",ICON_BADGE_CHANGED:"os.icon.badge-changed",COMPONENTS_REGISTERED:"os.components.registered",DOCK_ITEM_APPENDED:"os.dock.item-appended",DOCK_ITEM_REMOVED:"os.dock.item-removed",DOCK_BEFORE_RENDER:"os.dock.before-render",DOCK_AFTER_RENDER:"os.dock.after-render",DOCK_REFRESH_ACTIVE:"os.dock.refresh-active",DOCK_TILE_CLASS:"os.dock.tile-class",DOCK_TILE_ELEMENT:"os.dock.tile-element",DOCK_TILE_RENDERED:"os.dock.tile-rendered",DOCK_TILE_TOOLTIP:"os.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"os.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"os.dock.peek-card-element",CONSTELLATION_PANEL:"os.constellation.panel",CONSTELLATION_OPENED:"os.constellation.opened",CONSTELLATION_CLOSED:"os.constellation.closed",OVERVIEW_ENTERING:"os.overview.entering",OVERVIEW_ENTERED:"os.overview.entered",OVERVIEW_EXITING:"os.overview.exiting",OVERVIEW_EXITED:"os.overview.exited",OVERVIEW_WINDOW_HOVER:"os.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"os.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"os.overview.window-click",WORK_AREA_CHANGED:"os.work-area.changed",ARRANGE_CASCADE_STARTING:"os.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"os.arrange.cascade.applied",ARRANGE_TILE_STARTING:"os.arrange.tile.starting",ARRANGE_TILE_APPLIED:"os.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"os.arrange.tile.dimensions",ARRANGE_COLUMNS_STARTING:"os.arrange.columns.starting",ARRANGE_COLUMNS_APPLIED:"os.arrange.columns.applied",ARRANGE_FOCUS_SPLIT:"os.arrange.focus.split",ARRANGE_FOCUS_STARTING:"os.arrange.focus.starting",ARRANGE_FOCUS_APPLIED:"os.arrange.focus.applied",ARRANGE_SNAP_CHANGED:"os.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"os.arrange.snap.cell-size",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 iE=0;function Gd(e){if(Hd(y.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++iE}`;ee(y.INIT,t,e)}function rE(){return Hd(y.INIT)>0}const Vr="data-os-mode";function zd(e,t){e.getAttribute(Vr)!==t&&e.setAttribute(Vr,t)}function Ht(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(Vr)==="mobile"}const Kr="data-os-display";function jd(e,t){e.getAttribute(Kr)!==t&&e.setAttribute(Kr,t)}function aE(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(Kr)==="standalone"}const cE=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"],qr=[];function lE(e){if(!e.pathname.endsWith("/admin.php")||!e.searchParams.get("page"))return qr;const t=e.searchParams.get("action");return t==="edit"&&e.searchParams.get("id")?["id"]:t==="new"?["action"]:qr}function Vd(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 ue(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=[...cE,...lE(n)];for(const c of a){const d=n.searchParams.get(c);d&&r.set(c,d)}const l=r.toString();return Vd(l?`${i}?${l}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),Vd(o)}function dE(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function uE(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 Kd(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 En(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 qd(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 _n=null;function qs(){return!!window.openStationWindowSystem}function Yd(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(qs()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){qs()?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 fE(){return window.openStationConfig?.windowSystemBundleUrl??""}function pE(e){!e||qs()||_n||(_n=Yd(e).catch(t=>{_n=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function hE(e){if(qs())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 _n||(_n=Yd(e)),await _n,window.openStationWindowSystem}let Sn=null;function vo(){return!!window.openStationShellOverlays}function Xd(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(vo()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){vo()?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 mE(e){!e||vo()||Sn||(Sn=Xd(e).catch(t=>{Sn=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function Yr(e){return vo()||!e?Promise.resolve():(Sn||(Sn=Xd(e)),Sn)}function Xr(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function Ys(e,t){const n=Xr();if(vo()||!n){t();return}Yr(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Zd="desktop-mode";function Zr(){return window.wp?.i18n}function b(e,t=Zd){return Zr()?.__(e,t)??e}function Gt(e,t,n,o=Zd){return Zr()?._n(e,t,n,o)??(n===1?e:t)}function ae(e,...t){const n=Zr()?.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 gE=900,wE=260,Jr="os-desktop-name-hud";let Xe=null,_t=null;function yE(e,t){t.trim()&&(_t!==null&&window.clearTimeout(_t),Xe||(Xe=document.createElement("div"),Xe.className=Jr,Xe.setAttribute("role","status")),Xe.textContent=t,Xe.classList.remove(`${Jr}--out`),e.appendChild(Xe),_t=window.setTimeout(()=>{Xe?.classList.add(`${Jr}--out`),_t=window.setTimeout(()=>{Xe?.remove(),_t=null},wE)},gE))}function vE(){_t!==null&&(window.clearTimeout(_t),_t=null),Xe?.remove(),Xe=null}function bE(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 EE(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 _E(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 Qr(e,t,n=0){const o=e.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,l=34,c=(t.width-r*2-a*(s-1))/s,d=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-l);return e.map((f,p)=>{const g=p%s,h=Math.floor(p/s),m=t.left+r+g*(c+a),E=t.top+n+r+h*(d+a)+l,S=f.element.offsetWidth,R=f.element.offsetHeight,$=Math.min(c/S,u/R),_=S*$,M=R*$;return{win:f,x:m+(c-_)/2,y:E+(u-M)/2,scale:$}})}const SE=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],Jd=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],kE=[...SE,...Jd],Qd={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 eu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function tu(e){return Object.prototype.hasOwnProperty.call(Qd,e)?Qd[e]:null}function IE(e){return tu(e)!==null}function zt(e,t={}){const n=tu(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="${eu(s)}"`),i?a.push('role="img"',`aria-label="${eu(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 nu(e,t={}){const n=zt(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 AE(e,t={}){const n=zt(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const CE=Object.freeze({svg:zt,node:nu,dataUri:AE,names:Object.freeze([...kE]),ours:Object.freeze([...Jd]),has:IE}),LE=120,TE=56;function ou(e){return LE+(e?.querySelector(".os-overview-top-bar__header")?TE:0)}const NE="openstation";function bo(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")===NE}const su=["target","intent","openstation_overview","openstation_hop","openstation_hop_from"];function OE(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!bo(n)||!su.some(o=>n.searchParams.has(o))?null:(su.forEach(o=>n.searchParams.delete(o)),n.href)}const iu="__openStationSharedStores";function DE(){const e=window;let t=e[iu];return t||(t=new Map,e[iu]=t),t}function ie(e,t){const n=DE();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 ru="X-WP-Nonce";function au(e,t){const n=RE();if(!n)return t;const o=xE(e);if(!o||!ME(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(ru)?t:(i.set(ru,n),{...t??{},headers:i})}function RE(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function xE(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 ME(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Le(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=au(e,t);return fetch(e,s)}const Eo=ie("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),ht=Eo.state.registry,ea=Eo.state.listeners,WE=/^[a-z0-9_-]+$/;function cu(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!WE.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).`);ht.set(e.id,e),Xs()}function PE(e){ht.delete(e)&&Xs()}function $E(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ht.entries()))o.owner===e&&(ht.delete(n),t++);return t>0&&Xs(),t}function UE(e){return ht.get(e)}function BE(){return Array.from(ht.values())}function FE(e){return ea.add(e),()=>{ea.delete(e)}}function HE(e){Eo.state.activeId!==e&&(Eo.state.activeId=e,Xs())}function ta(){return ht.get(Eo.state.activeId)??ht.get("default")??ht.values().next().value}function Xs(){const e=Array.from(ea);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function jt(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 GE 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 Ne(e,t,n){if(t.length!==0)throw new GE(e,t,n)}function lu(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const St=[[0,0],[100,0],[100,100],[0,100]],zE=48,jE=80,na=6,oa=8,du=4,uu=3,fu=64,sa=105,kt=2;function pu(e){return`${Math.round(e*1e3)/1e3}%`}function It(e){return e.slice().reverse()}function _o(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function VE(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 it(e,t=[]){const n=[],o=s=>{n.push(`${pu(s[0])} ${pu(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 hu(e){return it(St,[It(VE(50,50,e,zE))])}function mu(e){return it(St,[It(_o(50-e,-kt,50+e,100+kt))])}function gu(e){const t=100/na,n=[];for(let o=0;o<na;o++){const s=o*t;n.push(It(_o(-kt,s,100+kt,s+e)))}return it(St,n)}function wu(e){return it(St,[It(_o(-kt,50-e,100+kt,50+e))])}function yu(e){const t=100/oa,n=[];for(let o=0;o<oa;o++){const s=o*t;n.push(It(_o(s,-kt,s+e,100+kt)))}return it(St,n)}function vu(e){return it(St,[It([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function bu(e){const t=100/du,n=100/uu,o=[];for(let s=0;s<uu;s++)for(let i=0;i<du;i++){const r=i*t+t/2,a=s*n+n/2,l=t/2*e,c=n/2*e;o.push(It(_o(r-l,a-c,r+l,a+c)))}return it(St,o)}function Eu(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<fu;s++){const i=t+s/(fu-1)*n;o.push([50+Math.cos(i)*sa,50+Math.sin(i)*sa])}return it(St,[It(o)])}function KE(){return{from:hu(0),to:hu(jE)}}function qE(){return{from:mu(0),to:mu(52)}}function YE(){return{from:gu(0),to:gu(100/na+.5)}}function XE(){return{from:wu(0),to:wu(52)}}function ZE(){return{from:yu(0),to:yu(100/oa+.5)}}function JE(){return{from:vu(0),to:vu(sa)}}function QE(){return{from:bu(0),to:bu(1.04)}}function e_(){return{from:Eu(0),to:Eu(360)}}function t_(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function n_(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function o_(){return{from:it([[-60,0],[100,0],[100,100],[0,100]]),to:it([[100,0],[260,0],[260,100],[160,100]])}}const ia=6,ra=100,kn=ra/2,Zs=200,_u=90,Su=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],s_="#101014",i_=1.25,In="http://www.w3.org/2000/svg";let r_=0;function Js(e){return Math.round(e*1e3)/1e3}function aa(e){return e/ia*Math.PI*2-Math.PI/2}function a_(e){const n=aa(e)+Math.PI/ia+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function c_(e){const t=aa(e),n=aa(e+1);return[[kn,kn],[kn+Math.cos(t)*Zs,kn+Math.sin(t)*Zs],[kn+Math.cos(n)*Zs,kn+Math.sin(n)*Zs]]}function ku(e,t){const n=c_(e),o=document.createElementNS(In,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${Js(s)} ${Js(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",Su[e%Su.length]),o.setAttribute("stroke",s_),o.setAttribute("stroke-width",String(i_)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function l_(){const e=`os-iris-${++r_}`,t=document.createElementNS(In,"svg");t.setAttribute("viewBox",`0 0 ${ra} ${ra}`),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(In,"defs"),o=document.createElementNS(In,"mask");o.setAttribute("id",e);const s=document.createElementNS(In,"g"),i=document.createElementNS(In,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let l=0;l<ia;l++){const c=ku(l,!0),d=ku(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=a_(d),f=Js(u.x*_u),p=Js(u.y*_u);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 So="none",d_=460,u_="cubic-bezier( 0.33, 0, 0.2, 1 )",Iu=80,Au=4e3,f_=70,p_=600,Cu=ie("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),Qs=Cu.state.registry,h_=Cu.state.listeners,Lu=/^[a-z0-9_/-]+$/;function Tu(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function m_(e){return typeof e!="number"||!Number.isFinite(e)?d_:Math.min(Au,Math.max(Iu,e))}const ca=0;function Nu(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?ca:Math.min(Au,Math.max(Iu,e))}function An(e){return typeof e!="number"||!Number.isFinite(e)?f_:Math.min(p_,Math.max(0,e))}function Ou(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 Du(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=Tu(e.from),r=Tu(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 g_(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)"):Lu.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===So&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Lu} — 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(...Du(r,`layers[ ${a} ]`))})):t.push(...Du(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):g_(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)"))}Ne("WindowReveal",t,e);const n=e.id.trim().toLowerCase();Qs.set(n,{...e,id:n}),Mu()}function w_(e){Qs.delete(e.toLowerCase())&&Mu()}function Ru(){const e=Array.from(Qs.values()),t=X(y.WINDOW_REVEALS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-reveals` filter returned a non-array; falling back to registry list."),e)}function xu(e){return Ru().find(t=>t.id===e)}function y_(e){return Qs.has(e)}function Mu(){const e=Array.from(h_);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:b("Sweep"),description:b("A straight edge travels across the window, uncovering the page behind it."),...n_(),duration:420}),Ue({id:"iris",label:b("Iris"),description:b("The page opens out from the centre of the window, like a camera shutter."),...KE(),duration:520}),Ue({id:"curtain",label:b("Curtain"),description:b("Two panels part from the middle of the window and slide off the sides."),...qE(),duration:480}),Ue({id:"blinds",label:b("Blinds"),description:b("Six horizontal slats retract at once, letting the page through between them."),...YE(),duration:560}),Ue({id:"diagonal",label:b("Diagonal"),description:b("A slanted edge sweeps off the trailing corner of the window."),...o_(),duration:460}),Ue({id:"rise",label:b("Rise"),description:b("The page rises into the window from the bottom edge upward."),...t_(),duration:440}),Ue({id:"shutter",label:b("Shutter"),description:b("Two panels part from the middle of the window and slide off the top and bottom."),...XE(),duration:480}),Ue({id:"slats",label:b("Slats"),description:b("Eight vertical slats retract at once, letting the page through between them."),...ZE(),duration:560}),Ue({id:"diamond",label:b("Diamond"),description:b("The page opens out from the centre of the window through a growing rhombus."),...JE(),duration:520}),Ue({id:"mosaic",label:b("Mosaic"),description:b("The page arrives as a grid of tiles, each opening out from its own centre."),...QE(),duration:600}),Ue({id:"obturator",label:b("Camera shutter"),description:b("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:l_,duration:720,edgeLag:0}),Ue({id:"radar",label:b("Radar"),description:b("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...e_(),duration:760});const Wu="desktop-mode-os-settings",Cn="desktop-mode-os-settings",v_="custom-gradient",ei="custom-image",la="galaxy",Pu="custom",$u=[{id:"pulse",label:"Pulse",value:"#f252fc"},{id:"nebula",label:"Nebula",value:"#ec9bff"},{id:"sirius",label:"Sirius",value:"#9af2ff"},{id:"lagoon",label:"Lagoon",value:"#9f98ff"},{id:"starlight",label:"Starlight",value:"#fffbff"},{id:"wp-blue",label:"WordPress Blue",value:"#2271b1"},{id:"indigo",label:"Indigo",value:"#3858e9"},{id:"teal",label:"Teal",value:"#04a4cc"},{id:"emerald",label:"Emerald",value:"#059669"},{id:"amber",label:"Amber",value:"#d97706"},{id:"rose",label:"Rose",value:"#e11d48"}];function ti(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return $u;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:$u}function da(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:la}const ua=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],fa=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],ni=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],oi=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"}],b_=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],E_=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],Ln={wallpaper:la,accent:"pulse",customAccent:"#f252fc",dockSize:"default",windowRadius:"round",adminBarMode:"hidden",desktopLayout:"unified",dockPlacement:"bottom",dockBehavior:"static",sideDockBehavior:"static",dockRailRenderer:"default",desktopTheme:"",appliedThemeRecommendations:[],unfocusEffect:"darken",windowReveal:"none",windowRevealDuration:0,windowLinkRenderer:"svg-splines",windowLinkVisibility:"always",windowLinksEnabled:!0,windowLinkRaiseOnFocus:!0,windowLinkHighlight:!0,customGradient:{from:"#2271b1",to:"#7c3aed",angle:135},customImage:null,wallpaperSettings:{},libraryHdOnly:!0,ai:{enabled:!1},heartbeatRate:60,nativePostsEnabled:!1,nativePostsHiddenColumns:[],nativePagesEnabled:!1,nativePagesHiddenColumns:[],nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,stationHomeEnabled:!1,adminAssetCacheEnabled:!0,windowPrewarmEnabled:!0,showDesktopOnWallpaperClick:!1,confirmCloseAllWindows:!0,mioEnabled:!1,mioApiEnabled:!1,mioShowOnWallpaper:!0,mioStyle:{appearance:{},physics:{}},showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,navPlacement:{},navOrder:[],mobileLayout:"auto",mobileTabs:[],dockPromotedPositions:{}},Uu={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},Bu=["dockRailRenderer","windowReveal","accent"],Fu={windowRevealDuration:{min:80,max:4e3}},__=/^[a-z0-9_-]+$/;[...Object.keys(Uu),...Bu,...Object.keys(Fu)];function Hu(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries(Uu)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of Bu){const i=t[s];typeof i=="string"&&__.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(Fu)){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 S_(e){const t=Hu(e);return typeof t.dockRailRenderer=="string"&&UE(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==So&&!y_(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!ti().some(n=>n.id===t.accent)&&delete t.accent,t}const k_=/^[a-z0-9_-]+$/,Gu=128;function I_(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function pa(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!k_.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>=Gu)break;c===""||!I_(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>=Gu)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:Hu(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload",cssDeferred:t.cssDeferred===!0}}function A_(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=pa(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const At=ie("desktop-mode/desktop-themes",A_);function Tn(){return At}function C_(){return At.getState().themes.slice()}function ha(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return At.getState().themes.find(n=>n.slug===t||n.id===e)??null}function ma(){return At.getState().activeId}function L_(e){const t=pa(e);if(!t)return null;const n=At.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)),At.setState({themes:n}),t}let ko=null;function zu(){if(ko)return ko;const e=window.openStationConfig?.desktopThemesUrl;return e?(ko=Le(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??[])L_(n)}).catch(()=>{ko=null}),ko):Promise.resolve()}function T_(e){const t=[];for(const n of e){const o=pa(n);o&&t.push(o)}At.setState({themes:t})}function N_(e){return At.subscribe(e)}function si(e){const t=Tn().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=X(y.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function ga(e){const t=Tn().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=X(y.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?O_(o):null}function O_(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 Vt={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"},D_={"desktop-mode-os-settings":Vt.OS_SETTINGS,"desktop-mode-recycle-bin":Vt.RECYCLE_BIN,"desktop-mode-bug-report":Vt.BUG_REPORT,"os-exit":Vt.EXIT_OPENSTATION,"os-pwa-install":Vt.PWA_INSTALL};function ii(e){if(typeof e!="string"||e==="")return"";const t=D_[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function R_(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Vt.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Vt?n:""}const ri=ie("desktop-mode/window-channels",()=>({parentSubs:new Map,nativeSubs:new Map,readyWindows:new Set,loadingWindows:new Set,pendingSends:new Map}));function wa(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 ju(e,t,n,o){const s={channel:n,windowId:t},i=wa(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=wa(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 x_(e,t,n){const o=wa(ri.state.parentSubs,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function M_(e,t,n){ju(ri.state.parentSubs,e,t,n)}function W_(e,t,n){ju(ri.state.nativeSubs,e,t,n)}function P_(e){const{readyWindows:t,loadingWindows:n,pendingSends:o}=ri.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)&&(C(y.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const $_="os.activity.";function ya(e){return $_+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let U_=0;const Se={publish(e,t){C(ya(e),t)},subscribe(e,t){const n=`os/activity-sub/${++U_}`,o=ya(e);ee(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,yo(o,n))}},filter(e,t,...n){return X(ya(e),t,...n)}},B_=4e3,F_=200,H_=1200;function de(e){const t=Se.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return Ys(()=>!n,()=>{o=G_(t)}),()=>{n=!0,o&&o()}}function G_(e){const t=K_(),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??B_,r=0;const a=()=>{s!==null&&(window.clearTimeout(s),s=null)},l=()=>{o||(o=!0,a(),V_(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),j_()},F_))},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,H_),c()}),z_(n),c(),Se.publish("os/toast-shown",{...e}),l}let ai=null,Io=0;function Vu(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(ai=t))}function z_(e){Io===0&&document.addEventListener("focusin",Vu,!0),Io+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(ai=n)}function j_(){Io=Math.max(0,Io-1),Io===0&&document.removeEventListener("focusin",Vu,!0)}function V_(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||ai?.isConnected===!0&&ai.focus()}function K_(){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 q_="http://localhost/";function rt(e,t){const n=typeof window<"u"&&window.location?window.location.href:q_,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 Y_="os-overview",X_="os-system",ci={mio:10,overview:20,system:30,exit:35},Z_=`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>')}`,J_=`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>')}`,Q_="os-exit";function eS(){return{id:Q_,title:b("Exit OpenStation"),navKind:"control",locked:!0,order:ci.exit,icon:"dashicons-exit",onOpen:()=>{tS()}}}async function tS(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){va(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{}va(o)}function va(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const Ku=800;function nS(e,t=Ku){window.setTimeout(()=>{if(e){va(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const oS="desktop_mode_nonces",sS="desktop-mode/v1",iS=3e4,rS=3,Nn=ie("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function qu(){return window.wp?.os?.config??{}}function aS(){const e=qu().restUrl;return e?rt(e,sS):null}function cS(){Nn.state.negativeConfirms=0}async function lS(){const e=Nn.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=rS)return;const t=aS();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<iS)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await Le(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}dS()}catch{}finally{e.confirmInFlight=!1}}}function dS(){if(!Nn.state.exiting){Nn.state.exiting=!0,nS(qu().adminUrl||"");try{de({message:b("OpenStation is no longer active. Returning to the WordPress dashboard…"),duration:Ku})}catch{}}}function uS(){if(Nn.state.booted)return;Nn.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[oS]!==void 0){cS();return}lS()}})}const fS=0,ba=40,Yu=250,pS=120,hS=250,Ao="os-window__loading",li="os-window__loading--visible",di=ie("desktop-mode/window-reveal-active",()=>({id:So,duration:ca}));function Xu(e){di.state.id=typeof e=="string"&&e!==""?e:So}function mS(){const e=di.state.id;return!e||e===So?null:xu(e)??null}function Zu(e){di.state.duration=Nu(e)}function gS(){return di.state.duration}function wS({osSettings:e}){const t=e.getOsSettingsSnapshot();Xu(t.windowReveal),Zu(t.windowRevealDuration),e.subscribeOsSettings(n=>{Xu(n.windowReveal),Zu(n.windowRevealDuration)})}const On="os-window__reveal",Co="os-window__reveal--edge",yS="os-window__reveal--custom",Kt="os-window__body--revealing",Ea="data-os-reveal",_a="data-os-reveal-layer",Ct=new WeakMap,Ju=ie("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function Qu(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const vS="--os-window-reveal-duration",bS="--os-window-reveal-edge-thickness";function ef(e){const t=e.trim();if(t==="")return 0;const n=/^(-?\d*\.?\d+)\s*(ms|s)?$/i.exec(t);if(!n)return 0;const o=Number(n[1]);return Number.isFinite(o)?n[2]?.toLowerCase()==="s"?o*1e3:o:0}function ES(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return Nu(ef(window.getComputedStyle(e).getPropertyValue(vS)))}catch{return 0}}function _S(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function SS(e,t){const n=_S(e,bS);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return An(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return An(t*Number(s[1]));const i=ef(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?An(i):null}function tf(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 kS(e,t){const n=m_(t.duration),o=gS(),s=o!==ca?o:ES(e)||n,i=SS(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=An(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:An(r*s/n)}}function nf(e){return e.querySelector(":scope .os-window__body")}function IS(e){return e.querySelector(`:scope .${On}:not( .${Co} )`)}function AS(e){return e.querySelector(`:scope .${Co}`)}function of(e){return Array.from(e.querySelectorAll(`:scope .${On}:not( .${Co} )`))}function sf(e){return Array.from(e.querySelectorAll(`:scope .${Co}`))}function Sa(e){return Array.from(e.querySelectorAll(`:scope .${On}`))}function rf(e,t,n,o){const s=document.createElement("div");s.className=o?`${On} ${Co}`:On;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(Ea,e.id),s.setAttribute(_a,String(n)),s.style.clipPath=t.from,s}function CS(){const e=mS();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(On),s.classList.add(yS),s.setAttribute("aria-hidden","true"),s.setAttribute(Ea,e.id),s.setAttribute(_a,"0"),Ju.set(s,o.play),[s]}const t=Ou(e);if(t.length===0)return[];const n=[];return An(e.edgeLag)>0&&t.forEach((o,s)=>n.push(rf(e,o,s,!0))),t.forEach((o,s)=>n.push(rf(e,o,s,!1))),n}function LS(e){const t=nf(e);if(t){t.classList.remove(Kt);for(const n of Sa(t))Ct.get(n)?.cancel(),Ct.delete(n),n.remove();for(const n of CS())t.appendChild(n)}}function af(e){const t=nf(e);if(!t)return;const n=IS(t);if(!n)return;let o;try{o=xu(n.getAttribute(Ea)??"")}catch(_){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",_)}if(!o){Sa(t).forEach(_=>_.remove());return}const i=!!t.querySelector(`:scope .${Ao}`)?.classList.contains(li)?Yu:0,{duration:r,edgeLag:a}=kS(t,o),l=o.easing??u_,c=Ju.get(n);if(c){t.classList.add(Kt);const _=()=>{Ct.delete(n),n.remove(),t.classList.remove(Kt)};if(Qu()||typeof n.animate!="function"){window.setTimeout(_,i);return}let M=[];try{M=c({duration:r,easing:l,delay:i})}catch(P){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,P)}if(M.length===0){_();return}M[0].addEventListener("finish",_),M[0].addEventListener("cancel",()=>{Ct.delete(n),t.classList.remove(Kt)}),Ct.set(n,M[0]);return}const d=AS(t);d&&(a<=0||tf(d))&&sf(t).forEach(_=>_.remove()),tf(n)&&of(t).forEach(_=>_.remove());const u=Sa(t);if(u.length===0)return;t.classList.add(Kt);const f=()=>{for(const _ of u)Ct.delete(_),_.remove();t.classList.remove(Kt)};if(Qu()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,g=Ou(o),h=(_,M)=>{const P=g[Number(_.getAttribute(_a))];if(!P)return _.remove(),null;_.style.willChange="clip-path";let B;try{B=_.animate([{clipPath:P.from},{clipPath:P.to}],{duration:M,easing:p,delay:i,fill:"both"})}catch(F){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,F),_.remove(),null}return Ct.set(_,B),B},m=of(t).map(_=>h(_,r)).filter(_=>_!==null),E=sf(t).map(_=>h(_,r+a)).filter(_=>_!==null),S=m[0]??null,R=E[0]??null;if(!S&&!R){f();return}(R??S)?.addEventListener("finish",f);const $=()=>{for(const _ of u)Ct.delete(_);t.classList.remove(Kt)};S?.addEventListener("cancel",$),R?.addEventListener("cancel",$)}const TS="os-window-tab-change";function cf(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function lf(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function df(e,t){return`${e.id||"os-window"}-tab-${lf(t)}`}function uf(e,t){return`${e.id||"os-window"}-panel-${lf(t)}`}function NS(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 OS(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 DS(e){const t=cf(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 ff(e){const t=new Map;for(const n of cf(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function pf(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 RS(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of ff(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 pf(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}DS(n),NS(n),e.dispatchEvent(new CustomEvent(TS,{bubbles:!0,detail:{value:t}}))}}function xS(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=ff(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=df(e,d.value),u.setAttribute("aria-controls",uf(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();OS(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of pf(e)){const u=d.getAttribute("for");u&&(d.id=uf(e,u),a?d.setAttribute("aria-labelledby",df(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&&RS(e,c)}const Lo="os-window__body--loading",ka="os-window__body--loading-out",Ia="data-os-loading-at",hf="data-os-loading-cycle";function ui(e){return e.getAttribute(hf)??"0"}function MS(e){e.setAttribute(Ia,String(Date.now())),e.setAttribute(hf,String(Number(ui(e))+1))}function WS(e,t){const n=Number(e.getAttribute(Ia)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=pS-o;if(s<=0){t.classList.add(li);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(Lo)&&t.classList.add(li)},s)}const PS=Symbol.for("desktop-mode/window-config");function $S(e){return e[PS]}const mf=window.location.origin;function US(e){const t=new URL(e,mf);return t.origin!==mf||bo(t)?null:(t.searchParams.set("openstation_chromeless","1"),t.toString())}function Aa(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function gf(){const e=document.createElement("div");e.className=Ao,e.setAttribute("role","status"),e.setAttribute("aria-live","polite");const t=document.createElement("os-spinner");return t.setAttribute("preset","classic"),t.setAttribute("size","clamp(96px, 14vw, 192px)"),t.setAttribute("label",b("Loading window content")),e.appendChild(t),e}function BS(e){let t=gf();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=X(y.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[openstation] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains(Ao)&&t.classList.add(Ao),t}function wf(e){e.querySelector(":scope .os-window__loading")?.remove()}function yf(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=$S(e),s=o?BS(o):gf();t.appendChild(s),WS(t,s)}const FS=8,vf=Object.freeze({top:0,right:0,bottom:0,left:0});function bf(e,t,n,o){return{left:e,top:t,width:n,height:o,right:e+n,bottom:t+o}}function HS(e,t){const n=t.left+t.width/2,o=t.top+t.height/2,s={top:Math.abs(o-e.top),bottom:Math.abs(e.bottom-o),left:Math.abs(n-e.left),right:Math.abs(e.right-n)},r=t.height>t.width?["left","right","top","bottom"]:["top","bottom","left","right"];let a=r[0];for(const l of r)s[l]<s[a]&&(a=l);return a}function GS(e,t,n=FS){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(HS(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 Ef(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 zS(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 jS(e,t){return e.top===t.top&&e.right===t.right&&e.bottom===t.bottom&&e.left===t.left}function _f(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const VS="os-work-area-changed",KS="data-os-dock-behavior",qS="os/work-area";function YS(){return{insets:{...vf},rect:{x:0,y:0,width:0,height:0},viewport:{x:0,y:0,width:0,height:0},area:{width:0,height:0}}}const mt=ie(qS,()=>({snapshot:YS(),installed:!1,areaEl:null})),Dn={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 Ca(e){return{insets:{...e.insets},rect:{...e.rect},viewport:{...e.viewport},area:{...e.area}}}function XS(){return Ca(mt.state.snapshot)}function me(e){const t=e??mt.state.areaEl;if(!t)return{...mt.state.snapshot.rect};const n=t.clientWidth||t.getBoundingClientRect().width,o=t.clientHeight||t.getBoundingClientRect().height;return Ef(n,o,mt.state.snapshot.insets)}function ZS(e){const{installed:t,snapshot:n}=mt.state;if(!t)return{...vf};const o=n.viewport;return zS(bf(o.x,o.y,o.width,o.height),e.getBoundingClientRect())}function To(e){return mt.subscribe(t=>{e(Ca(t.snapshot))})}function JS(e){const t=QS(e),n=[],o=e.shellBody.querySelectorAll(e.chromeSelector??".os-dock");for(const l of Array.from(o))l.hidden||l.getAttribute(KS)==="dynamic"||n.push(l.getBoundingClientRect());const s=GS(t,n),i=e.area.clientWidth||t.width,r=e.area.clientHeight||t.height,a=Ef(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 QS(e){const{area:t}=e;if(t.offsetWidth>0&&t.offsetParent===e.shellBody){const n=e.shellBody.getBoundingClientRect();return bf(n.left+t.offsetLeft,n.top+t.offsetTop,t.offsetWidth,t.offsetHeight)}return t.getBoundingClientRect()}function ek(e,t){e.style.setProperty(Dn.top,`${t.insets.top}px`),e.style.setProperty(Dn.right,`${t.insets.right}px`),e.style.setProperty(Dn.bottom,`${t.insets.bottom}px`),e.style.setProperty(Dn.left,`${t.insets.left}px`),e.style.setProperty(Dn.width,`${t.rect.width}px`),e.style.setProperty(Dn.height,`${t.rect.height}px`)}function tk(e,t){return jS(e.insets,t.insets)&&_f(e.rect,t.rect)&&_f(e.viewport,t.viewport)&&e.area.width===t.area.width&&e.area.height===t.area.height}function nk(e){const t=new Map;let n=null,o=null,s=!1,i=!1,r=null;const a=()=>{if(s||i)return;const p=JS(e);if(!!mt.state.installed&&tk(mt.state.snapshot,p))return;ek(e.shell,p),mt.setState({snapshot:p,installed:!0,areaEl:e.area});const h=Ca(p);C(y.WORK_AREA_CHANGED,h),document.dispatchEvent(new CustomEvent(VS,{detail:h}))},l=typeof ResizeObserver<"u",c=()=>{if(!l)return;const p=new Set(Array.from(e.shellBody.querySelectorAll(e.chromeSelector??".os-dock")));for(const[g,h]of t)p.has(g)||(h.disconnect(),t.delete(g));for(const g of p){if(t.has(g))continue;const h=new ResizeObserver(a);h.observe(g,{box:"border-box"}),t.set(g,h)}};l&&(n=new ResizeObserver(a),n.observe(e.area)),typeof MutationObserver<"u"&&(o=new MutationObserver(()=>{c(),a()}),o.observe(e.shellBody,{childList:!0}));const d=()=>{c(),a()};document.addEventListener("os-layout-changed",d),window.addEventListener("resize",a);const u=()=>{i=!0},f=()=>{i=!1,a()};return ee(y.OVERVIEW_ENTERING,fi,u),ee(y.OVERVIEW_EXITED,fi,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),yo(y.OVERVIEW_ENTERING,fi),yo(y.OVERVIEW_EXITED,fi),pi===r&&(pi=null)}},pi=r,r}const fi="openstation/work-area";let pi=null;function ok(){pi?.refresh()}const sk={get:XS,rectOf:me,insetsOf:ZS,subscribe:To};function ik(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){Sf(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=dk(e,n),i=Qr(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=Fa(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"){No(e);return}const u=e.getById(l.id);if(!u){No(e);return}rk(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&No(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 rk(e,t){const n=e._splitOverviewZone;if(!n){No(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),C(y.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),No(e)}function No(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();Sf(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 Sf(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const kf=30,ak=260;function ck(e,t){return e<=t.left+kf?"left":e>=t.right-kf?"right":null}function lk(e,t){const n=me(e._desktop),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?n.x:n.x+n.width-o,y:n.y,width:o,height:s}}function dk(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 uk(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=lk(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 La(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()},ak)}function fk(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=ck(n,o),i=e._snapPendingZone;s?(uk(e,s),i!==s&&C(y.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(La(e),C(y.SNAP_ZONE_CANCELED,{windowId:t.id}))}function pk(e,t){const n=e._snapPendingZone;return n?(La(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),C(y.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{ik(e,t,n)}),!0):!1}function If(e){e._snapPendingZone&&La(e)}const hk=6,mk=6,gk=8,wk={Shake:"shake"},Af="os-window--grid-snapping",Cf="os-area--grid-snapping";function yk(e){const t={cols:hk,rows:mk},n=X(y.GRID_SNAP_DIMENSIONS,t,{areaWidth:e.width,areaHeight:e.height});return!!n&&Number.isInteger(n.cols)&&Number.isInteger(n.rows)&&n.cols>=1&&n.rows>=1&&n.cols<=24&&n.rows<=24?{cols:n.cols,rows:n.rows}:t}function Ta(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:Lf(Math.floor(s*o.cols),o.cols),row:Lf(Math.floor(i*o.rows),o.rows)}}function Lf(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t-1,e)):0}function vk(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 hi(e,t,n,o){const s=vk(e,t,n,o),i=Math.round(gk/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 bk(e,t){return e.col===t.col&&e.row===t.row}function Na(e,t,n){const o=e._desktop.getBoundingClientRect();return{x:t-o.left,y:n-o.top}}function Oa(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 Ek(e,t,n,o){if(e._gridSnap)return;If(e);const s=me(e._desktop),i=yk(s),r=Na(e,n,o),a=Ta(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:hi(a,a,s,i),overlayEl:l,targetEl:c,windowEl:t.element};e._gridSnap=d,t.element.classList.add(Af),e._desktop.classList.add(Cf),Oa(d,s),requestAnimationFrame(()=>{e._gridSnap===d&&l.classList.add("os-grid-snap--visible")}),C(y.GRID_SNAP_ARMED,{windowId:t.id,anchor:{...a},dims:{...i}}),C(y.GRID_SNAP_CHANGED,{windowId:t.id,anchor:{...a},cursor:{...a},rect:{...d.rect}})}function _k(e,t,n){const o=e._gridSnap;if(!o)return;const s=me(e._desktop),i=Na(e,t,n),r=Ta(i.x,i.y,s,o.dims),a=hi(o.anchor,r,s,o.dims),l=!bk(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,Oa(o,s),(l||c)&&C(y.GRID_SNAP_CHANGED,{windowId:o.windowId,anchor:{...o.anchor},cursor:{...r},rect:{...a}})}function Sk(e,t,n,o){const s=e._gridSnap;if(!s)return;const i=me(e._desktop),r=Na(e,t,n),a=Ta(r.x,r.y,i,s.dims);s.anchor=a,s.cursor=a,s.rect=hi(a,a,i,s.dims),Oa(s,i),s.targetEl.classList.remove("os-grid-snap__target--reset"),s.targetEl.offsetWidth,s.targetEl.classList.add("os-grid-snap__target--reset"),C(y.GRID_SNAP_ANCHOR_RESET,{windowId:s.windowId,anchor:{...a},reason:o}),C(y.GRID_SNAP_CHANGED,{windowId:s.windowId,anchor:{...a},cursor:{...a},rect:{...s.rect}})}const kk=200;function Tf(e){const t=e._gridSnap;if(!t)return null;e._gridSnap=null,t.windowEl.classList.remove(Af),e._desktop.classList.remove(Cf);const n=t.overlayEl;return n.classList.remove("os-grid-snap--visible"),window.setTimeout(()=>n.remove(),kk),t}function Ik(e){const t=Tf(e);t&&C(y.GRID_SNAP_CANCELED,{windowId:t.windowId})}function Ak(e,t){const n=Tf(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 C(y.GRID_SNAP_COMMITTED,{...s,anchor:{...n.anchor},cursor:{...n.cursor},dims:{...n.dims}}),C(y.WINDOW_DRAG_END,{windowId:t.id,x:o.x,y:o.y}),C(y.WINDOW_MOVED,{windowId:t.id,x:o.x,y:o.y}),C(y.WINDOW_RESIZED,{windowId:t.id,width:o.width,height:o.height}),!0}function Nf(e,t){return hi(e.anchor,e.cursor,t,{cols:e.cols,rows:e.rows})}function Of(e,t){const n=e._gridSpan;if(!n||e.state!=="normal"&&e.state!=="minimized")return!1;const o=Nf(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 Ck(e){const t=me(e._desktop),n=[];for(const o of e._stack)Of(o,t)&&(o._emitChange("moved"),n.push(o.id));return n.length>0&&C(y.GRID_SNAP_REFLOWED,{windowIds:n}),n}function Lk(e){return To(()=>{Ck(e)})}function Tk(e){return[e.id,e.menu?.url??"",e.entry?.url??"",e.windowId??"",e.title].join(`
2 `).toLowerCase()}function Df(e,t){const n=t.trim().toLowerCase();return n?Tk(e).includes(n):!1}function Nk(e,t){if(t.length===0)return[];const n=[],o=new Set;for(const s of e)o.has(s.id)||t.some(i=>Df(s,i))&&(o.add(s.id),n.push(s.id));return n}function Rf(e,t){const n=[];for(const o of t){const s=e.find(i=>Df(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 Ok=["index.php","upload.php","options-general.php"];function Dk(){return[{id:"commerce",label:b("Commerce"),description:b("A shop floor. WooCommerce orders, products and analytics side by side; everything that is not commerce leaves the rails."),icon:"dashicons-cart",color:"#7f54b3",defaultLabel:b("Commerce"),order:10,apps:["woocommerce","wc-admin","wc-orders","wc-reports","wc-settings","post_type=product","post_type=shop_order","post_type=shop_coupon","edit-tags.php?taxonomy=product_cat","users.php"],widgets:["clock","desktop-mode/site-views"],appearance:{wallpaper:"dark",accent:"indigo"},windows:[{match:"wc-orders"},{match:"post_type=product",url:"edit.php?post_type=product"},{match:"wc-admin"}],layout:"columns"},{id:"learning",label:b("Learning"),description:b("A course studio. Sensei courses, lessons and learners tiled together, so moving between them is a glance rather than a navigation."),icon:"dashicons-welcome-learn-more",color:"#43a047",defaultLabel:b("Learning"),order:20,apps:["sensei","post_type=course","post_type=lesson","post_type=question","post_type=sensei_message","sensei_learner_admin","sensei-settings","users.php"],widgets:["clock","desktop-mode/heartbeat","desktop-mode/recent-comments"],appearance:{wallpaper:"aurora",accent:"emerald"},windows:[{match:"post_type=course",url:"edit.php?post_type=course"},{match:"post_type=lesson",url:"edit.php?post_type=lesson"},{match:"sensei"}],layout:"tile"},{id:"publishing",label:b("Publishing"),description:b("A writing desk. A blank page takes two thirds of the screen, the library sits in the margin, and the rest of the admin is somewhere else."),icon:"dashicons-edit-page",color:"#c8102e",defaultLabel:b("Publishing"),order:30,apps:["edit.php","post-new.php","upload.php","edit-comments.php","edit-tags.php","post_type=page"],widgets:["desktop-mode/drafts","desktop-mode/post-stats","desktop-mode/focus-timer","desktop-mode/notes"],appearance:{wallpaper:"mono",accent:"rose",dockBehavior:"dynamic"},windows:[{match:"edit.php",url:"post-new.php",title:b("New draft")},{match:"edit.php",url:"edit.php"}],layout:"focus"}]}const Da=new Map;function xf(e){e?.id&&Da.set(e.id,e)}function Ra(e){Da.delete(e)}function Oo(){const e=[...Dk(),...Da.values()],t=X(y.WORKSPACE_PRESETS,e);return(Array.isArray(t)?t.slice():e).map((o,s)=>({preset:o,index:s})).sort((o,s)=>(o.preset.order??0)-(s.preset.order??0)||o.index-s.index).map(o=>o.preset)}function Rk(e){return Oo().find(t=>t.id===e)??null}function Mf(e,t){const n=[...e.apps,...e.apps.length?Ok:[]],o=Nk(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 xk=12,Mk=["free","cascade","tile","columns","focus"],Wf=["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 Wk(e){return e.kind!=="control"&&!e.locked}function Pk(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)||!Wk(i)||(s[i.id]="hidden");return s}function $k(e){const t=e?.widgets;return!t||t.mode!=="only"?null:t.ids}function Uk(e){const t=e?.appearance;if(!t)return null;const n={};for(const o of Wf)t[o]!==void 0&&(n[o]=t[o]);return Object.keys(n).length>0?n:null}function $f(e){const t={};for(const n of Wf)e[n]!==void 0&&(t[n]=e[n]);return t}function Bk(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 qt(e,t){return e.getDesktops().find(n=>n.id===t)?.profile??null}function Fk(e){return qt(e,e.getActiveDesktopId())}function Rn(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()&&xa(e,t),C(y.WORKSPACE_UPDATED,{desktopId:t,profile:n}),!0):!1}function Hk(e,t){e.setVisibleWidgets?.($k(qt(e.manager,t)))}function Gk(e,t){e.setAppearance?.(Uk(qt(e.manager,t)))}function xa(e,t){Gk(e,t),Hk(e,t)}function Ma(e,t={}){const n=t.preset?Rk(t.preset):null;let o=t.profile??null;!o&&n&&(o=X(y.WORKSPACE_PROFILE,Mf(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&&Rn(e,s.id,o),t.activate!==!1&&e.manager.switchDesktop(s.id),s}function Uf(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 Wa(e,t,n={}){const o=qt(e.manager,t);if(!o||o.provisioned&&!n.force)return;Rn(e,t,{...o,provisioned:!0});const s=Rf(e.getNavItems(),o.windows);let i=0;for(const a of s){if(a.url){const l=Ff(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=>mi(e.manager,c,a)).catch(()=>{});continue}a.item.windowId&&(i++,e.openNative(a.item.windowId),Bf(e.manager,a.item.windowId).then(l=>{l&&mi(e.manager,l,a)}))}const r=()=>{Uf(e.manager,o.layout),C(y.WORKSPACE_PROVISIONED,{desktopId:t,opened:i,layout:o.layout})};typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>requestAnimationFrame(r)):r()}function zk(e,t){const n=qt(e.manager,t);if(!n||!n.provisioned||n.windows.length===0)return;const o=Rf(e.getNavItems(),n.windows);for(const s of o){if(s.url){const i=Ff(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=>mi(e.manager,a,s)).catch(()=>{});continue}if(s.item.windowId){if(e.manager.getById(s.item.windowId))continue;e.openNative(s.item.windowId),Bf(e.manager,s.item.windowId).then(i=>{i&&mi(e.manager,i,s)})}}}function Pa(e,t){const n=[],o=new Set,s=me(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=jk({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>=xk)break}return n}function jk(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 mi(e,t,n){const o=me(e._desktop);if(n.gridSpan){t._gridSpan={anchor:{...n.gridSpan.anchor},cursor:{...n.gridSpan.cursor},cols:n.gridSpan.cols,rows:n.gridSpan.rows},Of(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 Bf(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 Vk(e,t,n={}){const o=e.manager._desktops.find(r=>r.id===t);if(!o)return null;const i={...o.profile??Pf(),windows:Pa(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]}),Rn(e,t,i),i}function Ff(e,t){if(/^https?:\/\//i.test(e))return e;try{return new URL(e,t).href}catch{return t}}let Lt=null;function Kk(e){return Lt=e,()=>{Lt=null}}function qk(){return Lt!==null}function Yk(){return Lt?(Lt.openCreator(),!0):!1}function Xk(e){return Lt?(Lt.openEditor(e),!0):!1}function Hf(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 Zk(e){const t=Lt;return t?(t.manager.switchDesktop(e),xa(t,e),Wa(t,e,{force:!0}),!0):!1}const Gf=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],gi="osHadFullscreenBeforeOverview";function zf(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[gi]="true",Aa()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function jf(e){if(e.element.dataset[gi]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[gi],Aa();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[gi],Aa()}}function $a(e,t=!0){t&&jf(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function Vf(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function Kf(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function Jk(e){if(e._overviewActive)return;qf(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,C(y.OVERVIEW_ENTERING,{}),C(y.DOCK_REFRESH_ACTIVE,{});for(const c of Gf){const d=document.getElementById(c);d&&(d.inert=!0)}Vf(!0),Kf(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)zf(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=Yf(e),e._desktop.appendChild(e._overviewTopBar);const a=Qr(t,i,ou(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=Fa(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"){gt(e);return}const p=e.getById(d.id);C(y.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),gt(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){gt(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){Xf(e);return}gt(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&&C(y.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&C(y.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&C(y.OVERVIEW_ENTERED,{})},300)}function qf(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function Qk(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 Ua=null;function eI(e){return Ua=e,()=>{Ua=null}}function Yf(e){const t=document.createElement("div");t.className="os-overview-top-bar";const n=Ua?.();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(Hf)&&o.classList.add("os-overview-top-bar__list--restorable");for(const a of e._desktops)o.appendChild(tI(e,a));const s=document.createElement("button");s.type="button",s.className="os-overview-top-bar__tile os-overview-top-bar__tile--add",e._overviewAddTileFocused&&s.classList.add("os-overview-top-bar__tile--cursor"),s.setAttribute("aria-label",b("Add new 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(),Xf(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 Xf(e){if(e._overviewAddTileFocused=!1,Yk()){gt(e);return}const t=Jf(e);Ba(e,t.id)}function tI(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",ae(b("Switch to %s"),t.label));const s=t.profile;s?.color&&(n.style.setProperty("--os-workspace-accent",s.color),o.classList.add("os-overview-top-bar__tile--tinted"));const i=document.createElement("span");if(i.className="os-overview-top-bar__tile-preview",s?.icon){const f=document.createElement("span");f.className=`os-overview-top-bar__tile-glyph dashicons ${s.icon}`,f.setAttribute("aria-hidden","true"),i.appendChild(f)}const r=e._stack.filter(f=>f.config.desktopId===t.id).length;if(r>0){const f=document.createElement("span");f.className="os-overview-top-bar__tile-count",f.textContent=String(r),i.appendChild(f)}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",f=>{f.preventDefault(),f.stopPropagation(),!a.hasAttribute("contenteditable")&&Ba(e,t.id)});const l=qk(),c=document.createElement("button");c.type="button",c.className="os-overview-top-bar__tile-edit",l?c.setAttribute("aria-label",ae(b("Edit %s — its apps, widgets, look and windows"),t.label)):c.setAttribute("aria-label",ae(b("Rename %s"),t.label)),c.title=c.getAttribute("aria-label")??"",c.innerHTML=zt("edit",{size:14}),c.addEventListener("click",f=>{if(f.preventDefault(),f.stopPropagation(),!l){nI(e,a,t);return}Ba(e,t.id),Xk(t.id)});const d=document.createElement("button");d.type="button",d.className="os-overview-top-bar__tile-close",d.setAttribute("aria-label",ae(b("Close %s"),t.label)),d.innerHTML=zt("close",{size:16}),d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),np(e,t.id),Do(e)}),n.appendChild(o),n.appendChild(c),n.appendChild(d);const u=document.createElement("div");if(u.className="os-overview-top-bar__tile-actions",Hf(t)){const f=document.createElement("button");f.type="button",f.className="os-overview-top-bar__tile-action os-overview-top-bar__tile-restore",f.setAttribute("aria-label",ae(b("Restore %s — reopen its windows, widgets and look"),t.label)),f.title=f.getAttribute("aria-label")??"",f.innerHTML=`${zt("windows",{size:12})}<span>${b("Restore")}</span>`,f.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),Zk(t.id)&&gt(e)}),u.appendChild(f)}return u.childElementCount>0&&n.appendChild(u),n}function nI(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&&ep(e,n.id,t.textContent??""),e._overviewActive&&Do(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 Do(e){if(!e._overviewTopBar)return;const t=Yf(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Ba(e,t){tp(e,t),gt(e)}function Fa(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=ae(Gt("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function gt(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,C(y.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),C(y.DOCK_REFRESH_ACTIVE,{}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of Gf){const r=document.getElementById(i);r&&(r.inert=!1)}Vf(!1),Kf(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"&&(jf(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"),$a(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),C(y.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>qf(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&&(C(y.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function oI(e){return[...e._desktops]}function Zf(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function sI(e){return Zf(e).id}function wi(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&$a(t)}function Ha(e){for(const t of e._stack)wi(e,t)}function iI(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?Ga(e):wi(e,o),C(y.WINDOW_DESKTOP_CHANGED,{windowId:t,from:s,to:n})),!0}function Jf(e,t){e._desktopSeq++;const n={id:`desktop-${e._desktopSeq}`,label:t?.label?.trim().slice(0,Qf)||ae(b("Desktop %d"),e._desktopSeq)};return e._desktops.push(n),C(y.DESKTOP_CREATED,{desktopId:n.id}),n}const Qf=64;function ep(e,t,n){const o=e._desktops.find(r=>r.id===t);if(!o)return!1;const s=n.trim().slice(0,Qf);if(!s||s===o.label)return!1;const i=o.label;return o.label=s,C(y.DESKTOP_RENAMED,{desktopId:t,label:s,previousLabel:i}),!0}function tp(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)Ga(e),Do(e);else{Ha(e),n?.direction&&rI(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&&yE(e._desktop,i.label)}C(y.DESKTOP_SWITCHED,{from:o,to:t})}function rI(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 np(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?Ga(e):Ha(e),C(y.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function Ga(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"),$a(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),Ha(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||""}),zf(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=Qr(t,o,ou(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=Fa(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function aI(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 cI(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;C(y.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=me(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"}})),C(y.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function op(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=me(e._desktop),o=_E(t.length,n.width,n.height),s=X(y.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=bE(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;C(y.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,l=12,c=Math.floor((n.width-a*2-l*(i-1))/i),d=Math.floor((n.height-a*2-l*(r-1))/r);t.forEach((f,p)=>{const g=p%i,h=Math.floor(p/i);f._gridSpan=null,f.element.style.left=`${n.x+a+g*(c+l)}px`,f.element.style.top=`${n.y+a+h*(d+l)}px`,f.element.style.width=`${c}px`,f.element.style.height=`${d}px`});const u=e.getFocused();u&&e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"tile"}})),C(y.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}function sp(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 lI(e,t){const n=e.getFocused();n&&e.focus(n),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:t}}))}const dI=4;function uI(e){const t=sp(e);if(t.length===0)return;if(t.length>dI){op(e);return}const n=t.length;C(y.ARRANGE_COLUMNS_STARTING,{windowCount:t.length,cols:n});const o=me(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`}),lI(e,"columns"),C(y.ARRANGE_COLUMNS_APPLIED,{windowCount:t.length,cols:n})}const ip=.64;function fI(e){const t=sp(e);if(t.length===0)return;const n=me(e._desktop),o=X(y.ARRANGE_FOCUS_SPLIT,ip,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),s=Number.isFinite(o)&&o>=.3&&o<=.9?o:ip;C(y.ARRANGE_FOCUS_STARTING,{windowCount:t.length,split:s});const i=16,r=12,a=n.width-i*2,l=n.height-i*2,c=e.getFocused(),d=c&&t.includes(c)?t.indexOf(c):0,u=t[d],f=t.filter((g,h)=>h!==d),p=f.length===0?a:Math.floor(a*s);if(u.element.style.left=`${n.x+i}px`,u.element.style.top=`${n.y+i}px`,u.element.style.width=`${p}px`,u.element.style.height=`${l}px`,f.length>0){const g=n.x+i+p+r,h=a-p-r,m=Math.floor((l-r*(f.length-1))/f.length);f.forEach((E,S)=>{E.element.style.left=`${g}px`,E.element.style.top=`${n.y+i+S*(m+r)}px`,E.element.style.width=`${h}px`,E.element.style.height=`${m}px`})}e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"focus"}})),C(y.ARRANGE_FOCUS_APPLIED,{windowCount:t.length,split:s})}const rp="desktop-mode-snap-to-grid";function pI(){try{return window.localStorage.getItem(rp)==="1"}catch{return!1}}function hI(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(rp,t?"1":"0")}catch{}C(y.ARRANGE_SNAP_CHANGED,{enabled:t})}}function mI(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=X(y.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=EE(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}const ap="desktop-mode-native-window-geometry",cp=64,at=8192;function yi(){try{const e=window.localStorage.getItem(ap);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function lp(e){try{window.localStorage.setItem(ap,JSON.stringify(e))}catch{}}function vi(e){if(!e)return null;const n=yi()[e];if(!n)return null;const o=Number(n.width),s=Number(n.height);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0||s<=0||o>at||s>at)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),a=Number(n.y),l=Number.isFinite(r)&&Number.isFinite(a)&&r>=0&&a>=0&&r<=at&&a<=at;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function dp(e,t){if(!e)return;const n=Math.round(Number(t.width)),o=Math.round(Number(t.height));if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0||n>at||o>at)return;const s=yi(),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||(Ro(s,e,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),xo(s))}function up(e,t){if(!e)return;const n=Math.round(Number(t.x)),o=Math.round(Number(t.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>at||o>at)return;const s=yi(),i=s[e];i&&(i.x===n&&i.y===o||(Ro(s,e,{...i,x:n,y:o}),xo(s)))}function fp(e,t,n){if(!e)return;const o=yi(),s=o[e];if(!s){if(t===null||!n)return;const i=Math.round(Number(n.width)),r=Math.round(Number(n.height));if(!Number.isFinite(i)||!Number.isFinite(r)||i<=0||r<=0||i>at||r>at)return;Ro(o,e,{width:i,height:r,state:t}),xo(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;Ro(o,e,r),xo(o);return}s.state!==t&&(Ro(o,e,{...s,state:t}),xo(o))}function Ro(e,t,n){delete e[t],e[t]=n}function xo(e){const t=Object.keys(e);if(t.length>cp){const n={};for(const o of t.slice(-cp))n[o]=e[o];lp(n);return}lp(e)}function gI(e,t,n,o){const s=o.x+ba-n,i=o.x+o.width-ba,r=Math.max(s,Math.min(e,i)),a=o.y+fS,l=o.y+o.height-ba,c=Math.max(a,Math.min(t,l));return{x:r,y:c}}const pp=100,bi=30;class wI{constructor(t){this._stack=[],this._cascadeMinimized=new WeakSet,this._cascadeDepth=0,this.cascadeIndex=0,this._pendingRestoreState=new Map,this._reservedRestoreIds=new Set,this._openingWindowIds=new Set,this._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=pI(),this._overviewActive=!1,this._overviewSnapshot=new Map,this._overviewLabels=new Map,this._overviewPointerDownHandler=null,this._overviewPointerUpHandler=null,this._overviewKeyHandler=null,this._overviewPressTarget=null,this._overviewClickBlocker=null,this._overviewTopBar=null,this._overviewMouseHandler=null,this._lastOverviewHoverId=null,this._overviewAddTileFocused=!1,this._overviewEnterTimeoutId=null,this._overviewExitTimeoutId=null,this._overviewExitFinalizer=null,this._snapPendingZone=null,this._snapPreviewEl=null,this._gridSnap=null,this._splitOverviewActive=!1,this._splitOverviewAnchor=null,this._splitOverviewZone=null,this._splitOverviewSnapshot=new Map,this._splitOverviewLabels=new Map,this._splitOverviewPointerDown=null,this._splitOverviewPointerUp=null,this._splitOverviewPressTarget=null,this._splitOverviewClickBlocker=null,this._splitOverviewKey=null,this._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this._unsubscribeWorkArea=To(()=>this.reflowStatefulWindows()),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const t=this._desktop.ownerDocument?.activeElement??null;if(!t||t.tagName!=="IFRAME")return;const n=t.closest(".os-window");if(!n)return;const o=n.id.replace(/^wp-window-/,""),s=this.getById(o);s&&(this._overviewActive||this.getFocused()!==s&&this.focus(s))},0)})}reflowStatefulWindows(){if(!this._overviewActive){for(const t of this._stack){const n=t.element.parentElement;if(!n)continue;const o=me(n);if(t.state==="maximized")t.element.classList.add("os-window--reflowing"),t.element.style.left=`${o.x}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${o.width}px`,t.element.style.height=`${o.height}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("os-window--reflowing");const s=Math.floor(o.width/2),i=o.height,r=t.state==="snapped-left"?o.x:o.x+o.width-s;t.element.style.left=`${r}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${s}px`,t.element.style.height=`${i}px`}else if(t.state==="normal"){const s=parseInt(t.element.style.left,10)||0,i=parseInt(t.element.style.top,10)||0,r=t.element.offsetWidth||0,a=gI(s,i,r,{x:0,y:0,width:n.clientWidth,height:n.clientHeight});(s!==a.x||i!==a.y)&&(t.element.classList.add("os-window--reflowing"),t.element.style.left=`${a.x}px`,t.element.style.top=`${a.y}px`)}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const t of this._stack)t.element.classList.remove("os-window--reflowing")},140)}}async open(t){if(!t||typeof t!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(t===null?"null":typeof t));if(typeof t.id!="string"||t.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof t.url!="string"||t.url==="")throw new TypeError('windowManager.open(): config.url must be a non-empty string. Pass an admin URL (e.g. "/wp-admin/edit.php") or a hash fragment (e.g. "#my-window") for native windows.');if(typeof t.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=t.baseId||t.id,o=this.getByBaseIdOnActiveDesktop(n);if(o){const r=o.state==="minimized";this.focus(o),r&&o.restore();let a=!1;if(!o.config.native){const c=En(t.url);c===En(o.getCurrentUrl())||c===En(o.config.url||"")||c===En(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})),C(y.WINDOW_REOPENED,l),o}const s=this.adoptPrewarmed(n,t);if(s)return s;const i=this.getByBaseId(n)?this.nextInstanceId(n):t.id;return this.createWindow({...t,id:i,baseId:n})}async prewarm(t){const n=t.baseId||t.id;if(t.native||this._prewarmInFlight||this._prewarmed?.baseId===n||this.getByBaseId(n))return!1;this._prewarmInFlight=!0;try{this.discardPrewarmed();const o=await this.createWindow({...t,id:t.id,baseId:n},{prewarm:!0});if(this.getByBaseId(n))return this.teardownSpeculativeWindow(o),!1;const s=window.setTimeout(()=>this.discardPrewarmed(),45e3);return this._prewarmed={baseId:n,win:o,timer:s},!0}finally{this._prewarmInFlight=!1}}adoptPrewarmed(t,n){const o=this._prewarmed;if(!o||o.baseId!==t)return null;const s=o.win;if(En(n.url)!==En(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),wi(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})),C(y.WINDOW_OPENED,i),s}discardPrewarmed(){const t=this._prewarmed;t&&(this._prewarmed=null,window.clearTimeout(t.timer),this.teardownSpeculativeWindow(t.win))}teardownSpeculativeWindow(t){try{globalThis.__openStationConnectionBridge?.onWindowClosed?.(t.id)}catch{}t.onClose=null;try{t.destroy()}catch{}t.element.remove()}async openNew(t){const n=t.baseId||t.id,o=t.id!==n&&!this.getById(t.id)&&!this._openingWindowIds.has(t.id)?t.id:this.nextInstanceId(n),s=40+this.cascadeIndex%8*bi,i=40+this.cascadeIndex%8*bi;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),this._reservedRestoreIds.delete(t.id),t={...t,...o});const s=this._desktop.getBoundingClientRect(),i=me(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*bi,d=i.y+40+this.cascadeIndex%8*bi,u=t.baseId||t.id,f=t.minWidth??320,p=t.minHeight??200,g=typeof t.width=="number",h=typeof t.height=="number",m=typeof t.x=="number",E=typeof t.y=="number",S=typeof t.initialState=="string",R=!g||!h||!S||!m||!E?vi(u):null;let $=t.width??(R?Math.max(R.width,f):a),_=t.height??(R?Math.max(R.height,p):l);!m&&!E&&!R&&($=Math.max(f,Math.min($,i.width-r*2)),_=Math.max(p,Math.min(_,i.height-r*2)));const P=Math.max(i.x+r,Math.min(c,i.x+i.width-$-r)),B=Math.max(i.y+r,Math.min(d,i.y+i.height-_-r)),F=t.initialState??(R?.state==="maximized"?"maximized":void 0);let K,Z;if(R&&typeof R.x=="number"&&typeof R.y=="number"){const q=Math.max(i.x,i.x+i.width-$-r),ne=Math.max(i.y,i.y+i.height-_-r);K=Math.max(i.x+r,Math.min(R.x,q)),Z=Math.max(i.y+r,Math.min(R.y,ne))}const Y=t.x??K??P,L=t.y??Z??B,x=g||h||m||E||S,j=!!R,V={x:Y,y:L,width:$,height:_,state:F};let J;try{J=X(y.WINDOW_GEOMETRY,V,{windowId:t.id,baseId:u,hasSavedGeometry:j,callerPinned:x,desktopRect:{width:s.width,height:s.height},workArea:{...i}})}catch(q){C(y.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:q}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,q),J=V}const O=(q,ne)=>typeof q=="number"&&Number.isFinite(q)?q:ne,T=J&&typeof J=="object"?J:V,W=Math.max(O(T.width,$),f),v=Math.max(O(T.height,_),p),I=O(T.x,Y),N=O(T.y,L),D=T.state??F,k={icon:t.icon||"dashicons-admin-generic",...t,x:I,y:N,width:W,height:v,minWidth:f,minHeight:p,...D?{initialState:D}:{},baseId:u,desktopId:t.desktopId||this._activeDesktopId};if(t.gridSpan){const q=Nf(t.gridSpan,me(this._desktop));k.x=q.x,k.y=q.y,k.width=q.width,k.height=q.height}this.cascadeIndex++,this._openingWindowIds.add(t.id);const U=Promise.all([hE(fE()),Yr(Xr())]);let G;try{G=await U}catch(q){throw this._openingWindowIds.delete(t.id),q}this._openingWindowIds.delete(t.id);const[le]=G,re=le.createWindow(k);if(t.gridSpan&&(re._gridSpan={anchor:{...t.gridSpan.anchor},cursor:{...t.gridSpan.cursor},cols:t.gridSpan.cols,rows:t.gridSpan.rows}),re.onFocusRequest=q=>{this._cascadeDepth>0||this.focus(q)},re.onClose=q=>this.remove(q),re.onMinimize=q=>{this._cascadeDepth++;try{this.cascadeMinimize(q)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const ne=this._stack.filter(be=>be.state!=="minimized");ne.length>0&&this.focus(ne[ne.length-1])},re.onRestore=q=>{this._cascadeDepth++;try{this.cascadeRestore(q)}finally{this._cascadeDepth--}},re.onOpenAnother=q=>{const ne=q.config.baseId||q.id;q.config.native&&window.wp?.os?.openNewWindow?.(ne,{source:"open-another"})||this.openNew({id:ne,baseId:ne,url:q.config.url||"",title:q.config.title,icon:q.config.icon,submenu:q.config.submenu,multi:!0})},re.onOpenInNewWindow=q=>{const ne=q.config.baseId||q.id;if(q.config.native&&window.wp?.os?.openNewWindow?.(ne,{source:"open-in-new-window"}))return;const be=q.getCurrentUrl();this.openNew({id:ne,baseId:ne,url:be||q.config.url||"",title:q.config.title,icon:q.config.icon,submenu:q.config.submenu,multi:!0})},re.onToggleStartup=q=>{this.onToggleStartupRequested?.(q)},re.snapConfigProvider=()=>this.getSnapConfig(),re.onDragMove=(q,ne,be)=>{if(this._gridSnap){_k(this,ne,be);return}fk(this,q,ne)},re.onDragGesture=(q,ne)=>{switch(ne.type){case"modifier":ne.active?Ek(this,q,ne.clientX,ne.clientY):Ik(this);break;case"shake":Sk(this,ne.clientX,ne.clientY,wk.Shake);break}},re.onDragEnd=q=>this._gridSnap?Ak(this,q):this._snapPendingZone?pk(this,q):(If(this),!1),n.prewarm)return re.element.style.display="none",re.element.setAttribute("aria-hidden","true"),this._desktop.appendChild(re.element),re;this._stack.push(re),this._desktop.appendChild(re.element),wi(this,re),re.hydrateNative(),this.focus(re);const ge={windowId:re.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:ge})),C(y.WINDOW_OPENED,ge),re}nextInstanceId(t){const n=new Set([...this._stack.map(s=>s.id),...this._openingWindowIds,...this._reservedRestoreIds]);if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=typeof t=="string"?this.getById(t):t;if(!n||typeof n.setZIndex!="function"){t&&typeof t!="string"&&console.warn("[openstation] windowManager.focus() expects a Window or a window id; received",t);return}const o=this.blockingChildOf(n)??n;o!==n&&(o.shake?.(),C(y.WINDOW_CHILD_BLOCKED,{windowId:n.id,childWindowId:o.id}),document.dispatchEvent(new CustomEvent("os-window-child-blocked",{detail:{windowId:n.id,childWindowId:o.id}})));const s=this._stack.length>0?this._stack[this._stack.length-1]:null,i=this._stack.find(l=>l!==o&&l.isFocused()&&l.isFullscreen());i&&X(y.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:i.id,focusedTo:o.id})&&i.toggleFullscreen();const r=this._stack.indexOf(o);if(r>-1&&this._stack.splice(r,1),this._stack.push(o),this.enforceOwnershipOrder(),this._stack.forEach((l,c)=>{l.setZIndex(pp+c),l.setFocused(c===this._stack.length-1)}),s&&s!==o&&s.id!==o.id){const l={windowId:s.id,focusedTo:o.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:l})),C(y.WINDOW_BLURRED,l)}const a={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:a})),C(y.WINDOW_FOCUSED,a)}raise(t){const n=this.getById(t);if(!n||this._stack.length<2)return;const o=this._stack.indexOf(n);o===-1||o===this._stack.length-1||(this._stack.splice(o,1),this._stack.splice(this._stack.length-1,0,n),this.enforceOwnershipOrder(),this._stack.forEach((s,i)=>{s.setZIndex(pp+i)}))}async openChild(t,n){const o=this.getById(t);if(!o)throw new Error(`windowManager.openChild(): no open window with id "${t}". Open the owner first, or use open() for a standalone window.`);const s=vi(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=me(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})),C(y.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),C(y.WINDOW_CLOSED,i)}getById(t){return this._stack.find(n=>n.id===t)}getByBaseId(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===t)return o}}getByBaseIdOnActiveDesktop(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==t)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(t){const n=o=>{if(o===t)return 1;const s=`${t}-`;if(o.startsWith(s)){const i=parseInt(o.slice(s.length),10);return Number.isFinite(i)?i:999}return 999};return this._stack.filter(o=>(o.config.baseId||o.id)===t).sort((o,s)=>n(o.id)-n(s.id))}getAllByBaseIdOnActiveDesktop(t){return this.getAllByBaseId(t).filter(n=>(n.config.desktopId||this._activeDesktopId)===this._activeDesktopId)}getAll(){return[...this._stack]}findByIframeSource(t){if(t)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===t)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(t){const n=this.getById(t);if(!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)return!1;const s=this.getFocused();return!!s&&s.id===t}isActiveByBaseId(t){const n=this.getFocused();return!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId?!1:(n.config.baseId||n.id)===t}getDesktops(){return oI(this)}getActiveDesktop(){return Zf(this)}getActiveDesktopId(){return sI(this)}createDesktop(t){return Jf(this,t)}switchDesktop(t,n){tp(this,t,n)}closeDesktop(t){np(this,t)}renameDesktop(t,n){return ep(this,t,n)}moveWindowToDesktop(t,n){return iI(this,t,n)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=X(y.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(c=>!n.has(c.id));C(y.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=X(y.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(c=>!i.includes(c));let a=0;const l=[];for(const c of i.slice())try{c.close(),c._isDestroyed||c._closePending?a++:l.push(c)}catch(d){l.push(c),typeof console<"u"&&console.error("[openstation] closeAll: window.close() threw for",c.id,d)}return C(y.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r,refused:l}),a}minimizeAll(){const t=[];for(const n of this._stack.slice())if((n.config.desktopId||this._activeDesktopId)===this._activeDesktopId&&n.state!=="minimized")try{n.minimize(),t.push(n)}catch(s){typeof console<"u"&&console.error("[openstation] minimizeAll: window.minimize() threw for",n.id,s)}return t}restoreFrom(t){if(!Array.isArray(t))return;const n=new Set(this._stack);for(const o of t)if(!(!n.has(o)||(o.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)&&o.state==="minimized")try{o.restore()}catch(i){typeof console<"u"&&console.error("[openstation] restoreFrom: window.restore() threw for",o.id,i)}}toggleShowDesktop(){const t=this._stack.filter(o=>(o.config.desktopId||this._activeDesktopId)===this._activeDesktopId);if(t.length===0)return!1;if(t.every(o=>o.state==="minimized")){for(const o of t)try{o.restore()}catch{}return!1}return this.minimizeAll(),!0}cascade(){cI(this)}tile(){op(this)}columns(){uI(this)}focusLayout(){fI(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){hI(this,t)}getSnapConfig(){return mI(this)}enterOverview(){if(Ht()){document.dispatchEvent(new CustomEvent("os-mobile-open-switcher"));return}Jk(this)}exitOverview(t,n=!1){gt(this,t,n)}destroy(){this._unsubscribeWorkArea(),this.desktopResizeObserver?.disconnect(),this._reflowRestoreTimer!==null&&(window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=null),this._overviewActive&&gt(this),this.discardPrewarmed(),Qk(this),vE()}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=X(y.SESSION_SNAPSHOT,i);return r&&Array.isArray(r.windows)?r:i}seedWindowRestoreState(t,n={}){this._pendingRestoreState=new Map(Object.entries(t)),this._reservedRestoreIds=n.reserveIds?new Set(Object.keys(t)):new Set}discardWindowRestoreState(t){if(t){this._pendingRestoreState.delete(t),this._reservedRestoreIds.delete(t);return}this._pendingRestoreState.clear(),this._reservedRestoreIds.clear()}seedDesktops(t,n){aI(this,t,n)}}function yI(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 hp(e,t){if(e._overviewActive)return;const n=yI(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 mp=!1;function za(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;return gp(t)}function gp(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 vI(e){if(mp)return;mp=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(za(document)||(n.preventDefault(),hp(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"||hp(e,o.direction==="prev"?"prev":"next")})}let Mo=null;function bI(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:gp(n)}function EI(e=window){if(Mo)return Mo;const t=o=>{bI(o)&&o.stopPropagation()};e.addEventListener("keydown",t,!0);const n=()=>{e.removeEventListener("keydown",t,!0),Mo===n&&(Mo=null)};return Mo=n,n}function wp(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 yp(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,Do(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function _I(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function SI(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function vp(e){return e._overviewActive?(e.exitOverview(),!0):!1}function kI(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function II(e){return kI(e)?(e.toggleShowDesktop(),!0):!1}let bp=!1;function AI(e){bp||(bp=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||Ht()||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||za(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?yp(e,"prev"):wp(e,"prev");break;case"ArrowRight":n=e._overviewActive?yp(e,"next"):wp(e,"next");break;case"ArrowUp":n=vp(e)||II(e)||_I(e);break;case"ArrowDown":n=vp(e)||SI(e);break}n&&t.preventDefault()},!0))}async function Yt(e){return await Yr(Xr()),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 CI="os-window-close-all";function LI(e){return e.code!=="KeyW"||e.getModifierState?.("AltGraph")||!(e.ctrlKey||e.metaKey)?!1:e.altKey&&!e.shiftKey}let ja=!1;function Ep(e){const t=e.getActiveDesktopId();return e.getAll().filter(n=>(n.config.desktopId||t)===t)}async function _p(e,t){if(ja)return 0;const n=Ep(e);if(n.length===0)return 0;if(t&&!t.shouldAsk())return Sp(e);const o=t?{rememberLabel:b("Don't ask again"),onRemember:i=>{i&&t.setAsk(!1)}}:{};ja=!0;let s=!1;try{s=await Yt({title:b("Close all windows?"),message:ae(Gt("%d open window on this desktop will be closed.","%d open windows on this desktop will be closed.",n.length),n.length),confirmLabel:b("Close all"),danger:!0,...o})}finally{ja=!1}return s?Sp(e):0}const TI=700,NI=50;function OI(e,t){const n=()=>t.filter(o=>!e.getById(o)).length;return new Promise(o=>{const s=Date.now()+TI,i=()=>{const r=n();if(r===t.length||Date.now()>=s){o(r);return}setTimeout(i,NI)};i()})}async function Sp(e){e._overviewActive&&e.exitOverview();const t=Ep(e).map(s=>s.id),n=e.getAll().map(s=>s.id).filter(s=>!t.includes(s));e.closeAll({exceptIds:n});const o=await OI(e,t);return o>0&&de({message:ae(Gt("Closed %d window.","Closed %d windows.",o),o)}),o}let kp=!1;function DI(e,t){if(kp)return;kp=!0,document.addEventListener("keydown",o=>{LI(o)&&(o.preventDefault(),o.stopImmediatePropagation(),_p(e,t))},!0);const n=window.location.origin;window.addEventListener("message",o=>{if(o.origin!==n)return;const s=o.data;!s||s.type!==CI||_p(e,t)})}const Ip=Yu;let Ap=!1;function Cp(e){return e?document.getElementById(`wp-window-${e}`):null}function RI(){Ap||(Ap=!0,xI())}function xI(){ee(y.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=Cp(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove(ka),n.classList.add(Lo),MS(n),yf(t),LS(t))}),ee(y.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=Cp(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 .${Ao}`)?.classList.contains(li);if(n.classList.remove(Lo),n.removeAttribute(Ia),!o){wf(t),af(t);return}n.classList.add(ka);const s=ui(n);af(t),window.setTimeout(()=>{ui(n)===s&&(n.classList.contains(Lo)||wf(t))},Ip),window.setTimeout(()=>{ui(n)===s&&(n.classList.contains(Lo)||n.classList.remove(ka))},Ip+hS)}),ee(y.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Lp())})}function Lp(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),yf(n))})}const MI="os_person_view";function WI(e){return e.searchParams.has(MI)}const Wo=ie("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function PI(e){Wo.state.deps=e}function Tt(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=Wo.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>$I(e.id)}function $I(e){const t=Wo.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function Ei(e){const{deps:t,remaps:n}=Wo.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}=Wo.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 UI="desktop_mode_classic";function BI(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has("page")&&!e.searchParams.has(UI)}const Va=ie("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function FI(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=Va.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Tp(e.id)}function Tp(e){const t=Va.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function HI(){return Va.state.entries.slice()}const GI=32,zI=64,jI=/^[a-z0-9_/-]+$/,ye=ie("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function Xt(e){return`${e.type}:${e.id}`}function Np(e){return e.root?Xt(e.root):Xt(e)}function Op(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&jI.test(o.trim().toLowerCase());return jt(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 Dp(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function VI(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,GI).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=Dp(e.previewUrl);o&&(n.previewUrl=o);const s=Dp(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,zI).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 Rp(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 Ka(e){return e?[Xt(e),Np(e),...(e.links??[]).map(t=>Xt(t)+(t.rel==="child"?"!child":""))].join("|"):""}function _i(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Ne("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=Op(t);if(a.length>0){o==="api"&&Ne("WindowContentRef",a,t),lu("WindowContentRef",a,t);return}s=VI(t,o)}if(s=X(y.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||Op(s).length>0)){lu("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=ye.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&Ka(s)===Ka(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&s.revisionsUrl===i.revisionsUrl&&s.revisionCount===i.revisionCount&&Rp(s)===Rp(i))return;s===null?ye.state.contentByWindow.delete(e):ye.state.contentByWindow.set(e,s);const r={windowId:e,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("os-window-content-changed",{detail:r})),C(y.WINDOW_CONTENT_CHANGED,r),ZI(),YI()}function Je(e){return ye.state.contentByWindow.get(e)}function qa(){const e=new Map;for(const[s,i]of ye.state.contentByWindow){const r=Np(i);let a=e.get(r);a||(a={key:r,root:i.root?{...i.root}:{type:i.type,id:i.id},rootWindowIds:[],children:[]},e.set(r,a)),i.root?a.children.push({windowId:s,content:i}):a.rootWindowIds.push(s)}const t=ye.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=X(y.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[openstation] `os.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function xp(e){return qa().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function KI(e){const t=new Set,n=xp(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of Mp())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function Mp(){const e=ye.state.focusSeq,t=new Map;for(const[a,l]of ye.state.contentByWindow){const c=Xt(l),d=t.get(c);(!d||(e.get(a)??0)>(e.get(d)??0))&&t.set(c,a)}const n=new Map,o=(a,l)=>`${a}→${l}`;for(const[a,l]of ye.state.contentByWindow){if(l.root){const c=t.get(Xt(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(Xt(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=X(y.WINDOW_LINK_EDGES,s);return Array.isArray(r)?r:(typeof console<"u"&&console.warn("[openstation] `os.window-links.edges` filter returned a non-array; falling back to derived edges."),s)}function qI(e){return ye.state.listeners.add(e),()=>{ye.state.listeners.delete(e)}}function YI(){for(const e of Array.from(ye.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function XI(){return Array.from(ye.state.contentByWindow).map(([e,t])=>`${e}=${Ka(t)}`).sort().join(";")}function ZI(){const e=XI();if(e===ye.state.lastGroupsSignature)return;ye.state.lastGroupsSignature=e;const n={groups:qa()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),C(y.WINDOW_LINK_GROUPS_CHANGED,n)}const JI={get:Je,set:(e,t)=>_i(e,t,{source:"api"}),groups:qa,edges:Mp,groupOf:xp,related:KI,subscribe:qI};function QI({manager:e}){ye.state.manager=e,!ye.state.started&&(ye.state.started=!0,ee(y.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=ye.state.manager?.getById(t.windowId)?.config?.content;o&&_i(t.windowId,o,{source:"config"})}),ee(y.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(ye.state.focusSeq.delete(t.windowId),_i(t.windowId,null,{source:"config"}))}),ee(y.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(ye.state.seq+=1,ye.state.focusSeq.set(t.windowId,ye.state.seq))}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t.data;if(!n||n.type!=="os-content-identity")return;const o=ye.state.manager?.findByIframeSource?.(t.source);o&&_i(o.id,n.identity??null,{source:"bridge"})}))}const eA=ie("desktop-mode/admin-link-deps",()=>({deps:null}));function tA(e){eA.state.deps=e}const Wp=ie("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),xn=Wp.state.seed,nA=Wp.state.listeners;function Mn(e){Ne("Wallpaper",jt(e,Up),e);const t=xn.findIndex(n=>n.id===e.id);t>=0?xn[t]=e:xn.push(e),$p()}function Pp(e){const t=xn.findIndex(n=>n.id===e);t>=0&&(xn.splice(t,1),$p())}function $p(){const e=Array.from(nA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function Ya(){const e=xn.slice(),t=X(y.WALLPAPERS,e);return Array.isArray(t)?t.filter(oA):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function Po(e){return Ya().find(t=>t.id===e)}const Up=[{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 oA(e){return jt(e,Up).length===0}const Bp=ie("desktop-mode/wallpaper-settings",()=>({values:{}}));function sA(e){return{...Bp.state.values[e]??{}}}function iA(e){const t=Bp.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const rA=20,Xa=1,Si=24,Wn="os-dock--revealed",$o="data-os-dock-behavior",aA="os-dock",Fp="os-side-dock",ki="os-dock-vt",cA=".os-constellation, .os-dock-peek";function lA(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 Hp(e){return e.getAttribute($o)==="dynamic"}function dA(e,t,n,o,s,i=rA){switch(e){case"bottom":return n>=s-i;case"left":return t<=i;case"right":return t>=o-i}return!1}function uA(e,t,n,o){const s=e.getBoundingClientRect();if(s.width<=0||s.height<=0)return!1;let i=s.top-Si;const r=s.bottom+Si;let a=s.left-Si,l=s.right+Si;switch(t){case"bottom":i=s.top-s.height*Xa;break;case"left":l=s.right+s.width*Xa;break;case"right":a=s.left-s.width*Xa;break}return n>=a&&n<=l&&o>=i&&o<=r}function fA(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function pA(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=_=>{const M=e.getBehaviors(),P=_.id===Fp?M.sidebar:M.dock;_.getAttribute($o)!==P&&_.setAttribute($o,P)},d=_=>{const M=_.ownerDocument.activeElement;if(M&&_.contains(M))return!0;if(!n)return!1;if(o)return _.classList.contains(Wn);const P=lA(_);return dA(P,n.x,n.y,window.innerWidth,window.innerHeight)||_.classList.contains(Wn)&&uA(_,P,n.x,n.y)},u=(_,M)=>{if(_.classList.contains(Wn)===M){i.delete(_);return}if(!M&&r){a=!0;return}if(s.has(_)){i.set(_,M);return}const P=()=>{_.classList.toggle(Wn,M)},B=document;if(typeof B.startViewTransition!="function"||fA()){P();return}const F=`os-dock-${_.id||"rail"}`;_.style.setProperty("view-transition-name",F),document.documentElement.classList.add(ki);let K;try{K=B.startViewTransition(P)}catch{_.style.removeProperty("view-transition-name"),document.documentElement.classList.remove(ki),P();return}const Z=K.finished&&typeof K.finished.then=="function"?K.finished:Promise.resolve(),Y=()=>{_.style.removeProperty("view-transition-name"),s.delete(_),s.size===0&&document.documentElement.classList.remove(ki);const L=i.get(_);i.delete(_),!t&&L!==void 0&&u(_,L)};s.set(_,Z.then(Y,Y))},f=()=>{if(!t)for(const _ of l()){if(c(_),!Hp(_)){_.classList.remove(Wn);continue}u(_,d(_))}},p=_=>{if(t||!l().some(Hp))return;n={x:_.clientX,y:_.clientY};const M=_.target;o=M instanceof Element&&M.closest(cA)!==null,f()};let g=0;const h=()=>{g||(g=requestAnimationFrame(()=>{g=0,f()}))},m=()=>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",m);let R=null;typeof MutationObserver<"u"&&(R=new MutationObserver(f),R.observe(e.shellBody,{childList:!0})),f();const $={refresh:f,destroy:()=>{t=!0,g&&(cancelAnimationFrame(g),g=0),R?.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",m);for(const _ of l())_.classList.remove(Wn),_.style.removeProperty("view-transition-name");i.clear(),document.documentElement.classList.remove(ki),Ii===$&&(Ii=null)}};return Ii=$,$}let Ii=null;function hA(){Ii?.refresh()}function Gp(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const zp=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","linerWidth","linerColor","glow","glowBlur","eyeColor","eyeScale"],jp=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function Za(){return{appearance:{},physics:{}}}function mA(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function Ai(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&&mA(i)&&Object.assign(n,{[s]:i})}return n}function Vp(e){if(!e||typeof e!="object"||Array.isArray(e))return Za();const t=e;return{appearance:Ai(t.appearance,zp),physics:Ai(t.physics,jp)}}function gA(e){return{appearance:Ai(e,zp),physics:Ai(e,jp)}}function wA(){const e=yA();if(e){const t=Qa(e,Ja());return ec(t),kA(t),t}try{const t=window.localStorage.getItem(Wu);if(t)return Qa(JSON.parse(t),Ja())}catch{}return Ja()}function Ja(){const e=Zp();return e.wallpaper=da(),e}function yA(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}const Ge=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_e=(e,t)=>typeof e=="boolean"?e:t,Zt=e=>(t,n)=>e.some(o=>o.id===t)?t:n,Pn=e=>(t,n)=>typeof t=="string"&&e.test(t)?t:n,Ci=/^[a-z0-9_/-]+$/,Kp={wallpaper:(e,t)=>typeof e=="string"&&e!==""?e:t,accent:(e,t)=>e===Pu||ti().some(n=>n.id===e)?e:t,customAccent:Pn(/^#[0-9a-fA-F]{6}$/),dockSize:Zt(ua),windowRadius:Zt(fa),adminBarMode:Zt(ni),desktopLayout:Zt(E_),dockPlacement:Zt(b_),dockBehavior:Zt(oi),sideDockBehavior:Zt(oi),dockRailRenderer:Pn(/^[a-z0-9_-]+$/),desktopTheme:Pn(/^[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:Pn(Ci),windowReveal:Pn(Ci),windowRevealDuration:(e,t)=>typeof e!="number"||!Number.isFinite(e)?t:e>0?Math.min(4e3,Math.max(80,Math.round(e))):0,windowLinkRenderer:Pn(Ci),windowLinkVisibility:(e,t)=>e==="focus"||e==="always"||e==="off"?e:t,windowLinksEnabled:_e,windowLinkRaiseOnFocus:_e,windowLinkHighlight:_e,customGradient:(e,t)=>Ge(e)?TA(e):{...t},customImage:(e,t)=>e===null||Ge(e)?NA(e):t,wallpaperSettings:(e,t)=>Ge(e)?bA(e):t,libraryHdOnly:_e,ai:(e,t)=>LA(e,t),heartbeatRate:(e,t)=>e===15||e===30||e===45||e===60?e:t,nativePostsEnabled:_e,nativePostsHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativePagesEnabled:_e,nativePagesHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativeUsersEnabled:_e,nativePluginsEnabled:_e,nativeCommentsEnabled:_e,stationHomeEnabled:_e,adminAssetCacheEnabled:_e,windowPrewarmEnabled:_e,showDesktopOnWallpaperClick:_e,confirmCloseAllWindows:_e,mioEnabled:_e,mioApiEnabled:_e,mioShowOnWallpaper:_e,mioStyle:(e,t)=>Ge(e)?Vp(e):t,showPostStatusRibbons:_e,developerModeEnabled:_e,foldersSharingEnabled:_e,navPlacement:(e,t)=>Ge(e)?EA(e):t,navOrder:(e,t)=>Array.isArray(e)?Yp(e):t,mobileLayout:(e,t)=>e==="auto"||e==="desktop"||e==="mobile"?e:t,mobileTabs:(e,t)=>Array.isArray(e)?Yp(e).slice(0,3):t,dockPromotedPositions:(e,t)=>Ge(e)?_A(e):t},qp=Object.keys(Kp);function Qa(e,t){const n=Qt(t),o=e,s=Kp;for(const i of qp)i in o&&(n[i]=s[i](o[i],n[i]));return typeof o.mioEnabled=="boolean"?n.mioEnabled=o.mioEnabled:typeof o.mioApiEnabled=="boolean"&&(n.mioEnabled=o.mioApiEnabled),n.mioApiEnabled=n.mioEnabled,n}const vA=new Set(["wallpaper","accent","customAccent","customGradient","customImage","wallpaperSettings","dockSize","windowRadius","adminBarMode","desktopLayout","dockPlacement","dockBehavior","sideDockBehavior","dockRailRenderer","desktopTheme"]);function bA(e){if(!Ge(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(o===""||!Ci.test(o)||!Ge(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 EA(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 Yp(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 _A(e){const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(s===""||!Ge(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 Li=null;const SA=250;let Jt=null;function kA(e){Jt=Qt(e)}function Qt(e){return{...e,customGradient:{...e.customGradient},customImage:e.customImage?{...e.customImage}:null,wallpaperSettings:Object.fromEntries(Object.entries(e.wallpaperSettings).map(([t,n])=>[t,{...n}])),ai:{...e.ai},mioStyle:{appearance:{...e.mioStyle.appearance},physics:{...e.mioStyle.physics}},appliedThemeRecommendations:e.appliedThemeRecommendations.slice(),nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),nativePagesHiddenColumns:e.nativePagesHiddenColumns.slice(),navPlacement:{...e.navPlacement},navOrder:e.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function IA(e,t={}){ec(e),AA(e,t.windowId)}function ec(e){try{window.localStorage.setItem(Wu,JSON.stringify(e))}catch{}}function AA(e,t){Li!==null&&clearTimeout(Li),t&&(tc=t),Nt("pending"),Li=setTimeout(()=>{Li=null;const n=tc;tc=null,Xp(e,n)},SA)}let tc=null;function CA(e){if(!Jt)return{...e};const t=Jt,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 nc=!1,oc=null;function Xp(e,t){if(nc){oc={state:e,windowId:t},Nt("pending");return}const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Nt("saved",void 0,void 0,e);return}const i=CA(e);if(!i){Nt("saved",void 0,void 0,e);return}Nt("saving"),nc=!0;const r=Qt(e),a=t||Cn;Le(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}`);Jt=r,Nt("saved",void 0,void 0,r)}).catch(l=>{Ti=!0,Jt?(ec(Jt),Nt("failed",l instanceof Error?l.message:String(l),Qt(Jt))):Nt("failed",l instanceof Error?l.message:String(l))}).finally(()=>{nc=!1;const l=oc;if(oc=null,l&&Ti){Ti=!1;return}Ti=!1,l&&Xp(l.state,l.windowId)})}let Ti=!1;function Nt(e,t,n,o){const s={phase:e};o&&(s.savedSettings=Qt(o)),t&&(s.error=t),n&&(s.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:s}))}function Zp(){return Qt(Ln)}function LA(e,t=Ln.ai){if(!Ge(e))return{...t};const{enabled:n}=e;return{enabled:typeof n=="boolean"?n:t.enabled}}function TA(e){if(!Ge(e))return{...Ln.customGradient};const{from:t,to:n,angle:o}=e;return{from:Gp(t)?t:Ln.customGradient.from,to:Gp(n)?n:Ln.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:Ln.customGradient.angle}}function NA(e){if(!Ge(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 sc(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 OA(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function Ni(e,t,n){if(!OA(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 DA="data-os-constellation";function RA(){return document.body.hasAttribute(DA)}const Jp="os-item-menu-opening",xA=180,MA=220,Qp=32;function eh(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"&&(RA()&&(t.dataset.menuSlug||t.dataset.constellationId)||WA(e)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},xA))))},u=h=>{n&&h.relatedTarget instanceof Node&&n.contains(h.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},MA)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=PA(e,()=>c(),r),document.body.appendChild(n),zA(n),jA(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,l()}),n.addEventListener("pointerleave",h=>{h.relatedTarget instanceof Node&&t.contains(h.relatedTarget)||(i=!1,f())})},g=()=>c();return t.addEventListener("pointerenter",d),t.addEventListener("pointerleave",u),document.addEventListener(Jp,g),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(Jp,g),c()}}function WA(e){return e.getInstances().length>=1}function PA(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",ae(b("%s — open windows"),e.item.title));const s=document.createElement("div");s.className="os-dock-peek__cards",o.appendChild(s);const i=e.getInstances();let r=0;for(const a of i){const l=$A(a,e,r++,t,n);s.appendChild(l)}if(e.enableGhost!==!1){const a=BA(e,r,t);s.appendChild(a)}return o}function th(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function $A(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*Qp}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${sc(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",dE(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 R=document.createElement("span");R.className="os-dock-peek__card-line",f.appendChild(R)}const p={window:e,item:t.item},g=X(y.DOCK_PEEK_CARD_CONTENT,f,p);g!==f&&g.classList.add("os-dock-peek__card-body--custom"),i.appendChild(g),e.state==="minimized"&&(i.dataset.state="minimized");const h=()=>{s.delete(e.id),delete i.dataset.preview},m=S=>{if(h(),S.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(S.previouslyFocusedId){const R=t.windowManager.getById(S.previouslyFocusedId);R&&t.windowManager.focus(R)}};return i.addEventListener("click",()=>{h(),UA(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const S=e.state==="minimized",R=t.windowManager.getFocused(),$=R&&R!==e?R.id:null;(S||$!==null)&&(s.set(e.id,{wasMinimized:S,previouslyFocusedId:$}),i.dataset.preview=""),S?th(e,i):R&&R!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const S=s.get(e.id);S&&m(S)}),X(y.DOCK_PEEK_CARD_ELEMENT,i,p)}function UA(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),th(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 BA(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*Qp}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=ae(b("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{FA(e,n)}),o}function FA(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const HA=12,GA=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function zA(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of GA){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function jA(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(()=>VA(e))}function VA(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=HA;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 Uo(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 nh(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 oh=new Map;function KA(e){const t=oh.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 oh.set(e,n),n}function qA(){const e=new Set,t=document.querySelectorAll('script[src*="load-scripts.php"]');for(const n of Array.from(t))for(const o of KA(n.src))e.add(o);return e}const YA=["-js","-js-before","-js-after","-js-extra","-js-translations"];function XA(e){return e?YA.some(t=>{const n=document.getElementById(e+t);return!!n&&n.tagName==="SCRIPT"}):!1}function ic(e){return e.url&&nh(e.url)?!0:e.handle?qA().has(e.handle)||XA(e.handle):!1}const Oi=new Map,sh=new Set;function fe(e,t){const n=Oi.get(e);if(n)return n;const o=t?.deps;if(o&&o.length>0){const i=a=>ic(a)?Promise.resolve():a.url?fe(a.url,{...a,deps:void 0}):(ZA(a),Promise.resolve()),r=o.reduce((a,l)=>a.then(()=>i(l)),Promise.resolve(void 0)).then(()=>ih(e,t));return Oi.set(e,r),r}const s=ih(e,t);return Oi.set(e,s),s}function ZA(e){if(e.handle){if(sh.has(e.handle))return;sh.add(e.handle)}for(const t of e.l10n??[])Ot(t);for(const t of e.before??[])Ot(t);for(const t of e.after??[])Ot(t)}function ih(e,t){return new Promise((n,o)=>{const s=`script[data-os-vendor="${JA(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=nh(e);if(r){r.dataset.osVendor=e,r.dataset.loaded="1",n();return}if(ic({handle:t?.handle})){n();return}t?.translations&&Ot(t.translations);for(const l of t?.l10n??[])Ot(l);for(const l of t?.before??[])Ot(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??[])Ot(l);n()},{once:!0}),a.addEventListener("error",()=>{Oi.delete(e),a.remove(),o(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(a)})}function Ot(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function rh(e){Ot(e)}function JA(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let ah=0;function ch(){return window.openStationItemVisibilityMenu??null}function QA(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function lh(e){const t=ch();if(t){t.openItemVisibilityMenu(e);return}const n=QA();if(!n)return;const o=++ah;fe(n).then(()=>{o===ah&&ch()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const e0={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function t0(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function dh(e){return e==="core"?"core":e==="control"?"controls":"apps"}function uh(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??e0[e.kind]}function fh(e){return e==="rail"||e==="both"}function n0(e){return e==="desktop"||e==="both"}function o0(e,t,n){return fh(e)?"rail":"hidden"}function ph(e,t){if(t.length===0||e.length<=1)return e.slice();const n=new Map;for(const i of e)n.set(i.id,i);const o=[],s=new Set;for(const i of t){const r=n.get(i);r&&!s.has(i)&&(o.push(r),s.add(i))}for(const i of e)s.has(i.id)||o.push(i);return o}function s0(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 hh(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 Di(){return window.wp?.os??null}function i0(){const e=Di()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function r0(){return Di()?.getNavItems?.()??[]}function a0(e){const t=r0();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function c0(e){const t=Di();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 l0(e,t,n){const o=Array.isArray(e)?e:[e],s=i0().placement,i=[];for(const r of o){const a=typeof r=="string"?a0(r):r;a&&i.push({item:a,placement:o0(uh(a,s))})}c0(i)}function d0(e){const t=Di();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:s0(n,e)})}const ct=["core","apps","controls"];function mh(e){const{items:t,config:n,layout:o,openWindows:s}=e,i={core:[],apps:[],controls:[]},r=[],a=[],l=new Set,c=new Set,d=new Map,u=new Set;for(const p of t){u.add(p.id),p.windowId&&!d.has(p.windowId)&&d.set(p.windowId,p);const g=uh(p,n.placement);if(fh(g)){c.add(p.id);const h=dh(p.kind);t0(p.kind,o)==="sidebar"?r.push(p):i[h].push(p)}n0(g)&&a.push(p)}for(const p of t)for(const g of p.answersFor??[])d.has(g)||d.set(g,p);for(const p of s){const g=d.get(p.id);if(g){if(c.has(g.id)||l.has(g.id))continue;i.apps.push(g),l.add(g.id);continue}p.fromAdminUrl||l.has(p.id)||u.has(p.id)||(i.apps.push({id:p.id,kind:"app",title:p.title,icon:p.icon,windowId:p.id,transient:!0}),l.add(p.id))}const f=p=>ph(u0(hh(p)),n.order);for(const p of ct)i[p]=f(i[p]);return{dock:i,sidebar:f(r),desktop:ph(hh(a),n.order),ephemeral:l}}function u0(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 f0=["action","action2","_wpnonce","nonce","delete_all"];function p0(e){const t=e.slice(e.lastIndexOf("/")+1);return/-new\.php$/.test(t)}function h0(e){if(p0(e.pathname))return!0;for(const t of f0)if(e.searchParams.has(t))return!0;return!1}function gh(e){return dh(e.navKind??"app")}const $e=class $e{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/${++$e.instanceCounter}`,this.container.classList.add("os-dock--no-transition"),this.container.setAttribute("data-os-dock-placement",i),this.container.offsetWidth,this.container.classList.remove("os-dock--no-transition");const r=document.createElement("div");r.className="os-dock__scroll";const a=document.createElement("div");a.className="os-dock__pinned",t.appendChild(r),t.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="os-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.zones=this.zonesFromMenu(o,[]),this.render(),this.bindWindowEvents()}buildHookContextBase(){return{rail:this.rail,orientation:this.orientation,dockId:this.container.id,container:this.container}}setOrientation(t){this.orientation!==t&&(this.orientation=t,this.container.setAttribute("data-os-dock-placement",t),this.tooltip.classList.remove("os-dock__tooltip--above","os-dock__tooltip--before","os-dock__tooltip--after"),t==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):t==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"))}replaceItems(t){this.zones=this.zonesFromMenu(t,this.systemEntries()),this.render()}setZones(t){this.zones={core:t.core.slice(),apps:t.apps.slice(),controls:t.controls.slice()},this.render()}systemEntries(){const t=[];for(const n of ct)for(const o of this.zones[n])o.type==="system"&&t.push(o);return t}zonesFromMenu(t,n){const o={core:[],apps:[],controls:[]};for(const s of t)o[s.isCore?"core":"apps"].push({type:"menu",item:s});for(const s of n)s.type==="system"&&o[gh(s.item)].push(s);return o}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(t){let n=!1;for(const o of ct){const s=this.zones[o].filter(i=>i.type!=="system"||i.item.id!==t);s.length!==this.zones[o].length&&(n=!0),this.zones[o]=s}n&&(this.badgeOverrides.delete(t),this.artOverrides.delete(t),this.render(),C(y.DOCK_ITEM_REMOVED,{id:t,placement:this.rail}))}setBadge(t,n){const o=this._resolveTileElement(t);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(t):this.badgeOverrides.set(t,s);const i=o.querySelector(".os-dock__item-primary");wh(i??o,s),Se.publish("os/badge-changed",{itemId:t,count:s,rail:this.rail})}clearBadge(t){this.setBadge(t,0)}setArt(t,n){if(!n){if(!this.artOverrides.delete(t))return;const s=this._resolveTileElement(t),i=this._declaredIcon(t);s&&i&&this._paintArt(s,t,i),Se.publish("os/art-changed",{itemId:t,icon:"",rail:this.rail});return}this.artOverrides.set(t,n);const o=this._resolveTileElement(t);o&&(this._paintArt(o,t,n),Se.publish("os/art-changed",{itemId:t,icon:n,rail:this.rail}))}getArt(t){return this.artOverrides.get(t)??""}_declaredIcon(t){const n=this.items.find(s=>s.id===t);if(n)return n.icon;const o=this.systemItems.find(s=>s.id===t);return o?o.icon:""}_paintArt(t,n,o){const s=t.querySelector(".os-dock__item-primary")??t,i=this.resolveIcon(o,this._declaredTitle(n),void 0,ii(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=gh(t),o={type:"system",item:t};for(const a of ct)this.zones[a]=this.zones[a].filter(l=>l.type!=="system"||l.item.id!==t.id);const s=this.zones[n],i=t.order??0,r=s.findIndex(a=>a.type==="system"&&(a.item.order??0)>i);r===-1?s.push(o):s.splice(r,0,o),this.render()}render(){if($e.activeDragReset){const o=$e.activeDragReset;$e.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="",this.systemHost.innerHTML="",this.itemElements.clear(),this.systemItemElements.clear(),this.items=[],this.systemItems=[];for(const o of ct)for(const s of this.zones[o])s.type==="menu"?this.items.push(s.item):this.systemItems.push(s.item);const t=this.buildHookContextBase();C(y.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of ct){const s=this.zones[o];if(s.length===0)continue;const i=o==="controls"?this.systemHost:this.itemHost;if(n){const r=document.createElement("div");r.className=o==="controls"?"os-dock__separator":"os-dock__separator os-dock__separator--group",r.setAttribute("aria-hidden","true"),i.appendChild(r)}for(const r of s)this.paintEntry(r,o,i,t);n=!0}this.updateActiveStates(),C(y.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}paintEntry(t,n,o,s){const i=t.item.id,r=t.type==="menu"?this.createItemButton(t.item):this.createSystemItemButton(t.item);r.dataset.zone=n,r.dataset.navId=i,t.type==="system"&&t.item.locked===!0?r.dataset.navLocked="true":(this.attachDragReorder(r,i,n),r.addEventListener("contextmenu",d=>{d.preventDefault(),lh({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");wh(d??r,l)}const c=this.artOverrides.get(i);c&&this._paintArt(r,i,c),C(y.DOCK_TILE_RENDERED,{...s,item:t.item,isSystem:t.type==="system",el:r})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=X(y.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id,o.dataset.osWindowBaseId=t.id,t.submenu&&t.submenu.length>0&&(o.dataset.constellationId=t.id);const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title,void 0,ii(t.id))),r.addEventListener("click",l=>t.onOpen(l)),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=eh({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)),X(y.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];t.multi&&s.push("os-dock__item--multi");const i=X(y.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const a=this.resolveIcon(t.icon,t.title,t.url,ii(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",ae(Gt("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const l=this.resolveItemBaseId(t);o.dataset.osWindowBaseId=l;const c=eh({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),X(y.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n,o){let r=!1,a=0,l=0,c=[],d=null,u=-1,f=null,p=!1;const g=()=>{r=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",B),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",K,!0),window.removeEventListener("blur",Z),document.removeEventListener("visibilitychange",Y),u=-1,f=null},h=o==="controls"?this.systemHost:this.itemHost,m=L=>!!L&&L instanceof HTMLElement&&L.classList.contains("os-dock__item")&&L.dataset.zone===o&&!!L.dataset.navId&&L.dataset.navLocked===void 0,E=L=>{for(const x of Array.from(h.children))x instanceof HTMLElement&&x!==t&&m(x)&&L(x)},S=()=>{const L=[];for(const x of Array.from(h.children))m(x)&&L.push(x.dataset.navId);return L},R=L=>{E(x=>{const j=L.get(x);if(!j)return;const V=x.getBoundingClientRect(),J=j.left-V.left,O=j.top-V.top;if(Math.abs(J)<.5&&Math.abs(O)<.5)return;x.style.transition="none",x.style.transform=`translate(${J}px, ${O}px)`,x.offsetHeight,x.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",x.style.transform="";const T=()=>{x.style.transition="",x.style.transform="",x.removeEventListener("transitionend",T)};x.addEventListener("transitionend",T)})},$=L=>{if(u!==-1&&L.pointerId!==u)return;if(!r){const I=L.clientX-a,N=L.clientY-l;if(I*I+N*N<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 x=L.clientX-a,j=L.clientY-l;t.style.transform=`translate(${x}px, ${j}px)`;const J=document.elementFromPoint(L.clientX,L.clientY)?.closest(".os-dock__item");if(!J||J===t||!m(J))return;const O=J.getBoundingClientRect();let T;this.orientation==="bottom"?T=L.clientX<O.left+O.width/2:T=L.clientY<O.top+O.height/2;const W=new Map;E(I=>{W.set(I,I.getBoundingClientRect())});let v=!1;if(T?J!==t.nextSibling&&(h.insertBefore(t,J),v=!0):J.nextSibling!==t&&(h.insertBefore(t,J.nextSibling),v=!0),v){t.style.transform="";const I=t.getBoundingClientRect();a=I.left+I.width/2,l=I.top+I.height/2,t.style.transform=`translate(${L.clientX-a}px, ${L.clientY-l}px)`,R(W)}},_=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",B),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",K,!0),window.removeEventListener("blur",Z),document.removeEventListener("visibilitychange",Y),u=-1,f=null,r=!1,$e.activeDragReset===g&&($e.activeDragReset=null)},M=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const L=()=>{t.style.transition="",t.removeEventListener("transitionend",L)};t.addEventListener("transitionend",L)},P=L=>{d0(L)},B=L=>{if(u!==-1&&L.pointerId!==u)return;if(!r){_();return}p=!0;const x=S();M(),_(),x.length===c.length&&x.every((V,J)=>V===c[J])||P(x),setTimeout(()=>{p=!1},200)},F=L=>{if(!(L&&u!==-1&&L.pointerId!==u)){if(r&&d!==void 0){const x=new Map;E(j=>{x.set(j,j.getBoundingClientRect())}),h.insertBefore(t,d),R(x)}M(),_()}},K=L=>{L.key==="Escape"&&F()},Z=()=>F(),Y=()=>{document.visibilityState!=="visible"&&F()};t.addEventListener("pointerdown",L=>{if(!(L.button!==0||Ht())){if($e.activeDragReset){const x=$e.activeDragReset;$e.activeDragReset=null,x()}(r||u!==-1)&&g(),a=L.clientX,l=L.clientY,u=L.pointerId,r=!1,$e.activeDragReset=g,document.addEventListener("pointermove",$),document.addEventListener("pointerup",B),document.addEventListener("pointercancel",F),document.addEventListener("keydown",K,!0),window.addEventListener("blur",Z),document.addEventListener("visibilitychange",Y)}}),t.addEventListener("click",L=>{p&&(L.preventDefault(),L.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=si(s);a!==null&&(t=a,i=!0),r=ga(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if(Ni(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(Ni(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=sc(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=X(y.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("os-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("os-dock__tooltip--visible")}))}positionTooltip(t,n){const o=t.getBoundingClientRect();this.tooltip.textContent=n,this.orientation==="bottom"?(this.tooltip.style.left=`${o.left+o.width/2}px`,this.tooltip.style.top=`${o.top-14}px`):this.orientation==="right"?(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.left}px`):(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.right+8}px`)}bindHoverPrewarm(t,n){if(!n.url){const{windowId:o}=n;o&&this.bindPrewarmDwell(t,()=>this.prewarmNativeWindow(o));return}this.bindPrewarmDwell(t,()=>{const o=Ei(n.url);if(o){this.prewarmNativeWindow(o);return}try{const i=new URL(n.url,window.location.href);if(i.origin!==window.location.origin||h0(i)||bo(i))return}catch{return}const s=this.deriveWindowId(n.url);this.windowManager.prewarm({id:s,baseId:s,url:n.url,parentUrl:n.url,title:n.title,icon:n.icon.startsWith("dashicons-")?n.icon:"dashicons-admin-generic",submenu:n.submenu,selfLabel:n.selfLabel,multi:!!n.multi})})}bindPrewarmDwell(t,n){let s;const i=()=>{s!==void 0&&(window.clearTimeout(s),s=void 0)};t.addEventListener("pointerenter",r=>{r.pointerType!=="mouse"||!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled||(i(),s=window.setTimeout(()=>{s=void 0,n()},180))}),t.addEventListener("pointerleave",i),t.addEventListener("pointerdown",i)}prewarmNativeWindow(t){if(this.windowManager.getById(t))return;window.wp?.os?.prewarmWindow?.(t)}openPage(t){if(t.windowId&&!t.url){const o=this.windowManager.getById(t.windowId);if(o){const i=o.state==="minimized";this.windowManager.focus(o),i&&o.restore();return}window.wp?.os?.openWindow?.(t.windowId);return}if(Uo(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(Uo(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=Ei(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 ue(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:Ei(t.url)??this.deriveWindowId(t.url)}bindWindowEvents(){const t=()=>this.updateActiveStates();this.boundRefresh=t,document.addEventListener("os-window-opened",t),document.addEventListener("os-window-closed",t),document.addEventListener("os-window-focused",t),window.wp?.hooks?.addAction?.("os.os.switched",this.hooksNamespace,t),window.wp?.hooks?.addAction?.("os.os.closed",this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(y.DOCK_REFRESH_ACTIVE,this.hooksNamespace,t)}destroy(){document.removeEventListener("os-window-opened",this.boundRefresh),document.removeEventListener("os-window-closed",this.boundRefresh),document.removeEventListener("os-window-focused",this.boundRefresh),window.wp?.hooks?.removeAction?.("os.os.switched",this.hooksNamespace),window.wp?.hooks?.removeAction?.("os.os.closed",this.hooksNamespace),window.wp?.hooks?.removeAction?.(y.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(y.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(y.WINDOW_RESTORED,this.hooksNamespace);for(const t of this.attentionTimers.values())window.clearTimeout(t);this.attentionTimers.clear();for(const t of this.peekTeardowns.values())t();for(this.peekTeardowns.clear(),this.tooltip.remove();this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.itemElements.clear(),this.systemItemElements.clear(),this.systemItems=[],this.zones={core:[],apps:[],controls:[]},this.container.removeAttribute("data-os-dock-placement")}updateActiveStates(){const t=this.windowManager.getFocused(),n=this.windowManager.getActiveDesktopId(),o=i=>(i.config.desktopId||n)===n,s=i=>i.state==="minimized";for(const i of this.items){const r=this.itemElements.get(i.id);if(!r)continue;const a=this.resolveItemBaseId(i);let l=this.windowManager.getAllByBaseId(a).filter(o);if(l.length===0&&i.url){const f=this.deriveWindowId(i.url);l=this.windowManager.getAll().filter(p=>{const g=p.config.baseId||p.id;if(g===a||g===f||g===i.id||p.config.parentUrl&&this.deriveWindowId(p.config.parentUrl)===f)return!0;if(p.config.url){const h=this.deriveWindowId(p.config.url);return h===a||h===f}return!1}).filter(o)}const c=l.length>0,d=c&&l.every(s),u=!!t&&o(t)&&!s(t)&&l.some(f=>f.id===t.id||(t.config.baseId||t.id)===a);r.classList.toggle("os-dock__item--active",c),r.classList.toggle("os-dock__item--focused",u),r.classList.toggle("os-dock__item--all-minimized",d),r.classList.toggle("os-dock__item--stacked",c&&l.length>1)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const a=this.windowManager.getById(i.id),l=i.isOpen?i.isOpen():!!a,c=!!a&&s(a),d=!!t&&t.id===i.id&&!s(t);r.classList.toggle("os-dock__item--active",l),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",c)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("os-show-desktop-active",o)}};$e.instanceCounter=0,$e.activeDragReset=null;let Ri=$e;function wh(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",ae(Gt("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="os-dock__badge",s.textContent=o,s.setAttribute("aria-label",ae(Gt("%d notification","%d notifications",t),t)),e.appendChild(s)}const yh=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),rc={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 Ri(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[yh]: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 vh(e){if(!e)return null;const n=e[yh];return n instanceof Ri?n:null}function m0(){cu(rc)}const bh="os-desktop-theme-css",g0="os-desktop-theme-inline-css",ac="data-os-desktop-theme-css",Eh="os-desktop-theme-changed";function _h(){return document.getElementById("os-shell")}function Sh(){const e=[];for(const t of[bh,g0]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${ac}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function cc(){for(const e of Sh())e.remove()}function w0(e){const t=_h();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:Sh().length>0}function kh(e){if(e.cssUrl!==""){const t=document.createElement("link");t.id=bh,t.rel="stylesheet",t.href=e.cssUrl,t.setAttribute(ac,e.slug),document.head.appendChild(t)}else if(e.cssText!==""){const t=document.createElement("style");t.setAttribute(ac,e.slug),t.textContent=e.cssText,document.head.appendChild(t)}}function Ih(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 lc(e){const t=Tn(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:ha(o),i=s?s.slug:null;if(i===n)return;const r=_h();if(!s)r?.removeAttribute("data-os-desktop-theme"),Ih(null),cc(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!w0(s.slug))if(s.cssDeferred&&s.cssUrl===""&&s.cssText===""){const l=s.slug,c=()=>zu().then(()=>{if(Tn().state.activeId!==l)return;const d=ha(l);if(!d||d.cssDeferred)throw new Error(`theme "${l}" resolved without a stylesheet`);cc(),kh(d)}).catch(d=>{Tn().state.activeId===l&&(de({message:b("Could not load that desktop theme — the previous one is still showing."),action:{label:b("Retry"),onClick:()=>void c()},persistent:!0,dismissible:!0}),console.warn("[openstation] desktop theme stylesheet failed to load",d))});c()}else cc(),kh(s);r?.setAttribute("data-os-desktop-theme",s.slug),Ih(s.slug),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};C(y.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(Eh,{detail:a}))}function y0(e={}){const t=e.deactivate??(()=>lc(""));return function(o){T_(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=Tn().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const v0="",b0="system-default",E0={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function _0(e,t,n={}){const o=t===v0,s=o?null:ha(t);if(!o&&!s)return{};const i=o?b0:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=S_(o?E0: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 Ah(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}function S0(e,t){Mn({id:v_,label:b("Custom gradient"),type:"css",preview:Ah(e()),description:b("Mix your own two-colour gradient and set the angle — your desk, your palette."),resolveValue:()=>Ah(e())})}function k0(e){if(!e.customImage){Po(ei)&&Pp(ei);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`,o=Po(ei);o&&o.type==="css"&&o.value===n||Mn({id:ei,label:b("Custom image"),type:"css",value:n,preview:n,description:b("Any image from your media library or an upload, sized to cover the whole desk.")})}function I0(e){const t=/^#?([0-9a-f]{6})$/i.exec(e.trim());if(!t)return!1;const n=i=>{const r=parseInt(i,16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4},o=t[1];return .2126*n(o.slice(0,2))+.7152*n(o.slice(2,4))+.0722*n(o.slice(4,6))>.35}function Ch(e){return JSON.parse(JSON.stringify(e))}function A0(e,t){return e===t?!0:typeof e!="object"||typeof t!="object"||e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}class C0{constructor(t){this.listeners=new Set,this.baseState=null,this.overridePatch=null,this.layer=t,this.state=wA(),document.addEventListener("os-settings-save-lifecycle",n=>{const o=n.detail;!o||(window.wp?.os?.windowManager?.getById(Cn)?.markActivity(o.phase,{error:o.error}),o.phase!=="failed"||!o.rolledBackTo)||(this.state=o.rolledBackTo,this.apply(),this.notify())}),S0(()=>this.state)}getOsSettingsSnapshot(){return Qt(this.state)}subscribeOsSettings(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}apply(){const t=document.getElementById("os-shell");if(!t)return;iA(this.state.wallpaperSettings),k0(this.state);const n=Po(this.state.wallpaper)||Po(da())||Po(la)||Ya()[0];n&&this.layer.apply(n);const o=ti(),s=o.find(g=>g.id===this.state.accent)??o[0],i=this.state.accent===Pu?this.state.customAccent:s.value,r=ua.find(g=>g.id===this.state.dockSize)??ua[1],a=fa.find(g=>g.id===this.state.windowRadius)??fa[1],l=document.body;l.style.setProperty("--wp-admin-theme-color",i),l.style.setProperty("--os-ui-accent",i);const c=I0(i)?"#0c0b0f":"#fffbff";l.style.setProperty("--os-ui-accent-ink",c);const u=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;u===null?l.style.removeProperty("--os-ui-accent-dim"):l.style.setProperty("--os-ui-accent-dim",u),t.style.setProperty("--os-ui-accent",i),t.style.setProperty("--os-ui-accent-ink",c),u===null?t.style.removeProperty("--os-ui-accent-dim"):t.style.setProperty("--os-ui-accent-dim",u),l.style.setProperty("--os-dock-width",`${r.width}px`),l.style.setProperty("--os-dock-icon-size",`${r.icon}px`),t.style.setProperty("--os-dock-width",`${r.width}px`),t.style.setProperty("--os-dock-icon-size",`${r.icon}px`),l.style.setProperty("--os-window-radius",`${a.value}px`),t.style.setProperty("--os-window-radius",`${a.value}px`);const f=ni.find(g=>g.id===this.state.adminBarMode)??ni[0];for(const g of ni)document.body.classList.toggle(`os-admin-bar-${g.id}`,g.id===f.id);const p=g=>(oi.find(h=>h.id===g)??oi[0]).id;document.getElementById(aA)?.setAttribute($o,p(this.state.dockBehavior)),document.getElementById(Fp)?.setAttribute($o,p(this.state.sideDockBehavior)),hA(),ok(),t.setAttribute("data-os-layout",this.state.desktopLayout),HE(this.state.dockRailRenderer),lc(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=Ch(t),this.state={...n,...Ch(t)};this.apply(),this.notify()}save(t={}){IA(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))A0(o[r],s[r])&&(o[r]=i[r]);return o}update(t,n={}){const o={...t};delete o.appliedThemeRecommendations,delete o.adminAssetCacheEnabled,delete o.windowPrewarmEnabled;const s=Qa(o,this.state),i=qp.filter(r=>r in o);Object.assign(this.state,s),this.save(n),i.some(r=>vA.has(r))&&this.apply()}applyThemeRecommendations(t){const n=_0(this.state,t,{force:!0});return Object.keys(n).length>0&&(this.save(),this.apply()),n}reset(t={}){const n=Zp();n.wallpaper=da(),n.customImage=this.state.customImage,n.adminAssetCacheEnabled=this.state.adminAssetCacheEnabled,n.windowPrewarmEnabled=this.state.windowPrewarmEnabled,Object.assign(this.state,n),this.save(t),this.apply()}notify(){if(this.listeners.size===0)return;const t=this.getOsSettingsSnapshot();for(const n of Array.from(this.listeners))try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] os-settings listener threw:",o)}}}const L0="os-network-admin";function T0(e,t){const n=e.networkAdmin;return!n||e.isNetworkAdmin?null:{id:L0,title:b("Network Admin"),icon:"dashicons-admin-multisite",placeable:!0,navKind:"core",onOpen:o=>t(n.url,o),get submenu(){return n.rows.map(({title:o,url:s})=>({title:o,url:s,onSelect:i=>t(s,i)}))}}}function Lh(e){return!!e&&(e.metaKey||e.ctrlKey||e.shiftKey||e.button===1)}function dc(e,t){if(Lh(t)){window.open(e,"_blank","noopener,noreferrer");return}window.location.assign(e)}function N0(e){return async(t,n)=>{try{const o=await Le(e.hopUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({target:t,direction:n})},{source:"desktop-mode/network-hop"});if(!o.ok)return null;const s=await o.json();return typeof s.url=="string"&&s.url!==""?s.url:null}catch{return null}}}const O0=220,D0=360,R0=4e3,uc="openstation-hop-direction",fc="os-shell--arriving",Th="os-shell--revealing";function pc(){return document.getElementById("os-shell")}function Nh(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function x0(e){try{window.sessionStorage.setItem(uc,e)}catch{}const t=pc();return!t||Nh()?Promise.resolve():(t.classList.add(`os-shell--hop-out-${e}`),new Promise(n=>{window.setTimeout(n,O0)}))}function M0(){try{const e=window.sessionStorage.getItem(uc);return window.sessionStorage.removeItem(uc),e==="next"||e==="prev"?e:null}catch{return null}}function W0(e=null){const t=pc();if(!t||!t.classList.contains(fc))return;const n=M0()??e;n&&t.classList.add(`os-shell--arriving-${n}`),window.setTimeout(Oh,R0)}function Oh(){const e=pc();!e||!e.classList.contains(fc)||(e.classList.remove(fc,"os-shell--arriving-next","os-shell--arriving-prev"),!Nh()&&(e.classList.add(Th),window.setTimeout(()=>e.classList.remove(Th),D0)))}function $n(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function P0(e){return!!e&&e.__wpdHtml===!0}const $0="$$wpd$$",Oe=/\$\$wpd\$\$(\d+)\$\$/g,U0="$$wpd-node$$",B0=/^\$\$wpd-node\$\$(\d+)\$\$$/,F0=new Set(["style","script","textarea","title"]);function H0(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,F0.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?`${$0}${l}$$`:`<!--${U0}${l}$$-->`)}return t}const Dh=new WeakMap;function Rh(e){const t=Dh.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=H0(e);const o=[],s=(a,l)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const f of Array.from(u.attributes)){const p=f.name,g=f.value,h=p[0];if(Oe.test(g))if(Oe.lastIndex=0,h==="@"){const m=Oe.exec(g);Oe.lastIndex=0,o.push({path:l,kind:"event",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else if(h==="."){const m=Oe.exec(g);Oe.lastIndex=0,o.push({path:l,kind:"prop",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else if(h==="?"){const m=Oe.exec(g);Oe.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else{const m=[],E=[];let S=0,R;for(Oe.lastIndex=0;(R=Oe.exec(g))!==null;)m.push(g.slice(S,R.index)),E.push(Number(R[1])),S=R.index+R[0].length;m.push(g.slice(S)),o.push({path:l,kind:"attr",name:p,template:m,valueIndices:E}),u.setAttribute(p,"")}}}const c=Array.from(a.childNodes);let d=0;for(let u=0;u<c.length;u++){const f=c[u],p=u+d;if(f.nodeType===Node.COMMENT_NODE){const g=B0.exec(f.data);if(g){const h=document.createTextNode("");f.parentNode.replaceChild(h,f),o.push({path:[...l,p],kind:"node",valueIndex:Number(g[1])})}continue}if(f.nodeType===Node.TEXT_NODE){const g=f.textContent||"";if(!Oe.test(g)){Oe.lastIndex=0;continue}Oe.lastIndex=0;const h=f.parentNode;let m=0,E;const S=[],R=[];for(Oe.lastIndex=0;(E=Oe.exec(g))!==null;){E.index>m&&S.push(document.createTextNode(g.slice(m,E.index)));const $=document.createTextNode("");S.push($),R.push({path:[...l,p+S.length-1],kind:"node",valueIndex:Number(E[1])}),m=E.index+E[0].length}m<g.length&&S.push(document.createTextNode(g.slice(m)));for(const $ of S)h.insertBefore($,f);h.removeChild(f),d+=S.length-1,o.push(...R)}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 Dh.set(e,r),r}const xh=new WeakMap;function G0(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function z0(e,t){const n=xh.get(t);if(n&&n.strings===e.strings&&G0(n,t)){xi(n.parts,e.values);return}const o=Rh(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),xi(i,e.values),xh.set(t,{strings:e.strings,parts:i,nodes:r})}function xi(e,t){for(const n of e)if(n.kind==="node")Mi(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+=Mh(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 Mi(e,t){if(t==null||t===!1){e.state&&(Dt(e.state),e.state=null);return}if(Array.isArray(t)){q0(e,t);return}if(P0(t)){K0(e,t);return}if(t instanceof Node){j0(e,t);return}V0(e,Mh(t))}function j0(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Dt(n),Bo(e,[t]),e.state={shape:"node",node:t})}function V0(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Dt(n);const o=document.createTextNode(t);Bo(e,[o]),e.state={shape:"text",node:o,text:t}}function K0(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){xi(n.parts,t.values);return}n&&Dt(n);const o=Rh(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);Bo(e,[s]),xi(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function q0(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++)Mi(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&&Dt(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("");Bo(e,[r]);const a={anchor:r,state:null};Mi(a,t[i]),n.entries.push(a)}return}n&&Dt(n);const o=[];for(const s of t){const i=document.createTextNode("");Bo(e,[i]);const r={anchor:i,state:null};Mi(r,s),o.push(r)}e.state={shape:"array",entries:o}}function Bo(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Dt(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&&(Dt(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&&Dt(t.state),t.anchor.remove()}function Mh(e){return e==null||e===!1?"":String(e)}const Ft=class Ft 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(Wh)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=Y0(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=Wh(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&&z0(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(!Ft._lightStylesAdopted.has(t)){Ft._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)}}}};Ft.props=[],Ft.styles=[],Ft.shadow=!0,Ft._lightStylesAdopted=new WeakSet;let en=Ft;function Fo(e,t){customElements.get(e)||customElements.define(e,t)}function Wh(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Y0(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const X0=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function Ce(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(X0){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}const hc=Ce`: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 ) )}`,Z0=Ce` .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%}}`,Ph=Ce` .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%}}`,J0=Ce` .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}}`,Q0=Ce` .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}}`,eC=Ce` .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}}`,tC=Ce` .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%}}`,nC=Ce` .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}}`,oC=Ce` 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}}`,sC=Ce` input[ type='checkbox' ],input[ type='radio' ]{appearance:none;-webkit-appearance:none;position:relative;flex:0 0 auto;box-sizing:border-box;width:16px;height:16px;margin:0;padding:0;border:1px solid var( --_holo-track-edge );border-radius:4px;background-color:var( --_holo-track );background-image:none;background-repeat:no-repeat;cursor:inherit;transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input[ type='radio' ]{border-radius:50%}input[ type='checkbox' ]:hover:not(:disabled ),input[ type='radio' ]:hover:not(:disabled ){border-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:focus-visible,input[ type='radio' ]:focus-visible{outline:none;box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked,input[ type='checkbox' ]:indeterminate,input[ type='radio' ]:checked{border-color:transparent;background-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:checked:focus-visible,input[ type='radio' ]:checked:focus-visible{box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:46%;width:3.5px;height:7.5px;border:solid var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );border-width:0 2px 2px 0;transform:translate( -50%,-50% ) rotate( 45deg );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:indeterminate::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:8px;height:2px;border:0;border-radius:1px;background:var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );transform:translate( -50%,-50% )}input[ type='radio' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:6px;height:6px;border-radius:50%;background:var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );transform:translate( -50%,-50% );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:disabled,input[ type='radio' ]:disabled{cursor:not-allowed}@keyframes os-holo-tick{from{opacity:0;transform:translate( -50%,-50% ) rotate( 45deg ) scale( 0.4 )}}@media ( prefers-reduced-motion:reduce ){input[ type='checkbox' ]:checked::after,input[ type='radio' ]:checked::after{animation:none}}`,iC=Ce` @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}}`;Ce` ${hc} ${Z0} ${Ph} ${J0} ${Q0} ${eC} ${tC} ${nC} ${oC} ${sC} ${iC} `;const rC=Ce` ${hc}:host{display:inline-flex;position:relative;padding:3px;background:var( --os-ui-segmented-bg,var( --os-ui-hover,rgba( 0,0,0,0.05 ) ) );border-radius:8px;gap:2px;box-shadow:var( --os-ui-segmented-edge,none )}.os-segmented__thumb{position:absolute;top:3px;bottom:3px;left:0;width:var( --_thumb-w,0px );border-radius:6px;background-color:var( --os-ui-segmented-selected-bg,color-mix( in srgb,var( --os-ui-accent,#2271b1 ) var( --os-ui-segmented-selected-accent,100% ),var( --os-ui-segmented-selected-base,var( --os-ui-surface,#fff ) ) ) );background-image:var( --os-ui-segmented-selected-image,none );box-shadow:var( --os-ui-segmented-selected-shadow,none );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;transform:translateX( var( --_thumb-x,0px ) );pointer-events:none;opacity:0}:host( [ data-thumb ] ) .os-segmented__thumb{opacity:1}:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition:transform var( --_holo-t-slow ) var( --_holo-spring ),width var( --_holo-t-slow ) var( --_holo-ease ),opacity var( --_holo-t-fast ) linear}@media ( prefers-reduced-motion:reduce ){:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition-duration:1ms}}`,aC=Ce` ${hc} ${Ph}:host{flex:1 1 auto;min-width:0;--_holo-sheen:var( --os-ui-segmented-hover-sheen,var( --os-ui-holo-sheen,linear-gradient( 124deg,rgba( 159,214,255,0.1 ) 0%,rgba( 236,155,255,0.12 ) 34%,rgba( 242,82,252,0.1 ) 58%,rgba( 147,240,198,0.09 ) 100% ) ) )}button{appearance:none;display:block;width:100%;padding:6px 13px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --os-ui-fg-muted,#646970 );cursor:pointer;border-radius:6px;transition:background-color var( --_holo-t ) ease,color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,background-position var( --_holo-t ) ease;white-space:nowrap}button:hover{color:var( --os-ui-fg,#1d2327 )}:host(:not( [ aria-checked='true' ] ) ) button:hover{background-color:var( --os-ui-segmented-hover-bg,transparent )}button:focus-visible{outline:none;box-shadow:var( --_holo-focus )}:host( [ aria-checked='true' ] ) button{color:var( --os-ui-segmented-selected-fg,color-mix( in srgb,var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) ) var( --os-ui-segmented-selected-accent,100% ),var( --os-ui-fg,#1d2327 ) ) );transition-duration:var( --_holo-t-fast )}:host( [ aria-checked='true' ] ) button::before{display:none}`,Fs=class Fs extends en{render(){return this.setAttribute("role","radio"),$n`
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})}};Fs.props=["value"],Fs.styles=[aC],Fs.help=void 0;let mc=Fs;Fo("os-segment",mc);const Hs=class Hs extends en{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()}),$n`<span class="os-segmented__thumb" aria-hidden="true"></span
11 ><slot></slot>`}};Hs.props=["value","label"],Hs.styles=[rC],Hs.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:$n`
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 gc=Hs;Fo("os-segmented",gc);const cC="openstation_overview",lC="openstation_hop_from";function $h(e,t){try{const n=new URL(e,window.location.href);return n.searchParams.set(cC,"1"),t&&n.origin!==window.location.origin&&n.searchParams.set(lC,t),n.toString()}catch{return e}}function wc(e){const t=[];e.networkAdmin?.shellUrl&&t.push({value:"network",label:b("Network Admin"),shellUrl:e.networkAdmin.shellUrl,external:!1,foreign:e.networkAdmin.foreign===!0});for(const n of e.sites??[])t.push({value:n.id,label:n.name,shellUrl:n.shellUrl,external:n.kind==="member",foreign:n.foreign===!0,tabUrl:n.active===!1?n.adminUrl:void 0});return t}function yc(e,t,n={}){const o=n.hop??dc,s=wc(e),i=e.current??"",r=s.findIndex(f=>f.value===t);if(r<0||t===i)return!1;const a=s[r];if(a.tabUrl)return window.open(a.tabUrl,"_blank","noopener"),!0;const l=s.findIndex(f=>f.value===i),c=r>l?"next":"prev",d=$h(a.shellUrl,c),u=n.mint&&a.foreign?n.mint(a.shellUrl,c).catch(()=>null):Promise.resolve(null);return Promise.all([x0(c),u]).then(([,f])=>o(f??d)),!0}function dC(e){const t=n=>{if(n.key!=="Tab"||n.ctrlKey||n.metaKey||n.altKey||n.defaultPrevented)return;const o=e.multisite();if(!o||!e.isShown()||za(document))return;const i=(n.target?.ownerDocument??document).activeElement;if(i&&i.closest(".os-overview-top-bar")&&!i.closest(".os-site-switcher"))return;const r=o.current??"",a=wc(o).filter(u=>!u.tabUrl||u.value===r);if(a.length<2)return;const l=a.findIndex(u=>u.value===r),c=n.shiftKey?-1:1,d=a[(l+c+a.length)%a.length];n.preventDefault(),yc(o,d.value,e)};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)}function Uh(){const e=document.createElement("span");return e.className="dashicons dashicons-external os-site-switcher__mark",e.setAttribute("aria-hidden","true"),e}function uC(e,t={}){const n=t.hop??dc,o=wc(e);if(o.length<2)return null;const s=e.current??"",i=new Map(o.map(c=>[c.value,c])),r=document.createElement("os-segmented");r.className="os-site-switcher",r.setAttribute("label",b("Site")),r.setAttribute("value",s);let a=!1;for(const c of o){if(c.external&&!a){a=!0;const u=document.createElement("span");u.className="os-site-switcher__divider",u.setAttribute("role","separator"),u.setAttribute("aria-orientation","vertical"),r.appendChild(u)}const d=document.createElement("os-segment");if(d.setAttribute("value",c.value),c.external){d.setAttribute("data-external",""),d.title=b("External site"),d.appendChild(Uh());const u=document.createElement("span");u.className="screen-reader-text",u.textContent=b("External site:")+" ",d.appendChild(u)}else if(c.tabUrl){d.setAttribute("data-opens-tab",""),d.title=b("OpenStation is not active on this site. Opens its admin in a new tab."),d.appendChild(Uh());const u=document.createElement("span");u.className="screen-reader-text",u.textContent=b("Opens in a new tab:")+" ",d.appendChild(u)}d.appendChild(document.createTextNode(c.label)),r.appendChild(d)}const l=c=>{const d=c.target?.closest("os-segment"),u=d?i.get(d.getAttribute("value")??""):void 0;if(!u)return;if(u.tabUrl&&(c.type==="click"||c.button===1)){c.preventDefault(),c.stopPropagation(),window.open(u.tabUrl,"_blank","noopener");return}if(!Lh(c))return;c.preventDefault(),c.stopPropagation();const f=$h(u.shellUrl);if(!t.mint||!u.foreign){n(f,c);return}const p=window.open("","_blank");t.mint(u.shellUrl,"next").catch(()=>null).then(g=>{p?p.location.href=g??f:n(f,c)})};return r.addEventListener("click",l,!0),r.addEventListener("auxclick",l,!0),r.addEventListener("os-pick",c=>{const d=c.detail?.value;d&&yc(e,d,t)}),r}function fC(e){return(t,n)=>Le(t,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e},body:JSON.stringify({accept:n})},{source:"desktop-mode/network"})}async function pC(e,t){const n=e.email?`${e.name} (${e.email})`:e.name,o=await t.confirm({title:b("Arrive logged in next time?"),message:b("%1$s just switched here from %2$s while you were logged in. Link that account to yours, and a switch from there logs you in as you. You can undo this in the Network window.").replace("%1$s",n).replace("%2$s",e.site),confirmLabel:b("Link accounts")});try{await t.post(e.url,o)}catch{}return o}const Wi=new Map;function Bh(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}Wi.set(e.id,e)}function hC(){return Array.from(Wi.keys())}async function vc(e){if(!e||e.length===0)return;const t=e.filter(n=>!Wi.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${hC().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=Wi.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():fe(o.url)}))}function Fh(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:mC(),visible:!document.hidden,settings:sA(e)}}function mC(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class Hh{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,C(y.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){C(y.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(t){const n=t.resolveValue?t.resolveValue(Fh(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=Fh(t.id,this.pluginUrl);C(y.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?vc(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},C(y.WALLPAPER_MOUNTED,{id:t.id,container:this.element,ctx:o}),this.isEffectivelyHidden()&&this.emitEffectiveVisibility()};s.then(()=>{if(n!==this.generation)return;let r;try{r=t.mount(this.element,o)}catch(a){this.handleMountFailure(t.id,a);return}if(gC(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&&C(y.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){C(y.WALLPAPER_SUSPEND,{id:this.active?.id??null,suspended:this.isSuspended(),reasons:Array.from(this.suspendReasons.keys())})}installFreezeOverlay(){if(this.freezeOverlay||!this.active)return;const t=this.element.querySelector("canvas");if(!(!t||t.width===0||t.height===0))try{const n=document.createElement("canvas");n.width=t.width,n.height=t.height;const o=n.getContext("2d");if(!o)return;o.drawImage(t,0,0),n.className="os-wallpaper-freeze",n.style.position="absolute",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.setAttribute("aria-hidden","true"),this.element.appendChild(n),t.style.visibility="hidden",this.freezeOverlay=n,this.frozenCanvas=t}catch{}}removeFreezeOverlay(){this.freezeOverlay?.remove(),this.freezeOverlay=null,this.frozenCanvas&&(this.frozenCanvas.style.visibility="",this.frozenCanvas=null)}handleMountFailure(t,n){this.element.innerHTML="",C(y.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),C(y.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function gC(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const Gh=ie("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),Un=Gh.state.seed,bc=Gh.state.listeners;function Ec(e){Ne("Game",jt(e,Kh),e);const t=Un.findIndex(n=>n.id===e.id);t>=0?Un[t]=e:Un.push(e),jh()}function zh(e){const t=Un.findIndex(n=>n.id===e);t>=0&&(Un.splice(t,1),jh())}function wC(e){return bc.add(e),()=>{bc.delete(e)}}function jh(){const e=Array.from(bc);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function Vh(){const e=Un.slice(),t=X(y.GAMES,e);return Array.isArray(t)?t.filter(yC):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function Pi(e){return Vh().find(t=>t.id===e)}const Kh=[{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 yC(e){return jt(e,Kh).length===0}const qh=new Set;function $i(e){if(qh.has(e))return;const n=window.openStationConfig?.deferredStyles?.[e];if(!n?.url)return;qh.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 vC="desktop-mode/games";function bC(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function Ho(e,t={},n={}){const{restUrl:o,restNonce:s}=bC(),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 Le(rt(o,e),{...t,headers:i,credentials:"same-origin"},{source:vC,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 EC(e,t,n={}){return Ho(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function _C(){return Ho("desktop-mode/v1/games/playtime")}function SC(e,t,n={}){return Ho(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function kC(e){return Ho(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function IC(e,t,n={}){return Ho(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const AC=6e4;function CC(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,SC(e,l,{windowId:t.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,AC);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const Bn=ie("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function LC(){return Bn.state}function _c(e){const t=Bn.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&&NC()}function TC(e){return Bn.state.listeners.add(e),()=>{Bn.state.listeners.delete(e)}}function NC(){for(const e of Array.from(Bn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function OC(){return Array.from(Bn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function Yh(){return window.wp?.os??{}}const DC=760,RC=560,xC=480,MC=380;function WC(){const e=window.openStationConfig?.gameStyleHandles??[];for(const t of e)$i(t)}async function PC(e){if(typeof e.render=="function")return e;const t=Yh().loadVendorScript;if(!e.scriptUrl||typeof t!="function")throw new Error(`[openstation] Game "${e.id}" has no render callback and no loadable script.`);await t(e.scriptUrl,{translations:e.scriptTranslations,deps:e.scriptDeps,l10n:e.scriptL10n,before:e.scriptBefore,after:e.scriptAfter});const o=window.openStationGames?.[e.id];if(!o||typeof o.render!="function")throw new Error(`[openstation] No game def on window.openStationGames["${e.id}"]. Script loaded but didn't publish a def — check the plugin's global assignment.`);const s={...e,render:o.render,window:o.window??e.window};return Ec(s),s}async function Xh(e,t={}){const n=Yh(),o=Pi(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);if(WC(),typeof n.registerWindow!="function")throw new Error("[openstation] wp.os.registerWindow is missing — the shell must boot before launching games.");const s=`os-game-${e}`,i=`game:${s}`,r=n.windowManager,a=r?.getByBaseId?.(s)??r?.getById(s);if(a){const g=a.config?.desktopId;g&&r?.switchDesktop&&g!==r?.getActiveDesktopId?.()&&r.switchDesktop(g),n.registerWindow({id:s,title:o.title,icon:o.icon,render:()=>{}});return}n.wallpaper?.suspend(i);let l=!1;const c=()=>{l||(l=!0,n.wallpaper?.resume(i))};let d=null;const u=()=>{d?.stop(),d=null};n.onWindow?.(s,{closed:()=>{u(),c()},minimized:()=>d?.pause(),restored:()=>d?.resume()});const f=(g,h)=>{n.activity?.publish("os/game-score-recorded",{game:e,score:g.score,meta:g.meta??{},windowId:s,challengeId:h})},p=g=>{if(t.challenge){const h=t.challenge.id;return IC(h,g,{windowId:s}).then(({challenge:m})=>{_c([m]),f(g,h)})}return EC(e,g,{windowId:s}).then(()=>f(g))};try{await n.registerWindow({id:s,title:o.title,icon:o.icon,width:o.window?.width??DC,height:o.window?.height??RC,minWidth:o.window?.minWidth??xC,minHeight:o.window?.minHeight??MC,render:async g=>{const h=await PC(o),m=h.render;if(typeof m!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);const E={windowId:s,container:g,config:h.config??{},challenge:t.challenge,submitScore:p,close:()=>{n.windowManager?.getById(s)?.close()}};d=CC(e,{windowId:s});const S=m(E);return()=>{try{S?.()}finally{u(),c()}}}})}catch(g){throw u(),c(),g}}const Zh={register:Ec,unregister:zh,list:Vh,get:Pi,subscribe:wC,launch:Xh,getPlaytime:()=>_C().then(e=>e.playtime)},Fn=ie("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function $C(e){Fn.state.pending.set(e.id,e)}function Ui(e){Fn.state.pending.delete(e)}function UC(e){return(window.openStationWallpapers||{})[e]??null}function Jh(e){const t=Fn.state.inflight.get(e);if(t)return t;const n=Fn.state.pending.get(e);if(!n)return Promise.resolve(null);const o=(async()=>{try{await fe(n.scriptUrl,{translations:n.scriptTranslations,deps:n.scriptDeps,l10n:n.scriptL10n,before:n.scriptBefore,after:n.scriptAfter})}catch(i){return C(y.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=UC(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return C(y.SHELL_ERROR,{scope:"wallpaper-missing-def",id:n.id,error:new Error(`[openstation] No wallpaper def on window.openStationWallpapers["${n.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)}),null;try{Mn(s)}catch(i){return C(y.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return Ui(n.id),s})().finally(()=>{Fn.state.inflight.delete(e)});return Fn.state.inflight.set(e,o),o}function BC(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 Jh(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await vc(o.needs),o.mount(t,n))}}}function FC(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){Mn(a),n.add(r.id),t.apply();return}if(!r.scriptUrl)return;$C(r);const l=r.preview!==""||r.value!=="";if(l){try{Mn(BC(r))}catch(c){C(y.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:c}),Ui(r.id);return}n.add(r.id)}if(!l||t.state.wallpaper===r.id){const c=await Jh(r.id);if(!l){if(!c){Ui(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(Pp(r),Ui(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 HC(e){return{id:e.id,title:e.title,icon:e.icon,description:e.description||void 0,scoreColumns:Array.isArray(e.scoreColumns)?e.scoreColumns:[],config:e.config??{},window:e.window&&Object.keys(e.window).length>0?e.window:void 0,scriptUrl:e.scriptUrl,scriptTranslations:e.scriptTranslations,scriptL10n:e.scriptL10n,scriptBefore:e.scriptBefore,scriptAfter:e.scriptAfter,scriptDeps:e.scriptDeps}}function GC(){const e=new Set,t=o=>{try{const s=Pi(o.id),i=HC(o);Ec(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)&&(zh(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 wt=ie("desktop-mode/heartbeat-bus",()=>({suppliers:new Map,subscribers:new Map,booted:!1})),De={contribute(e,t){return wt.state.suppliers.set(e,t),()=>{wt.state.suppliers.get(e)===t&&wt.state.suppliers.delete(e)}},subscribe(e,t){let n=wt.state.subscribers.get(e);return n||(n=new Set,wt.state.subscribers.set(e,n)),n.add(t),()=>{n.delete(t)}}};function zC(){if(wt.state.booted)return;wt.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 wt.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 wt.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 Bi=null,Fi={installHintDismissed:!1,notificationsEnabled:!1};const Sc=new Set;function Qh(e){if(!e){Bi=null;return}Bi=e,Fi={...e.state},tm()}function Go(){return{...Fi}}function kc(e){if(Fi={...Fi,...e},tm(),!Bi)return Go();const t=JSON.stringify(e),n=jC();return fetch(Bi.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)}),Go()}function em(e){return Sc.add(e),()=>{Sc.delete(e)}}function tm(){const e=Go();for(const t of Array.from(Sc))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function jC(){return window.openStationConfig?.restNonce??""}const VC=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:Go,initPwaState:Qh,subscribePwaState:em,updatePwaState:kc},Symbol.toStringTag,{value:"Module"}));function Ic(e){const t=Se.filter("os/notification-requested",{...e});if(!t||t.cancel===!0||!t.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=de({message:t.body?t.title+" — "+t.body:t.title}),Se.publish("os/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=nm(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){kc({notificationsEnabled:!0}),o=nm(t),o||r();return}r()}}),i)}function nm(e){let t=null;try{t=new Notification(e.title,{body:e.body,icon:e.icon,tag:e.tag,requireInteraction:e.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[openstation] Notification ctor threw:",n),null}if(e.onClick){const n=e.onClick;t.onclick=()=>{try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] notification onClick threw:",o)}}}return Se.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function KC(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&kc({notificationsEnabled:!0}),e}function qC(){return typeof Notification>"u"?"unsupported":Notification.permission}function YC(e){return Pi(e)?.title||e}const om=new Set,sm=new Set;async function XC(e){const{challenge:t}=await kC(e.id);_c([t]),await Xh(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function ZC(e){const t=ae(b("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,YC(e.game),String(e.scoreToBeat));Ic({title:b("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),de({message:t,persistent:!0,dismissible:!0,action:{label:b("Accept & Play"),onClick:()=>{XC(e).catch(n=>{de({message:n instanceof Error?n.message:b("Could not accept the challenge.")})})}}})}function JC(e){let t;e.result==="beaten"?t=b("%1$s beat your score: %2$s vs your %3$s."):t=b("%1$s did not beat your score: %2$s vs your %3$s.");const n=ae(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));Ic({title:b("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),de({message:n})}function QC(e){const{currentUserId:t}=e;if(!t)return;De.contribute("openstation_games_subscribe",()=>({challengesVersion:LC().version})),De.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&_c(o.challenges)});const n=()=>{for(const o of OC())o.state==="pending"&&o.recipientId===t&&!om.has(o.id)&&(om.add(o.id),ZC(o)),o.state==="completed"&&o.challengerId===t&&!sm.has(o.id)&&(sm.add(o.id),JC(o))};TC(n),n()}const im=/^[a-z0-9_/-]+$/,rm=ie("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),tn=rm.state.registry,eL=rm.state.listeners;function Hn(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)"):im.test(n)||t.push(`slug (must match ${im} — 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)")),Ne("Command",t,e),tn.set(n,{...e,slug:n}),Ac()}function am(e){tn.delete(e.toLowerCase())&&Ac()}function Hi(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(tn.entries()))o.owner===e&&(tn.delete(n),t++);return t>0&&Ac(),t}function cm(){return Array.from(tn.values())}function tL(){const e=[];for(const t of tn.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function nL(e){return tn.get(e.toLowerCase())??null}function Ac(){const e=Array.from(eL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function oL(){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,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(y.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.slug)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.slug)}return a},i=r=>{const a=new Set;for(const c of cm())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))am(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const lm=ie("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),zo=lm.state.registry,sL=lm.state.listeners;function dm(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}zo.set(t,{...e,id:t}),Cc()}function um(e){zo.delete(e.toLowerCase())&&Cc()}function iL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(zo.entries()))o.owner===e&&(zo.delete(n),t++);return t>0&&Cc(),t}function fm(){return Array.from(zo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Cc(){const e=Array.from(sL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function rL(){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,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(y.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{iL(r);const a=n.get(r);if(a){const l=new Set(fm().map(c=>c.id));for(const c of a)l.has(c)&&um(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 pm=ie("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),jo=pm.state.registry,aL=pm.state.listeners,hm=/^[a-z0-9_/-]+$/;function Vo(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):hm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${hm} — 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)")),Ne("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();jo.set(n,{...e,id:n}),Gi()}function mm(e){jo.delete(e.toLowerCase())&&Gi()}function cL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(jo.entries()))o.owner===e&&(jo.delete(n),t++);return t>0&&Gi(),t}function lL(){return Array.from(jo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Gi(){const e=Array.from(aL);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"&&Gi()});function dL(){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,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){C(y.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(cL(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const gm=ie("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),Ko=gm.state.registry,uL=gm.state.listeners,wm=/^[a-z0-9_/-]+$/;function Lc(){for(const e of Array.from(uL))try{e()}catch{}}function ym(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())||t.push(`id (must match ${wm} — 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)")),Ne("WindowAction",t,e);const n=e.id.trim().toLowerCase();Ko.set(n,{...e,id:n}),Lc()}function fL(e){Ko.delete(String(e||"").toLowerCase())&&Lc()}function pL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Ko.entries()))o.owner===e&&(Ko.delete(n),t++);return t>0&&Lc(),t}function hL(){return Array.from(Ko.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function mL(){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,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){C(y.SHELL_ERROR,{scope:"window-action-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(pL(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function vm(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function gL({items:e,onPick:t}){const n=document.createElement("os-menu");n.classList.add("os-window__menu-panel"),n.classList.add("os-window__related-panel");const o=new Map;for(const r of e){const a=o.get(r.group);a?a.push(r):o.set(r.group,[r])}const s=Array.from(o.entries()).sort((r,a)=>vm(r[0])-vm(a[0])),i=[];for(const[,r]of s){const a=r.find(l=>typeof l.groupLabel=="string"&&l.groupLabel!=="")?.groupLabel;if(a){const l=document.createElement("div");l.className="os-window__related-group",l.setAttribute("role","presentation"),l.textContent=a,n.appendChild(l)}for(const l of r){const c=document.createElement("os-menu-item");c.setAttribute("role","menuitem"),c.setAttribute("value",l.id),c.tabIndex=-1,l.icon&&c.setAttribute("icon",l.icon),c.classList.add("os-window__related-item"),c.textContent=typeof l.count=="number"?`${l.label} (${l.count})`:l.label,c.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),t(l)}),i.push(c),n.appendChild(c)}}return n.addEventListener("keydown",r=>{const a=r,l=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const c=a.key==="ArrowDown";let d=i[c?0:i.length-1];l!==-1&&(d=i[(l+(c?1:-1)+i.length)%i.length]),d?.focus()}else if(a.key==="Home"||a.key==="End")a.preventDefault(),a.stopPropagation(),i[a.key==="Home"?0:i.length-1]?.focus();else if(a.key==="Enter"||a.key===" "){const c=i[l];c&&(a.preventDefault(),a.stopPropagation(),c.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function bm(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 Em(e){const t=Je(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=X(y.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(bm):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(bm))}function Tc(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function wL(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function yL(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=Em(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=gL({items:s,onPick:c=>{r(),wL(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 vL({manager:e,openUrl:t}){Vo({id:"desktop-mode/related-entities",label:b("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>Em(n.id).length>0,render:(n,o)=>{Tc(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")){Tc(o.element);return}yL(n,o,t)})}}),ee(y.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(Tc(o.element),o.renderCustomTitleBarButtons?.())})}const Nc="os-broadcast",_m="os-broadcast",Sm=window.location.origin;let Oc=null;function bL(e){Oc=e}function zi(e,t){const n=String(X("os.broadcast.topic",e,{payload:t})??e),o=X("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Nc,{detail:s})),C(y.BROADCAST,s),Se.publish(n,o),!Oc)return;const i={type:_m,topic:n,payload:o};for(const r of Oc._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Sm)}catch{}}}function Gn(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){C(y.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Nc,n),()=>document.removeEventListener(Nc,n)}function EL(){window.addEventListener("message",e=>{if(e.origin!==Sm)return;const t=e.data;!t||t.type!==_m||t._fromParent||typeof t.topic=="string"&&zi(t.topic,t.payload)})}function km(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||zi(`os.${i}.changed`,{source:o,action:t,ids:s})}const _L=new Set(["saved","no-editor","not-dirty","error"]);let Im=0;function Am(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function SL(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Im+=1;const o=`os-editor-preview-${Date.now()}-${Im}`;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"&&_L.has(d.status)?d.status:"error",f=Am(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 Me=ie("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),kL=400,Cm=1500;function qo(e){return e?`${e.type}:${e.id}`:""}function IL(e){for(const t of Me.state.pairings.values())if(t.previewWindowId===e)return t}function AL(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function CL(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 ji(e,t,n,o){Me.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(Tm(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})),C(y.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function Dc(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?.()},kL)}function LL(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=Gn(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||Dc(e,t)})}let Lm=0;function Tm(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 Nm(e,t,n){Tm(e,t);const o=X(y.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:Cm},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;Lm+=1;const i=`${t.previewWindowId}-watch-${Lm}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:Cm},window.location.origin),t.watchId=i}catch{}}let TL=SL;async function NL(e,t){const n=Me.state.pairings.get(t.id);if(n){ji(e,n,"toggled","close");return}if(Me.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=Je(t.id);if(!o?.previewUrl){de({message:b("No preview is available for this content.")});return}Me.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=AL();s||t.applySnap?.("left");const i=TL(t);i.then(f=>{f.status==="error"&&de({message:b("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{Me.state.busyEditors.delete(t.id),e.getById(t.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=b("Preview");o.label&&(a=ae(b("Preview: %s"),o.label));let l={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=X(y.EDITOR_PREVIEW_WINDOW_CONFIG,l,{editorWindowId:t.id,content:o});if(c&&typeof c=="object"&&typeof c.id=="string"&&c.id!==""&&typeof c.url=="string"&&c.url!==""?l=c:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await e.open(l),!e.getById(t.id)||qo(Je(t.id))!==qo(o)){e.getById(l.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:l.id,postKey:qo(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};LL(e,d,o),Nm(e,d,o),Me.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})),C(y.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Me.state.pairings.get(t.id)===d&&f.status==="saved"&&Dc(e,d,f.previewUrl)})}function OL({manager:e}){Vo({id:"desktop-mode/editor-preview",label:b("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!Je(t.id)?.previewUrl||CL(t)),render:(t,n)=>{if(!Je(n.id)?.previewUrl){const i=b("Save the post to enable its preview");t.setAttribute("aria-disabled","true"),t.setAttribute("aria-label",i),t.setAttribute("title",i),t.classList.add("os-window__btn--disabled"),t.addEventListener("click",r=>{r.stopPropagation(),de({message:b("The preview opens once the post has been saved.")})});return}const o=Me.state.pairings.has(n.id),s=Me.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(),NL(e,n)})}}),ee(y.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Me.state.pairings.get(t.windowId);n&&qo(t.content)!==n.postKey&&ji(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),ee(y.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Me.state.pairings.get(t.windowId);if(n){ji(e,n,"editor-closed","destroy");return}const o=IL(t.windowId);o&&ji(e,o,"preview-closed","none")}),ee(y.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Me.state.pairings.get(t.windowId);if(n){const o=Je(t.windowId);o&&qo(o)===n.postKey&&Nm(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 Me.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){Dc(e,o,Am(n.previewUrl));return}}})}const Om=16,ze=16,DL=1100,RL=860;function xL(e,t){const n=Math.max(0,t.width-ze*2),o=Math.max(320,Math.min(DL,Math.round(n*.5))),s=Math.max(200,Math.min(RL,Math.round(t.height*.8))),i=ML(e.y,ze,Math.max(ze,t.height-s-ze)),r=e.x+e.width+Om;if(r+o+ze<=t.width)return{x:r,y:i,width:o,height:s};const a=e.x-Om-o;if(a>=ze)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(ze,t.width-o-ze):ze,y:u?Math.max(ze,t.height-s-ze):ze,width:o,height:s}}function ML(e,t,n){return Math.min(Math.max(e,t),n)}function WL(e){return`revisions-${String(e.type).replace(/\//g,"-")}-${e.id}`}function PL(e){const t=e?.revisionCount;return typeof t=="number"&&t>0?ae(b("View revisions (%d)"),t):b("View revisions")}function $L(e,t,n){if(vi(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?{}:xL({x:o.offsetLeft,y:o.offsetTop,width:o.offsetWidth,height:o.offsetHeight},{width:s.clientWidth,height:s.clientHeight})}async function UL(e,t){const n=Je(t.id);if(!n?.revisionsUrl){de({message:b("No revisions are available for this content.")});return}const o=WL(n);let s=b("Revisions");n.label&&(s=ae(b("Revisions: %s"),n.label));let i={id:o,baseId:o,url:n.revisionsUrl,title:s,icon:"dashicons-backup",content:{type:"revisions",id:n.id,root:{type:n.type,id:n.id},label:s},...$L(e,t.id,o)};const r=X(y.REVISIONS_WINDOW_CONFIG,i,{editorWindowId:t.id,content:n});r&&typeof r=="object"&&typeof r.id=="string"&&r.id!==""&&typeof r.url=="string"&&r.url!==""?i=r:typeof console<"u"&&console.warn("[openstation] `os.revisions.window-config` filter returned an invalid config; using the default."),await e.open(i);const a={editorWindowId:t.id,revisionsWindowId:i.id,content:n};document.dispatchEvent(new CustomEvent("os-revisions-opened",{detail:a})),C(y.REVISIONS_OPENED,a)}function BL({manager:e}){ym({id:"desktop-mode/view-revisions",label:t=>PL(Je(t.id)),icon:"dashicons-backup",order:60,isVisible:t=>!!Je(t.id)?.revisionsUrl,onSelect:t=>{UL(e,t)}})}const Dm="none",Rm=ie("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),Yo=Rm.state.registry,Rc=Rm.state.listeners,xm=/^[a-z0-9_/-]+$/;function Vi(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):xm.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Dm&&t.push('id ("none" is reserved)'):t.push(`id (must match ${xm} — 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)")),Ne("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();Yo.set(n,{...e,id:n}),Mc()}function FL(e){Yo.delete(e.toLowerCase())&&Mc()}function HL(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Yo.entries()))o.owner===e&&(Yo.delete(n),t++);return t>0&&Mc(),t}function xc(){const e=Array.from(Yo.values()),t=X(y.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function Mm(e){return xc().find(t=>t.id===e)}function GL(e){return Rc.add(e),()=>{Rc.delete(e)}}function Mc(){const e=Array.from(Rc);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}Vi({id:"darken",label:b("Darken"),description:b("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),Vi({id:"frost",label:b("Frost"),description:b("Throw unfocused windows out of focus — a soft, frosted-glass blur, as if you were looking at them through an iced-over pane."),className:"os-window--fx-frost"}),Vi({id:"grayscale",label:b("Grayscale"),description:b("Drain the colour from unfocused windows so the focused one is the only thing still in colour — your eye snaps right to it."),className:"os-window--fx-grayscale"});function zL(){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,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){C(y.SHELL_ERROR,{scope:"unfocus-effect-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(HL(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const jL="none",Wm=ie("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),Xo=Wm.state.registry,VL=Wm.state.listeners,Pm=/^[a-z0-9_/-]+$/;function $m(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Pm.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===jL&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Pm} — 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)")),Ne("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();Xo.set(n,{...e,id:n}),Pc()}function KL(e){Xo.delete(e.toLowerCase())&&Pc()}function qL(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&&Pc(),t}function Wc(){const e=Array.from(Xo.values()),t=X(y.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function Pc(){const e=Array.from(VL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}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,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){C(y.SHELL_ERROR,{scope:"window-link-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(qL(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}let nn=null;function Um(){if(nn)return nn;if(window.openStationWindowLinkVisuals)return nn=Promise.resolve(!0),nn;const t=window.openStationConfig?.windowLinkVisualsBundleUrl;return t?(nn=fe(t).then(()=>!0).catch(n=>{throw nn=null,n}),nn):Promise.resolve(!1)}const $c="svg-splines";function XL(){if(Wc().some(t=>t.id===$c))return;const e=async t=>{if(!await Um())return;const o=Wc().find(s=>s.id===$c);if(!(!o||o.mount===e))return o.mount(t)};$m({id:$c,label:b("Splines"),description:b("Curved connectors between related windows, ending in circular dots — the larger dot sits on the window the content belongs to; windows that reference each other get large dots on both ends."),mount:e})}const Uc="data-desktop-unfocus-effect",Bc="data-desktop-unfocus-effect-class";let Bm=!1;function ZL(e){return e.querySelector("canvas")!==null}function JL(e){return e.state==="snapped-left"||e.state==="snapped-right"}function QL({manager:e,osSettings:t}){if(Bm)return;Bm=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(Bc);l&&(r.classList.remove(l),r.removeAttribute(Bc));const c=r.getAttribute(Uc);c&&Mm(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(Uc)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Bc,a.className)),r.setAttribute(Uc,a.id),a.apply?.(r)},i=()=>{const r=n===Dm?void 0:Mm(n),a=xc();for(const l of e.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(JL(l)||ZL(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()}),GL(()=>i()),i()}function eT(){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,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){C(y.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||($E(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function tT(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 Fm=ie("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),Zo=Fm.state.registry,nT=Fm.state.listeners,Hm=/^[a-z0-9_/-]+$/;function Gm(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)"):Hm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Hm} — 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)")}Ne("WindowTheme",t,e);const n=e.id.trim().toLowerCase();Zo.set(n,{...e,id:n}),Fc()}function zm(e){Zo.delete(e.toLowerCase())&&Fc()}function oT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Zo.entries()))o.owner===e&&(Zo.delete(n),t++);return t>0&&Fc(),t}function jm(){return Array.from(Zo.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function Fc(){const e=Array.from(nT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function sT(){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,deps:l.scriptDeps,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){C(y.SHELL_ERROR,{scope:"window-theme-script-load",handle:l.handle,url:l.scriptUrl,error:c});return}t.add(l.scriptUrl),e.add(l.handle)},i=l=>{const c=new Map;if(!l)return c;for(const d of l){if(!d.scriptHandle||!d.id)continue;let u=c.get(d.scriptHandle);u||(u=new Set,c.set(d.scriptHandle,u)),u.add(d.id)}return c},r=l=>{const c=new Set;for(const u of jm())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{Gm({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){C(y.SHELL_ERROR,{scope:"window-theme-shell-register",id:c.id,error:d})}}};return async(l,c)=>{const d=new Set;for(const u of l)u.handle&&d.add(u.handle);for(const u of Array.from(e)){if(d.has(u))continue;const f=r(u);for(const p of f)zm(p),o.delete(p);oT(u),e.delete(u)}a(c);for(const u of l)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const Vm=ie("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),Jo=Vm.state.registry,iT=Vm.state.listeners,Km=/^[a-z0-9_/-]+$/;function Qo(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(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)`),(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")')),Ne("WindowControl",t,e);const n=e.id.trim().toLowerCase();Jo.set(n,{...e,id:n}),Hc()}function qm(e){Jo.delete(e.toLowerCase())&&Hc()}function rT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Jo.entries()))o.owner===e&&(Jo.delete(n),t++);return t>0&&Hc(),t}function Ym(){return Array.from(Jo.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Hc(){const e=Array.from(iT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function aT(){Qo({id:"core/minimize",label:b("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),Qo({id:"core/maximize",label:b("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),Qo({id:"core/focus-tab",label:b("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),Qo({id:"core/close",label:b("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function cT(){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,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(y.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of Ym())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))qm(d);rT(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Xm=ie("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),es=Xm.state.registry,lT=Xm.state.listeners,Zm=/^[a-z0-9_/-]+$/,Jm=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Qm(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Zm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Zm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):Jm.has(e.slot)||t.push(`slot (must be one of ${Array.from(Jm).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Ne("WindowSlot",t,e);const n=e.id.trim().toLowerCase();es.set(n,{...e,id:n}),zc()}function Gc(e){es.delete(e.toLowerCase())&&zc()}function dT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(es.entries()))o.owner===e&&(es.delete(n),t++);return t>0&&zc(),t}function eg(){return Array.from(es.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function zc(){const e=Array.from(lT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function uT(){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,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(y.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of eg())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))Gc(d);dT(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const fT="desktop-mode-notice-dismissed";function pT(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function tg(){return`${fT}:${pT()}`}function jc(){try{const e=window.localStorage.getItem(tg());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function ng(e){try{window.localStorage.setItem(tg(),JSON.stringify(e))}catch{}}function Ki(e){return e?jc()[e]===!0:!1}function qi(e){if(!e)return;const t=jc();t[e]=!0,ng(t)}function og(e){if(!e)return;const t=jc();t[e]&&(delete t[e],ng(t))}const hT=Ce`: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 ) )}`,Gs=class Gs extends en{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&Ki(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&qi(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&og(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return $n`
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=${b("Dismiss notice")}
29 @click=${o=>this._onDismiss(o)}
30 >
31 ${nu("close",{size:null})}
32 </button>
33 `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};Gs.props=["tone","notDismissible","icon","noticeId"],Gs.styles=[hT],Gs.help=void 0;let Vc=Gs;Fo("os-notice",Vc);const ts=ie("desktop-mode/window-notices",()=>({entries:new Map})),mT=/^[a-z0-9_/-]+$/;function sg(e){return`os-notice/${e.toLowerCase()}`}function gT(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 ig(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!mT.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};ts.state.entries.set(t,n);const o=sg(t);return Qm({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=ts.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=ts.state.entries.get(t);i&&s.appendChild(gT(i))}}),()=>Kc(t)}function Kc(e){const t=String(e??"").trim().toLowerCase();t&&ts.state.entries.delete(t)&&Gc(sg(t))}function rg(){return Array.from(ts.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 wT(e){const t=String(e??"").trim().toLowerCase();t&&qi(t)}function yT(e){const t=String(e??"").trim().toLowerCase();t&&og(t)}function vT(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 ag(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),ig({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:vT(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of rg())n.owner==="__server__"&&(t.has(n.id)||Kc(n.id))}const cg=ie("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),ns=cg.state.registry,bT=cg.state.listeners,lg=/^[a-z0-9_/-]+$/;function ET(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):lg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${lg} — 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)")),Ne("WindowChrome",t,e);const n=e.id.trim().toLowerCase();ns.set(n,{...e,id:n}),qc()}function dg(e){ns.delete(e.toLowerCase())&&qc()}function _T(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ns.entries()))o.owner===e&&(ns.delete(n),t++);return t>0&&qc(),t}function ug(){return Array.from(ns.values()).sort((e,t)=>e.id.localeCompare(t.id))}function qc(){const e=Array.from(bT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function ST(){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,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){C(y.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of ug())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))dg(d);_T(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Yc=window.location.origin,Te=ie("desktop-mode/connection",()=>({connSeq:0,connections:new Map,connectionsByTarget:new Map,syntheticIframes:new Map}));function kT(e,t){const{syntheticIframes:n}=Te.state;return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function IT(){return`os-conn-${++Te.state.connSeq}`}function AT(e){const t=(l,c)=>{try{l.contentWindow?.postMessage(c,Yc)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=IT(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let g=!1,h=!1;const m=()=>{const P=Te.state.syntheticIframes.get(l);return P||(e.getById(l)?.iframe??null)},E=()=>{if(m())return!1;const P=e.getById(l);return!!P&&P.config?.native===!0},S=[],R=()=>{const P=m();if(P)for(;p.length;){const B=p.shift();t(P,{type:"os-bridge-publish",connectionId:d,topic:B.topic,payload:B.payload})}},$={id:d,target:l,isOpen:()=>g,subscribe(P,B){const F=B;if(E()){const Z=x_(l,P,(Y,L)=>{C(y.CONNECTION_MESSAGE,{connectionId:d,topic:L.channel,direction:"in"});try{F(Y,{topic:L.channel})}catch(x){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",x)}});return S.push(Z),Z}let K=f.get(P);return K||(K=new Set,f.set(P,K)),K.add(F),()=>{K?.delete(F)}},send(P,B){if(h)return;if(C(y.CONNECTION_MESSAGE,{connectionId:d,topic:P,direction:"out"}),E()){W_(l,P,B);return}if(!g){p.push({topic:P,payload:B});return}const F=m();F&&t(F,{type:"os-bridge-publish",connectionId:d,topic:P,payload:B})},disconnect(){$._destroy("disconnect")},_targetWindow:m,_handleIframeMessage(P){if(!P||typeof P!="object")return;const B=P;if(B.type==="os-bridge-handshake-ack"){if(g)return;g=!0,C(y.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:$});try{c.onOpen?.()}catch(F){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",F)}R();return}if(B.type==="os-bridge-publish"){const F=P,K=typeof F.topic=="string"?F.topic:"";if(!K)return;C(y.CONNECTION_MESSAGE,{connectionId:d,topic:K,direction:"in"});const Z=f.get(K);if(Z)for(const L of Array.from(Z))try{L(F.payload,{topic:K})}catch(x){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",x)}const Y=f.get("*");if(Y)for(const L of Array.from(Y))try{L(F.payload,{topic:K})}catch(x){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",x)}return}B.type==="os-bridge-disconnect"&&$._destroy("disconnect")},_destroy(P){if(h)return;h=!0;const B=g;g=!1,Te.state.connections.delete(d);const F=Te.state.connectionsByTarget.get(l);F&&(F.delete(d),F.size===0&&Te.state.connectionsByTarget.delete(l));for(const K of S.splice(0))try{K()}catch{}if(B){const K=m();K&&t(K,{type:"os-bridge-disconnect",connectionId:d})}C(y.CONNECTION_CLOSED,{connectionId:d,reason:P});try{c.onClose?.(P)}catch(K){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",K)}}};Te.state.connections.set(d,$);let _=Te.state.connectionsByTarget.get(l);if(_||(_=new Set,Te.state.connectionsByTarget.set(l,_)),_.add(d),E())return Promise.resolve().then(()=>{if(!(h||g)){g=!0,C(y.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(P){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",P)}}}),$;const M=m();return M&&t(M,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),$},o=(l,c)=>{if(!l||typeof l!="object")return;const d=l;if(typeof d.type!="string"||!d.type.startsWith("os-bridge-"))return;if(d.type==="os-bridge-connection-request"&&typeof d.requestId=="string"&&typeof c=="string"&&c!==""){s(c,d.requestId,Array.isArray(d.topics)?d.topics:[]);return}if(typeof d.connectionId!="string")return;Te.state.connections.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=Te.state.syntheticIframes.get(l)??e.getById(l)?.iframe??null;if(!f)return;const p=X(y.IFRAME_CONNECTION_REQUEST,!0,{windowId:l,requestId:c,topics:d.slice()});if(p===!1){try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!1,reason:"rejected"},Yc)}catch{}return}const g=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,h=n(l,{topics:g});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:h.id},Yc)}catch{}};return{connect:n,getConnection:l=>Te.state.connections.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=Te.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c)){const u=Te.state.connections.get(d);if(!u||u.isOpen())continue;const f=u._targetWindow();f&&t(f,{type:"os-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:l=>{const c=Te.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c))Te.state.connections.get(d)?._destroy("window-closed")}}}const CT={};function LT(...e){(typeof{url:jr&&jr.tagName.toUpperCase()==="SCRIPT"&&jr.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&CT?"production":void 0)!=="production"&&console.log(...e)}const TT="iframe:";function Xc(e){return TT+e}function fg(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function NT(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const OT=250;class DT{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"&&(Hi(Xc(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&&Hi(Xc(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()},OT)}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){LT("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=Xc(t);Hi(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=NT(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?qd(s.iconSvg):"",a={slug:i,label:s.label,icon:fg(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,fg(s)):this.runProxy(t,s.name)};try{Hn(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=ue(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 RT(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 pg="global",xT=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,MT=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,WT=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,PT=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,$T=/getSiteEditorPage\s*\(|site-editor\.php/,UT=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function BT(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 FT{constructor(t){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=t.manager,this.adminUrl=t.adminUrl}install(){this.tryMount(0)}tryMount(t){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){t<40&&window.setTimeout(()=>this.tryMount(t+1),150);return}this.mount()}mount(){const t=window.wp,n=t.element,o=t.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,l=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof l!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const c=document.createElement("div");c.setAttribute("aria-hidden","true"),c.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(c),this.host=c;const d={perLoader:{},statics:[],loadersList:[]},u=h=>{if(!Array.isArray(h)||h.length===0)return"";const m=new Array(h.length);for(let E=0;E<h.length;E++){const S=h[E];m[E]=S&&S.name?S.name:""}return m.join("|")},f=()=>{let h=[];for(const m of d.loadersList){const E=d.perLoader[m];Array.isArray(E)&&(h=h.concat(E))}Array.isArray(d.statics)&&(h=h.concat(d.statics)),this.callbackCache=Object.create(null);for(const m of h)m&&m.name&&typeof m.callback=="function"&&(this.callbackCache[m.name]=m.callback);this.publish(h)},p=h=>{const m=h.loader;let E=null;try{E=m.hook({search:""})}catch{}const S=E&&Array.isArray(E.commands)?E.commands:[],R=a(()=>u(S),[S]);return i(()=>{d.perLoader[m.name]=S,f()},[R]),i(()=>()=>{delete d.perLoader[m.name],f()},[]),null},g=()=>{const h=l(_=>{const M=_("core/commands");return!M||typeof M.getCommandLoaders!="function"?[]:[...M.getCommandLoaders(!1)||[],...M.getCommandLoaders(!0)||[]]},[]),m=l(_=>{const M=_("core/commands");return!M||typeof M.getCommands!="function"?[]:[...M.getCommands(!1)||[],...M.getCommands(!0)||[]]},[]),E=a(()=>Array.isArray(h)?h.map(_=>_&&_.name||""):[],[h]),S=E.join("|");i(()=>{d.loadersList=E,f()},[S]);const R=a(()=>u(Array.isArray(m)?m:[]),[m]);if(i(()=>{d.statics=Array.isArray(m)?m:[],f()},[R]),!Array.isArray(h)||h.length===0)return null;const $=[];for(const _ of h)!_||typeof _.hook!="function"||$.push(s(p,{key:_.name,loader:_}));return s(n.Fragment||"div",null,$)};try{this.root=n.createRoot(c),this.root.render(s(g))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(t){const n=Object.create(null),o=[];for(const i of t)!i||!i.name||!i.label||i.disabled||n[i.name]||(n[i.name]=!0,o.push(this.classify(i)));let s="";for(const i of o)s+=`${i.name}|${i.kind}|${i.url||""}
34 `;if(s!==this.lastFingerprint){this.lastFingerprint=s,Hi(pg);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!==""?qd(i.iconSvg):void 0,owner:pg,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name)};try{Hn(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=BT(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(xT)||i.match(MT)||i.match(WT);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(PT.test(i)){const l=$T.test(i)?n.name.match(UT):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=ue(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(ae(b("No live callback for command “%s” — the palette and the command registry are out of step. Reload the page."),t));s({close:()=>o.close()})}}}const hg="os-command-palette-ready";let os=null;function HT(){const t=window.openStationConfig?.commandPalette;return!t||!Array.isArray(t.scripts)?null:t}function GT(){const e=window.wp;try{return!!e?.data?.select?.("core/commands")}catch{return!1}}function zT(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 jT(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 VT(){const e=HT();if(!e||e.scripts.length===0)return GT();for(const s of e.styles??[])zT(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||!ic(s));for(const s of o)s.url&&jT(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!==""&&rh(i);return document.dispatchEvent(new CustomEvent(hg)),!0}function KT(){return os||(os=VT().catch(e=>{throw os=null,e}),os)}const zn=[];function Zc(e){Ne("Widget",jt(e,mg),e);const t=zn.findIndex(n=>n.id===e.id);t>=0?zn[t]=e:zn.push(e)}function qT(e){const t=zn.findIndex(n=>n.id===e);t>=0&&zn.splice(t,1)}function Jc(){const e=zn.slice(),t=X(y.WIDGETS,e);return Array.isArray(t)?t.filter(YT):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function jn(e){return Jc().find(t=>t.id===e)}const mg=[{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 YT(e){return jt(e,mg).length===0}let Qe=null;function XT(e){if(Qe)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",b("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=b("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),gg(o,e),document.body.appendChild(t),ZT(t,e.anchor);const s=a=>{const l=a.target;l&&(t.contains(l)||e.anchor.contains(l)||Qc())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&Qc()};document.addEventListener("keydown",i),Qe={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function ss(){if(!Qe)return;const e=Qe.panel.querySelector(".os-widget-picker__list");e&&gg(e,Qe.options)}function Qc(){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 gg(e,t){e.innerHTML="";const n=new Set(t.enabledIds()),o=t.registry();if(o.length===0){const s=document.createElement("div");s.className="os-widget-picker__empty",s.textContent=b("No widgets available. Activate a plugin that registers one, or see the docs for the registerWidget API."),e.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="os-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("os-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=ae(b("%s (already added)"),s.label):a=ae(b("Add %s"),s.label),i.setAttribute("aria-label",a);const l=document.createElement("span");l.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-widget-picker__entry-text";const d=document.createElement("span");if(d.className="os-widget-picker__entry-label",d.textContent=s.label,c.appendChild(d),s.description){const u=document.createElement("span");u.className="os-widget-picker__entry-description",u.textContent=s.description,c.appendChild(u)}if(i.appendChild(c),r){const u=document.createElement("span");u.className="os-widget-picker__entry-status",u.textContent=b("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function ZT(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 Yi="os-widgets__card--floating",JT="os-widgets__card--movable",QT="os-widgets__card--resizable",wg="os-widgets__card--dragging",yg="os-widgets__card--resizing",eN=160,vg=80,tN=280,nN=180,Vn=20,on=20,bg=5,oN=bg*bg,sN='input, textarea, select, button, a, [contenteditable="true"]';function iN(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(JT),i&&o.classList.add(QT),s?o.appendChild(rN(e,n.onRemove,n.onRedock)):o.appendChild(cN(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(Xi(o,Sg(t.geometry,t.floatingParent)),o.classList.add(Yi)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${pN(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(Yi),l=[];if(i)for(const d of uN()){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(dN(o,u,d,e,t,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=lN(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 rN(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(aN(e,n));const r=Eg(e,t);return o.appendChild(r),o}function aN(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",ae(b("Dock %s back to widget column"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2 6h6M5.5 3.5L8 6l-2.5 2.5M10 2.5v7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n.dataset.noDrag="true",n}function cN(e,t){const n=Eg(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function Eg(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",ae(b("Remove %s"),e.label)),n.innerHTML=zt("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function lN(e,t,n,o,s){let i=null,r=0,a=0,l=0,c=0,d=!1;const u=h=>{if(h.button!==0)return;const m=h.target;m&&m.closest(sN)||(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(Yi)){const h=o.floatingParent.getBoundingClientRect(),m=e.getBoundingClientRect(),E={x:m.left-h.left,y:m.top-h.top,width:m.width||n.defaultWidth||tN,height:m.height||n.defaultHeight||nN};Xi(e,E),e.classList.add(Yi),s.onLiberate(E),l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(wg)},p=h=>{if(i===null||h.pointerId!==i)return;const m=h.clientX-r,E=h.clientY-a;if(!d){if(m*m+E*E<oN)return;d=!0,f()}const S=Ig(Kn(l+m),Kn(c+E),e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${kg(S.x)}px`,e.style.top=`${kg(S.y)}px`},g=h=>{if(!(i===null||h.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(wg),s.onGeometryChanged(_g(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g)}}function dN(e,t,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const g=E=>{if(E.button!==0||!r()&&!fN(n))return;E.preventDefault(),E.stopPropagation(),a=E.pointerId,l=E.clientX,c=E.clientY;const S=e.getBoundingClientRect(),R=s.floatingParent.getBoundingClientRect();d=S.left-R.left,u=S.top-R.top,f=S.width,p=S.height,t.setPointerCapture(a),e.classList.add(yg)},h=E=>{if(a===null||E.pointerId!==a)return;const S=E.clientX-l,R=E.clientY-c,$=hN(n,S,R,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${$.x}px`,e.style.top=`${$.y}px`,e.style.width=`${$.width}px`),e.style.height=`${$.height}px`},m=E=>{if(!(a===null||E.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(yg),r()?i.onGeometryChanged(_g(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",g),t.addEventListener("pointermove",h),t.addEventListener("pointerup",m),t.addEventListener("pointercancel",m),()=>{t.removeEventListener("pointerdown",g),t.removeEventListener("pointermove",h),t.removeEventListener("pointerup",m),t.removeEventListener("pointercancel",m)}}function uN(){return["n","e","s","w","ne","nw","se","sw"]}function fN(e){return e==="s"}function Xi(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 _g(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function pN(e,t){return qn(e,t.minHeight??vg,t.maxHeight??1/0)}function Sg(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Ig(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function Kn(e){return Math.round(e/on)*on}function kg(e){const t=Math.floor(e/on)*on;return t>=Vn?t:Math.min(e,Vn)}function Ig(e,t,n,o,s){const i=me(s),r=i.x+Vn,a=i.y+Vn,l=Math.max(i.x,i.x+i.width-n-Vn),c=Math.max(i.y,i.y+i.height-o-Vn);return{x:Math.min(Math.max(r,e),l),y:Math.min(Math.max(a,t),c)}}function hN(e,t,n,o,s,i,r,a,l,c){const d=a.minWidth??eN,u=a.minHeight??vg,f=a.maxWidth??1/0,p=a.maxHeight??1/0,g=me(l),h=g.x+g.width,m=g.y+g.height;let E=o,S=s,R=i,$=r;if((e==="e"||e==="ne"||e==="se")&&(c?R=Zi(Kn(o+i+t),o+d,Math.min(o+f,h))-o:R=qn(i+t,d,Math.min(f,h-o))),e==="w"||e==="nw"||e==="sw"){const _=o+i;if(c)E=Zi(Kn(o+t),Math.max(0,_-Math.min(f,_)),_-d),R=_-E;else{const M=qn(i-t,d,Math.min(f,_));E=o+(i-M),R=M}}if((e==="s"||e==="se"||e==="sw")&&(c?$=Zi(Kn(s+r+n),s+u,Math.min(s+p,m))-s:$=qn(r+n,u,Math.min(p,m-s))),e==="n"||e==="ne"||e==="nw"){const _=s+r;if(c)S=Zi(Kn(s+n),Math.max(0,_-Math.min(p,_)),_-u),$=_-S;else{const M=qn(r-n,u,Math.min(p,_));S=s+(r-M),$=M}}return c||(R=i,E=o),{x:E,y:S,width:R,height:$}}function Zi(e,t,n){const o=qn(e,t,n),s=Math.floor(o/on)*on;if(s>=t)return s;const i=s+on;return i<=n?i:o}function qn(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const Ag="desktop-mode-widgets",Cg="desktop-mode-widgets-geometry",Lg="desktop-mode-widgets-docked-heights";function Tg(){try{return window.localStorage.getItem(Ag)}catch{return null}}function mN(){const e=Tg();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function el(e){try{window.localStorage.setItem(Ag,JSON.stringify(e))}catch{}}function gN(){try{const e=window.localStorage.getItem(Cg);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=yN(s);i&&(n[o]=i)}return n}catch{return{}}}function tl(e){try{window.localStorage.setItem(Cg,JSON.stringify(e))}catch{}}function wN(){try{const e=window.localStorage.getItem(Lg);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 Ng(e){try{window.localStorage.setItem(Lg,JSON.stringify(e))}catch{}}function yN(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 vN=120,bN="os-inline-loader",Og="os-inline-loader-keyframes";function EN(){return typeof customElements<"u"&&!!customElements.get("os-spinner")}function _N(){if(document.getElementById(Og))return;const e=document.createElement("style");e.id=Og,e.textContent="@keyframes os-inline-loader-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function SN(){if(EN()){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||(_N(),e.style.animation="os-inline-loader-spin 0.7s linear infinite"),e}function kN(e,t={}){const n=t.label??b("Loading…");let o=null,s=!1;const i=()=>{if(s||o||!e.isConnected)return;o=document.createElement("div"),o.className=bN,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(SN()),o.appendChild(l),e.appendChild(o)},r=t.immediate?null:window.setTimeout(i,vN);t.immediate&&i();const a=()=>{r!==null&&window.clearTimeout(r)};return{done:()=>{s||(s=!0,a(),o?.remove(),o=null)},fail:(l,c)=>{if(s||(s=!0,a(),o||(s=!1,i(),s=!0),!o))return;o.textContent="",o.setAttribute("aria-live","assertive"),o.style.flexDirection="column",o.style.color="var(--os-ui-fg-muted,#646970)";const d=document.createElement("span");if(d.textContent=l,o.appendChild(d),c){const u=document.createElement("button");u.type="button",u.textContent=b("Retry"),u.className="button button-small",u.addEventListener("click",()=>{o?.remove(),o=null,s=!1,c()}),o.appendChild(u)}}}}function IN(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 AN=["clock"],Ji=40,CN=12;class LN{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=mN(),this.geometry=gN(),this.dockedHeights=wN(),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(){Tg()===null&&(this.enabledIds=AN.filter(t=>!!jn(t)),el(this.enabledIds));for(const t of this.visibleIds())this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){if(jn(t)){if(this.override){if(this.override.includes(t))return;this.override=[...this.override,t],this.mountById(t),this.paintEmptyState(),C(y.WIDGET_ADDED,{id:t});return}this.enabledIds.includes(t)||(this.enabledIds.push(t),el(this.enabledIds),this.mountById(t),this.paintEmptyState(),C(y.WIDGET_ADDED,{id:t}))}}remove(t){if(this.override){if(!this.override.includes(t))return;this.override=this.override.filter(o=>o!==t),this.unmountById(t),this.paintEmptyState(),C(y.WIDGET_REMOVED,{id:t}),ss();return}const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(el(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],tl(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],Ng(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),C(y.WIDGET_REMOVED,{id:t}),ss())}getEnabledIds(){return[...this.enabledIds]}getMountedIds(){return Array.from(this.mounted.keys())}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),XT({anchor:this.addTile,registry:()=>Jc(),enabledIds:()=>[...this.enabledIds],onAdd:t=>{this.add(t),Qc(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){jn(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 jn(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)||!jn(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=jn(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=iN(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:IN(t)};C(y.WIDGET_MOUNTING,{id:t,container:i.body,ctx:l});const c=u=>{const f=this.mounted.get(t);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,this.positionAddTile(),C(y.WIDGET_MOUNTED,{id:t,container:i.body,ctx:l})};let d;try{d=n.mount(i.body,l)}catch(u){this.handleMountFailure(t,u);return}if(TN(d)){const u=kN(i.body,{label:b("Loading…")});d.then(f=>{u.done(),c(f)},f=>{u.done(),this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,f)});return}c(d)}unmountById(t){const n=this.mounted.get(t);if(n){C(y.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){C(y.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)),C(y.WIDGET_MOUNT_FAILED,{id:t,error:n}),C(y.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="os-widgets__add",t.setAttribute("aria-label",b("Add widget"));const n=document.createElement("span");n.className="os-widgets__add-plus",n.setAttribute("aria-hidden","true"),n.textContent="+";const o=document.createElement("span");return o.className="os-widgets__add-label",o.textContent=b("Add widget"),t.appendChild(n),t.appendChild(o),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.openPicker()}),t}watchPointerProximity(){let t=null,n=0;const o=()=>{t=null,this.positionAddTile()},s=()=>{n||(n=requestAnimationFrame(()=>{n=0,this.positionAddTile()}))},i=c=>{t||(t=this.root.getBoundingClientRect());const d=c.clientX>=t.left-Ji&&c.clientX<=t.right+Ji&&c.clientY>=t.top-Ji&&c.clientY<=t.bottom+Ji;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=To(()=>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),Xi(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],tl(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=Sg(o,this.floatingHost);s.x===o.x&&s.y===o.y||(Xi(n.frame.card,s),this.persistGeometry(t,s))}}persistGeometry(t,n){this.geometry[t]=n,tl(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+CN,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,Ng(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 TN(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const NN=280,ON=220,DN=520,RN=400;function xN(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function MN(e,t,n){return o=>{const s=xN(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=kT(s,i);t.push(r);let a;try{a=new URL(e.url,window.location.origin).origin}catch{a=window.location.origin}let l=null;const c=new Promise(f=>{l=f}),d=()=>{if(e.bridge)try{const f=i.contentDocument;if(f&&!f.querySelector("script[data-os-iframe-bridge]")){const p=window.openStationConfig?.iframeBridgeUrl;if(p){const g=f.createElement("script");g.src=p,g.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(g)}}}catch{}P_(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!==""&&M_(s,p.channel,p.payload);try{e.onMessage?.(f.data)}catch(g){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",g)}};return window.addEventListener("message",u),t.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),c}}function WN(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=MN(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??DN,height:t.height??RN,minWidth:t.minWidth??NN,minHeight:t.minHeight??ON,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let PN=0;function $N(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++PN}`,s=n.persistent===!0,i=[["opened",y.WINDOW_OPENED],["reopened",y.WINDOW_REOPENED],["focused",y.WINDOW_FOCUSED],["blurred",y.WINDOW_BLURRED],["closing",y.WINDOW_CLOSING],["closed",y.WINDOW_CLOSED],["minimized",y.WINDOW_MINIMIZED],["restored",y.WINDOW_RESTORED],["maximized",y.WINDOW_MAXIMIZED],["unmaximized",y.WINDOW_UNMAXIMIZED],["fullscreenEntered",y.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",y.WINDOW_FULLSCREEN_EXITED],["resized",y.WINDOW_RESIZED],["bodyResized",y.WINDOW_BODY_RESIZED],["boundsChanged",y.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const l=()=>{if(!a){a=!0;for(const c of r)yo(c,o)}};for(const[c,d]of i){const u=t[c];u&&(r.push(d),ee(d,o,f=>{const p=f;if(p.windowId!==e)return;const{windowId:g,...h}=p;u(h),c==="closed"&&!s&&l()}))}return l}function UN(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function BN(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&xS(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function Dg(e,t){const n=t??{},o=s=>{const i=s?n[s]:void 0;if(!i?.deps||i.deps.length===0)return;const r=[];for(const a of i.deps){const l=n[a];l&&r.push({handle:a,url:l.url??"",before:l.before,after:l.after,l10n:l.l10n,translations:l.translations})}return r.length>0?r:void 0};return e.map(s=>{const i=s.scriptHandle?n[s.scriptHandle]:void 0,r=[];for(const l of s.companionScripts??[]){if(typeof l!="string"){r.push(l);continue}const c=n[l];c?.url&&r.push({scriptUrl:c.url,scriptHandle:l,scriptBefore:c.before,scriptAfter:c.after,scriptL10n:c.l10n,scriptTranslations:c.translations,scriptDeps:o(l)})}const a=(s.tabs??[]).map(l=>{if(typeof l.scriptUrl=="string")return l;const c=l.scriptHandle?n[l.scriptHandle]:void 0;return{...l,scriptUrl:c?.url??"",scriptBefore:c?.before,scriptAfter:c?.after,scriptL10n:c?.l10n,scriptTranslations:c?.translations,scriptDeps:o(l.scriptHandle)}});return{...s,scriptUrl:s.scriptUrl??i?.url??"",scriptBefore:s.scriptBefore??i?.before,scriptAfter:s.scriptAfter??i?.after,scriptL10n:s.scriptL10n??i?.l10n,scriptTranslations:s.scriptTranslations??i?.translations,scriptDeps:s.scriptDeps??o(s.scriptHandle),companionScripts:r,tabs:a}})}function FN(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=v=>{const I=vi(v.id);return I?{width:Math.max(I.width,v.minWidth),height:Math.max(I.height,v.minHeight)}:{width:v.width,height:v.height}},u=v=>{if(i.has(v.templateId))return;if(document.getElementById(v.templateId)){i.add(v.templateId);return}if(!v.templateHtml)return;const I=document.createElement("template");I.id=v.templateId,I.innerHTML=v.templateHtml,document.body.appendChild(I),i.add(v.templateId)},f=v=>{const I=v.styleUrl;if(!I||l.has(I))return;const N=I.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${N}"]`)){const k=document.createElement("link");k.rel="stylesheet",k.href=I,v.styleHandle&&(k.dataset.osStyleHandle=v.styleHandle),document.head.appendChild(k)}if(Array.isArray(v.styleInline))for(const k of v.styleInline){if(typeof k!="string"||k==="")continue;const U=document.createElement("style");v.styleHandle&&(U.dataset.osStyleHandle=v.styleHandle),U.textContent=k,document.head.appendChild(U)}l.add(I)},p=v=>{f(v)},g=v=>{for(const I of v.companionStyles??[])f(I)},h=new Set,m=(v,I)=>{if(h.has(v))return;h.add(v);const N=[I.scriptTranslations??"",...I.scriptL10n??[],...I.scriptBefore??[],...I.scriptAfter??[]];for(const D of N)typeof D=="string"&&D!==""&&rh(D)},E=(v,I)=>{const N=I.scriptUrl,D=`${v}|${N}`;if(r.has(N))return m(D,I),Promise.resolve();const k=a.get(N);if(k)return k.then(()=>m(D,I));h.add(D);const U=fe(N,{translations:I.scriptTranslations,l10n:I.scriptL10n,before:I.scriptBefore,after:I.scriptAfter,deps:I.scriptDeps}).catch(G=>{C(y.SHELL_ERROR,{scope:"native-window-script-load",id:v,error:G})}).then(()=>{r.add(N),a.delete(N)});return a.set(N,U),U},S=async v=>{g(v);for(const I of v.companionScripts??[])I.scriptUrl&&await E(v.id,I);v.scriptUrl&&await E(v.id,v)},R=async v=>{v.preloadScript&&await S(v)},$=new Set,_=(v,I)=>{if(!v||$.has(v)||r.has(v)||l.has(v))return;$.add(v);const N=document.createElement("link");N.rel="prefetch",N.as=I,N.href=v,document.head.appendChild(N)},M=()=>{const v=navigator.connection;if(!(v?.saveData||/2g$/.test(v?.effectiveType??""))){for(const I of c.values())if(!I.preloadScript){for(const N of I.companionScripts??[])_(N.scriptUrl,"script");_(I.scriptUrl,"script");for(const N of I.companionStyles??[])_(N.styleUrl,"style")}}};let P=!1;const B=()=>{if(P)return;P=!0;const v=()=>{P=!1,M()};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(v,{timeout:4e3}):window.setTimeout(v,1500)},F=v=>async(I,N)=>{I.appendChild(Rg(v.templateId)),BN(I,v),await S(v),window.wp?.os?.apps?.refresh?.();const k=UN()[v.id];return k?.(I,N)},K=(v,I)=>{const N=F(v),D=d(v);t.open({id:v.id,baseId:v.id,native:!0,url:`#${v.id}`,title:v.title,icon:v.icon,width:D.width,height:D.height,minWidth:v.minWidth,minHeight:v.minHeight,render:N,autofocus:v.autofocus,ownerHandle:v.ownerHandle||v.scriptHandle,...I?{params:I}:{}})},Z=(v,I)=>{const N=F(v),D=d(v);t.openNew({id:v.id,baseId:v.id,native:!0,url:`#${v.id}`,title:v.title,icon:v.icon,width:D.width,height:D.height,minWidth:v.minWidth,minHeight:v.minHeight,initialState:"normal",render:N,autofocus:v.autofocus,ownerHandle:v.ownerHandle||v.scriptHandle,...I?{params:I}:{}})},Y=(v,I,N)=>{const D=F(v),k=d(v);t.openNew({id:I,baseId:v.id,native:!0,url:`#${v.id}`,title:v.title,icon:v.icon,width:k.width,height:k.height,minWidth:v.minWidth,minHeight:v.minHeight,render:D,autofocus:v.autofocus,ownerHandle:v.ownerHandle||v.scriptHandle,...N})},L=async v=>{if(!s.has(v.id)){if(v.placement==="none"){u(v),p(v),await R(v),s.add(v.id);return}u(v),p(v),await R(v),n({id:v.id,title:v.title,icon:v.icon,windowId:v.id,navKind:v.navKind==="control"?"control":"app",defaultPlacement:"rail",order:v.dockOrder,placeable:v.placeable===!0,isOpen:()=>!!t.getById(v.id),onOpen:()=>K(v)}),C(y.DOCK_ITEM_APPENDED,{id:v.id}),s.add(v.id)}},x=v=>{s.has(v)&&(o(v),s.delete(v),c.delete(v))},j=async v=>{const I=new Set;for(const N of v)I.add(N.id),c.set(N.id,N);for(const N of Array.from(s))I.has(N)||x(N);for(const N of v)s.has(N.id)||await L(N);B()},V=(v,I={})=>{const N=c.get(v);return N?(Se.publish("os/open-requested",{windowId:v,source:I.source??"api"}),K(N,I.params),!0):!1},J=(v,I={})=>{const N=c.get(v);return N?(Se.publish("os/open-requested",{windowId:v,source:I.source??"api"}),Z(N,I.params),!0):!1},O=(v,I,N)=>{const D=c.get(I);return D?(Y(D,v,N),!0):!1};return ee(y.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",v=>{const I=v,N=I?.windowId,D=I?.width,k=I?.height;if(!N||typeof D!="number"||typeof k!="number")return;const U=t.getById(N);if(!U||U.state!=="normal")return;const G=U.config.baseId||U.id;dp(G,{width:D,height:k}),U.element&&up(G,{x:U.element.offsetLeft,y:U.element.offsetTop})}),ee(y.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",v=>{const I=v?.windowId;if(!I)return;const N=t.getById(I);if(!N||N.state!=="normal"||!N.element)return;const D=N.config.baseId||N.id;dp(D,{width:N.element.offsetWidth,height:N.element.offsetHeight}),up(D,{x:N.element.offsetLeft,y:N.element.offsetTop})}),ee(y.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",v=>{const I=v?.windowId;if(!I||Ht())return;const N=t.getById(I);if(!N)return;const D=N.config.baseId||N.id,k=c.get(D),U=k?{width:k.width,height:k.height}:{width:N.config.width,height:N.config.height};fp(D,"maximized",U)}),ee(y.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",v=>{const I=v?.windowId;if(!I)return;const N=t.getById(I);if(!N)return;const D=N.config.baseId||N.id;fp(D,null)}),{sync:j,openById:V,openNewById:J,restoreById:O,loadScriptById:async v=>{const I=c.get(v);return I?(await S(I),!0):!1},prewarmById:async v=>{const I=c.get(v);return!I||t.getById(v)?!1:(await S(I),window.wp?.os?.apps?.prewarm?.(v)===!0)}}}function Rg(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 Qi(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=ue(e,o);return s.find(r=>ue(r.url,o)===i||(r.submenu??[]).some(a=>ue(a.url,o)===i))??null}const xg="data:image/svg+xml;base64,",er=new Map;function HN(e){const t=er.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(xg.length)).includes("currentColor")}catch{}return er.size>=256&&er.clear(),er.set(e,n),n}function Yn(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const l=si(t.slot);l!==null&&(e=l),s=ga(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",Ni(l,e,s))return l}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const l=e.slice(xg.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",HN(e)&&Ni(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 Mg(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return Mg(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=GN(o);i.textContent=r;const a=sc(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 Mg(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 GN(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 Wg="os-icon__badge",is=new Map,rs=new Map;function zN(e){return Math.max(0,Math.floor(Number(e)||0))}function Pg(e,t){if(!e)return;const n=Fg(e);if(!n)return;const o=zN(t),s=is.get(e)??0;o!==s&&(o===0?is.delete(e):is.set(e,o),Hg(n,o),Se.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),C(y.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function jN(e){Pg(e,0)}function VN(e){return is.get(e)??0}function KN(e,t){if(e){if(!t){rs.delete(e);return}rs.get(e)!==t&&(rs.set(e,t),YN(e,t),Se.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function $g(e){return rs.get(e)??""}function qN(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function YN(e,t){const o=Fg(e)?.querySelector(".os-icon__image");if(o){const s=Yn(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${qN(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const nl={setBadge:Pg,clearBadge:jN,getBadge:VN,setArt:KN,getArt:$g};function XN(e){return!e||e.length===0?"":`${ma()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let Ug="";function Bg(e,t,n){const o=XN(t);if(o===Ug&&e.querySelector(":scope > .os-icons"))return;Ug=o;const s=e.querySelector(":scope > .os-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="os-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",b("Desktop icons"));const r=[...t].sort((l,c)=>{const d=l.pinned?0:1,u=c.pinned?0:1;return d-u}),a=new Map;for(const l of r){const c=JN(l,n),d=is.get(l.id)??0;d>0&&Hg(c,d);const u=rs.get(l.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(Yn(u,{className:"os-icon__image",title:""}))}i.appendChild(c),a.set(l.id,c)}e.appendChild(i),C(y.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(l=>l.id),container:i,tiles:a})}function Fg(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${ZN(e)}"]`):null}function Hg(e,t){const n=e.querySelector(`:scope > .${Wg}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=ae(Gt("%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=Wg,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function ZN(e){const t=window.CSS;return t?.escape?t.escape(e):e}function JN(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=Yn(e.icon,{title:e.title,className:"os-icon__image",slot:ii(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(),C(y.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),QN(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),lh({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function QN(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(Uo(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=Qi(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 eO(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 Gg="os-side-dock";function tO(e,t,n,o,s="bottom"){let i=t,r=s,a=n,l=o??[],c=null,d=null,u=null,f=null,p=null;const g=new Map;let h=[],m=mh({items:[],config:{placement:{},order:[]},layout:i,openWindows:[]});const E=()=>e.getSettings?.()??{navPlacement:{},navOrder:[]},S=()=>{const k=e.windowManager.getActiveDesktopId(),U=[],G=new Set;for(const le of e.windowManager.getAll()){if((le.config.desktopId||k)!==k)continue;const re=le.config.baseId||le.id;G.has(re)||(G.add(re),U.push({id:re,title:le.config.title||re,icon:le.config.icon||"dashicons-admin-generic",fromAdminUrl:le.config.native!==!0}))}return U},R=k=>k.windowId?k.windowId:Ei(k.url)??ue(k.url,e.adminUrl),$=()=>{const k=[];for(const G of g.values())k.push({item:G,kind:G.navKind??"app",locked:G.locked});h=eO({menuItems:a,systemTiles:k,icons:l,resolveMenuWindowId:R});const U=E();m=mh({items:h,config:{placement:Pk(U.navPlacement,h,e.getWorkspaceProfile?.()??null),order:U.navOrder},layout:i,openWindows:S()})},_=k=>k.tile?{type:"system",item:k.tile}:k.menu?{type:"menu",item:k.windowId?{...k.menu,windowId:k.windowId}:k.menu}:{type:"menu",item:{id:k.id,title:k.title,icon:k.icon,url:k.entry?.url||"",windowId:k.windowId,badge:0,submenu:[],isCore:!1}},M=k=>!!k.entry||!!k.windowId||!!k.menu?.url,P=(k,U)=>k.entry?k.entry:{id:k.id,title:k.title,icon:k.icon,window:k.windowId??"",url:k.menu?.url||"",position:2e3+U},B=k=>({core:(k.core??[]).map(_),apps:(k.apps??[]).map(_),controls:(k.controls??[]).map(_)}),F=(k,U,G)=>{if(!k)return;if(k.setZones){k.setZones(U),G.clear();for(const ge of ct)for(const q of U[ge])q.type==="system"&&G.add(q.item.id);return}const le=[],re=new Set;for(const ge of ct)for(const q of U[ge])q.type==="menu"?le.push(q.item):re.add(q.item.id);k.replaceItems(le);for(const ge of Array.from(G))re.has(ge)||(k.removeSystemItem(ge),G.delete(ge));for(const ge of ct)for(const q of U[ge])q.type==="system"&&!G.has(q.item.id)&&(k.appendSystemItem(q.item),G.add(q.item.id))},K=new Set,Z=new Set,Y=()=>{$(),F(c,B(m.dock),K),F(d,{core:m.sidebar.map(_),apps:[],controls:[]},Z),e.renderIcons(m.desktop.filter(M).map(P))},L=()=>Array.from(m.ephemeral).sort().join(","),x=()=>{const k=document.getElementById(Gg);if(k)return k;const U=document.createElement("nav");return U.id=Gg,U.className="os-dock",U.setAttribute("role","toolbar"),U.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(U,e.shellBody.firstChild),U},j=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},V=()=>{if(c){try{c.destroy()}catch(k){C(y.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:k})}c=null,u=null}if(d){try{d.destroy()}catch(k){C(y.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:k})}d=null,f=null}K.clear(),Z.clear()},J=k=>{const U=ta();if(!U)return C(y.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return U.mount(k)}catch(G){if(C(y.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:U.id,error:G}),U===rc)return null;try{return rc.mount(k)}catch{return null}}},O=(k,U)=>({container:k,items:[],fullMenu:a.slice(),fullSystemTiles:h.filter(G=>!!G.tile).filter(G=>T(G.id)).map(G=>G.tile),orientation:U,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:G=>{const le=ue(G.url,e.adminUrl);e.windowManager.open({id:le,baseId:le,url:G.url,parentUrl:G.url,title:G.title,icon:G.icon.startsWith("dashicons-")?G.icon:"dashicons-admin-generic",submenu:G.submenu,selfLabel:G.selfLabel,multi:!!G.multi})},openSubmenuPick:(G,le)=>{Uo(le.url)||e.windowManager.open({id:ue(le.url,e.adminUrl),baseId:ue(G.url,e.adminUrl),url:le.url,parentUrl:G.url,title:G.title,icon:G.icon.startsWith("dashicons-")?G.icon:"dashicons-admin-generic",submenu:G.submenu,selfLabel:G.selfLabel,multi:!!G.multi})},openSystemItem:G=>G.onOpen()}),T=k=>{for(const U of ct)if(m.dock[U].some(G=>G.id===k))return!0;return m.sidebar.some(U=>U.id===k)},W=()=>i==="classic"?"bottom":r,v=()=>{V(),$(),i==="classic"?(p=x(),d=J(O(p,"left")),f=vh(d)):j(),c=J(O(e.bottomDockEl,W())),u=vh(c),Y()},I=()=>{document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:W(),primary:u,side:f}}))},N={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:k=>{k!==i&&(i=k,e.shellRoot.setAttribute("data-os-layout",k),v(),I())},getDockPlacement:()=>r,setDockPlacement:k=>{if(k===r)return;const U=W();r=k,W()!==U&&(v(),I())},applyDockItems:k=>{a=k,Y()},applyDesktopIcons:k=>{l=k??[],Y()},appendSystemTile:k=>{g.set(k.id,k),Y()},removeSystemTile:k=>{g.delete(k)&&Y()},listSystemTiles:()=>Array.from(g.values()).map(k=>({id:k.id,title:k.title,icon:k.icon,navKind:k.navKind??"app",placeable:k.placeable===!0,locked:k.locked===!0})),getSystemTile:k=>g.get(k)??null,getMenuItems:()=>a.slice(),getNavItems:()=>h.slice(),getNav:()=>m,refresh:Y,destroy:()=>{V(),j()}};for(const k of["os-window-opened","os-window-closed"])document.addEventListener(k,()=>{const U=L();$(),L()!==U&&Y()});e.shellRoot.setAttribute("data-os-layout",i),v();let D=ta()?.id??null;return FE(()=>{const k=ta()?.id??null;k!==D&&(D=k,v(),I())}),N}const zg="os-ai-loading",jg="os-ai-loading-keyframes";let Xn=null,as=null;function nO(){if(document.getElementById(jg))return;const e=document.createElement("style");e.id=jg,e.textContent="@keyframes os-ai-loading-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function oO(e){if(Xn&&Xn.isConnected)return;as=r=>{r.key==="Escape"&&(tr(),e?.())},document.addEventListener("keydown",as);const t=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=document.createElement("div");n.id=zg,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||(nO(),s.style.animation="os-ai-loading-spin 0.7s linear infinite");const i=document.createElement("span");i.textContent=b("Starting the command palette…"),o.appendChild(s),o.appendChild(i),n.appendChild(o),document.body.appendChild(n),Xn=n}function tr(){as&&(document.removeEventListener("keydown",as),as=null),Xn&&(Xn.remove(),Xn=null),document.getElementById(zg)?.remove()}function sO(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 iO{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 KT().catch(t=>{console.warn("[openstation] command-palette runtime failed to load",t)}),this._loadPromise?this._loadPromise:($i("desktop-mode-ai-assistant"),this._loadPromise=sO(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||oO(()=>this.close()),this._ensure().then(t=>{tr(),this._intendOpen&&t.open()}).catch(t=>{tr(),console.warn("[openstation] command palette failed to load",t)})}close(){this._intendOpen=!1,tr(),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 Vg=e=>!e||typeof e!="object"?!1:e.name==="AbortError",rO=e=>{if(!e)return[];const t=tL();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}}):[]},aO=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 cO(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 lO(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function dO(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 Le(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 Vg(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=nL(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:lO(a)}};l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);let u;try{u=await t(d,c)}catch(g){if(Vg(g))throw g;return null}if(!u.ok)return null;const f=await u.json().catch(()=>({}));return(typeof f.message=="string"?f.message.trim():"")!==""?f.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[openstation] wp.os.ai.ask: empty query passed with non-default options — likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const l=rO(r.tools),c=aO(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:g,args:h,result:m}=p;let E=cO(f.message,m);if(r.followUp===!0){const S=await o(a,g,h,m,c,r.signal);S!==null&&(E=S)}return{answer_type:"tool_call",message:E,entity:null,admin_links:null,toolCall:{slug:g,args:h,result:m},request_id:f.request_id}}}const et=ie("openstation/trash-optimistic",()=>({changes:new Map,reconcile:new Set})),uO=e=>`${e.type}:${e.id}`;function Kg(e){return{subtitle:"",mime:"",preview:"",icon:"",deleted_at:new Date().toISOString(),deleted_by:"",deleted_by_id:0,can_restore:!1,can_purge:!1,edit_link:"",...e}}function Zn(e){const t=e.file,n=t.type==="shortcut"?"shortcut":"placement";return Kg({id:t.type==="folder"?Number(t.ref):e.id,type:t.type==="folder"?"folder":n,title:t.title,icon:t.icon,preview:t.previewUrl})}function fO(){return Array.from(et.state.changes.values())}function pO(e,t){const n=et.subscribe(e);return()=>{n()}}function sn(e,t="in"){const n=uO(e);if(et.state.changes.get(n)?.pending)return null;const o={item:e,direction:t,pending:!0};return et.state.changes.set(n,o),et.notify(),{async finish(s){et.state.changes.get(n)!==o||!o.pending||(o.pending=!1,s&&(et.notify(),await Promise.allSettled(Array.from(et.state.reconcile,async i=>i()))),et.state.changes.get(n)===o&&(et.state.changes.delete(n),et.notify()))}}}const qg="[os-bin badge]";function lt(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(qg,...e)}catch{}}function nr(...e){console.warn(qg,...e)}const cs="desktop-mode-recycle-bin",hO="openstation_recycle_bin_seen_ts";function mO(){return window.wp?.os}const we=ie("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function ls(e){const t=Math.max(0,Math.floor(e)),n=we.state.current;we.state.current=t,lt("setRecycleBinCount",{prev:n,next:t}),or(t)}function Yg(e){ls(we.state.current+e)}function gO(){return we.state.current}function or(e){const t=fO().filter(i=>i.pending),o=e+t.reduce((i,r)=>i+(r.direction==="in"?1:-1),0)>0?we.state.fullArt:we.state.emptyArt;if(lt("paintIconState",{count:e,full:e>0,hasArt:!!o}),!o)return;const s=mO();s?.dock?.setArt?.(cs,o),s?.taskbar?.setArt?.(cs,o),s?.icons?.setArt?.(cs,o)}function wO(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;we.state.emptyArt=String(o?.recycleBinIconEmpty??""),we.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;lt("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:we.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)||nr("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),we.state.started){ls(n);return}we.state.started=!0,we.state.countUrl=t,we.state.seenTs=Date.now(),ls(n),yO(),vO(),pO(()=>or(we.state.current)),bO(),EO(),_O()}function yO(){ee(y.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===cs&&or(we.state.current)})}function vO(){ee(y.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(cs)&&or(we.state.current)})}function bO(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":Yg(+r);break;case"untrashed":case"deleted":Yg(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])Gn(`os.${s}.changed`,e)}function EO(){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<=we.state.seenTs){lt("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:we.state.seenTs});return}lt("postMessage triggers refetch",{ts:o,prevSeenTs:we.state.seenTs}),we.state.seenTs=o,SO()})}function _O(){const e=window.jQuery;if(!e){nr("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}lt("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[hO]=we.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;lt("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>we.state.seenTs&&(we.state.seenTs=o.ts),typeof o.count=="number"&&ls(o.count))})}async function SO(){if(!we.state.countUrl){lt("refetchCount: no countUrl, skip");return}lt("refetchCount: hitting",we.state.countUrl);try{const e=await fetch(we.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){nr("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();lt("refetchCount: response",t),typeof t.count=="number"&&ls(t.count)}catch(e){nr("refetchCount: fetch failed",e)}}const kO="desktop-mode-os-settings",IO="desktop-mode-recycle-bin";function AO(e){const t=TO();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===kO?CO():i===IO?LO(s,e.getRecycleBinCount):n})}function CO(e){const t=document.createElement("span");t.className="os-dock-peek__card-body os-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="os-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="os-dock-peek__os-subtitle",o.textContent=b("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="os-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`os-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function LO(e,t){const n=document.createElement("span");n.className="os-dock-peek__card-body os-dock-peek__card-body--recycle-bin",n.setAttribute("aria-hidden","true");const o=Math.max(0,Math.floor(t()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="os-dock-peek__bin-stage";const i=document.createElement("span");i.className="os-dock-peek__bin-stack";for(let l=0;l<3;l++){const c=document.createElement("span");c.className="os-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="os-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="os-dock-peek__bin-label",o===0?a.textContent=b("Trash — empty"):o===1?a.textContent=b("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function TO(){return window.wp?.hooks??null}const ds="desktop-mode-bug-report",NO="WordPress",OO="openstation",Xg=6e3;function DO(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="os-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="os-bug-report__intro",n.textContent=b("Found a bug or have a feature idea? Fill this in and we will open a pre-filled GitHub issue for you to review and submit."),t.appendChild(n),t.appendChild(RO()),t.appendChild(xO("title",b("Title"),{placeholder:b("A short summary"),required:!0})),t.appendChild(Zg("description",b("What happened? What did you expect?"),{placeholder:b("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(Zg("steps",b("Steps to reproduce (bug only)"),{placeholder:b("One step per line"),rows:4}));const o=MO();t.appendChild(o);const s=document.createElement("div");s.className="os-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="os-bug-report__submit",i.textContent=b("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=b("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const l=PO(t);if(!l.title.trim()||!l.description.trim()){WO(t,b("Title and description are both required."));return}const c=$O(l);window.open(c,"_blank","noopener")}),e.appendChild(t)}function RO(){const e=document.createElement("div");e.className="os-bug-report__field os-bug-report__field--type";const t=document.createElement("span");t.className="os-bug-report__label",t.textContent=b("Type"),e.appendChild(t);const n=document.createElement("div");n.className="os-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:b("Bug"),checked:!0},{value:"feature",label:b("Feature request")},{value:"question",label:b("Question")}];for(const s of o){const i=document.createElement("label");i.className="os-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const a=document.createElement("span");a.textContent=s.label,i.appendChild(a),n.appendChild(i)}return e.appendChild(n),e}function xO(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 Zg(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 MO(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=b("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=Qg(Jg()),e.appendChild(n),e}function WO(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 PO(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 $O(e){const t=UO(e.type),n=BO(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/${NO}/${OO}/issues/new?${o.toString()}`}function UO(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function BO(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(Qg(Jg())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(`
35 `);return n.length>Xg&&(n=n.slice(0,Xg)+`
36
37 …(truncated to fit GitHub URL length limit)`),n}function Jg(){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 Qg(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 `)}let rn=null,ew=!1,tw=!1,nw=!1,ol=null,us=!1,sl=[],an="pending";const FO=5e3,HO=3e3;function GO(e,t,n){if(tw)return;tw=!0;const o=typeof t.shellBuild=="string"?t.shellBuild:"",s=(r,a)=>{jO(r).then(l=>{if(!(o!==""&&l!==""&&l!==o)){a&&ow(r);return}a&&(ol=r),!(nw||!n)&&(nw=!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(ol=null,us){us=!1;const a=sl;sl=[];for(const l of a)l();return}const r=navigator.serviceWorker.controller;r&&s(r,!1)})}function ow(e){us=!0;try{e.postMessage({type:"os-sw-skip-waiting"})}catch{us=!1}}function zO(){const e=ol;return e?new Promise(t=>{let n=!1;const o=()=>{n||(n=!0,window.clearTimeout(s),t())},s=window.setTimeout(o,HO);sl.push(o),ow(e),us||o()}):Promise.resolve()}function jO(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(""),FO),navigator.serviceWorker.addEventListener("message",s);try{e.postMessage({type:"os-sw-get-build"})}catch{i("")}})}const VO=5*6e4;let sw=null,il=0;function KO(e){if(sw)return;il=Date.now();const t=()=>{if(typeof document<"u"&&document.visibilityState==="hidden")return;const n=Date.now();if(!(n-il<VO)){il=n;try{e.update().catch(()=>{})}catch{}}};document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),sw=()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t)}}const qO=["/desktop-mode/sw.js"];function YO(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:qO.some(o=>n.pathname.endsWith(o))}catch{return!1}}function iw(){const e=window.openStationConfig?.pwa?.swConfig;ZO({adminAssetCache:e?.adminAssetCache===!0,windowPrewarm:e?.windowPrewarm===!0})}async function XO(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return an="unsupported",null;if(rn||ew)return rn;if(!t.forceReplace){const s=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(i=>{const r=i.active?.scriptURL??i.installing?.scriptURL??"";return r!==""&&!YO(r,e)});if(s)return an="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{rn=await n(e.swUrl)}catch(o){if(!e.swFallbackUrl||e.swFallbackUrl===e.swUrl)throw o;rn=await n(e.swFallbackUrl)}return an="registered",GO(rn,e,t.onShellUpdated),KO(rn),iw(),navigator.serviceWorker.addEventListener("controllerchange",iw),rn}catch(o){return ew=!0,an="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",o),null}}function ZO(e){try{navigator.serviceWorker?.controller?.postMessage({type:"os-sw-config",...e})}catch{}}function JO(){return an}const QO="os-pwa-install";function rw(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function aw(){if(rw())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 Rt=null;function eD(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(),Rt=s}function o(){Rt=null,t({message:ae(b("Installed %s as an app."),e)})}}function tD(e,t){return{id:QO,title:b("Install web app"),icon:"dashicons-download",onOpen:()=>{nD(e,t)}}}async function nD(e,t){if(Rt){const n=Rt;Rt=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:b("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await aw()){t({message:ae(b("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(JO()==="foreign-sw"){t({message:b("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the openstation_pwa_force_replace_sw filter to true.")});return}t({message:b("Install isn't available right now. Keep using the page; if it still doesn't appear, the app may already be installed in this browser.")})}async function oD(){if(!Rt)return"unavailable";const e=Rt;Rt=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function sD(){Promise.resolve().then(()=>VC).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function iD(e,t,n){if(!e.pwa)return;Qh(e.pwa),eD(e.pwa.appName||"WordPress",t);const o=n?()=>{t({message:b("A new version of OpenStation is available."),action:{label:b("Reload"),onClick:()=>{zO().then(()=>n())}},persistent:!0,dismissible:!0})}:void 0;XO(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw,onShellUpdated:o})}const fs=ie("desktop-mode/drag-bridge-resolvers",()=>({byKind:new Map}));function rD(e,t){return fs.state.byKind.set(e,t),()=>{fs.state.byKind.get(e)===t&&fs.state.byKind.delete(e)}}function aD(e){return fs.state.byKind.has(e.kind)}async function cD(e){const t=fs.state.byKind.get(e.kind);if(!t)return e;try{return await t(e)}catch(n){return console.error("[openstation] bridge payload resolver threw:",n),null}}const Jn={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function lD(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function dD(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function uD(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function fD(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 pD{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(lD(n)){this._startDrag(n.payload);return}if(dD(n)){this._endDrag();return}if(uD(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=fD(t);this._payload=n,document.dispatchEvent(new CustomEvent(Jn.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(Jn.END,{detail:{payload:t}}))}}class hD{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 mD="os-drag-ghost",cw="os-drag-ghost--accept",lw="os-drag-ghost--reject",gD="os-drag-hint",dw="os-drag-hint--accept",uw="os-drag-hint--reject",fw="os-drag-hint--neutral",wD=16,yD=18;function vD(e,t,n){const o=ID(e),s=e.ghost?.offsetX??AD(e.source),i=e.ghost?.offsetY??CD(e.source);o.classList.add(mD),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=ED(e),a=r?bD():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+wD}px, ${d+yD}px, 0)`)},setMode(c,d){o.classList.remove(cw,lw),c==="accept"?o.classList.add(cw):c==="reject"&&o.classList.add(lw),a&&r&&(a.classList.remove(dw,uw,fw),c==="accept"?(a.classList.add(dw),a.textContent=d?.acceptLabel??r.accept):c==="reject"?(a.classList.add(uw),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 bD(){const e=document.createElement("div");return e.className=gD,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 ED(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??_D(e),reject:t?.reject??SD(),neutral:t?.neutral??kD(e)}}function _D(e){return e.type==="shortcut"?b("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?b("Drop here to move","desktop-mode"):b("Drop here","desktop-mode")}function SD(e){return b("Can’t drop here","desktop-mode")}function kD(e){return e.type==="shortcut"?b("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?b("Drop in a folder","desktop-mode"):""}function ID(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 AD(e){return e.offsetWidth/2}function CD(e){return e.offsetHeight/2}let pw=!1;function LD(e){pw||(pw=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const hw=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"},sr="os-file-tile--dragging",mw="os-file-tile--drop-target",gw="data-os-trash-drop-active",ww="data-files-drop-active",yw="data-os-dragging",vw="data-os-drag-type",rl="data-os-drag-mode";class TD{constructor(){this._registry=new hD,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)<hw&&Math.abs(s)<hw)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),yt(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||Ht())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(),LD(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:()=>bw(),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(sr),t._ghost=vD(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(yw,""),document.body.setAttribute(vw,String(t.payload.type)),document.body.setAttribute(rl,"neutral")),yt(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&&al(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(ND(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),yt(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(rl,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),al(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)}yt(ke.COMMIT,{payload:t.payload,targetId:n.id}),yt(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&&al(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}yt(ke.CANCEL,{payload:t.payload,reason:n}),yt(ke.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(sr)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(yw),document.body.removeAttribute(vw),document.body.removeAttribute(rl)),OD()}}function yt(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function ND(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}yt(ke.ENTER,{payload:t.payload,targetId:e.id})}function al(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}yt(ke.LEAVE,{payload:t.payload,targetId:e.id})}function bw(){if(typeof document>"u")return[];const e=[];for(const t of[`.${sr}`,`.${mw}`,`[${gw}]`,`[${ww}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function OD(){for(const e of bw())e.classList.remove(sr,mw),e.removeAttribute(gw),e.removeAttribute(ww)}const DD=".os-window",Ew="wp-window-";function _w(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(DD);return o instanceof HTMLElement?o:null}function RD(e){if(!e.id.startsWith(Ew))return null;const t=e.id.slice(Ew.length);return t.length>0?t:null}const xD="desktop-mode-iframe-drop-",ir="iframe.os-window__iframe",cl="data-os-iframe-drop-active";let ll=!1,Sw=null;const je=new Map,cn=new Map;let vt=null,ln=null;function MD(){document.querySelectorAll(ir).forEach(t=>{je.has(t)||(je.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function WD(){je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear()}function kw(e,t){const n=_w(e,t);if(!n)return null;const o=n.querySelector(ir);return o instanceof HTMLIFrameElement?o:null}const Iw=e=>{if(!vt)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=kw(e.clientX,e.clientY);if(t===ln){t&&dl(t,e.clientX,e.clientY);return}ln&&(ul(),dt(ln,{type:"os-drag-leave"})),ln=t,t&&(dt(t,{type:"os-drag-over",payload:vt}),dl(t,e.clientX,e.clientY))},Aw=e=>{if(!vt)return;const t=kw(e.clientX,e.clientY);if(!t){e.preventDefault(),rr();return}e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const n=vt;rr();const o=t.getBoundingClientRect();dt(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},Cw=()=>{rr()};function PD(e){if(vt){vt=e;return}vt=e,MD(),document.addEventListener("dragover",Iw,!0),document.addEventListener("drop",Aw,!0),document.addEventListener("dragend",Cw,!0)}function rr(){vt&&(vt=null,ul(),ln&&(dt(ln,{type:"os-drag-leave"}),ln=null),document.removeEventListener("dragover",Iw,!0),document.removeEventListener("drop",Aw,!0),document.removeEventListener("dragend",Cw,!0),WD())}function ar(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}let Qn=null,cr=null,eo=0;function dl(e,t,n){cr={iframe:e,clientX:t,clientY:n},!eo&&(eo=requestAnimationFrame(()=>{eo=0;const o=cr;if(cr=null,!o||!o.iframe.isConnected)return;const s=o.iframe.getBoundingClientRect();dt(o.iframe,{type:"os-drag-move",position:{x:o.clientX-s.left,y:o.clientY-s.top}})}))}function ul(){cr=null,eo&&(cancelAnimationFrame(eo),eo=0)}function dt(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function $D(e,t,n,o){return e.registerDropTarget({id:`${xD}${o}`,element:n,accept:s=>!!ar(s),onEnter:s=>{const i=ar(s.payload);i&&(n.setAttribute(cl,""),Qn=t,dt(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(cl),Qn===t&&(Qn=null),dt(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(cl),Qn=null;const r=ar(s.payload);if(!r)return;const a=t.getBoundingClientRect(),l={x:i.clientX-a.left,y:i.clientY-a.top};if(!aD(r)){dt(t,{type:"os-drop",payload:r,position:l});return}UD(t,r,l)}})}async function UD(e,t,n){const o=await cD(t);if(!o){dt(e,{type:"os-drag-leave"});return}dt(e,{type:"os-drop",payload:o,position:n})}function Lw(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 BD(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 FD(e){const t=Sw;if(!t)return;const n=document.querySelectorAll(ir),o=!!ar(e);BD(n.length,o,e),n.forEach(s=>{if(je.has(s)||(je.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||cn.has(s))return;const i=s.parentElement;if(!i)return;const r=Lw(s),a=$D(t,s,i,r);cn.set(s,a)})}function HD(){ul(),Qn=null,je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear(),cn.forEach(e=>{try{e()}catch{}}),cn.clear()}function GD(e){ll||(ll=!0,Sw=e,document.addEventListener(ke.START,t=>{const n=t.detail;FD(n?.payload)}),document.addEventListener(ke.END,()=>{HD()}),document.addEventListener(ke.MOVE,t=>{const n=Qn;if(!n)return;const o=t.detail;typeof o?.clientX!="number"||typeof o?.clientY!="number"||dl(n,o.clientX,o.clientY)}),document.addEventListener(Jn.START,t=>{const n=t.detail;n?.payload&&PD(n.payload)}),document.addEventListener(Jn.END,()=>{rr()}),ee(y.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(je))t.isConnected||je.delete(t);for(const[t,n]of Array.from(cn))if(!t.isConnected){try{n()}catch{}cn.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:ll,iframesInDom:document.querySelectorAll(ir).length,suppressedCount:je.size,registeredCount:cn.size,suppressedIframeIds:Array.from(je.keys()).map(Lw)}))}const zD=250,jD=1e3,VD="os-drag-hover";let Tw=!1,fl=null,pl=null,ps=null,hs=null,hl=null;function Nw(){ps!==null&&(clearTimeout(ps),ps=null)}function Ow(){hs!==null&&(clearTimeout(hs),hs=null)}function ms(){Nw(),Ow(),pl=null}function Dw(){Ow(),hs=setTimeout(()=>{hs=null,ms()},jD)}function KD(e,t){const n=fl?.getById(e);if(!(!n||n.isFocused()||!X(y.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{fl?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function Rw(e,t){e!==pl&&(Nw(),pl=e,e!==null&&(ps=setTimeout(()=>{ps=null,KD(e,t)},zD)))}function xw(e,t,n){const o=_w(e,t);Rw(o?RD(o):null,n)}const qD=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||xw(t.clientX,t.clientY,t.payload?.type??"")},YD=()=>{ms()};function XD(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 ZD=e=>{Dw();const t=hl??(XD(e)?"os-file":"external");xw(e.clientX,e.clientY,t)},Mw=()=>{ms()},JD=e=>{e.relatedTarget===null&&ms()};function QD(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 eR=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==VD)return;const n=QD(e.source);n&&(Dw(),Rw(n,typeof t.payloadType=="string"?t.payloadType:"external"))},tR=e=>{const t=e.detail;t?.payload&&(hl=t.payload.kind??"")},nR=()=>{hl=null,ms()};function oR(e){Tw||(Tw=!0,fl=e,document.addEventListener(ke.MOVE,qD),document.addEventListener(ke.END,YD),document.addEventListener(Jn.START,tR),document.addEventListener(Jn.END,nR),document.addEventListener("dragover",ZD,!0),document.addEventListener("drop",Mw,!0),document.addEventListener("dragend",Mw,!0),document.addEventListener("dragleave",JD,!0),window.addEventListener("message",eR))}function Ww(){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=X("os.open-command.items",o);return Array.isArray(i)?i:o}const sR={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=Ww();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=Ww(),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 iR(){Hn(sR)}const Ie=[],rR=new Set;function Pw(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=Ie.findIndex(n=>n.id===e.id);return t>=0?Ie[t]=e:Ie.push(e),ml(),()=>{const n=Ie.findIndex(o=>o.id===e.id);n>=0&&(Ie.splice(n,1),ml())}}function aR(e){const t=Ie.findIndex(n=>n.id===e);t>=0&&(Ie.splice(t,1),ml())}function cR(){return Ie.slice()}function ml(){for(const e of Array.from(rR))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",t)}}function gs(e,t){try{document.dispatchEvent(new CustomEvent(t?"os-palette-opened":"os-palette-closed",{detail:{id:e}}))}catch{}}function $w(){if(Ie.length===0)return;const e=Ie.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{Ie[0].open(),gs(Ie[0].id,!0)}catch{}return}try{Ie[e].close(),gs(Ie[e].id,!1)}catch{}const t=e+1;if(t<Ie.length)try{Ie[t].open(),gs(Ie[t].id,!0)}catch{}}function gl(e){const t=Ie.find(n=>n.id===e);if(t){for(const n of Ie)if(n.id!==e)try{n.isOpen()&&(n.close(),gs(n.id,!1))}catch{}try{t.open(),gs(t.id,!0)}catch{}}}let Uw=!1;function lR(){if(Uw)return;Uw=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),$w())},!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"&&$w()})}const tt=ie("os/presence",()=>({byUser:new Map,serverTimeMs:0})),dR=5*60*1e3;let Bw=Date.now(),Fw=!1;function lr(){Bw=Date.now()}function uR(e){if(!e||!e.snapshot)return;const t=tt.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})}tt.state.byUser=n,typeof e.serverTimeMs=="number"&&(tt.state.serverTimeMs=e.serverTimeMs),tt.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),Se.publish("os/presence-changed",i)}Se.publish("os/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function fR(){Fw||(Fw=!0,document.addEventListener("pointerdown",lr,{capture:!0,passive:!0}),window.addEventListener("keydown",lr,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||lr()}),De.contribute("openstation_presence_active",()=>!0),De.contribute("openstation_user_active",()=>Date.now()-Bw<dR),De.subscribe("openstation_presence",e=>{uR(e)}))}function pR(e){const t=tt.state.byUser.get(e);return t?t.status:"offline"}function hR(){return new Map(tt.state.byUser)}function mR(e){return tt.state.byUser.get(e)??null}function gR(e){return tt.subscribe(t=>e(t))}function wR(){lr()}function yR(e){if(!Array.isArray(e)||e.length===0)return;const t=tt.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)){tt.state.byUser=n,tt.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),Se.publish("os/presence-changed",i)}Se.publish("os/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const vR=Object.freeze({getStatus:pR,getAll:hR,getEntry:mR,subscribe:gR,markActive:wR,applyBatch:yR});function Hw(e){const t=new Set;let n=null;const o=new Set;e.onChange&&o.add(e.onChange);const s=()=>e.order().filter(a=>t.has(a)),i=()=>{const a=s();for(const l of o)try{l(a)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=a=>{const l=t.size,c=Array.from(t);a(),!(t.size===l&&c.every(d=>t.has(d)))&&i()};return{keys:s,has:a=>t.has(a),size:()=>t.size,anchor:()=>n,set(a){r(()=>{t.clear();for(const l of a)t.add(l)}),n=a.length>0?a[a.length-1]:null},add(a){r(()=>{t.add(a)}),n=a},remove(a){r(()=>{t.delete(a)}),n===a&&(n=null)},toggle(a){r(()=>{t.has(a)?t.delete(a):t.add(a)}),n=a},selectRange(a,l=!1){const c=e.order(),d=c.indexOf(a),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{l||t.clear(),t.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{l||t.clear();for(let g=f;g<=p;g+=1)t.add(c[g])})},selectAll(){const a=e.order();r(()=>{for(const l of a)t.add(l)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const a=new Set(e.order());let l=!1;return r(()=>{for(const c of Array.from(t))a.has(c)||(t.delete(c),l=!0)}),n!==null&&!a.has(n)&&(n=null),l},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const bR=".os-file-tile",ER="os-file-tile--selected",_R="os-selection-marquee",Gw=4,zw=36,jw=12,Vw="data-os-marquee";function SR(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function kR(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(Vw,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(Vw)}}const IR=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note, .os-mobile-home, .os-mobile-edge",AR="os-area--overview";function CR(e,t){const n=t.itemSelector??bR,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??IR,r=()=>Array.from(e.querySelectorAll(n)).filter(T=>t.keyOf(T)!==null),a=()=>{const T=[],W=new Map;r().forEach((I,N)=>{const D=I.parentElement??e;let k=W.get(D);k||(k=[],W.set(D,k),T.push(D)),k.push({key:t.keyOf(I),top:parseFloat(I.style.top)||0,left:parseFloat(I.style.left)||0,index:N})});const v=[];for(const I of T){const N=W.get(I)??[];N.sort((D,k)=>D.top!==k.top?D.top-k.top:D.left!==k.left?D.left-k.left:D.index-k.index);for(const D of N)v.push(D.key)}return v},l=t.order??a,c=Hw({order:l,onChange:T=>{p(),t.onChange?.(T),u(T)}}),d={},u=T=>{typeof document>"u"||(to={surface:t.surface??"",scope:t.scope??"",keys:T.slice(),count:T.length},yl=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:to})))},f=T=>r().find(W=>t.keyOf(W)===T)??null,p=()=>{for(const T of r()){const W=t.keyOf(T),v=c.has(W);v!==T.hasAttribute("selected")&&(v?T.setAttribute("selected",""):T.removeAttribute("selected")),T.classList.toggle(ER,v),T.hasAttribute("selectable")||T.setAttribute("selectable","");const I=v?"true":"false";T.getAttribute("aria-selected")!==I&&T.setAttribute("aria-selected",I)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let g=null;const h=T=>{if(!(T.target instanceof Element))return;const W=T.target.closest(n);if(W&&e.contains(W)){const v=t.keyOf(W);if(v===null)return;if(g=v,T.stopPropagation(),T.shiftKey){c.selectRange(v,T.ctrlKey||T.metaKey);return}if(T.ctrlKey||T.metaKey){c.toggle(v);return}c.set([v]);return}if($){$=!1;return}c.clear()};o.addEventListener("click",h);let m=null,E=null,S=null,R=[],$=!1,_=0,M=null,P=null;const B=T=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(T),P=T}catch{}},F=()=>{if(P===null||typeof o.releasePointerCapture!="function"){P=null;return}try{o.hasPointerCapture?.(P)&&o.releasePointerCapture(P)}catch{}P=null},K=(T,W)=>{const v=o.getBoundingClientRect();return{x:T-v.left+o.scrollLeft,y:W-v.top+o.scrollTop}},Z=()=>{m?.remove(),m=null,E=null,S=null,M?.(),M=null,F(),_&&(cancelAnimationFrame(_),_=0),document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",j),document.removeEventListener("pointercancel",V),o.removeEventListener("lostpointercapture",V),o.removeEventListener("scroll",Y),window.removeEventListener("blur",V)};function Y(){if(!E||!S)return;const T=K(S.x,S.y),W=T.x-E.x,v=T.y-E.y;if(!m&&Math.abs(W)<Gw&&Math.abs(v)<Gw)return;m||(m=document.createElement("div"),m.className=_R,m.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(m),$=!0,M=kR(o),L());const I=Math.min(E.x,T.x),N=Math.min(E.y,T.y),D=Math.abs(W),k=Math.abs(v);m.style.left=`${I}px`,m.style.top=`${N}px`,m.style.width=`${D}px`,m.style.height=`${k}px`;const U=o.getBoundingClientRect(),G=U.left-o.scrollLeft,le=U.top-o.scrollTop,re={left:I+G,top:N+le,right:I+D+G,bottom:N+k+le},ge=[];for(const q of r()){const ne=q.getBoundingClientRect();ne.left<re.right&&ne.right>re.left&&ne.top<re.bottom&&ne.bottom>re.top&&ge.push(t.keyOf(q))}c.set(Array.from(new Set([...R,...ge])))}function L(){if(_||typeof requestAnimationFrame!="function")return;const T=()=>{if(_=0,!m||!S)return;const W=o.getBoundingClientRect();if(SR(o)){let I=0;if(S.y<W.top+zw?I=-jw:S.y>W.bottom-zw&&(I=jw),I!==0){const N=o.scrollTop;o.scrollTop+=I,o.scrollTop!==N&&Y()}}_=requestAnimationFrame(T)};_=requestAnimationFrame(T)}const x=T=>{E&&(S={x:T.clientX,y:T.clientY},Y())},j=()=>{m&&(wl=Date.now()),Z()},V=()=>{Z()},J=T=>{if(!s||T.button!==0||!(T.target instanceof Element)||o.classList.contains(AR)||T.target.closest(n))return;const W=T.target.closest(i);W&&W!==o&&o.contains(W)||(E=K(T.clientX,T.clientY),S={x:T.clientX,y:T.clientY},typeof T.pointerId=="number"&&B(T.pointerId),R=T.ctrlKey||T.metaKey||T.shiftKey?c.keys():[],R.length===0&&c.clear(),document.addEventListener("pointermove",x),document.addEventListener("pointerup",j),document.addEventListener("pointercancel",V),o.addEventListener("lostpointercapture",V),window.addEventListener("blur",V),o.addEventListener("scroll",Y,{passive:!0}))};o.addEventListener("pointerdown",J);const O=T=>{if(T.key==="a"&&(T.ctrlKey||T.metaKey)){T.preventDefault(),c.selectAll();return}if(T.key==="Escape"){if(m||E){Z();return}c.size()>0&&c.clear();return}const W=T.key==="ArrowRight"||T.key==="ArrowDown",v=T.key==="ArrowLeft"||T.key==="ArrowUp";if(!W&&!v)return;const I=W?1:-1,N=l();if(N.length===0)return;const D=g??c.anchor(),k=D===null?-1:N.indexOf(D),U=Math.min(N.length-1,Math.max(0,k<0?0:k+I));T.preventDefault();const G=N[U];g=G,T.shiftKey?c.selectRange(G):c.set([G]),f(G)?.focus()};return e.addEventListener("keydown",O),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){Z(),o.removeEventListener("click",h),o.removeEventListener("pointerdown",J),e.removeEventListener("keydown",O),yl===d&&(to=null,yl=null)}}}let wl=0;function LR(){return wl>0&&Date.now()-wl<500}let to=null,yl=null;function TR(){return to?{...to,keys:to.keys.slice()}:null}function vl(e){return typeof e.sort=="number"?e.sort:100}function NR(e,t){return ae(b("%1$s (%2$d items)","desktop-mode"),e,t)}function Kw(e,t){if(e.length===0)return[];const n=e.map(a=>{const l=t(a);return Array.isArray(l)?l:[]});if(e.length===1)return n[0];const o=e.length,s=[],i=a=>a.multiId??a.id;for(const a of n[0]){const l=i(a),c=[];let d=!1;for(const p of n){const g=p.find(h=>i(h)===l);if(!g||g.multi!==!0){d=!0;break}c.push(g)}if(d||s.some(p=>p.id===l))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):NR(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(vl)),multi:!0,onClick:async p=>{const g=new Map,h=[];c.forEach((m,E)=>{const S=m.bulk;if(typeof S!="function"){h.push(m);return}const R=g.get(S);R?R.push(e[E]):g.set(S,[e[E]])});for(const[m,E]of g)try{await m(E)}catch(S){console.error(`[openstation] selection action '${l}' failed for a batch:`,S)}for(const m of h)try{await m.onClick(p)}catch(E){console.error(`[openstation] selection action '${l}' failed for one item:`,E)}}})}s.sort((a,l)=>{const c=vl(a),d=vl(l);return c!==d?c-d:a.label.localeCompare(l.label)});const r=X("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function qw(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 bl=8;function Yw(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function El(e){Yw(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-bl)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-bl)}px`)})}function Xw(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,Yw(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-bl)}px`)})}const OR="os-wallpaper-menu";let no=null,_l=null,Zw=0;function Sl(){if(!no)return;const e=no.dataset.menuScope??"selection",t=_l;no.dispatchEvent(new CustomEvent("tile-menu-closed")),no.remove(),no=null,_l=null,t?.(),C(`os.${e}.menu.closed`,{})}function DR(e,t){Sl();const n=++Zw;Ys(()=>n===Zw,()=>RR(e,t))}function RR(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(OR),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",xR(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(g=>{console.error(`[openstation] menu action '${p.id}' threw:`,g)}))}),document.body.appendChild(a),no=a,_l=r??null,El(a);const c=qw(a,{close:()=>Sl()});a.addEventListener("tile-menu-closed",c);const d=t.map(u=>u.id);i?.(d),C(`os.${s}.menu.opened`,{items:d,count:t.length})}function xR(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const MR={active:TR,resolveCommonActions:Kw,createModel:Hw};let ws=null;function WR(){De.contribute("openstation_content_changes_seen_ts",()=>ws===null?0:ws),De.subscribe("openstation_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=ws===null,n=ws??0;let o=Math.max(n,e.ts);if(!t&&Array.isArray(e.entries))for(const s of e.entries)!s||typeof s.ts!="number"||s.ts<=n||typeof s.type!="string"||s.type===""||(zi(`os.${s.type}.changed`,{source:"heartbeat",action:typeof s.action=="string"&&s.action!==""?s.action:"updated",ids:Array.isArray(s.ids)?s.ids.map(Number).filter(i=>i>0):[]}),s.ts>o&&(o=s.ts));ws=o})}const PR="desktop_mode_nonces",kl=new Map;let Jw=!1;function Il(e,t){if(typeof e!="string"||e==="")return()=>{};let n=kl.get(e);return n||(n=new Set,kl.set(e,n)),n.add(t),()=>{n.delete(t)}}function $R(){Jw||(Jw=!0,De.subscribe(PR,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=kl.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)}}}),UR())}function UR(){Il("wp_rest",BR),Il("desktop-mode-plugins",e=>{Qw("desktop-mode-plugins","ajaxNonce",e)}),Il("updates",e=>{Qw("desktop-mode-plugins","updatesNonce",e)})}function BR(e){const t=FR();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=ey();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Qw(e,t,n){const s=ey()?.[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 FR(){if(!(typeof window>"u"))return window.openStationConfig}function ey(){if(!(typeof window>"u"))return window.openStationWindowConfig}const HR="desktop_mode_auth",GR=5e3,ty=1e3,zR=1e4;let ny=!1,dr=!1,Al=!1,ur=0,oy=0,ys=0,oo=null,sy=0,iy=null,ry=null,ay=()=>{try{window.location.reload()}catch{}};function Cl(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function Ll(e=ty){const t=Date.now();if(t<ys){oo===null&&(oo=window.setTimeout(()=>{oo=null,ys=Date.now()+ty,Cl()},ys-t));return}ys=t+e,Cl()}function jR(){dr=!0,!Al&&(Al=!0,C(y.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function VR(){for(const e of KR())try{e.contentWindow?.location.reload()}catch{}}function KR(){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 Tl(){const e=Date.now();e-sy<zR||(sy=e,dr=!1,Al=!1,oo!==null&&(window.clearTimeout(oo),oo=null),ys=0,Ll(),VR(),C(y.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function qR(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(ur<=0){ur=t;return}t!==ur&&ay()}}function YR(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<oy||(oy=o+GR,Cl())}function XR(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");ry=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&Ll(),t=n}),ry.observe(e,{attributes:!0,attributeFilter:["class"]})}function ZR(e={}){ny||(ny=!0,ur=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(ay=e.reloadShell),De.subscribe("wp-auth-check",t=>{if(t===!1){jR();return}t===!0&&dr&&Tl()}),De.subscribe("nonces_expired",()=>{if(dr){Tl();return}Ll()}),De.subscribe(HR,qR),iy=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&Tl()},window.addEventListener("message",iy),XR())}const so=12;function Nl(e,t){return cy(ue(e,t.adminUrl),t)}function cy(e,t){if(e)return(t.dockItems||[]).find(n=>ue(n.url,t.adminUrl)===e||(n.submenu||[]).some(o=>ue(o.url,t.adminUrl)===e))}function ly(e,t){const n=t.x??0,o=t.y??0,s=Math.max(200,t.width-so*2),i=Math.max(200,t.height-so*2),r=Math.min(e.width,s),a=Math.min(e.height,i),l=n+Math.max(0,t.width-r-so),c=o+Math.max(0,t.height-a-so),d=Math.max(n+so,Math.min(e.x,l)),u=Math.max(o+so,Math.min(e.y,c));return{x:d,y:u,width:r,height:a}}const dy=window.location.origin;function JR(e,t){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let l;try{l=new URL(a,window.location.href)}catch(m){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",a,m);return}if(l.origin!==dy)return;let c;try{c=new URL(t.adminUrl).pathname}catch(m){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,m),c="/wp-admin/"}if(!l.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(l.pathname)||l.searchParams.has("action")&&l.searchParams.get("action")==="logout"||l.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Ze(l.href)))return;const d=ue(l.href,t.adminUrl),u=Nl(l.href,t),f=(i.dataset.osWindowTitle||"").trim(),p=(i.textContent||"").trim()||u?.title||"",g=!!i.closest("#wp-admin-bar-new-content"),h={id:d,baseId:d,multi:!!u?.multi||g,url:l.href,parentUrl:u?.url??l.href,title:f||u?.title||p,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu,selfLabel:u?.selfLabel};if(g){e.openNew(h);return}e.open(h)},!0)}function QR(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 ex(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 tx(e){const t=QR(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=ex(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 nx="os-registry-changed";function ox(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 Ol(e,t,n){const{added:o,removed:s}=ox(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(nx,{detail:i}))}function sx(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:l,syncServerWindowActions:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:g,renderIcons:h,applyDesktopIcons:m,refreshRootPlacements:E,syncShortcuts:S,applyMultisite:R}=e,$=_=>(_??[]).map(M=>String(M?.id??"")).sort().join(`
39 `);return function(M){const P=M.dockItems,B=M.nativeWindows,F=M.serverWidgets,K=M.serverWallpapers,Z=M.serverCommandScripts,Y=M.serverCommands,L=M.serverSettingsTabScripts,x=M.serverSettingsTabs,j=M.serverDockRailRendererScripts,V=M.serverTitleBarButtonScripts,J=M.serverWindowActionScripts,O=M.serverUnfocusEffectScripts,T=M.serverWindowLinkRendererScripts,W=M.serverWindowNotices,v=M.serverGames,I=M.serverDesktopThemes,N=M.desktopIcons;if(!Array.isArray(P)||P.length===0)return;const D=n.dockItems;if(t(P),n.dockItems=P,Ol("dock-items",D,P),S?.(),Array.isArray(B)){const k=n.nativeWindows;o(Dg(B,M.nativeWindowScriptData)),n.nativeWindows=B,M.nativeWindowScriptData&&(n.nativeWindowScriptData=M.nativeWindowScriptData),Ol("native-windows",k,B)}if(Array.isArray(F)&&(s(F),n.serverWidgets=F),Array.isArray(K)&&(i(K),n.serverWallpapers=K),Array.isArray(v)&&(p(v),n.serverGames=v),Array.isArray(I)&&(g?.(I),n.serverDesktopThemes=I),Array.isArray(Z)&&(r(Z,Array.isArray(Y)?Y:void 0),n.serverCommandScripts=Z,Array.isArray(Y)&&(n.serverCommands=Y)),Array.isArray(L)&&(a(L,Array.isArray(x)?x:void 0),n.serverSettingsTabScripts=L,Array.isArray(x)&&(n.serverSettingsTabs=x)),Array.isArray(V)&&(l(V),n.serverTitleBarButtonScripts=V),Array.isArray(J)&&(c(J),n.serverWindowActionScripts=J),Array.isArray(O)&&(d(O),n.serverUnfocusEffectScripts=O),Array.isArray(T)&&(u(T),n.serverWindowLinkRendererScripts=T),Array.isArray(j)&&(f(j),n.serverDockRailRendererScripts=j),Array.isArray(W)&&(ag(W),n.serverWindowNotices=W),Array.isArray(N)){const k=n.desktopIcons;h(N),m?.(N),S?.(),$(k)!==$(N)&&E?.(),n.desktopIcons=N,Ol("desktop-icons",k,N)}tx(M.updateCounts),"multisite"in M&&R?.(M.multisite??null)}}const ix=8e3,rx=600;function ax(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:h,applyMultisite:m,renderIcons:E,refreshRootPlacements:S,syncShortcuts:R}=e,$=sx({applyDockItems:L=>t?.applyDockItems(L),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:h,applyMultisite:m,renderIcons:E,applyDesktopIcons:L=>t?.applyDesktopIcons(L),refreshRootPlacements:S,syncShortcuts:R});let _=typeof o.menuSig=="string"?o.menuSig:"",M=!1,P=null,B=!1,F=!1;const K=()=>{if(!o.adminUrl)return Promise.resolve();const L=(()=>{try{const x=new URL("admin.php",o.adminUrl);return x.searchParams.set("openstation_chromeless","1"),x.searchParams.set("openstation_menu_refresh","1"),x.toString()}catch{return null}})();return L?new Promise(x=>{const j=document.createElement("iframe");j.setAttribute("aria-hidden","true"),j.tabIndex=-1,j.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",j.src=L;let V=!1;const J=()=>{V||(V=!0,window.clearTimeout(T),window.removeEventListener("message",O),j.parentNode&&j.parentNode.removeChild(j),x())},O=W=>{if(W.source!==j.contentWindow)return;const v=W.data;!v||v.type!=="os-plugins-changed"||J()},T=window.setTimeout(()=>{C(y.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),J()},ix);window.addEventListener("message",O),document.body.appendChild(j)}):Promise.resolve()},Z=()=>{if(B){F=!0;return}B=!0,K().finally(()=>{B=!1,F&&(F=!1,Z())})},Y=()=>{P!==null&&window.clearTimeout(P),P=window.setTimeout(()=>{P=null,Z()},rx)};return window.addEventListener("message",L=>{if(L.origin!==dy)return;const x=L.data;if(x){if(x.type==="os-plugins-changed"){x.payload&&($(x.payload),typeof x.payload.menuSig=="string"&&(_=x.payload.menuSig));return}if(x.type==="os-updates-changed"){Y();return}if(x.type==="os-menu-signature"){const j=x.sig;typeof j=="string"&&j!==""&&j!==_&&!M&&(M=!0,K().finally(()=>{M=!1}))}}}),K}function uy(e,t){const n=ly(e,t);return{x:n.x,y:n.y,width:n.width,height:n.height,initialState:e.state}}function cx(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 lx(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 dx(e,t,n,o){const s=me(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?{}:uy(r,s),...r.params?{params:r.params}:{},...r.gridSpan?{gridSpan:r.gridSpan}:{}});Object.keys(i).length>0&&e.seedWindowRestoreState(i,{reserveIds:!0});for(const r of t.session.windows){if(r.native){if(e.discardWindowRestoreState(r.id),!o?.(r.id,r.baseId||r.id,i[r.id]))continue;await lx(e,r.id);continue}if(bo(r.url,t.adminUrl))continue;const a=Nl(r.url,t)??cy(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?{}:uy(r,s),submenu:a?.submenu,selfLabel:a?.selfLabel,...r.gridSpan?{gridSpan:r.gridSpan}:{}});if(Array.isArray(r.externalTabs))for(const c of r.externalTabs)c&&typeof c.url=="string"&&c.url!==""&&l.addExternalTab(c.url,typeof c.label=="string"&&c.label!==""?c.label:c.url)}if(e.discardWindowRestoreState(),t.session.focused){const r=e.getById(t.session.focused);r&&e.focus(r)}}async function ux(e,t){if(bo(t.currentPage,t.adminUrl)||Ze(t.currentPage))return;const n=ue(t.currentPage,t.adminUrl),o=Nl(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 fx(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function Dl(e,t,n,o){const s=au(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,YR(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(px(a));return a})).catch(()=>{}),i}function px(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return ae(b("Request failed (HTTP %s)."),t)}const hx="os-remember-session";function mx(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:hx,urls:t})}catch{}}const gx=500,wx=1500;function fy(e){const{updated:t,...n}=e;return JSON.stringify(n)}function py(e){try{if(!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled)return;mx(e.windows.filter(n=>!n.native&&n.url).map(n=>US(n.url)||"").filter(Boolean))}catch{}}function yx(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=fy(f);return p===a?Promise.resolve():(o=!0,r=Date.now(),py(f),i=(async()=>{try{(await Dl(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:f}),keepalive:!0},{silent:!0}))?.ok&&(a=p)}catch(g){C(y.SHELL_ERROR,{scope:"session-save",error:g})}finally{o=!1,i=null,s&&(s=!1,u())}})(),i)},c=async()=>{for(n!==null&&(clearTimeout(n),n=null);i;)await i;s=!1,await l()},d=()=>{n!==null&&(clearTimeout(n),n=null),s=!1;const f=e.snapshot(),p=fy(f);if(p===a)return;py(f);const g=new Blob([JSON.stringify({session:f})],{type:"application/json"}),h=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);if(navigator.sendBeacon&&navigator.sendBeacon(h,g)){a=p;return}l()},u=()=>{n!==null&&clearTimeout(n);let f=gx;if(r!==0){const p=Date.now()-r;f=Math.max(f,wx-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 vx=120;function bx(e){document.addEventListener("os-window-opened",e),document.addEventListener("os-window-closed",e),document.addEventListener("os-window-focused",e),document.addEventListener("os-window-changed",e),ee(y.DESKTOP_CREATED,"desktop-mode/session-save",e),ee(y.DESKTOP_CLOSED,"desktop-mode/session-save",e),ee(y.DESKTOP_SWITCHED,"desktop-mode/session-save",e),ee(y.DESKTOP_RENAMED,"desktop-mode/session-save",e),ee(y.WORKSPACE_UPDATED,"desktop-mode/session-save",e),ee(y.WORKSPACE_PROVISIONED,"desktop-mode/session-save",e)}function Ex(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;C(y.SHELL_RESIZED,{width:o?Math.round(o.width):window.innerWidth,height:o?Math.round(o.height):window.innerHeight})};window.addEventListener("resize",()=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(n,vx)}),document.addEventListener("visibilitychange",()=>{C(y.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function _x(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 X(y.DOCK_TILE_CLASS,e,o)}function Sx(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 X(y.DOCK_TILE_ELEMENT,e,o)}function kx(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 X(y.DOCK_TILE_TOOLTIP,e,o)}function Ix(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};C(y.DOCK_TILE_RENDERED,{...o,el:e})}const Ax=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),Rl=new Set;function Cx(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(Ax))return!0;for(const n of Rl)if(t.closest(n))return!0;return!1}function Lx(e){return typeof e!="string"||e.trim()===""?()=>{}:(Rl.add(e),()=>{Rl.delete(e)})}const bt=new Map,Tx=window.location.origin;function hy(e){let t=bt.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},bt.set(e,t)),Nx(e,t),t}function Nx(e,t){const n=xl(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(()=>io(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function Ox(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function xl(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 Dx(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 io(e){const t=xl(e);if(!t||!t.contentWindow)return;const n=bt.get(e),o=n?Dx(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},Tx)}catch{}}ee(y.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&bt.has(t.windowId)&&io(t.windowId)}),ee(y.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=bt.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const xt=new Map,Rx=1e3;function my(e,t,n){const o=xt.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,!!xt.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=xt.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>my(e,t,n),Rx))})}function xx(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function Mx(e,t){const n=xt.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let Wx=0;const gy={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=hy(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),io(e),()=>{const r=bt.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),io(e),wy(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=hy(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,io(e)),()=>{const i=bt.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),io(e)),wy(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=xl(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=gy.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){Mx(e,{id:++Wx,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=xt.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},xt.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=xx();r&&my(e,r.restUrl,r.restNonce)}return()=>{const r=xt.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),xt.delete(e))}}}};function wy(e){const t=bt.get(e);t&&t.headers.size===0&&t.observers.size===0&&(Ox(t),bt.delete(e))}function Px(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:yy(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:yy(c),face:"top",element:l})});const a=X(y.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function yy(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const $x="__openstationKeyedListKey",Ux="__openstationKeyedListData";function Bx(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function Fx(e,t,n){const o=Bx(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[$x]=c,u[Ux]=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 Hx(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function Gx(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:l=B=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",B)}}=e;let c=e.sentinel??null;c||(c=document.createElement("div"),c.dataset.osInfiniteListSentinel="",c.style.height="1px",t.appendChild(c));const d=new Set;let u=r,f=!0,p=!1,g=null,h=0,m=!1,E=null;const S=B=>{if(p!==B){p=B;try{a(B)}catch(F){l(F)}}},R=()=>{E&&(E.disconnect(),E=null)},$=()=>{E||!c||m||(E=new IntersectionObserver(B=>{for(const F of B)F.isIntersecting&&_()},{rootMargin:i}),E.observe(c))},_=async()=>{if(m||p||!f)return;S(!0),g=new AbortController;const B=g;try{const F=await n(u,B.signal);if(m||B!==g)return;let K=0;const Z=document.createDocumentFragment();for(const Y of F.items??[]){const L=String(o(Y));if(d.has(L))continue;d.add(L);const x=s(Y,h+K);Z.appendChild(x),K++}K>0&&(c&&c.parentNode===t?t.insertBefore(Z,c):t.appendChild(Z),h+=K),u=F.nextCursor??null,u||(f=!1,R())}catch(F){if(F?.name==="AbortError")return;l(F)}finally{B===g&&(S(!1),g=null)}},M=()=>{if(m)return;g?.abort(),g=null,d.clear(),u=r,f=!0,h=0;const B=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);B&&c&&t.appendChild(c),S(!1),$(),_()},P=()=>{m||(m=!0,R(),g?.abort(),g=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,S(!1))};return $(),_(),{reset:M,loadMore:_,hasMore:()=>f,isLoading:()=>p,destroy:P}}const zx=520,jx=720,Vx=500;function Kx(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=Yx(),o=Xx();return Le(rt(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=>qx(s,e,t))}function qx(e,t,n){return new Promise((o,s)=>{const i=n.width??zx,r=n.height??jx,a=Math.max(0,Math.floor((window.screen.width-i)/2)),l=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${l}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(e.authorize_url,`os-oauth-${t}`,c);if(!d){s(new Error("[openstation] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let f=null,p=!1;const g=()=>{p||(p=!0,window.removeEventListener("message",h),f!==null&&(window.clearInterval(f),f=null))},h=m=>{if(m.origin!==u)return;const E=m.data;if(!E||E.type!=="os-oauth-callback")return;const S=E.payload;if(g(),S&&S.ok)o(S);else{const R=S?.reason??"unknown",$=S?.message??"OAuth flow failed",_=new Error(`[openstation] startOAuth(${t}) failed: ${R} — ${$}`);_.cause=S,s(_)}};window.addEventListener("message",h),f=window.setInterval(()=>{d.closed&&(g(),s(new Error(`[openstation] startOAuth(${t}) cancelled — popup closed before completing.`)))},Vx)})}function vy(){return window.openStationConfig??{}}function Yx(){const e=vy().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function Xx(){const e=vy().restNonce;return typeof e=="string"&&e!==""?e:null}const fr=["os-section","os-button","os-swatch","os-swatch-grid","os-segmented","os-segment","os-select","os-option","os-multiselect","os-color-field","os-range-field","os-text-field","os-number-field","os-checkbox","os-checkbox-label","os-switch","os-toast","os-toast-container","os-tabs","os-tab","os-tabpanel","os-window-button","os-menu","os-menu-item","os-action-menu","os-context-menu","os-context-menu-option","os-confirm-dialog","os-modal","os-user-search","os-role-picker","os-flyout","os-tab-chip","os-stack","os-cluster","os-icon","os-body","os-panel","os-row","os-grid","os-app-frame","os-split","os-display","os-disclosure","os-empty-state","os-key","os-code","os-badge","os-ribbon","os-tile","os-log","os-steps","os-step","os-table","os-spinner","os-relative-time","os-histogram","os-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"],by=new Set(fr);let pr=null;function Ml(){return!!window.openStationComponents}function Zx(){return window.openStationConfig?.componentsBundleUrl??""}function Jx(e){return new Promise((t,n)=>{const o=()=>{if(Ml()){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){Ml()?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 Qx(e){const t=e.filter(n=>!by.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 ${fr.length} tags; see docs/components-reference.md for the list. The others in this call still loaded.`)}async function eM(e){if(e){if(Qx(e),e.filter(o=>by.has(o)&&!customElements.get(o)).length===0)return}else if(Ml())return;const t=Zx();t&&(pr||(pr=Jx(t).catch(n=>{throw pr=null,n})),await pr)}const tM=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","dockPlacement","icons","iconSet","files","confirm","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","openNewWindow","cloneTemplate","onWindow","createInfiniteList","startOAuth","repaintLoadingOverlays","loadVendorScript","getWallpaperSurfaces","wallpaper","games","mode","deactivationFeedback","registerModule","loadModules","whenReady","ready","isReady","setDefaultWindow","refreshMenu","config","ai","dragBridge","dragManager","registerCommand","unregisterCommand","listCommands","registerDestructiveAdminAction","unregisterDestructiveAdminAction","listDestructiveAdminActions","registerSettingsTab","unregisterSettingsTab","listSettingsTabs","registerDockRailRenderer","unregisterDockRailRenderer","listDockRailRenderers","openOsSettings","getOsSettings","subscribeOsSettings","updateOsSettings","resetOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","getNavItems","getNav","renderIcon","applyTileClasses","applyTileElement","applyTileTooltip","dispatchTileRendered","isDockElement","registerDockSelector","registerTitleBarButton","unregisterTitleBarButton","listTitleBarButtons","registerWindowAction","unregisterWindowAction","listWindowActions","registerUnfocusEffect","unregisterUnfocusEffect","listUnfocusEffects","registerWindowReveal","unregisterWindowReveal","listWindowReveals","relations","registerWindowLinkRenderer","unregisterWindowLinkRenderer","listWindowLinkRenderers","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","desktopThemes","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","getConnection","broadcast","subscribe","announceContentChange","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","workArea","selection","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","getWindowParams","debug","registerNativeUrlRemap","fetch"]);function nM(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:l,registerWindow:c,openWindowById:d,openNewWindowById:u,loadWindowScriptById:f,prewarmWindowById:p,placeSystemTile:g,setDefaultWindow:h,refreshMenu:m,openOsSettings:E,aiAssistant:S,dragBridge:R,dragManager:$,connect:_,getConnection:M,wallpaperSuspend:P,mio:B,mode:F,workspaces:K,config:Z}=e,Y={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,iconSet:CE,files:r,confirm:Yt,saveSession:a,hooks:sE(),HOOKS:y,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:L=>{Mn(L),s.apply()},registerWidget:L=>{Zc(L)},widgetLayer:l,widgets:{redock:L=>{l?.redock(L)}},loadVendorScript:fe,getWallpaperSurfaces:()=>Px(t),wallpaper:P,mio:B,mode:F,games:Zh,registerWindow:c,openWindow:d,openNewWindow:u,loadWindowScript:f,prewarmWindow:p,loadComponents:eM,fetch:(L,x,j)=>Dl(t,L,x,j),repaintLoadingOverlays:Lp,cloneTemplate:Rg,onWindow:$N,createInfiniteList:Gx,startOAuth:Kx,registerSystemTile:L=>{g(L),C(y.DOCK_ITEM_APPENDED,{id:L.id})},registerModule:Bh,loadModules:vc,whenReady:Gd,ready:Gd,isReady:rE,setDefaultWindow:h,refreshMenu:m,config:Z,ai:S,dragBridge:R,dragManager:$,registerCommand:Hn,unregisterCommand:am,listCommands:cm,registerDestructiveAdminAction:FI,unregisterDestructiveAdminAction:Tp,listDestructiveAdminActions:HI,registerSettingsTab:dm,unregisterSettingsTab:um,listSettingsTabs:fm,registerDockRailRenderer:cu,unregisterDockRailRenderer:PE,listDockRailRenderers:BE,openOsSettings:E,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:L=>s.subscribeOsSettings(L),updateOsSettings:(L,x={})=>{s.update(L,x),(L.navPlacement||L.navOrder)&&o?.refresh()},resetOsSettings:(L={})=>{s.reset(L),o?.refresh()},deriveWindowId:(L,x)=>ue(L,x??Z.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:L=>o?.getSystemTile(L)??null,getMenuItems:()=>o?.getMenuItems()??[],getNavItems:()=>o?.getNavItems()??[],getNav:()=>o?.getNav()??null,renderIcon:Yn,applyTileClasses:_x,applyTileElement:Sx,applyTileTooltip:kx,dispatchTileRendered:Ix,isDockElement:Cx,registerDockSelector:Lx,registerTitleBarButton:Vo,unregisterTitleBarButton:mm,listTitleBarButtons:lL,registerWindowAction:ym,unregisterWindowAction:fL,listWindowActions:hL,registerUnfocusEffect:Vi,unregisterUnfocusEffect:FL,listUnfocusEffects:xc,registerWindowReveal:Ue,unregisterWindowReveal:w_,listWindowReveals:Ru,relations:JI,registerWindowLinkRenderer:$m,unregisterWindowLinkRenderer:KL,listWindowLinkRenderers:Wc,registerWindowTheme:Gm,unregisterWindowTheme:zm,listWindowThemes:jm,desktopThemes:{list:C_,getActive:ma,setActive:lc,ensureFull:zu,subscribe:N_,resolveIcon:si,resolveIconColor:ga,applyRecommendedOsSettings:L=>{const x=L!==void 0?L:ma()??"";return s.applyThemeRecommendations(x)}},applyWindowTheme:(L,x)=>{const j=t.getById(L);j&&j.setAppearanceTheme(x)},registerWindowControl:Qo,unregisterWindowControl:qm,listWindowControls:Ym,applyWindowControls:(L,x)=>{const j=t.getById(L);j&&j.setAppearanceControls(x)},registerWindowSlot:Qm,unregisterWindowSlot:Gc,listWindowSlots:eg,applyWindowSlot:(L,x,j)=>{const V=t.getById(L);V&&V.setAppearanceSlot(x,j)},registerWindowNotice:ig,unregisterWindowNotice:Kc,listWindowNotices:rg,dismissWindowNotice:wT,undismissWindowNotice:yT,registerWindowChrome:ET,unregisterWindowChrome:dg,listWindowChromes:ug,applyWindowChrome:(L,x)=>{const j=t.getById(L);j&&j.setAppearanceChrome(x)},connect:_,getConnection:M,broadcast:zi,subscribe:Gn,announceContentChange:km,registerPalette:Pw,unregisterPalette:aR,listPalettes:cR,openPalette:gl,devtools:gy,createSharedStore:ie,presence:vR,workArea:sk,workspaces:K,selection:MR,activity:Se,heartbeat:De,showToast:de,notify:Ic,pwa:{promptInstall:oD,undismissInstallHint:sD,getState:Go,subscribe:em,requestNotificationPermission:KC,getNotificationPermission:qC},renderKeyedList:Fx,clearKeyedList:Hx,registerNamespace:(L,x)=>{if(typeof L!="string"||L===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!x||typeof x!="object"){console.warn(`[openstation] registerNamespace("${L}"): api must be an object`);return}if(tM.has(L)){console.warn(`[openstation] registerNamespace("${L}"): name is reserved by the shell — pick a plugin-specific key`);return}Y[L]=x;const j=window.wp?.os;j&&j!==Y&&(j[L]=x)},getWindowConfig:L=>{const x=window.openStationWindowConfig;if(!x||typeof x!="object")return;const j=x[L];return j===void 0?void 0:j},getWindowParams:L=>{const x=t.getById(L);if(x)return{...x.config.params??{}}},registerNativeUrlRemap:Tt,debug:{window:L=>{const x=(Z.nativeWindows??[]).find(W=>W.id===L);if(!x)return null;const j=x.scriptUrl||(x.scriptHandle?Z.nativeWindowScriptData?.[x.scriptHandle]?.url??"":"");let V="unknown",J=!1;j&&(document.querySelector(`script[data-os-vendor="${j.replace(/"/g,'\\"')}"]`)?(V="lazy",J=!0):Array.from(document.querySelectorAll("script[src]")).find(I=>I.src===j)&&(V="eager",J=!0));const O=window.openStationWindowConfig,T=!!(O&&typeof O=="object"&&Object.prototype.hasOwnProperty.call(O,L));return{id:L,scriptHandle:x.scriptHandle||"",scriptUrl:j,loadPath:V,tagInDom:J,configPresent:T,extras:{hasTranslations:!!x.scriptTranslations,l10nCount:(x.scriptL10n??[]).length,beforeCount:(x.scriptBefore??[]).length,afterCount:(x.scriptAfter??[]).length}}}}};return Y}function oM(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const Wl=ie("desktop-mode/layout",()=>({layout:"classic"}));function Ey(e){Wl.state.layout!==e&&(Wl.state.layout=e,Wl.notify())}class _y{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 sM extends _y{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const vs=new Map,Pl=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.");vs.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),C("os.files.type-registered",e.type,e),ky()}function iM(e){vs.delete(e)&&(C("os.files.type-unregistered",e),ky())}function rM(e){const t=vs.get(e);return t||null}function Sy(){const e=Array.from(vs.values()).slice(),t=X("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 Mt(e){const t=vs.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new sM(e,e.type)}function aM(e){return Pl.add(e),()=>Pl.delete(e)}function ky(){for(const e of Pl)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const hr=new Map,$l=new Set;let Ul={};function Iy(e){Ul={...e},Gl()}function Bl(){return{...Ul}}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.");hr.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}),C("os.files.opener-registered",e.id,e),Gl()}function cM(e){hr.delete(e)&&(C("os.files.opener-unregistered",e),Gl())}function lM(e){return hr.get(e)??null}function Ay(){const e=Array.from(hr.values()).slice(),t=X("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 Fl(e,t){return Ay().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function Hl(e,t){const n=Fl(e,t);if(n.length===0)return null;const o=Ul[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]),X("os.files.resolve-opener",s,e)??null}function Cy(e){return $l.add(e),()=>$l.delete(e)}function Gl(){for(const e of $l)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let Wt=null;function dM(e){Wt=e}function zl(e){return!Wt||!e.url?!1:Wt.openUrl({id:Wt.deriveWindowId(e.url),...e})}async function bs(e,t){if(!Wt)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=Hl(e.type(),e);if(!n)return C("os.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;C("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):Wt.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),l=Wt.openUrl({id:i,url:s,title:r,icon:a});return C("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=Wt.openNativeWindow(o.windowId,s);return C("os.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),C("os.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return C("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 uM="dashicons-portfolio";function fM(){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})}function pM(){const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]%16+64,e[8]=e[8]%64+128;const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}class ro extends Error{constructor(t,n){super(t),this.retryable=n}}async function hM(e,t,n){const o=new AbortController,s=window.setTimeout(()=>o.abort(),15e3);try{const i=await Le(rt(e.restRoot,t),{method:n?"POST":"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:n?JSON.stringify(n):void 0,signal:o.signal,cache:"no-store"},{source:"desktop-mode/agents",silent:!n}),r=await i.json().catch(()=>null);if(!i.ok)throw new ro(r?.message||`HTTP ${i.status}`,i.status>=500&&!r?.code||i.status===408);if(!r||!r.jobId&&typeof r.text!="string")throw new ro(b("The job status could not be read.","desktop-mode"),!0);return r}finally{window.clearTimeout(s)}}function mM(e){return new Promise(t=>window.setTimeout(t,e))}async function gM(e,t,n,o,s=()=>{}){const i=`desktop-mode/v1/agents/${e}`,r=Date.now()+2*60*60*1e3;let a=!1,l=2e3;for(;Date.now()<r;){try{const c=await hM(n,a?`${i}/jobs/${o}`:`${i}/invoke`,a?void 0:{...t,async:!0,requestId:o});if(!("jobId"in c))return c;if(c.jobId!==o)throw new ro(b("The server returned a different job.","desktop-mode"),!1);if(a=!0,c.status==="completed"&&c.result)return c.result;if(c.status==="failed")throw new ro(c.error?.message||b("The agent job failed.","desktop-mode"),!1);if(c.status!=="queued"&&c.status!=="running")throw new ro(b("The server returned an invalid job state.","desktop-mode"),!1);s(c.status),l=Math.min(1e4,Math.max(l*1.25,(c.pollAfter||3)*1e3))}catch(c){if(c instanceof ro&&!c.retryable)throw c;s("reconnecting"),l=Math.min(l*2,3e4)}await mM(document.hidden?Math.max(l,15e3):l)}throw new Error(b("The background job has not returned a result. Some work may already have been applied. Check the site before submitting again.","desktop-mode"))}const Fe=ie("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function Ly(e){Fe.state.activeAgent=e,Fe.state.transcripts[e.id]||(Fe.state.transcripts[e.id]=[]),Fe.state.conversationIds||(Fe.state.conversationIds={},Fe.state.conversationsRev=0),Fe.notify()}const Ty="desktop-mode/v1/agents/conversations";async function Ny(e,t,n={}){const o=await Le(rt(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 wM(e){return e.filter(t=>!t.pending)}async function yM(e,t){const n=Fe.state,o=wM(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await Ny(t,`${Ty}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await Ny(t,Ty,{method:"POST",body:JSON.stringify({agentId:e.id,messages:o})});n.conversationIds[e.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,Fe.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const Oy={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function Dy(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function Ry(e){if(e.type==="shortcut"){const t=e.data;let n=Oy[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=Dy(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=Oy[String(n.type??"")],s=Dy(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function vM(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function bM(e){return ae(b('The user dropped the %1$s "%2$s" (id %3$s) onto you. Handle it according to your instructions, using your tools as needed.',"desktop-mode"),e.kind,e.title,String(e.id))}function EM(e){return{kind:e.kind,id:e.id,title:e.title}}function xy(e,t="agents"){Ly(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function _M(e,t,n,o,s){Ly(e);const i=Fe.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:b("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(a),Fe.notify();try{const l=await gM(e.id,{message:t,source:o,history:r},n,pM(),c=>{const d={queued:b("Queued — waiting for a WordPress worker…","desktop-mode"),reconnecting:b("Reconnecting to the background job…","desktop-mode"),running:b("Working in the background…","desktop-mode")};a.text=d[c],Fe.notify()});a.text=l.text||b("The agent finished without a text answer.","desktop-mode"),a.toolCalls=l.toolCalls,Array.isArray(l.callToActions)&&l.callToActions.length>0&&(a.callToActions=l.callToActions)}catch(l){a.role="error",a.text=l instanceof Error?l.message:String(l)}a.pending=!1,Fe.notify(),yM(e,n)}function SM(e,t,n){return xy(e,"agents-drop"),_M(e,bM(t),n,"drag",EM(t))}let jl=null;function My(e){jl=e}function Es(){if(!jl)throw new Error("[openstation] files REST client called before installRestDeps().");return jl}function kM(){return Es()}class Vl 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 pe(e,t){const{baseUrl:n,nonce:o}=Es(),s=rt(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 Le(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 Vl(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 Re(e=0){return pe(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function _s(e){return pe("/placements",{method:"POST",body:JSON.stringify(e)})}function ao(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),pe(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Kl(e){return pe(`/placements/${e}`,{method:"DELETE"})}async function mr(e,t){const{baseUrl:n,nonce:o}=Es(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Le(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 Wy(){return pe("/folders",{method:"GET"})}function ql(e){return pe("/folders",{method:"POST",body:JSON.stringify(e)})}function Py(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),pe(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Yl(e){return pe(`/folders/${e}`,{method:"DELETE"})}function $y(e){return pe("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function IM(e){return pe(`/folders/${e}/shares`,{method:"GET"})}function AM(e,t){return pe(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function CM(e,t,n){return pe(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function LM(e,t){return pe(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function TM(e,t){return pe(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function NM(e,t){return pe(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function Uy(e){return pe(`/folders/${e}/leave`,{method:"POST"})}function OM(){return pe("/folder-sharing-tables/purge",{method:"POST"})}function DM(e){return pe(`/uploads/${e}/shares`,{method:"GET"})}function RM(e,t){return pe(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function xM(e,t){return pe(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function MM(e,t){return pe(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function WM(e,t){return pe(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function By(e){return pe(`/uploads/${e}/leave`,{method:"POST"})}function PM(e,t){return pe(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function gr(e){return pe(`/uploads/${e}/media`,{method:"POST"})}function Fy(e,t){return pe(`/uploads/${e}/post`,{method:"POST",body:JSON.stringify({postType:t})})}function Hy(e,t){return pe(`/posts/${e}/uploads`,{method:"POST",body:JSON.stringify({fileIds:t})})}function $M(e,t){return pe("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function dn(e){const{baseUrl:t,nonce:n}=Es(),o=rt(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function Gy(e){const{baseUrl:t,nonce:n}=Es(),o=rt(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const UM=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:Vl,acceptFileShare:MM,acceptShare:TM,addUploadToMediaLibrary:gr,attachUploadsToPost:Hy,createFolder:ql,createPlacement:_s,deleteFolder:Yl,deletePlacement:Kl,denyFileShare:WM,denyShare:NM,ensureUploadPath:$M,getFilesRestDeps:kM,getFolderZipUrl:Gy,getUploadDownloadUrl:dn,installRestDeps:My,inviteFileShare:RM,inviteShare:AM,leaveFileShare:By,leaveShare:Uy,listFileShares:DM,listFolders:Wy,listPlacements:Re,listShares:IM,purgeFolderSharingTables:OM,renameUpload:PM,restoreTrashedItem:mr,revokeFileShare:xM,revokeShare:LM,saveAssociations:$y,startPostFromUpload:Fy,updateFolder:Py,updatePlacement:ao,updateShareCapability:CM},Symbol.toStringTag,{value:"Module"})),BM="desktop-mode/files";function nt(){return ie(BM,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function co(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function Pt(e,t){const n=nt(),o=new Map(n.state.placementsByFolder);o.set(e,t.slice());const s=new Set(n.state.hydratedFolders);s.add(e),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),co({kind:"placements-set",folderId:e})}function Xl(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=nt(),o=new Map(n.state.placementsByFolder);for(const[a,l]of o)if(l.findIndex(d=>d&&d.id===e.id)>=0&&a!==e.parentId){const d=l.filter(Boolean),u=d.findIndex(f=>f.id===e.id);u>=0&&d.splice(u,1),o.set(a,d)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),co({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function Ss(e,t="local"){const n=nt(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(l=>l&&l.id===e)>=0){const l=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,l),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),co({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function Zl(e){const t=nt(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),co({kind:"folders-set"})}function Jl(e,t="local"){const n=nt(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),co({kind:"folder-upserted",folderRowId:e.id,source:t})}function Ql(e,t="local"){const n=nt(),o=new Map(n.state.folders);o.delete(e);const s=new Map(n.state.placementsByFolder);s.delete(e),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),co({kind:"folder-removed",folderRowId:e,source:t})}function ed(e){return nt().subscribe(e)}function $t(){return nt().getState()}function zy(e){const t=$t(),n=t.placementsByFolder.get(e.parentId)?.find(o=>o&&o.id===e.id);if(n)return n;for(const o of t.placementsByFolder.values()){const s=o.find(i=>i&&i.id===e.id);if(s)return s}return e}const te={getState:$t,subscribe:ed,setFolderPlacements:Pt,upsertPlacement:Xl,upsertFolder:Jl,removePlacement:Ss,removeFolder:Ql,currentPlacement:zy},FM=Ce`:host{display:inline-block}`,HM=Ce`: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 ) )}`,zs=class zs extends en{render(){return $n`<span class="banner" part="banner"><slot></slot></span>`}};zs.props=["placement","tone"],zs.styles=[HM],zs.help=void 0;let td=zs;Fo("os-ribbon",td);const ce="os-file-tile",jy={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function GM(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function zM(){return window.wp?.os?.dragManager??null}const jM=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],go=class go extends en{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(`${ce}--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 $n``}_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=[ce,`${ce}--folder`,`${ce}--missing`,`${ce}--access-gated`,`${ce}--selected`];for(const E of f)this.classList.remove(E);this.classList.add(ce),r==="folder"&&this.classList.add(`${ce}--folder`),d&&this.classList.add(`${ce}--missing`),u&&this.classList.add(`${ce}--access-gated`),l&&this.classList.add(`${ce}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",c?"option":"listitem"),c?this.setAttribute("aria-selected",l?"true":"false"):this.removeAttribute("aria-selected"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const g=[`${ce}__visual`,`${ce}__label`,`${ce}__lock`];for(const E of g)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=`${ce}__visual`,i){const E=document.createElement("img");E.src=i,E.alt="",E.loading="lazy",E.decoding="async",E.className=`${ce}__preview`,E.draggable=!1,h.appendChild(E)}else if(s){const E=Yn(s,{title:o,className:`${ce}__icon`});h.appendChild(E)}this.appendChild(h);const m=document.createElement("span");if(m.className=`${ce}__label`,m.textContent=o,this.appendChild(m),u){const E=document.createElement("span");E.className=`${ce}__lock dashicons dashicons-lock`,E.setAttribute("aria-hidden","true"),this.appendChild(E)}if(a&&a!=="publish"&&jy[a]&&GM()){const E=document.createElement("os-ribbon");E.setAttribute("placement","top-end"),E.setAttribute("tone",VM(a)),E.textContent=jy[a],this.appendChild(E)}uE(this),C("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=zM();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)}};go.shadow=!1,go.props=jM,go.styles=[FM],go.help=void 0;let nd=go;function VM(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}Fo("os-tile",nd);function KM(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=X("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 qM(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(`${ce}--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:Mt(e.file).title()}function YM(e,t){const n=Mt(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:$g(e.file.ref)||i||si(R_(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 XM(e,t){const n=KM(YM(e,t)),o=X("os.files.tile-class",ce,e);o&&o!==ce&&(n.className=o);const s=X("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=zy(e),a=Mt(r.file);if(r.accessGated){de({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}bs(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),C("os.files.tile-rendered",{tile:n,placement:e}),n}function un(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const ZM=ie("desktop-mode/tile-payload-handlers",()=>({handlers:new Map}));function ks(){return ZM.state.handlers}function Is(e,t){const n=ks().get(e);return n?n.push(t):ks().set(e,[t]),()=>{const o=ks().get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&ks().delete(e)}}function od(e,t){const n=ks().get(e);if(n)return n.find(o=>o.appliesTo(t))}function JM(e,t){return od(e,t)?.acceptLabel}function QM(e,t){const n=od(e.type,t);return n?n.accept(e.data,t):!1}function e1(e,t,n){const o=od(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function t1(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&&DR(e,{actions:o,scope:"files.tile",dataset:{placementId:String(n.placementIds[0]??""),placementIds:n.placementIds.join(",")},onOpened:s=>{C("os.files.tile-menu.opened",{placementId:n.placementIds[0],placementIds:n.placementIds.slice(),items:s})},onClosed:()=>{C("os.files.tile-menu.closed",{})}})}const n1="my-wordpress",lo=ie("desktop-mode/my-wordpress/open-target",()=>({kind:null,entityId:"",id:0,title:"",requestedAt:0}));function o1(e){lo.state.kind=e.kind,lo.state.entityId=e.entityId,lo.state.id=e.id,lo.state.title=e.title,lo.state.requestedAt=Date.now(),lo.notify()}function s1(e){const t=window.wp?.os?.openWindow;t?.(n1,{source:e})}function Ky(e){const t=Number(e.postId);!Number.isFinite(t)||t<=0||(o1({kind:"detail",entityId:e.entityId||"posts",id:t,title:e.postTitle??""}),s1("my-wordpress/open-detail"))}function i1(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function sd(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function id(e){const t=()=>{const n=e.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};t()||queueMicrotask(()=>void t())}const We="os-create-folder-dialog";let As=null;function rd(){As&&(As.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),As.remove(),As=null,C("os.files.create-folder.closed",{}))}function ad(e){if(rd(),X("os.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${We}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=We,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${We}-title`);const i=document.createElement("h2");i.id=`${We}-title`,i.className=`${We}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${We}__field`,r.id=`${We}-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=`${We}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const l=document.createElement("div");l.className=`${We}__actions`;const c=document.createElement("os-button");c.className=`${We}__btn ${We}__btn--secondary`,c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className=`${We}__btn ${We}__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),As=o,id(r),C("os.files.create-folder.opened",{});const u=m=>{sd(r,m),sd(c,m),sd(d,m),s.classList.toggle(`${We}--busy`,m)},f=m=>{a.textContent=m,a.hidden=!1},p=()=>{rd(),e.onCancel?.()},g=async()=>{const m=i1(r).trim();if(!m){f("Please enter a name."),id(r);return}a.hidden=!0,u(!0);try{await e.onSubmit(m),rd()}catch(E){u(!1),f(E instanceof Error?E.message:"Could not create the folder."),id(r)}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void g()),o.addEventListener("click",m=>{m.target===o&&p()});const h=m=>{m.key==="Escape"?(m.preventDefault(),p()):m.key==="Enter"&&!m.isComposing&&(m.preventDefault(),g())};s.addEventListener("keydown",h),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",h)})}function wr(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function r1(e){return e.id<=0||wr(e)!==null}function qy(e){e.length!==0&&l0(e)}function uo(e,t,n){km(e,t,n,"desktop-files")}function yr(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 cd(e,t){const n=window.wp?.os;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function Yy(e){const t=sn(Zn(e));if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Item",i=e.file?.type==="shortcut"?"shortcut":"placement";te.removePlacement(n);try{await Kl(n),uo(i,"trashed",[n]),t.finish(!0),cd(`"${s}" moved to Trash`,async()=>{const r=sn(Zn(e),"out");try{await mr(n,"placement");const a=await Re(o);te.setFolderPlacements(o,a.placements),uo(i,"untrashed",[n]),r?.finish(!0)}catch(a){r?.finish(!1),console.error("[openstation] restore failed:",a)}})}catch(r){console.error("[openstation] deletePlacement failed:",r),t.finish(!1),te.upsertPlacement(e),yr(r),Re(o).then(a=>{te.setFolderPlacements(o,a.placements)}).catch(()=>{})}}async function Xy(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=sn(Zn(e));if(!n)return;const o=e.id,s=e.parentId,i=e.file?.title??"Folder";te.removePlacement(o);const r=te.getState().folders.get(t);te.removeFolder(t);try{await Yl(t),uo("folder","trashed",[t]),n.finish(!0),cd(`"${i}" moved to Trash`,async()=>{const a=sn(Zn(e),"out");try{await mr(t,"folder");const l=await Re(s);te.setFolderPlacements(s,l.placements),uo("folder","untrashed",[t]),a?.finish(!0)}catch(l){a?.finish(!1),console.error("[openstation] restore folder failed:",l)}})}catch(a){console.error("[openstation] deleteFolder failed:",a),r&&te.upsertFolder(r),n.finish(!1),te.upsertPlacement(e),yr(a),Re(s).then(l=>{te.setFolderPlacements(s,l.placements)}).catch(()=>{})}}async function Zy(e){if(e.length===0)return;if(e.length===1)return a1(e[0]);const t=new Map(e.map(d=>[d.id,sn(Zn(d))]));e=e.filter(d=>t.get(d.id));const n=new Map(te.getState().folders),o=new Set;for(const d of e)if(o.add(d.parentId),te.removePlacement(d.id),d.file?.type==="folder"){const u=parseInt(d.file.ref,10);u&&te.removeFolder(u)}const s=async()=>{for(const d of o)try{const u=await Re(d);te.setFolderPlacements(d,u.placements)}catch(u){console.error("[openstation] files: re-hydrate failed:",u)}},i=await Promise.allSettled(e.map(async d=>{if(d.file?.type==="folder"){const u=parseInt(d.file.ref,10);if(!u)throw new Error("folder placement without a folder id");return await Yl(u),{id:u,kind:"folder",restoreId:u,restoreKind:"folder"}}return await Kl(d.id),{id:d.id,kind:d.file?.type==="shortcut"?"shortcut":"placement",restoreId:d.id,restoreKind:"placement"}}));i.forEach((d,u)=>{if(d.status==="rejected"){const f=e[u];te.upsertPlacement(f);const p=f.file.type==="folder"&&n.get(Number(f.file.ref));p&&te.upsertFolder(p),t.get(e[u].id)?.finish(!1)}});const r=[];let a=0;for(const d of i)d.status==="fulfilled"?r.push(d.value):(a+=1,console.error("[openstation] trash (bulk) failed for one item:",d.reason));if(a>0&&s(),r.length===0){yr(i.find(d=>d.status==="rejected")?.reason);return}for(const d of["placement","shortcut","folder"]){const u=r.filter(f=>f.kind===d).map(f=>f.id);u.length>0&&uo(d,"trashed",u)}i.forEach((d,u)=>{d.status==="fulfilled"&&t.get(e[u].id)?.finish(!0)});const l=r.length===1?"item":"items",c=a>0?`${r.length} ${l} moved to Trash · ${a} could not be moved`:`${r.length} ${l} moved to Trash`;cd(c,async()=>{const d=r.map(g=>{const h=e.find(m=>m.file.type==="folder"?Number(m.file.ref)===g.id&&g.kind==="folder":m.id===g.id&&g.kind!=="folder");return h?sn(Zn(h),"out"):null}),u=await Promise.allSettled(r.map(g=>mr(g.restoreId,g.restoreKind)));await s();const f=r.filter((g,h)=>u[h].status==="fulfilled"),p=r.length-f.length;for(const g of u)g.status==="rejected"&&console.error("[openstation] restore (bulk) failed for one item:",g.reason);for(const g of["placement","shortcut","folder"]){const h=f.filter(m=>m.kind===g).map(m=>m.id);h.length>0&&uo(g,"untrashed",h)}u.forEach((g,h)=>{d[h]?.finish(g.status==="fulfilled")}),p>0&&yr(new Error(`${p} of ${r.length} items could not be restored.`))})}function a1(e){return e.file?.type==="folder"?Xy(e):Yy(e)}const c1=5,Jy=e=>Zy(e);async function l1(e){if(!(e.length>c1&&!await Yt({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await bs(Mt(t.file))}function d1(e){const t=parseInt(e.file.ref,10);t&&ad({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:e.file.title,onSubmit:async n=>{const o=n.trim();if(!o||o===e.file.title)return;const s=e.file.title,i={...e,file:{...e.file,title:o}};te.upsertPlacement(i);try{const r=te.getState().folders.get(t)?.updatedAtMs??0,a=await Py(t,{name:o},r);te.upsertFolder(a);const l=await Re(e.parentId);te.setFolderPlacements(e.parentId,l.placements)}catch(r){console.error("[openstation] rename folder failed:",r),te.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function u1(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=typeof e.file.postType=="string"?e.file.postType:"post";Ky({entityId:n==="page"?"pages":"posts",postId:t,postTitle:e.file.title||`#${t}`})}function f1(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>l1(i),onClick:()=>{bs(Mt(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>u1(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>d1(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:Jy,onClick:()=>Xy(e)});else{const i=wr(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=>{qy(l.map(c=>wr(c)??c.file.ref).filter(c=>!!c))},onClick:()=>qy([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:Jy,onClick:()=>Yy(e)})}const o=X("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const Ut=16,Qy=88,ev=104,p1=20,h1=16,ld=Qy+p1,dd=ev+h1;function Cs(e,t){const n=Math.max(0,Math.round((e-Ut)/ld)),o=Math.max(0,Math.round((t-Ut)/dd));return fn(n,o)}function fn(e,t){return{col:e,row:t,x:Ut+e*ld,y:Ut+t*dd}}const m1=5,g1=4;function Ls(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 w1(e){const t=Ls(e).height;return t<=0?m1:Math.max(1,Math.floor((t-Ut)/dd))}function y1(e){const t=Ls(e).width;return t<=0?g1:Math.max(1,Math.floor((t-Ut)/ld))}const tv=999;function vr(e,t="column",n){if(t==="row"){const s=y1(n);for(let i=0;i<tv;i++)for(let r=0;r<s;r++)if(!e.has(Ae(r,i)))return fn(r,i);return fn(0,0)}const o=w1(n);for(let s=0;s<tv;s++)for(let i=0;i<o;i++)if(!e.has(Ae(s,i)))return fn(s,i);return fn(0,0)}function nv(e,t,n="column",o){const s=new Set(t),i=[];for(let r=0;r<e;r++){const a=vr(s,n,o);s.add(Ae(a.col,a.row)),i.push(a)}return i}function Bt(e,t,n,o,s="column"){const i=Cs(e,t);return n.has(Ae(i.col,i.row))?vr(n,s,o):i}function ov(e,t){const n=new Set;for(const o of e){const s=Cs(o.x,o.y);n.add(Ae(s.col,s.row))}return n}function Ae(e,t){return`${e},${t}`}function v1(e){const t=String(e),{placementsByFolder:n}=nt().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 b1(e,t){const n=v1(e);if(n)return Mt(n);const o=nt().state.folders.get(e);return Mt({type:"folder",ref:String(e),title:o?.name||t||"Folder",icon:uM,previewUrl:"",exists:!0})}function sv(e){return e instanceof Vl}function E1(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 iv(e){const t=E1(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{bs(b1(n,e.detail.current.parentName))}}),de({message:t,action:o,duration:7e3})}const _1=ie("desktop-mode/canvas-payload-handlers",()=>({handlers:new Map}));function rv(){return _1.state.handlers}function S1(e,t){const n=rv().get(e.type);return n?n.accept(e.data,t):!1}function k1(e,t,n){const o=rv().get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function pn(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function br(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}const av="application/x-wp-media-attachment",cv="data-files-drop-active";function lv(){const e=window.wp?.os?.dragBridge;if(!e)return null;try{return e.getPayload()}catch{return null}}function dv(e){if(!e)return null;switch(e.kind){case"attachment":case"post":case"user":return typeof e.id!="number"?null:{kind:e.kind,ref:String(e.id),title:e.title};default:return null}}function I1(e){if(!e)return null;let t="";try{t=e.getData(av)}catch{return null}if(!t)return null;try{const n=JSON.parse(t),o=typeof n.id=="number"?n.id:Number(n.id);return!Number.isFinite(o)||o<=0?null:{kind:"attachment",ref:String(o),title:typeof n.title=="string"?n.title:void 0}}catch{return null}}function uv(e){const t=e.dataTransfer?.types,n=t?Array.from(t):[];return n.includes("Files")?!1:n.includes(av)?!0:dv(lv())!==null}function fv(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 pv(e,t){if(!(e instanceof Element))return null;const n=e.closest(`.${ce}`);return!(n instanceof HTMLElement)||!t.contains(n)?null:n.dataset.fileType==="folder"?n:null}function A1(e){const{host:t,container:n,folderId:o}=e;let s=null;const i=()=>{t.removeAttribute(cv),s&&(s.classList.remove(`${ce}--drop-target`),s=null)},r=c=>{if(!uv(c))return;if(!fv(c.target,t,n)){i();return}c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),t.setAttribute(cv,"");const d=pv(c.target,n);d!==s&&(s?.classList.remove(`${ce}--drop-target`),d?.classList.add(`${ce}--drop-target`),s=d)},a=c=>{const d=c.relatedTarget;d instanceof Node&&t.contains(d)||i()},l=c=>{if(!uv(c))return;if(!fv(c.target,t,n)){i();return}i(),c.preventDefault(),c.stopPropagation();const d=dv(lv())??I1(c.dataTransfer);if(!d)return;const u=pv(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 C1(){return window.openStationConfig?.desktopStorage?.canAddToMedia===!0}function L1(e){if(e.type!=="upload"||e.isMedia!==!0||!C1())return;const t=parseInt(String(e.ref??""),10);if(!(!Number.isFinite(t)||t<=0))return{kind:"upload",fileId:t,title:String(e.title??""),mime:String(e.mime??""),thumbnailUrl:e.previewUrl?String(e.previewUrl):void 0}}function T1(e){return(e instanceof Error?e.message:String(e)).replace(/^\[openstation\] files REST \d+: \S+ /,"")}async function N1(e){if(e.kind!=="upload")return null;try{const t=await gr(e.fileId);return{kind:"attachment",id:t.attachmentId,url:t.url,title:t.title||e.title,alt:"",mime:e.mime,thumbnailUrl:e.thumbnailUrl}}catch(t){return de({message:`Could not add to the Media Library: ${T1(t)}`}),null}}function O1(){return rD("upload",N1)}function D1(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o};if(t.type==="upload")return L1(t)}function Ts(){return window.wp?.os?.dragManager??null}const R1="os-files-layer";function Er(e){return e===0?"column":"row"}function x1(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function hv(e,t){return t!==0||!e?e:{get width(){return me(e).width},get height(){return me(e).height}}}function mv(e,t=0){const n=Er(t),o=hv(e,t),s=document.createElement("div");s.className=R1,s.setAttribute("role","list"),s.dataset.folderId=String(t),e.appendChild(s);let i="";const r=O=>{const T=te.getState().placementsByFolder.get(t)??[],W=new Map;for(const v of T)v&&W.set(String(v.id),v);return O.map(v=>W.get(v)).filter(v=>!!v)},a=new Set,l=new Set,c=CR(s,{itemSelector:`.${ce}`,background:e,surface:"files",scope:String(t),keyOf:O=>O.dataset.placementId??null,onChange:O=>{const T=r(O),W=T.length===1?T[0]:null;for(const v of a)try{v(W)}catch(I){console.error("[openstation] files: selection listener threw:",I)}for(const v of l)try{v(T)}catch(I){console.error("[openstation] files: selection listener threw:",I)}}}),d=()=>r(c.keys()),u=O=>{const T=new Map,W=new Set;let v=0;for(const N of O){if(!Pe(N))continue;const D=fn(0,v);T.set(N.id,{x:D.x,y:D.y}),W.add(Ae(D.col,D.row)),v+=1}const I=new Map;for(const N of O){if(T.has(N.id))continue;const D=Cs(N.x,N.y),k=Ae(D.col,D.row);if(!W.has(k)){W.add(k);continue}const U=Bt(N.x,N.y,W,o,n);W.add(Ae(U.col,U.row)),I.set(N.id,{x:U.x,y:U.y})}return{pinnedSlots:T,displaced:I}},f=(O,T,W,v)=>{const I=W.get(T.id),N=v.get(T.id);I?un(O,I.x,I.y):N?un(O,N.x,N.y):un(O,T.x,T.y)},p=(O,T,W)=>{const v=XM(O,t),I=T.get(O.id);if(I){if(un(v,I.x,I.y),v.classList.add(`${ce}--pinned`),bv(v,O,c,d),gv(O)){const D=Ts();D&&S.set(O.id,vv(D,v,O))}return v}const N=W.get(O.id);if(N&&un(v,N.x,N.y),B1(v,O,t,c,d),bv(v,O,c,d),O.file.type==="folder"){const D=parseInt(O.file.ref,10);if(D>0){const k=Ts();if(k){const U=U1(k,v,D);E.set(O.id,U)}}}else if(gv(O)){const D=Ts();D&&S.set(O.id,vv(D,v,O))}return v},g=O=>{const T=new Map;for(const N of s.querySelectorAll("[data-placement-id]")){const D=N.dataset.placementId??"",k=parseInt(D,10);if(D===""||Number.isNaN(k)&&D!=="-0")return!1;T.set(k,N)}const W=new Set;for(const N of O)W.add(N.id);for(const N of O){const D=T.get(N.id);if(!D)continue;if(D.dataset.fileType!==N.file.type||D.dataset.fileRef!==N.file.ref||D.classList.contains(`${ce}--pinned`)!==Pe(N))return!1}for(const[N,D]of T){if(W.has(N))continue;const k=E.get(N);if(k){try{k()}catch{}E.delete(N)}const U=S.get(N);if(U){try{U()}catch{}S.delete(N)}D.remove()}const{pinnedSlots:v,displaced:I}=u(O);for(const N of O){const D=T.get(N.id);if(D){f(D,N,v,I),yv(D,N);continue}s.appendChild(p(N,v,I))}return c.refresh(),C("os.files.grid-rendered",{folderId:t,count:O.length}),!0},h=O=>{const W=(O.placementsByFolder.get(t)??[]).slice().sort((D,k)=>{const U=Pe(D)?0:1,G=Pe(k)?0:1;return U-G}),v=M1(W);if(v===i||(i=v,$1(W,s,o,n))||g(W))return;s.replaceChildren();for(const[,D]of E)try{D()}catch{}E.clear();for(const[,D]of S)try{D()}catch{}S.clear();const{pinnedSlots:I,displaced:N}=u(W);for(const D of W)s.appendChild(p(D,I,N));c.refresh(),C("os.files.grid-rendered",{folderId:t,count:W.length})},m=[],E=new Map,S=new Map;let R=null,$=null;const _=O=>{if(R||O.payload.type!=="desktop-file")return;const T=document.createElement("div");T.className="os-files-drop-preview",T.setAttribute("aria-hidden","true"),s.appendChild(T),R=T;const W=O.payload.ghost,v=W?.offsetX??0,I=W?.offsetY??0,D=O.payload.data?.placement?.id,k=(le,re)=>{const ge=s.getBoundingClientRect(),q=Math.max(0,le-ge.left-v),ne=Math.max(0,re-ge.top-I),be=te.getState().placementsByFolder.get(t)??[],bn=Sr(be,D),xe=Bt(q,ne,bn,o,n);T.style.transform=`translate3d(${xe.x}px, ${xe.y}px, 0)`},U=O.payload.source.getBoundingClientRect();k(U.left+v,U.top+I);const G=le=>{k(le.clientX,le.clientY)};document.addEventListener("pointermove",G),$=G},M=()=>{$&&(document.removeEventListener("pointermove",$),$=null),R&&(R.remove(),R=null)},P={id:`os-files-canvas-${t}`,element:e,accept:O=>{if(O.type!=="desktop-file"&&O.type!=="shortcut")return S1(O,{folderId:t,host:e});if(t>0&&O.type==="desktop-file"){const T=O.data;for(const W of pn(T)){if(W.file?.type!=="folder")continue;const v=parseInt(W.file.ref,10);if(!Number.isNaN(v)&&wv(v,t))return!1}}return!0},onEnter:O=>{e.setAttribute("data-files-drop-active",""),(O.payload.type==="desktop-file"||O.payload.type==="shortcut")&&_(O)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),M()},onDrop:(O,T)=>{if(e.removeAttribute("data-files-drop-active"),M(),O.payload.type!=="desktop-file"&&O.payload.type!=="shortcut"){k1(O,T,{folderId:t,host:e});return}const W=s.getBoundingClientRect(),v=O.payload.ghost,I=v?.offsetX??0,N=v?.offsetY??0,D=Math.max(0,T.clientX-W.left-I),k=Math.max(0,T.clientY-W.top-N),U=te.getState().placementsByFolder.get(t)??[];if(O.payload.type==="desktop-file"){const G=O.payload.data,le=pn(G),re=new Set(le.map(ne=>ne.id)),ge=Sr(U,re),q=Bt(D,k,ge,o,n);ge.add(Ae(q.col,q.row));for(const ne of le){let be=q;if(ne.id!==G.placement.id){const xe=ne.x-G.placement.x,Hr=ne.y-G.placement.y;be=Bt(Math.max(0,q.x+xe),Math.max(0,q.y+Hr),ge,o,n),ge.add(Ae(be.col,be.row))}const bn={...ne,x:be.x,y:be.y,parentId:t};if(te.upsertPlacement(bn),C("os.files.tile-manually-placed",{folderId:t,placementId:ne.id}),_r(ne)){const xe=wr(ne);xe&&P1(xe,be.x,be.y);continue}ao(ne.id,{x:be.x,y:be.y,parentId:t},ne.updatedAtMs).then(xe=>{te.upsertPlacement(xe,"remote")}).catch(xe=>{sv(xe)?iv(xe):console.error("[openstation] files: drag persist failed",xe),te.upsertPlacement(ne)})}return}if(O.payload.type==="shortcut"){const G=O.payload.data;ud(br(G),t,e)}}},B=Ts();if(B&&m.push(B.registerDropTarget(P)),m.push(A1({host:e,container:s,folderId:t,fileEntities:(O,T)=>{ud(O,T,T===t?e:null)}})),!te.getState().hydratedFolders.has(t)){const O=x1(t);O&&te.setFolderPlacements(t,O)}h(te.getState()),queueMicrotask(()=>j());const F=te.subscribe(O=>{h(O),j()});let K=()=>{};const Z=new Promise(O=>{K=O});te.getState().hydratedFolders.has(t)?queueMicrotask(K):Re(t).then(O=>{te.setFolderPlacements(t,O.placements)}).catch(O=>{console.error("[openstation] files: failed to hydrate folder",t,O)}).finally(()=>{K()});const Y=O=>{const T=new Set;for(let W=0;W<O;W+=1)T.add(Ae(0,W));return T},L=(O,T)=>{const W=O.slice();switch(T){case"name-asc":W.sort((v,I)=>v.file.title.localeCompare(I.file.title));break;case"name-desc":W.sort((v,I)=>I.file.title.localeCompare(v.file.title));break;case"date-asc":W.sort((v,I)=>v.updatedAtMs-I.updatedAtMs);break;case"date-desc":W.sort((v,I)=>I.updatedAtMs-v.updatedAtMs);break}return W},x=O=>{const T=te.getState().placementsByFolder.get(t);if(!T||T.length===0)return;const W=T.filter(D=>Pe(D)),v=T.filter(D=>!Pe(D)),I=L(v,O),N=nv(I.length,Y(W.length),n,o);I.forEach((D,k)=>{const{x:U,y:G}=N[k],le={...D,x:U,y:G,sortOrder:k};te.upsertPlacement(le),!_r(D)&&ao(D.id,{x:U,y:G,sortOrder:k}).catch(re=>{console.error("[openstation] files: sort persist failed",re)})})},j=()=>{const O=te.getState().placementsByFolder.get(t);if(!O||O.length===0)return;const T=Ls(o),W=T.width>0?T.width:1/0,v=T.height>0?T.height:1/0;if(!O.some(U=>U.x+Qy>W||U.y+ev>v))return;const N=O.filter(U=>Pe(U)),D=O.filter(U=>!Pe(U)),k=nv(D.length,Y(N.length),n,o);D.forEach((U,G)=>{const le=s.querySelector(`[data-placement-id="${U.id}"]`);le&&un(le,k[G].x,k[G].y)})};let V=Ls(o),J=null;return typeof ResizeObserver<"u"&&(J=new ResizeObserver(()=>{const O=Ls(o);O.width===V.width&&O.height===V.height||(V=O,j())}),J.observe(e)),{host:e,folderId:t,onSelectionChange(O){return a.add(O),()=>{a.delete(O)}},onSelectionChanged(O){return l.add(O),()=>{l.delete(O)}},getSelection:d,selectAll:()=>c.model.selectAll(),clearSelection:()=>c.model.clear(),sort:x,reflow:j,hydrated:Z,dispose(){F(),J?.disconnect(),J=null;for(const O of m)try{O()}catch{}m.length=0;for(const O of E.values())try{O()}catch{}E.clear();for(const O of S.values())try{O()}catch{}S.clear(),c.destroy(),a.clear(),l.clear(),s.remove()}}}function M1(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}:${Pe(n)?1:0}`);return t.join("|")}function Pe(e){return!!e.file.pinned}function _r(e){return r1(e)}const W1="desktop-mode-recycle-bin";function gv(e){return!(e.file?.type==="folder"||e.file?.ref===W1)}function Sr(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,a)=>{const l=Pe(r)?0:1,c=Pe(a)?0:1;return l-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(Pe(r))s.add(Ae(0,i)),i+=1;else{const a=Cs(r.x,r.y);s.add(Ae(a.col,a.row))}return s}function ud(e,t,n){const o=te.getState().placementsByFolder.get(t)??[],s=Sr(o),i=Er(t);for(const r of e){const a=vr(s,i,hv(n,t));s.add(Ae(a.col,a.row)),_s({parentId:t,type:r.kind,ref:r.ref,x:a.x,y:a.y}).then(l=>{te.upsertPlacement(l),C("os.files.shortcut-dropped",{folderId:t,placement:l})}).catch(l=>{console.error("[openstation] shortcut drop failed:",l)})}}function wv(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=te.getState();for(const a of o.placementsByFolder.values())for(const l of a){if(l.file?.type!=="folder")continue;const c=parseInt(l.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,l.parentId)}const s=new Set;let i=t,r=256;for(;i>0&&r-- >0;){if(i===e||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function P1(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 $1(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(`${ce}--pinned`)!==Pe(d))return!1}const r=new Map,a=new Set;let l=0;for(const d of e){if(!Pe(d))continue;const u=fn(0,l);r.set(d.id,{x:u.x,y:u.y}),a.add(Ae(u.col,u.row)),l+=1}const c=new Map;for(const d of e){if(r.has(d.id))continue;const u=Cs(d.x,d.y),f=Ae(u.col,u.row);if(!a.has(f)){a.add(f);continue}const p=Bt(d.x,d.y,a,n,o);a.add(Ae(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};un(u,f.x,f.y),yv(u,d)}return!0}function yv(e,t){const n=Vy(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function vv(e,t,n){const o={placement:n};let s=null;return e.registerDropTarget({id:`os-files-tile-${n.id}-reject`,element:t,get acceptLabel(){return s?JM(s,o):void 0},accept:i=>(s=i.type,QM(i,o)),onEnter:()=>{t.classList.add(`${ce}--drop-target`)},onLeave:()=>{t.classList.remove(`${ce}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${ce}--drop-target`),e1(i,r,o)}})}function U1(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 pn(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||_r(a))return!1;if(a.file.type==="folder"){const l=parseInt(a.file.ref,10);if(!Number.isNaN(l)&&wv(l,n))return!1}}}return!0},onEnter:()=>{t.classList.add(`${ce}--drop-target`)},onLeave:()=>{t.classList.remove(`${ce}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${ce}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a=te.getState().placementsByFolder.get(n)??[],l=Sr(a),c=Er(n);for(const d of pn(r)){const u=vr(l,c);l.add(Ae(u.col,u.row)),te.upsertPlacement({...d,x:u.x,y:u.y,parentId:n}),ao(d.id,{x:u.x,y:u.y,parentId:n},d.updatedAtMs).then(f=>{te.upsertPlacement(f,"remote")}).catch(f=>{sv(f)?iv(f):console.error("[openstation] files: move-into-folder persist failed",f),te.upsertPlacement(d)})}return}if(i.payload.type==="shortcut"){const r=i.payload.data;ud(br(r),n)}}};return e.registerDropTarget(s)}function B1(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=Ts();if(!r)return;const l=te.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||l.x,parseFloat(e.style.top)||l.y;const c=o.model.has(String(l.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===l.id)?d:[l];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(l.id)])};document.addEventListener("os.drag.start",f);const p=()=>{document.removeEventListener("os.drag.start",f),document.removeEventListener("pointerup",p)};document.addEventListener("pointerup",p)}if(u.length>1){const f=[],p=()=>{for(const h of f)h.classList.remove(`${ce}--dragging`);f.length=0,document.removeEventListener("os.drag.start",g),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},g=()=>{for(const h of u){const m=e.parentElement?.querySelector(`[data-placement-id="${h.id}"]`);m&&m!==e&&(m.classList.add(`${ce}--dragging`),f.push(m))}};document.addEventListener("os.drag.start",g),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:e,data:{placement:l,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:D1(l)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?qM(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 bv(e,t,n,o){e.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=te.currentPlacement(t);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),a=r.length>0?r:[i],l=Kw(a,f1);t1({x:s.clientX,y:s.clientY},l,{placementIds:a.map(c=>c.id)})})}function Ev(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 fo="os-folder-status-bar";function F1(e,t,n={}){const o=document.createElement("div");o.className=fo,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const a=$t().placementsByFolder.get(t)??[],l=a.filter(p=>p.file.type==="folder").length,c=a.length-l;let d=0;for(const p of a)if(p.file.type==="upload"){const g=Number(p.file.sizeBytes??0);Number.isFinite(g)&&g>0&&(d+=g)}const u={folderId:t,selectedCount:n.selection?.count()??0,totals:{files:c,folders:l,total:a.length,bytes:d}},f=H1(u);G1(o,f)};s();const i=ed(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function H1(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:Sv(n,"file","files")+(t>0?`, ${Sv(t,"folder","folders")}`:"")+(o>0?` (${Ev(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=X("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function G1(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(_v("start",o)),e.appendChild(_v("end",s))}function _v(e,t){const n=document.createElement("div");n.className=`${fo}__cluster ${fo}__cluster--${e}`;for(const o of t)n.appendChild(z1(o));return n}function z1(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${fo}__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=`${fo}__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=`${fo}__label`,o.textContent=e.label,n.appendChild(o),n}function Sv(e,t,n){return`${e} ${e===1?t:n}`}const kr="os-icon-canvas-menu";let Ns=null,Ir=null,fd=null,Os=null,Ds=null;function j1(e,t){t.openOnBackgroundClick;const n=i=>{V1(i.target)||kv(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(fd===e&&Ns){hn();return}const a=K1(t),l=X("os.icon-canvas.menu",a,t.scope),c=Array.isArray(l)?l:a,d=++o;Ys(()=>d===o,()=>q1(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),hn()}}}function V1(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function kv(e){return e instanceof Element?e.closest(`.${kr}`)!==null:!1}function K1(e){const n=[{id:"sort-by",label:b("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:b("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:b("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:b("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:b("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function Iv(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 q1(e,t,n){if(hn(),e.length===0)return;fd=n;const o=Iv(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(kr),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=Av(s,r);Ar(r)&&a.addEventListener("mouseenter",()=>{Cv(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,l=i.get(a.id);if(l){if(Ar(l)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${l.id}"]`);c&&Cv(l,c);return}hn(),l.onClick?.()}}),document.body.appendChild(s),Ns=s,El(s),queueMicrotask(()=>{Os=r=>{kv(r.target)||hn()},Ds=r=>{r.key==="Escape"&&hn()},document.addEventListener("mousedown",Os),document.addEventListener("keydown",Ds)})}function Av(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",Y1(t.icon)),Ar(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function Cv(e,t){if(Lv(),!Ar(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(kr,`${kr}--flyout`);const o=new Map;for(const s of Iv(e.children??[]))o.set(s.id,s),Av(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),hn(),r.onClick?.())}),document.body.appendChild(n),Ir=n,Xw(n,t)}function Ar(e){return Array.isArray(e.children)&&e.children.length>0}function Lv(){Ir&&(Ir.remove(),Ir=null)}function hn(){Lv(),Ns&&(Ns.remove(),Ns=null),fd=null,Os&&(document.removeEventListener("mousedown",Os),Os=null),Ds&&(document.removeEventListener("keydown",Ds),Ds=null)}function Y1(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const mn="os-breadcrumbs";function X1(e,t,n={}){if(e.replaceChildren(),e.classList.add(mn),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${mn}__back`,s.setAttribute("aria-label",b("Back","desktop-mode")),s.title=b("Back","desktop-mode");const i=document.createElement("span");i.className="dashicons dashicons-arrow-left-alt2",i.setAttribute("aria-hidden","true"),s.appendChild(i),n.backDisabled&&(s.disabled=!0);const r=n.onBack;s.addEventListener("click",()=>{s.disabled||r()}),e.appendChild(s)}const o=document.createElement("nav");o.className=`${mn}__crumbs`,o.setAttribute("aria-label",b("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const l=document.createElement("span");l.className=`${mn}__sep`,l.setAttribute("aria-hidden","true"),l.textContent="›",o.appendChild(l)}if(!s.onClick){const l=document.createElement("span");l.className=`${mn}__crumb ${mn}__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=`${mn}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}function Cr(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 Rs(e,t={}){const n=await Le(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":Z1(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function Z1(){return window.wp?.os?.config?.restNonce??""}function J1(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function xs(e){return rt(J1(),e)}function Q1(e,t){const n=X("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(eW(e));return}t.replaceChildren(uW()),tW(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(fW(o))})}function eW(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 tW(e){const t=e.file;switch(t.type){case"post":return nW(t.ref,t);case"folder":return cW(t);case"shortcut":return lW(t);case"attachment":return rW(t.ref,t);case"upload":return aW(t);case"user":return oW(t.ref,t);case"term":return sW(t);case"comment":return iW(t.ref,t);case"bookmark":return dW(t);default:return ot(t)}}async function nW(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await Rs(xs(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return ot(t);const s=ut(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Lr(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(Tv(o.date)),o.status&&o.status!=="publish"&&a.push(o.status),r.textContent=a.join(" · "),s.appendChild(r),o.content?.rendered){const u=document.createElement("div");u.className="os-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const c=document.createElement("os-button");c.setAttribute("variant","secondary"),c.textContent=b("Explore details","desktop-mode"),c.title=b("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),c.addEventListener("click",()=>{const u=typeof t.postType=="string"?t.postType:"post";Ky({entityId:u==="page"?"pages":"posts",postId:n,postTitle:Lr(o.title.rendered)||`#${n}`})}),l.appendChild(c);const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=b("Open in editor","desktop-mode"),d.addEventListener("click",()=>{const u=window.wp?.os?.config?.adminUrl;if(!u)return;const f=`${u}post.php?post=${n}&action=edit`,p=window.wp?.os?.windowManager,h=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${h}-edit-${n}`,url:f,title:Lr(o.title.rendered),icon:t.icon})}),l.appendChild(d),s.appendChild(l),s}async function oW(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;try{o=await Rs(xs(`desktop-mode/v1/user-stats/${n}`))}catch{return ot(t)}const s=ut("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(po(o.counts.posts.total.toLocaleString(),b("Posts","desktop-mode"))),l.appendChild(po(o.counts.pages.total.toLocaleString(),b("Pages","desktop-mode"))),l.appendChild(po(o.counts.commentsReceived.toLocaleString(),b("Comments received","desktop-mode"))),s.appendChild(l),s}async function sW(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return ot(e);let o=null;try{o=await Rs(xs(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return ot(e)}const s=ut(),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(po(o.counts.posts.total.toLocaleString(),b("Posts","desktop-mode"))),a.appendChild(po(o.counts.commentsReceived.toLocaleString(),b("Comments","desktop-mode"))),a.appendChild(po(o.counts.distinctAuthors.toLocaleString(),b("Authors","desktop-mode"))),s.appendChild(a),s}async function iW(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;try{o=await Rs(xs(`desktop-mode/v1/comment-stats/${n}`))}catch{return ot(t)}const s=ut(),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=`${Tv(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 rW(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;try{o=await Rs(xs(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return ot(t)}const s=ut(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Lr(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 aW(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Uploaded file","desktop-mode"),t.appendChild(n);const o=typeof e.mime=="string"?e.mime:"",s=typeof e.sizeBytes=="number"?e.sizeBytes:0,i=typeof e.kind=="string"?e.kind:"file",r=document.createElement("p");r.className="os-my-wordpress__article-meta",r.textContent=[o,s>0?Ev(s):""].filter(Boolean).join(" · "),t.appendChild(r);const a=parseInt(e.ref,10),l=()=>{const c=document.createElement("p");return c.className="os-my-wordpress__article-meta os-files__no-preview",c.textContent=b("No preview available for this file type.","desktop-mode"),c};if(a>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=dn(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=dn(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=dn(a),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else t.appendChild(l());if(a>0){const c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=b("Download","desktop-mode"),d.addEventListener("click",()=>{Cr(dn(a))}),c.appendChild(d),t.appendChild(c)}return t}function cW(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=b("Double-click to open.","desktop-mode"),t.appendChild(o),t}function lW(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=b("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function dW(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Bookmark","desktop-mode"),t.appendChild(n);const o=typeof e.url=="string"?e.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",t.appendChild(s)}return t}function ot(e){const t=ut(),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=ae(b("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="os-my-wordpress__article-meta",s.textContent=b("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function ut(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function po(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 uW(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function fW(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:b("Unknown error.","desktop-mode"),t}function Lr(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function Tv(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function Nv(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=b("Select an item to preview it here.","desktop-mode"),e}function pW(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=ae(b("%d items selected","desktop-mode"),e.length),t.appendChild(n);const o=new Map;for(const i of e){const r=i.file?.type||"item";o.set(r,(o.get(r)??0)+1)}const s=Array.from(o.entries()).sort((i,r)=>r[1]-i[1]||i[0].localeCompare(r[0])).map(([i,r])=>`${r} × ${i}`).join(" · ");if(s){const i=document.createElement("div");i.className="os-files-preview__selection-breakdown",i.textContent=s,t.appendChild(i)}return t}const Tr="desktop-mode-embed-",hW=800,mW=600,pd=360,hd=240,Nr=16,md=new Map;function gW(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?`${Tr}${s.id}`:`${Tr}anon-${bW(n)}`,a=i?.name?.trim()??"",l=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:l,icon:e.icon(),minWidth:pd,minHeight:hd},d=i?.window,u=document.getElementById("os-area"),f=u?me(u):{x:0,y:0,width:window.innerWidth,height:window.innerHeight};if(d&&Number.isFinite(d.width)&&Number.isFinite(d.height)){const{x:p,y:g,width:h,height:m}=vW(d,f);c.x=p,c.y=g,c.width=h,c.height=m}else c.width=Math.min(hW,Math.max(pd,f.width-Nr*2)),c.height=Math.min(mW,Math.max(hd,f.height-Nr*2));s&&d&&md.set(r,{...d}),o.open(c)}let Ov=!1;function wW(){if(Ov)return;Ov=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(Tr))return;const s=o.slice(Tr.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=md.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(md.set(o,c),yW(i,c))};ee(y.WINDOW_DRAG_END,"os-embed-persist",e),ee(y.WINDOW_RESIZE_END,"os-embed-persist",e)}async function yW(e,t){try{const i={...(await Re(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await ao(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function vW(e,t){const n=Math.max(pd,Math.min(e.width,t.width-Nr)),o=Math.max(hd,Math.min(e.height,t.height-Nr)),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 bW(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 Ms(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function Dv(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 EW(){Be({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Ms()}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=>`${Ms()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Be({id:"agent-chat",label:b("Agent chat","desktop-mode"),types:["user"],isDefault:!0,sort:5,appliesTo:e=>e.shape.isAgent===!0,handler:{kind:"js",open:e=>{const t=e.shape;xy({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=>`${Ms()}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`${Ms()}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=>`${Ms()}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&&Cr(dn(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=te.getState().folders.get(t),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),l=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:l,icon:e.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window"),$i("desktop-mode-my-wordpress");const d=[{folderId:t,title:e.title()}];let u=null;const f=document.createElement("header");c.appendChild(f);const p=document.createElement("div");p.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",c.appendChild(p);const g=()=>{const m=d.map((E,S)=>S===d.length-1?{label:E.title}:{label:E.title,onClick:()=>{d.length=S+1,h()}});X1(f,m,{onBack:()=>{d.length<=1||(d.pop(),h())},backDisabled:d.length<=1})},h=()=>{u?.(),u=null,p.replaceChildren();const m=document.createElement("div");m.className="os-folder-window__split",p.appendChild(m);const E=document.createElement("div");E.className="os-folder-window__layer",m.appendChild(E);const S=document.createElement("div");S.className="os-folder-window__preview",S.appendChild(Nv()),m.appendChild(S);const R=d[d.length-1],$=mv(E,R.folderId),_=$.onSelectionChanged(F=>{if(F.length===0){S.replaceChildren(Nv());return}if(F.length>1){S.replaceChildren(pW(F));return}Q1(F[0],S)}),M=F=>{if(!(F.target instanceof Element))return;const K=F.target.closest(".os-file-tile");if(!K||K.dataset.fileType!=="folder")return;const Z=parseInt(K.dataset.fileRef??"",10);if(!Z)return;F.preventDefault(),F.stopPropagation();const Y=K.querySelector(".os-file-tile__label")?.textContent??`#${Z}`;d.push({folderId:Z,title:Y}),h()};E.addEventListener("dblclick",M,!0);const P=j1(E,{scope:`os-folder:${R.folderId}`,onSort:F=>$.sort(F),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{ad({onSubmit:async F=>{const K=await ql({name:F}),Z=te.getState().placementsByFolder.get(R.folderId)??[],Y=ov(Z),L=Bt(Ut,Ut,Y,E,Er(R.folderId)),x=await _s({type:"folder",ref:String(K.id),parentId:R.folderId,x:L.x,y:L.y});te.upsertFolder(K),te.upsertPlacement(x)}})}}]}),B=F1(p,R.folderId,{selection:{count:()=>$.getSelection().length,subscribe:F=>$.onSelectionChanged(()=>F())}});u=()=>{_(),P.dispose(),B.dispose(),E.removeEventListener("dblclick",M,!0),$.dispose()},g()};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?ue(o.toString(),s):`desktop-icon-${e.ref()}`,r=Qi(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=Dv(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=Dv(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)=>{gW(e,t)}}})}const _W="os-file-associations";let gn=null;function SW(){dm({id:_W,label:"File Associations",order:50,render(e){gn&&(gn(),gn=null),Rv(e),gn=Cy(()=>{if(!e.isConnected){gn&&(gn(),gn=null);return}Rv(e)})}})}function Rv(e){e.replaceChildren();const t=Sy();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=Bl(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(kW(i.type,i.label,o));e.appendChild(s)}function kW(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=Fl(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=Hl(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={...Bl(),[e]:d};Iy(u),$y(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(l),o}function IW(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,Zl(t),!0)}function AW(){return window.openStationConfig?.filesOverlaysBundleUrl??""}async function Ws(){if(window.openStationFilesOverlays)return window.openStationFilesOverlays;const e=AW();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 xv(...e){await(await Ws())?.openShareSettingsModal(...e)}async function CW(...e){await(await Ws())?.openFileShareModal(...e)}async function LW(...e){return(await Ws())?.openPendingFileInviteModal(...e)}async function TW(...e){return(await Ws())?.openPendingInviteModal(...e)}function NW(...e){Ws().then(t=>t?.openUrlDialog(...e))}function Mv(){return Number(window.openStationConfig?.currentUserId??0)}function OW(e){window.wp?.os?.windowManager?.getById?.(e)?.close?.()}function gd(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function Wv(e){const t=$t().folders.get(e);return t?Number(t.ownerId):0}function Pv(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function DW(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function RW(e){return Number(e.file.ownerId??0)}function xW(){pt("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!gd())return e;const n=DW(t);if(n===null)return e;const o=Wv(n)||RW(t),s=Mv();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:()=>{xv({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 Yt({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 Uy(n),Ss(t.id);try{const a=await Re(0);Pt(0,a.placements)}catch{}const r=`os-folder-${n}`;OW(r),de({message:"You left the shared folder."})}catch(r){de({message:`Could not leave: ${r.message}`})}}});return e}),Vo({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!gd())return!1;const t=e.config.baseId??e.id,n=Pv(t);return n===null?!1:Wv(n)===Mv()},onClick:e=>{if(!gd())return;const t=e.config.baseId??e.id,n=Pv(t);n!==null&&xv({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),ee("os.files.tile-rendered","desktop-mode/folder-share",e=>{const{tile:t,placement:n}=e;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||t.querySelector(".os-file-tile__share-badge"))return;const s=document.createElement("span");s.className="os-file-tile__share-badge dashicons dashicons-share",s.setAttribute("aria-label","Shared folder"),s.title="Shared folder",s.style.cssText=["position:absolute","top:6px","inset-inline-end:6px","background:rgba(0,0,0,0.55)","color:#fff","border-radius:50%","width:18px","height:18px","font-size:12px","line-height:18px","text-align:center","pointer-events:none"].join(";"),t.appendChild(s)})}let wd=null;function Or(){return wd||(wd=ie("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),wd}function MW(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 $v(e){const t=Or(),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(MW(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 Dr(e,t={}){const n=Or();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 Uv=new Set;function WW(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function PW(){const e=Or(),t=n=>{if(WW()){for(const o of n.pending)if(!Uv.has(o.id)){if(Uv.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;LW({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?Dr(o.id):i==="denied"&&Dr(o.id,{denied:!0,fileId:s})});continue}TW({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Dr(o.id):s==="denied"&&Dr(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function $W(){return Number(window.openStationConfig?.currentUserId??0)}function Bv(){return window.openStationConfig?.desktopStorage??{}}function UW(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function BW(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function FW(){pt("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&Bv().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:()=>{Cr(Gy(i))}}),e}const n=BW(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{Cr(dn(n))}});const o=Number(t.file.ownerId??0),s=$W();return o===s&&UW()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{CW({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 Yt({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 By(n),Ss(t.id);try{const r=await Re(0);Pt(0,r.placements)}catch{}de({message:"You left the shared file."})}catch(r){de({message:`Could not leave: ${r.message}`})}}}),e}),pt("os.wallpaper-context-menu","desktop-mode/uploads",e=>(Bv().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>Fv(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>Fv(!0)})),e))}function Fv(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&&HW(n,e)}),t.click()}async function HW(e,t){const n=window.openStationConfig?.fileDropBundleUrl;if(n){try{await fe(n)}catch{de({message:"Upload machinery failed to load — try again."});return}await window.openStationFileDrop?.routePickedFiles(e,t)}}function GW(){return window.openStationConfig?.desktopStorage??{}}function Hv(e){if(e.file.type!=="upload"||e.file.isMedia!==!0)return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function zW(e){return e.file.kind==="image"}function Gv(e){return(e instanceof Error?e.message:String(e)).replace(/^\[openstation\] files REST \d+: \S+ /,"")}function jW(e){de({message:e.created?"Added to the Media Library.":"Already in the Media Library.",action:{label:"Open",onClick:()=>{zl({url:e.editUrl,title:e.title||"Attachment",icon:"dashicons-admin-media"})}}})}async function VW(e){try{jW(await gr(e))}catch(t){de({message:`Could not add to the Media Library: ${Gv(t)}`})}}const KW=async e=>{let t=0,n=0,o=0;for(const i of e){const r=Hv(i);if(r!==null)try{(await gr(r)).created?t+=1:n+=1}catch{o+=1}}const s=[];t>0&&s.push(`Added ${t} ${t===1?"file":"files"} to the Media Library.`),n>0&&s.push(`${n} already there.`),o>0&&s.push(`${o} could not be added.`),s.length>0&&de({message:s.join(" ")})};async function zv(e,t){try{const n=await Fy(e,t);zl({url:n.editUrl,title:t==="page"?"Add New Page":"Add New Post",icon:t==="page"?"dashicons-admin-page":"dashicons-admin-post"})||(window.location.href=n.editUrl)}catch(n){de({message:`Could not start a ${t}: ${Gv(n)}`})}}function qW(){pt("os.files.tile-menu","desktop-mode/media-library",(e,t)=>{const n=Hv(t);if(n===null)return e;const o=GW();return!o.canAddToMedia||(e.push({id:"desktop-mode/upload-add-to-media",label:"Add to Media Library",icon:"dashicons-admin-media",sort:50,multi:!0,bulkLabel:s=>`Add ${s} files to Media Library`,bulk:KW,onClick:()=>VW(n)}),!zW(t))||(o.canStartPost&&e.push({id:"desktop-mode/upload-start-post",label:"Start a post with this image",icon:"dashicons-admin-post",sort:55,onClick:()=>zv(n,"post")}),o.canStartPage&&e.push({id:"desktop-mode/upload-start-page",label:"Start a page with this image",icon:"dashicons-admin-page",sort:56,onClick:()=>zv(n,"page")})),e})}function YW(){return window.openStationConfig?.desktopStorage?.canAddToMedia===!0}function XW(e){const t=e.placement.file;if(t.type!=="post"||t.exists===!1||t.status==="trash"||!YW())return 0;const n=parseInt(String(t.ref??""),10);return Number.isFinite(n)&&n>0?n:0}function jv(e){const t=pn(e);if(t.length===0)return[];const n=[];for(const o of t){const s=o?.file;if(!s||s.type!=="upload"||s.isMedia!==!0)return[];const i=parseInt(String(s.ref??""),10);if(!Number.isFinite(i)||i<=0)return[];n.push(i)}return n}function ZW(e){return(e instanceof Error?e.message:String(e)).replace(/^\[openstation\] files REST \d+: \S+ /,"")}async function JW(e,t){const n=parseInt(String(e.file.ref??""),10);try{const o=await Hy(n,t),s=o.attachments.length,i=s===1?"file":`${s} files`,r=o.title||e.file.title||`#${n}`;if(zl({url:o.editUrl,title:r,icon:e.file.icon||"dashicons-admin-post"}),de({message:`Added ${i} to “${r}”.`}),o.featuredImageSet)try{const a=await Re(e.parentId);Pt(e.parentId,a.placements)}catch{}}catch(o){de({message:`Could not add to the post: ${ZW(o)}`})}}function Vv(e){return{appliesTo:t=>{if(XW(t)===0)return!1;const n=t.placement.file.postType==="page";return e==="page"?n:!n},accept:t=>jv(t).length>0,acceptLabel:e==="page"?"Add to page":"Add to post",onDrop:(t,n,o)=>{const s=jv(t.payload.data);s.length!==0&&JW(o.placement,s)}}}function QW(){const e=Is("desktop-file",Vv("page")),t=Is("desktop-file",Vv("other"));return()=>{e(),t()}}fM(),EW(),wW(),SW(),IW(),xW(),FW(),qW(),O1(),QW();const yd=window.openStationConfig?.serverPendingShares;Array.isArray(yd)&&yd.length>0&&$v(yd),PW();const He={DesktopFile:_y,registerType:Ve,unregisterType:iM,getType:rM,getTypes:Sy,resolve:Mt,subscribe:aM,registerOpener:Be,unregisterOpener:cM,getOpener:lM,getOpeners:Ay,getOpenersForType:Fl,resolveOpener:Hl,subscribeOpeners:Cy,getUserAssociations:Bl,open:bs,registerTilePayloadHandler:Is,rest:UM,store:{get:nt,getState:$t,subscribe:ed,setFolderPlacements:Pt,upsertPlacement:Xl,removePlacement:Ss,setFolders:Zl,upsertFolder:Jl,removeFolder:Ql}},Kv="__synthFromDockItem";function eP(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function tP(e,t){const n=!!e.tile,o=t[e.id];return{id:eP(e.id),parentId:0,x:o?o.x:0,y:o?o.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Kv]: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 vd=!1;const bd=new Map;function nP(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 oP(e,t,n={}){if(!vd){vd=!0;try{const s=He.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[Kv]: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)||He.store.upsertPlacement(tP(d,n));const c=[];for(const[d,u]of r)i.has(d)||(He.store.removePlacement(u.id),n[d]&&c.push(d));c.length>0&&nP(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&&(bd.set(u.id,f),He.store.removePlacement(f.id));continue}if(!f){const p=bd.get(u.id);p&&(He.store.upsertPlacement(p),bd.delete(u.id))}}}finally{vd=!1}}}function sP(e){queueMicrotask(e);const t=He.store.subscribe(e),n="desktop-mode/shortcuts-sync";return ee(y.DOCK_ITEM_APPENDED,n,e),()=>{t(),yo(y.DOCK_ITEM_APPENDED,n)}}const Rr="os-note-created",iP="openstation_notes";function rP(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(Rr,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(Rr,{detail:a.detail})),s()};document.addEventListener(Rr,i);const r=()=>{s()};return window.addEventListener("dragstart",r,!0),document.addEventListener(ke.START,r),pt("os.wallpaper-context-menu","desktop-mode/notes-sentinel",(a,l)=>{if(!Array.isArray(a)||a.some(u=>u.id==="new-note"))return a;const{x:c,y:d}=l??{x:0,y:0};return[...a,{id:"new-note",label:b("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{s().then(u=>{if(!u)return;const f=u.normalizedFromClient(c,d);u.createNoteAt({...f,focus:!0})})}}]}),e.hasNotes?(typeof requestIdleCallback=="function"?requestIdleCallback:l=>window.setTimeout(l,200))(()=>void s()):o=De.subscribe(iP,a=>{a&&(o?.(),o=null,s())}),()=>{document.removeEventListener(Rr,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(ke.START,r),o?.(),o=null}}const aP={id:"clock",get label(){return b("Clock")},get description(){return b("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("os-widget-clock");const t=document.createElement("div");t.className="os-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="os-widget-clock__date",e.appendChild(n);const o=()=>{const a=new Date;t.textContent=a.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=a.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})};o();const s=1e3-Date.now()%1e3;let i=null;const r=window.setTimeout(()=>{o(),i=window.setInterval(o,1e3)},s);return()=>{window.clearTimeout(r),i!==null&&window.clearInterval(i)}}};function cP(){Zc(aP)}async function lP(){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 qv(e,t){if(t){const o=b('WordPress %1$s "%2$s" is available.');return ae(o,e,t)}const n=b("WordPress %s is available.");return ae(n,e)}async function dP(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(Ki(a))return;const l=`${a}:no-art`,c=()=>n({url:t.url,title:b("WordPress Updates")}),u=e.resolveArt&&e.loadImage&&e.showCard?null:await lP(),f=e.resolveArt??u?.resolveReleaseArt,p=e.loadImage??u?.preloadImage,g=e.showCard??u?.showReleaseCard,h=f?await f(s,i):null;if(h&&h.artUrl&&p&&g&&await p(h.artUrl)){g({message:qv(o,i?h.name:""),artUrl:h.artUrl,dismissKey:a,onUpdate:c});return}Ki(l)||de({message:qv(o,""),persistent:!0,dismissible:!0,onDismiss:()=>qi(l),action:{label:b("Update now"),onClick:c}})}function Yv(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(Ki(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})}),de({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>qi(i),action:c})}}const Ed="desktop-mode/starter",uP="desktop-mode/dev-mode-gate";let Xv=!1;function fP({osSettings:e,layer:t}){if(Xv)return;Xv=!0,pt(y.WIDGETS,uP,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==Ed));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(Ed):t.unmount(Ed),ss())})}function pP(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){C(y.SHELL_ERROR,{scope:"widget-script-load",id:c.id,error:d});return}o.add(c.scriptUrl)}},i=c=>(window.openStationWidgets||{})[c]??null,r=c=>({id:c.id,label:c.label,description:c.description,icon:c.icon,movable:c.movable,resizable:c.resizable,minWidth:c.minWidth||void 0,minHeight:c.minHeight||void 0,maxWidth:c.maxWidth||void 0,maxHeight:c.maxHeight||void 0,defaultWidth:c.defaultWidth||void 0,defaultHeight:c.defaultHeight||void 0,mount:async(d,u)=>{await s(c);const f=i(c.id);if(!f){const p=new Error(`[openstation] No mount callback on window.openStationWidgets["${c.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`);throw C(y.SHELL_ERROR,{scope:"widget-missing-mount",id:c.id,error:p}),p}return f(d,u)}}),a=async c=>{if(n.has(c.id))return;const d=r(c);try{Zc(d)}catch(u){C(y.SHELL_ERROR,{scope:"widget-register",id:c.id,error:u});return}n.add(c.id),ss(),t&&t.mountIfEnabled(c.id)},l=c=>{n.has(c)&&(t?.unmount(c),qT(c),n.delete(c),ss())};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 Zv=new Set(fr),hP=2e3,_d=new Set,Jv=new WeakSet;let Qv=!1;function mP(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 gP(e){let t=null,n=1/0;for(const o of Zv){const s=mP(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function wP(e){return e.startsWith("os-")?e.slice(4):e}function yP(e,t){if(_d.has(e))return;if(_d.add(e),Zv.has(e)){const s=wP(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=gP(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 eb(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||_d.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||yP(t,e)},hP)}function tb(e){e instanceof Element&&(eb(e),e.shadowRoot&&xr(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];eb(o),o.shadowRoot&&xr(o.shadowRoot)}}function xr(e){if(Jv.has(e))return;Jv.add(e),tb(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&&tb(r)}}}).observe(e,{childList:!0,subtree:!0})}function vP(){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"&&xr(s),s};n.__wpdPatched=!0,e.attachShadow=n}function bP(){Qv||typeof document>"u"||(Qv=!0,vP(),xr(document))}const nb=`<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>`,EP=`data:image/svg+xml;base64,${btoa(nb)}`;let Sd=0;function _P(e,t,n){const o=`openstation/mio-window-${++Sd}`,s=new Set,i=r=>{const a=t(),l=a.available&&a.enabled;let c=b(l?"Disable MIO in this window":"Enable MIO in this window");a.available||(c=b("Enable MIO in the dock first")),r.setAttribute("aria-label",c),r.setAttribute("title",c),r.setAttribute("aria-pressed",String(l)),r.toggleAttribute("disabled",!a.available),r.inert=!a.available,r.setAttribute("aria-hidden",String(!a.available)),r.dataset.mioAvailable=String(a.available),r.toggleAttribute("active",l),r.dataset.mioDisabled=String(!l),r.dataset.mioThinking=String(l&&a.thinking)};return Vo({id:o,label:b("MIO in this window"),icon:nb.replace('id="mio"',`id="mio-${Sd}"`).replace("url(#mio)",`url(#mio-${Sd})`),placement:"right",order:20,match:r=>r.id===e,render:r=>{r.classList.add("os-mio-window-toggle");const a=r.querySelector("svg");if(a){const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M3 3L21 21"),l.setAttribute("class","os-mio-window-toggle__slash"),a.appendChild(l)}s.add(r),i(r),r.addEventListener("os-button-activate",()=>{t().available&&n()})}}),{update:()=>{for(const r of s)r.isConnected?i(r):s.delete(r)},dispose:()=>{mm(o),s.clear()}}}class SP{constructor(t,n,o,s){this.host=t,this.frame=n,this.handle=o,this.visibility=s,this.request=null,this.dismissed=new Set,this.active=!1,this.visible=!1,this.raf=0,this.bubble=document.createElement("aside"),this.bubble.className="os-mio-callout",this.bubble.hidden=!0,this.bubble.setAttribute("aria-label",b("MIO tip")),this.message=document.createElement("span"),this.message.setAttribute("role","status");const i=document.createElement("os-button");i.setAttribute("variant","ghost"),i.setAttribute("aria-label",b("Dismiss MIO tip"));const r=document.createElement("span");r.textContent="×",r.setAttribute("aria-hidden","true");const a=document.createElement("span");a.className="screen-reader-text",a.textContent=b("Dismiss MIO tip"),i.append(r,a),i.addEventListener("click",()=>{this.request&&(this.dismissed.add(this.request.id),this.update(),this.request.onDismiss?.())}),this.bubble.append(this.message,i),n.append(this.bubble),this.observer=new MutationObserver(()=>this.update()),this.observer.observe(t,{childList:!0,subtree:!0,attributes:!0})}show(t){if(!t.id.trim()||!t.message.trim()||typeof t.target!="function")throw new Error("MIO callouts require an id, message and a live target resolver.");this.request=t,this.message.textContent=t.message,this.update()}clear(){this.request=null,this.update()}setActive(t){this.active=t,this.update()}update(){cancelAnimationFrame(this.raf),this.raf=0;const t=this.request,n=this.active&&t&&!this.dismissed.has(t.id)?t.target():null,o=this.frame.getBoundingClientRect(),s=n?.getBoundingClientRect(),i=!!(n?.isConnected&&this.host.contains(n)&&s&&s.width>0&&s.height>0&&s.bottom>o.top&&s.top<o.bottom&&s.right>o.left&&s.left<o.right);if(this.bubble.hidden=!i,i&&s){const r=(f,p,g)=>Math.max(p,Math.min(f,g)),a=getComputedStyle(this.frame).direction==="rtl",l={x:r(a?s.left+60:s.right-60,o.left+60,o.right-60),y:r(s.bottom+65,o.top+65,o.bottom-65)};this.handle()?.setAnchor?.(l,!0);const c=this.handle()?.getPosition()??l,d=this.bubble.offsetWidth,u=this.bubble.offsetHeight;this.bubble.style.left=`${r(c.x-o.left+(a?45:-d-45),8,o.width-d-8)}px`,this.bubble.style.top=`${r(c.y-o.top-u-24,8,o.height-u-8)}px`}i!==this.visible&&(this.visible=i,i||this.handle()?.setAnchor?.(null),this.visibility(i)),this.active&&t&&!this.dismissed.has(t.id)&&(this.raf=requestAnimationFrame(()=>this.update()))}dispose(){this.setActive(!1),this.observer.disconnect(),this.bubble.remove()}}function kP(e,t,n){const o=e.getBoundingClientRect(),s=n()?.getPosition(),i=s?{x:s.x-o.left,y:s.y-o.top}:null,r=new ResizeObserver(a);function a(){if(!e.isConnected||e.hidden)return;const l=e.getBoundingClientRect(),c=t.getBoundingClientRect();let d=i?{x:l.left+i.x,y:l.top+i.y}:null;c.left-l.left>=140&&(d={x:c.left-70,y:Math.min(c.top+70,l.bottom-70)}),n()?.setAnchor?.(d,!0)}return r.observe(t),r.observe(e),a(),{close:l=>{r.disconnect();const c=e.getBoundingClientRect();n()?.setAnchor?.(l&&i?{x:c.left+i.x,y:c.top+i.y}:null,!1)}}}const ft=Object.freeze({rounds:8,calls:16,validationFailures:3,repeatedReads:4});class Mr extends Error{constructor(t,n=!0){super(t.map(o=>`${o.path}: ${o.message}`).join("; ")),this.errors=t,this.retryable=n,this.name="MioValidationError"}}function ho(e,t){try{e?.(t)}catch{}}function ob(e){if(!e||typeof e!="object")return null;const t=e;return t.effect==="none"&&t.status==="completed"||t.effect==="none"&&t.status==="rejected"&&Array.isArray(t.errors)||t.effect==="write"&&t.status==="confirmed"&&typeof t.receipt=="string"&&t.receipt.length>0&&t.receipt.length<=500||t.effect==="write"&&t.status==="unknown"?t:null}class IP{constructor(t){this.records=new Map,this.inspectors=new Map,this.receipts=new Map,this.context=t}list(){return Array.from(this.records.values(),t=>structuredClone(t))}record(t,n,o,s){const i=this.records.get(t.callId);if(i?.status==="confirmed"&&o!=="confirmed")return structuredClone(i);if(i?.receipt&&s&&i.receipt!==s)throw new Error("MIO operation receipt changed unexpectedly.");const r=s&&this.receipts.has(s)&&this.receipts.get(s)!==t.callId,a={turnId:t.turnId,callId:t.callId,idempotencyKey:t.idempotencyKey,windowId:t.windowId,revision:t.revision,ability:n,effect:t.effect,status:r?"unknown":o,...s?{receipt:s}:{}};for(s&&!r&&this.receipts.set(s,t.callId),this.records.set(t.callId,a),this.context.operationStatus&&this.inspectors.set(t.callId,this.context.operationStatus);this.records.size>64;){const l=this.records.keys().next().value,c=this.records.get(l);c?.receipt&&this.receipts.get(c.receipt)===l&&this.receipts.delete(c.receipt),this.records.delete(l),this.inspectors.delete(l)}if(ho(this.context.onOperation,structuredClone(a)),r)throw new Error("MIO received a duplicate write receipt; inspect the operation status before continuing.");return structuredClone(a)}async inspect(t,n){const o=this.records.get(t),s=this.inspectors.get(t);if(!o)throw new Error("Unknown MIO operation.");if(o.effect!=="write"||o.status==="confirmed"||!s)return structuredClone(o);n.throwIfAborted();const i=ob(await s(structuredClone(o),n));return n.throwIfAborted(),i?.effect==="write"&&i.status==="confirmed"?this.record({...o,signal:n,limits:ft,validationFailures:0,validationRemaining:0},o.ability,"confirmed",i.receipt):i?.effect==="none"&&i.status==="rejected"?this.record({...o,signal:n,limits:ft,validationFailures:0,validationRemaining:0},o.ability,"rejected"):structuredClone(o)}}function AP(e){return`Reads: ${e.reads}; rejected candidates: ${e.rejected}; confirmed writes: ${e.confirmedWrites}; unknown write outcomes: ${e.unknownWrites}. Completed writes are not rolled back.`}const kd=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t;class CP{constructor(t,n,o){this.entries=new Map,this.listeners=new Set,this.disposed=!1,this.context=t,this.active=n,this.messages=o}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notify(){for(const t of this.listeners)ho(t,void 0)}create(t){const n=[];if(this.disposed)return n;try{const o=this.context.responseActions?.(t);if(!Array.isArray(o)||this.disposed)return n;const s=new Set;let i=!1;for(const r of o.slice(0,100))try{if(!r||typeof r!="object")continue;const a={...r};if(!kd(a.id,80)||s.has(a.id)||!kd(a.label,40)||typeof a.run!="function"||!["read","navigate"].includes(a.effect)||a.emphasis!==void 0&&!["primary","secondary"].includes(a.emphasis)||a.allowed!==void 0&&typeof a.allowed!="function"||a.ariaLabel!==void 0&&!kd(a.ariaLabel,160))continue;s.add(a.id),a.icon!==void 0&&(typeof a.icon!="string"||!/^(?:dashicons-)?[a-z][a-z0-9-]{0,63}$/.test(a.icon))&&delete a.icon,a.emphasis==="primary"&&!i?i=!0:a.emphasis="secondary";const l=crypto.randomUUID();if(this.entries.set(l,{messageId:t.messageId,turnId:t.summary.turnId,action:a,pending:null,status:""}),n.push(l),n.length===3)break}catch{}}catch{}return n}prune(){const t=new Set(this.messages().slice(-40).flatMap(n=>n.role==="assistant"?(n.actionIds??[]).map(o=>`${n.id}/${o}`):[]));for(const[n,o]of this.entries)t.has(`${o.messageId}/${n}`)||(o.pending?.abort(),this.entries.delete(n))}allowed(t){try{return!this.disposed&&this.active()&&(t.action.allowed?.()??!0)}catch{return!1}}list(t){return this.prune(),t.role!=="assistant"?[]:(t.actionIds??[]).flatMap(n=>{const o=this.entries.get(n);if(!o||o.messageId!==t.id)return[];const s=this.allowed(o);if(!s&&!o.status)return[];const{label:i,ariaLabel:r,icon:a,emphasis:l}=o.action;return[{id:n,label:i,ariaLabel:r,icon:a,emphasis:l??"secondary",pending:o.pending!==null,available:s,status:o.status}]})}async run(t,n){this.prune();const o=this.entries.get(n);if(!o||o.messageId!==t||o.pending)return;if(!this.allowed(o)){o.status=b("This action is no longer available."),this.notify();return}const s=new AbortController;o.pending=s,o.status=b("Working…"),this.notify();try{if(s.signal.throwIfAborted(),!this.allowed(o))throw new Error(b("This action is no longer available."));await o.action.run({signal:s.signal,messageId:t,turnId:o.turnId}),o.status=b("Done.")}catch(i){o.status=i instanceof Error?i.message.slice(0,500):b("Could not complete this action. Try again."),s.signal.aborted&&(o.status="")}finally{o.pending=null,this.notify()}}cancel(){for(const t of this.entries.values())t.pending?.abort()}dispose(){this.disposed=!0,this.cancel(),this.entries.clear(),this.listeners.clear()}}const LP=new Set("a an and are as at be by can do for from how i in is it me of on or please that the this to use we what with you your".split(" ")),Id=e=>(e.toLocaleLowerCase().match(/[\p{L}\p{N}_-]+/gu)??[]).filter(t=>!LP.has(t)),sb=e=>({id:e.id,title:e.title,version:e.version,topics:e.topics??[],componentIds:e.componentIds??[]});function ib(e){const t=[],n=new Map;let o={id:"intro",title:"Introduction",markdown:""},s="";for(const i of e.split(`
64 `)){const r=i.match(/^\s*(`{3,}|~{3,})/)?.[1];r&&(s?r[0]===s[0]&&r.length>=s.length&&(s=""):s=r);const a=!s&&i.match(/^#{1,6}\s+(.+?)\s*#*$/);if(a){o.markdown&&t.push(o);const l=a[1].toLowerCase().replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^-|-$/g,"")||"section",c=n.get(l)??0;n.set(l,c+1),o={id:c?`${l}-${c}`:l,title:a[1],markdown:""}}o.markdown+=`${o.markdown?`
65 `:""}${i}`}return o.markdown&&t.push(o),t}function TP(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%4294967291;return t.toString(36)}function rb(e,t){const n=[...new Set(Id(t))],o=t.trim().toLowerCase();return e.map(s=>{const i=[s.id,s.id.replace(/\.md$/,""),s.title,...s.componentIds??[],...s.topics??[]].map(f=>f.toLowerCase()),r=i.includes(o)?1e3:0,a=ib(s.markdown).map(f=>{const p=new Set(Id(f.markdown)),g=new Set(Id(`${s.title} ${s.id} ${f.title} ${i.join(" ")}`));return{section:f,score:r+n.reduce((h,m)=>h+(p.has(m)?1:0)+(g.has(m)?10:0),0)}}).sort((f,p)=>p.score-f.score),l=a[0],c=l?.section.markdown??"";let d=Math.min(c.length,3200);d<c.length&&/[\uD800-\uDBFF]/.test(c[d-1])&&d--;const u=c.slice(0,d);return{...sb(s),score:l?.score??0,section:l?.section.id,excerpt:u,truncated:(l?.section.markdown.length??0)>u.length,sections:a.slice(0,2).map(f=>({id:f.section.id,title:f.section.title}))}}).filter(s=>s.score>0).sort((s,i)=>i.score-s.score).slice(0,4)}function ab(e,t,n,o){const s=e.find(p=>p.id===t);if(!s)throw new Error("Unknown help document.");const i=ib(s.markdown),r=n?i.find(p=>p.id===n):null;if(n&&!r)throw new Error("Unknown help section.");const a=r?.markdown??s.markdown,l=TP(`${t}
66 ${s.version??""}
67 ${n??""}
68 ${a}`);let c=0;if(o){const p=o.match(/^([a-z0-9]+):(\d+)$/);if(!p||p[1]!==l||Number(p[2])>=a.length)throw new Error("Invalid or stale help cursor; read the document again.");c=Number(p[2])}let d=Math.min(a.length,c+12e3);d<a.length&&/[\uD800-\uDBFF]/.test(a[d-1])&&d--;const u=new URL(t,"https://mio.invalid/"),f=[...s.markdown.matchAll(/\]\(([^)\s]+)(?:\s+[^)]*)?\)/g)].map(p=>{try{const g=new URL(p[1],u);return g.origin===u.origin?decodeURIComponent(g.pathname.slice(1)):""}catch{return""}}).filter(p=>e.some(g=>g.id===p));return{...sb(s),section:n,markdown:a.slice(c,d),truncated:d<a.length,cursor:d<a.length?`${l}:${d}`:null,sections:i.map(p=>({id:p.id,title:p.title})),links:[...new Set(f)]}}function NP(e){return["search_help","read_help"].map(t=>{const n=t==="search_help"?"query":"id";return{name:t,effect:"read",description:t==="search_help"?"Search local help by document, topic or exact component ID. Returns section IDs and explicit truncation.":"Read a document or section. Follow cursor with the same id and section until truncated is false.",parameters:{type:"object",properties:{[n]:{type:"string"},...t==="read_help"?{section:{type:"string"},cursor:{type:"string"}}:{}},required:[n],additionalProperties:!1},validate:o=>{if(!(Object.keys(o).every(i=>(t==="read_help"?["id","section","cursor"]:["query"]).includes(i)&&typeof o[i]=="string"&&o[i].length<=500)&&typeof o[n]=="string"))return!1;if(t==="read_help")try{ab(e,o.id,o.section,o.cursor)}catch(i){return{ok:!1,retryable:!0,errors:[{code:"help_location",path:"$",message:i.message,suggestion:"Use search_help to find a current document and section."}]}}return!0},run:o=>t==="search_help"?rb(e,o.query):ab(e,o.id,o.section,o.cursor)}})}const cb=Object.freeze({prompt:16e3,transcript:96e3,tools:96e3,request:22e4}),lb=e=>new TextEncoder().encode(e).byteLength;class OP extends Error{constructor(t,n,o){super(`MIO ${t} budget exceeded (${n}/${o} UTF-8 bytes). Use a compact draft reference or smaller edit; no document was truncated.`),this.scope=t,this.usedBytes=n,this.limitBytes=o,this.code="mio_request_budget",this.name="MioBudgetError",this.remainingBytes=Math.max(0,o-n)}}const DP=e=>JSON.stringify(e).replace(/\//g,"\\/").replace(/[^\x00-\x7f]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`);function db(e){const t={prompt:e.prompt,transcript:e.transcript,tools:DP(e.tools),request:JSON.stringify(e)};for(const n of Object.keys(t)){const o=lb(t[n]);if(o>cb[n])throw new OP(n,o,cb[n])}}function Wr(e,t){return new Mr([{code:e,path:"$",message:t}])}function ub(e){if(!Array.isArray(e)||!e.length||e.length>20)throw new Error("Invalid MIO validation feedback.");return e.map(t=>{if(!t||typeof t.code!="string"||typeof t.path!="string"||typeof t.message!="string")throw new Error("Invalid MIO validation feedback.");return{code:t.code.slice(0,80),path:t.path.slice(0,300),message:t.message.slice(0,1e3),...typeof t.suggestion=="string"?{suggestion:t.suggestion.slice(0,1e3)}:{}}})}function RP(e,t,n){if(typeof e!="string"||lb(e)>96e3)throw Wr("argument_budget","Provide JSON arguments within 96,000 UTF-8 bytes; use a draft reference or a smaller patch for larger documents.");let o;try{o=JSON.parse(e)}catch{throw Wr("invalid_json","Provide a valid JSON object for the tool arguments.")}if(!o||typeof o!="object"||Array.isArray(o))throw Wr("invalid_envelope","Expected an object containing the advertised argument properties.");const s=t.validate(o,n);if(s===!1)throw Wr("invalid_arguments",`Arguments do not satisfy ${t.name}; check its schema and live options.`);if(s!==!0&&s?.ok!==!0)throw!s||s.ok!==!1||typeof s.retryable!="boolean"?new Error("Invalid MIO validator result."):new Mr(ub(s.errors),s.retryable);return o}function Ad(e){return Array.isArray(e)?`[${e.map(Ad).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Ad(e[t])}`).join(",")}}`:JSON.stringify(e)}function xP(){let e=[];return{read:()=>e.map(t=>({...t,...t.actionIds?{actionIds:[...t.actionIds]}:{}})),write:t=>{e=t.slice(-40).map(n=>({...n,...n.actionIds?{actionIds:[...n.actionIds]}:{}}))},clear:()=>{e=[]}}}class MP{constructor(t,n,o,s=xP()){this.context=t,this.transport=n,this.active=o,this.conversation=s,this.disposed=!1,this.pending=null,this.abortTurn=null,this.thinkingListeners=new Set,this.operations=new IP(t),this.responseActions=new CP(t,()=>!this.disposed&&o(),()=>s.read())}subscribeThinking(t){return this.thinkingListeners.add(t),t(this.pending!==null),()=>{this.thinkingListeners.delete(t)}}notifyThinking(){for(const t of this.thinkingListeners)ho(t,this.pending!==null)}cancel(){this.responseActions.cancel(),this.pending?.abort(),this.abortTurn?.(),this.abortTurn=null,this.pending=null,this.notifyThinking()}dispose(){this.disposed=!0,this.responseActions.dispose(),this.cancel(),this.conversation.clear(),this.thinkingListeners.clear()}async ask(t){if(this.disposed)throw new Error("This MIO window session is disposed.");if(this.pending)throw new Error("MIO is already answering.");if(!t.trim()||t.length>4e3)throw new Error("Write a message of 1–4000 characters.");const n=new AbortController,{signal:o}=n,s=crypto.randomUUID();let i=0,r=0,a=0,l=!1,c,d="failed",u=null;const f=()=>({turnId:s,windowId:this.context.windowId,revision:c,signal:o,limits:ft,validationFailures:r,validationRemaining:Math.max(0,ft.validationFailures-r)}),p=()=>{const P=this.operations.list().filter(B=>B.turnId===s);return{...f(),status:d,reads:a,rejected:r,calls:i,confirmedWrites:P.filter(B=>B.status==="confirmed").length,unknownWrites:P.filter(B=>B.effect==="write"&&(B.status==="unknown"||B.status==="running")).length}},g=()=>{l||(l=!0,d="aborted",u?.context.effect==="write"&&this.operations.record(u.context,u.name,"unknown"),ho(this.context.onTurnAbort,f()))},h=()=>{if(o.aborted||!this.active())throw n.abort(),g(),new DOMException("The window context changed.","AbortError")};this.pending=n,this.abortTurn=g,this.notifyThinking();const m=[...this.conversation.read().slice(-39),{role:"user",text:t,id:crypto.randomUUID()}];this.conversation.write(m),this.responseActions.prune();const E=P=>{const B={role:"assistant",text:P,id:crypto.randomUUID()},F=this.responseActions.create(Object.freeze({messageId:B.id,summary:Object.freeze(p()),operations:Object.freeze(this.operations.list().filter(K=>K.turnId===s).map(K=>Object.freeze(K)))}));if(F.length&&(B.actionIds=F),this.disposed||this.pending!==n){this.responseActions.prune();return}this.conversation.write([...m,B].slice(-40)),this.responseActions.prune()},S=[],R=new Set,$=new Map,_=()=>[...NP(this.context.documents),...this.context.abilities()].filter(P=>!P.allowed||P.allowed()),M=(P,B,F,K)=>{r++,this.operations.record(B,F,"rejected");const Z=ub(P.errors);if(S.push(JSON.parse(JSON.stringify({name:F,callId:B.callId,effect:"none",status:"rejected",result:{effect:"none",status:"rejected",errors:Z,data:K,retryable:P.retryable,validationRemaining:Math.max(0,ft.validationFailures-r)}}))),!P.retryable)throw new Error(`MIO validation is terminal: ${P.message}`);if(r>=ft.validationFailures)throw new Error("MIO validation retry budget exhausted; no further candidates will run in this turn.")};try{h(),c=this.context.revision?.(),ho(this.context.onTurnBegin,f());for(let P=0;P<ft.rounds;P++){h();const B=_();if(new Set(B.map(L=>L.name)).size!==B.length)throw new Error("MIO ability names must be unique within a window.");c=this.context.revision?.();const F=await this.context.prompt();h();const K={messages:m.slice(-20).map(({role:L,text:x})=>({role:L,text:x})),help:rb(this.context.documents,t),outcomes:S},Z={prompt:F,transcript:JSON.stringify(this.context.compactHistory?this.context.compactHistory(structuredClone(K),f()):K),tools:B.map(({name:L,description:x,parameters:j,effect:V})=>({name:L,description:`[Effect: ${V??"write"}] ${x}`,parameters:j}))};db(Z),h();const Y=await this.transport(Z,o);if(h(),!Array.isArray(Y.calls)||Y.calls.length>ft.calls)throw new Error("Invalid MIO tool response.");if(!Y.calls.length){if(typeof Y.message!="string"||!Y.message.trim())throw new Error("MIO returned no answer.");return d="completed",E(Y.message),Y.message}for(const L of Y.calls){if(h(),i>=ft.calls)throw new Error("MIO reached its action limit. Review the changes before continuing.");i++;const x=_().find(D=>D.name===L.name);if(!x||!B.some(D=>D.name===L.name))throw new Error("MIO requested an unavailable action.");c=this.context.revision?.();const j=`${s}:${i}`,V={...f(),callId:j,idempotencyKey:j,effect:x.effect??"write"};let J;try{J=RP(L.arguments,x,V)}catch(D){if(D instanceof Mr){M(D,V,L.name);break}throw D}const O=Ad([L.name,J]);if(V.effect==="write"&&R.has(O))throw new Error("MIO repeated an action; stopped to avoid replaying a write.");if(V.effect!=="write"){const D=($.get(O)??0)+1;if($.set(O,D),D>ft.repeatedReads)throw new Error("MIO repeated-read budget exhausted.")}if(h(),x.allowed&&!x.allowed())throw new Error("MIO requested an unavailable action.");V.effect==="write"&&R.add(O),u={context:V,name:L.name},this.operations.record(V,L.name,"running");try{if(h(),x.allowed&&!x.allowed())throw new Error("MIO requested an unavailable action.")}catch(D){throw u=null,this.operations.record(V,L.name,"rejected"),D}let T;try{T=await x.run(J,o,V)}catch(D){throw this.operations.record(V,L.name,V.effect==="write"?"unknown":"rejected"),u=null,D}const W=ob(T);if(W?.effect==="none"&&W.status==="rejected"){this.operations.record(V,L.name,"rejected"),u=null,R.delete(O),h();const D=x.history?x.history({name:L.name,callId:j,args:J,result:W},V):W.data;M(new Mr(W.errors,W.retryable),V,L.name,D);break}if(W?.effect==="none"&&W.status==="completed")this.operations.record(V,L.name,"completed"),u=null;else if(V.effect==="write"){const D=!W&&!!T&&typeof T=="object"&&T.saved===!0,k=W?.effect==="write"&&W.status==="confirmed"?W.receipt:void 0;if(this.operations.record(V,L.name,k||D?"confirmed":"unknown",k??(D?j:void 0)),u=null,!k&&!D)throw new Error("MIO write outcome is unknown; inspect its status before making another change.")}else this.operations.record(V,L.name,"completed"),V.effect==="read"&&a++,u=null;h();const v={name:L.name,callId:j,args:J,result:T},I=x.history?x.history(v,V):{result:T},N=this.operations.list().find(D=>D.callId===j);S.push(JSON.parse(JSON.stringify({...I,name:L.name,callId:j,effect:W?.effect??V.effect,status:N?.status,receipt:N?.receipt})))}}throw new Error("MIO reached its action limit. Review the changes before continuing.")}catch(P){if(this.pending===n){const B=P instanceof Error?P.message:String(P);E(`${B} ${AP(p())}`)}throw P}finally{ho(this.context.onTurnEnd,p()),this.pending===n&&(this.pending=null,this.abortTurn=null,this.notifyThinking())}}}function WP(e){return async(t,n)=>{db(t);const o=window.wp?.os?.config;if(!o?.aiSearchUrl||!o.restNonce)throw new Error("Enable the AI assistant in Preferences → Features and connect a provider.");const s=o.aiSearchUrl.replace(/\/ai\/search(?=\?|$)/,"/mio/turn");if(s===o.aiSearchUrl)throw new Error("MIO transport URL is unavailable.");const i=await Le(s,{method:"POST",credentials:"same-origin",cache:"no-store",signal:n,headers:{"Content-Type":"application/json","X-WP-Nonce":o.restNonce},body:JSON.stringify(t)},{windowId:e,source:"mio/window"}),r=await i.json();if(!i.ok)throw new Error(r.message||"MIO could not reach the AI provider.");return r}}class PP{constructor(t){this.options=t,this.residents=new Map,this.attachmentObserver=new MutationObserver(()=>{for(const n of this.residents.values())(!n.context.host.isConnected||!n.frame.isConnected)&&n.dispose?.()}),this.owner=null,this.chat=null,this.chatPlacement=null,this.thinkingOwner=null,this.revision=0,this.transitioning=!1,this.targetLayer=null,this.moving=Promise.resolve(),this.animation=null,this.deskPosition=null;for(const n of["os-window-focused","os-window-closed"])document.addEventListener(n,()=>this.refresh());for(const n of[y.WINDOW_MINIMIZED,y.WINDOW_RESTORED,y.DESKTOP_SWITCHED,y.WINDOW_DESKTOP_CHANGED])ee(n,"openstation/mio-residency",()=>this.refresh())}canChat(){return this.options.enabled()&&(this.options.chatAvailable?.()??!0)}getWindowId(){return this.owner?.id??null}register(t,n){const o=document.getElementById(`wp-window-${t}`),s=o?.querySelector(".os-window__body");if(!o||!s||!n.host.isConnected||!s.contains(n.host)||!n.title.trim()||typeof n.prompt!="function")throw new Error("MIO requires an explicit context belonging to a live window body.");if(this.residents.has(t))throw new Error("This window already registered MIO. Dispose its lease before replacing it.");const i=document.createElement("div");i.className="os-mio-residence",i.hidden=!0,o.appendChild(i);const r=()=>{i.style.top=`${s.offsetTop}px`,i.style.left=`${s.offsetLeft}px`,i.style.width=`${s.clientWidth}px`,i.style.height=`${s.clientHeight}px`},a=new ResizeObserver(r);a.observe(s),r();const l=document.createElement("os-button");l.className="os-mio-chat-launcher",l.hidden=!this.canChat(),l.setAttribute("variant","ghost"),l.textContent=b("Ask MIO"),l.setAttribute("aria-haspopup","dialog"),i.appendChild(l);const c={enabled:n.enabled!==!1,thinking:!1,calloutVisible:!1,id:t,context:n,frame:i,button:l,observer:a,session:new MP({...n,windowId:t},WP(t),()=>this.canChat()&&c.enabled&&this.owner===c&&this.options.focused()===t&&n.host.isConnected)};c.callout=new SP(n.host,i,this.options.handle,p=>{c.calloutVisible=p,this.syncVisibility()}),this.residents.set(t,c),this.attachmentObserver.observe(document.body,{childList:!0,subtree:!0});const d=p=>{this.residents.get(t)!==c||c.enabled===p||(c.enabled=p,p||c.session.cancel(),this.refresh(),C("os.mio.window-enabled-changed",{windowId:t,enabled:p}))};c.toggle=_P(t,()=>({enabled:c.enabled,available:this.options.enabled(),thinking:c.thinking}),()=>d(!c.enabled)),c.session.subscribeThinking(p=>{c.thinking=p,c.toggle?.update(),this.syncThinking()});const u=async()=>{if(!n.host.isConnected||!this.canChat()||!c.enabled||this.options.focused()!==t||this.residents.get(t)!==c||(await this.options.ready(),await window.wp?.os?.loadComponents(["os-button","os-textarea"]),await this.moving,!n.host.isConnected||!this.canChat()||!c.enabled||this.owner!==c||this.options.focused()!==t))return;this.closeChat(),this.chat=window.openStationMountMioChat?.(i,n.title,c.session,()=>this.closeChat(!0))??null,l.hidden=this.chat!==null,c.callout?.setActive(!1),this.syncVisibility();const p=i.querySelector(".os-mio-chat");p&&(this.chatPlacement=kP(i,p,this.options.handle))};l.addEventListener("click",()=>{u().catch(p=>{l.textContent=p instanceof Error?p.message:b("MIO could not open.")})});const f=()=>{if(this.residents.get(t)!==c)return;this.residents.delete(t),c.session.dispose(),c.callout?.dispose(),c.toggle?.dispose(),a.disconnect(),this.refresh();const p=this.options.layer();p&&i.contains(p)&&(this.options.shell.appendChild(p),delete p.dataset.mioWindow,delete p.dataset.mioThinking),i.remove(),this.residents.size||this.attachmentObserver.disconnect()};return c.dispose=f,this.refresh(),{showCallout:p=>c.callout?.show(p),clearCallout:()=>c.callout?.clear(),isEnabled:()=>c.enabled,setEnabled:d,openChat:u,getOperations:()=>c.session.operations.list(),inspectOperation:(p,g=new AbortController().signal)=>c.session.operations.inspect(p,g),dispose:f}}closeChat(t=!1){this.chatPlacement?.close(t),this.chatPlacement=null,this.chat?.destroy(),this.chat=null,this.owner&&(this.owner.button.hidden=!this.canChat(),t&&(this.owner.button.shadowRoot?.querySelector("button")??this.owner.button).focus()),this.syncCallouts()}syncVisibility(){const t=this.options.layer();t&&(t.dataset.mioVisible=String(this.owner?!!this.chat||this.owner.calloutVisible:this.options.wallpaperVisible?.()??!0))}syncCallouts(){for(const t of this.residents.values())t.callout?.setActive(this.options.enabled()&&t.enabled&&this.owner===t&&!this.chat&&!this.transitioning);this.syncVisibility()}syncThinking(){const t=this.owner?.thinking&&this.options.enabled()&&this.owner.enabled?this.owner.id:null,n=this.options.layer();n&&(n.dataset.mioThinking=String(t!==null)),this.thinkingOwner!==t&&(this.thinkingOwner&&C("os.mio.thinking-changed",{windowId:this.thinkingOwner,thinking:!1}),this.thinkingOwner=t,t&&C("os.mio.thinking-changed",{windowId:t,thinking:!0}))}refresh(){const t=this.options.enabled();!this.canChat()&&this.chat&&this.closeChat();for(const c of this.residents.values())c.toggle?.update(),c.button.hidden=!this.canChat()||c===this.owner&&this.chat!==null,this.canChat()||c.session.cancel();if(!t)for(const c of this.residents.values())c.frame.hidden=!0;const n=t?this.options.focused():null,o=n?this.residents.get(n)??null:null,s=o?.enabled&&o.context.host.isConnected?o:null,i=this.options.layer();if(this.owner===s&&i===this.targetLayer){this.syncVisibility();return}this.targetLayer=i;const r=this.owner;this.transitioning=!0,this.closeChat(),r?.session.cancel(),this.owner=s,this.syncCallouts(),this.syncThinking();const a=++this.revision;this.animation?.cancel(),this.animation=null,this.options.handle()?.setAnimating(!1),s&&i&&!i.dataset.mioWindow&&(this.deskPosition=this.options.handle()?.getPosition()??null),s&&(s.frame.hidden=!1,s.button.hidden=!this.canChat());const l=async()=>{const c=async(d,u)=>{if(!i?.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;const f=this.options.handle()?.getPosition(),p=i.getBoundingClientRect();i.style.transformOrigin=f?`${f.x-p.left}px ${f.y-p.top}px`:"50% 50%",this.animation=i.animate([{transform:`scale(${d})`,opacity:d},{transform:`scale(${u})`,opacity:u}],{duration:150,easing:"ease-in-out",fill:"forwards"}),await this.animation.finished};try{if(await c(1,0),a!==this.revision)return;for(const d of this.residents.values())d.frame.hidden=d!==s;if(i){i.style.opacity="0",this.animation?.cancel(),this.animation=null,(s?.frame??this.options.shell).appendChild(i),s?(i.dataset.mioWindow=s.id,i.dataset.mioThinking=String(s.thinking)):(delete i.dataset.mioWindow,delete i.dataset.mioThinking);const d=i.getBoundingClientRect(),u=s?{x:d.right-82,y:d.bottom-95}:this.deskPosition;u&&this.options.handle()?.setPosition(u.x,u.y)}C("os.mio.owner-changed",{windowId:s?.id??null,previousWindowId:r?.id??null}),this.options.handle()?.setAnimating(!document.hidden),await c(0,1)}catch{}finally{a===this.revision&&(this.animation?.cancel(),this.animation=null,i?.style.removeProperty("opacity"),this.transitioning=!1,this.syncCallouts(),this.options.handle()?.setAnimating(!document.hidden))}};this.moving=l()}}const fb={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}},oe={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 se(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function Cd(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 pb(e,t){return typeof e=="boolean"?e:t}const $P=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function UP(e,t){return $P.includes(e)?e:t}function Ps(e,t=fb){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:se(o.radius,t.appearance.radius,oe.radius),bodyColor:Cd(o.bodyColor,t.appearance.bodyColor),bodyAlpha:se(o.bodyAlpha,t.appearance.bodyAlpha,oe.bodyAlpha),hueStart:se(o.hueStart,t.appearance.hueStart,oe.hueStart),hueSpan:se(o.hueSpan,t.appearance.hueSpan,oe.hueSpan),hueDrift:se(o.hueDrift,t.appearance.hueDrift,oe.hueDrift),hueLoop:pb(o.hueLoop,t.appearance.hueLoop),hueAngle:se(o.hueAngle,t.appearance.hueAngle,oe.hueAngle),hueSpin:se(o.hueSpin,t.appearance.hueSpin,oe.hueSpin),saturation:se(o.saturation,t.appearance.saturation,oe.saturation),lightness:se(o.lightness,t.appearance.lightness,oe.lightness),iridescence:se(o.iridescence,t.appearance.iridescence,oe.iridescence),outlineWidth:se(o.outlineWidth,t.appearance.outlineWidth,oe.outlineWidth),linerWidth:se(o.linerWidth,t.appearance.linerWidth,oe.linerWidth),linerColor:Cd(o.linerColor,t.appearance.linerColor),glow:se(o.glow,t.appearance.glow,oe.glow),glowBlur:pb(o.glowBlur,t.appearance.glowBlur),eyeColor:Cd(o.eyeColor,t.appearance.eyeColor),eyeScale:se(o.eyeScale,t.appearance.eyeScale,oe.eyeScale)},r={points:Math.round(se(s.points,t.physics.points,oe.points)),shapePreset:UP(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(se(s.shapeLobes,t.physics.shapeLobes,oe.shapeLobes)),shapeAmount:se(s.shapeAmount,t.physics.shapeAmount,oe.shapeAmount),shapeAngle:se(s.shapeAngle,t.physics.shapeAngle,oe.shapeAngle),shapeShuffle:se(s.shapeShuffle,t.physics.shapeShuffle,oe.shapeShuffle),radialStiffness:se(s.radialStiffness,t.physics.radialStiffness,oe.radialStiffness),edgeStiffness:se(s.edgeStiffness,t.physics.edgeStiffness,oe.edgeStiffness),bendStiffness:se(s.bendStiffness,t.physics.bendStiffness,oe.bendStiffness),pressure:se(s.pressure,t.physics.pressure,oe.pressure),damping:se(s.damping,t.physics.damping,oe.damping),airDamping:se(s.airDamping,t.physics.airDamping,oe.airDamping),magnetStrength:se(s.magnetStrength,t.physics.magnetStrength,oe.magnetStrength),magnetRange:se(s.magnetRange,t.physics.magnetRange,oe.magnetRange),magnetGrip:se(s.magnetGrip,t.physics.magnetGrip,oe.magnetGrip),magnetDamping:se(s.magnetDamping,t.physics.magnetDamping,oe.magnetDamping),floatAmplitude:se(s.floatAmplitude,t.physics.floatAmplitude,oe.floatAmplitude),floatSpeed:se(s.floatSpeed,t.physics.floatSpeed,oe.floatSpeed),idleWobble:se(s.idleWobble,t.physics.idleWobble,oe.idleWobble),idleWobbleSpeed:se(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,oe.idleWobbleSpeed),speedStretch:se(s.speedStretch,t.physics.speedStretch,oe.speedStretch),friction:se(s.friction,t.physics.friction,oe.friction),restitution:se(s.restitution,t.physics.restitution,oe.restitution),dragStiffness:se(s.dragStiffness,t.physics.dragStiffness,oe.dragStiffness),throwBoost:se(s.throwBoost,t.physics.throwBoost,oe.throwBoost),minStretch:se(s.minStretch,t.physics.minStretch,oe.minStretch),maxStretch:se(s.maxStretch,t.physics.maxStretch,oe.maxStretch),minAngularGap:se(s.minAngularGap,t.physics.minAngularGap,oe.minAngularGap),dragMaxAccel:se(s.dragMaxAccel,t.physics.dragMaxAccel,oe.dragMaxAccel),limitIterations:Math.round(se(s.limitIterations,t.physics.limitIterations,oe.limitIterations)),subStep:se(s.subStep,t.physics.subStep,oe.subStep),maxSubSteps:Math.round(se(s.maxSubSteps,t.physics.maxSubSteps,oe.maxSubSteps))};return{appearance:i,physics:r}}const hb="desktop-mode-mio-position",mb="os-mio",BP="os-mio-toggle";class FP{constructor(t){this.layer=null,this.handle=null,this.mounting=null,this.parked=null,this.generation=0,this.loading=null,this.look=Za(),this.options=t,this.residency=new PP({shell:t.shell,focused:t.focusedWindow??(()=>null),layer:()=>this.layer,handle:()=>this.handle,enabled:()=>this.enabled,chatAvailable:t.chatAvailable,wallpaperVisible:t.wallpaperVisible,ready:()=>this.mount()}),this.enabled=t.enabled,this.look=Vp(t.savedLook),this.config=this.resolveConfig()}boot(){this.enabled&&this.mount()}syncEnabled(t){this.setEnabled(t,!1),this.residency.refresh()}refreshWindowAvailability(){this.residency.refresh()}api(){return{registerWindow:(t,n)=>this.residency.register(t,n),getWindowId:()=>this.residency.getWindowId(),isEnabled:()=>this.enabled,enable:()=>this.setEnabled(!0),disable:()=>{this.setEnabled(!1)},toggle:()=>this.setEnabled(!this.enabled),getPosition:()=>this.handle?.getPosition()??null,setPosition:(t,n)=>this.handle?.setPosition(t,n),getConfig:()=>this.config,setConfig:t=>{this.config=Ps(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=gA(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=Ps({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=Za(),this.config=this.resolveConfig(),this.handle?.applyConfig(this.config),this.commitLook()}}}async setEnabled(t,n=!0){t!==this.enabled&&(this.enabled=t,this.generation++,n&&this.options.persist(t),C(t?"os.mio.enabled":"os.mio.disabled",{}),C(y.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount())}resolveConfig(){const t=Ps(this.options.serverConfig,fb),n=X("os.mio.config",t),o=Ps(n,t);return Ps({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(mb);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=mb,n.className="os-mio",n.dataset.mioVisible=String(this.options.wallpaperVisible?.()??!0),n.setAttribute("aria-hidden","true"),this.options.shell.appendChild(n),this.layer=n,n}mount(){if(this.mounting?.generation===this.generation)return this.mounting.promise;const t=this.mountInstance().finally(()=>{this.mounting?.promise===t&&(this.mounting=null)});return this.mounting={generation:this.generation,promise:t},t}async mountInstance(){const t=this.generation;if(this.handle)return;const n=this.parked;if(n){this.parked=null,n.layer.style.removeProperty("display"),n.handle.applyConfig(this.config),n.handle.setAnimating(!0),this.handle=n.handle,this.layer=n.layer,this.residency.refresh();return}try{await this.loadBundle()}catch(i){console.warn("[desktop-mode/mio] bundle failed to load.",i);return}if(t!==this.generation||!this.enabled)return;const o=window.openStationMountMio;if(typeof o!="function"){console.warn("[desktop-mode/mio] bundle loaded but did not publish window.openStationMountMio.");return}const s=await o({host:this.ensureLayer(),config:this.config,position:HP(),savePosition:i=>{this.residency.getWindowId()||gb(i)}});if(!s){this.layer?.remove(),this.layer=null;return}if(t!==this.generation||!this.enabled){const i=this.layer;this.layer=null,s.setAnimating(!1),i?(i.style.display="none",this.parked={handle:s,layer:i}):s.destroy();return}this.handle=s,this.residency.refresh()}unmount(){const t=this.residency.getWindowId()!==null;this.residency.closeChat();const n=this.handle,o=this.layer;if(this.handle=null,this.layer=null,this.residency.refresh(),!n||!o){o?.remove();return}const s=n.getPosition();s&&!t&&gb(s),n.setAnimating(!1),o.style.display="none",this.parked={handle:n,layer:o}}loadBundle(){if(typeof window.openStationMountMio=="function")return Promise.resolve();if(!this.loading){if(!this.options.bundleUrl)return Promise.reject(new Error("No Mio bundle URL in the shell config."));this.loading=fe(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function HP(){try{const e=window.localStorage.getItem(hb);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 gb(e){try{window.localStorage.setItem(hb,JSON.stringify(e))}catch{}}const GP='<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>',zP=2400,wb="os-notch";function jP(e,t){document.getElementById(wb)?.remove();const n=document.createElement("button");n.type="button",n.id=wb,n.className="os-notch",n.setAttribute("aria-label",b("Open the site assistant"));const o=document.createElement("span");o.className="os-notch__glyph",o.setAttribute("aria-hidden","true"),o.innerHTML=GP,n.appendChild(o);const s=document.createElement("span");s.className="os-notch__label",s.setAttribute("aria-hidden","true"),s.textContent=b("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)},zP)};return e.appendChild(n),{say:a,destroy:()=>{r!==null&&window.clearTimeout(r),n.remove()}}}const Ld="--os-admin-bar-height",VP="wpadminbar";function KP(e){const t=e.getBoundingClientRect();return t.height<=0||t.top<0?null:Math.round(t.bottom*100)/100}function qP(e={}){const t=e.bar===void 0?document.getElementById(VP):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=KP(t);c!==s&&(s=c,c===null?n.style.removeProperty(Ld):n.style.setProperty(Ld,`${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(Ld)}}}const YP="New: ",XP=b("Edit this workspace…"),ZP=b("New desktop…"),yb=b("Keep this desk"),vb=b("Make this workspace open the way the desk is now — these windows where they are, these widgets, these apps.");function JP(e,t,n=()=>{},o=()=>!1){const s=()=>{const i=e.manager.getActiveDesktopId(),r=c=>e.manager.getAll().filter(d=>(d.config.desktopId||i)===c).length,a=c=>c===i?b("You are here"):ae(b("%d open"),r(c)),l=e.manager.getDesktops().map(c=>({label:c.label,description:a(c.id),icon:c.profile?.icon||"dashicons-desktop",run:()=>e.manager.switchDesktop(c.id)}));for(const c of Oo())l.push({label:`${YP}${c.label}`,description:c.description,icon:c.icon,run:()=>{Ma(e,{preset:c.id})}});return l.push({label:ZP,description:b("Blank, or set up for a job — the wizard asks."),icon:"dashicons-plus-alt2",run:n}),l.push({label:XP,description:b("Name, apps, widgets, look and windows."),icon:"dashicons-admin-generic",run:()=>t(e.manager.getActiveDesktopId())}),l.push({label:yb,description:vb,icon:"dashicons-saved",run:()=>{o(e.manager.getActiveDesktopId())}}),l};Hn({slug:"keep-desk",label:yb,description:vb,icon:"dashicons-saved",run(i,r){if(!o(e.manager.getActiveDesktopId()))return b("There is no desk to keep.");r.close()}}),Hn({slug:"workspace",label:b("Workspace"),description:b("Switch, create or edit a workspace."),hint:"[name]",icon:"dashicons-desktop",suggest(i){const r=i.trim().toLowerCase();return s().filter(c=>!r||c.label.toLowerCase().includes(r)).slice(0,12).map(c=>({value:c.label,label:c.label,description:c.description,icon:c.icon}))},run(i,r){const a=i.trim();if(!a)return b("Type a workspace name to switch to it, or pick a template to create one.");const l=a.toLowerCase(),c=s(),d=c.find(u=>u.label.toLowerCase()===l)??c.find(u=>u.label.toLowerCase().includes(l));if(!d)return ae(b("No workspace matching **%s** — try `/workspace` alone to see them all."),a);d.run(),r.close()}})}let bb=0;function Eb(){return window.openStationWorkspaceWizard??null}function QP(){return window.openStationConfig?.workspaceWizardBundleUrl??""}function _b(e){const t=Eb();if(t){t.openWorkspaceWizard(e);return}const n=QP();if(!n)return;const o=++bb;fe(n).then(()=>{o===bb&&Eb()?.openWorkspaceWizard(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] workspace-wizard bundle failed to load; wizard suppressed:",s)})}function e$(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=>qt(e.manager,i),setProfile:(i,r)=>Rn(e,i,r),create:i=>Ma(e,i),switchTo:i=>e.manager.switchDesktop(i),arrange:i=>Uf(e.manager,i),provision:(i,r)=>Wa(e,i,r),capture:i=>Pa(e.manager,i),captureAppearance:n,edit:t,openCreator:o,saveDesk:s,presets:Oo,registerPreset:xf,unregisterPreset:Ra}}const Sb="desktop-mode/workspace-presets";let Pr=null;const wn=new Set;function t$(e){const t=Mk.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:$f(e.appearance??{}),windows:Array.isArray(e.windows)?e.windows.map(n=>({...n})):[],layout:t,order:typeof e.order=="number"?e.order:0}}function n$(e){if(!Array.isArray(e))return;const t=new Set(e.map(o=>o.id).filter(Boolean)),n=new Set(Oo().filter(o=>!wn.has(o.id)).map(o=>o.id));for(const o of e)!o?.id||n.has(o.id)||(xf(t$(o)),wn.add(o.id));for(const o of[...wn])t.has(o)||(Ra(o),wn.delete(o));Pr=t}function o$(){return pt(y.WORKSPACE_PRESETS,Sb,e=>Pr?e.filter(t=>wn.has(t.id)||Pr?.has(t.id)):e),()=>{oE(y.WORKSPACE_PRESETS,Sb),Pr=null;for(const e of wn)Ra(e);wn.clear()}}function s$(){return document.fullscreenElement!==null}function i$(){if(s$()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function kb(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 r$(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(kb(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 a$(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(kb(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 c$(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(r$(n.contextual)),n.general&&t.appendChild(a$(n.general)),e.appendChild(t)}const Td="openstation-shortcuts",l$=`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 d$(e){e({id:Td,baseId:Td,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:l$,native:!0,render:c$,width:760,height:560,minWidth:480,minHeight:360})}const Ib="openstation-rebrand",u$=1200,f$="a[href], button:not([disabled])";async function p$(e){const t=e.seenIntrosUrl;if(t)try{await Le(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:Ib})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function h$(){const e=document.createElement("div");e.className="os-announce",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","os-announce-title"),e.setAttribute("aria-describedby","os-announce-desc");const t=document.createElement("div");t.className="os-announce__card",e.appendChild(t);const n=document.createElement("div");n.className="os-announce__hero",t.appendChild(n);const o=document.createElement("span");o.className="os-announce__eyebrow";const s=document.createElement("span");s.className="os-announce__eyebrow-dot",s.setAttribute("aria-hidden","true"),o.appendChild(s),o.appendChild(document.createTextNode(b("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=b("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=b("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",t.appendChild(a);const l=document.createElement("p");l.id="os-announce-desc",l.textContent=b("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),a.appendChild(l);const c=document.createElement("p");c.textContent=b("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=b("Everything is already set up. You don't need to install any new plugins, so you can keep using the same features as before."),a.appendChild(d);const u=document.createElement("div");u.className="os-announce__actions",t.appendChild(u);const f=document.createElement("button");return f.type="button",f.className="os-announce__btn os-announce__btn--primary",f.dataset.rebrandDismiss="",f.textContent=b("Got it"),u.appendChild(f),e}async function m$(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(Ib))return;await new Promise(c=>window.setTimeout(c,u$));const n=h$(),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?.(),p$(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(f$));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 g$="(display-mode: standalone)";function Ab(e,t){return e||t?.standalone===!0?"standalone":"browser"}const w$=["auto","desktop","mobile"],$r={mobile:767,tablet:1024};function Ur(e){return w$.includes(e)?e:"auto"}function y$(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,$r.mobile),s=Math.max(o+1,n(t.tablet,$r.tablet));return{mobile:o,tablet:s}}function Cb(e,t="auto",n=$r){return t==="mobile"?"mobile":t==="desktop"?"desktop":e<=n.mobile?"mobile":e<=n.tablet?"tablet":"desktop"}function v$(e={}){const t=e.root??document.documentElement,n=e.win??window,o=y$({...$r,...e.breakpoints??{}});let s=Ur(e.preference);const i=new Set,r=()=>typeof n.innerWidth=="number"&&n.innerWidth>0?n.innerWidth:Number.POSITIVE_INFINITY;let a=Cb(r(),s,o);zd(t,a);const l=e.nav??(typeof navigator<"u"?navigator:void 0),c=typeof n.matchMedia=="function"?n.matchMedia(g$):null;let d=Ab(!!c?.matches,l);jd(t,d);const u=()=>{d=Ab(!!c?.matches,l),jd(t,d)},f=()=>{const h=Cb(r(),s,o);if(h===a)return;const m={mode:h,previous:a,preference:s};a=h,zd(t,a),C(y.MODE_CHANGED,m),document.dispatchEvent(new CustomEvent("os-mode-changed",{detail:m}));for(const E of i)try{E(m)}catch(S){console.error("[openstation] mode listener threw:",S)}},p=[];if(typeof n.matchMedia=="function")for(const h of[o.mobile,o.tablet]){const m=n.matchMedia(`(max-width: ${h}px)`);typeof m.addEventListener=="function"?m.addEventListener("change",f):typeof m.addListener=="function"&&m.addListener(f),p.push(m)}return c&&(typeof c.addEventListener=="function"?c.addEventListener("change",u):typeof c.addListener=="function"&&c.addListener(u)),{api:{get:()=>a,getPreference:()=>s,getBreakpoints:()=>({...o}),isMobile:()=>a==="mobile",getDisplay:()=>d,isStandalone:()=>d==="standalone",subscribe(h,m){return i.add(h),m?.immediate&&h({mode:a,previous:a,preference:s}),()=>{i.delete(h)}}},setPreference(h){const m=Ur(h);m!==s&&(s=m,f())},dispose(){for(const h of p)typeof h.removeEventListener=="function"?h.removeEventListener("change",f):typeof h.removeListener=="function"&&h.removeListener(f);c&&(typeof c.removeEventListener=="function"?c.removeEventListener("change",u):typeof c.removeListener=="function"&&c.removeListener(u)),i.clear()}}}function b$(e){return Ht(e)||aE(e)}function E$(e={}){const t=e.root??document.documentElement,n=e.doc??document,o=a=>{b$(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 yn="openstation/mobile";function _$(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 S$(e){const{manager:t,mode:n}=e,o=new Map,s=new Map;let i=[];const r=new Set,a=()=>{for(const h of r)h()},l=h=>{if(!n.isMobile())return;const m=t.getById(h);if(!(!m||m.isMinimized()||m.isMaximized()||m.isFullscreen())){if(!o.has(m.id)){const E=m.getSnapshot();o.set(m.id,{x:E.x,y:E.y,width:E.width,height:E.height,state:E.state,unplaced:!1})}m.maximize()}},c=h=>{if(!n.isMobile())return;const m=t.getById(h);if(!m)return;const E=t.getActiveDesktopId(),S=m.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,R]of s)h.has(R)&&t.moveWindowToDesktop(S,R);s.clear();const m=t.getActiveDesktopId(),E=t.getFocused();if(E&&(E.config.desktopId||m)!==m){const S=[...t.getAll()].reverse().find(R=>(R.config.desktopId||m)===m&&!R.isMinimized());S&&t.focus(S)}},u=h=>{const m=me();if(m.width<=0||m.height<=0)return null;const E=12,S=Math.min(Math.round(m.width*.8),1200),R=Math.min(Math.round(m.height*.8),800),$=40+h%8*30;return{x:Math.max(m.x+E,Math.min(m.x+$,m.x+m.width-S-E)),y:Math.max(m.y+E,Math.min(m.y+$,m.y+m.height-R-E)),width:S,height:R}};pt(y.WINDOW_GEOMETRY,yn,(h,m)=>!n.isMobile()||h.state==="minimized"?h:(o.set(m.windowId,{x:h.x,y:h.y,width:h.width,height:h.height,state:h.state??"normal",unplaced:!m.hasSavedGeometry&&!m.callerPinned}),{...h,state:"maximized"}));const f=h=>{const m=h?.windowId;m&&l(m)};ee(y.WINDOW_RESTORED,yn,f),ee(y.WINDOW_UNMAXIMIZED,yn,f),ee(y.WINDOW_OPENED,yn,h=>{const m=h?.windowId;m&&(c(m),l(m))}),ee(y.WINDOW_CLOSED,yn,h=>{const m=h?.windowId;m&&(o.delete(m),s.delete(m))});const p=n.subscribe(h=>{if(h.mode==="mobile"){for(const E of t.getAll())c(E.id),l(E.id);return}if(h.previous!=="mobile")return;d();let m=0;for(const E of t.getAll()){const S=o.get(E.id);if(!(!S||!E.isMaximized())){if(S.unplaced){const R=u(m++);R&&(E._savedGeometry=R)}E.toggleMaximize()}}o.clear()});pt(y.SESSION_SNAPSHOT,yn,h=>{const m=new Set(h.windows.map(R=>R.id)),E=h.windows.map(R=>{const $=o.get(R.id),_=s.get(R.id);return!n.isMobile()||!$&&!_?R:{...R,...$?{x:$.x,y:$.y,width:$.width,height:$.height,state:$.state,...$.unplaced?{unplaced:!0}:{}}:{},..._?{desktopId:_}:{}}}),S=i.filter(R=>!m.has(R.id));return S.length?{...h,windows:[...E,...S]}:{...h,windows:E}});const g={list:()=>i.slice(),forget(h){const m=i.filter(E=>E.id!==h);m.length!==i.length&&(i=m,a())},open(h){if(g.forget(h.id),h.native)return e.openNative(h.id,h.baseId||h.id,{desktopId:h.desktopId,...h.params?{params:h.params}:{}}),void 0;const m=Qi(h.url);t.openNew({id:h.id,baseId:h.baseId||h.id,url:h.url,parentUrl:m?.url??h.url,title:h.title,icon:h.icon||"dashicons-admin-generic",desktopId:h.desktopId,x:h.x,y:h.y,width:h.width,height:h.height,submenu:m?.submenu,selfLabel:m?.selfLabel,multi:!!m?.multi}).then(E=>{for(const 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 ee(y.WINDOW_OPENED,yn,h=>{const m=h?.windowId;m&&g.forget(m)}),{recents:g,trimSessionForMobile(h){const{restore:m,recents:E}=_$(h.session);return i=E,a(),{...h,session:{...h.session,windows:m}}},forcedIds:()=>Array.from(o.keys()),foldedIds:()=>Array.from(s.keys()),dispose(){p(),r.clear()}}}let Br=null;function Nd(){return window.openStationMobile}function k$(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-mobile="1"]'),s=()=>{const a=Nd();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){Nd()?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 I$(e){const t=Nd();return t?Promise.resolve(t):e?(Br||(Br=k$(e).catch(n=>{throw Br=null,n})),Br):Promise.reject(new Error("[openstation] no `mobileBundleUrl` in the shell config — is `mobile[.min].js` built and the config key wired?"))}function A$(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(Uo(i)||Ze(i))return!0;let r;try{r=new URL(i,window.location.origin)}catch{return!1}const a=r.toString(),l=ue(a,n),c=s.menu??Qi(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 C$(){return window.wp?.os?.config??{}}async function L$(e,t){const{restUrl:n,restNonce:o}=C$();if(!n||!e||!(t>0))throw new Error("[openstation] trashByRestPath: missing REST config or target.");const s=await Le(rt(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 T$=ie("desktop-mode/recycle-bin-payload-handlers",()=>({handlers:new Map}));function Lb(){return T$.state.handlers}function N$(e){const t=Lb().get(e.type);return t?t.accept(e.data):!1}function O$(e,t){const n=Lb().get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}const D$=new Set(["user","attachment"]),Od="data-os-trash-drop-active",$s="desktop-mode-recycle-bin",R$=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${$s}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${$s}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${$s}"]`},{id:"recycle-bin-window",selector:"[data-os-recycle-bin-root]"}];let Tb=!1;const Dd=new Map;let Nb=null;function x$(e){return e.payload.type==="desktop-file"}function M$(e){return e.payload.type==="shortcut"}function W$(e){if(!e.kind||!e.ref||!e.restPath||D$.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return Number.isFinite(t)&&t>0}function P$(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:b("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const s=o.data,i=s?.placement;if(!i)return!1;const r=pn(s);return r.length>1?r.every(a=>a.file?.ref!==$s&&a.canTrash!==!1):i.file?.ref===$s?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=br(s);return i.length>0&&i.every(r=>W$(r))}return N$(o)},onEnter:()=>{n.setAttribute(Od,"")},onLeave:()=>{n.removeAttribute(Od)},onDrop:(o,s)=>{if(n.removeAttribute(Od),x$(o)){Zy(pn(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&O$(o,s))&&M$(o)){const r=br(o.payload.data).map(l=>({title:l.title??"",icon:l.icon??"",restPath:l.restPath,kind:l.kind,ref:Number.parseInt(l.ref,10)})).filter(l=>!!l.restPath&&Number.isFinite(l.ref)&&l.ref>0);if(r.length===0)return;const a=r.map(l=>sn(Kg({id:l.ref,type:l.kind,title:l.title,icon:l.icon})));Promise.allSettled(r.map((l,c)=>a[c]?L$(l.restPath,l.ref):Promise.reject(new Error("Item is already moving to Trash.")))).then(l=>{const c=l.filter(p=>p.status==="rejected");for(const p of c)console.error("[openstation] recycle-bin: shortcut trash failed:",p.reason);const d=r.filter((p,g)=>l[g]?.status==="fulfilled").reduce((p,g)=>{var h;return(p[h=g.kind]??(p[h]=[])).push(g.ref),p},{}),u=window.wp?.os?.announceContentChange;for(const[p,g]of Object.entries(d))u?.(p,"trashed",g,"recycle-bin");l.forEach((p,g)=>{a[g]?.finish(p.status==="fulfilled")});const f=r.length-c.length;(f>1||c.length>0)&&de({message:c.length>0?`${f} moved to Trash · ${c.length} could not be moved`:`${f} items moved to Trash`,duration:c.length>0?6e3:4e3})})}}})}function $$(e){if(Tb)return;Tb=!0;const t=()=>{for(const{id:n,selector:o}of R$){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=Dd.get(n);if(!i){r?.deregister(),Dd.delete(n);continue}r&&r.el===i||(r?.deregister(),Dd.set(n,{el:i,deregister:P$(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),ee(y.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),ee(y.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){Nb=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;Nb.observe(n,{childList:!0,subtree:!0})}}function Rd(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function U$(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function Ob(e){return{appliesTo(t){return Rd(t)!==null},accept(t,n){const o=Rd(n);if(!o)return!1;const s=Ry({type:e,data:t});return vM(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:b("Send to agent","desktop-mode"),onDrop(t,n,o){const s=Rd(o);if(!s)return;const i=Ry({type:t.payload.type,data:t.payload.data}),r=U$();!i||!r||SM({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let Db=!1;function B$(){Db||(Db=!0,Is("shortcut",Ob("shortcut")),Is("desktop-file",Ob("desktop-file")))}let Rb=!1,vn=0;function F$(){Rb||(Rb=!0,De.contribute("openstation_files_subscribe",()=>{const e=$t(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:vn,sharesVersion:Or().state.sharesVersion}}),De.subscribe("openstation_files",e=>{H$(e)}))}function H$(e){const t=e.folders??[];for(const i of t)Jl(i,"remote"),i.updatedAtMs>vn&&(vn=i.updatedAtMs);const n=e.placements??[];for(const i of n)Xl(i,"remote"),i.updatedAtMs>vn&&(vn=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])Ql(i,"remote");for(const i of o.placements??[])Ss(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>vn&&(vn=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&$v(s),e.truncated){const i=Array.from($t().hydratedFolders);for(const r of i)Re(r).then(a=>{Pt(r,a.placements)}).catch(()=>{})}}let xb=!1;const G$=[];function z$(){if(xb)return;xb=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||j$()};G$.push(Gn("os.placement.changed",e),Gn("os.shortcut.changed",e),Gn("os.folder.changed",e))}function j$(){Wy().then(t=>{Zl(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from($t().hydratedFolders);for(const t of e)Re(t).then(n=>{Pt(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const Us="os-wallpaper-menu";let mo=null;function Mb(){return mo!==null}let Wb=0;function V$(e,t,n,o={}){Bs();const s=++Wb;Ys(()=>s===Wb,()=>K$(e,t,n,o))}function K$(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,g=typeof f.sort=="number"?f.sort:100;return p!==g?p-g:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(Us),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",Pb(u.icon));const p=Array.isArray(u.children)&&u.children.length>0;p&&f.setAttribute("has-children",""),f.textContent=u.label,f.addEventListener("mouseenter",()=>{if(p){c(u,f);return}l()}),s.appendChild(f)}s.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=i.get(f.id)??null;if(p){if(Array.isArray(p.children)&&p.children.length>0){if(u.stopPropagation(),a&&a.id===p.id){l();return}const g=s.querySelector(`[data-menu-item-id="${p.id}"]`);g&&c(p,g);return}Bs(),p.onClick(new MouseEvent("click"))}});function c(u,f){l();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(Us,`${Us}--flyout`),p.dataset.parentId=u.id;const g=(u.children??[]).slice().sort((h,m)=>{const E=typeof h.sort=="number"?h.sort:100,S=typeof m.sort=="number"?m.sort:100;return E!==S?E-S:h.label.localeCompare(m.label)});for(const h of g){const m=document.createElement("os-context-menu-option");m.dataset.menuItemId=h.id,m.setAttribute("value",h.id),h.icon&&m.setAttribute("icon",Pb(h.icon)),h.disabled&&m.setAttribute("disabled",""),h.checked&&m.setAttribute("checked",""),m.textContent=h.label,m.addEventListener("os-context-menu-pick",E=>{E.stopPropagation(),Bs(),h.onClick(new MouseEvent("click"))}),p.appendChild(m)}document.body.appendChild(p),r=p,a=u,Xw(p,f)}e.appendChild(s),mo=s,El(s);const d=qw(s,{close:()=>Bs(),siblingSelectors:[`.${Us}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),C("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function Bs(){mo&&(document.querySelectorAll(`.${Us}--flyout`).forEach(e=>e.remove()),mo.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),mo.remove(),mo=null,C("os.wallpaper-menu.closed",{}))}function q$(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=>Y$(i,e)),o=[...t,...n],s=X("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function Y$(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()}C("os.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function Pb(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function xd(e){const t=e.dataTransfer?.types;return t?Array.from(t).includes("Files"):!1}function X$(e){if(!e.bundleUrl||Ht())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,de({message:b("That drop could not be processed — please try again.","desktop-mode")}))})),t),r=c=>{xd(c)&&i()},a=c=>{!n&&xd(c)&&(c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"))},l=c=>{if(n||!xd(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 $b=[];let Md=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(Md){Promise.resolve().then(o);return}$b.push(o)}},ready(o){n.whenReady(o)},isReady(){return Md}};t.wp.os=n})();let Wd=[],Fr=Number.POSITIVE_INFINITY,Pd=!1;function Ke(e,t=1500){if(Wd.push(e),t<Fr&&(Fr=t),Pd)return;Pd=!0;const n=()=>{const o=Wd;Wd=[],Fr=Number.POSITIVE_INFINITY,Pd=!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:Fr}):window.setTimeout(n,0)}function Ub(){const e=window.openStationConfig;if(!e)return;const t=document.getElementById("os-area");if(!t)return;const n=OE(window.location.href);if(n)try{window.history.replaceState(window.history.state,"",n)}catch{}W0(e.arrivalDirection==="next"||e.arrivalDirection==="prev"?e.arrivalDirection:null);const o=new wI(t),s=document.getElementById("os-wallpaper"),i=e.pluginUrl||"";let r=null;s&&(r=new Hh(s,i));const a=document.getElementById("os-widgets");let l=null;cP(),m0(),a&&(l=new LN(a,i)),Bh({id:"pixijs",url:`${i}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const c=new C0(r??new Hh(document.createElement("div"),i));c.apply();const d=v$({preference:Ur(c.getOsSettingsSnapshot().mobileLayout??e.mode?.preference),breakpoints:e.mode?.breakpoints});c.subscribeOsSettings(w=>{d.setPreference(Ur(w.mobileLayout))}),E$();const u=S$({manager:o,mode:d.api,openNative:(w,A,H)=>k(w,A,H)}),f=document.getElementById("os-shell"),p=new FP({shell:f??document.body,focusedWindow:()=>{const w=o.getFocused();return w&&o.isActive(w.id)?w.id:null},bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:c.state.mioEnabled,wallpaperVisible:()=>c.state.mioShowOnWallpaper,chatAvailable:()=>!!(c.state.ai.enabled&&e.aiAssistant?.available&&e.aiAssistant.assistantProviderConfigured),persist:w=>{c.state.mioEnabled=w,c.state.mioApiEnabled=w,c.save()},savedLook:c.state.mioStyle,persistLook:w=>{c.state.mioStyle=w,c.save()}}),g=p.api();if(c.subscribeOsSettings(w=>p.syncEnabled(w.mioEnabled)),document.addEventListener("os-ai-status-changed",()=>p.refreshWindowAvailability()),!d.api.isMobile())p.boot();else{const w=d.api.subscribe(A=>{A.mode!=="mobile"&&(w(),p.boot())})}l&&fP({osSettings:c,layer:l});const h=new iO({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(dO({config:()=>e,fallbackContext:()=>({close:()=>h.close(),openInWindow:(w,A,H)=>{o.open({url:w,title:A,icon:H??"dashicons-admin-generic"})},confirm:w=>Yt({message:w})})}));const m=new pD,E=new TD;document.addEventListener(ke.START,w=>{const H=w.detail?.payload;if(!H||H.type!=="shortcut"&&H.type!=="desktop-file")return;const z=H.data?.bridgePayload;z&&m.start(z)}),document.addEventListener(ke.END,()=>{m.end()}),Ke(()=>GD(E)),Ke(()=>oR(o)),window.addEventListener("message",w=>{if(w.origin!==window.location.origin)return;const A=w.data;!A||A.type!=="os-drop-failed"||de({message:"Could not insert into the editor."})}),Pw({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>h.open(),close:()=>h.close(),isOpen:()=>h.isOpen}),EI(),lR(),vI(o),AI(o),DI(o,{shouldAsk:()=>c.state.confirmCloseAllWindows,setAsk:w=>{c.state.confirmCloseAllWindows=w,c.save()}}),Ke(()=>{new DT({manager:o,adminUrl:e.adminUrl}).install(),RT(o);const w=new FT({manager:o,adminUrl:e.adminUrl});w.install(),document.addEventListener(hg,()=>w.install(),{once:!0})}),document.addEventListener("os-open-ai",()=>{gl("desktop-mode-ai-assistant")}),document.addEventListener("click",w=>{const A=w.target;!(A instanceof Element)||!A.closest("#wp-admin-bar-command-palette")||(w.preventDefault(),w.stopImmediatePropagation(),gl("desktop-mode-ai-assistant"))},!0);const S=document.getElementById("os-dock"),R=document.getElementById("os-shell"),$=R?.querySelector(".os-shell__body");let _=null,M=null;const P=(w,A)=>{if(d.api.isMobile()){w.setAppearance?.(null),w.setVisibleWidgets?.(null);return}xa(w,A)},B=(w,A)=>{d.api.isMobile()||Wa(w,A)};let F=!1;const K=()=>$f(c.getOsSettingsSnapshot()),Z=w=>({presets:Oo(),apps:w.getNavItems().map(A=>({id:A.id,title:A.title,kind:A.kind,locked:A.locked,url:A.menu?.url||A.entry?.url||void 0,windowId:A.windowId})),widgets:Jc().map(A=>({id:A.id,label:A.label||A.id,description:A.description})),enabledWidgetIds:l?.getEnabledIds()??[],wallpapers:Ya().map(A=>({id:A.id,label:A.label,preview:A.preview})),accents:ti().map(A=>({id:A.id,label:A.label,value:A.value})),resolvePreset:A=>Mf(A,w.getNavItems()),captureAppearance:K}),Y=()=>{if(!M)return;const w=M;_b({mode:"create",...Z(w),onCreate:A=>{Ma(w,{label:A.label||void 0,...A.preset?{preset:A.preset}:{profile:A.profile??void 0}})}})},L=(w=o.getActiveDesktopId())=>{if(!M)return!1;const A=_?.getNav();let H;A&&(H=[...A.dock.core,...A.dock.apps,...A.dock.controls,...A.sidebar,...A.desktop].filter(Ee=>!A.ephemeral.has(Ee.id)).map(Ee=>Ee.id));const z=Vk(M,w,{visibleAppIds:H,mountedWidgetIds:l?.getMountedIds()});if(!z)return!1;const he=o.getDesktops().find(ve=>ve.id===w)?.label??"",qe=o.getAll().filter(ve=>(ve.config.desktopId||w)===w).length,st=z.windows.length;let Q;return qe>st?Q=ae(b("%1$s will open like this — the top %2$d of %3$d windows, where they are."),he,st,qe):Q=ae(b("%1$s will open like this — %2$d windows, where they are."),he,st),de({message:Q}),!0},x=w=>{if(!M)return;const A=o.getDesktops().find(z=>z.id===w);if(!A)return;const H=M;_b({mode:"edit",desktopId:w,label:A.label,profile:A.profile??Pf(),...Z(H),onSave:z=>{z.label&&o.renameDesktop(w,z.label),Rn(H,w,z.profile)},captureWindows:()=>Pa(o,w),onDelete:o.getDesktops().length>1?()=>o.closeDesktop(w):void 0})},j=w=>w.some(A=>!!A.windowId&&o.getAllByBaseIdOnActiveDesktop(A.windowId).length>0),V=FN({manager:o,appendSystemTile:w=>_?.appendSystemTile(w),removeSystemTile:w=>_?.removeSystemTile(w)}),J=V.sync;PI({getSnapshot:()=>c.getOsSettingsSnapshot(),openById:(w,A)=>V.openById(w,A),adminUrl:e.adminUrl});const O=w=>{const A=ue(w,e.adminUrl),H=_?_.getMenuItems():e.dockItems??[];for(const z of H){if(ue(z.url,e.adminUrl)===A)return{title:z.title,icon:z.icon,url:z.url,submenu:z.submenu,selfLabel:z.selfLabel,multi:z.multi};for(const he of z.submenu??[])if(ue(he.url,e.adminUrl)===A)return{title:he.title,icon:z.icon,url:z.url,multi:z.multi}}return null},T=dc,W=(w,A)=>{const H=e.multisite?.hopUrl;return H?N0({hopUrl:H,restNonce:e.restNonce})(w,A):Promise.resolve(null)};if(eI(()=>e.multisite?uC(e.multisite,{mint:W}):null),document.addEventListener("os-app-effect",w=>{const A=w.detail?.effect;A?.type==="hop"&&e.multisite&&typeof A.site=="string"&&yc(e.multisite,A.site,{mint:W})}),dC({multisite:()=>e.multisite,isShown:()=>!!document.querySelector(".os-area--overview .os-site-switcher"),mint:W}),e.hopLinkOffer&&pC(e.hopLinkOffer,{confirm:w=>Yt(w),post:fC(e.restNonce)}),tA({adminUrl:e.adminUrl,deriveSlug:w=>ue(w,e.adminUrl),openWindow:w=>{o.open(w)},findDockEntry:O,openOtherAdmin:T}),Tt({id:"desktop-mode-dashboard",nativeWindowId:"desktop-mode-dashboard",matches:(w,A)=>BI(A),enabled:w=>w.stationHomeEnabled===!0}),Tt({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(w,A)=>{if(!A.pathname.endsWith("/edit.php"))return!1;const H=A.searchParams.get("post_type");return!H||H==="post"},enabled:w=>w.nativePostsEnabled===!0}),Tt({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(w,A)=>A.pathname.endsWith("/edit.php")?A.searchParams.get("post_type")==="page":!1,enabled:w=>w.nativePagesEnabled===!0}),Tt({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(w,A)=>A.pathname.endsWith("/users.php"),enabled:w=>w.nativeUsersEnabled===!0}),Tt({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(w,A)=>{if(WI(A))return!1;const H=A.pathname;return H.endsWith("/profile.php")?!0:H.endsWith("/user-edit.php")?A.searchParams.has("user_id"):!1},enabled:w=>w.nativeUsersEnabled===!0,params:(w,A)=>{const H=parseInt(A.searchParams.get("user_id")??"0",10);return{userId:H>0?H:0}}}),Tt({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(w,A)=>A.pathname.endsWith("/edit-comments.php"),enabled:w=>w.nativeCommentsEnabled===!0,params:(w,A)=>{const H=parseInt(A.searchParams.get("p")??"0",10);return{post:H>0?H:0}}}),Tt({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(w,A)=>{const H=A.pathname;return H.endsWith("/plugins.php")||H.endsWith("/plugin-install.php")},enabled:w=>w.nativePluginsEnabled===!0,params:(w,A)=>({tab:A.pathname.endsWith("/plugin-install.php")?"browse":"installed"})}),S&&R&&$&&e.dockItems){t.classList.add("os-area--with-dock");const w=c.getOsSettingsSnapshot(),A=w.desktopLayout,H=w.dockPlacement,z=Q=>{Bg(t,Q,{openWindow:V.openById,manager:o,deriveWindowId:ve=>ue(ve,e.adminUrl)})};_=tO({shellRoot:R,shellBody:$,bottomDockEl:S,desktopArea:t,windowManager:o,adminUrl:e.adminUrl,renderIcons:z,getSettings:()=>{const Q=c.getOsSettingsSnapshot();return{navPlacement:Q.navPlacement,navOrder:Q.navOrder}},getWorkspaceProfile:()=>d.api.isMobile()?null:Fk(o)},A,e.dockItems,e.desktopIcons,H),qP(),nk({shell:R,shellBody:$,area:t}),Lk(o),pA({shellBody:$,getBehaviors:()=>({dock:c.state.dockBehavior,sidebar:c.state.sideDockBehavior})}),tT({bundleUrl:e.dockConstellationBundleUrl??"",deps:{windowManager:o,adminUrl:e.adminUrl,getMenuItems:()=>_?.getMenuItems()??[],getSystemItem:Q=>_?.getSystemTile(Q)??null}}),jP(R,()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))}),M={manager:o,getNavItems:()=>_?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:Q=>ue(Q,e.adminUrl),openNative:V.openById,refreshLayout:()=>_?.refresh(),setVisibleWidgets:Q=>l?.setVisibleIds(Q),setAppearance:Q=>c.setWorkspaceAppearance(Q)},o$(),n$(e.workspacePresets),JP(M,x,Y,L),Kk({...M,openCreator:Y,openEditor:x}),ee(y.DESKTOP_SWITCHED,"desktop-mode/workspace-provision",Q=>{!M||!Q?.to||(P(M,Q.to),B(M,Q.to))});const he=(Q,ve)=>{if(!M||!ve)return;const Ee=o.getActiveDesktopId(),Ye=qt(o,Ee);if(!Ye||Ye.widgets?.mode!=="only")return;const Ks=Bk(Ye,Q,ve);Ks!==Ye&&Rn(M,Ee,Ks)};if(ee(y.WIDGET_ADDED,"desktop-mode/workspace-widgets",Q=>he(Q.id,!0)),M){const Q=o.getActiveDesktopId();P(M,Q),B(M,Q)}const qe=tD(e.pwa?.appName||"WordPress",de),st={id:X_,title:"System",icon:J_,navKind:"control",placeable:!0,order:ci.system,onOpen:()=>v(),get submenu(){const Q=[{title:"OpenStation Preferences",url:"",windowId:Cn,onSelect:()=>v()}];return e.homeUrl&&Q.push({title:"View site",url:e.homeUrl}),Q.push({title:"Fullscreen",url:"",onSelect:i$},{title:"Keyboard shortcuts",url:"",windowId:Td,onSelect:()=>d$(ve=>{o.open(ve)})},{title:"Report a bug",url:"",windowId:ds,onSelect:()=>I()}),!rw()&&!F&&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:()=>j(st.submenu??[])};_.appendSystemTile(st),aw().then(Q=>{F=Q})}function v(w={}){const A={extended:"features",effects:"windows"},H=w.tabId?A[w.tabId]:void 0;H&&(w={...w,tabId:H});const z=!!o.getById(Cn);V.openById(Cn,{source:"os-settings",...w.tabId?{params:{tab:w.tabId}}:{}}),w.tabId&&z&&window.wp?.os?.apps?.local(Cn,"tab",{value:w.tabId})}function I(w=ds,A){$i("desktop-mode-bug-report");const H={id:w,baseId:ds,url:`#${ds}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:z=>DO(z),width:560,height:620,minWidth:420,minHeight:480,...A};A?o.openNew(H):o.open(H)}if(document.addEventListener("os-open-bug-report",()=>{I()}),_){if(_.appendSystemTile(eS()),e.multisite){const w=T0(e.multisite,T);w&&_.appendSystemTile(w)}_.appendSystemTile({id:BP,title:"Mio",icon:EP,navKind:"control",placeable:!0,order:ci.mio,isOpen:()=>g.isEnabled(),onOpen:()=>{g.toggle()}}),_.appendSystemTile({id:Y_,title:"Overview",icon:Z_,navKind:"control",placeable:!0,order:ci.overview,isOpen:()=>o._overviewActive,onOpen:()=>{o._overviewActive?o.exitOverview():o.enterOverview()}})}const N=_?.getPrimary()??null;J(Dg(Array.isArray(e.nativeWindows)?e.nativeWindows:[],e.nativeWindowScriptData));const D=cx(e.session);function k(w,A,H){const z=A||w;return z==="desktop-mode-dashboard"&&c.getOsSettingsSnapshot().stationHomeEnabled!==!0?!1:z===ds?(I(w,H),!0):H?V.restoreById(w,z,H):V.openById(w)}const U=typeof e.soloWindow=="string"?e.soloWindow:"";U&&queueMicrotask(()=>{if(k(U))return;const w=U.startsWith("os-game-")?U.slice(8):"";if(w){Zh.launch(w).catch(A=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",A)});return}typeof console<"u"&&console.error(`[openstation] solo window "${U}" is not registered; nothing to paint.`)});const G=d.api.isMobile()?u.trimSessionForMobile(e):e,le=D&&!U?dx(o,G,t,k).catch(w=>{typeof console<"u"&&console.error("[openstation] session restore failed:",w)}):Promise.resolve(),re=e.defaultWindow?.enabled!==!1,ge=e.defaultWindow?.url??"",q=typeof ge=="string"&&ge.startsWith("native:");let ne=le;if(!U&&fx({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:D,defaultEnabled:re,isNativeDefault:q})&&(ne=le.then(()=>ux(o,e).catch(w=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",w)}))),e.landInOverview&&!U&&ne.then(()=>{o.enterOverview(),Oh()}),!U&&M){const w=M;le.then(()=>{const A=o.getActiveDesktopId();d.api.isMobile()||zk(w,A),P(w,A)})}const be=yx(o,e);bx(be);const bn=async w=>{try{const A=await Dl(o,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:w})},{source:"desktop-mode/default-window"});if(!A.ok)throw new Error(`HTTP ${A.status}`);const H=await A.json();e.defaultWindow=H,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:H}))}catch(A){C(y.SHELL_ERROR,{scope:"default-window-save",error:A}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",A)}};if(o.onToggleStartupRequested=w=>{const A=e.defaultWindow,H=!!w.config.native,z=H?`native:${w.id}`:w.getCurrentUrl(),he=H?A?.url===z:Kd(A?.url??"")===Kd(z),qe=!!A?.enabled&&he;bn(qe?null:z)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!D&&q){const w=ge.slice(7);queueMicrotask(()=>{k(w)})}const xe=w=>{_?.appendSystemTile(w)},Hr=pP({layer:l});Hr(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const $d=FC({osSettings:c});$d(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),ee(y.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",w=>{const A=w?.wallpapers;Array.isArray(A)&&$d(A)});const Bb=GC();Bb(Array.isArray(e.serverGames)?e.serverGames:[]);const Fb=y0();Fb(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const Hb=oL();Hb(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const Gb=rL();Gb(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const zb=dL();zb(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const jb=mL();jb(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const Vb=zL();Vb(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const Kb=YL();Kb(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),QL({manager:o,osSettings:c}),wS({osSettings:c}),QI({manager:o}),XL();{let w=!1;ee(y.WINDOW_LINK_GROUPS_CHANGED,"desktop-mode/window-link-visuals-sentinel",()=>{w||(w=!0,Um().then(A=>{A&&window.openStationWindowLinkVisuals?.start({manager:o,osSettings:c})}).catch(()=>{w=!1}))})}vL({manager:o,openUrl:w=>{if(w.windowId&&V.openById(w.windowId,{source:"related-entities",...w.params?{params:w.params}:{}})||!w.url||Ze(w.url))return;const A=ue(w.url,e.adminUrl);o.open({id:A,baseId:A,url:w.url,title:w.label,icon:w.icon||"dashicons-admin-links"})}}),OL({manager:o}),BL({manager:o});const qb=eT();qb(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),sT()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),aT(),cT()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),uT()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),ag(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),ST()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const js=AT(o);bL(o),Ke(()=>EL()),RI(),ee("os.shell.toast","desktop-mode/shell-toast",w=>{!w||typeof w.message!="string"||de({message:w.message,action:w.action,duration:w.duration})});const Ud=e,Z$=Ud.recycleBinCount;wO(Number(Z$)||0,typeof Ud.recycleBinCountUrl=="string"?Ud.recycleBinCountUrl:""),AO({getRecycleBinCount:gO}),window.__openStationConnectionBridge=js,ee(y.WINDOW_CLOSED,"desktop-mode/connection-cleanup",w=>{w?.windowId&&js.onWindowClosed(w.windowId)}),ee(y.IFRAME_READY,"desktop-mode/connection-rearm",w=>{w?.windowId&&js.onIframeReady(w.windowId)});const J$=WN(o),Q$=w=>{if(_){_.applyDesktopIcons(w);return}Bg(t,w,{openWindow:V.openById,manager:o,deriveWindowId:A=>ue(A,e.adminUrl)})},Bd=()=>{_&&oP(_.getNav().desktop,_.getNavItems(),c.getOsSettingsSnapshot().dockPromotedPositions)},e2=ax({layoutDispatcher:_,desktopArea:t,config:e,applyMultisite:w=>{const A=e.multisite;e.multisite=w&&A?{...w,current:A.current,isNetworkAdmin:A.isNetworkAdmin}:w,Do(o)},syncNativeWindows:J,syncServerWidgets:Hr,syncServerWallpapers:$d,syncServerCommands:Hb,syncServerSettingsTabs:Gb,syncServerTitleBarButtons:zb,syncServerWindowActions:jb,syncServerUnfocusEffects:Vb,syncServerWindowLinkRenderers:Kb,syncServerDockRailRenderers:qb,syncServerGames:Bb,syncServerDesktopThemes:Fb,renderIcons:Q$,refreshRootPlacements:()=>{Re(0).then(w=>{Pt(0,w.placements)}).catch(()=>{})},syncShortcuts:Bd});document.addEventListener(Eh,()=>{_&&_.setLayout(_.getLayout());for(const w of o._stack)try{w.repaintWindowControls(),w.repaintThemedChrome()}catch(A){C(y.SHELL_ERROR,{scope:"desktop-theme-repaint",id:w.id,error:A})}}),c.subscribeOsSettings(w=>{if(!_)return;const A=_.getLayout(),H=_.getDockPlacement();_.setDockPlacement(w.dockPlacement),_.setLayout(w.desktopLayout),Vs.dock=_.getPrimary(),Vs.sideDock=_.getSide(),Vs.desktopLayout=w.desktopLayout,Vs.dockPlacement=_.getDockPlacement(),A===w.desktopLayout&&H===w.dockPlacement&&_.refresh(),Bd(),Ey(w.desktopLayout)}),sP(Bd),Ey(c.getOsSettingsSnapshot().desktopLayout);const Vs=nM({manager:o,dock:N,layoutDispatcher:_,osSettings:c,iconsApi:nl,filesApi:He,saveSession:be,widgetLayer:l,registerWindow:J$,openWindowById:V.openById,openNewWindowById:V.openNewById,loadWindowScriptById:V.loadScriptById,prewarmWindowById:V.prewarmById,placeSystemTile:xe,setDefaultWindow:bn,refreshMenu:e2,openOsSettings:v,aiAssistant:h,dragBridge:m,dragManager:E,connect:js.connect,getConnection:js.getConnection,mio:g,mode:d.api,workspaces:e$(M??{manager:o,getNavItems:()=>_?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:w=>ue(w,e.adminUrl),openNative:V.openById,refreshLayout:()=>_?.refresh()},x,K,Y,L),wallpaperSuspend:{suspend:w=>r?.suspend(w),resume:w=>r?.resume(w),isSuspended:()=>r?.isSuspended()??!1},config:e});oM(Vs);let wo=null,Yb=0;const t2=A$({manager:o,adminUrl:e.adminUrl,openNative:k}),Xb=()=>{const w=++Yb;if(!d.api.isMobile()){wo&&(wo.unmount(),wo=null);return}if(wo||!R)return;const A=R;I$(e.mobileBundleUrl??"").then(H=>{w!==Yb||!d.api.isMobile()||wo||(wo=H.mount({manager:o,shell:A,area:t,mode:d.api,getNav:()=>_?.getNav()??null,openNavItem:t2,getBadge:z=>Math.max(z.menu?.badge??0,nl.getBadge(z.id)),getPinnedTabIds:()=>{const z=c.getOsSettingsSnapshot().mobileTabs;return Array.isArray(z)&&z.length>0?z:e.mode?.tabBar??[]},subscribeNav:z=>{const he=c.subscribeOsSettings(z);return document.addEventListener("os-layout-changed",z),document.addEventListener("os-registry-changed",z),()=>{he(),document.removeEventListener("os-layout-changed",z),document.removeEventListener("os-registry-changed",z)}},wallpaper:{suspend:z=>r?.suspend(z),resume:z=>r?.resume(z)},openExternal:z=>{window.open(z,"_blank","noopener")},adminUrl:e.adminUrl,renderIcon:(z,he)=>Yn(z,he),getArt:z=>nl.getArt(z.id)||N?.getArt(z.id)||"",subscribeArt:z=>Se.subscribe("os/art-changed",()=>z())}))}).catch(H=>{typeof console<"u"&&console.error("[openstation] the phone layer failed to load:",H)})};Xb(),d.api.subscribe(Xb),d.api.subscribe(w=>{if(w.mode!=="mobile"&&w.previous!=="mobile"||(_?.refresh(),!M))return;const A=o.getActiveDesktopId();P(M,A),B(M,A)}),Ke(()=>$$(E)),Ke(()=>B$()),zC(),uS(),e.gamesEnabled!==!1&&QC({currentUserId:Number(e.currentUserId)||0}),Ke(()=>WR()),Ke(()=>$R()),Ke(()=>ZR({currentUserId:Number(e.currentUserId)||0})),rP({bundleUrl:e.notesBundleUrl??"",hasNotes:!!e.hasNotes,host:t,config:e,onError:w=>{de({message:w})}}),dM({openUrl:({id:w,url:A,title:H,icon:z})=>(Ze(A)||o.open({id:w,baseId:w,url:A,title:H,icon:z}),!0),openNativeWindow:w=>V.openById(w),deriveWindowId:w=>ue(w,e.adminUrl)}),Iy(e.userFileAssociations??{}),dP({update:e.coreUpdate,openUrl:({url:w,title:A})=>{Ze(w)||o.open({id:"update-core",baseId:"update-core",url:w,title:A,icon:"dashicons-update"})}});const Zb=({url:w,title:A})=>{if(Ze(w))return;const H=ue(w,e.adminUrl);o.open({id:H,baseId:H,url:w,title:A,icon:"dashicons-info"})};if(Yv({notices:e.coreNotices,openUrl:Zb}),Yv({notices:e.pluginNotices,openUrl:Zb,keyPrefix:"plugin-notice"}),m$({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){My({baseUrl:e.filesUrl,nonce:e.restNonce});const w=document.getElementById("os-area");if(w){const A=mv(w,0),H=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},z=setTimeout(H,2e3);A.hydrated.then(()=>{clearTimeout(z),H()})}}Ke(()=>F$()),Ke(()=>z$()),Ke(()=>fR()),C(y.COMPONENTS_REGISTERED,{tags:[...fr]}),iR(),iD(e,de,async()=>{await be.flush(),window.location.reload()});const Jb=()=>{mE(e.shellOverlaysBundleUrl??""),pE(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(Jb,{timeout:1500}):window.setTimeout(Jb,0),C(y.INIT,{config:e}),Md=!0;const n2=$b.splice(0);for(const w of n2)try{w()}catch(A){C(y.SHELL_ERROR,{scope:"when-ready-cb",error:A}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",A)}if(c.apply(),!d.api.isMobile())l?.hydrate();else{const w=d.api.subscribe(A=>{A.mode!=="mobile"&&(w(),l?.hydrate())})}window.addEventListener("pagehide",()=>{r?.teardownActive(),l?.disposeAll()}),Ex(),JR(o,e);const Qb=(w,A=!0)=>{const H=He.store.getState().placementsByFolder.get(0)??[],z=w(H),he=me(t),qe=Math.max(1,Math.floor((he.height-16)/110)),st=new Set;let Q=0;for(const ve of z){const Ee=Bt(16+Math.floor(Q/qe)*96,16+Q%qe*110,st,he);st.add(`${Ee.col},${Ee.row}`),Q++,!(ve.x===Ee.x&&ve.y===Ee.y)&&(He.store.upsertPlacement({...ve,x:Ee.x,y:Ee.y,sortOrder:Q}),!(!A||_r(ve))&&ao(ve.id,{x:Ee.x,y:Ee.y,sortOrder:Q}).catch(Ye=>{console.error("[openstation] relayout persist failed",Ye)}))}},eE=w=>A=>{const H=A.slice();switch(w){case"name-asc":H.sort((z,he)=>z.file.title.localeCompare(he.file.title));break;case"name-desc":H.sort((z,he)=>he.file.title.localeCompare(z.file.title));break;case"date-asc":H.sort((z,he)=>z.updatedAtMs-he.updatedAtMs);break;case"date-desc":H.sort((z,he)=>he.updatedAtMs-z.updatedAtMs);break}return H},Fd="desktop-mode:root-sort-mode",o2=w=>w==="name-asc"||w==="name-desc"||w==="date-asc"||w==="date-desc";let Gr=(()=>{try{const w=window.localStorage.getItem(Fd);return o2(w)?w:null}catch{return null}})();const tE=w=>{Gr=w;try{w?window.localStorage.setItem(Fd,w):window.localStorage.removeItem(Fd)}catch{}};ee("os.files.tile-manually-placed","desktop-mode/root-sort-clear",w=>{w?.folderId===0&&tE(null)});{let w=me(t);const A=()=>{if(!Gr)return;const H=me(t);H.width===w.width&&H.height===w.height||(w=H,Qb(eE(Gr),!1))};typeof ResizeObserver<"u"&&new ResizeObserver(A).observe(t),To(A)}let nE=!1;t.addEventListener("pointerdown",w=>{w.isPrimary&&(nE=w.target===t)}),t.addEventListener("click",w=>{c.state.showDesktopOnWallpaperClick&&w.target===t&&nE&&(t.classList.contains("os-area--overview")||Mb()||E.recentlyEndedDrag()||LR()||o.toggleShowDesktop())}),t.addEventListener("contextmenu",w=>{if(w.target!==t)return;w.preventDefault();const A=w.clientX,H=w.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(Mb()){Bs();return}const z={x:A,y:H},he=()=>{const Q=t.getBoundingClientRect(),ve=Math.max(0,z.x-Q.left),Ee=Math.max(0,z.y-Q.top),Ye=ov(He.store.getState().placementsByFolder.get(0)??[]);return Bt(ve,Ee,Ye,me(t))},qe=(Q,ve)=>{NW({title:Q,description:ve,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:Ee,url:Ye})=>{const Ks=he(),s2=await _s({type:"link",ref:Ye,parentId:0,x:Ks.x,y:Ks.y,meta:Ee?{name:Ee}:void 0});He.store.upsertPlacement(s2)}})},st=q$({createFolder:()=>{ad({onSubmit:async Q=>{const ve=await ql({name:Q}),Ee=he(),Ye=await _s({type:"folder",ref:String(ve.id),parentId:0,x:Ee.x,y:Ee.y});He.store.upsertFolder(ve),He.store.upsertPlacement(Ye)}})},createUrl:()=>qe("New URL","Opens the URL in a new browser tab."),addWidget:()=>l?.openPicker(),toggleShowDesktop:()=>o.toggleShowDesktop(),openOsSettings:()=>v(),sortIcons:Q=>{tE(Q),Qb(eE(Q))},currentSortMode:Gr,includeShowDesktop:!c.state.showDesktopOnWallpaperClick,position:{x:A,y:H},labels:{createFolder:"New folder",showDesktop:"Show desktop",osSettings:"OpenStation Preferences",sortHeading:"Sort by",sortNameAsc:"Name (A → Z)",sortNameDesc:"Name (Z → A)",sortDateAsc:"Date (oldest first)",sortDateDesc:"Date (newest first)",newUrl:"New URL",addWidget:"Add widget"},serverItems:e.serverWallpaperMenuItems??[]});V$(document.body,{x:A,y:H},st)})()}),X$({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:D}}))}return bP(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ub):Ub(),zr.clampGeometryToViewport=ly,Object.defineProperty(zr,Symbol.toStringTag,{value:"Module"}),zr}({});
69