PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 1.1.4
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v1.1.4
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.4, at assets/js/desktop.min.js

91 lines 573.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 var openStation=function(tr){"use strict";var nr=typeof document<"u"?document.currentScript:null;const Ay="desktop-mode-my-wordpress";function kl(){return window.wp?.os}async function Iy(){const e=kl();return typeof e?.loadWindowScript=="function"&&await e.loadWindowScript(Ay),kl()?.myWordpress}function hs(e,t){return async(...n)=>{const o=await Iy();if(!o||o===t())return;const s=o[e];typeof s=="function"&&await s(...n)}}function Cy(){const e=window;e.wp=e.wp??{};const t=e.wp;t.os||(t.os={});const n=t.os;if(n.myWordpress)return;const o=[],s=()=>i,i={openDetail:hs("openDetail",s),openMedia:hs("openMedia",s),openUserFootprint:hs("openUserFootprint",s),trashEntity:hs("trashEntity",s),registerEntityKind:(r,a)=>{const c={unregister:null},l={kind:r,renderer:a,slot:c};return o.push(l),()=>{if(c.unregister){c.unregister(),c.unregister=null;return}const d=o.indexOf(l);d!==-1&&o.splice(d,1)}},__pendingKinds:o};n.myWordpress=i}Cy();function Lt(){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 Bn(e,t,n,o){Lt().addFilter(e,t,n,o)}function ne(e,t,n,o){Lt().addAction(e,t,n,o)}function Fn(e,t){return Lt().removeAction(e,t)}function Z(e,t,...n){return Lt().applyFilters(e,t,...n)}function T(e,...t){Lt().doAction(e,...t)}function Sl(e){return Lt().didAction(e)}function Ly(){return Lt()}const m={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_SNAP_CHANGED:"os.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"os.arrange.snap.cell-size",ARRANGE_CUSTOM_ACTION:"os.arrange.custom-action",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",PRIMARY_DESKTOP_ID:"os.primary-desktop-id",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",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"};let Ty=0;function Al(e){if(Sl(m.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++Ty}`;ne(m.INIT,t,e)}function Ny(){return Sl(m.INIT)>0}const Il=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"];Il.filter(e=>e!=="p");function Cl(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 le(e,t){let n=null;try{n=new URL(e,t)}catch{n=null}if(n){const s=new URL(t).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams;for(const c of Il){const l=n.searchParams.get(c);l&&r.set(c,l)}const a=r.toString();return Cl(a?`${i}?${a}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),Cl(o)}function Oy(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function Dy(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 Ll(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 tn(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 Tl(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 c of Array.from(a.attributes)){const l=c.name.toLowerCase(),d=c.value.trim().toLowerCase();if(l.startsWith("on")){a.removeAttribute(c.name);continue}d.startsWith("javascript:")&&a.removeAttribute(c.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 nn=null;function ms(){return!!window.openStationWindowSystem}function Nl(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(ms()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){ms()?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 Ry(){return window.openStationConfig?.windowSystemBundleUrl??""}function xy(e){!e||ms()||nn||(nn=Nl(e).catch(t=>{nn=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function My(e){if(ms())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 nn||(nn=Nl(e)),await nn,window.openStationWindowSystem}let on=null;function Hn(){return!!window.openStationShellOverlays}function Ol(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(Hn()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){Hn()?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 Py(e){!e||Hn()||on||(on=Ol(e).catch(t=>{on=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function or(e){return Hn()||!e?Promise.resolve():(on||(on=Ol(e)),on)}function sr(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function gs(e,t){const n=sr();if(Hn()||!n){t();return}or(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const Dl="desktop-mode";function ir(){return window.wp?.i18n}function k(e,t=Dl){return ir()?.__(e,t)??e}function Gn(e,t,n,o=Dl){return ir()?._n(e,t,n,o)??(n===1?e:t)}function de(e,...t){const n=ir()?.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 Wy=900,$y=260,rr="os-desktop-name-hud";let Ve=null,ft=null;function Uy(e,t){t.trim()&&(ft!==null&&window.clearTimeout(ft),Ve||(Ve=document.createElement("div"),Ve.className=rr,Ve.setAttribute("role","status")),Ve.textContent=t,Ve.classList.remove(`${rr}--out`),e.appendChild(Ve),ft=window.setTimeout(()=>{Ve?.classList.add(`${rr}--out`),ft=window.setTimeout(()=>{Ve?.remove(),ft=null},$y)},Wy))}function By(){ft!==null&&(window.clearTimeout(ft),ft=null),Ve?.remove(),Ve=null}function Fy(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 Hy(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 Gy(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 c=t/r/Math.max(1,n/a),l=Math.abs(c-o),d=r*a-e,u=l+d*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function ar(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,c=34,l=(t.width-r*2-a*(s-1))/s,d=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-c);return e.map((f,p)=>{const v=p%s,b=Math.floor(p/s),w=t.left+r+v*(l+a),g=t.top+n+r+b*(d+a)+c,_=f.element.offsetWidth,N=f.element.offsetHeight,$=Math.min(l/_,u/N),C=_*$,V=N*$;return{win:f,x:w+(l-C)/2,y:g+(u-V)/2,scale:$}})}const zy=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],Rl=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],jy=[...zy,...Rl],xl={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 Ml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Pl(e){return Object.prototype.hasOwnProperty.call(xl,e)?xl[e]:null}function Vy(e){return Pl(e)!==null}function sn(e,t={}){const n=Pl(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="${Ml(s)}"`),i?a.push('role="img"',`aria-label="${Ml(i)}"`):a.push('aria-hidden="true"','focusable="false"');const c=r?`<g transform="rotate(${r} 12 12)">${n.b}</g>`:n.b;return`<svg ${a.join(" ")}>${c}</svg>`}function Wl(e,t={}){const n=sn(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 Ky(e,t={}){const n=sn(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const qy=Object.freeze({svg:sn,node:Wl,dataUri:Ky,names:Object.freeze([...jy]),ours:Object.freeze([...Rl]),has:Vy}),$l=120,Ul="__openStationSharedStores";function Yy(){const e=window;let t=e[Ul];return t||(t=new Map,e[Ul]=t),t}function ie(e,t){const n=Yy();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 c of Object.keys(a))delete a[c];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}const Bl="X-WP-Nonce";function Fl(e,t){const n=Xy();if(!n)return t;const o=Zy(e);if(!o||!Jy(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Bl)?t:(i.set(Bl,n),{...t??{},headers:i})}function Xy(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function Zy(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 Jy(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Be(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=Fl(e,t);return fetch(e,s)}const zn=ie("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),st=zn.state.registry,cr=zn.state.listeners,Qy=/^[a-z0-9_-]+$/;function Hl(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!Qy.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).`);st.set(e.id,e),ws()}function eb(e){st.delete(e)&&ws()}function tb(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(st.entries()))o.owner===e&&(st.delete(n),t++);return t>0&&ws(),t}function nb(e){return st.get(e)}function ob(){return Array.from(st.values())}function sb(e){return cr.add(e),()=>{cr.delete(e)}}function ib(e){zn.state.activeId!==e&&(zn.state.activeId=e,ws())}function lr(){return st.get(zn.state.activeId)??st.get("default")??st.values().next().value}function ws(){const e=Array.from(cr);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function Tt(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 rb 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 Ie(e,t,n){if(t.length!==0)throw new rb(e,t,n)}function Gl(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected โ€” fields: `+t.join(", ")+".",n)}const pt=[[0,0],[100,0],[100,100],[0,100]],ab=48,cb=80,dr=6,ur=8,zl=4,jl=3,Vl=64,fr=105,ht=2;function Kl(e){return`${Math.round(e*1e3)/1e3}%`}function mt(e){return e.slice().reverse()}function jn(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function lb(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 Ze(e,t=[]){const n=[],o=s=>{n.push(`${Kl(s[0])} ${Kl(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 ql(e){return Ze(pt,[mt(lb(50,50,e,ab))])}function Yl(e){return Ze(pt,[mt(jn(50-e,-ht,50+e,100+ht))])}function Xl(e){const t=100/dr,n=[];for(let o=0;o<dr;o++){const s=o*t;n.push(mt(jn(-ht,s,100+ht,s+e)))}return Ze(pt,n)}function Zl(e){return Ze(pt,[mt(jn(-ht,50-e,100+ht,50+e))])}function Jl(e){const t=100/ur,n=[];for(let o=0;o<ur;o++){const s=o*t;n.push(mt(jn(s,-ht,s+e,100+ht)))}return Ze(pt,n)}function Ql(e){return Ze(pt,[mt([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function ed(e){const t=100/zl,n=100/jl,o=[];for(let s=0;s<jl;s++)for(let i=0;i<zl;i++){const r=i*t+t/2,a=s*n+n/2,c=t/2*e,l=n/2*e;o.push(mt(jn(r-c,a-l,r+c,a+l)))}return Ze(pt,o)}function td(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<Vl;s++){const i=t+s/(Vl-1)*n;o.push([50+Math.cos(i)*fr,50+Math.sin(i)*fr])}return Ze(pt,[mt(o)])}function db(){return{from:ql(0),to:ql(cb)}}function ub(){return{from:Yl(0),to:Yl(52)}}function fb(){return{from:Xl(0),to:Xl(100/dr+.5)}}function pb(){return{from:Zl(0),to:Zl(52)}}function hb(){return{from:Jl(0),to:Jl(100/ur+.5)}}function mb(){return{from:Ql(0),to:Ql(fr)}}function gb(){return{from:ed(0),to:ed(1.04)}}function wb(){return{from:td(0),to:td(360)}}function yb(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function bb(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function vb(){return{from:Ze([[-60,0],[100,0],[100,100],[0,100]]),to:Ze([[100,0],[260,0],[260,100],[160,100]])}}const pr=6,hr=100,rn=hr/2,ys=200,nd=90,od=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],Eb="#101014",_b=1.25,an="http://www.w3.org/2000/svg";let kb=0;function bs(e){return Math.round(e*1e3)/1e3}function mr(e){return e/pr*Math.PI*2-Math.PI/2}function Sb(e){const n=mr(e)+Math.PI/pr+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function Ab(e){const t=mr(e),n=mr(e+1);return[[rn,rn],[rn+Math.cos(t)*ys,rn+Math.sin(t)*ys],[rn+Math.cos(n)*ys,rn+Math.sin(n)*ys]]}function sd(e,t){const n=Ab(e),o=document.createElementNS(an,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${bs(s)} ${bs(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",od[e%od.length]),o.setAttribute("stroke",Eb),o.setAttribute("stroke-width",String(_b)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function Ib(){const e=`os-iris-${++kb}`,t=document.createElementNS(an,"svg");t.setAttribute("viewBox",`0 0 ${hr} ${hr}`),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(an,"defs"),o=document.createElementNS(an,"mask");o.setAttribute("id",e);const s=document.createElementNS(an,"g"),i=document.createElementNS(an,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let c=0;c<pr;c++){const l=sd(c,!0),d=sd(c,!1);s.appendChild(l),i.appendChild(d),r.push({el:l,index:c},{el:d,index:c})}o.appendChild(s),n.appendChild(o),t.appendChild(n),t.appendChild(i);const a=document.createElement("div");return a.appendChild(t),{element:a,play:c=>r.map(({el:l,index:d})=>{const u=Sb(d),f=bs(u.x*nd),p=bs(u.y*nd);return l.animate([{transform:"translate( 0px, 0px )"},{transform:`translate( ${f}px, ${p}px )`}],{duration:c.duration,easing:c.easing,delay:c.delay,fill:"both"})})}}const Vn="none",Cb=460,Lb="cubic-bezier( 0.33, 0, 0.2, 1 )",id=80,rd=4e3,Tb=70,Nb=600,ad=ie("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),vs=ad.state.registry,Ob=ad.state.listeners,cd=/^[a-z0-9_/-]+$/;function ld(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function Db(e){return typeof e!="number"||!Number.isFinite(e)?Cb:Math.min(rd,Math.max(id,e))}const gr=0;function dd(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?gr:Math.min(rd,Math.max(id,e))}function cn(e){return typeof e!="number"||!Number.isFinite(e)?Tb:Math.min(Nb,Math.max(0,e))}function ud(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 fd(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=ld(e.from),r=ld(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 Rb(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function Pe(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)"):cd.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Vn&&t.push('id ("none" is reserved)'):t.push(`id (must match ${cd} โ€” 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(...fd(r,`layers[ ${a} ]`))})):t.push(...fd(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):Rb(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)"))}Ie("WindowReveal",t,e);const n=e.id.trim().toLowerCase();vs.set(n,{...e,id:n}),md()}function xb(e){vs.delete(e.toLowerCase())&&md()}function pd(){const e=Array.from(vs.values()),t=Z(m.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 hd(e){return pd().find(t=>t.id===e)}function Mb(e){return vs.has(e)}function md(){const e=Array.from(Ob);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Pe({id:"sweep",label:k("Sweep"),description:k("A straight edge travels across the window, uncovering the page behind it."),...bb(),duration:420}),Pe({id:"iris",label:k("Iris"),description:k("The page opens out from the centre of the window, like a camera shutter."),...db(),duration:520}),Pe({id:"curtain",label:k("Curtain"),description:k("Two panels part from the middle of the window and slide off the sides."),...ub(),duration:480}),Pe({id:"blinds",label:k("Blinds"),description:k("Six horizontal slats retract at once, letting the page through between them."),...fb(),duration:560}),Pe({id:"diagonal",label:k("Diagonal"),description:k("A slanted edge sweeps off the trailing corner of the window."),...vb(),duration:460}),Pe({id:"rise",label:k("Rise"),description:k("The page rises into the window from the bottom edge upward."),...yb(),duration:440}),Pe({id:"shutter",label:k("Shutter"),description:k("Two panels part from the middle of the window and slide off the top and bottom."),...pb(),duration:480}),Pe({id:"slats",label:k("Slats"),description:k("Eight vertical slats retract at once, letting the page through between them."),...hb(),duration:560}),Pe({id:"diamond",label:k("Diamond"),description:k("The page opens out from the centre of the window through a growing rhombus."),...mb(),duration:520}),Pe({id:"mosaic",label:k("Mosaic"),description:k("The page arrives as a grid of tiles, each opening out from its own centre."),...gb(),duration:600}),Pe({id:"obturator",label:k("Camera shutter"),description:k("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:Ib,duration:720,edgeLag:0}),Pe({id:"radar",label:k("Radar"),description:k("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...wb(),duration:760});const gd="desktop-mode-os-settings",Pb="custom-gradient",wd="custom-image",wr="galaxy",yd="custom",bd=[{id:"pulse",label:"Pulse",value:"#f252fc"},{id:"nebula",label:"Nebula",value:"#ec9bff"},{id:"sirius",label:"Sirius",value:"#9af2ff"},{id:"lagoon",label:"Lagoon",value:"#9f98ff"},{id:"wp-blue",label:"WordPress Blue",value:"#2271b1"},{id:"indigo",label:"Indigo",value:"#3858e9"},{id:"teal",label:"Teal",value:"#04a4cc"},{id:"emerald",label:"Emerald",value:"#059669"},{id:"amber",label:"Amber",value:"#d97706"},{id:"rose",label:"Rose",value:"#e11d48"}];function yr(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return bd;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:bd}function vd(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:wr}const br=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],vr=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],Es=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],_s=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"}],Wb=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],$b=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],J={wallpaper:wr,accent:"pulse",customAccent:"#f252fc",dockSize:"default",windowRadius:"round",adminBarMode:"hidden",desktopLayout:"unified",dockPlacement:"bottom",dockBehavior:"static",sideDockBehavior:"static",dockRailRenderer:"default",desktopTheme:"",appliedThemeRecommendations:[],unfocusEffect:"darken",windowReveal:"none",windowRevealDuration:0,windowLinkRenderer:"svg-splines",windowLinkVisibility:"always",windowLinksEnabled:!0,windowLinkRaiseOnFocus:!0,windowLinkHighlight:!0,customGradient:{from:"#2271b1",to:"#7c3aed",angle:135},customImage:null,wallpaperSettings:{},libraryHdOnly:!0,ai:{enabled:!1},heartbeatRate:60,nativePostsEnabled:!1,nativePostsHiddenColumns:[],nativePagesEnabled:!1,nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,stationHomeEnabled:!1,adminAssetCacheEnabled:!1,windowPrewarmEnabled:!1,showDesktopOnWallpaperClick:!1,mioEnabled:!1,mioStyle:{appearance:{},physics:{}},showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,navPlacement:{},navOrder:[],dockPromotedPositions:{}},Ed={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},_d=["dockRailRenderer","windowReveal","accent"],kd={windowRevealDuration:{min:80,max:4e3}},Ub=/^[a-z0-9_-]+$/;[...Object.keys(Ed),..._d,...Object.keys(kd)];function Sd(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries(Ed)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of _d){const i=t[s];typeof i=="string"&&Ub.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(kd)){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 Bb(e){const t=Sd(e);return typeof t.dockRailRenderer=="string"&&nb(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==Vn&&!Mb(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!yr().some(n=>n.id===t.accent)&&delete t.accent,t}const Fb=/^[a-z0-9_-]+$/,Ad=128;function Hb(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function Er(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!Fb.test(n))return null;const o={};if(t.icons&&typeof t.icons=="object"){let c=0;for(const[l,d]of Object.entries(t.icons)){if(c>=Ad)break;l===""||!Hb(d)||(o[l]=d,c+=1)}}const s={};if(t.tokens&&typeof t.tokens=="object")for(const[c,l]of Object.entries(t.tokens))typeof l=="string"&&(s[c]=l);const i=[];if(Array.isArray(t.fonts))for(const c of t.fonts)typeof c=="string"&&c!==""&&i.push(c);const r={};if(t.iconColors&&typeof t.iconColors=="object"){let c=0;for(const[l,d]of Object.entries(t.iconColors)){if(c>=Ad)break;l===""||typeof d!="string"||d===""||(r[l]=d,c+=1)}}const a=c=>typeof t[c]=="string"?t[c]:"";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:Sd(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload",cssDeferred:t.cssDeferred===!0}}function Gb(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=Er(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const gt=ie("desktop-mode/desktop-themes",Gb);function ln(){return gt}function zb(){return gt.getState().themes.slice()}function _r(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return gt.getState().themes.find(n=>n.slug===t||n.id===e)??null}function kr(){return gt.getState().activeId}function jb(e){const t=Er(e);if(!t)return null;const n=gt.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)),gt.setState({themes:n}),t}let Kn=null;function Id(){if(Kn)return Kn;const e=window.openStationConfig?.desktopThemesUrl;return e?(Kn=Be(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??[])jb(n)}).catch(()=>{Kn=null}),Kn):Promise.resolve()}function Vb(e){const t=[];for(const n of e){const o=Er(n);o&&t.push(o)}gt.setState({themes:t})}function Kb(e){return gt.subscribe(e)}function ks(e){const t=ln().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=Z(m.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function Sr(e){const t=ln().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=Z(m.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?qb(o):null}function qb(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 Nt={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"},Yb={"desktop-mode-os-settings":Nt.OS_SETTINGS,"desktop-mode-recycle-bin":Nt.RECYCLE_BIN,"desktop-mode-bug-report":Nt.BUG_REPORT,"os-exit":Nt.EXIT_OPENSTATION,"os-pwa-install":Nt.PWA_INSTALL};function Ss(e){if(typeof e!="string"||e==="")return"";const t=Yb[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function Xb(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Nt.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Nt?n:""}const Cd=new Map,Zb=new Map;function Ar(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 Ld(e,t,n,o){const s={channel:n,windowId:t},i=Ar(e,t,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(c){typeof console<"u"&&console.error(`[openstation] window-channel subscriber for "${n}" threw:`,c)}const r=Ar(e,t,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(c){typeof console<"u"&&console.error(`[openstation] window-channel wildcard subscriber for "${t}" threw:`,c)}}function Jb(e,t,n){const o=Ar(Cd,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function Qb(e,t,n){Ld(Cd,e,t,n)}function ev(e,t,n){Ld(Zb,e,t,n)}const Td=new Set,tv=new Set,Nd=new Map;function nv(e){if(!Td.has(e)){Td.add(e);const t=Nd.get(e);if(t){Nd.delete(e);for(const n of t)try{n.flush()}catch(o){typeof console<"u"&&console.error(`[openstation] flushing queued window-send for "${n.channel}" threw:`,o)}}}tv.delete(e)&&(T(m.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const ov="os.activity.";function Ir(e){return ov+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let sv=0;const Ee={publish(e,t){T(Ir(e),t)},subscribe(e,t){const n=`os/activity-sub/${++sv}`,o=Ir(e);ne(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,Fn(o,n))}},filter(e,t,...n){return Z(Ir(e),t,...n)}},iv=4e3,rv=200,av=1200;function fe(e){const t=Ee.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return gs(()=>!n,()=>{o=cv(t)}),()=>{n=!0,o&&o()}}function cv(e){const t=fv(),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(),c()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{e.onDismiss?.(),c()})),t.appendChild(n);let o=!1,s=null,i=e.duration??iv,r=0;const a=()=>{s!==null&&(window.clearTimeout(s),s=null)},c=()=>{o||(o=!0,a(),uv(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),dv()},rv))},l=()=>{o||e.persistent||s!==null||(r=Date.now(),s=window.setTimeout(c,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,av),l()}),lv(n),l(),Ee.publish("os/toast-shown",{...e}),c}let As=null,qn=0;function Od(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(As=t))}function lv(e){qn===0&&document.addEventListener("focusin",Od,!0),qn+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(As=n)}function dv(){qn=Math.max(0,qn-1),qn===0&&document.removeEventListener("focusin",Od,!0)}function uv(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||As?.isConnected===!0&&As.focus()}function fv(){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 pv="http://localhost/";function it(e,t){const n=typeof window<"u"&&window.location?window.location.href:pv,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 c=o.searchParams.get("rest_route")??"/",l=c.endsWith("/")?c:c+"/";o.searchParams.set("rest_route",l+r)}else{const c=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=c+r}return a&&new URLSearchParams(a).forEach((l,d)=>{o.searchParams.append(d,l)}),o.toString()}const hv="os-overview",mv="os-system",Is={mio:10,overview:20,system:30,exit:35},gv=`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>')}`,wv=`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>')}`,yv="os-exit";function bv(){return{id:yv,title:k("Exit OpenStation"),navKind:"control",locked:!0,order:Is.exit,icon:"dashicons-exit",onOpen:()=>{vv()}}}async function vv(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Cr(t);return}const n=new URLSearchParams;n.set("action","save-openstation"),n.set("nonce",e.nonce),n.set("enabled","");let o=t;try{const s=await fetch(e.ajaxUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),credentials:"same-origin"});if(s.ok){const i=await s.json();i?.success&&i.data?.redirect&&(o=i.data.redirect)}}catch{}Cr(o)}function Cr(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const Dd=800;function Ev(e,t=Dd){window.setTimeout(()=>{if(e){Cr(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const _v="desktop_mode_nonces",kv="desktop-mode/v1",Sv=3e4,Av=3,dn=ie("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function Rd(){return window.wp?.os?.config??{}}function Iv(){const e=Rd().restUrl;return e?it(e,kv):null}function Cv(){dn.state.negativeConfirms=0}async function Lv(){const e=dn.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=Av)return;const t=Iv();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<Sv)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await Be(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}Tv()}catch{}finally{e.confirmInFlight=!1}}}function Tv(){if(!dn.state.exiting){dn.state.exiting=!0,Ev(Rd().adminUrl||"");try{fe({message:k("OpenStation is no longer active. Returning to the WordPress dashboardโ€ฆ"),duration:Dd})}catch{}}}function Nv(){if(dn.state.booted)return;dn.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[_v]!==void 0){Cv();return}Lv()}})}const Ov=0,Lr=40,xd=250,Dv=120,Rv=250,Yn="os-window__loading",Cs="os-window__loading--visible",Ls=ie("desktop-mode/window-reveal-active",()=>({id:Vn,duration:gr}));function Md(e){Ls.state.id=typeof e=="string"&&e!==""?e:Vn}function xv(){const e=Ls.state.id;return!e||e===Vn?null:hd(e)??null}function Pd(e){Ls.state.duration=dd(e)}function Mv(){return Ls.state.duration}function Pv({osSettings:e}){const t=e.getOsSettingsSnapshot();Md(t.windowReveal),Pd(t.windowRevealDuration),e.subscribeOsSettings(n=>{Md(n.windowReveal),Pd(n.windowRevealDuration)})}const un="os-window__reveal",Xn="os-window__reveal--edge",Wv="os-window__reveal--custom",Ot="os-window__body--revealing",Tr="data-os-reveal",Nr="data-os-reveal-layer",wt=new WeakMap,Wd=ie("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function $d(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const $v="--os-window-reveal-duration",Uv="--os-window-reveal-edge-thickness";function Ud(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 Bv(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return dd(Ud(window.getComputedStyle(e).getPropertyValue($v)))}catch{return 0}}function Fv(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function Hv(e,t){const n=Fv(e,Uv);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return cn(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return cn(t*Number(s[1]));const i=Ud(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?cn(i):null}function Bd(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 Gv(e,t){const n=Db(t.duration),o=Mv(),s=o!==gr?o:Bv(e)||n,i=Hv(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=cn(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:cn(r*s/n)}}function Fd(e){return e.querySelector(":scope .os-window__body")}function zv(e){return e.querySelector(`:scope .${un}:not( .${Xn} )`)}function jv(e){return e.querySelector(`:scope .${Xn}`)}function Hd(e){return Array.from(e.querySelectorAll(`:scope .${un}:not( .${Xn} )`))}function Gd(e){return Array.from(e.querySelectorAll(`:scope .${Xn}`))}function Or(e){return Array.from(e.querySelectorAll(`:scope .${un}`))}function zd(e,t,n,o){const s=document.createElement("div");s.className=o?`${un} ${Xn}`:un;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(Tr,e.id),s.setAttribute(Nr,String(n)),s.style.clipPath=t.from,s}function Vv(){const e=xv();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(un),s.classList.add(Wv),s.setAttribute("aria-hidden","true"),s.setAttribute(Tr,e.id),s.setAttribute(Nr,"0"),Wd.set(s,o.play),[s]}const t=ud(e);if(t.length===0)return[];const n=[];return cn(e.edgeLag)>0&&t.forEach((o,s)=>n.push(zd(e,o,s,!0))),t.forEach((o,s)=>n.push(zd(e,o,s,!1))),n}function Kv(e){const t=Fd(e);if(t){t.classList.remove(Ot);for(const n of Or(t))wt.get(n)?.cancel(),wt.delete(n),n.remove();for(const n of Vv())t.appendChild(n)}}function jd(e){const t=Fd(e);if(!t)return;const n=zv(t);if(!n)return;let o;try{o=hd(n.getAttribute(Tr)??"")}catch(C){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",C)}if(!o){Or(t).forEach(C=>C.remove());return}const i=!!t.querySelector(`:scope .${Yn}`)?.classList.contains(Cs)?xd:0,{duration:r,edgeLag:a}=Gv(t,o),c=o.easing??Lb,l=Wd.get(n);if(l){t.classList.add(Ot);const C=()=>{wt.delete(n),n.remove(),t.classList.remove(Ot)};if($d()||typeof n.animate!="function"){window.setTimeout(C,i);return}let V=[];try{V=l({duration:r,easing:c,delay:i})}catch(K){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,K)}if(V.length===0){C();return}V[0].addEventListener("finish",C),V[0].addEventListener("cancel",()=>{wt.delete(n),t.classList.remove(Ot)}),wt.set(n,V[0]);return}const d=jv(t);d&&(a<=0||Bd(d))&&Gd(t).forEach(C=>C.remove()),Bd(n)&&Hd(t).forEach(C=>C.remove());const u=Or(t);if(u.length===0)return;t.classList.add(Ot);const f=()=>{for(const C of u)wt.delete(C),C.remove();t.classList.remove(Ot)};if($d()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=c,v=ud(o),b=(C,V)=>{const K=v[Number(C.getAttribute(Nr))];if(!K)return C.remove(),null;C.style.willChange="clip-path";let j;try{j=C.animate([{clipPath:K.from},{clipPath:K.to}],{duration:V,easing:p,delay:i,fill:"both"})}catch(F){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,F),C.remove(),null}return wt.set(C,j),j},w=Hd(t).map(C=>b(C,r)).filter(C=>C!==null),g=Gd(t).map(C=>b(C,r+a)).filter(C=>C!==null),_=w[0]??null,N=g[0]??null;if(!_&&!N){f();return}(N??_)?.addEventListener("finish",f);const $=()=>{for(const C of u)wt.delete(C);t.classList.remove(Ot)};_?.addEventListener("cancel",$),N?.addEventListener("cancel",$)}const qv="os-window-tab-change";function Vd(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function Kd(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function qd(e,t){return`${e.id||"os-window"}-tab-${Kd(t)}`}function Yd(e,t){return`${e.id||"os-window"}-panel-${Kd(t)}`}function Yv(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 Xv(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 Zv(e){const t=Vd(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 Xd(e){const t=new Map;for(const n of Vd(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function Zd(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 Jv(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of Xd(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 Zd(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}Zv(n),Yv(n),e.dispatchEvent(new CustomEvent(qv,{bubbles:!0,detail:{value:t}}))}}function Qv(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=Xd(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=qd(e,d.value),u.setAttribute("aria-controls",Yd(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();Xv(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of Zd(e)){const u=d.getAttribute("for");u&&(d.id=Yd(e,u),a?d.setAttribute("aria-labelledby",qd(e,u)):d.removeAttribute("aria-labelledby"))}const c=d=>d!==void 0&&t.some(u=>u.value===d),l=[n,i,t[0]?.value].find(c);l!==void 0&&Jv(e,l)}const Zn="os-window__body--loading",Dr="os-window__body--loading-out",Rr="data-os-loading-at",Jd="data-os-loading-cycle";function Ts(e){return e.getAttribute(Jd)??"0"}function eE(e){e.setAttribute(Rr,String(Date.now())),e.setAttribute(Jd,String(Number(Ts(e))+1))}function tE(e,t){const n=Number(e.getAttribute(Rr)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=Dv-o;if(s<=0){t.classList.add(Cs);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(Zn)&&t.classList.add(Cs)},s)}const nE=Symbol.for("desktop-mode/window-config");function oE(e){return e[nE]}const Qd=window.location.origin;function sE(e){const t=new URL(e,Qd);return t.origin!==Qd?null:(t.searchParams.set("openstation_chromeless","1"),t.toString())}function xr(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function eu(){const e=document.createElement("div");e.className=Yn,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",k("Loading window content")),e.appendChild(t),e}function iE(e){let t=eu();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=Z(m.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(Yn)&&t.classList.add(Yn),t}function tu(e){e.querySelector(":scope .os-window__loading")?.remove()}function nu(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=oE(e),s=o?iE(o):eu();t.appendChild(s),tE(t,s)}const ou=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],Ns="osHadFullscreenBeforeOverview";function su(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[Ns]="true",xr()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function iu(e){if(e.element.dataset[Ns]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[Ns],xr();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[Ns],xr()}}function Mr(e,t=!0){t&&iu(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function ru(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function au(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function rE(e){if(e._overviewActive)return;cu(e);const t=e._stack.filter(l=>l.config.desktopId===e._activeDesktopId);e._overviewActive=!0,T(m.OVERVIEW_ENTERING,{}),T(m.DOCK_REFRESH_ACTIVE,{});for(const l of ou){const d=document.getElementById(l);d&&(d.inert=!0)}ru(!0),au(e,!0),e._overviewSnapshot.clear();for(const l of t)e._overviewSnapshot.set(l.id,{transform:l.element.style.transform||"",transition:l.element.style.transition||""});for(const l of t)su(l);const n=e._desktop.getBoundingClientRect(),o=Array.from(document.querySelectorAll(".os-dock"));let s=0;for(const l of o){const d=l.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=lu(e),e._desktop.appendChild(e._overviewTopBar);const a=ar(t,i,$l);e._overviewLabels.clear();for(const l of a){const d=l.win.element;d.classList.add("os-window--overview");const u=l.x-d.offsetLeft,f=l.y-d.offsetTop;d.style.transform=`translate(${u}px, ${f}px) scale(${l.scale})`;const p=Pr(l);d.insertAdjacentElement("afterend",p),e._overviewLabels.set(l.win.id,p)}const c=l=>{const d=l.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=l=>{if(l.button!==0){e._overviewPressTarget=null;return}e._overviewPressTarget=c(l),e._overviewPressTarget&&(l.preventDefault(),l.stopPropagation())},e._overviewPointerUpHandler=l=>{if(l.button!==0)return;const d=e._overviewPressTarget;if(e._overviewPressTarget=null,!d)return;const u=d.element.getBoundingClientRect();if(!(l.clientX>=u.left&&l.clientX<=u.right&&l.clientY>=u.top&&l.clientY<=u.bottom))return;if(l.preventDefault(),l.stopPropagation(),d.id==="backdrop"){Dt(e);return}const p=e.getById(d.id);T(m.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),Dt(e,p)},e._overviewKeyHandler=l=>{if(l.key==="Escape"){Dt(e);return}if(l.key==="Enter"){const u=l.target?.ownerDocument||document;if(u.activeElement&&u.activeElement.tagName==="BUTTON")return;if(l.preventDefault(),e._overviewAddTileFocused){du(e);return}Dt(e)}},e._desktop.addEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._desktop.addEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewClickBlocker=l=>{l.target?.closest(".os-overview-top-bar")||(l.stopPropagation(),l.preventDefault())},e._desktop.addEventListener("click",e._overviewClickBlocker,!0),document.addEventListener("keydown",e._overviewKeyHandler),e._lastOverviewHoverId=null,e._overviewMouseHandler=l=>{const u=l.target?.closest(".os-window--overview"),f=u?u.id.replace(/^wp-window-/,""):null;f!==e._lastOverviewHoverId&&(e._lastOverviewHoverId&&T(m.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&T(m.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&T(m.OVERVIEW_ENTERED,{})},300)}function cu(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function aE(e){e._overviewEnterTimeoutId!==null&&(window.clearTimeout(e._overviewEnterTimeoutId),e._overviewEnterTimeoutId=null),e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null),e._overviewExitFinalizer=null}function lu(e){const t=document.createElement("div");t.className="os-overview-top-bar";const n=document.createElement("div");n.className="os-overview-top-bar__list",t.appendChild(n);for(const s of e._desktops)n.appendChild(cE(e,s));const o=document.createElement("button");return o.type="button",o.className="os-overview-top-bar__tile os-overview-top-bar__tile--add",e._overviewAddTileFocused&&o.classList.add("os-overview-top-bar__tile--cursor"),o.setAttribute("aria-label",k("Add new desktop")),o.innerHTML='<span class="os-overview-top-bar__tile-plus" aria-hidden="true">+</span>',o.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),du(e)}),n.appendChild(o),t}function du(e){const t=pu(e);e._overviewAddTileFocused=!1,uu(e,t.id)}function cE(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",de(k("Switch to %s"),t.label));const s=document.createElement("span");s.className="os-overview-top-bar__tile-preview";const i=e._stack.filter(l=>l.config.desktopId===t.id).length;if(i>0){const l=document.createElement("span");l.className="os-overview-top-bar__tile-count",l.textContent=String(i),s.appendChild(l)}o.appendChild(s);const r=document.createElement("span");r.className="os-overview-top-bar__tile-label",r.textContent=t.label,o.appendChild(r),o.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),!r.hasAttribute("contenteditable")&&uu(e,t.id)});const a=document.createElement("button");a.type="button",a.className="os-overview-top-bar__tile-rename",a.setAttribute("aria-label",de(k("Rename %s"),t.label)),a.innerHTML=sn("edit",{size:14}),a.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),lE(e,r,t)});const c=document.createElement("button");return c.type="button",c.className="os-overview-top-bar__tile-close",c.setAttribute("aria-label",de(k("Close %s"),t.label)),c.innerHTML=sn("close",{size:16}),c.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),gu(e,t.id),Os(e)}),n.appendChild(o),n.appendChild(a),n.appendChild(c),n}function lE(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=c=>{r||(r=!0,t.removeAttribute("contenteditable"),c&&hu(e,n.id,t.textContent??""),e._overviewActive&&Os(e))};t.addEventListener("keydown",c=>{c.stopPropagation(),(c.key==="Enter"||c.key==="Escape")&&(c.preventDefault(),a(c.key==="Enter"))}),t.addEventListener("blur",()=>a(!0)),t.addEventListener("click",c=>c.stopPropagation())}function Os(e){if(!e._overviewTopBar)return;const t=lu(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function uu(e,t){mu(e,t),Dt(e)}function Pr(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=de(Gn("ยท %d open tab","ยท %d open tabs",r),r),t.appendChild(a)}return t}function Dt(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,T(m.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),T(m.DOCK_REFRESH_ACTIVE,{}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of ou){const r=document.getElementById(i);r&&(r.inert=!1)}ru(!1),au(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"&&(iu(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"),Mr(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),T(m.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>cu(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&&(T(m.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function dE(e){return[...e._desktops]}function fu(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function uE(e){return fu(e).id}function Wr(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&Mr(t)}function $r(e){for(const t of e._stack)Wr(e,t)}function pu(e){e._desktopSeq++;const t={id:`desktop-${e._desktopSeq}`,label:de(k("Desktop %d"),e._desktopSeq)};return e._desktops.push(t),T(m.DESKTOP_CREATED,{desktopId:t.id}),t}const fE=64;function hu(e,t,n){const o=e._desktops.find(r=>r.id===t);if(!o)return!1;const s=n.trim().slice(0,fE);if(!s||s===o.label)return!1;const i=o.label;return o.label=s,T(m.DESKTOP_RENAMED,{desktopId:t,label:s,previousLabel:i}),!0}function mu(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)wu(e),Os(e);else{$r(e),n?.direction&&pE(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&&Uy(e._desktop,i.label)}T(m.DESKTOP_SWITCHED,{from:o,to:t})}function pE(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 gu(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?wu(e):$r(e),T(m.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function wu(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"),Mr(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),$r(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||""}),su(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=ar(t,o,$l);for(const i of s){const r=i.win.element;r.classList.add("os-window--overview");const a=i.x-r.offsetLeft,c=i.y-r.offsetTop;r.style.transform=`translate(${a}px, ${c}px) scale(${i.scale})`;const l=Pr(i);r.insertAdjacentElement("afterend",l),e._overviewLabels.set(i.win.id,l)}}function hE(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)}const mE=8,yu=Object.freeze({top:0,right:0,bottom:0,left:0});function bu(e,t,n,o){return{left:e,top:t,width:n,height:o,right:e+n,bottom:t+o}}function gE(e,t){const n={top:Math.abs(t.top-e.top),bottom:Math.abs(e.bottom-t.bottom),left:Math.abs(t.left-e.left),right:Math.abs(e.right-t.right)},s=t.height>t.width?["left","right","top","bottom"]:["top","bottom","left","right"];let i=s[0];for(const r of s)n[r]<n[i]&&(i=r);return i}function wE(e,t,n=mE){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),c=Math.min(e.bottom,r.bottom)-Math.max(e.top,r.top);if(!(a<=0||c<=0))switch(gE(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 vu(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 yE(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 bE(e,t){return e.top===t.top&&e.right===t.right&&e.bottom===t.bottom&&e.left===t.left}function Eu(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const vE="os-work-area-changed",EE="data-os-dock-behavior",_E="os/work-area";function kE(){return{insets:{...yu},rect:{x:0,y:0,width:0,height:0},viewport:{x:0,y:0,width:0,height:0},area:{width:0,height:0}}}const rt=ie(_E,()=>({snapshot:kE(),installed:!1,areaEl:null})),fn={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 Ur(e){return{insets:{...e.insets},rect:{...e.rect},viewport:{...e.viewport},area:{...e.area}}}function SE(){return Ur(rt.state.snapshot)}function Ce(e){const t=e??rt.state.areaEl;if(!t)return{...rt.state.snapshot.rect};const n=t.clientWidth||t.getBoundingClientRect().width,o=t.clientHeight||t.getBoundingClientRect().height;return vu(n,o,rt.state.snapshot.insets)}function AE(e){const{installed:t,snapshot:n}=rt.state;if(!t)return{...yu};const o=n.viewport;return yE(bu(o.x,o.y,o.width,o.height),e.getBoundingClientRect())}function Br(e){return rt.subscribe(t=>{e(Ur(t.snapshot))})}function IE(e){const t=CE(e),n=[],o=e.shellBody.querySelectorAll(e.chromeSelector??".os-dock");for(const c of Array.from(o))c.hidden||c.getAttribute(EE)==="dynamic"||n.push(c.getBoundingClientRect());const s=wE(t,n),i=e.area.clientWidth||t.width,r=e.area.clientHeight||t.height,a=vu(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 CE(e){const{area:t}=e;if(t.offsetWidth>0&&t.offsetParent===e.shellBody){const n=e.shellBody.getBoundingClientRect();return bu(n.left+t.offsetLeft,n.top+t.offsetTop,t.offsetWidth,t.offsetHeight)}return t.getBoundingClientRect()}function LE(e,t){e.style.setProperty(fn.top,`${t.insets.top}px`),e.style.setProperty(fn.right,`${t.insets.right}px`),e.style.setProperty(fn.bottom,`${t.insets.bottom}px`),e.style.setProperty(fn.left,`${t.insets.left}px`),e.style.setProperty(fn.width,`${t.rect.width}px`),e.style.setProperty(fn.height,`${t.rect.height}px`)}function TE(e,t){return bE(e.insets,t.insets)&&Eu(e.rect,t.rect)&&Eu(e.viewport,t.viewport)&&e.area.width===t.area.width&&e.area.height===t.area.height}function NE(e){const t=new Map;let n=null,o=null,s=!1,i=!1,r=null;const a=()=>{if(s||i)return;const p=IE(e);if(!!rt.state.installed&&TE(rt.state.snapshot,p))return;LE(e.shell,p),rt.setState({snapshot:p,installed:!0,areaEl:e.area});const b=Ur(p);T(m.WORK_AREA_CHANGED,b),document.dispatchEvent(new CustomEvent(vE,{detail:b}))},c=typeof ResizeObserver<"u",l=()=>{if(!c)return;const p=new Set(Array.from(e.shellBody.querySelectorAll(e.chromeSelector??".os-dock")));for(const[v,b]of t)p.has(v)||(b.disconnect(),t.delete(v));for(const v of p){if(t.has(v))continue;const b=new ResizeObserver(a);b.observe(v),t.set(v,b)}};c&&(n=new ResizeObserver(a),n.observe(e.area)),typeof MutationObserver<"u"&&(o=new MutationObserver(()=>{l(),a()}),o.observe(e.shellBody,{childList:!0}));const d=()=>{l(),a()};document.addEventListener("os-layout-changed",d),window.addEventListener("resize",a);const u=()=>{i=!0},f=()=>{i=!1,a()};return ne(m.OVERVIEW_ENTERING,Ds,u),ne(m.OVERVIEW_EXITED,Ds,f),l(),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),Fn(m.OVERVIEW_ENTERING,Ds),Fn(m.OVERVIEW_EXITED,Ds),Rs===r&&(Rs=null)}},Rs=r,r}const Ds="openstation/work-area";let Rs=null;function OE(){Rs?.refresh()}const DE={get:SE,rectOf:Ce,insetsOf:AE,subscribe:Br};function RE(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;T(m.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=Ce(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)),c=Math.max(1,Math.floor((n.height-r-o)/s)),l=Math.min(a,c);t.forEach((u,f)=>{const p=f%Math.max(1,l);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"}})),T(m.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function xE(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=Ce(e._desktop),o=Gy(t.length,n.width,n.height),s=Z(m.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=Fy(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;T(m.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,c=12,l=Math.floor((n.width-a*2-c*(i-1))/i),d=Math.floor((n.height-a*2-c*(r-1))/r);t.forEach((f,p)=>{const v=p%i,b=Math.floor(p/i);f.element.style.left=`${n.x+a+v*(l+c)}px`,f.element.style.top=`${n.y+a+b*(d+c)}px`,f.element.style.width=`${l}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"}})),T(m.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}const _u="desktop-mode-snap-to-grid";function ME(){try{return window.localStorage.getItem(_u)==="1"}catch{return!1}}function PE(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(_u,t?"1":"0")}catch{}T(m.ARRANGE_SNAP_CHANGED,{enabled:t})}}function WE(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=Z(m.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=Hy(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function $E(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){ku(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=GE(e,n),i=ar(o,s,0);e._splitOverviewLabels.clear();for(const a of i){const c=a.win.element;c.classList.add("os-window--overview");const l=a.x-c.offsetLeft,d=a.y-c.offsetTop;c.style.transform=`translate(${l}px, ${d}px) scale(${a.scale})`;const u=Pr(a);c.insertAdjacentElement("afterend",u),e._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const c=a.target,l=c?.closest(".os-window--overview");return l?{id:l.id.replace(/^wp-window-/,""),element:l}:c?{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 c=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!c)return;const l=c.element.getBoundingClientRect();if(!(a.clientX>=l.left&&a.clientX<=l.right&&a.clientY>=l.top&&a.clientY<=l.bottom))return;if(a.preventDefault(),a.stopPropagation(),c.id==="dismiss"){Jn(e);return}const u=e.getById(c.id);if(!u){Jn(e);return}UE(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&Jn(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 UE(e,t){const n=e._splitOverviewZone;if(!n){Jn(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),T(m.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),Jn(e)}function Jn(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();ku(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 ku(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const Su=30,BE=260;function FE(e,t){return e<=t.left+Su?"left":e>=t.right-Su?"right":null}function HE(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?0:n.width-o,y:0,width:o,height:s}}function GE(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 zE(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=HE(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 Fr(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()},BE)}function jE(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=FE(n,o),i=e._snapPendingZone;s?(zE(e,s),i!==s&&T(m.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(Fr(e),T(m.SNAP_ZONE_CANCELED,{windowId:t.id}))}function VE(e,t){const n=e._snapPendingZone;return n?(Fr(e),t.state==="normal"&&(t._savedGeometry={x:t.element.offsetLeft,y:t.element.offsetTop,width:t.element.offsetWidth,height:t.element.offsetHeight}),t.applySnap(n),T(m.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{$E(e,t,n)}),!0):!1}function KE(e){e._snapPendingZone&&Fr(e)}const Au="desktop-mode-native-window-geometry",Iu=64,Je=8192;function xs(){try{const e=window.localStorage.getItem(Au);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function Cu(e){try{window.localStorage.setItem(Au,JSON.stringify(e))}catch{}}function Hr(e){if(!e)return null;const n=xs()[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>Je||s>Je)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),a=Number(n.y),c=Number.isFinite(r)&&Number.isFinite(a)&&r>=0&&a>=0&&r<=Je&&a<=Je;return{width:Math.round(o),height:Math.round(s),...c?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function Lu(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>Je||o>Je)return;const s=xs(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,c=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===c||(Qn(s,e,{width:n,height:o,...typeof a=="number"&&typeof c=="number"?{x:a,y:c}:{},...r?{state:r}:{}}),eo(s))}function Tu(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>Je||o>Je)return;const s=xs(),i=s[e];i&&(i.x===n&&i.y===o||(Qn(s,e,{...i,x:n,y:o}),eo(s)))}function Nu(e,t,n){if(!e)return;const o=xs(),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>Je||r>Je)return;Qn(o,e,{width:i,height:r,state:t}),eo(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;Qn(o,e,r),eo(o);return}s.state!==t&&(Qn(o,e,{...s,state:t}),eo(o))}function Qn(e,t,n){delete e[t],e[t]=n}function eo(e){const t=Object.keys(e);if(t.length>Iu){const n={};for(const o of t.slice(-Iu))n[o]=e[o];Cu(n);return}Cu(e)}function qE(e,t,n,o){const s=o.x+Lr-n,i=o.x+o.width-Lr,r=Math.max(s,Math.min(e,i)),a=o.y+Ov,c=o.y+o.height-Lr,l=Math.max(a,Math.min(t,c));return{x:r,y:l}}const Ou=100,Ms=30;class YE{constructor(t){this._stack=[],this._cascadeMinimized=new WeakSet,this._cascadeDepth=0,this.cascadeIndex=0,this._pendingRestoreState=new Map,this._prewarmed=null,this._prewarmInFlight=!1,this._desktops=[{id:"desktop-1",label:"Desktop 1"}],this._activeDesktopId="desktop-1",this._desktopSeq=1,this.onToggleStartupRequested=null,this.desktopResizeObserver=null,this._reflowRestoreTimer=null,this._snapEnabled=ME(),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._splitOverviewActive=!1,this._splitOverviewAnchor=null,this._splitOverviewZone=null,this._splitOverviewSnapshot=new Map,this._splitOverviewLabels=new Map,this._splitOverviewPointerDown=null,this._splitOverviewPointerUp=null,this._splitOverviewPressTarget=null,this._splitOverviewClickBlocker=null,this._splitOverviewKey=null,this._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const t=this._desktop.ownerDocument?.activeElement??null;if(!t||t.tagName!=="IFRAME")return;const n=t.closest(".os-window");if(!n)return;const o=n.id.replace(/^wp-window-/,""),s=this.getById(o);s&&(this._overviewActive||this.getFocused()!==s&&this.focus(s))},0)})}reflowStatefulWindows(){if(!this._overviewActive){for(const t of this._stack){const n=t.element.parentElement;if(!n)continue;const o={x:0,y:0,width:n.clientWidth,height:n.clientHeight};if(t.state==="maximized")t.element.classList.add("os-window--reflowing"),t.element.style.left=`${o.x}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${o.width}px`,t.element.style.height=`${o.height}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("os-window--reflowing");const s=Math.floor(o.width/2),i=o.height,r=t.state==="snapped-left"?o.x:o.x+o.width-s;t.element.style.left=`${r}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${s}px`,t.element.style.height=`${i}px`}else if(t.state==="normal"){const s=parseInt(t.element.style.left,10)||0,i=parseInt(t.element.style.top,10)||0,r=t.element.offsetWidth||0,a=qE(s,i,r,o);(s!==a.x||i!==a.y)&&(t.element.classList.add("os-window--reflowing"),t.element.style.left=`${a.x}px`,t.element.style.top=`${a.y}px`)}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const t of this._stack)t.element.classList.remove("os-window--reflowing")},140)}}async open(t){if(!t||typeof t!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(t===null?"null":typeof t));if(typeof t.id!="string"||t.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof t.url!="string"||t.url==="")throw new TypeError('windowManager.open(): config.url must be a non-empty string. Pass an admin URL (e.g. "/wp-admin/edit.php") or a hash fragment (e.g. "#my-window") for native windows.');if(typeof t.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=t.baseId||t.id,o=this.getByBaseIdOnActiveDesktop(n);if(o){const r=o.state==="minimized";this.focus(o),r&&o.restore();let a=!1;if(!o.config.native){const l=tn(t.url);l===tn(o.getCurrentUrl())||l===tn(o.config.url||"")||l===tn(o.config.parentUrl??o.config.url??"")||(a=o.navigateTo(t.url))}t.params&&(o.config.params={...t.params});const c={windowId:o.id,baseId:n,wasMinimized:r,navigated:a,params:o.config.params??{}};return document.dispatchEvent(new CustomEvent("os-window-reopened",{detail:c})),T(m.WINDOW_REOPENED,c),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(tn(n.url)!==tn(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),Wr(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})),T(m.WINDOW_OPENED,i),s}discardPrewarmed(){const t=this._prewarmed;t&&(this._prewarmed=null,window.clearTimeout(t.timer),this.teardownSpeculativeWindow(t.win))}teardownSpeculativeWindow(t){try{globalThis.__openStationConnectionBridge?.onWindowClosed?.(t.id)}catch{}t.onClose=null;try{t.destroy()}catch{}t.element.remove()}async openNew(t){const n=t.baseId||t.id,o=t.id!==n&&!this.getById(t.id)?t.id:this.nextInstanceId(n),s=40+this.cascadeIndex%8*Ms,i=40+this.cascadeIndex%8*Ms;return this.createWindow({initialState:"normal",x:s,y:i,...t,id:o,baseId:n})}async createWindow(t,n={}){const o=this._pendingRestoreState.get(t.id);o&&(this._pendingRestoreState.delete(t.id),t={...t,...o});const s=this._desktop.getBoundingClientRect(),i=Ce(this._desktop),r=12,a=Math.min(Math.round(i.width*.8),1200),c=Math.min(Math.round(i.height*.8),800),l=i.x+40+this.cascadeIndex%8*Ms,d=i.y+40+this.cascadeIndex%8*Ms,u=t.baseId||t.id,f=t.minWidth??320,p=t.minHeight??200,v=typeof t.width=="number",b=typeof t.height=="number",w=typeof t.x=="number",g=typeof t.y=="number",_=typeof t.initialState=="string",N=!v||!b||!_||!w||!g?Hr(u):null;let $=t.width??(N?Math.max(N.width,f):a),C=t.height??(N?Math.max(N.height,p):c);!w&&!g&&!N&&($=Math.max(f,Math.min($,i.width-r*2)),C=Math.max(p,Math.min(C,i.height-r*2)));const K=Math.max(i.x+r,Math.min(l,i.x+i.width-$-r)),j=Math.max(i.y+r,Math.min(d,i.y+i.height-C-r)),F=t.initialState??(N?.state==="maximized"?"maximized":void 0);let E,B;if(N&&typeof N.x=="number"&&typeof N.y=="number"){const X=Math.max(i.x,i.x+i.width-$-r),oe=Math.max(i.y,i.y+i.height-C-r);E=Math.max(i.x+r,Math.min(N.x,X)),B=Math.max(i.y+r,Math.min(N.y,oe))}const P=t.x??E??K,h=t.y??B??j,A=v||b||w||g||_,O=!!N,G={x:P,y:h,width:$,height:C,state:F};let Y;try{Y=Z(m.WINDOW_GEOMETRY,G,{windowId:t.id,baseId:u,hasSavedGeometry:O,callerPinned:A,desktopRect:{width:s.width,height:s.height},workArea:{...i}})}catch(X){T(m.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:X}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,X),Y=G}const I=(X,oe)=>typeof X=="number"&&Number.isFinite(X)?X:oe,S=Y&&typeof Y=="object"?Y:G,M=Math.max(I(S.width,$),f),D=Math.max(I(S.height,C),p),U=I(S.x,P),H=I(S.y,h),W=S.state??F,L={icon:t.icon||"dashicons-admin-generic",...t,x:U,y:H,width:M,height:D,minWidth:f,minHeight:p,...W?{initialState:W}:{},baseId:u,desktopId:t.desktopId||this._activeDesktopId};this.cascadeIndex++;const[z]=await Promise.all([My(Ry()),or(sr())]),R=z.createWindow(L);if(R.onFocusRequest=X=>{this._cascadeDepth>0||this.focus(X)},R.onClose=X=>this.remove(X),R.onMinimize=X=>{this._cascadeDepth++;try{this.cascadeMinimize(X)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const oe=this._stack.filter(ce=>ce.state!=="minimized");oe.length>0&&this.focus(oe[oe.length-1])},R.onRestore=X=>{this._cascadeDepth++;try{this.cascadeRestore(X)}finally{this._cascadeDepth--}},R.onOpenAnother=X=>{const oe=X.config.baseId||X.id;X.config.native&&window.wp?.os?.openNewWindow?.(oe,{source:"open-another"})||this.openNew({id:oe,baseId:oe,url:X.config.url||"",title:X.config.title,icon:X.config.icon,submenu:X.config.submenu,multi:!0})},R.onOpenInNewWindow=X=>{const oe=X.config.baseId||X.id;if(X.config.native&&window.wp?.os?.openNewWindow?.(oe,{source:"open-in-new-window"}))return;const ce=X.getCurrentUrl();this.openNew({id:oe,baseId:oe,url:ce||X.config.url||"",title:X.config.title,icon:X.config.icon,submenu:X.config.submenu,multi:!0})},R.onToggleStartup=X=>{this.onToggleStartupRequested?.(X)},R.snapConfigProvider=()=>this.getSnapConfig(),R.onDragMove=(X,oe)=>{jE(this,X,oe)},R.onDragEnd=X=>this._snapPendingZone?VE(this,X):(KE(this),!1),n.prewarm)return R.element.style.display="none",R.element.setAttribute("aria-hidden","true"),this._desktop.appendChild(R.element),R;this._stack.push(R),this._desktop.appendChild(R.element),Wr(this,R),R.hydrateNative(),this.focus(R);const ae={windowId:R.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:ae})),T(m.WINDOW_OPENED,ae),R}nextInstanceId(t){const n=new Set(this._stack.map(s=>s.id));if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=typeof t=="string"?this.getById(t):t;if(!n||typeof n.setZIndex!="function"){t&&typeof t!="string"&&console.warn("[openstation] windowManager.focus() expects a Window or a window id; received",t);return}const o=this.blockingChildOf(n)??n;o!==n&&(o.shake?.(),T(m.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(c=>c!==o&&c.isFocused()&&c.isFullscreen());i&&Z(m.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((c,l)=>{c.setZIndex(Ou+l),c.setFocused(l===this._stack.length-1)}),s&&s!==o&&s.id!==o.id){const c={windowId:s.id,focusedTo:o.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:c})),T(m.WINDOW_BLURRED,c)}const a={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:a})),T(m.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(Ou+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=Hr(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(),c=n.width??Math.round(a.width*.8),l=n.height??Math.round(a.height*.8),d=Ce(this._desktop),u=Math.max(d.x,d.x+d.width-c),f=Math.max(d.y,d.y+d.height-l);r={width:c,height:l,x:Math.min(u,Math.max(d.x,Math.round(a.x+(a.width-c)/2))),y:Math.min(f,Math.max(d.y,Math.round(a.y+(a.height-l)/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})),T(m.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),T(m.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 dE(this)}getActiveDesktop(){return fu(this)}getActiveDesktopId(){return uE(this)}createDesktop(){return pu(this)}switchDesktop(t,n){mu(this,t,n)}closeDesktop(t){gu(this,t)}renameDesktop(t,n){return hu(this,t,n)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=Z(m.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));T(m.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=Z(m.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(c=>!i.includes(c));let a=0;for(const c of i.slice())try{c.close(),a++}catch(l){typeof console<"u"&&console.error("[openstation] closeAll: window.close() threw for",c.id,l)}return T(m.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r}),a}minimizeAll(){const t=[];for(const n of this._stack.slice())if((n.config.desktopId||this._activeDesktopId)===this._activeDesktopId&&n.state!=="minimized")try{n.minimize(),t.push(n)}catch(s){typeof console<"u"&&console.error("[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(){RE(this)}tile(){xE(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){PE(this,t)}getSnapConfig(){return WE(this)}enterOverview(){rE(this)}exitOverview(t,n=!1){Dt(this,t,n)}destroy(){this._overviewActive&&Dt(this),this.discardPrewarmed(),aE(this),By()}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(i=>!i.config.ephemeral&&!i.config.parentWindowId).map(i=>{const r=i.getSnapshot(),a=i.getExternalTabsSnapshot(),c=!!i.config.native,l=i.config.params,d=c&&l?this.sanitizeParams(l):null;return{id:i.id,baseId:i.config.baseId||i.id,desktopId:i.config.desktopId||this._activeDesktopId,...c?{native:!0}:{},...d?{params:d}:{},url:c?i.config.url||`#${i.id}`:i.getCurrentUrl(),title:i.config.title,icon:i.config.icon,state:r.state,x:r.x,y:r.y,width:r.width,height:r.height,...a.length>0?{externalTabs:a}:{}}}),s=t&&!t.config.ephemeral&&!t.config.parentWindowId?t.id:"";return{windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Date.now()}}seedWindowRestoreState(t){this._pendingRestoreState=new Map(Object.entries(t))}seedDesktops(t,n){hE(this,t,n)}}function XE(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 Du(e,t){if(e._overviewActive)return;const n=XE(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 Ru=!1;function xu(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;if(!t)return!1;if(t instanceof HTMLIFrameElement||t instanceof HTMLTextAreaElement)return!0;if(t instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(t.type);if(t instanceof HTMLElement&&t.isContentEditable===!0)return!0;const n=t.getAttribute("contenteditable");return n!==null&&n!=="false"}function ZE(e){if(Ru)return;Ru=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(xu(document)||(n.preventDefault(),Du(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"||Du(e,o.direction==="prev"?"prev":"next")})}function Mu(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 Pu(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(c=>c.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,Os(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function JE(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function QE(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Wu(e){return e._overviewActive?(e.exitOverview(),!0):!1}function e_(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function t_(e){return e_(e)?(e.toggleShowDesktop(),!0):!1}let $u=!1;function n_(e){$u||($u=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||xu(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Pu(e,"prev"):Mu(e,"prev");break;case"ArrowRight":n=e._overviewActive?Pu(e,"next"):Mu(e,"next");break;case"ArrowUp":n=Wu(e)||t_(e)||JE(e);break;case"ArrowDown":n=Wu(e)||QE(e);break}n&&t.preventDefault()},!0))}const Uu=xd;let Bu=!1;function Fu(e){return e?document.getElementById(`wp-window-${e}`):null}function o_(){Bu||(Bu=!0,s_())}function s_(){ne(m.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=Fu(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove(Dr),n.classList.add(Zn),eE(n),nu(t),Kv(t))}),ne(m.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=Fu(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 .${Yn}`)?.classList.contains(Cs);if(n.classList.remove(Zn),n.removeAttribute(Rr),!o){tu(t),jd(t);return}n.classList.add(Dr);const s=Ts(n);jd(t),window.setTimeout(()=>{Ts(n)===s&&(n.classList.contains(Zn)||tu(t))},Uu),window.setTimeout(()=>{Ts(n)===s&&(n.classList.contains(Zn)||n.classList.remove(Dr))},Uu+Rv)}),ne(m.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Hu())})}function Hu(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),nu(n))})}const i_="os_person_view";function r_(e){return e.searchParams.has(i_)}const to=ie("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function a_(e){to.state.deps=e}function yt(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.nativeWindowId!="string"||e.nativeWindowId==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=to.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>c_(e.id)}function c_(e){const t=to.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function Ps(e){const{deps:t,remaps:n}=to.state;if(!t||!e)return null;let o;try{o=new URL(e,t.adminUrl)}catch{return null}const s=t.getSnapshot();for(const i of n)if(i.matches(e,o)&&!(i.enabled&&!i.enabled(s)))return i.nativeWindowId;return null}function Qe(e){const{deps:t,remaps:n}=to.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(c){console.warn(`[openstation] URL remap onMatch hook threw for "${i.id}":`,c)}let r;if(i.params)try{r=i.params(e,o)??void 0}catch(c){console.warn(`[openstation] URL remap params hook threw for "${i.id}":`,c)}if(r?t.openById(i.nativeWindowId,{params:r}):t.openById(i.nativeWindowId))return!0}return!1}const l_="desktop_mode_classic";function d_(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has("page")&&!e.searchParams.has(l_)}const Gr=ie("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function u_(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=Gr.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Gu(e.id)}function Gu(e){const t=Gr.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function f_(){return Gr.state.entries.slice()}const p_=32,h_=64,m_=/^[a-z0-9_/-]+$/,me=ie("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function Rt(e){return`${e.type}:${e.id}`}function zu(e){return e.root?Rt(e.root):Rt(e)}function ju(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&m_.test(o.trim().toLowerCase());return Tt(e,[{field:"type",valid:o=>n(o.type),message:"must match /^[a-z0-9_/-]+$/ โ€” lowercase alphanum, hyphens, underscores, slashes for vendor/sub-type"},{field:"id",valid:o=>t(o.id),message:"must be a finite number or non-empty string"},{field:"root",valid:o=>o.root===void 0||!!o.root&&typeof o.root=="object"&&n(o.root.type)&&t(o.root.id),message:"when present, must be { type, id } with the same shapes as the ref itself"},{field:"related",valid:o=>o.related===void 0||Array.isArray(o.related)&&o.related.every(s=>!!s&&typeof s=="object"&&typeof s.id=="string"&&s.id.trim()!==""&&typeof s.group=="string"&&s.group.trim()!==""&&typeof s.label=="string"&&s.label.trim()!==""&&typeof s.url=="string"&&s.url.trim()!==""&&(s.groupLabel===void 0||typeof s.groupLabel=="string")&&(s.icon===void 0||typeof s.icon=="string")&&(s.count===void 0||typeof s.count=="number"&&Number.isFinite(s.count))),message:"when present, must be an array of { id, group, label, url, groupLabel?, icon?, count? } entries with non-empty strings"},{field:"links",valid:o=>o.links===void 0||Array.isArray(o.links)&&o.links.every(s=>!!s&&typeof s=="object"&&n(s.type)&&t(s.id)&&(s.rel===void 0||s.rel==="references"||s.rel==="child")),message:"when present, must be an array of { type, id, rel?: 'references'|'child' } entries"}])}function g_(e,t){const n={type:e.type.trim().toLowerCase(),id:e.id,source:t};if(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,p_).map(o=>{const s={type:o.type.trim().toLowerCase(),id:o.id};return o.rel==="child"&&(s.rel="child"),s})),typeof e.label=="string"&&e.label!==""&&(n.label=e.label),typeof e.previewUrl=="string"&&e.previewUrl!=="")try{new URL(e.previewUrl,window.location.origin).origin===window.location.origin&&(n.previewUrl=e.previewUrl)}catch{}return Array.isArray(e.related)&&e.related.length>0&&(n.related=e.related.slice(0,h_).map(o=>{const s={id:o.id,group:o.group,label:o.label,url:o.url};return typeof o.groupLabel=="string"&&o.groupLabel!==""&&(s.groupLabel=o.groupLabel),typeof o.icon=="string"&&o.icon!==""&&(s.icon=o.icon),typeof o.count=="number"&&(s.count=o.count),s})),n}function Vu(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 zr(e){return e?[Rt(e),zu(e),...(e.links??[]).map(t=>Rt(t)+(t.rel==="child"?"!child":""))].join("|"):""}function Ws(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Ie("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=ju(t);if(a.length>0){o==="api"&&Ie("WindowContentRef",a,t),Gl("WindowContentRef",a,t);return}s=g_(t,o)}if(s=Z(m.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||ju(s).length>0)){Gl("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=me.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&zr(s)===zr(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&Vu(s)===Vu(i))return;s===null?me.state.contentByWindow.delete(e):me.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})),T(m.WINDOW_CONTENT_CHANGED,r),E_(),b_()}function bt(e){return me.state.contentByWindow.get(e)}function jr(){const e=new Map;for(const[s,i]of me.state.contentByWindow){const r=zu(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=me.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=Z(m.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 Ku(e){return jr().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function w_(e){const t=new Set,n=Ku(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of qu())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function qu(){const e=me.state.focusSeq,t=new Map;for(const[a,c]of me.state.contentByWindow){const l=Rt(c),d=t.get(l);(!d||(e.get(a)??0)>(e.get(d)??0))&&t.set(l,a)}const n=new Map,o=(a,c)=>`${a}โ†’${c}`;for(const[a,c]of me.state.contentByWindow){if(c.root){const l=t.get(Rt(c.root));l&&l!==a&&n.set(o(a,l),{fromWindowId:a,toWindowId:l,kind:"child-root",bidirectional:!1})}for(const l of c.links??[]){const d=t.get(Rt(l));if(!d||d===a)continue;if(l.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,c]of n){if(i.has(a))continue;const l=o(c.toWindowId,c.fromWindowId),d=n.get(l);if(d&&c.kind==="reference"){if(d.kind==="reference"){i.add(l),s.push({...c,bidirectional:!0});continue}continue}s.push(c)}const r=Z(m.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 y_(e){return me.state.listeners.add(e),()=>{me.state.listeners.delete(e)}}function b_(){for(const e of Array.from(me.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function v_(){return Array.from(me.state.contentByWindow).map(([e,t])=>`${e}=${zr(t)}`).sort().join(";")}function E_(){const e=v_();if(e===me.state.lastGroupsSignature)return;me.state.lastGroupsSignature=e;const n={groups:jr()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),T(m.WINDOW_LINK_GROUPS_CHANGED,n)}const __={get:bt,set:(e,t)=>Ws(e,t,{source:"api"}),groups:jr,edges:qu,groupOf:Ku,related:w_,subscribe:y_};function k_({manager:e}){me.state.manager=e,!me.state.started&&(me.state.started=!0,ne(m.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=me.state.manager?.getById(t.windowId)?.config?.content;o&&Ws(t.windowId,o,{source:"config"})}),ne(m.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(me.state.focusSeq.delete(t.windowId),Ws(t.windowId,null,{source:"config"}))}),ne(m.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(me.state.seq+=1,me.state.focusSeq.set(t.windowId,me.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=me.state.manager?.findByIframeSource?.(t.source);o&&Ws(o.id,n.identity??null,{source:"bridge"})}))}const S_=ie("desktop-mode/admin-link-deps",()=>({deps:null}));function A_(e){S_.state.deps=e}const Yu=ie("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),pn=Yu.state.seed,I_=Yu.state.listeners;function hn(e){Ie("Wallpaper",Tt(e,Qu),e);const t=pn.findIndex(n=>n.id===e.id);t>=0?pn[t]=e:pn.push(e),Zu()}function Xu(e){const t=pn.findIndex(n=>n.id===e);t>=0&&(pn.splice(t,1),Zu())}function Zu(){const e=Array.from(I_);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function Ju(){const e=pn.slice(),t=Z(m.WALLPAPERS,e);return Array.isArray(t)?t.filter(C_):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function Vr(e){return Ju().find(t=>t.id===e)}const Qu=[{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 C_(e){return Tt(e,Qu).length===0}const ef=ie("desktop-mode/wallpaper-settings",()=>({values:{}}));function L_(e){return{...ef.state.values[e]??{}}}function T_(e){const t=ef.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const N_=20,Kr=1,$s=24,no="os-dock--revealed",oo="data-os-dock-behavior",O_="os-dock",tf="os-side-dock",Us="os-dock-vt",D_=".os-constellation, .os-dock-peek";function R_(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 nf(e){return e.getAttribute(oo)==="dynamic"}function x_(e,t,n,o,s,i=N_){switch(e){case"bottom":return n>=s-i;case"left":return t<=i;case"right":return t>=o-i}return!1}function M_(e,t,n,o){const s=e.getBoundingClientRect();if(s.width<=0||s.height<=0)return!1;let i=s.top-$s;const r=s.bottom+$s;let a=s.left-$s,c=s.right+$s;switch(t){case"bottom":i=s.top-s.height*Kr;break;case"left":c=s.right+s.width*Kr;break;case"right":a=s.left-s.width*Kr;break}return n>=a&&n<=c&&o>=i&&o<=r}function P_(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function W_(e){let t=!1,n=null,o=!1;const s=new Map,i=new Map,r=()=>Array.from(e.shellBody.querySelectorAll(".os-dock")),a=g=>{const _=e.getBehaviors(),N=g.id===tf?_.sidebar:_.dock;g.getAttribute(oo)!==N&&g.setAttribute(oo,N)},c=g=>{const _=g.ownerDocument.activeElement;if(_&&g.contains(_))return!0;if(!n)return!1;if(o)return!0;const N=R_(g);return x_(N,n.x,n.y,window.innerWidth,window.innerHeight)||g.classList.contains(no)&&M_(g,N,n.x,n.y)},l=(g,_)=>{if(g.classList.contains(no)===_){i.delete(g);return}if(s.has(g)){i.set(g,_);return}const N=()=>{g.classList.toggle(no,_)},$=document;if(typeof $.startViewTransition!="function"||P_()){N();return}const C=`os-dock-${g.id||"rail"}`;g.style.setProperty("view-transition-name",C),document.documentElement.classList.add(Us);let V;try{V=$.startViewTransition(N)}catch{g.style.removeProperty("view-transition-name"),document.documentElement.classList.remove(Us),N();return}const K=V.finished&&typeof V.finished.then=="function"?V.finished:Promise.resolve(),j=()=>{g.style.removeProperty("view-transition-name"),s.delete(g),s.size===0&&document.documentElement.classList.remove(Us);const F=i.get(g);i.delete(g),!t&&F!==void 0&&l(g,F)};s.set(g,K.then(j,j))},d=()=>{if(!t)for(const g of r()){if(a(g),!nf(g)){g.classList.remove(no);continue}l(g,c(g))}},u=g=>{if(t||!r().some(nf))return;n={x:g.clientX,y:g.clientY};const _=g.target;o=_ instanceof Element&&_.closest(D_)!==null,d()};let f=0;const p=()=>{f||(f=requestAnimationFrame(()=>{f=0,d()}))},v=()=>d();document.addEventListener("pointermove",u,{passive:!0}),document.addEventListener("pointerdown",u,{passive:!0}),document.addEventListener("focusin",p),document.addEventListener("focusout",p),document.addEventListener("os-layout-changed",v);let b=null;typeof MutationObserver<"u"&&(b=new MutationObserver(d),b.observe(e.shellBody,{childList:!0})),d();const w={refresh:d,destroy:()=>{t=!0,f&&(cancelAnimationFrame(f),f=0),b?.disconnect(),document.removeEventListener("pointermove",u),document.removeEventListener("pointerdown",u),document.removeEventListener("focusin",p),document.removeEventListener("focusout",p),document.removeEventListener("os-layout-changed",v);for(const g of r())g.classList.remove(no),g.style.removeProperty("view-transition-name");i.clear(),document.documentElement.classList.remove(Us),Bs===w&&(Bs=null)}};return Bs=w,w}let Bs=null;function $_(){Bs?.refresh()}function of(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const sf=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","glow","glowBlur","eyeColor","eyeScale"],rf=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function qr(){return{appearance:{},physics:{}}}function U_(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function Fs(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&&U_(i)&&Object.assign(n,{[s]:i})}return n}function af(e){if(!e||typeof e!="object"||Array.isArray(e))return qr();const t=e;return{appearance:Fs(t.appearance,sf),physics:Fs(t.physics,rf)}}function B_(e){return{appearance:Fs(e,sf),physics:Fs(e,rf)}}function F_(){const e=H_();if(e){const t=cf(e);return Xr(t),q_(t),t}try{const t=window.localStorage.getItem(gd);if(t)return cf(JSON.parse(t))}catch{}return J_()}function H_(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}function cf(e){const t=yr();return{wallpaper:typeof e.wallpaper=="string"&&e.wallpaper!==""?e.wallpaper:vd(),accent:e.accent===yd||t.some(n=>n.id===e.accent)?e.accent:J.accent,customAccent:typeof e.customAccent=="string"&&/^#[0-9a-fA-F]{6}$/.test(e.customAccent)?e.customAccent:J.customAccent,dockSize:br.some(n=>n.id===e.dockSize)?e.dockSize:J.dockSize,windowRadius:vr.some(n=>n.id===e.windowRadius)?e.windowRadius:J.windowRadius,adminBarMode:Es.some(n=>n.id===e.adminBarMode)?e.adminBarMode:J.adminBarMode,desktopLayout:$b.some(n=>n.id===e.desktopLayout)?e.desktopLayout:J.desktopLayout,dockPlacement:Wb.some(n=>n.id===e.dockPlacement)?e.dockPlacement:J.dockPlacement,dockBehavior:_s.some(n=>n.id===e.dockBehavior)?e.dockBehavior:J.dockBehavior,sideDockBehavior:_s.some(n=>n.id===e.sideDockBehavior)?e.sideDockBehavior:J.sideDockBehavior,dockRailRenderer:typeof e.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(e.dockRailRenderer)?e.dockRailRenderer:J.dockRailRenderer,desktopTheme:typeof e.desktopTheme=="string"&&/^[a-z0-9_-]*$/.test(e.desktopTheme)?e.desktopTheme:J.desktopTheme,appliedThemeRecommendations:Array.isArray(e.appliedThemeRecommendations)?Array.from(new Set(e.appliedThemeRecommendations.filter(n=>typeof n=="string"&&/^[a-z0-9_-]+$/.test(n)))).slice(-64):J.appliedThemeRecommendations.slice(),unfocusEffect:typeof e.unfocusEffect=="string"&&/^[a-z0-9_/-]+$/.test(e.unfocusEffect)?e.unfocusEffect:J.unfocusEffect,windowReveal:typeof e.windowReveal=="string"&&/^[a-z0-9_/-]+$/.test(e.windowReveal)?e.windowReveal:J.windowReveal,windowRevealDuration:typeof e.windowRevealDuration=="number"&&Number.isFinite(e.windowRevealDuration)&&e.windowRevealDuration>0?Math.min(4e3,Math.max(80,Math.round(e.windowRevealDuration))):J.windowRevealDuration,windowLinkRenderer:typeof e.windowLinkRenderer=="string"&&/^[a-z0-9_/-]+$/.test(e.windowLinkRenderer)?e.windowLinkRenderer:J.windowLinkRenderer,windowLinkVisibility:e.windowLinkVisibility==="focus"||e.windowLinkVisibility==="always"||e.windowLinkVisibility==="off"?e.windowLinkVisibility:J.windowLinkVisibility,windowLinksEnabled:typeof e.windowLinksEnabled=="boolean"?e.windowLinksEnabled:J.windowLinksEnabled,windowLinkRaiseOnFocus:typeof e.windowLinkRaiseOnFocus=="boolean"?e.windowLinkRaiseOnFocus:J.windowLinkRaiseOnFocus,windowLinkHighlight:typeof e.windowLinkHighlight=="boolean"?e.windowLinkHighlight:J.windowLinkHighlight,customGradient:ek(e.customGradient),customImage:tk(e.customImage),wallpaperSettings:G_(e.wallpaperSettings),libraryHdOnly:typeof e.libraryHdOnly=="boolean"?e.libraryHdOnly:J.libraryHdOnly,ai:Q_(e.ai),heartbeatRate:e.heartbeatRate===15||e.heartbeatRate===30||e.heartbeatRate===45||e.heartbeatRate===60?e.heartbeatRate:J.heartbeatRate,nativePostsEnabled:typeof e.nativePostsEnabled=="boolean"?e.nativePostsEnabled:J.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(e.nativePostsHiddenColumns)?e.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):J.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof e.nativePagesEnabled=="boolean"?e.nativePagesEnabled:J.nativePagesEnabled,nativeUsersEnabled:typeof e.nativeUsersEnabled=="boolean"?e.nativeUsersEnabled:J.nativeUsersEnabled,nativePluginsEnabled:typeof e.nativePluginsEnabled=="boolean"?e.nativePluginsEnabled:J.nativePluginsEnabled,nativeCommentsEnabled:typeof e.nativeCommentsEnabled=="boolean"?e.nativeCommentsEnabled:J.nativeCommentsEnabled,stationHomeEnabled:typeof e.stationHomeEnabled=="boolean"?e.stationHomeEnabled:J.stationHomeEnabled,adminAssetCacheEnabled:typeof e.adminAssetCacheEnabled=="boolean"?e.adminAssetCacheEnabled:J.adminAssetCacheEnabled,windowPrewarmEnabled:typeof e.windowPrewarmEnabled=="boolean"?e.windowPrewarmEnabled:J.windowPrewarmEnabled,showDesktopOnWallpaperClick:typeof e.showDesktopOnWallpaperClick=="boolean"?e.showDesktopOnWallpaperClick:J.showDesktopOnWallpaperClick,mioEnabled:typeof e.mioEnabled=="boolean"?e.mioEnabled:J.mioEnabled,mioStyle:af(e.mioStyle),showPostStatusRibbons:typeof e.showPostStatusRibbons=="boolean"?e.showPostStatusRibbons:J.showPostStatusRibbons,developerModeEnabled:typeof e.developerModeEnabled=="boolean"?e.developerModeEnabled:J.developerModeEnabled,foldersSharingEnabled:typeof e.foldersSharingEnabled=="boolean"?e.foldersSharingEnabled:J.foldersSharingEnabled,navPlacement:z_(e.navPlacement),navOrder:j_(e.navOrder),dockPromotedPositions:V_(e.dockPromotedPositions)}}function G_(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(typeof o!="string"||o===""||!/^[a-z0-9_/-]+$/.test(o)||!s||typeof s!="object"||Array.isArray(s))continue;const i={};let r=0;for(const[a,c]of Object.entries(s)){if(r>=32)break;if(!(typeof a!="string"||a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof c=="boolean")i[a]=c;else if(typeof c=="number"&&Number.isFinite(c))i[a]=c;else if(typeof c=="string")i[a]=c.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function z_(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=["both","rail","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(e)){if(o>=256)break;if(typeof s!="string"||s===""||typeof i!="string")continue;const r=i;t.includes(r)&&(n[s]=r,o++)}return n}function j_(e){if(!Array.isArray(e))return[];const t=[],n=new Set;for(const o of e)if(!(typeof o!="string"||o===""||n.has(o))&&(n.add(o),t.push(o),t.length>=256))break;return t}function V_(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(typeof s!="string"||s===""||!i||typeof i!="object"||Array.isArray(i))continue;const r=i;typeof r.x!="number"||typeof r.y!="number"||!Number.isFinite(r.x)||!Number.isFinite(r.y)||Math.abs(r.x)>o||Math.abs(r.y)>o||(t[s]={x:r.x,y:r.y},n++)}return t}let Hs=null;const K_=250;let xt=null;function q_(e){xt=Yr(e)}function Yr(e){return{...e,customGradient:{...e.customGradient},customImage:e.customImage?{...e.customImage}:null,wallpaperSettings:Object.fromEntries(Object.entries(e.wallpaperSettings).map(([t,n])=>[t,{...n}])),ai:{...e.ai},mioStyle:{appearance:{...e.mioStyle.appearance},physics:{...e.mioStyle.physics}},appliedThemeRecommendations:e.appliedThemeRecommendations.slice(),nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),navPlacement:{...e.navPlacement},navOrder:e.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function Y_(e,t={}){Xr(e),X_(e,t.windowId)}function Xr(e){try{window.localStorage.setItem(gd,JSON.stringify(e))}catch{}}function X_(e,t){Hs!==null&&clearTimeout(Hs),t&&(Zr=t),vt("pending"),Hs=setTimeout(()=>{Hs=null;const n=Zr;Zr=null,lf(e,n)},K_)}let Zr=null;function Z_(e){if(!xt)return{...e};const t=xt,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 Jr=!1,Qr=null;function lf(e,t){if(Jr){Qr={state:e,windowId:t},vt("pending");return}const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){vt("saved");return}const i=Z_(e);if(!i){vt("saved");return}vt("saving"),Jr=!0;const r=Yr(e),a=t||"desktop-mode-os-settings";Be(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:i})},{windowId:a}).then(c=>{if(!c.ok)throw new Error(`${c.status} ${c.statusText}`);xt=r,vt("saved")}).catch(c=>{Gs=!0,xt?(Xr(xt),vt("failed",c instanceof Error?c.message:String(c),Yr(xt))):vt("failed",c instanceof Error?c.message:String(c))}).finally(()=>{Jr=!1;const c=Qr;if(Qr=null,c&&Gs){Gs=!1;return}Gs=!1,c&&lf(c.state,c.windowId)})}let Gs=!1;function vt(e,t,n){const o={phase:e};t&&(o.error=t),n&&(o.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:o}))}function J_(){return{...J,customGradient:{...J.customGradient},customImage:null,wallpaperSettings:{...J.wallpaperSettings},ai:{...J.ai},appliedThemeRecommendations:[...J.appliedThemeRecommendations],navPlacement:{...J.navPlacement},navOrder:[...J.navOrder],dockPromotedPositions:{...J.dockPromotedPositions}}}function Q_(e){if(!e||typeof e!="object")return{...J.ai};const{enabled:t}=e;return{enabled:typeof t=="boolean"?t:J.ai.enabled}}function ek(e){if(!e||typeof e!="object")return{...J.customGradient};const{from:t,to:n,angle:o}=e;return{from:of(t)?t:J.customGradient.from,to:of(n)?n:J.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:J.customGradient.angle}}function tk(e){if(!e||typeof e!="object")return null;const{id:t,url:n}=e;return typeof t!="number"||!Number.isFinite(t)||t<=0||typeof n!="string"||!/^https?:\/\//i.test(n)?null:{id:t,url:n}}function ea(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 nk(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function zs(e,t,n){if(!nk(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 ok="data-os-constellation";function sk(){return document.body.hasAttribute(ok)}const df="os-item-menu-opening",ik=180,rk=220,uf=32;function ff(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)},c=()=>{s!==null&&(window.clearTimeout(s),s=null)},l=()=>{a(),c(),t.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),r?.clear(),r=null,e.suppressTooltip(!1)},d=b=>{b.pointerType==="mouse"&&(sk()&&(t.dataset.menuSlug||t.dataset.constellationId)||ak(e)&&(i=!0,c(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},ik))))},u=b=>{n&&b.relatedTarget instanceof Node&&n.contains(b.relatedTarget)||(i=!1,a(),f())},f=()=>{c(),s=window.setTimeout(()=>{s=null,!i&&l()},rk)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=ck(e,()=>l(),r),document.body.appendChild(n),mk(n),gk(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,c()}),n.addEventListener("pointerleave",b=>{b.relatedTarget instanceof Node&&t.contains(b.relatedTarget)||(i=!1,f())})},v=()=>l();return t.addEventListener("pointerenter",d),t.addEventListener("pointerleave",u),document.addEventListener(df,v),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(df,v),l()}}function ak(e){return e.getInstances().length>=1}function ck(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",de(k("%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 c=lk(a,e,r++,t,n);s.appendChild(c)}if(e.enableGhost!==!1){const a=uk(e,r,t);s.appendChild(a)}return o}function pf(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function lk(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*uf}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${ea(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 c=document.createElement("span");c.className="os-dock-peek__card-dots",c.setAttribute("aria-hidden","true");for(let _=0;_<3;_++)c.appendChild(document.createElement("i"));a.appendChild(c);const l=document.createElement("span");l.className="os-dock-peek__card-icon",l.setAttribute("aria-hidden","true");const d=e.config.icon||t.item.icon;d.startsWith("dashicons-")?l.classList.add("dashicons",Oy(d)):l.classList.add("dashicons","dashicons-admin-generic"),a.appendChild(l);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 _=0;_<3;_++){const N=document.createElement("span");N.className="os-dock-peek__card-line",f.appendChild(N)}const p={window:e,item:t.item},v=Z(m.DOCK_PEEK_CARD_CONTENT,f,p);v!==f&&v.classList.add("os-dock-peek__card-body--custom"),i.appendChild(v),e.state==="minimized"&&(i.dataset.state="minimized");const b=()=>{s.delete(e.id),delete i.dataset.preview},w=_=>{if(b(),_.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(_.previouslyFocusedId){const N=t.windowManager.getById(_.previouslyFocusedId);N&&t.windowManager.focus(N)}};return i.addEventListener("click",()=>{b(),dk(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const _=e.state==="minimized",N=t.windowManager.getFocused(),$=N&&N!==e?N.id:null;(_||$!==null)&&(s.set(e.id,{wasMinimized:_,previouslyFocusedId:$}),i.dataset.preview=""),_?pf(e,i):N&&N!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const _=s.get(e.id);_&&w(_)}),Z(m.DOCK_PEEK_CARD_ELEMENT,i,p)}function dk(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),pf(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 c=s.startViewTransition(r),l=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},d=c;d.finished&&typeof d.finished.then=="function"?d.finished.then(l,l):Promise.resolve().then(l)}function uk(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*uf}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=de(k("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{fk(e,n)}),o}function fk(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const pk=12,hk=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function mk(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of hk){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function gk(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(()=>wk(e))}function wk(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=pk;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 js(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}}const Vs=new Map;function ta(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}function ue(e,t){const n=Vs.get(e);if(n)return n;const o=t?.deps;if(o&&o.length>0){const i=a=>!a.url||ta(a.url)?Promise.resolve():ue(a.url,{...a,deps:void 0}),r=o.reduce((a,c)=>a.then(()=>i(c)),Promise.resolve(void 0)).then(()=>hf(e,t));return Vs.set(e,r),r}const s=hf(e,t);return Vs.set(e,s),s}function hf(e,t){return new Promise((n,o)=>{const s=`script[data-os-vendor="${yk(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=ta(e);if(r){r.dataset.osVendor=e,r.dataset.loaded="1",n();return}t?.translations&&so(t.translations);for(const c of t?.l10n??[])so(c);for(const c of t?.before??[])so(c);const a=document.createElement("script");a.src=e,a.async=!0,a.dataset.osVendor=e,a.addEventListener("load",()=>{a.dataset.loaded="1";for(const c of t?.after??[])so(c);n()},{once:!0}),a.addEventListener("error",()=>{Vs.delete(e),a.remove(),o(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(a)})}function so(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function mf(e){so(e)}function yk(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let gf=0;function wf(){return window.openStationItemVisibilityMenu??null}function bk(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function yf(e){const t=wf();if(t){t.openItemVisibilityMenu(e);return}const n=bk();if(!n)return;const o=++gf;ue(n).then(()=>{o===gf&&wf()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const vk={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function Ek(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function _k(e){return e==="core"?"core":e==="control"?"controls":"apps"}function bf(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??vk[e.kind]}function vf(e){return e==="rail"||e==="both"}function kk(e){return e==="desktop"||e==="both"}function Sk(e,t,n){return vf(e)?"rail":"hidden"}function na(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 Ak(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 oa(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 Ks(){return window.wp?.os??null}function Ik(){const e=Ks()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function Ck(){return Ks()?.getNavItems?.()??[]}function Lk(e){const t=Ck();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function Tk(e){const t=Ks();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 Nk(e,t,n){const o=Array.isArray(e)?e:[e],s=Ik().placement,i=[];for(const r of o){const a=typeof r=="string"?Lk(r):r;a&&i.push({item:a,placement:Sk(bf(a,s))})}Tk(i)}function Ok(e){const t=Ks();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:Ak(n,e)})}const et=["core","apps","controls"];function Ef(e){const{items:t,config:n,layout:o,openWindows:s}=e,i={core:[],apps:[],controls:[]},r=[],a=[],c=new Set,l=new Set,d=new Map,u=new Set;for(const f of t){u.add(f.id),f.windowId&&!d.has(f.windowId)&&d.set(f.windowId,f);const p=bf(f,n.placement);if(vf(p)){l.add(f.id);const v=_k(f.kind);Ek(f.kind,o)==="sidebar"?r.push(f):i[v].push(f)}kk(p)&&a.push(f)}for(const f of t)for(const p of f.answersFor??[])d.has(p)||d.set(p,f);for(const f of s){const p=d.get(f.id);if(p){if(l.has(p.id)||c.has(p.id))continue;i.apps.push(p),c.add(p.id);continue}f.fromAdminUrl||c.has(f.id)||u.has(f.id)||(i.apps.push({id:f.id,kind:"app",title:f.title,icon:f.icon,windowId:f.id,transient:!0}),c.add(f.id))}for(const f of et)i[f]=na(oa(i[f]),n.order);return{dock:i,sidebar:na(oa(r),n.order),desktop:na(oa(a),n.order),ephemeral:c}}const Dk=["action","action2","_wpnonce","nonce","delete_all"];function Rk(e){const t=e.slice(e.lastIndexOf("/")+1);return/-new\.php$/.test(t)}function xk(e){if(Rk(e.pathname))return!0;for(const t of Dk)if(e.searchParams.has(t))return!0;return!1}function _f(e){return e.navKind==="control"?"controls":"apps"}const xe=class xe{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/${++xe.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 et)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[_f(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 et){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(),T(m.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");kf(i??o,s),Ee.publish("os/badge-changed",{itemId:t,count:s,rail:this.rail})}clearBadge(t){this.setBadge(t,0)}setArt(t,n){if(!n){if(!this.artOverrides.delete(t))return;const s=this._resolveTileElement(t),i=this._declaredIcon(t);s&&i&&this._paintArt(s,t,i),Ee.publish("os/art-changed",{itemId:t,icon:"",rail:this.rail});return}this.artOverrides.set(t,n);const o=this._resolveTileElement(t);o&&(this._paintArt(o,t,n),Ee.publish("os/art-changed",{itemId:t,icon:n,rail:this.rail}))}_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,Ss(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 c=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},a);this.attentionTimers.set(t,c)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}appendSystemItem(t){const n=_f(t),o={type:"system",item:t};for(const a of et)this.zones[a]=this.zones[a].filter(c=>c.type!=="system"||c.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(xe.activeDragReset){const o=xe.activeDragReset;xe.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 et)for(const s of this.zones[o])s.type==="menu"?this.items.push(s.item):this.systemItems.push(s.item);const t=this.buildHookContextBase();T(m.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of et){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(),T(m.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(),yf({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 c=this.badgeOverrides.get(i);if(c!==void 0){const d=r.querySelector(".os-dock__item-primary");kf(d??r,c)}const l=this.artOverrides.get(i);l&&this._paintArt(r,i,l),T(m.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=Z(m.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id,t.submenu&&t.submenu.length>0&&(o.dataset.constellationId=t.id);const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title,void 0,Ss(t.id))),r.addEventListener("click",()=>t.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=ff({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:c=>{c&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),Z(m.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=Z(m.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,Ss(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",de(Gn("%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 c=this.resolveItemBaseId(t),l=ff({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(c),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,l),this.bindHoverPrewarm(o,t),Z(m.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n,o){let r=!1,a=0,c=0,l=[],d=null,u=-1,f=null,p=!1;const v=()=>{r=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",j),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",E,!0),window.removeEventListener("blur",B),document.removeEventListener("visibilitychange",P),u=-1,f=null},b=o==="controls"?this.systemHost:this.itemHost,w=h=>!!h&&h instanceof HTMLElement&&h.classList.contains("os-dock__item")&&h.dataset.zone===o&&!!h.dataset.navId&&h.dataset.navLocked===void 0,g=h=>{for(const A of Array.from(b.children))A instanceof HTMLElement&&A!==t&&w(A)&&h(A)},_=()=>{const h=[];for(const A of Array.from(b.children))w(A)&&h.push(A.dataset.navId);return h},N=h=>{g(A=>{const O=h.get(A);if(!O)return;const G=A.getBoundingClientRect(),Y=O.left-G.left,I=O.top-G.top;if(Math.abs(Y)<.5&&Math.abs(I)<.5)return;A.style.transition="none",A.style.transform=`translate(${Y}px, ${I}px)`,A.offsetHeight,A.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",A.style.transform="";const S=()=>{A.style.transition="",A.style.transform="",A.removeEventListener("transitionend",S)};A.addEventListener("transitionend",S)})},$=h=>{if(u!==-1&&h.pointerId!==u)return;if(!r){const U=h.clientX-a,H=h.clientY-c;if(U*U+H*H<5*5)return;r=!0,l=_(),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 A=h.clientX-a,O=h.clientY-c;t.style.transform=`translate(${A}px, ${O}px)`;const Y=document.elementFromPoint(h.clientX,h.clientY)?.closest(".os-dock__item");if(!Y||Y===t||!w(Y))return;const I=Y.getBoundingClientRect();let S;this.orientation==="bottom"?S=h.clientX<I.left+I.width/2:S=h.clientY<I.top+I.height/2;const M=new Map;g(U=>{M.set(U,U.getBoundingClientRect())});let D=!1;if(S?Y!==t.nextSibling&&(b.insertBefore(t,Y),D=!0):Y.nextSibling!==t&&(b.insertBefore(t,Y.nextSibling),D=!0),D){t.style.transform="";const U=t.getBoundingClientRect();a=U.left+U.width/2,c=U.top+U.height/2,t.style.transform=`translate(${h.clientX-a}px, ${h.clientY-c}px)`,N(M)}},C=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",j),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",E,!0),window.removeEventListener("blur",B),document.removeEventListener("visibilitychange",P),u=-1,f=null,r=!1,xe.activeDragReset===v&&(xe.activeDragReset=null)},V=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const h=()=>{t.style.transition="",t.removeEventListener("transitionend",h)};t.addEventListener("transitionend",h)},K=h=>{Ok(h)},j=h=>{if(u!==-1&&h.pointerId!==u)return;if(!r){C();return}p=!0;const A=_();V(),C(),A.length===l.length&&A.every((G,Y)=>G===l[Y])||K(A),setTimeout(()=>{p=!1},200)},F=h=>{if(!(h&&u!==-1&&h.pointerId!==u)){if(r&&d!==void 0){const A=new Map;g(O=>{A.set(O,O.getBoundingClientRect())}),b.insertBefore(t,d),N(A)}V(),C()}},E=h=>{h.key==="Escape"&&F()},B=()=>F(),P=()=>{document.visibilityState!=="visible"&&F()};t.addEventListener("pointerdown",h=>{if(h.button===0){if(xe.activeDragReset){const A=xe.activeDragReset;xe.activeDragReset=null,A()}(r||u!==-1)&&v(),a=h.clientX,c=h.clientY,u=h.pointerId,r=!1,xe.activeDragReset=v,document.addEventListener("pointermove",$),document.addEventListener("pointerup",j),document.addEventListener("pointercancel",F),document.addEventListener("keydown",E,!0),window.addEventListener("blur",B),document.addEventListener("visibilitychange",P)}}),t.addEventListener("click",h=>{p&&(h.preventDefault(),h.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=ks(s);a!==null&&(t=a,i=!0),r=Sr(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if(zs(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(zs(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 c=r.className.match(/\bdashicons-[\w-]+\b/);if(c&&c[0]!=="dashicons-before"){const f=document.createElement("span");return f.className=`dashicons ${c[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=ea(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=Z(m.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)return;const o=180;let s;const i=()=>{s!==void 0&&(window.clearTimeout(s),s=void 0)};t.addEventListener("pointerenter",r=>{if(!(r.pointerType!=="mouse"||!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled)){try{const c=new URL(n.url,window.location.href);if(c.origin!==window.location.origin||xk(c))return}catch{return}Ps(n.url)||(i(),s=window.setTimeout(()=>{s=void 0;const c=this.deriveWindowId(n.url);this.windowManager.prewarm({id:c,baseId:c,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})},o))}}),t.addEventListener("pointerleave",i),t.addEventListener("pointerdown",i)}openPage(t){if(t.windowId&&!t.url){const o=this.windowManager.getById(t.windowId);if(o){this.windowManager.focus(o);return}window.wp?.os?.openWindow?.(t.windowId);return}if(js(t.url)||Qe(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(js(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=Ps(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 le(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:Ps(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?.(m.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(m.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(m.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?.(m.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(m.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(m.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 c=this.windowManager.getAllByBaseId(a).filter(o);if(c.length===0&&i.url){const f=this.deriveWindowId(i.url);c=this.windowManager.getAll().filter(p=>{const v=p.config.baseId||p.id;if(v===a||v===f||v===i.id||p.config.parentUrl&&this.deriveWindowId(p.config.parentUrl)===f)return!0;if(p.config.url){const b=this.deriveWindowId(p.config.url);return b===a||b===f}return!1}).filter(o)}const l=c.length>0,d=l&&c.every(s),u=!!t&&o(t)&&!s(t)&&c.some(f=>f.id===t.id||(t.config.baseId||t.id)===a);r.classList.toggle("os-dock__item--active",l),r.classList.toggle("os-dock__item--focused",u),r.classList.toggle("os-dock__item--all-minimized",d),r.classList.toggle("os-dock__item--stacked",l&&c.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),c=i.isOpen?i.isOpen():!!a,l=!!a&&s(a),d=!!t&&t.id===i.id&&!s(t);r.classList.toggle("os-dock__item--active",c),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",l)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("os-show-desktop-active",o)}};xe.instanceCounter=0,xe.activeDragReset=null;let qs=xe;function kf(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",de(Gn("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="os-dock__badge",s.textContent=o,s.setAttribute("aria-label",de(Gn("%d notification","%d notifications",t),t)),e.appendChild(s)}const Sf=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),sa={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 qs(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[Sf]: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 Af(e){if(!e)return null;const n=e[Sf];return n instanceof qs?n:null}function Mk(){Hl(sa)}const If="os-desktop-theme-css",Pk="os-desktop-theme-inline-css",ia="data-os-desktop-theme-css",Cf="os-desktop-theme-changed";function Lf(){return document.getElementById("os-shell")}function Tf(){const e=[];for(const t of[If,Pk]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${ia}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function ra(){for(const e of Tf())e.remove()}function Wk(e){const t=Lf();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:Tf().length>0}function Nf(e){if(e.cssUrl!==""){const t=document.createElement("link");t.id=If,t.rel="stylesheet",t.href=e.cssUrl,t.setAttribute(ia,e.slug),document.head.appendChild(t)}else if(e.cssText!==""){const t=document.createElement("style");t.setAttribute(ia,e.slug),t.textContent=e.cssText,document.head.appendChild(t)}}function Of(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 aa(e){const t=ln(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:_r(o),i=s?s.slug:null;if(i===n)return;const r=Lf();if(!s)r?.removeAttribute("data-os-desktop-theme"),Of(null),ra(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!Wk(s.slug))if(s.cssDeferred&&s.cssUrl===""&&s.cssText===""){const c=s.slug,l=()=>Id().then(()=>{if(ln().state.activeId!==c)return;const d=_r(c);if(!d||d.cssDeferred)throw new Error(`theme "${c}" resolved without a stylesheet`);ra(),Nf(d)}).catch(d=>{ln().state.activeId===c&&(fe({message:k("Could not load that desktop theme โ€” the previous one is still showing."),action:{label:k("Retry"),onClick:()=>void l()},persistent:!0,dismissible:!0}),console.warn("[openstation] desktop theme stylesheet failed to load",d))});l()}else ra(),Nf(s);r?.setAttribute("data-os-desktop-theme",s.slug),Of(s.slug),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};T(m.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(Cf,{detail:a}))}const Df=new Set;function io(e){if(Df.has(e))return;const n=window.openStationConfig?.deferredStyles?.[e];if(!n?.url)return;Df.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 $k=120,Uk="os-inline-loader",Rf="os-inline-loader-keyframes";function Bk(){return typeof customElements<"u"&&!!customElements.get("os-spinner")}function Fk(){if(document.getElementById(Rf))return;const e=document.createElement("style");e.id=Rf,e.textContent="@keyframes os-inline-loader-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function Hk(){if(Bk()){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||(Fk(),e.style.animation="os-inline-loader-spin 0.7s linear infinite"),e}function xf(e,t={}){const n=t.label??k("Loadingโ€ฆ");let o=null,s=!1;const i=()=>{if(s||o||!e.isConnected)return;o=document.createElement("div"),o.className=Uk,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 c=document.createElement("span");c.textContent=n,o.appendChild(Hk()),o.appendChild(c),e.appendChild(o)},r=t.immediate?null:window.setTimeout(i,$k);t.immediate&&i();const a=()=>{r!==null&&window.clearTimeout(r)};return{done:()=>{s||(s=!0,a(),o?.remove(),o=null)},fail:(c,l)=>{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=c,o.appendChild(d),l){const u=document.createElement("button");u.type="button",u.textContent=k("Retry"),u.className="button button-small",u.addEventListener("click",()=>{o?.remove(),o=null,s=!1,l()}),o.appendChild(u)}}}}function tt(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function Gk(e){return!!e&&e.__wpdHtml===!0}const zk="$$wpd$$",Le=/\$\$wpd\$\$(\d+)\$\$/g;function jk(e){let t=e[0];for(let n=1;n<e.length;n++)t+=`${zk}${n-1}$$`+e[n];return t}const Mf=new WeakMap;function Pf(e){const t=Mf.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=jk(e);const o=[],s=(a,c)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const f of Array.from(u.attributes)){const p=f.name,v=f.value,b=p[0];if(Le.test(v))if(Le.lastIndex=0,b==="@"){const w=Le.exec(v);Le.lastIndex=0,o.push({path:c,kind:"event",name:p.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(p)}else if(b==="."){const w=Le.exec(v);Le.lastIndex=0,o.push({path:c,kind:"prop",name:p.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(p)}else if(b==="?"){const w=Le.exec(v);Le.lastIndex=0,o.push({path:c,kind:"bool",name:p.slice(1),valueIndex:w?Number(w[1]):0}),u.removeAttribute(p)}else{const w=[],g=[];let _=0,N;for(Le.lastIndex=0;(N=Le.exec(v))!==null;)w.push(v.slice(_,N.index)),g.push(Number(N[1])),_=N.index+N[0].length;w.push(v.slice(_)),o.push({path:c,kind:"attr",name:p,template:w,valueIndices:g}),u.setAttribute(p,"")}}}const l=Array.from(a.childNodes);let d=0;for(let u=0;u<l.length;u++){const f=l[u],p=u+d;if(f.nodeType===Node.TEXT_NODE){const v=f.textContent||"";if(!Le.test(v)){Le.lastIndex=0;continue}Le.lastIndex=0;const b=f.parentNode;let w=0,g;const _=[],N=[];for(Le.lastIndex=0;(g=Le.exec(v))!==null;){g.index>w&&_.push(document.createTextNode(v.slice(w,g.index)));const $=document.createTextNode("");_.push($),N.push({path:[...c,p+_.length-1],kind:"node",valueIndex:Number(g[1])}),w=g.index+g[0].length}w<v.length&&_.push(document.createTextNode(v.slice(w)));for(const $ of _)b.insertBefore($,f);b.removeChild(f),d+=_.length-1,o.push(...N)}else s(f,[...c,p])}};s(n.content,[]);const r={template:n,buildParts:a=>{const c=[];for(const l of o){let d=a;for(const u of l.path)d=d.childNodes[u];l.kind==="node"?c.push({kind:"node",valueIndex:l.valueIndex,child:{anchor:d,state:null}}):l.kind==="attr"?c.push({kind:"attr",element:d,name:l.name,template:l.template,valueIndices:l.valueIndices}):l.kind==="event"?c.push({kind:"event",valueIndex:l.valueIndex,element:d,name:l.name}):l.kind==="prop"?c.push({kind:"prop",valueIndex:l.valueIndex,element:d,name:l.name}):l.kind==="bool"&&c.push({kind:"bool",valueIndex:l.valueIndex,element:d,name:l.name})}return c}};return Mf.set(e,r),r}const Wf=new WeakMap;function Vk(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function Kk(e,t){const n=Wf.get(t);if(n&&n.strings===e.strings&&Vk(n,t)){Ys(n.parts,e.values);return}const o=Pf(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),Ys(i,e.values),Wf.set(t,{strings:e.strings,parts:i,nodes:r})}function Ys(e,t){for(const n of e)if(n.kind==="node")ca(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+=$f(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 ca(e,t){if(t==null||t===!1){e.state&&(Mt(e.state),e.state=null);return}if(Array.isArray(t)){Zk(e,t);return}if(Gk(t)){Xk(e,t);return}if(t instanceof Node){qk(e,t);return}Yk(e,$f(t))}function qk(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Mt(n),Xs(e,[t]),e.state={shape:"node",node:t})}function Yk(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Mt(n);const o=document.createTextNode(t);Xs(e,[o]),e.state={shape:"text",node:o,text:t}}function Xk(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){Ys(n.parts,t.values);return}n&&Mt(n);const o=Pf(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);Xs(e,[s]),Ys(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function Zk(e,t){const n=e.state;if(n?.shape==="array"&&n.entries.length===t.length){for(let s=0;s<t.length;s++)ca(n.entries[s],t[s]);return}n&&Mt(n);const o=[];for(const s of t){const i=document.createTextNode("");Xs(e,[i]);const r={anchor:i,state:null};ca(r,s),o.push(r)}e.state={shape:"array",entries:o}}function Xs(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Mt(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&&(Mt(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&&Mt(t.state),t.anchor.remove()}function $f(e){return e==null||e===!1?"":String(e)}const Ct=class Ct 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(Uf)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=Jk(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=Uf(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&&Kk(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(!Ct._lightStylesAdopted.has(t)){Ct._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)}}}};Ct.props=[],Ct.styles=[],Ct.shadow=!0,Ct._lightStylesAdopted=new WeakSet;let Pt=Ct;function ro(e,t){customElements.get(e)||customElements.define(e,t)}function Uf(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Jk(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const Qk=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function Se(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(Qk){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}const Zs=new Map;function Bf(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}Zs.set(e.id,e)}function eS(){return Array.from(Zs.keys())}async function la(e){if(!e||e.length===0)return;const t=e.filter(n=>!Zs.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${eS().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=Zs.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():ue(o.url)}))}const mn=ie("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function tS(e){mn.state.pending.set(e.id,e)}function Js(e){mn.state.pending.delete(e)}function nS(e){return(window.openStationWallpapers||{})[e]??null}function Ff(e){const t=mn.state.inflight.get(e);if(t)return t;const n=mn.state.pending.get(e);if(!n)return Promise.resolve(null);const o=(async()=>{try{await ue(n.scriptUrl,{translations:n.scriptTranslations,l10n:n.scriptL10n,before:n.scriptBefore,after:n.scriptAfter})}catch(i){return T(m.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=nS(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return T(m.SHELL_ERROR,{scope:"wallpaper-missing-def",id:n.id,error:new Error(`[openstation] No wallpaper def on window.openStationWallpapers["${n.id}"]. Script loaded but didn't publish a def โ€” check the plugin's enqueue + global assignment.`)}),null;try{hn(s)}catch(i){return T(m.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return Js(n.id),s})().finally(()=>{mn.state.inflight.delete(e)});return mn.state.inflight.set(e,o),o}function oS(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 Ff(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await la(o.needs),o.mount(t,n))}}}const da=Se`: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 ) )}`,sS=Se` .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%}}`,Hf=Se` .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%}}`,Gf=Se` .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}}`,zf=Se` .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}}`,jf=Se` .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}}`,iS=Se` .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%}}`,rS=Se` .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}}`,aS=Se` 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}}`,cS=Se` input[ type='checkbox' ],input[ type='radio' ]{appearance:none;-webkit-appearance:none;position:relative;flex:0 0 auto;box-sizing:border-box;width:16px;height:16px;margin:0;padding:0;border:1px solid var( --_holo-track-edge );border-radius:4px;background-color:var( --_holo-track );background-image:none;background-repeat:no-repeat;cursor:inherit;transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input[ type='radio' ]{border-radius:50%}input[ type='checkbox' ]:hover:not(:disabled ),input[ type='radio' ]:hover:not(:disabled ){border-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:focus-visible,input[ type='radio' ]:focus-visible{outline:none;box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked,input[ type='checkbox' ]:indeterminate,input[ type='radio' ]:checked{border-color:transparent;background-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:checked:focus-visible,input[ type='radio' ]:checked:focus-visible{box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:46%;width:3.5px;height:7.5px;border:solid var( --os-ui-fg-on-accent,#fff );border-width:0 2px 2px 0;transform:translate( -50%,-50% ) rotate( 45deg );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:indeterminate::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:8px;height:2px;border:0;border-radius:1px;background:var( --os-ui-fg-on-accent,#fff );transform:translate( -50%,-50% )}input[ type='radio' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:6px;height:6px;border-radius:50%;background:var( --os-ui-fg-on-accent,#fff );transform:translate( -50%,-50% );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:disabled,input[ type='radio' ]:disabled{cursor:not-allowed}@keyframes os-holo-tick{from{opacity:0;transform:translate( -50%,-50% ) rotate( 45deg ) scale( 0.4 )}}@media ( prefers-reduced-motion:reduce ){input[ type='checkbox' ]:checked::after,input[ type='radio' ]:checked::after{animation:none}}`,Vf=Se` @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}}`;Se` ${da} ${sS} ${Hf} ${Gf} ${zf} ${jf} ${iS} ${rS} ${aS} ${cS} ${Vf} `;const lS=Se` ${da}:host{display:none;position:fixed;inset:0;align-items:center;justify-content:center;background:var( --os-ui-scrim,rgba( 0,0,0,0.45 ) );background-image:var( --os-ui-scrim-image,none );background-repeat:var( --os-ui-scrim-image-repeat,repeat );background-size:var( --os-ui-scrim-image-size,auto );background-position:var( --os-ui-scrim-image-position,center );backdrop-filter:blur( 2px );z-index:10000;--os-ui-fg:var( --os-ui-modal-text,#f0f0f1 );--os-ui-fg-muted:var( --os-ui-modal-text-muted,#a7aaad );--os-ui-border:var( --os-ui-modal-border,rgba( 255,255,255,0.25 ) );--os-window-bg:var( --os-ui-modal-field-bg,#2c3338 );--os-ui-button-bg-hover:var( --os-ui-modal-button-bg-hover,rgba( 255,255,255,0.08 ) );--os-ui-surface:var( --os-ui-modal-surface,#2c3338 );--os-ui-surface-elevated:var( --os-ui-modal-surface-elevated,#3c434a );--os-ui-border-strong:var( --os-ui-modal-border-strong,rgba( 255,255,255,0.35 ) );--os-ui-hover:var( --os-ui-modal-hover,rgba( 255,255,255,0.08 ) )}:host( [ open ] ){display:flex;animation:os-modal-scrim var( --_holo-t ) var( --_holo-ease )}:host( [ open ] ) .dialog{animation:os-modal-dialog var( --_holo-t ) var( --_holo-spring )}@keyframes os-modal-scrim{from{opacity:0}}@keyframes os-modal-dialog{from{opacity:0;transform:scale( 0.96 ) translateY( 8px )}}@media ( prefers-reduced-motion:reduce ){:host( [ open ] ),:host( [ open ] ) .dialog{animation:none}}.dialog{max-width:92vw;max-height:90vh;background-color:var( --os-ui-modal-bg,#1d2327 );background-image:var( --os-ui-dialog-bg-image,none );background-repeat:var( --os-ui-dialog-bg-image-repeat,repeat );background-size:var( --os-ui-dialog-bg-image-size,auto );background-position:var( --os-ui-dialog-bg-image-position,center );color:var( --os-ui-modal-fg,var( --os-fg,#fff ) );border:1px solid var( --os-ui-border,rgba( 255,255,255,0.08 ) );border-radius:10px;box-shadow:0 20px 50px rgba( 0,0,0,0.6 );display:flex;flex-direction:column;overflow:hidden}:host( [ size='sm' ] ) .dialog{width:min( 360px,92vw )}:host(:not( [ size ] ) ) .dialog,:host( [ size='md' ] ) .dialog{width:min( 540px,92vw )}:host( [ size='lg' ] ) .dialog{width:min( 760px,94vw )}.header{display:flex;align-items:center;gap:10px;padding:16px 20px 12px;border-bottom:1px solid var( --os-ui-border,rgba( 255,255,255,0.06 ) )}.title{margin:0;flex:1;font-size:15px;font-weight:600}.header-actions{display:flex;gap:6px}.header-actions::slotted( * ){margin-inline-start:6px}.close{background:transparent;border:0;color:inherit;font-size:18px;line-height:1;padding:4px 8px;border-radius:4px;cursor:pointer;opacity:0.7}.close:hover{opacity:1;background:var( --os-ui-hover,rgba( 255,255,255,0.08 ) )}.body{padding:16px 20px;overflow:auto;flex:1 1 auto;font-size:13px;line-height:1.5}.footer{padding:12px 20px 16px;border-top:1px solid var( --os-ui-border,rgba( 255,255,255,0.06 ) )}.footer slot{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap}:host( [ mandatory ] ) .close{display:none}`,Kf='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',ls=class ls extends Pt{constructor(){super(...arguments),this._prevFocus=null,this._onKey=t=>{if(t.key==="Escape"&&!this.hasAttribute("mandatory")){t.preventDefault(),this._cancel();return}if(t.key==="Tab"){const n=this._focusables();if(n.length===0)return;const o=n[0],s=n[n.length-1],i=this.ownerDocument,r=i?i.activeElement:null,a=t.composedPath()[0]||r;t.shiftKey&&a===o?(t.preventDefault(),s.focus()):!t.shiftKey&&a===s&&(t.preventDefault(),o.focus())}},this._onBackdrop=t=>{if(this.hasAttribute("mandatory"))return;const n=t.composedPath();(n.length>0?n[0]:t.target)===this&&this._cancel()}}connectedCallback(){super.connectedCallback(),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","true"),this.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback?.(t,n,o),t==="open"){if(o!==null){const s=this.ownerDocument;this._prevFocus=s?s.activeElement:null,queueMicrotask(()=>this._focusFirst())}else if(this._prevFocus){try{this._prevFocus.focus()}catch{}this._prevFocus=null}}}showModal(){this.setAttribute("open","")}hideModal(){this.removeAttribute("open")}_focusables(){const t=this.shadowRoot;if(!t)return[];const n=Array.from(this.querySelectorAll(Kf)),o=Array.from(t.querySelectorAll(Kf));return[...n,...o].filter(s=>s.offsetParent!==null||s.tagName==="BUTTON")}_focusFirst(){const t=this._focusables();t.length>0?t[0].focus():this.shadowRoot?.querySelector(".dialog")?.focus?.()}_cancel(){const t=new CustomEvent("os-modal-cancel",{bubbles:!0,cancelable:!0,composed:!0});this.dispatchEvent(t)&&this.hideModal()}render(){const t=this.getAttribute("title")??"",n=this.hasAttribute("mandatory");return tt`
2 <div part="dialog" class="dialog" tabindex="-1">
3 ${t?tt`
4 <div class="header">
5 <h2 class="title">${t}</h2>
6 <div class="header-actions">
7 <slot name="header-actions"></slot>
8 ${n?tt``:tt`<button
9 type="button"
10 class="close"
11 aria-label="Close"
12 @click=${()=>this._cancel()}
13 >ร—</button>`}
14 </div>
15 </div>
16 `:tt``}
17 <div class="body">
18 <slot></slot>
19 </div>
20 <div class="footer">
21 <slot name="footer"></slot>
22 </div>
23 </div>
24 `}};ls.props=["open","title","size","mandatory"],ls.styles=[lS],ls.help=void 0;let ua=ls;ro("os-modal",ua);const dS=Se` ${da} ${Hf} ${Gf} ${zf} ${jf} ${Vf}:host{display:inline-flex}:host( [ fill-cell ] ){display:flex;width:100%}button{appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:6px;padding:var( --os-ui-button-padding,6px 12px );border-radius:var( --os-ui-button-border-radius,6px );font:inherit;font-weight:500;cursor:pointer;transition:background-color var( --_holo-t ) ease,color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,transform 80ms ease;background:var( --os-ui-button-bg,transparent );background-image:var( --os-ui-button-bg-image,none );background-repeat:var( --os-ui-button-bg-image-repeat,repeat );background-size:var( --os-ui-button-bg-image-size,auto );background-position:var( --os-ui-button-bg-image-position,center );color:var( --os-ui-button-fg,var( --os-ui-fg,#1d2327 ) );border:var( --os-ui-button-border,1px solid var( --os-ui-border,#c3c4c7 ) )}:host( [ fill-cell ] ) button{width:100%;min-height:var( --os-ui-button-min-height,44px )}button:disabled{opacity:0.5;cursor:not-allowed}button:active:not(:disabled ){transform:translateY( 1px )}button:hover:not(:disabled ){background-color:var( --os-ui-button-bg-hover,var( --os-ui-hover,rgba( 0,0,0,0.04 ) ) )}button:focus-visible{outline:none;box-shadow:var( --_holo-focus )}button:disabled::before,button:disabled::after,button:disabled .os-holo-glint{opacity:0 !important}:host( [ variant='primary' ] ) button{background-color:var( --os-ui-button-bg,var( --wp-admin-theme-color,#2271b1 ) );color:var( --os-ui-button-fg,var( --os-ui-fg-on-accent,#fff ) );border:var( --os-ui-button-border,1px solid transparent )}:host( [ variant='primary' ] ) button:hover:not(:disabled ){filter:brightness( 1.06 );background-color:var( --os-ui-button-bg,var( --wp-admin-theme-color,#2271b1 ) );box-shadow:var( --_holo-glow )}:host( [ variant='holo' ] ) button{background-color:transparent;background-image:var( --_holo-fill );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;color:var( --os-ui-button-fg,var( --_holo-ink ) );border:var( --os-ui-button-border,1px solid transparent );box-shadow:var( --_holo-glow );font-weight:600;transition:background-position var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,filter var( --_holo-t ) ease,transform 80ms ease}:host( [ variant='holo' ] ) button:hover:not(:disabled ){background-color:transparent;background-position:74% 66%;box-shadow:var( --_holo-glow-strong )}:host( [ variant='holo' ] ) button:active:not(:disabled ){background-position:88% 82%;filter:brightness( 0.94 )}:host( [ variant='holo' ] ) button::before{display:none}@media ( prefers-reduced-motion:reduce ){:host( [ variant='holo' ] ) button:hover:not(:disabled ),:host( [ variant='holo' ] ) button:active:not(:disabled ){background-position:22% 28%}}:host( [ variant='secondary' ] ) button{background-color:var( --os-ui-button-bg,var( --os-ui-hover,rgba( 0,0,0,0.06 ) ) );color:var( --os-ui-button-fg,var( --os-ui-fg,#1d2327 ) );border:var( --os-ui-button-border,1px solid transparent )}:host( [ variant='secondary' ] ) button:hover:not(:disabled ){background-color:var( --os-ui-button-bg-hover,var( --os-ui-hover,rgba( 0,0,0,0.1 ) ) )}:host( [ variant='danger' ] ) button{background-color:var( --os-ui-button-bg,transparent );color:var( --os-ui-button-fg,var( --os-ui-danger,#d63638 ) );border:var( --os-ui-button-border,1px solid currentColor )}:host( [ variant='danger' ] ) button:hover:not(:disabled ){background-color:var( --os-ui-danger,#d63638 );color:var( --os-ui-fg-on-accent,#fff )}:host( [ variant='danger' ] ) button::after{display:none}:host( [ variant='link' ] ) button{background-color:transparent;background-image:none;color:var( --os-ui-button-fg,var( --wp-admin-theme-color,#2271b1 ) );border:0;padding:0;text-decoration:underline}:host( [ variant='link' ] ) button::before,:host( [ variant='link' ] ) button::after,:host( [ variant='link' ] ) .os-holo-glint,:host( [ variant='link' ] ) .os-holo-ring{display:none}:host( [ variant='link' ] ) button:active:not(:disabled ){transform:none}:host( [ busy ] ) button{pointer-events:none;opacity:0.75}:host( [ variant='holo' ][ busy ] ) button{animation:os-holo-drift 12s ease-in-out infinite}@media ( prefers-reduced-motion:reduce ){:host( [ variant='holo' ][ busy ] ) button{animation:none}}.os-button__spinner{box-sizing:border-box;display:inline-block;width:12px;height:12px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:os-button-spin 0.6s linear infinite;flex-shrink:0}@keyframes os-button-spin{to{transform:rotate( 360deg )}}`,ds=class ds extends Pt{render(){const t=this.disabled!==null,n=this.busy!==null,o=this.type||"button";return tt`
25 <button
26 part="button"
27 class="os-holo-edge os-holo-sheen"
28 type=${o}
29 ?disabled=${t||n}
30 aria-busy=${n?"true":"false"}
31 >
32 ${n?tt`<span class="os-button__spinner" aria-hidden="true"></span>`:""}
33 <slot></slot>
34 <!--
35 The two motion layers. Elements rather than
36 pseudo-elements because the sheen and the hairline
37 have already taken this button's ::before and
38 ::after โ€” see the pseudo-element budget note in
39 src/ui/holo.ts. Both are inert and aria-hidden.
40 -->
41 <span class="os-holo-glint" aria-hidden="true"></span>
42 <span class="os-holo-ring" aria-hidden="true"></span>
43 </button>
44 `}};ds.props=["variant","disabled","type","busy","fill-cell"],ds.styles=[dS],ds.help=void 0;let fa=ds;ro("os-button",fa);function qf(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}const uS=()=>k("Mix your own two-colour gradient and set the angle โ€” your desk, your palette.");function fS(e){hn({id:Pb,label:k("Custom gradient"),type:"css",preview:qf(e.state),description:uS(),resolveValue:()=>qf(e.state)})}function pS(e){if(!e.customImage){Xu(wd);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`;hn({id:wd,label:k("Custom image"),type:"css",value:n,preview:n,description:k("Any image from your media library or an upload, sized to cover the whole desk.")})}let ao=null;function hS(e){return window.openStationRenderOsSettingsPanel?Promise.resolve(window.openStationRenderOsSettingsPanel):ao||(ao=new Promise((t,n)=>{const o=document.querySelector('script[data-os-settings-panel="1"]'),s=a=>{ao=null,document.querySelector('script[data-os-settings-panel="1"]')?.remove(),n(a)},i=()=>{const a=window.openStationRenderOsSettingsPanel;if(!a){s(new Error("[openstation] os-settings-panel bundle loaded but did not register openStationRenderOsSettingsPanel"));return}t(a)};if(o){window.openStationRenderOsSettingsPanel?i():(o.addEventListener("load",i),o.addEventListener("error",()=>s(new Error("failed to load os-settings-panel bundle"))));return}const r=document.createElement("script");r.src=e,r.async=!0,r.dataset.osSettingsPanel="1",r.addEventListener("load",i),r.addEventListener("error",()=>s(new Error("failed to load os-settings-panel bundle"))),document.head.appendChild(r)}),ao)}class mS{constructor(t,n){this.activeEditorTeardown=null,this.tabRegistryUnsubscribe=null,this.activeTabId=null,this.tabChangeAbort=null,this.osSettingsListeners=new Set,this._lastRenderedBody=null,this.config=t,this.layer=n,this.state=F_(),document.addEventListener("os-settings-save-lifecycle",o=>{const s=o.detail;if(!s)return;const r=window.wp?.os?.windowManager?.getById?.("os-settings");r&&r.markActivity(s.phase,{error:s.error}),!(s.phase!=="failed"||!s.rolledBackTo)&&(this.state=s.rolledBackTo,this.apply(),this._notify(),this._lastRenderedBody?.isConnected&&this.renderPanel(this._lastRenderedBody))}),fS(this),pS(this.state)}getOsSettingsSnapshot(){return{wallpaper:this.state.wallpaper,accent:this.state.accent,dockSize:this.state.dockSize,windowRadius:this.state.windowRadius,adminBarMode:this.state.adminBarMode,desktopLayout:this.state.desktopLayout,dockPlacement:this.state.dockPlacement,dockBehavior:this.state.dockBehavior,sideDockBehavior:this.state.sideDockBehavior,dockRailRenderer:this.state.dockRailRenderer,desktopTheme:this.state.desktopTheme,appliedThemeRecommendations:this.state.appliedThemeRecommendations.slice(),unfocusEffect:this.state.unfocusEffect,windowReveal:this.state.windowReveal,windowRevealDuration:this.state.windowRevealDuration,windowLinkRenderer:this.state.windowLinkRenderer,windowLinkVisibility:this.state.windowLinkVisibility,windowLinksEnabled:this.state.windowLinksEnabled,windowLinkRaiseOnFocus:this.state.windowLinkRaiseOnFocus,windowLinkHighlight:this.state.windowLinkHighlight,ai:{...this.state.ai},nativePostsEnabled:this.state.nativePostsEnabled,nativePostsHiddenColumns:this.state.nativePostsHiddenColumns.slice(),nativePagesEnabled:this.state.nativePagesEnabled,nativeUsersEnabled:this.state.nativeUsersEnabled,nativePluginsEnabled:this.state.nativePluginsEnabled,nativeCommentsEnabled:this.state.nativeCommentsEnabled,stationHomeEnabled:this.state.stationHomeEnabled,adminAssetCacheEnabled:this.state.adminAssetCacheEnabled,windowPrewarmEnabled:this.state.windowPrewarmEnabled,developerModeEnabled:this.state.developerModeEnabled,foldersSharingEnabled:this.state.foldersSharingEnabled,showPostStatusRibbons:this.state.showPostStatusRibbons,navPlacement:{...this.state.navPlacement},navOrder:this.state.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(this.state.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}subscribeOsSettings(t){return this.osSettingsListeners.add(t),()=>{this.osSettingsListeners.delete(t)}}apply(){const t=document.getElementById("os-shell");if(!t)return;T_(this.state.wallpaperSettings);const n=Vr(this.state.wallpaper)||Vr(vd())||Vr(wr)||Ju()[0];n&&this.layer.apply(n);const o=yr(),s=o.find(p=>p.id===this.state.accent)??o[0],i=this.state.accent===yd?this.state.customAccent:s.value,r=br.find(p=>p.id===this.state.dockSize)??br[1],a=vr.find(p=>p.id===this.state.windowRadius)??vr[1],c=document.body;c.style.setProperty("--wp-admin-theme-color",i),c.style.setProperty("--os-ui-accent",i);const d=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;d===null?c.style.removeProperty("--os-ui-accent-dim"):c.style.setProperty("--os-ui-accent-dim",d),t.style.setProperty("--os-ui-accent",i),d===null?t.style.removeProperty("--os-ui-accent-dim"):t.style.setProperty("--os-ui-accent-dim",d),c.style.setProperty("--os-dock-width",`${r.width}px`),c.style.setProperty("--os-dock-icon-size",`${r.icon}px`),c.style.setProperty("--os-window-radius",`${a.value}px`),t.style.setProperty("--os-window-radius",`${a.value}px`);const u=Es.find(p=>p.id===this.state.adminBarMode)??Es[0];for(const p of Es)document.body.classList.toggle(`os-admin-bar-${p.id}`,p.id===u.id);const f=p=>(_s.find(v=>v.id===p)??_s[0]).id;document.getElementById(O_)?.setAttribute(oo,f(this.state.dockBehavior)),document.getElementById(tf)?.setAttribute(oo,f(this.state.sideDockBehavior)),$_(),OE(),t.setAttribute("data-os-layout",this.state.desktopLayout),ib(this.state.dockRailRenderer),aa(this.state.desktopTheme)}save(t={}){Y_(this.state,t),this._notify()}_notify(){if(this.osSettingsListeners.size>0){const t=this.getOsSettingsSnapshot(),n=Array.from(this.osSettingsListeners);for(const o of n)try{o(t)}catch(s){typeof console<"u"&&console.error("[openstation] os-settings listener threw:",s)}}}focusTab(t){this.activeTabId=t;const n=this._lastRenderedBody;if(!n?.isConnected)return;const o=n.querySelector("os-tabs");o&&(o.value=t)}renderPanel(t){io("os-settings"),this._lastRenderedBody=t;const n=window.openStationRenderOsSettingsPanel;if(n){n(this,t);return}const o=xf(t,{label:k("Loading preferencesโ€ฆ")});hS(this.config.osSettingsPanelBundleUrl??"").then(s=>{o.done(),t.isConnected&&s(this,t)}).catch(s=>{o.fail(k("Preferences could not be loaded."),()=>this.renderPanel(t)),typeof console<"u"&&console.error("[openstation] OpenStation Preferences panel failed to load:",s)})}}const gS={userId:null,requestedAt:0,tabRequested:!1};let Qs=null;function wS(){if(Qs)return Qs;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(Qs=t("desktop-mode/user-edit/target",()=>({...gS})),Qs)}function yS(e){const t=wS();if(t){t.state.userId=e,t.state.requestedAt=Date.now(),t.state.tabRequested=!0,t.notify();return}const n=window;n._wpdUserEditTarget={userId:e,requestedAt:Date.now(),tabRequested:!0}}let ei=null;function bS(){if(ei)return ei;const e=window.wp?.os?.createSharedStore;return typeof e!="function"?null:(ei=e("desktop-mode/comments/post-filter",()=>({postId:0})),ei)}function Yf(e){const t=bS();t&&(t.state.postId=e,t.notify())}function vS(){Yf(0)}function Xf(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:ES(),visible:!document.hidden,settings:L_(e)}}function ES(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class Zf{constructor(t,n){this.generation=0,this.active=null,this.suspendReasons=new Map,this.freezeOverlay=null,this.frozenCanvas=null,this.boundVisibilityChange=()=>{this.emitEffectiveVisibility()},this.element=t,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(t){const n=++this.generation;if(this.teardownActive(),t.type==="css"){this.applyCss(t);return}this.applyCanvas(t,n)}suspend(t){const n=this.isSuspended();this.suspendReasons.set(t,(this.suspendReasons.get(t)??0)+1),!n&&(this.installFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}resume(t){const n=this.suspendReasons.get(t);if(n!==void 0){if(n>1){this.suspendReasons.set(t,n-1);return}this.suspendReasons.delete(t),!this.isSuspended()&&(this.removeFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}}isSuspended(){return this.suspendReasons.size>0}teardownActive(){if(this.removeFreezeOverlay(),!this.active)return;const{id:t,teardown:n}=this.active;this.active=null,T(m.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){T(m.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(Xf(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=Xf(t.id,this.pluginUrl);T(m.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?la(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},T(m.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(_S(r)){r.then(i,a=>{n===this.generation&&this.handleMountFailure(t.id,a)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(t.id,r)})}isEffectivelyHidden(){return document.hidden||this.isSuspended()}emitEffectiveVisibility(){this.active&&T(m.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){T(m.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="",T(m.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),T(m.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function _S(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const Jf=ie("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),gn=Jf.state.seed,pa=Jf.state.listeners;function ha(e){Ie("Game",Tt(e,np),e);const t=gn.findIndex(n=>n.id===e.id);t>=0?gn[t]=e:gn.push(e),ep()}function Qf(e){const t=gn.findIndex(n=>n.id===e);t>=0&&(gn.splice(t,1),ep())}function kS(e){return pa.add(e),()=>{pa.delete(e)}}function ep(){const e=Array.from(pa);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function tp(){const e=gn.slice(),t=Z(m.GAMES,e);return Array.isArray(t)?t.filter(SS):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function ti(e){return tp().find(t=>t.id===e)}const np=[{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 SS(e){return Tt(e,np).length===0}const AS="desktop-mode/games";function IS(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function co(e,t={},n={}){const{restUrl:o,restNonce:s}=IS(),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 Be(it(o,e),{...t,headers:i,credentials:"same-origin"},{source:AS,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok){const c=a?.message||`Games request failed (${r.status})`,l=new Error(c);throw l.status=r.status,l}return a}function CS(e,t,n={}){return co(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function LS(){return co("desktop-mode/v1/games/playtime")}function TS(e,t,n={}){return co(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function NS(e){return co(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function OS(e,t,n={}){return co(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const DS=6e4;function RS(e,t={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const c=Date.now();o+=Math.max(0,c-n),n=c},r=()=>{i();const c=Math.floor(o/1e3);c<1||(o-=c*1e3,TS(e,c,{windowId:t.windowId,silent:!0}).catch(()=>{o+=c*1e3}))},a=setInterval(r,DS);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const wn=ie("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function xS(){return wn.state}function ma(e){const t=wn.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&&PS()}function MS(e){return wn.state.listeners.add(e),()=>{wn.state.listeners.delete(e)}}function PS(){for(const e of Array.from(wn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function WS(){return Array.from(wn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function op(){return window.wp?.os??{}}const $S=760,US=560,BS=480,FS=380;function HS(){const e=window.openStationConfig?.gameStyleHandles??[];for(const t of e)io(t)}async function GS(e){if(typeof e.render=="function")return e;const t=op().loadVendorScript;if(!e.scriptUrl||typeof t!="function")throw new Error(`[openstation] Game "${e.id}" has no render callback and no loadable script.`);await t(e.scriptUrl,{translations:e.scriptTranslations,l10n:e.scriptL10n,before:e.scriptBefore,after:e.scriptAfter});const o=window.openStationGames?.[e.id];if(!o||typeof o.render!="function")throw new Error(`[openstation] No game def on window.openStationGames["${e.id}"]. Script loaded but didn't publish a def โ€” check the plugin's global assignment.`);const s={...e,render:o.render,window:o.window??e.window};return ha(s),s}async function sp(e,t={}){const n=op(),o=ti(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);if(HS(),typeof n.registerWindow!="function")throw new Error("[openstation] wp.os.registerWindow is missing โ€” the shell must boot before launching games.");const s=`os-game-${e}`,i=`game:${s}`,r=n.windowManager,a=r?.getByBaseId?.(s)??r?.getById(s);if(a){const v=a.config?.desktopId;v&&r?.switchDesktop&&v!==r?.getActiveDesktopId?.()&&r.switchDesktop(v),n.registerWindow({id:s,title:o.title,icon:o.icon,render:()=>{}});return}n.wallpaper?.suspend(i);let c=!1;const l=()=>{c||(c=!0,n.wallpaper?.resume(i))};let d=null;const u=()=>{d?.stop(),d=null};n.onWindow?.(s,{closed:()=>{u(),l()},minimized:()=>d?.pause(),restored:()=>d?.resume()});const f=(v,b)=>{n.activity?.publish("os/game-score-recorded",{game:e,score:v.score,meta:v.meta??{},windowId:s,challengeId:b})},p=v=>{if(t.challenge){const b=t.challenge.id;return OS(b,v,{windowId:s}).then(({challenge:w})=>{ma([w]),f(v,b)})}return CS(e,v,{windowId:s}).then(()=>f(v))};try{await n.registerWindow({id:s,title:o.title,icon:o.icon,width:o.window?.width??$S,height:o.window?.height??US,minWidth:o.window?.minWidth??BS,minHeight:o.window?.minHeight??FS,render:async v=>{const b=await GS(o),w=b.render;if(typeof w!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);const g={windowId:s,container:v,config:b.config??{},challenge:t.challenge,submitScore:p,close:()=>{n.windowManager?.getById(s)?.close()}};d=RS(e,{windowId:s});const _=w(g);return()=>{try{_?.()}finally{u(),l()}}}})}catch(v){throw u(),l(),v}}const ip={register:ha,unregister:Qf,list:tp,get:ti,subscribe:kS,launch:sp,getPlaytime:()=>LS().then(e=>e.playtime)};function zS(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){hn(a),n.add(r.id),t.apply();return}if(!r.scriptUrl)return;tS(r);const c=r.preview!==""||r.value!=="";if(c){try{hn(oS(r))}catch(l){T(m.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:l}),Js(r.id);return}n.add(r.id)}if(!c||t.state.wallpaper===r.id){const l=await Ff(r.id);if(!c){if(!l){Js(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(Xu(r),Js(r),n.delete(r),t.apply())};return async r=>{const a=new Set;for(const c of r)a.add(c.id);for(const c of Array.from(n))a.has(c)||i(c);for(const c of r)n.has(c.id)||await s(c)}}function jS(e){return{id:e.id,title:e.title,icon:e.icon,description:e.description||void 0,scoreColumns:Array.isArray(e.scoreColumns)?e.scoreColumns:[],config:e.config??{},window:e.window&&Object.keys(e.window).length>0?e.window:void 0,scriptUrl:e.scriptUrl,scriptTranslations:e.scriptTranslations,scriptL10n:e.scriptL10n,scriptBefore:e.scriptBefore,scriptAfter:e.scriptAfter}}function VS(){const e=new Set,t=o=>{try{const s=ti(o.id),i=jS(o);ha(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)&&(Qf(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)}}function KS(e={}){const t=e.deactivate??(()=>aa(""));return function(o){Vb(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=ln().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const at=ie("desktop-mode/heartbeat-bus",()=>({suppliers:new Map,subscribers:new Map,booted:!1})),Te={contribute(e,t){return at.state.suppliers.set(e,t),()=>{at.state.suppliers.get(e)===t&&at.state.suppliers.delete(e)}},subscribe(e,t){let n=at.state.subscribers.get(e);return n||(n=new Set,at.state.subscribers.set(e,n)),n.add(t),()=>{n.delete(t)}}};function qS(){if(at.state.booted)return;at.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 at.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 at.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 ni=null,oi={installHintDismissed:!1,notificationsEnabled:!1};const ga=new Set;function rp(e){if(!e){ni=null;return}ni=e,oi={...e.state},cp()}function lo(){return{...oi}}function wa(e){if(oi={...oi,...e},cp(),!ni)return lo();const t=JSON.stringify(e),n=YS();return fetch(ni.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)}),lo()}function ap(e){return ga.add(e),()=>{ga.delete(e)}}function cp(){const e=lo();for(const t of Array.from(ga))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function YS(){return window.openStationConfig?.restNonce??""}const XS=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:lo,initPwaState:rp,subscribePwaState:ap,updatePwaState:wa},Symbol.toStringTag,{value:"Module"}));function ya(e){const t=Ee.filter("os/notification-requested",{...e});if(!t||t.cancel===!0||!t.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=fe({message:t.body?t.title+" โ€” "+t.body:t.title}),Ee.publish("os/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=lp(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(c=>{if(!n){if(c==="granted"){wa({notificationsEnabled:!0}),o=lp(t),o||r();return}r()}}),i)}function lp(e){let t=null;try{t=new Notification(e.title,{body:e.body,icon:e.icon,tag:e.tag,requireInteraction:e.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[openstation] Notification ctor threw:",n),null}if(e.onClick){const n=e.onClick;t.onclick=()=>{try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] notification onClick threw:",o)}}}return Ee.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function ZS(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&wa({notificationsEnabled:!0}),e}function JS(){return typeof Notification>"u"?"unsupported":Notification.permission}function QS(e){return ti(e)?.title||e}const dp=new Set,up=new Set;async function e0(e){const{challenge:t}=await NS(e.id);ma([t]),await sp(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function t0(e){const t=de(k("%1$s challenged you to %2$s โ€” beat %3$s!"),e.challengerName,QS(e.game),String(e.scoreToBeat));ya({title:k("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),fe({message:t,persistent:!0,dismissible:!0,action:{label:k("Accept & Play"),onClick:()=>{e0(e).catch(n=>{fe({message:n instanceof Error?n.message:k("Could not accept the challenge.")})})}}})}function n0(e){let t;e.result==="beaten"?t=k("%1$s beat your score: %2$s vs your %3$s."):t=k("%1$s did not beat your score: %2$s vs your %3$s.");const n=de(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));ya({title:k("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),fe({message:n})}function o0(e){const{currentUserId:t}=e;if(!t)return;Te.contribute("openstation_games_subscribe",()=>({challengesVersion:xS().version})),Te.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&ma(o.challenges)});const n=()=>{for(const o of WS())o.state==="pending"&&o.recipientId===t&&!dp.has(o.id)&&(dp.add(o.id),t0(o)),o.state==="completed"&&o.challengerId===t&&!up.has(o.id)&&(up.add(o.id),n0(o))};MS(n),n()}const fp=/^[a-z0-9_/-]+$/,pp=ie("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),Wt=pp.state.registry,s0=pp.state.listeners;function si(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)"):fp.test(n)||t.push(`slug (must match ${fp} โ€” 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)")),Ie("Command",t,e),Wt.set(n,{...e,slug:n}),ba()}function hp(e){Wt.delete(e.toLowerCase())&&ba()}function ii(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Wt.entries()))o.owner===e&&(Wt.delete(n),t++);return t>0&&ba(),t}function mp(){return Array.from(Wt.values())}function i0(){const e=[];for(const t of Wt.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function r0(e){return Wt.get(e.toLowerCase())??null}function ba(){const e=Array.from(s0);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function a0(){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 ue(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(m.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 c of r){if(!c.scriptHandle||!c.slug)continue;let l=a.get(c.scriptHandle);l||(l=new Set,a.set(c.scriptHandle,l)),l.add(c.slug)}return a},i=r=>{const a=new Set;for(const l of mp())l.owner===r&&a.add(l.slug);const c=n.get(r);if(c)for(const l of c)a.add(l);return a};return async(r,a)=>{const c=new Set;for(const l of r)l.handle&&c.add(l.handle);for(const l of Array.from(e))if(!c.has(l)){for(const d of i(l))hp(d);e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const gp=ie("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),uo=gp.state.registry,c0=gp.state.listeners;function wp(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}uo.set(t,{...e,id:t}),va()}function yp(e){uo.delete(e.toLowerCase())&&va()}function l0(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(uo.entries()))o.owner===e&&(uo.delete(n),t++);return t>0&&va(),t}function bp(){return Array.from(uo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function va(){const e=Array.from(c0);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function d0(){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 ue(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(m.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 c of r){if(!c.scriptHandle||!c.id)continue;let l=a.get(c.scriptHandle);l||(l=new Set,a.set(c.scriptHandle,l)),l.add(c.id)}return a},i=r=>{l0(r);const a=n.get(r);if(a){const c=new Set(bp().map(l=>l.id));for(const l of a)c.has(l)&&yp(l)}};return async(r,a)=>{const c=new Set;for(const l of r)l.handle&&c.add(l.handle);for(const l of Array.from(e))c.has(l)||(i(l),e.delete(l));for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const vp=ie("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),fo=vp.state.registry,u0=vp.state.listeners,Ep=/^[a-z0-9_/-]+$/;function ri(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Ep.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Ep} โ€” 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)")),Ie("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();fo.set(n,{...e,id:n}),ai()}function f0(e){fo.delete(e.toLowerCase())&&ai()}function p0(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(fo.entries()))o.owner===e&&(fo.delete(n),t++);return t>0&&ai(),t}function h0(){return Array.from(fo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function ai(){const e=Array.from(u0);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"&&ai()});function m0(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ue(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(m.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)||(p0(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const _p=ie("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),po=_p.state.registry,g0=_p.state.listeners,kp=/^[a-z0-9_/-]+$/;function Ea(){for(const e of Array.from(g0))try{e()}catch{}}function w0(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):kp.test(e.id.trim().toLowerCase())||t.push(`id (must match ${kp} โ€” 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)")),Ie("WindowAction",t,e);const n=e.id.trim().toLowerCase();po.set(n,{...e,id:n}),Ea()}function y0(e){po.delete(String(e||"").toLowerCase())&&Ea()}function b0(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(po.entries()))o.owner===e&&(po.delete(n),t++);return t>0&&Ea(),t}function v0(){return Array.from(po.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function E0(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ue(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(m.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)||(b0(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function Sp(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function _0({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)=>Sp(r[0])-Sp(a[0])),i=[];for(const[,r]of s){const a=r.find(c=>typeof c.groupLabel=="string"&&c.groupLabel!=="")?.groupLabel;if(a){const c=document.createElement("div");c.className="os-window__related-group",c.setAttribute("role","presentation"),c.textContent=a,n.appendChild(c)}for(const c of r){const l=document.createElement("os-menu-item");l.setAttribute("role","menuitem"),l.setAttribute("value",c.id),l.tabIndex=-1,c.icon&&l.setAttribute("icon",c.icon),l.classList.add("os-window__related-item"),l.textContent=typeof c.count=="number"?`${c.label} (${c.count})`:c.label,l.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),t(c)}),i.push(l),n.appendChild(l)}}return n.addEventListener("keydown",r=>{const a=r,c=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const l=a.key==="ArrowDown";let d=i[l?0:i.length-1];c!==-1&&(d=i[(c+(l?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 l=i[c];l&&(a.preventDefault(),a.stopPropagation(),l.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function Ap(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 Ip(e){const t=bt(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=Z(m.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(Ap):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(Ap))}function _a(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function k0(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function S0(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=Ip(t.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",a),c.remove(),e.setAttribute("aria-expanded","false")},a=l=>{l.key==="Escape"&&(l.stopPropagation(),r(),e.focus())},c=_0({items:s,onPick:l=>{r(),k0(o),n(l)}});c._wpdRelatedClose=r,o.appendChild(c),o.addEventListener("keydown",a),e.setAttribute("aria-expanded","true"),i=l=>{const d=l.target;!d||c.contains(d)||e.contains(d)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),c.querySelector('[role="menuitem"]')?.focus()}function A0({manager:e,openUrl:t}){ri({id:"desktop-mode/related-entities",label:k("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>Ip(n.id).length>0,render:(n,o)=>{_a(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")){_a(o.element);return}S0(n,o,t)})}}),ne(m.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(_a(o.element),o.renderCustomTitleBarButtons?.())})}const ka="os-broadcast",Cp="os-broadcast",Lp=window.location.origin;let Sa=null;function I0(e){Sa=e}function ci(e,t){const n=String(Z("os.broadcast.topic",e,{payload:t})??e),o=Z("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(ka,{detail:s})),T(m.BROADCAST,s),Ee.publish(n,o),!Sa)return;const i={type:Cp,topic:n,payload:o};for(const r of Sa._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Lp)}catch{}}}function yn(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){T(m.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(ka,n),()=>document.removeEventListener(ka,n)}function C0(){window.addEventListener("message",e=>{if(e.origin!==Lp)return;const t=e.data;!t||t.type!==Cp||t._fromParent||typeof t.topic=="string"&&ci(t.topic,t.payload)})}function Tp(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||ci(`os.${i}.changed`,{source:o,action:t,ids:s})}const L0=new Set(["saved","no-editor","not-dirty","error"]);let Np=0;function Op(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function T0(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Np+=1;const o=`os-editor-preview-${Date.now()}-${Np}`;return new Promise(s=>{let i=null,r=!1;const a=l=>{r||(r=!0,window.removeEventListener("message",c),i!==null&&window.clearTimeout(i),s(l))},c=l=>{if(l.origin!==window.location.origin)return;const d=l?.data;if(!d||typeof d!="object"||d.type!=="os-editor-autosave-response"||d.requestId!==o)return;const u=typeof d.status=="string"&&L0.has(d.status)?d.status:"error",f=Op(d.previewUrl);a(f?{status:u,previewUrl:f}:{status:u})};window.addEventListener("message",c),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 Ne=ie("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),N0=400,Dp=1500;function ho(e){return e?`${e.type}:${e.id}`:""}function O0(e){for(const t of Ne.state.pairings.values())if(t.previewWindowId===e)return t}function D0(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function R0(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 li(e,t,n,o){Ne.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(xp(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})),T(m.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function Aa(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||bt(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?.()},N0)}function x0(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=yn(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||Aa(e,t)})}let Rp=0;function xp(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 Mp(e,t,n){xp(e,t);const o=Z(m.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:Dp},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;Rp+=1;const i=`${t.previewWindowId}-watch-${Rp}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:Dp},window.location.origin),t.watchId=i}catch{}}let M0=T0;async function P0(e,t){const n=Ne.state.pairings.get(t.id);if(n){li(e,n,"toggled","close");return}if(Ne.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=bt(t.id);if(!o?.previewUrl){fe({message:k("No preview is available for this content.")});return}Ne.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=D0();s||t.applySnap?.("left");const i=M0(t);i.then(f=>{f.status==="error"&&fe({message:k("Couldn't save your latest changes โ€” the preview shows the last saved version.")})}).finally(()=>{Ne.state.busyEditors.delete(t.id),e.getById(t.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=k("Preview");o.label&&(a=de(k("Preview: %s"),o.label));let c={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const l=Z(m.EDITOR_PREVIEW_WINDOW_CONFIG,c,{editorWindowId:t.id,content:o});if(l&&typeof l=="object"&&typeof l.id=="string"&&l.id!==""&&typeof l.url=="string"&&l.url!==""?c=l:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await e.open(c),!e.getById(t.id)||ho(bt(t.id))!==ho(o)){e.getById(c.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:c.id,postKey:ho(o),openUrl:c.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};x0(e,d,o),Mp(e,d,o),Ne.state.pairings.set(t.id,d);const u={editorWindowId:t.id,previewWindowId:c.id,content:o};document.dispatchEvent(new CustomEvent("os-editor-preview-opened",{detail:u})),T(m.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Ne.state.pairings.get(t.id)===d&&f.status==="saved"&&Aa(e,d,f.previewUrl)})}function W0({manager:e}){ri({id:"desktop-mode/editor-preview",label:k("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!bt(t.id)?.previewUrl||R0(t)),render:(t,n)=>{if(!bt(n.id)?.previewUrl){const i=k("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(),fe({message:k("The preview opens once the post has been saved.")})});return}const o=Ne.state.pairings.has(n.id),s=Ne.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(),P0(e,n)})}}),ne(m.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Ne.state.pairings.get(t.windowId);n&&ho(t.content)!==n.postKey&&li(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),ne(m.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Ne.state.pairings.get(t.windowId);if(n){li(e,n,"editor-closed","destroy");return}const o=O0(t.windowId);o&&li(e,o,"preview-closed","none")}),ne(m.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Ne.state.pairings.get(t.windowId);if(n){const o=bt(t.windowId);o&&ho(o)===n.postKey&&Mp(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 Ne.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){Aa(e,o,Op(n.previewUrl));return}}})}const Pp="none",Wp=ie("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),mo=Wp.state.registry,Ia=Wp.state.listeners,$p=/^[a-z0-9_/-]+$/;function di(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):$p.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Pp&&t.push('id ("none" is reserved)'):t.push(`id (must match ${$p} โ€” 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)")),Ie("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();mo.set(n,{...e,id:n}),La()}function $0(e){mo.delete(e.toLowerCase())&&La()}function U0(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(mo.entries()))o.owner===e&&(mo.delete(n),t++);return t>0&&La(),t}function Ca(){const e=Array.from(mo.values()),t=Z(m.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 Up(e){return Ca().find(t=>t.id===e)}function B0(e){return Ia.add(e),()=>{Ia.delete(e)}}function La(){const e=Array.from(Ia);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}di({id:"darken",label:k("Darken"),description:k("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),di({id:"frost",label:k("Frost"),description:k("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"}),di({id:"grayscale",label:k("Grayscale"),description:k("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 F0(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ue(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(m.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)||(U0(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const H0="none",Bp=ie("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),go=Bp.state.registry,G0=Bp.state.listeners,Fp=/^[a-z0-9_/-]+$/;function Hp(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Fp.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===H0&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Fp} โ€” 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)")),Ie("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();go.set(n,{...e,id:n}),Na()}function z0(e){go.delete(e.toLowerCase())&&Na()}function j0(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(go.entries()))o.owner===e&&(go.delete(n),t++);return t>0&&Na(),t}function Ta(){const e=Array.from(go.values()),t=Z(m.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 Na(){const e=Array.from(G0);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}function V0(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ue(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(m.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)||(j0(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}let $t=null;function Gp(){if($t)return $t;if(window.openStationWindowLinkVisuals)return $t=Promise.resolve(!0),$t;const t=window.openStationConfig?.windowLinkVisualsBundleUrl;return t?($t=ue(t).then(()=>!0).catch(n=>{throw $t=null,n}),$t):Promise.resolve(!1)}const Oa="svg-splines";function K0(){if(Ta().some(t=>t.id===Oa))return;const e=async t=>{if(!await Gp())return;const o=Ta().find(s=>s.id===Oa);if(!(!o||o.mount===e))return o.mount(t)};Hp({id:Oa,label:k("Splines"),description:k("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 Da="data-desktop-unfocus-effect",Ra="data-desktop-unfocus-effect-class";let zp=!1;function q0(e){return e.querySelector("canvas")!==null}function Y0(e){return e.state==="snapped-left"||e.state==="snapped-right"}function X0({manager:e,osSettings:t}){if(zp)return;zp=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const c=r.getAttribute(Ra);c&&(r.classList.remove(c),r.removeAttribute(Ra));const l=r.getAttribute(Da);l&&Up(l)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(Da)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Ra,a.className)),r.setAttribute(Da,a.id),a.apply?.(r)},i=()=>{const r=n===Pp?void 0:Up(n),a=Ca();for(const c of e.getAll()){const l=c.element;l&&(o(l,a),!(!r||c.isFocused()||c.state==="minimized")&&(Y0(c)||q0(l)||s(l,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()}),B0(()=>i()),i()}function Z0(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ue(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(m.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)||(tb(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function J0(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,ue(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 jp=ie("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),wo=jp.state.registry,Q0=jp.state.listeners,Vp=/^[a-z0-9_/-]+$/;function Kp(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)"):Vp.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Vp} โ€” 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)")}Ie("WindowTheme",t,e);const n=e.id.trim().toLowerCase();wo.set(n,{...e,id:n}),xa()}function qp(e){wo.delete(e.toLowerCase())&&xa()}function eA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(wo.entries()))o.owner===e&&(wo.delete(n),t++);return t>0&&xa(),t}function Yp(){return Array.from(wo.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function xa(){const e=Array.from(Q0);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function tA(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async c=>{if(!c.scriptUrl||t.has(c.scriptUrl)){e.add(c.handle);return}try{await ue(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter})}catch(l){T(m.SHELL_ERROR,{scope:"window-theme-script-load",handle:c.handle,url:c.scriptUrl,error:l});return}t.add(c.scriptUrl),e.add(c.handle)},i=c=>{const l=new Map;if(!c)return l;for(const d of c){if(!d.scriptHandle||!d.id)continue;let u=l.get(d.scriptHandle);u||(u=new Set,l.set(d.scriptHandle,u)),u.add(d.id)}return l},r=c=>{const l=new Set;for(const u of Yp())u.owner===c&&l.add(u.id);const d=n.get(c);if(d)for(const u of d)l.add(u);return l},a=c=>{if(c){for(const l of c)if(!(!l.id||!l.tokens))try{Kp({id:l.id,label:l.label,tokens:l.tokens,priority:l.priority,match:()=>!0,owner:l.scriptHandle||void 0}),o.add(l.id)}catch(d){T(m.SHELL_ERROR,{scope:"window-theme-shell-register",id:l.id,error:d})}}};return async(c,l)=>{const d=new Set;for(const u of c)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)qp(p),o.delete(p);eA(u),e.delete(u)}a(l);for(const u of c)!u.handle||e.has(u.handle)||await s(u);n=i(l)}}const Xp=ie("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),yo=Xp.state.registry,nA=Xp.state.listeners,Zp=/^[a-z0-9_/-]+$/;function bo(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Zp.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Zp} โ€” 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")')),Ie("WindowControl",t,e);const n=e.id.trim().toLowerCase();yo.set(n,{...e,id:n}),Ma()}function Jp(e){yo.delete(e.toLowerCase())&&Ma()}function oA(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&&Ma(),t}function Qp(){return Array.from(yo.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Ma(){const e=Array.from(nA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function sA(){bo({id:"core/minimize",label:k("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),bo({id:"core/maximize",label:k("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),bo({id:"core/focus-tab",label:k("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),bo({id:"core/close",label:k("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function iA(){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 ue(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(m.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 c of r){if(!c.scriptHandle||!c.id)continue;let l=a.get(c.scriptHandle);l||(l=new Set,a.set(c.scriptHandle,l)),l.add(c.id)}return a},i=r=>{const a=new Set;for(const l of Qp())l.owner===r&&a.add(l.id);const c=n.get(r);if(c)for(const l of c)a.add(l);return a};return async(r,a)=>{const c=new Set;for(const l of r)l.handle&&c.add(l.handle);for(const l of Array.from(e))if(!c.has(l)){for(const d of i(l))Jp(d);oA(l),e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const eh=ie("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),vo=eh.state.registry,rA=eh.state.listeners,th=/^[a-z0-9_/-]+$/,nh=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function oh(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):th.test(e.id.trim().toLowerCase())||t.push(`id (must match ${th} โ€” lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):nh.has(e.slot)||t.push(`slot (must be one of ${Array.from(nh).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Ie("WindowSlot",t,e);const n=e.id.trim().toLowerCase();vo.set(n,{...e,id:n}),Wa()}function Pa(e){vo.delete(e.toLowerCase())&&Wa()}function aA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(vo.entries()))o.owner===e&&(vo.delete(n),t++);return t>0&&Wa(),t}function sh(){return Array.from(vo.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Wa(){const e=Array.from(rA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function cA(){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 ue(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(m.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 c of r){if(!c.scriptHandle||!c.id)continue;let l=a.get(c.scriptHandle);l||(l=new Set,a.set(c.scriptHandle,l)),l.add(c.id)}return a},i=r=>{const a=new Set;for(const l of sh())l.owner===r&&a.add(l.id);const c=n.get(r);if(c)for(const l of c)a.add(l);return a};return async(r,a)=>{const c=new Set;for(const l of r)l.handle&&c.add(l.handle);for(const l of Array.from(e))if(!c.has(l)){for(const d of i(l))Pa(d);aA(l),e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const lA="desktop-mode-notice-dismissed";function dA(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function ih(){return`${lA}:${dA()}`}function $a(){try{const e=window.localStorage.getItem(ih());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function rh(e){try{window.localStorage.setItem(ih(),JSON.stringify(e))}catch{}}function ui(e){return e?$a()[e]===!0:!1}function fi(e){if(!e)return;const t=$a();t[e]=!0,rh(t)}function ah(e){if(!e)return;const t=$a();t[e]&&(delete t[e],rh(t))}const uA=Se`: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 ) )}`,us=class us extends Pt{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&ui(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&fi(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&ah(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return tt`
45 <span
46 class="os-notice__icon dashicons ${t??""}"
47 ?hidden=${!t}
48 aria-hidden="true"
49 ></span>
50 <span class="os-notice__label"><slot></slot></span>
51 <button
52 type="button"
53 class="os-notice__close"
54 ?hidden=${!n}
55 aria-label=${k("Dismiss notice")}
56 @click=${o=>this._onDismiss(o)}
57 >
58 ${Wl("close",{size:null})}
59 </button>
60 `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};us.props=["tone","notDismissible","icon","noticeId"],us.styles=[uA],us.help=void 0;let Ua=us;ro("os-notice",Ua);const Eo=ie("desktop-mode/window-notices",()=>({entries:new Map})),fA=/^[a-z0-9_/-]+$/;function ch(e){return`os-notice/${e.toLowerCase()}`}function pA(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 lh(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!fA.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};Eo.state.entries.set(t,n);const o=ch(t);return oh({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=Eo.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=Eo.state.entries.get(t);i&&s.appendChild(pA(i))}}),()=>Ba(t)}function Ba(e){const t=String(e??"").trim().toLowerCase();t&&Eo.state.entries.delete(t)&&Pa(ch(t))}function dh(){return Array.from(Eo.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 hA(e){const t=String(e??"").trim().toLowerCase();t&&fi(t)}function mA(e){const t=String(e??"").trim().toLowerCase();t&&ah(t)}function gA(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 uh(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),lh({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:gA(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of dh())n.owner==="__server__"&&(t.has(n.id)||Ba(n.id))}const fh=ie("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),_o=fh.state.registry,wA=fh.state.listeners,ph=/^[a-z0-9_/-]+$/;function yA(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):ph.test(e.id.trim().toLowerCase())||t.push(`id (must match ${ph} โ€” 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)")),Ie("WindowChrome",t,e);const n=e.id.trim().toLowerCase();_o.set(n,{...e,id:n}),Fa()}function hh(e){_o.delete(e.toLowerCase())&&Fa()}function bA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(_o.entries()))o.owner===e&&(_o.delete(n),t++);return t>0&&Fa(),t}function mh(){return Array.from(_o.values()).sort((e,t)=>e.id.localeCompare(t.id))}function Fa(){const e=Array.from(wA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function vA(){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 ue(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(m.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 c of r){if(!c.scriptHandle||!c.id)continue;let l=a.get(c.scriptHandle);l||(l=new Set,a.set(c.scriptHandle,l)),l.add(c.id)}return a},i=r=>{const a=new Set;for(const l of mh())l.owner===r&&a.add(l.id);const c=n.get(r);if(c)for(const l of c)a.add(l);return a};return async(r,a)=>{const c=new Set;for(const l of r)l.handle&&c.add(l.handle);for(const l of Array.from(e))if(!c.has(l)){for(const d of i(l))hh(d);bA(l),e.delete(l)}for(const l of r)!l.handle||e.has(l.handle)||await o(l);n=s(a)}}const Ha=window.location.origin;let EA=0;const bn=new Map,vn=new Map,ko=new Map;function _A(e,t){return ko.set(e,t),()=>{ko.get(e)===t&&ko.delete(e)}}function kA(){return`os-conn-${++EA}`}function SA(e){const t=(c,l)=>{try{c.contentWindow?.postMessage(l,Ha)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(c,l={})=>{const d=kA(),u=Array.isArray(l.topics)?[...l.topics]:[],f=new Map,p=[];let v=!1,b=!1;const w=()=>{const K=ko.get(c);return K||(e.getById(c)?.iframe??null)},g=()=>{if(w())return!1;const K=e.getById(c);return!!K&&K.config?.native===!0},_=[],N=()=>{const K=w();if(K)for(;p.length;){const j=p.shift();t(K,{type:"os-bridge-publish",connectionId:d,topic:j.topic,payload:j.payload})}},$={id:d,target:c,isOpen:()=>v,subscribe(K,j){const F=j;if(g()){const B=Jb(c,K,(P,h)=>{T(m.CONNECTION_MESSAGE,{connectionId:d,topic:h.channel,direction:"in"});try{F(P,{topic:h.channel})}catch(A){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",A)}});return _.push(B),B}let E=f.get(K);return E||(E=new Set,f.set(K,E)),E.add(F),()=>{E?.delete(F)}},send(K,j){if(b)return;if(T(m.CONNECTION_MESSAGE,{connectionId:d,topic:K,direction:"out"}),g()){ev(c,K,j);return}if(!v){p.push({topic:K,payload:j});return}const F=w();F&&t(F,{type:"os-bridge-publish",connectionId:d,topic:K,payload:j})},disconnect(){$._destroy("disconnect")},_targetWindow:w,_handleIframeMessage(K){if(!K||typeof K!="object")return;const j=K;if(j.type==="os-bridge-handshake-ack"){if(v)return;v=!0,T(m.CONNECTION_OPENED,{connectionId:d,targetWindowId:c,topics:u,connection:$});try{l.onOpen?.()}catch(F){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",F)}N();return}if(j.type==="os-bridge-publish"){const F=K,E=typeof F.topic=="string"?F.topic:"";if(!E)return;T(m.CONNECTION_MESSAGE,{connectionId:d,topic:E,direction:"in"});const B=f.get(E);if(B)for(const h of Array.from(B))try{h(F.payload,{topic:E})}catch(A){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",A)}const P=f.get("*");if(P)for(const h of Array.from(P))try{h(F.payload,{topic:E})}catch(A){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",A)}return}j.type==="os-bridge-disconnect"&&$._destroy("disconnect")},_destroy(K){if(b)return;b=!0;const j=v;v=!1,bn.delete(d);const F=vn.get(c);F&&(F.delete(d),F.size===0&&vn.delete(c));for(const E of _.splice(0))try{E()}catch{}if(j){const E=w();E&&t(E,{type:"os-bridge-disconnect",connectionId:d})}T(m.CONNECTION_CLOSED,{connectionId:d,reason:K});try{l.onClose?.(K)}catch(E){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",E)}}};bn.set(d,$);let C=vn.get(c);if(C||(C=new Set,vn.set(c,C)),C.add(d),g())return Promise.resolve().then(()=>{if(!(b||v)){v=!0,T(m.CONNECTION_OPENED,{connectionId:d,targetWindowId:c,topics:u});try{l.onOpen?.()}catch(K){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",K)}}}),$;const V=w();return V&&t(V,{type:"os-bridge-handshake",connectionId:d,targetWindowId:c,topics:u}),$},o=(c,l)=>{if(!c||typeof c!="object")return;const d=c;if(typeof d.type!="string"||!d.type.startsWith("os-bridge-"))return;if(d.type==="os-bridge-connection-request"&&typeof d.requestId=="string"&&typeof l=="string"&&l!==""){s(l,d.requestId,Array.isArray(d.topics)?d.topics:[]);return}if(typeof d.connectionId!="string")return;bn.get(d.connectionId)?._handleIframeMessage(c)},s=(c,l,d)=>{const f=ko.get(c)??e.getById(c)?.iframe??null;if(!f)return;const p=Z(m.IFRAME_CONNECTION_REQUEST,!0,{windowId:c,requestId:l,topics:d.slice()});if(p===!1){try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:l,accepted:!1,reason:"rejected"},Ha)}catch{}return}const v=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,b=n(c,{topics:v});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:l,accepted:!0,connectionId:b.id},Ha)}catch{}};return{connect:n,getConnection:c=>bn.get(c)??null,routeIncomingFromIframe:o,onIframeReady:c=>{const l=vn.get(c);if(l)for(const d of Array.from(l)){const u=bn.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:c=>{const l=vn.get(c);if(l)for(const d of Array.from(l))bn.get(d)?._destroy("window-closed")}}}const AA={};function IA(...e){(typeof{url:nr&&nr.tagName.toUpperCase()==="SCRIPT"&&nr.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&AA?"production":void 0)!=="production"&&console.log(...e)}const CA="iframe:";function Ga(e){return CA+e}function gh(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function LA(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const TA=250;class NA{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"&&(ii(Ga(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&&ii(Ga(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()},TA)}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){IA("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=Ga(t);ii(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=LA(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?Tl(s.iconSvg):"",a={slug:i,label:s.label,icon:gh(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,gh(s)):this.runProxy(t,s.name)};try{si(a)}catch(c){console.error("[openstation] iframe-bridge: dropping bad command",a,c)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Qe(t))return;const r=le(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 OA(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 wh="global",DA=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,RA=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,xA=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,MA=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,PA=/getSiteEditorPage\s*\(|site-editor\.php/,WA=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function $A(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 UA{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,c=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof c!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const l=document.createElement("div");l.setAttribute("aria-hidden","true"),l.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(l),this.host=l;const d={perLoader:{},statics:[],loadersList:[]},u=b=>{if(!Array.isArray(b)||b.length===0)return"";const w=new Array(b.length);for(let g=0;g<b.length;g++){const _=b[g];w[g]=_&&_.name?_.name:""}return w.join("|")},f=()=>{let b=[];for(const w of d.loadersList){const g=d.perLoader[w];Array.isArray(g)&&(b=b.concat(g))}Array.isArray(d.statics)&&(b=b.concat(d.statics)),this.callbackCache=Object.create(null);for(const w of b)w&&w.name&&typeof w.callback=="function"&&(this.callbackCache[w.name]=w.callback);this.publish(b)},p=b=>{const w=b.loader;let g=null;try{g=w.hook({search:""})}catch{}const _=g&&Array.isArray(g.commands)?g.commands:[],N=a(()=>u(_),[_]);return i(()=>{d.perLoader[w.name]=_,f()},[N]),i(()=>()=>{delete d.perLoader[w.name],f()},[]),null},v=()=>{const b=c(C=>{const V=C("core/commands");return!V||typeof V.getCommandLoaders!="function"?[]:[...V.getCommandLoaders(!1)||[],...V.getCommandLoaders(!0)||[]]},[]),w=c(C=>{const V=C("core/commands");return!V||typeof V.getCommands!="function"?[]:[...V.getCommands(!1)||[],...V.getCommands(!0)||[]]},[]),g=a(()=>Array.isArray(b)?b.map(C=>C&&C.name||""):[],[b]),_=g.join("|");i(()=>{d.loadersList=g,f()},[_]);const N=a(()=>u(Array.isArray(w)?w:[]),[w]);if(i(()=>{d.statics=Array.isArray(w)?w:[],f()},[N]),!Array.isArray(b)||b.length===0)return null;const $=[];for(const C of b)!C||typeof C.hook!="function"||$.push(s(p,{key:C.name,loader:C}));return s(n.Fragment||"div",null,$)};try{this.root=n.createRoot(l),this.root.render(s(v))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(t){const n=Object.create(null),o=[];for(const i of t)!i||!i.name||!i.label||i.disabled||n[i.name]||(n[i.name]=!0,o.push(this.classify(i)));let s="";for(const i of o)s+=`${i.name}|${i.kind}|${i.url||""}
61 `;if(s!==this.lastFingerprint){this.lastFingerprint=s,ii(wh);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),c={slug:r,label:i.label,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?Tl(i.iconSvg):void 0,owner:wh,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{si(c)}catch(l){console.error("[openstation] shell-harvester: dropping bad command",c,l)}}}}classify(t){const n={name:String(t.name),label:String(t.label),icon:typeof t.icon=="string"?t.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof t.callback=="function"?t.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=$A(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(DA)||i.match(RA)||i.match(xA);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(MA.test(i)){const c=PA.test(i)?n.name.match(WA):null;if(c){const l=c[1],d=c[2],u=`/${l}/${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(),Qe(t))return;const r=le(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runInvoke(t,n,o){return(s,i)=>{const r=this.callbackCache[t];if(typeof r!="function"){i.close();return}const a=this.runWithNavCapture(r);if(a){i.close();const c=le(a,this.adminUrl);this.manager.open({id:c,baseId:c,url:a,title:n,icon:o})}}}runWithNavCapture(t){let n=null;const o=c=>{n===null&&typeof c=="string"&&c!==""&&(n=c)},s=window.location,i=new Proxy(s,{get(c,l){const d=c[l];return l==="assign"||l==="replace"?u=>o(u):typeof d=="function"?d.bind(c):d},set(c,l,d){return l==="href"&&o(d),!0}}),r=[],a=c=>{try{Object.defineProperty(c,"location",{configurable:!0,get:()=>i,set:l=>o(l)}),r.push({obj:c,key:"location"})}catch{}};a(document),a(window);try{t({close:()=>{}})}catch{}finally{for(const c of r)try{delete c.obj[c.key]}catch{}}return n}}const yh="os-command-palette-ready";let So=null;function BA(){const t=window.openStationConfig?.commandPalette;return!t||!Array.isArray(t.scripts)?null:t}function FA(){const e=window.wp;try{return!!e?.data?.select?.("core/commands")}catch{return!1}}function HA(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 GA(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 zA(){const e=BA();if(!e||e.scripts.length===0)return FA();for(const s of e.styles??[])HA(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||!ta(s.url));for(const s of o)s.url&&GA(s.url);for(const s of o)if(s.url)await ue(s.url,{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!==""&&mf(i);return document.dispatchEvent(new CustomEvent(yh)),!0}function jA(){return So||(So=zA().catch(e=>{throw So=null,e}),So)}const En=[];function za(e){Ie("Widget",Tt(e,vh),e);const t=En.findIndex(n=>n.id===e.id);t>=0?En[t]=e:En.push(e)}function VA(e){const t=En.findIndex(n=>n.id===e);t>=0&&En.splice(t,1)}function bh(){const e=En.slice(),t=Z(m.WIDGETS,e);return Array.isArray(t)?t.filter(KA):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function Ao(e){return bh().find(t=>t.id===e)}const vh=[{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 KA(e){return Tt(e,vh).length===0}let Ke=null;function qA(e){if(Ke)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",k("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=k("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),Eh(o,e),document.body.appendChild(t),YA(t,e.anchor);const s=a=>{const c=a.target;c&&(t.contains(c)||e.anchor.contains(c)||ja())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&ja()};document.addEventListener("keydown",i),Ke={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function pi(){if(!Ke)return;const e=Ke.panel.querySelector(".os-widget-picker__list");e&&Eh(e,Ke.options)}function ja(){if(!Ke)return;document.removeEventListener("pointerdown",Ke.onOutsidePointerDown,!0),document.removeEventListener("keydown",Ke.onKeyDown),Ke.panel.remove();const{onClose:e}=Ke.options;Ke=null,e?.()}function Eh(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=k("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=de(k("%s (already added)"),s.label):a=de(k("Add %s"),s.label),i.setAttribute("aria-label",a);const c=document.createElement("span");c.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,c.setAttribute("aria-hidden","true"),i.appendChild(c);const l=document.createElement("span");l.className="os-widget-picker__entry-text";const d=document.createElement("span");if(d.className="os-widget-picker__entry-label",d.textContent=s.label,l.appendChild(d),s.description){const u=document.createElement("span");u.className="os-widget-picker__entry-description",u.textContent=s.description,l.appendChild(u)}if(i.appendChild(l),r){const u=document.createElement("span");u.className="os-widget-picker__entry-status",u.textContent=k("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function YA(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,c=n.top-i-r;a<8&&(a=8),c<8&&(c=n.bottom+r),e.style.left=`${Math.round(a)}px`,e.style.top=`${Math.round(c)}px`,e.style.visibility=""}const hi="os-widgets__card--floating",XA="os-widgets__card--movable",ZA="os-widgets__card--resizable",_h="os-widgets__card--dragging",kh="os-widgets__card--resizing",JA=160,Sh=80,QA=280,eI=180,_n=20,Ut=20,Ah=5,tI=Ah*Ah,nI='input, textarea, select, button, a, [contenteditable="true"]';function oI(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(XA),i&&o.classList.add(ZA),s?o.appendChild(sI(e,n.onRemove,n.onRedock)):o.appendChild(rI(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(mi(o,Lh(t.geometry,t.floatingParent)),o.classList.add(hi)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${uI(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(hi),c=[];if(i)for(const d of lI()){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),c.push(cI(o,u,d,e,t,n,a))}let l=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(l=aI(o,d,e,t,n))}return{card:o,body:r,dispose:()=>{for(const d of c)try{d()}catch{}if(l)try{l()}catch{}o.remove()}}}function sI(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(iI(e,n));const r=Ih(e,t);return o.appendChild(r),o}function iI(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",de(k("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 rI(e,t){const n=Ih(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function Ih(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",de(k("Remove %s"),e.label)),n.innerHTML=sn("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function aI(e,t,n,o,s){let i=null,r=0,a=0,c=0,l=0,d=!1;const u=b=>{if(b.button!==0)return;const w=b.target;w&&w.closest(nI)||(b.preventDefault(),i=b.pointerId,r=b.clientX,a=b.clientY,d=!1,c=parseFloat(e.style.left)||0,l=parseFloat(e.style.top)||0,t.setPointerCapture(i))},f=()=>{if(!e.classList.contains(hi)){const b=o.floatingParent.getBoundingClientRect(),w=e.getBoundingClientRect(),g={x:w.left-b.left,y:w.top-b.top,width:w.width||n.defaultWidth||QA,height:w.height||n.defaultHeight||eI};mi(e,g),e.classList.add(hi),s.onLiberate(g),c=parseFloat(e.style.left)||0,l=parseFloat(e.style.top)||0}e.classList.add(_h)},p=b=>{if(i===null||b.pointerId!==i)return;const w=b.clientX-r,g=b.clientY-a;if(!d){if(w*w+g*g<tI)return;d=!0,f()}const _=Nh(kn(c+w),kn(l+g),e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${Th(_.x)}px`,e.style.top=`${Th(_.y)}px`},v=b=>{if(!(i===null||b.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(_h),s.onGeometryChanged(Ch(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",v),t.addEventListener("pointercancel",v),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",v),t.removeEventListener("pointercancel",v)}}function cI(e,t,n,o,s,i,r){let a=null,c=0,l=0,d=0,u=0,f=0,p=0;const v=g=>{if(g.button!==0||!r()&&!dI(n))return;g.preventDefault(),g.stopPropagation(),a=g.pointerId,c=g.clientX,l=g.clientY;const _=e.getBoundingClientRect(),N=s.floatingParent.getBoundingClientRect();d=_.left-N.left,u=_.top-N.top,f=_.width,p=_.height,t.setPointerCapture(a),e.classList.add(kh)},b=g=>{if(a===null||g.pointerId!==a)return;const _=g.clientX-c,N=g.clientY-l,$=fI(n,_,N,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`},w=g=>{if(!(a===null||g.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(kh),r()?i.onGeometryChanged(Ch(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",v),t.addEventListener("pointermove",b),t.addEventListener("pointerup",w),t.addEventListener("pointercancel",w),()=>{t.removeEventListener("pointerdown",v),t.removeEventListener("pointermove",b),t.removeEventListener("pointerup",w),t.removeEventListener("pointercancel",w)}}function lI(){return["n","e","s","w","ne","nw","se","sw"]}function dI(e){return e==="s"}function mi(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 Ch(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function uI(e,t){return Sn(e,t.minHeight??Sh,t.maxHeight??1/0)}function Lh(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Nh(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function kn(e){return Math.round(e/Ut)*Ut}function Th(e){const t=Math.floor(e/Ut)*Ut;return t>=_n?t:Math.min(e,_n)}function Nh(e,t,n,o,s){const i=Ce(s),r=i.x+_n,a=i.y+_n,c=Math.max(i.x,i.x+i.width-n-_n),l=Math.max(i.y,i.y+i.height-o-_n);return{x:Math.min(Math.max(r,e),c),y:Math.min(Math.max(a,t),l)}}function fI(e,t,n,o,s,i,r,a,c,l){const d=a.minWidth??JA,u=a.minHeight??Sh,f=a.maxWidth??1/0,p=a.maxHeight??1/0,v=Ce(c),b=v.x+v.width,w=v.y+v.height;let g=o,_=s,N=i,$=r;if((e==="e"||e==="ne"||e==="se")&&(l?N=gi(kn(o+i+t),o+d,Math.min(o+f,b))-o:N=Sn(i+t,d,Math.min(f,b-o))),e==="w"||e==="nw"||e==="sw"){const C=o+i;if(l)g=gi(kn(o+t),Math.max(0,C-Math.min(f,C)),C-d),N=C-g;else{const V=Sn(i-t,d,Math.min(f,C));g=o+(i-V),N=V}}if((e==="s"||e==="se"||e==="sw")&&(l?$=gi(kn(s+r+n),s+u,Math.min(s+p,w))-s:$=Sn(r+n,u,Math.min(p,w-s))),e==="n"||e==="ne"||e==="nw"){const C=s+r;if(l)_=gi(kn(s+n),Math.max(0,C-Math.min(p,C)),C-u),$=C-_;else{const V=Sn(r-n,u,Math.min(p,C));_=s+(r-V),$=V}}return l||(N=i,g=o),{x:g,y:_,width:N,height:$}}function gi(e,t,n){const o=Sn(e,t,n),s=Math.floor(o/Ut)*Ut;if(s>=t)return s;const i=s+Ut;return i<=n?i:o}function Sn(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const Oh="desktop-mode-widgets",Dh="desktop-mode-widgets-geometry",Rh="desktop-mode-widgets-docked-heights";function xh(){try{return window.localStorage.getItem(Oh)}catch{return null}}function pI(){const e=xh();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Va(e){try{window.localStorage.setItem(Oh,JSON.stringify(e))}catch{}}function hI(){try{const e=window.localStorage.getItem(Dh);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=gI(s);i&&(n[o]=i)}return n}catch{return{}}}function Ka(e){try{window.localStorage.setItem(Dh,JSON.stringify(e))}catch{}}function mI(){try{const e=window.localStorage.getItem(Rh);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 Mh(e){try{window.localStorage.setItem(Rh,JSON.stringify(e))}catch{}}function gI(e){if(!e||typeof e!="object")return null;const{x:t,y:n,width:o,height:s}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)||typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||s<=0?null:{x:t,y:n,width:o,height:s}}function wI(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 yI=["clock"],wi=40,bI=12;class vI{constructor(t,n,o){this.mounted=new Map,this.generation=0,this.unwatchPointer=null,this.root=t,this.pluginUrl=n,this.enabledIds=pI(),this.geometry=hI(),this.dockedHeights=mI(),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()}hydrate(){xh()===null&&(this.enabledIds=yI.filter(t=>!!Ao(t)),Va(this.enabledIds));for(const t of this.enabledIds)this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){this.enabledIds.includes(t)||Ao(t)&&(this.enabledIds.push(t),Va(this.enabledIds),this.mountById(t),this.paintEmptyState(),T(m.WIDGET_ADDED,{id:t}))}remove(t){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(Va(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],Ka(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],Mh(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),T(m.WIDGET_REMOVED,{id:t}),pi())}getEnabledIds(){return[...this.enabledIds]}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),qA({anchor:this.addTile,registry:()=>bh(),enabledIds:()=>[...this.enabledIds],onAdd:t=>{this.add(t),ja(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){Ao(t)&&this.enabledIds.includes(t)&&(this.mounted.has(t)||(this.mountById(t),this.paintEmptyState()))}unmount(t){this.mounted.has(t)&&(this.unmountById(t),this.paintEmptyState())}ensureMounted(t){return Ao(t)?(this.enabledIds.includes(t)||this.add(t),!0):!1}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t);this.unwatchPointer?.(),this.unwatchPointer=null}mountById(t){const n=Ao(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=oI(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 c={id:t,pluginUrl:this.pluginUrl,storage:wI(t)};T(m.WIDGET_MOUNTING,{id:t,container:i.body,ctx:c});const l=u=>{const f=this.mounted.get(t);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,this.positionAddTile(),T(m.WIDGET_MOUNTED,{id:t,container:i.body,ctx:c})};let d;try{d=n.mount(i.body,c)}catch(u){this.handleMountFailure(t,u);return}if(EI(d)){const u=xf(i.body,{label:k("Loadingโ€ฆ")});d.then(f=>{u.done(),l(f)},f=>{u.done(),this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,f)});return}l(d)}unmountById(t){const n=this.mounted.get(t);if(n){T(m.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){T(m.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)),T(m.WIDGET_MOUNT_FAILED,{id:t,error:n}),T(m.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",k("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=k("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=l=>{t||(t=this.root.getBoundingClientRect());const d=l.clientX>=t.left-wi&&l.clientX<=t.right+wi&&l.clientY>=t.top-wi&&l.clientY<=t.bottom+wi;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 c=Br(()=>this.reclampFloating());this.unwatchPointer=()=>{n&&(cancelAnimationFrame(n),n=0),c(),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),mi(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],Ka(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=Lh(o,this.floatingHost);s.x===o.x&&s.y===o.y||(mi(n.frame.card,s),this.persistGeometry(t,s))}}persistGeometry(t,n){this.geometry[t]=n,Ka(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+bI,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,Mh(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 EI(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const _I=280,kI=220,SI=520,AI=400;function II(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function CI(e,t,n){return o=>{const s=II(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=_A(s,i);t.push(r);let a;try{a=new URL(e.url,window.location.origin).origin}catch{a=window.location.origin}let c=null;const l=new Promise(f=>{c=f}),d=()=>{if(e.bridge)try{const f=i.contentDocument;if(f&&!f.querySelector("script[data-os-iframe-bridge]")){const p=window.openStationConfig?.iframeBridgeUrl;if(p){const v=f.createElement("script");v.src=p,v.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(v)}}}catch{}nv(s),c?.()};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!==""&&Qb(s,p.channel,p.payload);try{e.onMessage?.(f.data)}catch(v){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",v)}};return window.addEventListener("message",u),t.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),l}}function LI(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=CI(t.iframeContent,s,t.id));const i=t.onClose,r=t.iframeContent?()=>{for(const c of s)try{c()}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??SI,height:t.height??AI,minWidth:t.minWidth??_I,minHeight:t.minHeight??kI,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let TI=0;function NI(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++TI}`,s=n.persistent===!0,i=[["opened",m.WINDOW_OPENED],["reopened",m.WINDOW_REOPENED],["focused",m.WINDOW_FOCUSED],["blurred",m.WINDOW_BLURRED],["closing",m.WINDOW_CLOSING],["closed",m.WINDOW_CLOSED],["minimized",m.WINDOW_MINIMIZED],["restored",m.WINDOW_RESTORED],["maximized",m.WINDOW_MAXIMIZED],["unmaximized",m.WINDOW_UNMAXIMIZED],["fullscreenEntered",m.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",m.WINDOW_FULLSCREEN_EXITED],["resized",m.WINDOW_RESIZED],["bodyResized",m.WINDOW_BODY_RESIZED],["boundsChanged",m.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const c=()=>{if(!a){a=!0;for(const l of r)Fn(l,o)}};for(const[l,d]of i){const u=t[l];u&&(r.push(d),ne(d,o,f=>{const p=f;if(p.windowId!==e)return;const{windowId:v,...b}=p;u(b),l==="closed"&&!s&&c()}))}return c}function OI(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function DI(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&Qv(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function Ph(e,t){const n=t??{};return e.map(o=>{const s=o.scriptHandle?n[o.scriptHandle]:void 0,i=[];for(const a of o.companionScripts??[]){if(typeof a!="string"){i.push(a);continue}const c=n[a];c?.url&&i.push({scriptUrl:c.url,scriptHandle:a,scriptBefore:c.before,scriptAfter:c.after,scriptL10n:c.l10n,scriptTranslations:c.translations})}const r=(o.tabs??[]).map(a=>{if(typeof a.scriptUrl=="string")return a;const c=a.scriptHandle?n[a.scriptHandle]:void 0;return{...a,scriptUrl:c?.url??"",scriptBefore:c?.before,scriptAfter:c?.after,scriptL10n:c?.l10n,scriptTranslations:c?.translations}});return{...o,scriptUrl:o.scriptUrl??s?.url??"",scriptBefore:o.scriptBefore??s?.before,scriptAfter:o.scriptAfter??s?.after,scriptL10n:o.scriptL10n??s?.l10n,scriptTranslations:o.scriptTranslations??s?.translations,companionScripts:i,tabs:r}})}function RI(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,a=new Map,c=new Set,l=new Map,d=h=>{const A=Hr(h.id);return A?{width:Math.max(A.width,h.minWidth),height:Math.max(A.height,h.minHeight)}:{width:h.width,height:h.height}},u=h=>{if(i.has(h.templateId))return;if(document.getElementById(h.templateId)){i.add(h.templateId);return}if(!h.templateHtml)return;const A=document.createElement("template");A.id=h.templateId,A.innerHTML=h.templateHtml,document.body.appendChild(A),i.add(h.templateId)},f=h=>{const A=h.styleUrl;if(!A||c.has(A))return;const O=A.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${O}"]`)){const Y=document.createElement("link");Y.rel="stylesheet",Y.href=A,h.styleHandle&&(Y.dataset.osStyleHandle=h.styleHandle),document.head.appendChild(Y)}if(Array.isArray(h.styleInline))for(const Y of h.styleInline){if(typeof Y!="string"||Y==="")continue;const I=document.createElement("style");h.styleHandle&&(I.dataset.osStyleHandle=h.styleHandle),I.textContent=Y,document.head.appendChild(I)}c.add(A)},p=h=>{f(h)},v=h=>{for(const A of h.companionStyles??[])f(A)},b=new Set,w=(h,A)=>{if(b.has(h))return;b.add(h);const O=[A.scriptTranslations??"",...A.scriptL10n??[],...A.scriptBefore??[],...A.scriptAfter??[]];for(const G of O)typeof G=="string"&&G!==""&&mf(G)},g=(h,A)=>{const O=A.scriptUrl,G=`${h}|${O}`;if(r.has(O))return w(G,A),Promise.resolve();const Y=a.get(O);if(Y)return Y.then(()=>w(G,A));b.add(G);const I=ue(O,{translations:A.scriptTranslations,l10n:A.scriptL10n,before:A.scriptBefore,after:A.scriptAfter}).catch(S=>{T(m.SHELL_ERROR,{scope:"native-window-script-load",id:h,error:S})}).then(()=>{r.add(O),a.delete(O)});return a.set(O,I),I},_=async h=>{v(h);for(const A of h.companionScripts??[])A.scriptUrl&&await g(h.id,A);h.scriptUrl&&await g(h.id,h)},N=async h=>{h.preloadScript&&await _(h)},$=h=>async(A,O)=>{A.appendChild(Wh(h.templateId)),DI(A,h),await _(h);const G=OI()[h.id];return G?.(A,O)},C=(h,A)=>{const O=$(h),G=d(h);t.open({id:h.id,baseId:h.id,native:!0,url:`#${h.id}`,title:h.title,icon:h.icon,width:G.width,height:G.height,minWidth:h.minWidth,minHeight:h.minHeight,render:O,autofocus:h.autofocus,ownerHandle:h.ownerHandle||h.scriptHandle,...A?{params:A}:{}})},V=(h,A)=>{const O=$(h),G=d(h);t.openNew({id:h.id,baseId:h.id,native:!0,url:`#${h.id}`,title:h.title,icon:h.icon,width:G.width,height:G.height,minWidth:h.minWidth,minHeight:h.minHeight,initialState:"normal",render:O,autofocus:h.autofocus,ownerHandle:h.ownerHandle||h.scriptHandle,...A?{params:A}:{}})},K=async h=>{if(!s.has(h.id)){if(h.placement==="none"){u(h),p(h),await N(h),s.add(h.id);return}u(h),p(h),await N(h),n({id:h.id,title:h.title,icon:h.icon,windowId:h.id,navKind:h.navKind==="control"?"control":"app",defaultPlacement:"rail",order:h.dockOrder,placeable:h.placeable===!0,isOpen:()=>!!t.getById(h.id),onOpen:()=>C(h)}),T(m.DOCK_ITEM_APPENDED,{id:h.id}),s.add(h.id)}},j=h=>{s.has(h)&&(o(h),s.delete(h),l.delete(h))},F=async h=>{const A=new Set;for(const O of h)A.add(O.id),l.set(O.id,O);for(const O of Array.from(s))A.has(O)||j(O);for(const O of h)s.has(O.id)||await K(O)},E=(h,A={})=>{const O=l.get(h);return O?(Ee.publish("os/open-requested",{windowId:h,source:A.source??"api"}),C(O,A.params),!0):!1},B=(h,A={})=>{const O=l.get(h);return O?(Ee.publish("os/open-requested",{windowId:h,source:A.source??"api"}),V(O,A.params),!0):!1};return ne(m.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",h=>{const A=h,O=A?.windowId,G=A?.width,Y=A?.height;if(!O||typeof G!="number"||typeof Y!="number")return;const I=t.getById(O);if(!I||I.state!=="normal")return;const S=I.config.baseId||I.id;Lu(S,{width:G,height:Y}),I.element&&Tu(S,{x:I.element.offsetLeft,y:I.element.offsetTop})}),ne(m.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",h=>{const A=h?.windowId;if(!A)return;const O=t.getById(A);if(!O||O.state!=="normal"||!O.element)return;const G=O.config.baseId||O.id;Lu(G,{width:O.element.offsetWidth,height:O.element.offsetHeight}),Tu(G,{x:O.element.offsetLeft,y:O.element.offsetTop})}),ne(m.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",h=>{const A=h?.windowId;if(!A)return;const O=t.getById(A);if(!O)return;const G=O.config.baseId||O.id,Y=l.get(G),I=Y?{width:Y.width,height:Y.height}:{width:O.config.width,height:O.config.height};Nu(G,"maximized",I)}),ne(m.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",h=>{const A=h?.windowId;if(!A)return;const O=t.getById(A);if(!O)return;const G=O.config.baseId||O.id;Nu(G,null)}),{sync:F,openById:E,openNewById:B,loadScriptById:async h=>{const A=l.get(h);return A?(await _(A),!0):!1}}}function Wh(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 $h(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=le(e,o);return s.find(r=>le(r.url,o)===i||(r.submenu??[]).some(a=>le(a.url,o)===i))??null}const Uh="data:image/svg+xml;base64,",yi=new Map;function xI(e){const t=yi.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(Uh.length)).includes("currentColor")}catch{}return yi.size>=256&&yi.clear(),yi.set(e,n),n}function Io(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const c=ks(t.slot);c!==null&&(e=c),s=Sr(t.slot)}if(typeof e=="string"&&e.startsWith("dashicons-")){const c=document.createElement("span");return c.className=`dashicons ${e} ${n}`.trim(),c.setAttribute("aria-hidden","true"),s!==null&&(c.style.color=s),c}if(s!==null&&typeof e=="string"){const c=document.createElement("span");if(c.className=n,c.setAttribute("aria-hidden","true"),c.style.display="inline-block",zs(c,e,s))return c}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const c=e.slice(Uh.length);if(/^[A-Za-z0-9+/=]+$/.test(c)){const l=document.createElement("span");return l.className=n,l.setAttribute("aria-hidden","true"),l.style.display="inline-block",xI(e)&&zs(l,e,"currentColor")||(l.style.backgroundImage=`url("${e}")`,l.style.backgroundRepeat="no-repeat",l.style.backgroundPosition="center",l.style.backgroundSize="contain"),l}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const c=e.indexOf(","),l=c>=0?e.slice(c+1):"";if(/^[A-Za-z0-9+/=]+$/.test(l))return Bh(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return Bh(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=MI(o);i.textContent=r;const a=ea(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 Bh(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 MI(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 Fh="os-icon__badge",Co=new Map,Lo=new Map;function PI(e){return Math.max(0,Math.floor(Number(e)||0))}function Hh(e,t){if(!e)return;const n=Vh(e);if(!n)return;const o=PI(t),s=Co.get(e)??0;o!==s&&(o===0?Co.delete(e):Co.set(e,o),Kh(n,o),Ee.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),T(m.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function WI(e){Hh(e,0)}function $I(e){return Co.get(e)??0}function UI(e,t){if(e){if(!t){Lo.delete(e);return}Lo.get(e)!==t&&(Lo.set(e,t),FI(e,t),Ee.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function Gh(e){return Lo.get(e)??""}function BI(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function FI(e,t){const o=Vh(e)?.querySelector(".os-icon__image");if(o){const s=Io(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${BI(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const HI={setBadge:Hh,clearBadge:WI,getBadge:$I,setArt:UI,getArt:Gh};function GI(e){return!e||e.length===0?"":`${kr()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let zh="";function jh(e,t,n){const o=GI(t);if(o===zh&&e.querySelector(":scope > .os-icons"))return;zh=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",k("Desktop icons"));const r=[...t].sort((c,l)=>{const d=c.pinned?0:1,u=l.pinned?0:1;return d-u}),a=new Map;for(const c of r){const l=jI(c,n),d=Co.get(c.id)??0;d>0&&Kh(l,d);const u=Lo.get(c.id);if(u){const f=l.querySelector(".os-icon__image");f&&f.replaceWith(Io(u,{className:"os-icon__image",title:""}))}i.appendChild(l),a.set(c.id,l)}e.appendChild(i),T(m.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(c=>c.id),container:i,tiles:a})}function Vh(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${zI(e)}"]`):null}function Kh(e,t){const n=e.querySelector(`:scope > .${Fh}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=de(Gn("%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=Fh,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function zI(e){const t=window.CSS;return t?.escape?t.escape(e):e}function jI(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=Io(e.icon,{title:e.title,className:"os-icon__image",slot:Ss(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(),T(m.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),VI(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),yf({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function VI(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(js(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=$h(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 KI(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(c=>c.windowId).filter(c=>!!c);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 qh="os-side-dock";function qI(e,t,n,o,s="bottom"){let i=t,r=s,a=n,c=o??[],l=null,d=null,u=null,f=null,p=null;const v=new Map;let b=[],w=Ef({items:[],config:{placement:{},order:[]},layout:i,openWindows:[]});const g=()=>e.getSettings?.()??{navPlacement:{},navOrder:[]},_=()=>{const L=e.windowManager.getActiveDesktopId(),z=[],R=new Set;for(const ae of e.windowManager.getAll()){if((ae.config.desktopId||L)!==L)continue;const X=ae.config.baseId||ae.id;R.has(X)||(R.add(X),z.push({id:X,title:ae.config.title||X,icon:ae.config.icon||"dashicons-admin-generic",fromAdminUrl:ae.config.native!==!0}))}return z},N=L=>L.windowId?L.windowId:Ps(L.url)??le(L.url,e.adminUrl),$=()=>{const L=[];for(const R of v.values())L.push({item:R,kind:R.navKind==="control"?"control":"app",locked:R.locked});b=KI({menuItems:a,systemTiles:L,icons:c,resolveMenuWindowId:N});const z=g();w=Ef({items:b,config:{placement:z.navPlacement,order:z.navOrder},layout:i,openWindows:_()})},C=L=>L.tile?{type:"system",item:L.tile}:L.menu?{type:"menu",item:L.windowId?{...L.menu,windowId:L.windowId}:L.menu}:{type:"menu",item:{id:L.id,title:L.title,icon:L.icon,url:L.entry?.url||"",windowId:L.windowId,badge:0,submenu:[],isCore:!1}},V=L=>!!L.entry||!!L.windowId||!!L.menu?.url,K=(L,z)=>L.entry?L.entry:{id:L.id,title:L.title,icon:L.icon,window:L.windowId??"",url:L.menu?.url||"",position:2e3+z},j=L=>({core:(L.core??[]).map(C),apps:(L.apps??[]).map(C),controls:(L.controls??[]).map(C)}),F=(L,z,R)=>{if(!L)return;if(L.setZones){L.setZones(z),R.clear();for(const oe of et)for(const ce of z[oe])ce.type==="system"&&R.add(ce.item.id);return}const ae=[],X=new Set;for(const oe of et)for(const ce of z[oe])ce.type==="menu"?ae.push(ce.item):X.add(ce.item.id);L.replaceItems(ae);for(const oe of Array.from(R))X.has(oe)||(L.removeSystemItem(oe),R.delete(oe));for(const oe of et)for(const ce of z[oe])ce.type==="system"&&!R.has(ce.item.id)&&(L.appendSystemItem(ce.item),R.add(ce.item.id))},E=new Set,B=new Set,P=()=>{$(),F(l,j(w.dock),E),F(d,{core:w.sidebar.map(C),apps:[],controls:[]},B),e.renderIcons(w.desktop.filter(V).map(K))},h=()=>Array.from(w.ephemeral).sort().join(","),A=()=>{const L=document.getElementById(qh);if(L)return L;const z=document.createElement("nav");return z.id=qh,z.className="os-dock",z.setAttribute("role","toolbar"),z.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(z,e.shellBody.firstChild),z},O=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},G=()=>{if(l){try{l.destroy()}catch(L){T(m.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:L})}l=null,u=null}if(d){try{d.destroy()}catch(L){T(m.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:L})}d=null,f=null}E.clear(),B.clear()},Y=L=>{const z=lr();if(!z)return T(m.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return z.mount(L)}catch(R){if(T(m.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:z.id,error:R}),z===sa)return null;try{return sa.mount(L)}catch{return null}}},I=(L,z)=>({container:L,items:[],fullMenu:a.slice(),fullSystemTiles:b.filter(R=>!!R.tile).filter(R=>S(R.id)).map(R=>R.tile),orientation:z,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:R=>{const ae=le(R.url,e.adminUrl);e.windowManager.open({id:ae,baseId:ae,url:R.url,parentUrl:R.url,title:R.title,icon:R.icon.startsWith("dashicons-")?R.icon:"dashicons-admin-generic",submenu:R.submenu,selfLabel:R.selfLabel,multi:!!R.multi})},openSubmenuPick:(R,ae)=>{js(ae.url)||e.windowManager.open({id:le(ae.url,e.adminUrl),baseId:le(R.url,e.adminUrl),url:ae.url,parentUrl:R.url,title:R.title,icon:R.icon.startsWith("dashicons-")?R.icon:"dashicons-admin-generic",submenu:R.submenu,selfLabel:R.selfLabel,multi:!!R.multi})},openSystemItem:R=>R.onOpen()}),S=L=>{for(const z of et)if(w.dock[z].some(R=>R.id===L))return!0;return w.sidebar.some(z=>z.id===L)},M=()=>i==="classic"?"bottom":r,D=()=>{G(),$(),i==="classic"?(p=A(),d=Y(I(p,"left")),f=Af(d)):O(),l=Y(I(e.bottomDockEl,M())),u=Af(l),P()},U=()=>{document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:M(),primary:u,side:f}}))},H={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:L=>{L!==i&&(i=L,e.shellRoot.setAttribute("data-os-layout",L),D(),U())},getDockPlacement:()=>r,setDockPlacement:L=>{if(L===r)return;const z=M();r=L,M()!==z&&(D(),U())},applyDockItems:L=>{a=L,P()},applyDesktopIcons:L=>{c=L??[],P()},appendSystemTile:L=>{v.set(L.id,L),P()},removeSystemTile:L=>{v.delete(L)&&P()},listSystemTiles:()=>Array.from(v.values()).map(L=>({id:L.id,title:L.title,icon:L.icon,navKind:L.navKind==="control"?"control":"app",placeable:L.placeable===!0,locked:L.locked===!0})),getSystemTile:L=>v.get(L)??null,getMenuItems:()=>a.slice(),getNavItems:()=>b.slice(),getNav:()=>w,refresh:P,destroy:()=>{G(),O()}};for(const L of["os-window-opened","os-window-closed"])document.addEventListener(L,()=>{const z=h();$(),h()!==z&&P()});e.shellRoot.setAttribute("data-os-layout",i),D();let W=lr()?.id??null;return sb(()=>{const L=lr()?.id??null;L!==W&&(W=L,D(),U())}),H}const Yh="os-ai-loading",Xh="os-ai-loading-keyframes";let An=null,To=null;function YI(){if(document.getElementById(Xh))return;const e=document.createElement("style");e.id=Xh,e.textContent="@keyframes os-ai-loading-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function XI(e){if(An&&An.isConnected)return;To=r=>{r.key==="Escape"&&(bi(),e?.())},document.addEventListener("keydown",To);const t=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=document.createElement("div");n.id=Yh,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||(YI(),s.style.animation="os-ai-loading-spin 0.7s linear infinite");const i=document.createElement("span");i.textContent=k("Starting the command paletteโ€ฆ"),o.appendChild(s),o.appendChild(i),n.appendChild(o),document.body.appendChild(n),An=n}function bi(){To&&(document.removeEventListener("keydown",To),To=null),An&&(An.remove(),An=null),document.getElementById(Yh)?.remove()}function ZI(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 JI{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 jA().catch(t=>{console.warn("[openstation] command-palette runtime failed to load",t)}),this._loadPromise?this._loadPromise:(io("desktop-mode-ai-assistant"),this._loadPromise=ZI(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||XI(()=>this.close()),this._ensure().then(t=>{bi(),this._intendOpen&&t.open()}).catch(t=>{bi(),console.warn("[openstation] command palette failed to load",t)})}close(){this._intendOpen=!1,bi(),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 Zh=e=>!e||typeof e!="object"?!1:e.name==="AbortError",QI=e=>{if(!e)return[];const t=i0();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}}):[]},eC=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 tC(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 nC(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function oC(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",c=r.restNonce??"";if(!a||!c)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Be(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":c},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(l){throw Zh(l)?l:new Error(`[openstation] wp.os.ai.ask: network error โ€” ${String(l?.message??l)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",c=r0(r);if(!c)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const l=i.commandContext??e.fallbackContext();let d;try{d=await Promise.resolve(c.run(a,l))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:d}},o=async(s,i,r,a,c,l)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:nC(a)}};c&&(d.system_prompt_text=c.text,d.system_prompt_mode=c.mode);let u;try{u=await t(d,l)}catch(v){if(Zh(v))throw v;return null}if(!u.ok)return null;const f=await u.json().catch(()=>({}));return(typeof f.message=="string"?f.message.trim():"")!==""?f.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[openstation] wp.os.ai.ask: empty query passed with non-default options โ€” likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const c=QI(r.tools),l=eC(r.systemPrompt),d={query:a};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),c.length>0&&(d.command_tools=c),l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);const u=await t(d,r.signal);if(!u.ok){const _=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[openstation] wp.os.ai.ask: HTTP ${u.status} โ€” ${_.message??u.statusText}`)}const f=await u.json();if(f.answer_type!=="tool_call"||!f.tool)return{answer_type:f.answer_type,message:f.message??"",entity:f.entity??null,admin_links:f.admin_links??null,request_id:f.request_id,continue:f.continue??null};const p=await n(f,r);if(!p.ok)return p.response;const{slug:v,args:b,result:w}=p;let g=tC(f.message,w);if(r.followUp===!0){const _=await o(a,v,b,w,l,r.signal);_!==null&&(g=_)}return{answer_type:"tool_call",message:g,entity:null,admin_links:null,toolCall:{slug:v,args:b,result:w},request_id:f.request_id}}}const Jh="[os-bin badge]";function nt(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(Jh,...e)}catch{}}function vi(...e){console.warn(Jh,...e)}const No="desktop-mode-recycle-bin",sC="openstation_recycle_bin_seen_ts";function iC(){return window.wp?.os}const pe=ie("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function Oo(e){const t=Math.max(0,Math.floor(e)),n=pe.state.current;pe.state.current=t,nt("setRecycleBinCount",{prev:n,next:t}),qa(t)}function Qh(e){Oo(pe.state.current+e)}function rC(){return pe.state.current}function qa(e){const t=e>0?pe.state.fullArt:pe.state.emptyArt;if(nt("paintIconState",{count:e,full:e>0,hasArt:!!t}),!t)return;const n=iC();n?.dock?.setArt?.(No,t),n?.taskbar?.setArt?.(No,t),n?.icons?.setArt?.(No,t)}function aC(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;pe.state.emptyArt=String(o?.recycleBinIconEmpty??""),pe.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;nt("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:pe.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)||vi("openStationConfig.recycleBinCount is missing โ€” PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),pe.state.started){Oo(n);return}pe.state.started=!0,pe.state.countUrl=t,pe.state.seenTs=Date.now(),Oo(n),cC(),lC(),dC(),uC(),fC()}function cC(){ne(m.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===No&&qa(pe.state.current)})}function lC(){ne(m.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(No)&&qa(pe.state.current)})}function dC(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":Qh(+r);break;case"untrashed":case"deleted":Qh(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])yn(`os.${s}.changed`,e)}function uC(){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<=pe.state.seenTs){nt("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:pe.state.seenTs});return}nt("postMessage triggers refetch",{ts:o,prevSeenTs:pe.state.seenTs}),pe.state.seenTs=o,pC()})}function fC(){const e=window.jQuery;if(!e){vi("wireHeartbeatProbe: window.jQuery not available โ€” heartbeat path disabled");return}nt("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[sC]=pe.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;nt("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>pe.state.seenTs&&(pe.state.seenTs=o.ts),typeof o.count=="number"&&Oo(o.count))})}async function pC(){if(!pe.state.countUrl){nt("refetchCount: no countUrl, skip");return}nt("refetchCount: hitting",pe.state.countUrl);try{const e=await fetch(pe.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){vi("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();nt("refetchCount: response",t),typeof t.count=="number"&&Oo(t.count)}catch(e){vi("refetchCount: fetch failed",e)}}const hC="desktop-mode-os-settings",mC="desktop-mode-recycle-bin";function gC(e){const t=bC();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===hC?wC():i===mC?yC(s,e.getRecycleBinCount):n})}function wC(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=k("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 yC(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 c=0;c<3;c++){const l=document.createElement("span");l.className="os-dock-peek__bin-slip",i.appendChild(l)}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=k("Trash โ€” empty"):o===1?a.textContent=k("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function bC(){return window.wp?.hooks??null}const Do="desktop-mode-bug-report",vC="WordPress",EC="openstation",em=6e3;function _C(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=k("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(kC()),t.appendChild(SC("title",k("Title"),{placeholder:k("A short summary"),required:!0})),t.appendChild(tm("description",k("What happened? What did you expect?"),{placeholder:k("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(tm("steps",k("Steps to reproduce (bug only)"),{placeholder:k("One step per line"),rows:4}));const o=AC();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=k("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=k("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const c=CC(t);if(!c.title.trim()||!c.description.trim()){IC(t,k("Title and description are both required."));return}const l=LC(c);window.open(l,"_blank","noopener")}),e.appendChild(t)}function kC(){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=k("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:k("Bug"),checked:!0},{value:"feature",label:k("Feature request")},{value:"question",label:k("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 SC(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 tm(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 AC(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=k("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=om(nm()),e.appendChild(n),e}function IC(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 CC(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 LC(e){const t=TC(e.type),n=NC(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/${vC}/${EC}/issues/new?${o.toString()}`}function TC(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function NC(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(om(nm())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(`
62 `);return n.length>em&&(n=n.slice(0,em)+`
63
64 โ€ฆ(truncated to fit GitHub URL length limit)`),n}function nm(){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 om(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(`
65 `)}let Ro=null,sm=!1,im=!1,rm=!1,Bt="pending";function OC(){if(im)return;im=!0;const e=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{e&&(rm||RC()||(xC(),rm=!0,setTimeout(()=>window.location.reload(),0)))})}const am="os-sw-reload-ts",DC=3e4;function RC(){try{const e=sessionStorage.getItem(am),t=e?Number.parseInt(e,10):0;return!Number.isFinite(t)||t<=0?!1:Date.now()-t<DC}catch{return!1}}function xC(){try{sessionStorage.setItem(am,String(Date.now()))}catch{}}const MC=["/desktop-mode/sw.js"];function PC(e,t){if(e===t.swUrl||e===t.swFallbackUrl)return!0;try{const n=new URL(e).pathname;return MC.some(o=>n.endsWith(o))}catch{return!1}}function cm(){const e=window.openStationConfig?.pwa?.swConfig;UC({adminAssetCache:e?.adminAssetCache===!0,windowPrewarm:e?.windowPrewarm===!0})}async function WC(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return Bt="unsupported",null;if(Ro||sm)return Ro;if(!t.forceReplace){const s=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(i=>{const r=i.active?.scriptURL??i.installing?.scriptURL??"";return r!==""&&!PC(r,e)});if(s)return Bt="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:"/",updateViaCache:"none"});try{try{Ro=await n(e.swUrl)}catch(o){if(!e.swFallbackUrl||e.swFallbackUrl===e.swUrl)throw o;Ro=await n(e.swFallbackUrl)}return Bt="registered",OC(),cm(),navigator.serviceWorker.addEventListener("controllerchange",cm),Ro}catch(o){return sm=!0,Bt="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",o),null}}function $C(e){try{navigator.serviceWorker?.controller?.postMessage({type:"os-sw-set-prewarm",enabled:e})}catch{}}function UC(e){try{navigator.serviceWorker?.controller?.postMessage({type:"os-sw-config",...e})}catch{}}function BC(){return Bt}const FC="os-pwa-install";function lm(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function dm(){if(lm())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 Et=null;function HC(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(),Et=s}function o(){Et=null,t({message:de(k("Installed %s as an app."),e)})}}function GC(e,t){return{id:FC,title:k("Install web app"),icon:"dashicons-download",onOpen:()=>{zC(e,t)}}}async function zC(e,t){if(Et){const n=Et;Et=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:k("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await dm()){t({message:de(k("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(BC()==="foreign-sw"){t({message:k("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:k("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 jC(){if(!Et)return"unavailable";const e=Et;Et=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function VC(){Promise.resolve().then(()=>XS).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function KC(e,t){e.pwa&&(rp(e.pwa),HC(e.pwa.appName||"WordPress",t),WC(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw}))}const In={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function qC(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function YC(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function XC(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function ZC(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 JC{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(qC(n)){this._startDrag(n.payload);return}if(YC(n)){this._endDrag();return}if(XC(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=ZC(t);this._payload=n,document.dispatchEvent(new CustomEvent(In.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(In.END,{detail:{payload:t}}))}}class QC{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 eL="os-drag-ghost",um="os-drag-ghost--accept",fm="os-drag-ghost--reject",tL="os-drag-hint",pm="os-drag-hint--accept",hm="os-drag-hint--reject",mm="os-drag-hint--neutral",nL=16,oL=18;function sL(e,t,n){const o=dL(e),s=e.ghost?.offsetX??uL(e.source),i=e.ghost?.offsetY??fL(e.source);o.classList.add(eL),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=rL(e),a=r?iL():null;a&&document.body.appendChild(a);const c={get element(){return o},moveTo(l,d){o.style.transform=`translate3d(${l-s}px, ${d-i}px, 0)`,a&&(a.style.transform=`translate3d(${l+nL}px, ${d+oL}px, 0)`)},setMode(l,d){o.classList.remove(um,fm),l==="accept"?o.classList.add(um):l==="reject"&&o.classList.add(fm),a&&r&&(a.classList.remove(pm,hm,mm),l==="accept"?(a.classList.add(pm),a.textContent=d?.acceptLabel??r.accept):l==="reject"?(a.classList.add(hm),a.textContent=r.reject):(a.classList.add(mm),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(l){const d=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return l()}finally{o.style.visibility=d,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return c.moveTo(t,n),c.setMode("neutral"),c}function iL(){const e=document.createElement("div");return e.className=tL,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 rL(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??aL(e),reject:t?.reject??cL(),neutral:t?.neutral??lL(e)}}function aL(e){return e.type==="shortcut"?k("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?k("Drop here to move","desktop-mode"):k("Drop here","desktop-mode")}function cL(e){return k("Canโ€™t drop here","desktop-mode")}function lL(e){return e.type==="shortcut"?k("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?k("Drop in a folder","desktop-mode"):""}function dL(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 uL(e){return e.offsetWidth/2}function fL(e){return e.offsetHeight/2}let gm=!1;function pL(e){gm||(gm=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const wm=4,_e={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"},Ei="os-file-tile--dragging",ym="os-file-tile--drop-target",bm="data-os-trash-drop-active",vm="data-files-drop-active",Em="data-os-dragging",_m="data-os-drag-type",Ya="data-os-drag-mode";class hL{constructor(){this._registry=new QC,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)<wm&&Math.abs(s)<wm)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),ct(_e.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)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(),pL(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:()=>km(),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(Ei),t._ghost=sL(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(Em,""),document.body.setAttribute(_m,String(t.payload.type)),document.body.setAttribute(Ya,"neutral")),ct(_e.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(c){console.error("[openstation] drop target accept() threw:",r.id,c)}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&&Xa(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(mL(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),ct(_e.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(Ya,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),Xa(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)}ct(_e.COMMIT,{payload:t.payload,targetId:n.id}),ct(_e.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&&Xa(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}ct(_e.CANCEL,{payload:t.payload,reason:n}),ct(_e.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(Ei)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(Em),document.body.removeAttribute(_m),document.body.removeAttribute(Ya)),gL()}}function ct(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function mL(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}ct(_e.ENTER,{payload:t.payload,targetId:e.id})}function Xa(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}ct(_e.LEAVE,{payload:t.payload,targetId:e.id})}function km(){if(typeof document>"u")return[];const e=[];for(const t of[`.${Ei}`,`.${ym}`,`[${bm}]`,`[${vm}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function gL(){for(const e of km())e.classList.remove(Ei,ym),e.removeAttribute(bm),e.removeAttribute(vm)}const wL=".os-window",Sm="wp-window-";function Am(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(wL);return o instanceof HTMLElement?o:null}function yL(e){if(!e.id.startsWith(Sm))return null;const t=e.id.slice(Sm.length);return t.length>0?t:null}const bL="desktop-mode-iframe-drop-",_i="iframe.os-window__iframe",Za="data-os-iframe-drop-active";let Ja=!1,Im=null;const Fe=new Map,Ft=new Map;let lt=null,Ht=null;function vL(){document.querySelectorAll(_i).forEach(t=>{Fe.has(t)||(Fe.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function EL(){Fe.forEach((e,t)=>{t.style.pointerEvents=e}),Fe.clear()}function Cm(e,t){const n=Am(e,t);if(!n)return null;const o=n.querySelector(_i);return o instanceof HTMLIFrameElement?o:null}const Lm=e=>{if(!lt)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=Cm(e.clientX,e.clientY);t!==Ht&&(Ht&&Gt(Ht,{type:"os-drag-leave"}),Ht=t,t&&Gt(t,{type:"os-drag-over",payload:lt}))},Tm=e=>{if(!lt)return;const t=Cm(e.clientX,e.clientY);if(!t){e.preventDefault(),ki();return}e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const n=lt;ki();const o=t.getBoundingClientRect();Gt(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},Nm=()=>{ki()};function _L(e){if(lt){lt=e;return}lt=e,vL(),document.addEventListener("dragover",Lm,!0),document.addEventListener("drop",Tm,!0),document.addEventListener("dragend",Nm,!0)}function ki(){lt&&(lt=null,Ht&&(Gt(Ht,{type:"os-drag-leave"}),Ht=null),document.removeEventListener("dragover",Lm,!0),document.removeEventListener("drop",Tm,!0),document.removeEventListener("dragend",Nm,!0),EL())}function Si(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function Gt(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function kL(e,t,n,o){return e.registerDropTarget({id:`${bL}${o}`,element:n,accept:s=>!!Si(s),onEnter:s=>{const i=Si(s.payload);i&&(n.setAttribute(Za,""),Gt(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(Za),Gt(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(Za);const r=Si(s.payload);if(!r)return;const a=t.getBoundingClientRect();Gt(t,{type:"os-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function Om(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 SL(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 AL(e){const t=Im;if(!t)return;const n=document.querySelectorAll(_i),o=!!Si(e);SL(n.length,o,e),n.forEach(s=>{if(Fe.has(s)||(Fe.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||Ft.has(s))return;const i=s.parentElement;if(!i)return;const r=Om(s),a=kL(t,s,i,r);Ft.set(s,a)})}function IL(){Fe.forEach((e,t)=>{t.style.pointerEvents=e}),Fe.clear(),Ft.forEach(e=>{try{e()}catch{}}),Ft.clear()}function CL(e){Ja||(Ja=!0,Im=e,document.addEventListener(_e.START,t=>{const n=t.detail;AL(n?.payload)}),document.addEventListener(_e.END,()=>{IL()}),document.addEventListener(In.START,t=>{const n=t.detail;n?.payload&&_L(n.payload)}),document.addEventListener(In.END,()=>{ki()}),ne(m.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(Fe))t.isConnected||Fe.delete(t);for(const[t,n]of Array.from(Ft))if(!t.isConnected){try{n()}catch{}Ft.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:Ja,iframesInDom:document.querySelectorAll(_i).length,suppressedCount:Fe.size,registeredCount:Ft.size,suppressedIframeIds:Array.from(Fe.keys()).map(Om)}))}const LL=250,TL=1e3,NL="os-drag-hover";let Dm=!1,Qa=null,ec=null,xo=null,Mo=null,tc=null;function Rm(){xo!==null&&(clearTimeout(xo),xo=null)}function xm(){Mo!==null&&(clearTimeout(Mo),Mo=null)}function Po(){Rm(),xm(),ec=null}function Mm(){xm(),Mo=setTimeout(()=>{Mo=null,Po()},TL)}function OL(e,t){const n=Qa?.getById(e);if(!(!n||n.isFocused()||!Z(m.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{Qa?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function Pm(e,t){e!==ec&&(Rm(),ec=e,e!==null&&(xo=setTimeout(()=>{xo=null,OL(e,t)},LL)))}function Wm(e,t,n){const o=Am(e,t);Pm(o?yL(o):null,n)}const DL=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||Wm(t.clientX,t.clientY,t.payload?.type??"")},RL=()=>{Po()};function xL(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 ML=e=>{Mm();const t=tc??(xL(e)?"os-file":"external");Wm(e.clientX,e.clientY,t)},$m=()=>{Po()},PL=e=>{e.relatedTarget===null&&Po()};function WL(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 $L=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==NL)return;const n=WL(e.source);n&&(Mm(),Pm(n,typeof t.payloadType=="string"?t.payloadType:"external"))},UL=e=>{const t=e.detail;t?.payload&&(tc=t.payload.kind??"")},BL=()=>{tc=null,Po()};function FL(e){Dm||(Dm=!0,Qa=e,document.addEventListener(_e.MOVE,DL),document.addEventListener(_e.END,RL),document.addEventListener(In.START,UL),document.addEventListener(In.END,BL),document.addEventListener("dragover",ML,!0),document.addEventListener("drop",$m,!0),document.addEventListener("dragend",$m,!0),document.addEventListener("dragleave",PL,!0),window.addEventListener("message",$L))}function Um(){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=Z("os.open-command.items",o);return Array.isArray(i)?i:o}const HL={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=Um();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=Um(),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 GL(){si(HL)}const ye=[],zL=new Set;function Bm(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=ye.findIndex(n=>n.id===e.id);return t>=0?ye[t]=e:ye.push(e),nc(),()=>{const n=ye.findIndex(o=>o.id===e.id);n>=0&&(ye.splice(n,1),nc())}}function jL(e){const t=ye.findIndex(n=>n.id===e);t>=0&&(ye.splice(t,1),nc())}function VL(){return ye.slice()}function nc(){for(const e of Array.from(zL))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",t)}}function Wo(e,t){try{document.dispatchEvent(new CustomEvent(t?"os-palette-opened":"os-palette-closed",{detail:{id:e}}))}catch{}}function Fm(){if(ye.length===0)return;const e=ye.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{ye[0].open(),Wo(ye[0].id,!0)}catch{}return}try{ye[e].close(),Wo(ye[e].id,!1)}catch{}const t=e+1;if(t<ye.length)try{ye[t].open(),Wo(ye[t].id,!0)}catch{}}function oc(e){const t=ye.find(n=>n.id===e);if(t){for(const n of ye)if(n.id!==e)try{n.isOpen()&&(n.close(),Wo(n.id,!1))}catch{}try{t.open(),Wo(t.id,!0)}catch{}}}let Hm=!1;function KL(){if(Hm)return;Hm=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),Fm())},!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"&&Fm()})}const qe=ie("os/presence",()=>({byUser:new Map,serverTimeMs:0})),qL=5*60*1e3;let Gm=Date.now(),zm=!1;function Ai(){Gm=Date.now()}function YL(e){if(!e||!e.snapshot)return;const t=qe.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 c={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},l=t.get(r);n.set(r,c),(!l||l.status!==c.status)&&o.push({userId:r,oldStatus:l?l.status:null,newStatus:c.status,entry:c})}qe.state.byUser=n,typeof e.serverTimeMs=="number"&&(qe.state.serverTimeMs=e.serverTimeMs),qe.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),Ee.publish("os/presence-changed",i)}Ee.publish("os/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function XL(){zm||(zm=!0,document.addEventListener("pointerdown",Ai,{capture:!0,passive:!0}),document.addEventListener("keydown",Ai,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||Ai()}),Te.contribute("openstation_presence_active",()=>!0),Te.contribute("openstation_user_active",()=>Date.now()-Gm<qL),Te.subscribe("openstation_presence",e=>{YL(e)}))}function ZL(e){const t=qe.state.byUser.get(e);return t?t.status:"offline"}function JL(){return new Map(qe.state.byUser)}function QL(e){return qe.state.byUser.get(e)??null}function eT(e){return qe.subscribe(t=>e(t))}function tT(){Ai()}function nT(e){if(!Array.isArray(e)||e.length===0)return;const t=qe.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)){qe.state.byUser=n,qe.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),Ee.publish("os/presence-changed",i)}Ee.publish("os/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const oT=Object.freeze({getStatus:ZL,getAll:JL,getEntry:QL,subscribe:eT,markActive:tT,applyBatch:nT});function jm(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 c of o)try{c(a)}catch(l){console.error("[openstation] selection listener threw:",l)}},r=a=>{const c=t.size,l=Array.from(t);a(),!(t.size===c&&l.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 c of a)t.add(c)}),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,c=!1){const l=e.order(),d=l.indexOf(a),u=n===null?-1:l.indexOf(n);if(d<0)return;if(u<0){r(()=>{c||t.clear(),t.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{c||t.clear();for(let v=f;v<=p;v+=1)t.add(l[v])})},selectAll(){const a=e.order();r(()=>{for(const c of a)t.add(c)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const a=new Set(e.order());let c=!1;return r(()=>{for(const l of Array.from(t))a.has(l)||(t.delete(l),c=!0)}),n!==null&&!a.has(n)&&(n=null),c},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const sT=".os-file-tile",iT="os-file-tile--selected",rT="os-selection-marquee",Vm=4,Km=36,qm=12,Ym="data-os-marquee";function aT(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function cT(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(Ym,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(Ym)}}const lT=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note",dT="os-area--overview";function uT(e,t){const n=t.itemSelector??sT,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??lT,r=()=>Array.from(e.querySelectorAll(n)).filter(S=>t.keyOf(S)!==null),a=()=>{const S=[],M=new Map;r().forEach((U,H)=>{const W=U.parentElement??e;let L=M.get(W);L||(L=[],M.set(W,L),S.push(W)),L.push({key:t.keyOf(U),top:parseFloat(U.style.top)||0,left:parseFloat(U.style.left)||0,index:H})});const D=[];for(const U of S){const H=M.get(U)??[];H.sort((W,L)=>W.top!==L.top?W.top-L.top:W.left!==L.left?W.left-L.left:W.index-L.index);for(const W of H)D.push(W.key)}return D},c=t.order??a,l=jm({order:c,onChange:S=>{p(),t.onChange?.(S),u(S)}}),d={},u=S=>{typeof document>"u"||(Cn={surface:t.surface??"",scope:t.scope??"",keys:S.slice(),count:S.length},ic=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:Cn})))},f=S=>r().find(M=>t.keyOf(M)===S)??null,p=()=>{for(const S of r()){const M=t.keyOf(S),D=l.has(M);D!==S.hasAttribute("selected")&&(D?S.setAttribute("selected",""):S.removeAttribute("selected")),S.classList.toggle(iT,D),S.hasAttribute("selectable")||S.setAttribute("selectable","");const U=D?"true":"false";S.getAttribute("aria-selected")!==U&&S.setAttribute("aria-selected",U)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let v=null;const b=S=>{if(!(S.target instanceof Element))return;const M=S.target.closest(n);if(M&&e.contains(M)){const D=t.keyOf(M);if(D===null)return;if(v=D,S.stopPropagation(),S.shiftKey){l.selectRange(D,S.ctrlKey||S.metaKey);return}if(S.ctrlKey||S.metaKey){l.toggle(D);return}l.set([D]);return}if($){$=!1;return}l.clear()};o.addEventListener("click",b);let w=null,g=null,_=null,N=[],$=!1,C=0,V=null,K=null;const j=S=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(S),K=S}catch{}},F=()=>{if(K===null||typeof o.releasePointerCapture!="function"){K=null;return}try{o.hasPointerCapture?.(K)&&o.releasePointerCapture(K)}catch{}K=null},E=(S,M)=>{const D=o.getBoundingClientRect();return{x:S-D.left+o.scrollLeft,y:M-D.top+o.scrollTop}},B=()=>{w?.remove(),w=null,g=null,_=null,V?.(),V=null,F(),C&&(cancelAnimationFrame(C),C=0),document.removeEventListener("pointermove",A),document.removeEventListener("pointerup",O),document.removeEventListener("pointercancel",G),o.removeEventListener("lostpointercapture",G),o.removeEventListener("scroll",P),window.removeEventListener("blur",G)};function P(){if(!g||!_)return;const S=E(_.x,_.y),M=S.x-g.x,D=S.y-g.y;if(!w&&Math.abs(M)<Vm&&Math.abs(D)<Vm)return;w||(w=document.createElement("div"),w.className=rT,w.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(w),$=!0,V=cT(o),h());const U=Math.min(g.x,S.x),H=Math.min(g.y,S.y),W=Math.abs(M),L=Math.abs(D);w.style.left=`${U}px`,w.style.top=`${H}px`,w.style.width=`${W}px`,w.style.height=`${L}px`;const z=o.getBoundingClientRect(),R=z.left-o.scrollLeft,ae=z.top-o.scrollTop,X={left:U+R,top:H+ae,right:U+W+R,bottom:H+L+ae},oe=[];for(const ce of r()){const ge=ce.getBoundingClientRect();ge.left<X.right&&ge.right>X.left&&ge.top<X.bottom&&ge.bottom>X.top&&oe.push(t.keyOf(ce))}l.set(Array.from(new Set([...N,...oe])))}function h(){if(C||typeof requestAnimationFrame!="function")return;const S=()=>{if(C=0,!w||!_)return;const M=o.getBoundingClientRect();if(aT(o)){let U=0;if(_.y<M.top+Km?U=-qm:_.y>M.bottom-Km&&(U=qm),U!==0){const H=o.scrollTop;o.scrollTop+=U,o.scrollTop!==H&&P()}}C=requestAnimationFrame(S)};C=requestAnimationFrame(S)}const A=S=>{g&&(_={x:S.clientX,y:S.clientY},P())},O=()=>{w&&(sc=Date.now()),B()},G=()=>{B()},Y=S=>{if(!s||S.button!==0||!(S.target instanceof Element)||o.classList.contains(dT)||S.target.closest(n))return;const M=S.target.closest(i);M&&M!==o&&o.contains(M)||(g=E(S.clientX,S.clientY),_={x:S.clientX,y:S.clientY},typeof S.pointerId=="number"&&j(S.pointerId),N=S.ctrlKey||S.metaKey||S.shiftKey?l.keys():[],N.length===0&&l.clear(),document.addEventListener("pointermove",A),document.addEventListener("pointerup",O),document.addEventListener("pointercancel",G),o.addEventListener("lostpointercapture",G),window.addEventListener("blur",G),o.addEventListener("scroll",P,{passive:!0}))};o.addEventListener("pointerdown",Y);const I=S=>{if(S.key==="a"&&(S.ctrlKey||S.metaKey)){S.preventDefault(),l.selectAll();return}if(S.key==="Escape"){if(w||g){B();return}l.size()>0&&l.clear();return}const M=S.key==="ArrowRight"||S.key==="ArrowDown",D=S.key==="ArrowLeft"||S.key==="ArrowUp";if(!M&&!D)return;const U=M?1:-1,H=c();if(H.length===0)return;const W=v??l.anchor(),L=W===null?-1:H.indexOf(W),z=Math.min(H.length-1,Math.max(0,L<0?0:L+U));S.preventDefault();const R=H[z];v=R,S.shiftKey?l.selectRange(R):l.set([R]),f(R)?.focus()};return e.addEventListener("keydown",I),p(),{model:l,keys:()=>l.keys(),elementFor:f,refresh(){l.prune(),p()},destroy(){B(),o.removeEventListener("click",b),o.removeEventListener("pointerdown",Y),e.removeEventListener("keydown",I),ic===d&&(Cn=null,ic=null)}}}let sc=0;function fT(){return sc>0&&Date.now()-sc<500}let Cn=null,ic=null;function pT(){return Cn?{...Cn,keys:Cn.keys.slice()}:null}function rc(e){return typeof e.sort=="number"?e.sort:100}function hT(e,t){return de(k("%1$s (%2$d items)","desktop-mode"),e,t)}function Xm(e,t){if(e.length===0)return[];const n=e.map(a=>{const c=t(a);return Array.isArray(c)?c:[]});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 c=i(a),l=[];let d=!1;for(const p of n){const v=p.find(b=>i(b)===c);if(!v||v.multi!==!0){d=!0;break}l.push(v)}if(d||s.some(p=>p.id===c))continue;const u=l[0],f=u.bulkLabel?u.bulkLabel(o):hT(u.label,o);s.push({id:c,label:f,icon:u.icon,disabled:l.some(p=>p.disabled===!0),danger:l.some(p=>p.danger===!0),sort:Math.min(...l.map(rc)),multi:!0,onClick:async p=>{const v=new Map,b=[];l.forEach((w,g)=>{const _=w.bulk;if(typeof _!="function"){b.push(w);return}const N=v.get(_);N?N.push(e[g]):v.set(_,[e[g]])});for(const[w,g]of v)try{await w(g)}catch(_){console.error(`[openstation] selection action '${c}' failed for a batch:`,_)}for(const w of b)try{await w.onClick(p)}catch(g){console.error(`[openstation] selection action '${c}' failed for one item:`,g)}}})}s.sort((a,c)=>{const l=rc(a),d=rc(c);return l!==d?l-d:a.label.localeCompare(c.label)});const r=Z("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function Zm(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 ac=8;function Jm(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function cc(e){Jm(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-ac)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-ac)}px`)})}function Qm(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,Jm(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-ac)}px`)})}const mT="os-wallpaper-menu";let Ln=null,lc=null,eg=0;function dc(){if(!Ln)return;const e=Ln.dataset.menuScope??"selection",t=lc;Ln.dispatchEvent(new CustomEvent("tile-menu-closed")),Ln.remove(),Ln=null,lc=null,t?.(),T(`os.${e}.menu.closed`,{})}function gT(e,t){dc();const n=++eg;gs(()=>n===eg,()=>wT(e,t))}function wT(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(mT),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 c=new Map;for(const u of t){c.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",yT(u.icon)),f.textContent=u.label,a.appendChild(f)}a.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=c.get(f.id);p&&(dc(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(v=>{console.error(`[openstation] menu action '${p.id}' threw:`,v)}))}),document.body.appendChild(a),Ln=a,lc=r??null,cc(a);const l=Zm(a,{close:()=>dc()});a.addEventListener("tile-menu-closed",l);const d=t.map(u=>u.id);i?.(d),T(`os.${s}.menu.opened`,{items:d,count:t.length})}function yT(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const bT={active:pT,resolveCommonActions:Xm,createModel:jm};let $o=null;function vT(){Te.contribute("openstation_content_changes_seen_ts",()=>$o===null?0:$o),Te.subscribe("openstation_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=$o===null,n=$o??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===""||(ci(`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));$o=o})}const ET="desktop_mode_nonces",uc=new Map;let tg=!1;function fc(e,t){if(typeof e!="string"||e==="")return()=>{};let n=uc.get(e);return n||(n=new Set,uc.set(e,n)),n.add(t),()=>{n.delete(t)}}function _T(){tg||(tg=!0,Te.subscribe(ET,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=uc.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)}}}),kT())}function kT(){fc("wp_rest",ST),fc("desktop-mode-plugins",e=>{ng("desktop-mode-plugins","ajaxNonce",e)}),fc("updates",e=>{ng("desktop-mode-plugins","updatesNonce",e)})}function ST(e){const t=AT();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=og();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function ng(e,t,n){const s=og()?.[e];s&&typeof s=="object"&&(s[t]=n)}function AT(){if(!(typeof window>"u"))return window.openStationConfig}function og(){if(!(typeof window>"u"))return window.openStationWindowConfig}const IT="desktop_mode_auth",CT=5e3,sg=1e3,LT=1e4;let ig=!1,Ii=!1,pc=!1,Ci=0,rg=0,Uo=0,Tn=null,ag=0,cg=null,lg=null,dg=()=>{try{window.location.reload()}catch{}};function hc(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function mc(e=sg){const t=Date.now();if(t<Uo){Tn===null&&(Tn=window.setTimeout(()=>{Tn=null,Uo=Date.now()+sg,hc()},Uo-t));return}Uo=t+e,hc()}function TT(){Ii=!0,!pc&&(pc=!0,T(m.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function NT(){for(const e of OT())try{e.contentWindow?.location.reload()}catch{}}function OT(){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 gc(){const e=Date.now();e-ag<LT||(ag=e,Ii=!1,pc=!1,Tn!==null&&(window.clearTimeout(Tn),Tn=null),Uo=0,mc(),NT(),T(m.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function DT(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(Ci<=0){Ci=t;return}t!==Ci&&dg()}}function RT(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<rg||(rg=o+CT,hc())}function xT(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");lg=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&mc(),t=n}),lg.observe(e,{attributes:!0,attributeFilter:["class"]})}function MT(e={}){ig||(ig=!0,Ci=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(dg=e.reloadShell),Te.subscribe("wp-auth-check",t=>{if(t===!1){TT();return}t===!0&&Ii&&gc()}),Te.subscribe("nonces_expired",()=>{if(Ii){gc();return}mc()}),Te.subscribe(IT,DT),cg=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&gc()},window.addEventListener("message",cg),xT())}const Nn=12;function wc(e,t){return ug(le(e,t.adminUrl),t)}function ug(e,t){if(e)return(t.dockItems||[]).find(n=>le(n.url,t.adminUrl)===e||(n.submenu||[]).some(o=>le(o.url,t.adminUrl)===e))}function yc(e,t){const n=t.x??0,o=t.y??0,s=Math.max(200,t.width-Nn*2),i=Math.max(200,t.height-Nn*2),r=Math.min(e.width,s),a=Math.min(e.height,i),c=n+Math.max(0,t.width-r-Nn),l=o+Math.max(0,t.height-a-Nn),d=Math.max(n+Nn,Math.min(e.x,c)),u=Math.max(o+Nn,Math.min(e.y,l));return{x:d,y:u,width:r,height:a}}const fg=window.location.origin;function PT(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 c;try{c=new URL(a,window.location.href)}catch(b){typeof console<"u"&&console.warn("[openstation] Couldnโ€™t parse href; letting the browser handle the click:",a,b);return}if(c.origin!==fg)return;let l;try{l=new URL(t.adminUrl).pathname}catch(b){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,b),l="/wp-admin/"}if(!c.pathname.startsWith(l)||/\/(admin-post|admin-ajax)\.php$/.test(c.pathname)||c.searchParams.has("action")&&c.searchParams.get("action")==="logout"||c.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Qe(c.href)))return;const d=le(c.href,t.adminUrl),u=wc(c.href,t),f=(i.textContent||"").trim()||u?.title||"",p=!!i.closest("#wp-admin-bar-new-content"),v={id:d,baseId:d,multi:!!u?.multi||p,url:c.href,parentUrl:u?.url??c.href,title:u?.title||f,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu,selfLabel:u?.selfLabel};if(p){e.openNew(v);return}e.open(v)},!0)}function WT(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 $T(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 UT(e){const t=WT(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=$T(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 BT="os-registry-changed";function FT(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 bc(e,t,n){const{added:o,removed:s}=FT(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(BT,{detail:i}))}function HT(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:c,syncServerWindowActions:l,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:v,renderIcons:b,applyDesktopIcons:w,refreshRootPlacements:g,syncShortcuts:_}=e,N=$=>($??[]).map(C=>String(C?.id??"")).sort().join(`
66 `);return function(C){const V=C.dockItems,K=C.nativeWindows,j=C.serverWidgets,F=C.serverWallpapers,E=C.serverCommandScripts,B=C.serverCommands,P=C.serverSettingsTabScripts,h=C.serverSettingsTabs,A=C.serverDockRailRendererScripts,O=C.serverTitleBarButtonScripts,G=C.serverWindowActionScripts,Y=C.serverUnfocusEffectScripts,I=C.serverWindowLinkRendererScripts,S=C.serverWindowNotices,M=C.serverGames,D=C.serverDesktopThemes,U=C.desktopIcons;if(!Array.isArray(V)||V.length===0)return;const H=n.dockItems;if(t(V),n.dockItems=V,bc("dock-items",H,V),_?.(),Array.isArray(K)){const W=n.nativeWindows;o(Ph(K,C.nativeWindowScriptData)),n.nativeWindows=K,C.nativeWindowScriptData&&(n.nativeWindowScriptData=C.nativeWindowScriptData),bc("native-windows",W,K)}if(Array.isArray(j)&&(s(j),n.serverWidgets=j),Array.isArray(F)&&(i(F),n.serverWallpapers=F),Array.isArray(M)&&(p(M),n.serverGames=M),Array.isArray(D)&&(v?.(D),n.serverDesktopThemes=D),Array.isArray(E)&&(r(E,Array.isArray(B)?B:void 0),n.serverCommandScripts=E,Array.isArray(B)&&(n.serverCommands=B)),Array.isArray(P)&&(a(P,Array.isArray(h)?h:void 0),n.serverSettingsTabScripts=P,Array.isArray(h)&&(n.serverSettingsTabs=h)),Array.isArray(O)&&(c(O),n.serverTitleBarButtonScripts=O),Array.isArray(G)&&(l(G),n.serverWindowActionScripts=G),Array.isArray(Y)&&(d(Y),n.serverUnfocusEffectScripts=Y),Array.isArray(I)&&(u(I),n.serverWindowLinkRendererScripts=I),Array.isArray(A)&&(f(A),n.serverDockRailRendererScripts=A),Array.isArray(S)&&(uh(S),n.serverWindowNotices=S),Array.isArray(U)){const W=n.desktopIcons;b(U),w?.(U),_?.(),N(W)!==N(U)&&g?.(),n.desktopIcons=U,bc("desktop-icons",W,U)}UT(C.updateCounts)}}const GT=8e3,zT=600;function jT(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:c,syncServerTitleBarButtons:l,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:v,syncServerDesktopThemes:b,renderIcons:w,refreshRootPlacements:g,syncShortcuts:_}=e,N=HT({applyDockItems:P=>t?.applyDockItems(P),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:c,syncServerTitleBarButtons:l,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:v,syncServerDesktopThemes:b,renderIcons:w,applyDesktopIcons:P=>t?.applyDesktopIcons(P),refreshRootPlacements:g,syncShortcuts:_});let $=typeof o.menuSig=="string"?o.menuSig:"",C=!1,V=null,K=!1,j=!1;const F=()=>{if(!o.adminUrl)return Promise.resolve();const P=(()=>{try{const h=new URL("admin.php",o.adminUrl);return h.searchParams.set("openstation_chromeless","1"),h.searchParams.set("openstation_menu_refresh","1"),h.toString()}catch{return null}})();return P?new Promise(h=>{const A=document.createElement("iframe");A.setAttribute("aria-hidden","true"),A.tabIndex=-1,A.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",A.src=P;let O=!1;const G=()=>{O||(O=!0,window.clearTimeout(I),window.removeEventListener("message",Y),A.parentNode&&A.parentNode.removeChild(A),h())},Y=S=>{if(S.source!==A.contentWindow)return;const M=S.data;!M||M.type!=="os-plugins-changed"||G()},I=window.setTimeout(()=>{T(m.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),G()},GT);window.addEventListener("message",Y),document.body.appendChild(A)}):Promise.resolve()},E=()=>{if(K){j=!0;return}K=!0,F().finally(()=>{K=!1,j&&(j=!1,E())})},B=()=>{V!==null&&window.clearTimeout(V),V=window.setTimeout(()=>{V=null,E()},zT)};return window.addEventListener("message",P=>{if(P.origin!==fg)return;const h=P.data;if(h){if(h.type==="os-plugins-changed"){h.payload&&(N(h.payload),typeof h.payload.menuSig=="string"&&($=h.payload.menuSig));return}if(h.type==="os-updates-changed"){B();return}if(h.type==="os-menu-signature"){const A=h.sig;typeof A=="string"&&A!==""&&A!==$&&!C&&(C=!0,F().finally(()=>{C=!1}))}}}),F}function VT(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 KT(e,t,n=5e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=c=>{window.clearTimeout(a),document.removeEventListener("os-window-opened",r),s(c)},r=c=>{c.detail?.windowId===t&&i(e.getById(t)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function qT(e,t,n,o){const s=Ce(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){if(!r.native)continue;const a=yc(r,s);i[r.id]={desktopId:r.desktopId,initialState:r.state,x:a.x,y:a.y,width:a.width,height:a.height,...r.params?{params:r.params}:{}}}Object.keys(i).length>0&&e.seedWindowRestoreState(i);for(const r of t.session.windows){if(r.native){if(!o?.(r.id))continue;await KT(e,r.id);continue}const a=yc(r,s),c=wc(r.url,t)??ug(r.baseId||r.id,t),l=await e.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!c?.multi,url:r.url,parentUrl:c?.url??r.url,title:r.title,icon:r.icon||"dashicons-admin-generic",x:a.x,y:a.y,width:a.width,height:a.height,initialState:r.state,submenu:c?.submenu,selfLabel:c?.selfLabel});if(Array.isArray(r.externalTabs))for(const d of r.externalTabs)d&&typeof d.url=="string"&&d.url!==""&&l.addExternalTab(d.url,typeof d.label=="string"&&d.label!==""?d.label:d.url)}if(t.session.focused){const r=e.getById(t.session.focused);r&&e.focus(r)}}async function YT(e,t){if(Qe(t.currentPage))return;const n=le(t.currentPage,t.adminUrl),o=wc(t.currentPage,t);await e.open({id:n,baseId:n,multi:!!o?.multi,url:t.currentPage,parentUrl:o?.url??t.currentPage,title:t.currentTitle,icon:t.currentIcon,submenu:o?.submenu,selfLabel:o?.selfLabel})}function XT(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function vc(e,t,n,o){const s=Fl(t,n),i=window.fetch(t,s);if(i.then(a=>{if(a.status===401||a.status===403){let c;typeof t=="string"?c=t:t instanceof URL?c=t.href:c=t.url,RT(a.status,c)}},()=>{}),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(ZT(a));return a})).catch(()=>{}),i}function ZT(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return de(k("Request failed (HTTP %s)."),t)}const JT="os-remember-session";function QT(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:JT,urls:t})}catch{}}const eN=500,tN=1500;function pg(e){try{if(!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled)return;QT(e.windows.filter(n=>!n.native&&n.url).map(n=>sE(n.url)||"").filter(Boolean))}catch{}}function nN(e,t){let n=null,o=!1,s=!1,i=0;const r=async()=>{if(o){s=!0;return}o=!0,i=Date.now();const l=e.snapshot();pg(l);try{await vc(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:l}),keepalive:!0},{silent:!0})}catch(d){T(m.SHELL_ERROR,{scope:"session-save",error:d})}finally{o=!1,s&&(s=!1,c())}},a=()=>{n!==null&&(clearTimeout(n),n=null),s=!1;const l=e.snapshot();pg(l);const d=new Blob([JSON.stringify({session:l})],{type:"application/json"}),u=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);navigator.sendBeacon&&navigator.sendBeacon(u,d)||r()},c=()=>{n!==null&&clearTimeout(n);let l=eN;if(i!==0){const d=Date.now()-i;l=Math.max(l,tN-d)}n=window.setTimeout(()=>{n=null,r()},l)};return window.addEventListener("pagehide",a),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&a()}),c}const oN=120;function sN(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),ne(m.DESKTOP_CREATED,"desktop-mode/session-save",e),ne(m.DESKTOP_CLOSED,"desktop-mode/session-save",e),ne(m.DESKTOP_SWITCHED,"desktop-mode/session-save",e),ne(m.DESKTOP_RENAMED,"desktop-mode/session-save",e)}function iN(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;T(m.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,oN)}),document.addEventListener("visibilitychange",()=>{T(m.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function rN(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 Z(m.DOCK_TILE_CLASS,e,o)}function aN(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 Z(m.DOCK_TILE_ELEMENT,e,o)}function cN(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 Z(m.DOCK_TILE_TOOLTIP,e,o)}function lN(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};T(m.DOCK_TILE_RENDERED,{...o,el:e})}const dN=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),Ec=new Set;function uN(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(dN))return!0;for(const n of Ec)if(t.closest(n))return!0;return!1}function fN(e){return typeof e!="string"||e.trim()===""?()=>{}:(Ec.add(e),()=>{Ec.delete(e)})}const dt=new Map,pN=window.location.origin;function hg(e){let t=dt.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},dt.set(e,t)),hN(e,t),t}function hN(e,t){const n=_c(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(()=>On(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function mN(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function _c(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 gN(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 On(e){const t=_c(e);if(!t||!t.contentWindow)return;const n=dt.get(e),o=n?gN(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},pN)}catch{}}ne(m.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&dt.has(t.windowId)&&On(t.windowId)}),ne(m.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=dt.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const _t=new Map,wN=1e3;function mg(e,t,n){const o=_t.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,!!_t.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const c=o.channels.get(a.channel);if(c)for(const l of c)try{l(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=_t.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>mg(e,t,n),wN))})}function yN(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function bN(e,t){const n=_t.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let vN=0;const gg={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=hg(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),On(e),()=>{const r=dt.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const c=a.indexOf(s);c>=0&&a.splice(c,1),a.length===0&&r.headers.delete(t),On(e),wg(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=hg(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,On(e)),()=>{const i=dt.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),On(e)),wg(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=_c(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=gg.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",c=new URL(a,window.location.origin);c.searchParams.set(i,t),o.src=c.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){bN(e,{id:++vN,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=_t.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},_t.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=yN();r&&mg(e,r.restUrl,r.restNonce)}return()=>{const r=_t.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),_t.delete(e))}}}};function wg(e){const t=dt.get(e);t&&t.headers.size===0&&t.observers.size===0&&(mN(t),dt.delete(e))}async function Bo(e){return await or(sr()),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","");const o=s=>{n.remove(),t(s)};n.addEventListener("os-confirm",()=>o(!0)),n.addEventListener("os-cancel",()=>o(!1)),document.body.appendChild(n)})}function EN(e){const t=[];for(const c of e.getVisibleRects()){if(c.state==="minimized"||c.element.offsetParent===null)continue;const l=c.element.getBoundingClientRect();t.push({id:`window:${c.windowId}`,kind:"window",rect:yg(l),face:"top",element:c.element})}const n=document.getElementById("os-shell");if(n){const c=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:c.left,y:c.bottom-1,width:c.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const c of Array.from(o)){const l=c.getBoundingClientRect();if(l.width<=0||l.height<=0)continue;const d=c.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:l.left,y:l.top,width:l.width,height:1},face:"top",element:c}):d==="right"?t.push({id:u,kind:"dock",rect:{x:l.left,y:l.top,width:1,height:l.height},face:"left",element:c}):t.push({id:u,kind:"dock",rect:{x:l.right-1,y:l.top,width:1,height:l.height},face:"right",element:c})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(c=>{const l=c.getBoundingClientRect();if(l.width===0&&l.height===0)return;const d=c.dataset.widgetId??String(r++);t.push({id:`widget:${d}`,kind:"widget",rect:yg(l),face:"top",element:c})});const a=Z(m.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function yg(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const _N="__openstationKeyedListKey",kN="__openstationKeyedListData";function SN(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function AN(e,t,n){const o=SN(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const c of t){const l=String(n.keyOf(c));a.has(l)&&console.warn("[desktop-mode/keyed-list] duplicate key โ€” only the last item with this key will render:",l),a.add(l);const d=s.get(l);if(d){const f=d.data;n.updateItem?.(d.el,c,f),d.data=c,i.set(l,d),r.push(d.el);continue}const u=n.buildItem(c);u[_N]=l,u[kN]=c,i.set(l,{el:u,data:c}),r.push(u)}for(const[c,l]of s)i.has(c)||l.el.remove();for(let c=0;c<r.length;c++){const l=r[c],d=e.children[c];d!==l&&e.insertBefore(l,d??null)}o.byKey=i}function IN(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function CN(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:c=j=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",j)}}=e;let l=e.sentinel??null;l||(l=document.createElement("div"),l.dataset.osInfiniteListSentinel="",l.style.height="1px",t.appendChild(l));const d=new Set;let u=r,f=!0,p=!1,v=null,b=0,w=!1,g=null;const _=j=>{if(p!==j){p=j;try{a(j)}catch(F){c(F)}}},N=()=>{g&&(g.disconnect(),g=null)},$=()=>{g||!l||w||(g=new IntersectionObserver(j=>{for(const F of j)F.isIntersecting&&C()},{rootMargin:i}),g.observe(l))},C=async()=>{if(w||p||!f)return;_(!0),v=new AbortController;const j=v;try{const F=await n(u,j.signal);if(w||j!==v)return;let E=0;const B=document.createDocumentFragment();for(const P of F.items??[]){const h=String(o(P));if(d.has(h))continue;d.add(h);const A=s(P,b+E);B.appendChild(A),E++}E>0&&(l&&l.parentNode===t?t.insertBefore(B,l):t.appendChild(B),b+=E),u=F.nextCursor??null,u||(f=!1,N())}catch(F){if(F?.name==="AbortError")return;c(F)}finally{j===v&&(_(!1),v=null)}},V=()=>{if(w)return;v?.abort(),v=null,d.clear(),u=r,f=!0,b=0;const j=l&&l.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);j&&l&&t.appendChild(l),_(!1),$(),C()},K=()=>{w||(w=!0,N(),v?.abort(),v=null,!e.sentinel&&l&&l.parentNode===t&&t.removeChild(l),l=null,_(!1))};return $(),C(),{reset:V,loadMore:C,hasMore:()=>f,isLoading:()=>p,destroy:K}}const LN=520,TN=720,NN=500;function ON(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=RN(),o=xN();return Be(it(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:e})},{source:"desktop-mode/oauth-start"}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`[openstation] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>DN(s,e,t))}function DN(e,t,n){return new Promise((o,s)=>{const i=n.width??LN,r=n.height??TN,a=Math.max(0,Math.floor((window.screen.width-i)/2)),c=Math.max(0,Math.floor((window.screen.height-r)/2)),l=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${c}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(e.authorize_url,`os-oauth-${t}`,l);if(!d){s(new Error("[openstation] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let f=null,p=!1;const v=()=>{p||(p=!0,window.removeEventListener("message",b),f!==null&&(window.clearInterval(f),f=null))},b=w=>{if(w.origin!==u)return;const g=w.data;if(!g||g.type!=="os-oauth-callback")return;const _=g.payload;if(v(),_&&_.ok)o(_);else{const N=_?.reason??"unknown",$=_?.message??"OAuth flow failed",C=new Error(`[openstation] startOAuth(${t}) failed: ${N} โ€” ${$}`);C.cause=_,s(C)}};window.addEventListener("message",b),f=window.setInterval(()=>{d.closed&&(v(),s(new Error(`[openstation] startOAuth(${t}) cancelled โ€” popup closed before completing.`)))},NN)})}function bg(){return window.openStationConfig??{}}function RN(){const e=bg().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function xN(){const e=bg().restNonce;return typeof e=="string"&&e!==""?e:null}const MN="",PN="system-default",WN={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function $N(e,t,n={}){const o=t===MN,s=o?null:_r(t);if(!o&&!s)return{};const i=o?PN:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=Bb(o?WN:s.recommendedOsSettings),c=Object.keys(a);if(c.length===0)return{};const l=e,d={};for(const u of c){const f=a[u];typeof f!="string"&&typeof f!="number"||!(u in e)||typeof l[u]!=typeof f||(l[u]=f,d[u]=f)}return Object.keys(d).length===0?{}:(r||(e.appliedThemeRecommendations=[...e.appliedThemeRecommendations,i].slice(-64)),d)}const Li=["os-section","os-button","os-swatch","os-swatch-grid","os-segmented","os-segment","os-select","os-option","os-multiselect","os-color-field","os-range-field","os-text-field","os-number-field","os-checkbox","os-checkbox-label","os-switch","os-toast","os-toast-container","os-tabs","os-tab","os-tabpanel","os-window-button","os-menu","os-menu-item","os-context-menu","os-context-menu-option","os-confirm-dialog","os-modal","os-user-search","os-role-picker","os-flyout","os-tab-chip","os-stack","os-cluster","os-icon","os-body","os-panel","os-row","os-grid","os-display","os-disclosure","os-empty-state","os-key","os-code","os-badge","os-ribbon","os-tile","os-log","os-steps","os-step","os-table","os-spinner","os-relative-time","os-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"],vg=new Set(Li);let Ti=null;function kc(){return!!window.openStationComponents}function UN(){return window.openStationConfig?.componentsBundleUrl??""}function BN(e){return new Promise((t,n)=>{const o=()=>{if(kc()){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){kc()?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 FN(e){const t=e.filter(n=>!vg.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 ${Li.length} tags; see docs/components-reference.md for the list. The others in this call still loaded.`)}async function HN(e){if(e){if(FN(e),e.filter(o=>vg.has(o)&&!customElements.get(o)).length===0)return}else if(kc())return;const t=UN();t&&(Ti||(Ti=BN(t).catch(n=>{throw Ti=null,n})),await Ti)}const GN=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","registerModule","loadModules","whenReady","ready","isReady","setDefaultWindow","refreshMenu","config","ai","dragBridge","dragManager","registerCommand","unregisterCommand","listCommands","registerDestructiveAdminAction","unregisterDestructiveAdminAction","listDestructiveAdminActions","registerSettingsTab","unregisterSettingsTab","listSettingsTabs","registerDockRailRenderer","unregisterDockRailRenderer","listDockRailRenderers","openOsSettings","getOsSettings","subscribeOsSettings","updateOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","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 zN(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:c,registerWindow:l,openWindowById:d,openNewWindowById:u,loadWindowScriptById:f,placeSystemTile:p,setDefaultWindow:v,refreshMenu:b,openOsSettings:w,aiAssistant:g,dragBridge:_,dragManager:N,connect:$,getConnection:C,wallpaperSuspend:V,mio:K,config:j}=e,F={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,iconSet:qy,files:r,confirm:Bo,saveSession:a,hooks:Ly(),HOOKS:m,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:E=>{hn(E),s.apply()},registerWidget:E=>{za(E)},widgetLayer:c,widgets:{redock:E=>{c?.redock(E)}},loadVendorScript:ue,getWallpaperSurfaces:()=>EN(t),wallpaper:V,mio:K,games:ip,registerWindow:l,openWindow:d,openNewWindow:u,loadWindowScript:f,loadComponents:HN,fetch:(E,B,P)=>vc(t,E,B,P),repaintLoadingOverlays:Hu,cloneTemplate:Wh,onWindow:NI,createInfiniteList:CN,startOAuth:ON,registerSystemTile:E=>{p(E),T(m.DOCK_ITEM_APPENDED,{id:E.id})},registerModule:Bf,loadModules:la,whenReady:Al,ready:Al,isReady:Ny,setDefaultWindow:v,refreshMenu:b,config:j,ai:g,dragBridge:_,dragManager:N,registerCommand:si,unregisterCommand:hp,listCommands:mp,registerDestructiveAdminAction:u_,unregisterDestructiveAdminAction:Gu,listDestructiveAdminActions:f_,registerSettingsTab:wp,unregisterSettingsTab:yp,listSettingsTabs:bp,registerDockRailRenderer:Hl,unregisterDockRailRenderer:eb,listDockRailRenderers:ob,openOsSettings:w,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:E=>s.subscribeOsSettings(E),updateOsSettings:(E,B={})=>{if(typeof E.wallpaper=="string"&&(s.state.wallpaper=E.wallpaper),typeof E.accent=="string"&&(s.state.accent=E.accent),typeof E.dockSize=="string"&&(s.state.dockSize=E.dockSize),typeof E.windowRadius=="string"&&(s.state.windowRadius=E.windowRadius),typeof E.adminBarMode=="string"&&(s.state.adminBarMode=E.adminBarMode),typeof E.desktopLayout=="string"&&(s.state.desktopLayout=E.desktopLayout),typeof E.dockPlacement=="string"&&(s.state.dockPlacement=E.dockPlacement),typeof E.dockBehavior=="string"&&(s.state.dockBehavior=E.dockBehavior),typeof E.sideDockBehavior=="string"&&(s.state.sideDockBehavior=E.sideDockBehavior),typeof E.desktopTheme=="string"&&(s.state.desktopTheme=E.desktopTheme),typeof E.unfocusEffect=="string"&&(s.state.unfocusEffect=E.unfocusEffect),typeof E.windowReveal=="string"&&(s.state.windowReveal=E.windowReveal),typeof E.windowRevealDuration=="number"&&(s.state.windowRevealDuration=E.windowRevealDuration),typeof E.dockRailRenderer=="string"&&(s.state.dockRailRenderer=E.dockRailRenderer),typeof E.windowLinkRenderer=="string"&&(s.state.windowLinkRenderer=E.windowLinkRenderer),(E.windowLinkVisibility==="focus"||E.windowLinkVisibility==="always"||E.windowLinkVisibility==="off")&&(s.state.windowLinkVisibility=E.windowLinkVisibility),typeof E.windowLinksEnabled=="boolean"&&(s.state.windowLinksEnabled=E.windowLinksEnabled),typeof E.windowLinkRaiseOnFocus=="boolean"&&(s.state.windowLinkRaiseOnFocus=E.windowLinkRaiseOnFocus),typeof E.windowLinkHighlight=="boolean"&&(s.state.windowLinkHighlight=E.windowLinkHighlight),E.ai&&typeof E.ai=="object"&&(s.state.ai={...s.state.ai,...E.ai}),typeof E.windowPrewarmEnabled=="boolean"&&(s.state.windowPrewarmEnabled=E.windowPrewarmEnabled,$C(E.windowPrewarmEnabled)),typeof E.adminAssetCacheEnabled=="boolean"&&(s.state.adminAssetCacheEnabled=E.adminAssetCacheEnabled),typeof E.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=E.nativePostsEnabled),typeof E.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=E.nativePagesEnabled),typeof E.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=E.nativeUsersEnabled),typeof E.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=E.nativePluginsEnabled),typeof E.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=E.nativeCommentsEnabled),typeof E.stationHomeEnabled=="boolean"&&(s.state.stationHomeEnabled=E.stationHomeEnabled),typeof E.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=E.foldersSharingEnabled),typeof E.showPostStatusRibbons=="boolean"&&(s.state.showPostStatusRibbons=E.showPostStatusRibbons),typeof E.developerModeEnabled=="boolean"&&(s.state.developerModeEnabled=E.developerModeEnabled),Array.isArray(E.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=E.nativePostsHiddenColumns.filter(P=>typeof P=="string"&&P!=="").slice(0,32)),E.navPlacement&&typeof E.navPlacement=="object"){const P=["both","rail","desktop","hidden"],h={};for(const[A,O]of Object.entries(E.navPlacement))typeof A!="string"||A===""||typeof O!="string"||!P.includes(O)||(h[A]=O);s.state.navPlacement=h}if(Array.isArray(E.navOrder)&&(s.state.navOrder=E.navOrder.filter(P=>typeof P=="string"&&P!=="").slice(0,256)),E.dockPromotedPositions&&typeof E.dockPromotedPositions=="object"){const h={};for(const[A,O]of Object.entries(E.dockPromotedPositions)){if(typeof A!="string"||A===""||!O||typeof O!="object")continue;const G=O;if(!(typeof G.x!="number"||typeof G.y!="number"||!Number.isFinite(G.x)||!Number.isFinite(G.y)||Math.abs(G.x)>1e5||Math.abs(G.y)>1e5)&&(h[A]={x:G.x,y:G.y},Object.keys(h).length>=256))break}s.state.dockPromotedPositions=h}s.save(B),(typeof E.wallpaper=="string"||typeof E.accent=="string"||typeof E.dockSize=="string"||typeof E.windowRadius=="string"||typeof E.adminBarMode=="string"||typeof E.desktopLayout=="string"||typeof E.dockPlacement=="string"||typeof E.dockBehavior=="string"||typeof E.sideDockBehavior=="string"||typeof E.dockRailRenderer=="string"||typeof E.desktopTheme=="string")&&s.apply(),(E.navPlacement||E.navOrder)&&o?.refresh()},deriveWindowId:(E,B)=>le(E,B??j.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:E=>o?.getSystemTile(E)??null,getMenuItems:()=>o?.getMenuItems()??[],getNavItems:()=>o?.getNavItems()??[],getNav:()=>o?.getNav()??null,renderIcon:Io,applyTileClasses:rN,applyTileElement:aN,applyTileTooltip:cN,dispatchTileRendered:lN,isDockElement:uN,registerDockSelector:fN,registerTitleBarButton:ri,unregisterTitleBarButton:f0,listTitleBarButtons:h0,registerWindowAction:w0,unregisterWindowAction:y0,listWindowActions:v0,registerUnfocusEffect:di,unregisterUnfocusEffect:$0,listUnfocusEffects:Ca,registerWindowReveal:Pe,unregisterWindowReveal:xb,listWindowReveals:pd,relations:__,registerWindowLinkRenderer:Hp,unregisterWindowLinkRenderer:z0,listWindowLinkRenderers:Ta,registerWindowTheme:Kp,unregisterWindowTheme:qp,listWindowThemes:Yp,desktopThemes:{list:zb,getActive:kr,setActive:aa,ensureFull:Id,subscribe:Kb,resolveIcon:ks,resolveIconColor:Sr,applyRecommendedOsSettings:E=>{const B=E??kr()??"";if(B==="")return{};const P=$N(s.state,B,{force:!0});return Object.keys(P).length>0&&(s.save(),s.apply()),P}},applyWindowTheme:(E,B)=>{const P=t.getById(E);P&&P.setAppearanceTheme(B)},registerWindowControl:bo,unregisterWindowControl:Jp,listWindowControls:Qp,applyWindowControls:(E,B)=>{const P=t.getById(E);P&&P.setAppearanceControls(B)},registerWindowSlot:oh,unregisterWindowSlot:Pa,listWindowSlots:sh,applyWindowSlot:(E,B,P)=>{const h=t.getById(E);h&&h.setAppearanceSlot(B,P)},registerWindowNotice:lh,unregisterWindowNotice:Ba,listWindowNotices:dh,dismissWindowNotice:hA,undismissWindowNotice:mA,registerWindowChrome:yA,unregisterWindowChrome:hh,listWindowChromes:mh,applyWindowChrome:(E,B)=>{const P=t.getById(E);P&&P.setAppearanceChrome(B)},connect:$,getConnection:C,broadcast:ci,subscribe:yn,announceContentChange:Tp,registerPalette:Bm,unregisterPalette:jL,listPalettes:VL,openPalette:oc,devtools:gg,createSharedStore:ie,presence:oT,workArea:DE,selection:bT,activity:Ee,heartbeat:Te,showToast:fe,notify:ya,pwa:{promptInstall:jC,undismissInstallHint:VC,getState:lo,subscribe:ap,requestNotificationPermission:ZS,getNotificationPermission:JS},renderKeyedList:AN,clearKeyedList:IN,registerNamespace:(E,B)=>{if(typeof E!="string"||E===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!B||typeof B!="object"){console.warn(`[openstation] registerNamespace("${E}"): api must be an object`);return}if(GN.has(E)){console.warn(`[openstation] registerNamespace("${E}"): name is reserved by the shell โ€” pick a plugin-specific key`);return}F[E]=B},getWindowConfig:E=>{const B=window.openStationWindowConfig;if(!B||typeof B!="object")return;const P=B[E];return P===void 0?void 0:P},getWindowParams:E=>{const B=t.getById(E);if(B)return{...B.config.params??{}}},registerNativeUrlRemap:yt,debug:{window:E=>{const B=(j.nativeWindows??[]).find(Y=>Y.id===E);if(!B)return null;const P=B.scriptUrl||(B.scriptHandle?j.nativeWindowScriptData?.[B.scriptHandle]?.url??"":"");let h="unknown",A=!1;P&&(document.querySelector(`script[data-os-vendor="${P.replace(/"/g,'\\"')}"]`)?(h="lazy",A=!0):Array.from(document.querySelectorAll("script[src]")).find(S=>S.src===P)&&(h="eager",A=!0));const O=window.openStationWindowConfig,G=!!(O&&typeof O=="object"&&Object.prototype.hasOwnProperty.call(O,E));return{id:E,scriptHandle:B.scriptHandle||"",scriptUrl:P,loadPath:h,tagInDom:A,configPresent:G,extras:{hasTranslations:!!B.scriptTranslations,l10nCount:(B.scriptL10n??[]).length,beforeCount:(B.scriptBefore??[]).length,afterCount:(B.scriptAfter??[]).length}}}}};return F}function jN(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const Sc=ie("desktop-mode/layout",()=>({layout:"classic"}));function Eg(e){Sc.state.layout!==e&&(Sc.state.layout=e,Sc.notify())}class _g{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 VN extends _g{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const Fo=new Map,Ac=new Set;function He(e){if(!e.type)throw new Error("[openstation] registerType: `type` is required.");if(!e.label)throw new Error("[openstation] registerType: `label` is required.");Fo.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),T("os.files.type-registered",e.type,e),Sg()}function KN(e){Fo.delete(e)&&(T("os.files.type-unregistered",e),Sg())}function qN(e){const t=Fo.get(e);return t||null}function kg(){const e=Array.from(Fo.values()).slice(),t=Z("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 kt(e){const t=Fo.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new VN(e,e.type)}function YN(e){return Ac.add(e),()=>Ac.delete(e)}function Sg(){for(const e of Ac)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const Ni=new Map,Ic=new Set;let Cc={};function Ag(e){Cc={...e},Oc()}function Lc(){return{...Cc}}function We(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.");Ni.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}),T("os.files.opener-registered",e.id,e),Oc()}function XN(e){Ni.delete(e)&&(T("os.files.opener-unregistered",e),Oc())}function ZN(e){return Ni.get(e)??null}function Ig(){const e=Array.from(Ni.values()).slice(),t=Z("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 Tc(e,t){return Ig().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function Nc(e,t){const n=Tc(e,t);if(n.length===0)return null;const o=Cc[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]),Z("os.files.resolve-opener",s,e)??null}function Cg(e){return Ic.add(e),()=>Ic.delete(e)}function Oc(){for(const e of Ic)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let Ho=null;function JN(e){Ho=e}async function Go(e,t){if(!Ho)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=Nc(e.type(),e);if(!n)return T("os.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;T("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):Ho.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),c=Ho.openUrl({id:i,url:s,title:r,icon:a});return T("os.files.opened",{file:e,openerId:n.id,kind:"url"}),c}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=Ho.openNativeWindow(o.windowId,s);return T("os.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),T("os.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return T("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 QN="dashicons-portfolio";function eO(){He({type:"shortcut",label:"Plugin shortcut",sort:1}),He({type:"folder",label:"Folder",sort:5}),He({type:"post",label:"Post",sort:10}),He({type:"attachment",label:"Media",sort:20}),He({type:"upload",label:"Uploaded file",sort:25}),He({type:"user",label:"User",sort:30}),He({type:"term",label:"Taxonomy term",sort:40}),He({type:"comment",label:"Comment",sort:50}),He({type:"bookmark",label:"Bookmark",sort:60}),He({type:"link",label:"Web link",sort:70}),He({type:"embed",label:"Embedded web window",sort:80})}const Ge=ie("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function Lg(e){Ge.state.activeAgent=e,Ge.state.transcripts[e.id]||(Ge.state.transcripts[e.id]=[]),Ge.state.conversationIds||(Ge.state.conversationIds={},Ge.state.conversationsRev=0),Ge.notify()}const Tg="desktop-mode/v1/agents/conversations";async function Ng(e,t,n={}){const o=await Be(it(e.restRoot,t),{...n,headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce,...n.headers??{}}},{source:"desktop-mode/agents",silent:!0}),s=await o.json().catch(()=>null);if(!o.ok){const i=s&&typeof s=="object"&&typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new Error(i)}return s}function tO(e){return e.filter(t=>!t.pending)}async function nO(e,t){const n=Ge.state,o=tO(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await Ng(t,`${Tg}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await Ng(t,Tg,{method:"POST",body:JSON.stringify({agentId:e.id,messages:o})});n.conversationIds[e.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,Ge.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const Og={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function Dg(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function Rg(e){if(e.type==="shortcut"){const t=e.data;let n=Og[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=Dg(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=Og[String(n.type??"")],s=Dg(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function oO(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function sO(e){return de(k('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 iO(e){return{kind:e.kind,id:e.id,title:e.title}}function xg(e,t="agents"){Lg(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function rO(e,t,n,o,s){Lg(e);const i=Ge.state.transcripts[e.id],r=i.filter(c=>!c.pending&&c.role!=="error").map(c=>({role:c.role,text:c.text}));i.push({role:"user",text:t,at:Date.now(),attachment:s});const a={role:"agent",text:k("Workingโ€ฆ","desktop-mode"),at:Date.now(),pending:!0};i.push(a),Ge.notify();try{const c=await Be(it(n.restRoot,`desktop-mode/v1/agents/${e.id}/invoke`),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":n.restNonce},body:JSON.stringify({message:t,source:o,history:r})},{source:"desktop-mode/agents"}),l=await c.json().catch(()=>null);if(!c.ok){if(c.status===504)throw new Error(k("The agent took too long to reply, so the answer never arrived. It may still be finishing the work: give it a moment before asking again.","desktop-mode"));const u=l&&typeof l=="object"&&typeof l.message=="string"?l.message:`HTTP ${c.status}`;throw new Error(u)}const d=l;a.text=d.text||k("The agent finished without a text answer.","desktop-mode"),a.toolCalls=d.toolCalls,Array.isArray(d.callToActions)&&d.callToActions.length>0&&(a.callToActions=d.callToActions)}catch(c){a.role="error",a.text=c instanceof Error?c.message:String(c)}a.pending=!1,Ge.notify(),nO(e,n)}function aO(e,t,n){return xg(e,"agents-drop"),rO(e,sO(t),n,"drag",iO(t))}let Dc=null;function Mg(e){Dc=e}function zo(){if(!Dc)throw new Error("[openstation] files REST client called before installRestDeps().");return Dc}function cO(){return zo()}class Rc 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 he(e,t){const{baseUrl:n,nonce:o}=zo(),s=it(n,e),i=new Headers(t.headers??{});i.set("X-WP-Nonce",o),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Be(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),a=await r.text();let c=null,l=null;if(a)try{c=JSON.parse(a)}catch(d){c=null,l=d}if(!r.ok){if(r.status===409){const u=c?.data?.data??c?.data;if(u&&typeof u=="object")throw new Rc(u)}const d=c;throw new Error(`[openstation] files REST ${r.status}: ${d?.code??""} ${d?.message??""}`.trim())}if(c===null){if(l&&a){const d=a.slice(0,120).replace(/\s+/g," ");throw new Error(`[openstation] files REST ${r.status} returned non-JSON body โ€” ${l.message}. First 120 chars: ${d}`)}throw new Error(`[openstation] files REST ${r.status}: empty or unparseable body.`)}return c}function Oe(e=0){return he(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function jo(e){return he("/placements",{method:"POST",body:JSON.stringify(e)})}function Dn(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),he(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function xc(e){return he(`/placements/${e}`,{method:"DELETE"})}async function Oi(e,t){const{baseUrl:n,nonce:o}=zo(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Be(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 Pg(){return he("/folders",{method:"GET"})}function Mc(e){return he("/folders",{method:"POST",body:JSON.stringify(e)})}function Wg(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),he(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Pc(e){return he(`/folders/${e}`,{method:"DELETE"})}function $g(e){return he("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function lO(e){return he(`/folders/${e}/shares`,{method:"GET"})}function dO(e,t){return he(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function uO(e,t,n){return he(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function fO(e,t){return he(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function pO(e,t){return he(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function hO(e,t){return he(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function Ug(e){return he(`/folders/${e}/leave`,{method:"POST"})}function mO(){return he("/folder-sharing-tables/purge",{method:"POST"})}function gO(e){return he(`/uploads/${e}/shares`,{method:"GET"})}function wO(e,t){return he(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function yO(e,t){return he(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function bO(e,t){return he(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function vO(e,t){return he(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function Bg(e){return he(`/uploads/${e}/leave`,{method:"POST"})}function EO(e,t){return he(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function _O(e,t){return he("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function zt(e){const{baseUrl:t,nonce:n}=zo(),o=it(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function Fg(e){const{baseUrl:t,nonce:n}=zo(),o=it(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const kO=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:Rc,acceptFileShare:bO,acceptShare:pO,createFolder:Mc,createPlacement:jo,deleteFolder:Pc,deletePlacement:xc,denyFileShare:vO,denyShare:hO,ensureUploadPath:_O,getFilesRestDeps:cO,getFolderZipUrl:Fg,getUploadDownloadUrl:zt,installRestDeps:Mg,inviteFileShare:wO,inviteShare:dO,leaveFileShare:Bg,leaveShare:Ug,listFileShares:gO,listFolders:Pg,listPlacements:Oe,listShares:lO,purgeFolderSharingTables:mO,renameUpload:EO,restoreTrashedItem:Oi,revokeFileShare:yO,revokeShare:fO,saveAssociations:$g,updateFolder:Wg,updatePlacement:Dn,updateShareCapability:uO},Symbol.toStringTag,{value:"Module"})),SO="desktop-mode/files";function Ye(){return ie(SO,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function Rn(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function jt(e,t){const n=Ye(),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(),Rn({kind:"placements-set",folderId:e})}function Wc(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=Ye(),o=new Map(n.state.placementsByFolder);for(const[a,c]of o)if(c.findIndex(d=>d&&d.id===e.id)>=0&&a!==e.parentId){const d=c.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(),Rn({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function Vo(e,t="local"){const n=Ye(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(c=>c&&c.id===e)>=0){const c=r.filter(Boolean).filter(l=>l.id!==e);o.set(i,c),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),Rn({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function $c(e){const t=Ye(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),Rn({kind:"folders-set"})}function Uc(e,t="local"){const n=Ye(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),Rn({kind:"folder-upserted",folderRowId:e.id,source:t})}function Bc(e,t="local"){const n=Ye(),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(),Rn({kind:"folder-removed",folderRowId:e,source:t})}function Fc(e){return Ye().subscribe(e)}function St(){return Ye().getState()}function Hg(e){const t=St(),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:St,subscribe:Fc,setFolderPlacements:jt,upsertPlacement:Wc,upsertFolder:Uc,removePlacement:Vo,removeFolder:Bc,currentPlacement:Hg},AO=Se`:host{display:inline-block}`,IO=Se`: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 ) )}`,fs=class fs extends Pt{render(){return tt`<span class="banner" part="banner"><slot></slot></span>`}};fs.props=["placement","tone"],fs.styles=[IO],fs.help=void 0;let Hc=fs;ro("os-ribbon",Hc);const re="os-file-tile",Gg={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function CO(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function LO(){return window.wp?.os?.dragManager??null}const TO=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],Un=class Un extends Pt{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(`${re}--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 tt``}_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")??"",c=this.hasAttribute("selected"),l=this.hasAttribute("selectable"),d=this.hasAttribute("missing"),u=this.hasAttribute("access-gated"),f=[re,`${re}--folder`,`${re}--missing`,`${re}--access-gated`,`${re}--selected`];for(const g of f)this.classList.remove(g);this.classList.add(re),r==="folder"&&this.classList.add(`${re}--folder`),d&&this.classList.add(`${re}--missing`),u&&this.classList.add(`${re}--access-gated`),c&&this.classList.add(`${re}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",l?"option":"listitem"),l?this.setAttribute("aria-selected",c?"true":"false"):this.removeAttribute("aria-selected"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You donโ€™t have permission to open this โ€” ask the folder owner for access.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const v=[`${re}__visual`,`${re}__label`,`${re}__lock`];for(const g of v)this.querySelectorAll(`:scope > .${g}`).forEach(_=>_.remove());this.querySelectorAll(":scope > os-ribbon").forEach(g=>g.remove());const b=document.createElement("span");if(b.className=`${re}__visual`,i){const g=document.createElement("img");g.src=i,g.alt="",g.loading="lazy",g.decoding="async",g.className=`${re}__preview`,g.draggable=!1,b.appendChild(g)}else if(s){const g=Io(s,{title:o,className:`${re}__icon`});b.appendChild(g)}this.appendChild(b);const w=document.createElement("span");if(w.className=`${re}__label`,w.textContent=o,this.appendChild(w),u){const g=document.createElement("span");g.className=`${re}__lock dashicons dashicons-lock`,g.setAttribute("aria-hidden","true"),this.appendChild(g)}if(a&&a!=="publish"&&Gg[a]&&CO()){const g=document.createElement("os-ribbon");g.setAttribute("placement","top-end"),g.setAttribute("tone",NO(a)),g.textContent=Gg[a],this.appendChild(g)}Dy(this),T("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=LO();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,c=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-c.left,offsetY:o.clientY-c.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};Un.shadow=!1,Un.props=TO,Un.styles=[AO],Un.help=void 0;let Gc=Un;function NO(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}ro("os-tile",Gc);function OO(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=Z("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 DO(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(`${re}--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 zg(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:kt(e.file).title()}function RO(e,t){const n=kt(e.file),o=n.previewUrl(),s=zg(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:Gh(e.file.ref)||i||ks(Xb(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 xO(e,t){const n=OO(RO(e,t)),o=Z("os.files.tile-class",re,e);o&&o!==re&&(n.className=o);const s=Z("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=Hg(e),a=kt(r.file);if(r.accessGated){fe({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}Go(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),T("os.files.tile-rendered",{tile:n,placement:e}),n}function Vt(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const MO=ie("desktop-mode/tile-payload-handlers",()=>({handlers:new Map}));function Ko(){return MO.state.handlers}function zc(e,t){const n=Ko().get(e);return n?n.push(t):Ko().set(e,[t]),()=>{const o=Ko().get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&Ko().delete(e)}}function jc(e,t){const n=Ko().get(e);if(n)return n.find(o=>o.appliesTo(t))}function PO(e,t){return jc(e,t)?.acceptLabel}function WO(e,t){const n=jc(e.type,t);return n?n.accept(e.data,t):!1}function $O(e,t,n){const o=jc(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function UO(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&&gT(e,{actions:o,scope:"files.tile",dataset:{placementId:String(n.placementIds[0]??""),placementIds:n.placementIds.join(",")},onOpened:s=>{T("os.files.tile-menu.opened",{placementId:n.placementIds[0],placementIds:n.placementIds.slice(),items:s})},onClosed:()=>{T("os.files.tile-menu.closed",{})}})}function BO(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function Vc(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function Kc(e){const t=()=>{const n=e.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};t()||queueMicrotask(()=>void t())}const De="os-create-folder-dialog";let qo=null;function qc(){qo&&(qo.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),qo.remove(),qo=null,T("os.files.create-folder.closed",{}))}function Yc(e){if(qc(),Z("os.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${De}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=De,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${De}-title`);const i=document.createElement("h2");i.id=`${De}-title`,i.className=`${De}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${De}__field`,r.id=`${De}-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=`${De}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const c=document.createElement("div");c.className=`${De}__actions`;const l=document.createElement("os-button");l.className=`${De}__btn ${De}__btn--secondary`,l.setAttribute("variant","ghost"),l.textContent="Cancel";const d=document.createElement("os-button");d.className=`${De}__btn ${De}__btn--primary`,d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",c.appendChild(l),c.appendChild(d),s.appendChild(c),o.appendChild(s),document.body.appendChild(o),qo=o,Kc(r),T("os.files.create-folder.opened",{});const u=w=>{Vc(r,w),Vc(l,w),Vc(d,w),s.classList.toggle(`${De}--busy`,w)},f=w=>{a.textContent=w,a.hidden=!1},p=()=>{qc(),e.onCancel?.()},v=async()=>{const w=BO(r).trim();if(!w){f("Please enter a name."),Kc(r);return}a.hidden=!0,u(!0);try{await e.onSubmit(w),qc()}catch(g){u(!1),f(g instanceof Error?g.message:"Could not create the folder."),Kc(r)}};l.addEventListener("click",()=>p()),d.addEventListener("click",()=>void v()),o.addEventListener("click",w=>{w.target===o&&p()});const b=w=>{w.key==="Escape"?(w.preventDefault(),p()):w.key==="Enter"&&!w.isComposing&&(w.preventDefault(),v())};s.addEventListener("keydown",b),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",b)})}function Di(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function FO(e){return e.id<=0||Di(e)!==null}function jg(e){e.length!==0&&Nk(e)}function xn(e,t,n){Tp(e,t,n,"desktop-files")}function Ri(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 Xc(e,t){const n=window.wp?.os;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function Vg(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";te.removePlacement(t);try{await xc(t),xn(s,"trashed",[t]),Xc(`"${o}" moved to Trash`,async()=>{try{await Oi(t,"placement");const i=await Oe(n);te.setFolderPlacements(n,i.placements),xn(s,"untrashed",[t])}catch(i){console.error("[openstation] restore failed:",i)}})}catch(i){console.error("[openstation] deletePlacement failed:",i),Ri(i),Oe(n).then(r=>{te.setFolderPlacements(n,r.placements)})}}async function Kg(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";te.removePlacement(n),te.removeFolder(t);try{await Pc(t),xn("folder","trashed",[t]),Xc(`"${s}" moved to Trash`,async()=>{try{await Oi(t,"folder");const i=await Oe(o);te.setFolderPlacements(o,i.placements),xn("folder","untrashed",[t])}catch(i){console.error("[openstation] restore folder failed:",i)}})}catch(i){console.error("[openstation] deleteFolder failed:",i),Ri(i),Oe(o).then(r=>{te.setFolderPlacements(o,r.placements)})}}async function qg(e){if(e.length===0)return;if(e.length===1)return HO(e[0]);const t=new Set;for(const c of e)if(t.add(c.parentId),te.removePlacement(c.id),c.file?.type==="folder"){const l=parseInt(c.file.ref,10);l&&te.removeFolder(l)}const n=async()=>{for(const c of t)try{const l=await Oe(c);te.setFolderPlacements(c,l.placements)}catch(l){console.error("[openstation] files: re-hydrate failed:",l)}},o=await Promise.allSettled(e.map(async c=>{if(c.file?.type==="folder"){const l=parseInt(c.file.ref,10);if(!l)throw new Error("folder placement without a folder id");return await Pc(l),{id:l,kind:"folder",restoreId:l,restoreKind:"folder"}}return await xc(c.id),{id:c.id,kind:c.file?.type==="shortcut"?"shortcut":"placement",restoreId:c.id,restoreKind:"placement"}})),s=[];let i=0;for(const c of o)c.status==="fulfilled"?s.push(c.value):(i+=1,console.error("[openstation] trash (bulk) failed for one item:",c.reason));if(i>0&&n(),s.length===0){Ri(o.find(c=>c.status==="rejected")?.reason);return}for(const c of["placement","shortcut","folder"]){const l=s.filter(d=>d.kind===c).map(d=>d.id);l.length>0&&xn(c,"trashed",l)}const r=s.length===1?"item":"items",a=i>0?`${s.length} ${r} moved to Trash ยท ${i} could not be moved`:`${s.length} ${r} moved to Trash`;Xc(a,async()=>{const c=await Promise.allSettled(s.map(u=>Oi(u.restoreId,u.restoreKind)));await n();const l=s.filter((u,f)=>c[f].status==="fulfilled"),d=s.length-l.length;for(const u of c)u.status==="rejected"&&console.error("[openstation] restore (bulk) failed for one item:",u.reason);for(const u of["placement","shortcut","folder"]){const f=l.filter(p=>p.kind===u).map(p=>p.id);f.length>0&&xn(u,"untrashed",f)}d>0&&Ri(new Error(`${d} of ${s.length} items could not be restored.`))})}function HO(e){return e.file?.type==="folder"?Kg(e):Vg(e)}const GO=5,Yg=e=>qg(e);async function zO(e){if(!(e.length>GO&&!await Bo({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await Go(kt(t.file))}function jO(e){const t=parseInt(e.file.ref,10);t&&Yc({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 Wg(t,{name:o},r);te.upsertFolder(a);const c=await Oe(e.parentId);te.setFolderPlacements(e.parentId,c.placements)}catch(r){console.error("[openstation] rename folder failed:",r),te.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function VO(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=window.wp?.os?.myWordpress,s=(typeof e.file.postType=="string"?e.file.postType:"post")==="page"?"pages":"posts";n?.openDetail({entityId:s,postId:t,postTitle:e.file.title||`#${t}`})}function KO(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>zO(i),onClick:()=>{Go(kt(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>VO(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Renameโ€ฆ",icon:"dashicons-edit",sort:30,onClick:()=>jO(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:Yg,onClick:()=>Kg(e)});else{const i=Di(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:c=>`Hide ${c} items from desktop`,bulk:c=>{jg(c.map(l=>Di(l)??l.file.ref).filter(l=>!!l))},onClick:()=>jg([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:Yg,onClick:()=>Vg(e)})}const o=Z("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const At=16,Xg=88,Zg=104,qO=20,YO=16,Zc=Xg+qO,Jc=Zg+YO;function Yo(e,t){const n=Math.max(0,Math.round((e-At)/Zc)),o=Math.max(0,Math.round((t-At)/Jc));return Kt(n,o)}function Kt(e,t){return{col:e,row:t,x:At+e*Zc,y:At+t*Jc}}const XO=5,ZO=4;function Xo(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 JO(e){const t=Xo(e).height;return t<=0?XO:Math.max(1,Math.floor((t-At)/Jc))}function QO(e){const t=Xo(e).width;return t<=0?ZO:Math.max(1,Math.floor((t-At)/Zc))}const Jg=999;function xi(e,t="column",n){if(t==="row"){const s=QO(n);for(let i=0;i<Jg;i++)for(let r=0;r<s;r++)if(!e.has(ke(r,i)))return Kt(r,i);return Kt(0,0)}const o=JO(n);for(let s=0;s<Jg;s++)for(let i=0;i<o;i++)if(!e.has(ke(s,i)))return Kt(s,i);return Kt(0,0)}function Qg(e,t,n="column",o){const s=new Set(t),i=[];for(let r=0;r<e;r++){const a=xi(s,n,o);s.add(ke(a.col,a.row)),i.push(a)}return i}function It(e,t,n,o,s="column"){const i=Yo(e,t);return n.has(ke(i.col,i.row))?xi(n,s,o):i}function ew(e,t){const n=new Set;for(const o of e){const s=Yo(o.x,o.y);n.add(ke(s.col,s.row))}return n}function ke(e,t){return`${e},${t}`}function eD(e){const t=String(e),{placementsByFolder:n}=Ye().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 tD(e,t){const n=eD(e);if(n)return kt(n);const o=Ye().state.folders.get(e);return kt({type:"folder",ref:String(e),title:o?.name||t||"Folder",icon:QN,previewUrl:"",exists:!0})}function tw(e){return e instanceof Rc}function nD(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 nw(e){const t=nD(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{Go(tD(n,e.detail.current.parentName))}}),fe({message:t,action:o,duration:7e3})}const oD=ie("desktop-mode/canvas-payload-handlers",()=>({handlers:new Map}));function ow(){return oD.state.handlers}function sD(e,t){const n=ow().get(e.type);return n?n.accept(e.data,t):!1}function iD(e,t,n){const o=ow().get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function Mn(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function Mi(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}const sw="application/x-wp-media-attachment",iw="data-files-drop-active";function rw(){const e=window.wp?.os?.dragBridge;if(!e)return null;try{return e.getPayload()}catch{return null}}function aw(e){if(!e||typeof e.id!="number")return null;switch(e.kind){case"attachment":case"post":case"user":return{kind:e.kind,ref:String(e.id),title:e.title};default:return null}}function rD(e){if(!e)return null;let t="";try{t=e.getData(sw)}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 cw(e){const t=e.dataTransfer?.types,n=t?Array.from(t):[];return n.includes("Files")?!1:n.includes(sw)?!0:aw(rw())!==null}function lw(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 dw(e,t){if(!(e instanceof Element))return null;const n=e.closest(`.${re}`);return!(n instanceof HTMLElement)||!t.contains(n)?null:n.dataset.fileType==="folder"?n:null}function aD(e){const{host:t,container:n,folderId:o}=e;let s=null;const i=()=>{t.removeAttribute(iw),s&&(s.classList.remove(`${re}--drop-target`),s=null)},r=l=>{if(!cw(l))return;if(!lw(l.target,t,n)){i();return}l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="copy"),t.setAttribute(iw,"");const d=dw(l.target,n);d!==s&&(s?.classList.remove(`${re}--drop-target`),d?.classList.add(`${re}--drop-target`),s=d)},a=l=>{const d=l.relatedTarget;d instanceof Node&&t.contains(d)||i()},c=l=>{if(!cw(l))return;if(!lw(l.target,t,n)){i();return}i(),l.preventDefault(),l.stopPropagation();const d=aw(rw())??rD(l.dataTransfer);if(!d)return;const u=dw(l.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",c),()=>{i(),t.removeEventListener("dragover",r),t.removeEventListener("dragleave",a),t.removeEventListener("drop",c)}}function cD(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o}}function Zo(){return window.wp?.os?.dragManager??null}const lD="os-files-layer";function Pi(e){return e===0?"column":"row"}function dD(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function uw(e,t){return t!==0||!e?e:{get width(){return Ce(e).width},get height(){return Ce(e).height}}}function fw(e,t=0){const n=Pi(t),o=uw(e,t),s=document.createElement("div");s.className=lD,s.setAttribute("role","list"),s.dataset.folderId=String(t),e.appendChild(s);let i="";const r=I=>{const S=te.getState().placementsByFolder.get(t)??[],M=new Map;for(const D of S)D&&M.set(String(D.id),D);return I.map(D=>M.get(D)).filter(D=>!!D)},a=new Set,c=new Set,l=uT(s,{itemSelector:`.${re}`,background:e,surface:"files",scope:String(t),keyOf:I=>I.dataset.placementId??null,onChange:I=>{const S=r(I),M=S.length===1?S[0]:null;for(const D of a)try{D(M)}catch(U){console.error("[openstation] files: selection listener threw:",U)}for(const D of c)try{D(S)}catch(U){console.error("[openstation] files: selection listener threw:",U)}}}),d=()=>r(l.keys()),u=I=>{const S=new Map,M=new Set;let D=0;for(const H of I){if(!Re(H))continue;const W=Kt(0,D);S.set(H.id,{x:W.x,y:W.y}),M.add(ke(W.col,W.row)),D+=1}const U=new Map;for(const H of I){if(S.has(H.id))continue;const W=Yo(H.x,H.y),L=ke(W.col,W.row);if(!M.has(L)){M.add(L);continue}const z=It(H.x,H.y,M,o,n);M.add(ke(z.col,z.row)),U.set(H.id,{x:z.x,y:z.y})}return{pinnedSlots:S,displaced:U}},f=(I,S,M,D)=>{const U=M.get(S.id),H=D.get(S.id);U?Vt(I,U.x,U.y):H?Vt(I,H.x,H.y):Vt(I,S.x,S.y)},p=(I,S,M)=>{const D=xO(I,t),U=S.get(I.id);if(U){if(Vt(D,U.x,U.y),D.classList.add(`${re}--pinned`),ww(D,I,l,d),pw(I)){const W=Zo();W&&_.set(I.id,gw(W,D,I))}return D}const H=M.get(I.id);if(H&&Vt(D,H.x,H.y),gD(D,I,t,l,d),ww(D,I,l,d),I.file.type==="folder"){const W=parseInt(I.file.ref,10);if(W>0){const L=Zo();if(L){const z=mD(L,D,W);g.set(I.id,z)}}}else if(pw(I)){const W=Zo();W&&_.set(I.id,gw(W,D,I))}return D},v=I=>{const S=new Map;for(const H of s.querySelectorAll("[data-placement-id]")){const W=H.dataset.placementId??"",L=parseInt(W,10);if(W===""||Number.isNaN(L)&&W!=="-0")return!1;S.set(L,H)}const M=new Set;for(const H of I)M.add(H.id);for(const H of I){const W=S.get(H.id);if(!W)continue;if(W.dataset.fileType!==H.file.type||W.dataset.fileRef!==H.file.ref||W.classList.contains(`${re}--pinned`)!==Re(H))return!1}for(const[H,W]of S){if(M.has(H))continue;const L=g.get(H);if(L){try{L()}catch{}g.delete(H)}const z=_.get(H);if(z){try{z()}catch{}_.delete(H)}W.remove()}const{pinnedSlots:D,displaced:U}=u(I);for(const H of I){const W=S.get(H.id);if(W){f(W,H,D,U),mw(W,H);continue}s.appendChild(p(H,D,U))}return l.refresh(),T("os.files.grid-rendered",{folderId:t,count:I.length}),!0},b=I=>{const M=(I.placementsByFolder.get(t)??[]).slice().sort((W,L)=>{const z=Re(W)?0:1,R=Re(L)?0:1;return z-R}),D=uD(M);if(D===i||(i=D,hD(M,s,o,n))||v(M))return;s.replaceChildren();for(const[,W]of g)try{W()}catch{}g.clear();for(const[,W]of _)try{W()}catch{}_.clear();const{pinnedSlots:U,displaced:H}=u(M);for(const W of M)s.appendChild(p(W,U,H));l.refresh(),T("os.files.grid-rendered",{folderId:t,count:M.length})},w=[],g=new Map,_=new Map;let N=null,$=null;const C=I=>{if(N||I.payload.type!=="desktop-file")return;const S=document.createElement("div");S.className="os-files-drop-preview",S.setAttribute("aria-hidden","true"),s.appendChild(S),N=S;const M=I.payload.ghost,D=M?.offsetX??0,U=M?.offsetY??0,W=I.payload.data?.placement?.id,L=(ae,X)=>{const oe=s.getBoundingClientRect(),ce=Math.max(0,ae-oe.left-D),ge=Math.max(0,X-oe.top-U),Ue=te.getState().placementsByFolder.get(t)??[],Qi=$i(Ue,W),Me=It(ce,ge,Qi,o,n);S.style.transform=`translate3d(${Me.x}px, ${Me.y}px, 0)`},z=I.payload.source.getBoundingClientRect();L(z.left+D,z.top+U);const R=ae=>{L(ae.clientX,ae.clientY)};document.addEventListener("pointermove",R),$=R},V=()=>{$&&(document.removeEventListener("pointermove",$),$=null),N&&(N.remove(),N=null)},K={id:`os-files-canvas-${t}`,element:e,accept:I=>{if(I.type!=="desktop-file"&&I.type!=="shortcut")return sD(I,{folderId:t,host:e});if(t>0&&I.type==="desktop-file"){const S=I.data;for(const M of Mn(S)){if(M.file?.type!=="folder")continue;const D=parseInt(M.file.ref,10);if(!Number.isNaN(D)&&hw(D,t))return!1}}return!0},onEnter:I=>{e.setAttribute("data-files-drop-active",""),(I.payload.type==="desktop-file"||I.payload.type==="shortcut")&&C(I)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),V()},onDrop:(I,S)=>{if(e.removeAttribute("data-files-drop-active"),V(),I.payload.type!=="desktop-file"&&I.payload.type!=="shortcut"){iD(I,S,{folderId:t,host:e});return}const M=s.getBoundingClientRect(),D=I.payload.ghost,U=D?.offsetX??0,H=D?.offsetY??0,W=Math.max(0,S.clientX-M.left-U),L=Math.max(0,S.clientY-M.top-H),z=te.getState().placementsByFolder.get(t)??[];if(I.payload.type==="desktop-file"){const R=I.payload.data,ae=Mn(R),X=new Set(ae.map(ge=>ge.id)),oe=$i(z,X),ce=It(W,L,oe,o,n);oe.add(ke(ce.col,ce.row));for(const ge of ae){let Ue=ce;if(ge.id!==R.placement.id){const Me=ge.x-R.placement.x,Qt=ge.y-R.placement.y;Ue=It(Math.max(0,ce.x+Me),Math.max(0,ce.y+Qt),oe,o,n),oe.add(ke(Ue.col,Ue.row))}const Qi={...ge,x:Ue.x,y:Ue.y,parentId:t};if(te.upsertPlacement(Qi),T("os.files.tile-manually-placed",{folderId:t,placementId:ge.id}),Wi(ge)){const Me=Di(ge);Me&&pD(Me,Ue.x,Ue.y);continue}Dn(ge.id,{x:Ue.x,y:Ue.y,parentId:t},ge.updatedAtMs).then(Me=>{te.upsertPlacement(Me,"remote")}).catch(Me=>{tw(Me)?nw(Me):console.error("[openstation] files: drag persist failed",Me),te.upsertPlacement(ge)})}return}if(I.payload.type==="shortcut"){const R=I.payload.data;Qc(Mi(R),t,e)}}},j=Zo();if(j&&w.push(j.registerDropTarget(K)),w.push(aD({host:e,container:s,folderId:t,fileEntities:(I,S)=>{Qc(I,S,S===t?e:null)}})),!te.getState().hydratedFolders.has(t)){const I=dD(t);I&&te.setFolderPlacements(t,I)}b(te.getState()),queueMicrotask(()=>O());const F=te.subscribe(I=>{b(I),O()});let E=()=>{};const B=new Promise(I=>{E=I});te.getState().hydratedFolders.has(t)?queueMicrotask(E):Oe(t).then(I=>{te.setFolderPlacements(t,I.placements)}).catch(I=>{console.error("[openstation] files: failed to hydrate folder",t,I)}).finally(()=>{E()});const P=I=>{const S=new Set;for(let M=0;M<I;M+=1)S.add(ke(0,M));return S},h=(I,S)=>{const M=I.slice();switch(S){case"name-asc":M.sort((D,U)=>D.file.title.localeCompare(U.file.title));break;case"name-desc":M.sort((D,U)=>U.file.title.localeCompare(D.file.title));break;case"date-asc":M.sort((D,U)=>D.updatedAtMs-U.updatedAtMs);break;case"date-desc":M.sort((D,U)=>U.updatedAtMs-D.updatedAtMs);break}return M},A=I=>{const S=te.getState().placementsByFolder.get(t);if(!S||S.length===0)return;const M=S.filter(W=>Re(W)),D=S.filter(W=>!Re(W)),U=h(D,I),H=Qg(U.length,P(M.length),n,o);U.forEach((W,L)=>{const{x:z,y:R}=H[L],ae={...W,x:z,y:R,sortOrder:L};te.upsertPlacement(ae),!Wi(W)&&Dn(W.id,{x:z,y:R,sortOrder:L}).catch(X=>{console.error("[openstation] files: sort persist failed",X)})})},O=()=>{const I=te.getState().placementsByFolder.get(t);if(!I||I.length===0)return;const S=Xo(o),M=S.width>0?S.width:1/0,D=S.height>0?S.height:1/0;if(!I.some(z=>z.x+Xg>M||z.y+Zg>D))return;const H=I.filter(z=>Re(z)),W=I.filter(z=>!Re(z)),L=Qg(W.length,P(H.length),n,o);W.forEach((z,R)=>{const ae=s.querySelector(`[data-placement-id="${z.id}"]`);ae&&Vt(ae,L[R].x,L[R].y)})};let G=Xo(o),Y=null;return typeof ResizeObserver<"u"&&(Y=new ResizeObserver(()=>{const I=Xo(o);I.width===G.width&&I.height===G.height||(G=I,O())}),Y.observe(e)),{host:e,folderId:t,onSelectionChange(I){return a.add(I),()=>{a.delete(I)}},onSelectionChanged(I){return c.add(I),()=>{c.delete(I)}},getSelection:d,selectAll:()=>l.model.selectAll(),clearSelection:()=>l.model.clear(),sort:A,reflow:O,hydrated:B,dispose(){F(),Y?.disconnect(),Y=null;for(const I of w)try{I()}catch{}w.length=0;for(const I of g.values())try{I()}catch{}g.clear();for(const I of _.values())try{I()}catch{}_.clear(),l.destroy(),a.clear(),c.clear(),s.remove()}}}function uD(e){if(e.length===0)return"0";const t=[];for(const n of e)t.push(`${n.id}:${n.parentId}:${n.x}:${n.y}:${n.sortOrder}:${n.updatedAtMs}:${n.file.type}:${n.file.ref}:${n.file.title}:${n.file.icon}:${Re(n)?1:0}`);return t.join("|")}function Re(e){return!!e.file.pinned}function Wi(e){return FO(e)}const fD="desktop-mode-recycle-bin";function pw(e){return!(e.file?.type==="folder"||e.file?.ref===fD)}function $i(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,a)=>{const c=Re(r)?0:1,l=Re(a)?0:1;return c-l}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(Re(r))s.add(ke(0,i)),i+=1;else{const a=Yo(r.x,r.y);s.add(ke(a.col,a.row))}return s}function Qc(e,t,n){const o=te.getState().placementsByFolder.get(t)??[],s=$i(o),i=Pi(t);for(const r of e){const a=xi(s,i,uw(n,t));s.add(ke(a.col,a.row)),jo({parentId:t,type:r.kind,ref:r.ref,x:a.x,y:a.y}).then(c=>{te.upsertPlacement(c),T("os.files.shortcut-dropped",{folderId:t,placement:c})}).catch(c=>{console.error("[openstation] shortcut drop failed:",c)})}}function hw(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 c of a){if(c.file?.type!=="folder")continue;const l=parseInt(c.file.ref,10);Number.isNaN(l)||l<=0||n.has(l)||n.set(l,c.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 pD(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 hD(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(`${re}--pinned`)!==Re(d))return!1}const r=new Map,a=new Set;let c=0;for(const d of e){if(!Re(d))continue;const u=Kt(0,c);r.set(d.id,{x:u.x,y:u.y}),a.add(ke(u.col,u.row)),c+=1}const l=new Map;for(const d of e){if(r.has(d.id))continue;const u=Yo(d.x,d.y),f=ke(u.col,u.row);if(!a.has(f)){a.add(f);continue}const p=It(d.x,d.y,a,n,o);a.add(ke(p.col,p.row)),l.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)??l.get(d.id)??{x:d.x,y:d.y};Vt(u,f.x,f.y),mw(u,d)}return!0}function mw(e,t){const n=zg(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function gw(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?PO(s,o):void 0},accept:i=>(s=i.type,WO(i,o)),onEnter:()=>{t.classList.add(`${re}--drop-target`)},onLeave:()=>{t.classList.remove(`${re}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${re}--drop-target`),$O(i,r,o)}})}function mD(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 Mn(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||Wi(a))return!1;if(a.file.type==="folder"){const c=parseInt(a.file.ref,10);if(!Number.isNaN(c)&&hw(c,n))return!1}}}return!0},onEnter:()=>{t.classList.add(`${re}--drop-target`)},onLeave:()=>{t.classList.remove(`${re}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${re}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a=te.getState().placementsByFolder.get(n)??[],c=$i(a),l=Pi(n);for(const d of Mn(r)){const u=xi(c,l);c.add(ke(u.col,u.row)),te.upsertPlacement({...d,x:u.x,y:u.y,parentId:n}),Dn(d.id,{x:u.x,y:u.y,parentId:n},d.updatedAtMs).then(f=>{te.upsertPlacement(f,"remote")}).catch(f=>{tw(f)?nw(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;Qc(Mi(r),n)}}};return e.registerDropTarget(s)}function gD(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=Zo();if(!r)return;const c=te.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||c.x,parseFloat(e.style.top)||c.y;const l=o.model.has(String(c.id)),d=l?s():[],u=d.length>1&&d.some(f=>f.id===c.id)?d:[c];if(!l){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(c.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 b of f)b.classList.remove(`${re}--dragging`);f.length=0,document.removeEventListener("os.drag.start",v),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},v=()=>{for(const b of u){const w=e.parentElement?.querySelector(`[data-placement-id="${b.id}"]`);w&&w!==e&&(w.classList.add(`${re}--dragging`),f.push(w))}};document.addEventListener("os.drag.start",v),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:e,data:{placement:c,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:cD(c)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?DO(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 ww(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],c=Xm(a,KO);UO({x:s.clientX,y:s.clientY},c,{placementIds:a.map(l=>l.id)})})}function yw(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 Pn="os-folder-status-bar";function wD(e,t,n={}){const o=document.createElement("div");o.className=Pn,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const a=St().placementsByFolder.get(t)??[],c=a.filter(p=>p.file.type==="folder").length,l=a.length-c;let d=0;for(const p of a)if(p.file.type==="upload"){const v=Number(p.file.sizeBytes??0);Number.isFinite(v)&&v>0&&(d+=v)}const u={folderId:t,selectedCount:n.selection?.count()??0,totals:{files:l,folders:c,total:a.length,bytes:d}},f=yD(u);bD(o,f)};s();const i=Fc(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function yD(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:vw(n,"file","files")+(t>0?`, ${vw(t,"folder","folders")}`:"")+(o>0?` (${yw(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=Z("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function bD(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,c=typeof r.sort=="number"?r.sort:100;return a!==c?a-c: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(bw("start",o)),e.appendChild(bw("end",s))}function bw(e,t){const n=document.createElement("div");n.className=`${Pn}__cluster ${Pn}__cluster--${e}`;for(const o of t)n.appendChild(vD(o));return n}function vD(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${Pn}__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=`${Pn}__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=`${Pn}__label`,o.textContent=e.label,n.appendChild(o),n}function vw(e,t,n){return`${e} ${e===1?t:n}`}const Ui="os-icon-canvas-menu";let Jo=null,Bi=null,el=null,Qo=null,es=null;function ED(e,t){t.openOnBackgroundClick;const n=i=>{_D(i.target)||Ew(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(el===e&&Jo){qt();return}const a=kD(t),c=Z("os.icon-canvas.menu",a,t.scope),l=Array.isArray(c)?c:a,d=++o;gs(()=>d===o,()=>SD(l,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),qt()}}}function _D(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function Ew(e){return e instanceof Element?e.closest(`.${Ui}`)!==null:!1}function kD(e){const n=[{id:"sort-by",label:k("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:k("Name (A โ†’ Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:k("Name (Z โ†’ A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:k("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:k("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function _w(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 SD(e,t,n){if(qt(),e.length===0)return;el=n;const o=_w(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(Ui),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=kw(s,r);Fi(r)&&a.addEventListener("mouseenter",()=>{Sw(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,c=i.get(a.id);if(c){if(Fi(c)){r.stopPropagation();const l=s.querySelector(`[data-menu-item-id="${c.id}"]`);l&&Sw(c,l);return}qt(),c.onClick?.()}}),document.body.appendChild(s),Jo=s,cc(s),queueMicrotask(()=>{Qo=r=>{Ew(r.target)||qt()},es=r=>{r.key==="Escape"&&qt()},document.addEventListener("mousedown",Qo),document.addEventListener("keydown",es)})}function kw(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",AD(t.icon)),Fi(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function Sw(e,t){if(Aw(),!Fi(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(Ui,`${Ui}--flyout`);const o=new Map;for(const s of _w(e.children??[]))o.set(s.id,s),kw(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),qt(),r.onClick?.())}),document.body.appendChild(n),Bi=n,Qm(n,t)}function Fi(e){return Array.isArray(e.children)&&e.children.length>0}function Aw(){Bi&&(Bi.remove(),Bi=null)}function qt(){Aw(),Jo&&(Jo.remove(),Jo=null),el=null,Qo&&(document.removeEventListener("mousedown",Qo),Qo=null),es&&(document.removeEventListener("keydown",es),es=null)}function AD(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const Yt="os-breadcrumbs";function ID(e,t,n={}){if(e.replaceChildren(),e.classList.add(Yt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${Yt}__back`,s.setAttribute("aria-label",k("Back","desktop-mode")),s.title=k("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=`${Yt}__crumbs`,o.setAttribute("aria-label",k("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const c=document.createElement("span");c.className=`${Yt}__sep`,c.setAttribute("aria-hidden","true"),c.textContent="โ€บ",o.appendChild(c)}if(!s.onClick){const c=document.createElement("span");c.className=`${Yt}__crumb ${Yt}__crumb--current`,c.setAttribute("aria-current","page"),c.textContent=s.label,o.appendChild(c);return}const r=document.createElement("button");r.type="button",r.className=`${Yt}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}function Hi(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 ts(e,t={}){const n=await Be(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":CD(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function CD(){return window.wp?.os?.config?.restNonce??""}function LD(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function ns(e){return it(LD(),e)}function TD(e,t){const n=Z("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(ND(e));return}t.replaceChildren(FD()),OD(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(HD(o))})}function ND(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 OD(e){const t=e.file;switch(t.type){case"post":return DD(t.ref,t);case"folder":return $D(t);case"shortcut":return UD(t);case"attachment":return PD(t.ref,t);case"upload":return WD(t);case"user":return RD(t.ref,t);case"term":return xD(t);case"comment":return MD(t.ref,t);case"bookmark":return BD(t);default:return Xe(t)}}async function DD(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await ts(ns(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return Xe(t);const s=ot(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Gi(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(Iw(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 c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const l=window.wp?.os?.myWordpress;if(l){const u=document.createElement("os-button");u.setAttribute("variant","secondary"),u.textContent=k("Explore details","desktop-mode"),u.title=k("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),u.addEventListener("click",()=>{const f=typeof t.postType=="string"?t.postType:"post";l.openDetail({entityId:f==="page"?"pages":"posts",postId:n,postTitle:Gi(o.title.rendered)||`#${n}`})}),c.appendChild(u)}const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=k("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,b=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${b}-edit-${n}`,url:f,title:Gi(o.title.rendered),icon:t.icon})}),c.appendChild(d),s.appendChild(c),s}async function RD(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;try{o=await ts(ns(`desktop-mode/v1/user-stats/${n}`))}catch{return Xe(t)}const s=ot("os-my-wordpress__user"),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.profile.avatarUrl){const l=document.createElement("img");l.className="os-my-wordpress__user-avatar",l.src=o.profile.avatarUrl,l.alt="",i.appendChild(l)}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 l=document.createElement("div");l.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,l.appendChild(u)}r.appendChild(l)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const l=document.createElement("div");l.className="os-my-wordpress__user-bio",l.textContent=o.profile.description,s.appendChild(l)}const c=document.createElement("div");return c.className="os-my-wordpress__user-stats",c.appendChild(Wn(o.counts.posts.total.toLocaleString(),k("Posts","desktop-mode"))),c.appendChild(Wn(o.counts.pages.total.toLocaleString(),k("Pages","desktop-mode"))),c.appendChild(Wn(o.counts.commentsReceived.toLocaleString(),k("Comments received","desktop-mode"))),s.appendChild(c),s}async function xD(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return Xe(e);let o=null;try{o=await ts(ns(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return Xe(e)}const s=ot(),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 c=document.createElement("div");c.className="os-my-wordpress__article-content",c.innerHTML=o.profile.description,s.appendChild(c)}const a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(Wn(o.counts.posts.total.toLocaleString(),k("Posts","desktop-mode"))),a.appendChild(Wn(o.counts.commentsReceived.toLocaleString(),k("Comments","desktop-mode"))),a.appendChild(Wn(o.counts.distinctAuthors.toLocaleString(),k("Authors","desktop-mode"))),s.appendChild(a),s}async function MD(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;try{o=await ts(ns(`desktop-mode/v1/comment-stats/${n}`))}catch{return Xe(t)}const s=ot(),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 c=document.createElement("p");c.className="os-my-wordpress__article-meta",c.textContent=`${Iw(o.comment.date)} ยท ${o.comment.status}`,r.appendChild(c),i.appendChild(r),s.appendChild(i);const l=document.createElement("div");if(l.className="os-my-wordpress__article-content",l.innerHTML=o.comment.rendered,s.appendChild(l),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 PD(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;try{o=await ts(ns(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return Xe(t)}const s=ot(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Gi(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 c=o.media_details?.sizes;a.src=c?.large?.source_url??c?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),c=document.createElement("a");c.href=o.source_url,c.textContent=o.source_url,c.target="_blank",c.rel="noopener noreferrer",a.appendChild(c),s.appendChild(a)}return s}function WD(e){const t=ot(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("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?yw(s):""].filter(Boolean).join(" ยท "),t.appendChild(r);const a=parseInt(e.ref,10),c=()=>{const l=document.createElement("p");return l.className="os-my-wordpress__article-meta os-files__no-preview",l.textContent=k("No preview available for this file type.","desktop-mode"),l};if(a>0&&i==="image"){const l=document.createElement("img");l.className="os-my-wordpress__article-hero",l.src=zt(a),l.alt=e.title||"",l.addEventListener("error",()=>{l.replaceWith(c())}),t.appendChild(l)}else if(a>0&&i==="video"){const l=document.createElement("video");l.className="os-my-wordpress__article-hero",l.controls=!0,l.preload="metadata",l.src=zt(a),l.addEventListener("error",()=>{l.replaceWith(c())}),t.appendChild(l)}else if(a>0&&i==="audio"){const l=document.createElement("audio");l.controls=!0,l.preload="metadata",l.src=zt(a),l.style.width="100%",l.addEventListener("error",()=>{l.replaceWith(c())}),t.appendChild(l)}else t.appendChild(c());if(a>0){const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=k("Download","desktop-mode"),d.addEventListener("click",()=>{Hi(zt(a))}),l.appendChild(d),t.appendChild(l)}return t}function $D(e){const t=ot(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=k("Double-click to open.","desktop-mode"),t.appendChild(o),t}function UD(e){const t=ot(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=k("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function BD(e){const t=ot(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("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 Xe(e){const t=ot(),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=de(k("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=k("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function ot(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function Wn(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 FD(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function HD(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:k("Unknown error.","desktop-mode"),t}function Gi(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function Iw(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function Cw(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=k("Select an item to preview it here.","desktop-mode"),e}function GD(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=de(k("%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 zi="desktop-mode-embed-",zD=800,jD=600,tl=360,nl=240,ji=16,ol=new Map;function VD(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?`${zi}${s.id}`:`${zi}anon-${XD(n)}`,a=i?.name?.trim()??"",c=a!==""?a:e.title(),l={id:r,baseId:r,url:n,title:c,icon:e.icon(),minWidth:tl,minHeight:nl},d=i?.window,u=document.getElementById("os-area"),f=u?Ce(u):{x:0,y:0,width:window.innerWidth,height:window.innerHeight};if(d&&Number.isFinite(d.width)&&Number.isFinite(d.height)){const{x:p,y:v,width:b,height:w}=YD(d,f);l.x=p,l.y=v,l.width=b,l.height=w}else l.width=Math.min(zD,Math.max(tl,f.width-ji*2)),l.height=Math.min(jD,Math.max(nl,f.height-ji*2));s&&d&&ol.set(r,{...d}),o.open(l)}let Lw=!1;function KD(){if(Lw)return;Lw=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(zi))return;const s=o.slice(zi.length),i=parseInt(s,10);if(!i)return;const c=window.wp?.os?.windowManager?.getById?.(o)?.element;if(!c)return;const l={x:c.offsetLeft,y:c.offsetTop,width:c.offsetWidth,height:c.offsetHeight},d=ol.get(o);d&&d.x===l.x&&d.y===l.y&&d.width===l.width&&d.height===l.height||(ol.set(o,l),qD(i,l))};ne(m.WINDOW_DRAG_END,"os-embed-persist",e),ne(m.WINDOW_RESIZE_END,"os-embed-persist",e)}async function qD(e,t){try{const i={...(await Oe(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await Dn(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function YD(e,t){const n=Math.max(tl,Math.min(e.width,t.width-ji)),o=Math.max(nl,Math.min(e.height,t.height-ji)),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 XD(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 os(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function Tw(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 ZD(){We({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${os()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),We({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${os()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),We({id:"agent-chat",label:k("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;xg({id:Number.parseInt(t.ref,10),name:t.title,description:t.agentDescription??"",avatarUrl:t.previewUrl??""},"agents-open")}}}),We({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${os()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),We({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`${os()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),We({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${os()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),We({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&&Hi(zt(t))}}}),We({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(),c=r?`${a} ยท Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:c,icon:e.icon(),native:!0,render:l=>{l.replaceChildren(),l.classList.add("desktop-mode-folder-window"),io("desktop-mode-my-wordpress");const d=[{folderId:t,title:e.title()}];let u=null;const f=document.createElement("header");l.appendChild(f);const p=document.createElement("div");p.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",l.appendChild(p);const v=()=>{const w=d.map((g,_)=>_===d.length-1?{label:g.title}:{label:g.title,onClick:()=>{d.length=_+1,b()}});ID(f,w,{onBack:()=>{d.length<=1||(d.pop(),b())},backDisabled:d.length<=1})},b=()=>{u?.(),u=null,p.replaceChildren();const w=document.createElement("div");w.className="os-folder-window__split",p.appendChild(w);const g=document.createElement("div");g.className="os-folder-window__layer",w.appendChild(g);const _=document.createElement("div");_.className="os-folder-window__preview",_.appendChild(Cw()),w.appendChild(_);const N=d[d.length-1],$=fw(g,N.folderId),C=$.onSelectionChanged(F=>{if(F.length===0){_.replaceChildren(Cw());return}if(F.length>1){_.replaceChildren(GD(F));return}TD(F[0],_)}),V=F=>{if(!(F.target instanceof Element))return;const E=F.target.closest(".os-file-tile");if(!E||E.dataset.fileType!=="folder")return;const B=parseInt(E.dataset.fileRef??"",10);if(!B)return;F.preventDefault(),F.stopPropagation();const P=E.querySelector(".os-file-tile__label")?.textContent??`#${B}`;d.push({folderId:B,title:P}),b()};g.addEventListener("dblclick",V,!0);const K=ED(g,{scope:`os-folder:${N.folderId}`,onSort:F=>$.sort(F),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{Yc({onSubmit:async F=>{const E=await Mc({name:F}),B=te.getState().placementsByFolder.get(N.folderId)??[],P=ew(B),h=It(At,At,P,g,Pi(N.folderId)),A=await jo({type:"folder",ref:String(E.id),parentId:N.folderId,x:h.x,y:h.y});te.upsertFolder(E),te.upsertPlacement(A)}})}}]}),j=wD(p,N.folderId,{selection:{count:()=>$.getSelection().length,subscribe:F=>$.onSelectionChanged(()=>F())}});u=()=>{C(),K.dispose(),j.dispose(),g.removeEventListener("dblclick",V,!0),$.dispose()},v()};b()},width:720,height:480,minWidth:360,minHeight:240})}}}),We({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(Qe(o.toString()))return;const s=n.config?.adminUrl,i=s?le(o.toString(),s):`desktop-icon-${e.ref()}`,r=$h(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{}}}}}),We({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Tw(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),We({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Tw(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),We({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{VD(e,t)}}})}const JD="os-file-associations";let Xt=null;function QD(){wp({id:JD,label:"File Associations",order:50,render(e){Xt&&(Xt(),Xt=null),Nw(e),Xt=Cg(()=>{if(!e.isConnected){Xt&&(Xt(),Xt=null);return}Nw(e)})}})}function Nw(e){e.replaceChildren();const t=kg();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=Lc(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(eR(i.type,i.label,o));e.appendChild(s)}function eR(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=Tc(e);if(i.length===0){const l=document.createElement("span");return l.className="os-file-associations__none",l.textContent="No app available",o.appendChild(l),o}const r=Nc(e),a=n[e]??r?.id??"",c=document.createElement("os-select");c.setAttribute("value",a),c.setAttribute("aria-label",`Default app for ${t}`),c.className="os-file-associations__select",s.htmlFor=`assoc-${e}`,c.id=`assoc-${e}`;for(const l of i){const d=document.createElement("os-option");d.setAttribute("value",l.id),d.textContent=l.isDefault?`${l.label} (default)`:l.label,c.appendChild(d)}return c.addEventListener("os-pick",l=>{const d=l.detail?.value;if(!d)return;const u={...Lc(),[e]:d};Ag(u),$g(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(c),o}function tR(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,$c(t),!0)}function nR(){return window.openStationConfig?.filesOverlaysBundleUrl??""}async function ss(){if(window.openStationFilesOverlays)return window.openStationFilesOverlays;const e=nR();if(!e)return null;try{await ue(e)}catch(t){return console.warn("[openstation] files-overlays bundle failed to load",t),null}return window.openStationFilesOverlays??null}async function Ow(...e){await(await ss())?.openShareSettingsModal(...e)}async function oR(...e){await(await ss())?.openFileShareModal(...e)}async function sR(...e){return(await ss())?.openPendingFileInviteModal(...e)}async function iR(...e){return(await ss())?.openPendingInviteModal(...e)}function rR(...e){ss().then(t=>t?.openUrlDialog(...e))}function Dw(){return Number(window.openStationConfig?.currentUserId??0)}function aR(e){window.wp?.os?.windowManager?.getById?.(e)?.close?.()}function sl(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function Rw(e){const t=St().folders.get(e);return t?Number(t.ownerId):0}function xw(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function cR(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function lR(e){return Number(e.file.ownerId??0)}function dR(){Bn("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!sl())return e;const n=cR(t);if(n===null)return e;const o=Rw(n)||lR(t),s=Dw();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:()=>{Ow({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 Bo({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 Ug(n),Vo(t.id);try{const a=await Oe(0);jt(0,a.placements)}catch{}const r=`os-folder-${n}`;aR(r),fe({message:"You left the shared folder."})}catch(r){fe({message:`Could not leave: ${r.message}`})}}});return e}),ri({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!sl())return!1;const t=e.config.baseId??e.id,n=xw(t);return n===null?!1:Rw(n)===Dw()},onClick:e=>{if(!sl())return;const t=e.config.baseId??e.id,n=xw(t);n!==null&&Ow({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),ne("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 il=null;function Vi(){return il||(il=ie("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),il}function uR(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 Mw(e){const t=Vi(),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(uR(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 Ki(e,t={}){const n=Vi();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 Pw=new Set;function fR(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function pR(){const e=Vi(),t=n=>{if(fR()){for(const o of n.pending)if(!Pw.has(o.id)){if(Pw.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;sR({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?Ki(o.id):i==="denied"&&Ki(o.id,{denied:!0,fileId:s})});continue}iR({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Ki(o.id):s==="denied"&&Ki(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function hR(){return Number(window.openStationConfig?.currentUserId??0)}function Ww(){return window.openStationConfig?.desktopStorage??{}}function mR(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function gR(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function wR(){Bn("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&Ww().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:()=>{Hi(Fg(i))}}),e}const n=gR(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{Hi(zt(n))}});const o=Number(t.file.ownerId??0),s=hR();return o===s&&mR()?e.push({id:"desktop-mode/upload-share",label:"Share fileโ€ฆ",icon:"dashicons-share",sort:30,onClick:()=>{oR({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 Bo({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 Bg(n),Vo(t.id);try{const r=await Oe(0);jt(0,r.placements)}catch{}fe({message:"You left the shared file."})}catch(r){fe({message:`Could not leave: ${r.message}`})}}}),e}),Bn("os.wallpaper-context-menu","desktop-mode/uploads",e=>(Ww().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload filesโ€ฆ",icon:"dashicons-upload",sort:15,onClick:()=>$w(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folderโ€ฆ",icon:"dashicons-portfolio",sort:16,onClick:()=>$w(!0)})),e))}function $w(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&&yR(n,e)}),t.click()}async function yR(e,t){const n=window.openStationConfig?.fileDropBundleUrl;if(n){try{await ue(n)}catch{fe({message:"Upload machinery failed to load โ€” try again."});return}await window.openStationFileDrop?.routePickedFiles(e,t)}}eO(),ZD(),KD(),QD(),tR(),dR(),wR();const rl=window.openStationConfig?.serverPendingShares;Array.isArray(rl)&&rl.length>0&&Mw(rl),pR();const $e={DesktopFile:_g,registerType:He,unregisterType:KN,getType:qN,getTypes:kg,resolve:kt,subscribe:YN,registerOpener:We,unregisterOpener:XN,getOpener:ZN,getOpeners:Ig,getOpenersForType:Tc,resolveOpener:Nc,subscribeOpeners:Cg,getUserAssociations:Lc,open:Go,registerTilePayloadHandler:zc,rest:kO,store:{get:Ye,getState:St,subscribe:Fc,setFolderPlacements:jt,upsertPlacement:Wc,removePlacement:Vo,setFolders:$c,upsertFolder:Uc,removeFolder:Bc}},Uw="__synthFromDockItem";function bR(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function vR(e,t){const n=!!e.tile,o=t[e.id];return{id:bR(e.id),parentId:0,x:o?o.x:0,y:o?o.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Uw]: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 al=!1;const cl=new Map;function ER(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 _R(e,t,n={}){if(!al){al=!0;try{const s=$e.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[Uw]: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 c=new Map;for(const d of s){const u=d?.file?.ref;typeof u=="string"&&a.has(u)&&c.set(u,d)}for(const d of e)d.entry||r.has(d.id)||$e.store.upsertPlacement(vR(d,n));const l=[];for(const[d,u]of r)i.has(d)||($e.store.removePlacement(u.id),n[d]&&l.push(d));l.length>0&&ER(l);for(const d of t){const u=d.entry;if(!u)continue;const f=c.get(u.id);if(!i.has(d.id)){f&&(cl.set(u.id,f),$e.store.removePlacement(f.id));continue}if(!f){const p=cl.get(u.id);p&&($e.store.upsertPlacement(p),cl.delete(u.id))}}}finally{al=!1}}}function kR(e){queueMicrotask(e);const t=$e.store.subscribe(e),n="desktop-mode/shortcuts-sync";return ne(m.DOCK_ITEM_APPENDED,n,e),()=>{t(),Fn(m.DOCK_ITEM_APPENDED,n)}}const qi="os-note-created",SR="openstation_notes";function AR(e){if(!e.bundleUrl)return()=>{};let t=null;const n=[];let o=null;const s=()=>(t||(t=ue(e.bundleUrl).then(()=>{const a=window.openStationNotes;if(!a)return null;const c=a.boot({host:e.host,config:e.config,onError:e.onError});document.removeEventListener(qi,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(_e.START,r);for(const l of n.splice(0))document.dispatchEvent(l);return c}).catch(a=>(t=null,console.warn("[openstation] notes bundle failed to load",a),null))),t),i=a=>{n.push(new CustomEvent(qi,{detail:a.detail})),s()};document.addEventListener(qi,i);const r=()=>{s()};return window.addEventListener("dragstart",r,!0),document.addEventListener(_e.START,r),Bn("os.wallpaper-context-menu","desktop-mode/notes-sentinel",(a,c)=>{if(!Array.isArray(a)||a.some(u=>u.id==="new-note"))return a;const{x:l,y:d}=c??{x:0,y:0};return[...a,{id:"new-note",label:k("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{s().then(u=>{if(!u)return;const f=u.normalizedFromClient(l,d);u.createNoteAt({...f,focus:!0})})}}]}),e.hasNotes?(typeof requestIdleCallback=="function"?requestIdleCallback:c=>window.setTimeout(c,200))(()=>void s()):o=Te.subscribe(SR,a=>{a&&(o?.(),o=null,s())}),()=>{document.removeEventListener(qi,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(_e.START,r),o?.(),o=null}}const IR={id:"clock",get label(){return k("Clock")},get description(){return k("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 CR(){za(IR)}async function LR(){const e=window;if(e.openStationReleaseCard)return e.openStationReleaseCard;const t=e.openStationConfig?.releaseCardBundleUrl??"";if(!t)return null;try{await ue(t)}catch{return null}return e.openStationReleaseCard??null}function Bw(e,t){if(t){const o=k('WordPress %1$s "%2$s" is available.');return de(o,e,t)}const n=k("WordPress %s is available.");return de(n,e)}async function TR(e){const{update:t,openUrl:n}=e;if(!t||typeof t.version!="string"||!t.version||typeof t.url!="string"||!t.url)return;const o=t.version,s=typeof t.branch=="string"&&t.branch?t.branch:o,i=t.crossing===!0,a=`desktop-mode/core-update:${typeof t.available=="string"&&t.available?t.available:o}`;if(ui(a))return;const c=`${a}:no-art`,l=()=>n({url:t.url,title:k("WordPress Updates")}),u=e.resolveArt&&e.loadImage&&e.showCard?null:await LR(),f=e.resolveArt??u?.resolveReleaseArt,p=e.loadImage??u?.preloadImage,v=e.showCard??u?.showReleaseCard,b=f?await f(s,i):null;if(b&&b.artUrl&&p&&v&&await p(b.artUrl)){v({message:Bw(o,i?b.name:""),artUrl:b.artUrl,dismissKey:a,onUpdate:l});return}ui(c)||fe({message:Bw(o,""),persistent:!0,dismissible:!0,onDismiss:()=>fi(c),action:{label:k("Update now"),onClick:l}})}function Fw(e){const{notices:t,openUrl:n,keyPrefix:o="core-notice"}=e;if(Array.isArray(t))for(const s of t){if(!s||typeof s.id!="string"||!s.id||typeof s.message!="string"||!s.message)continue;const i=`desktop-mode/${o}:${s.id}`;if(ui(i))continue;const r=s.actionLabel,a=s.actionUrl,c=s.title||r||"";let l;r&&a&&(l={label:r,onClick:()=>n({url:a,title:c})}),fe({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>fi(i),action:l})}}const ll="desktop-mode/starter",NR="desktop-mode/dev-mode-gate";let Hw=!1;function OR({osSettings:e,layer:t}){if(Hw)return;Hw=!0,Bn(m.WIDGETS,NR,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==ll));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(ll):t.unmount(ll),pi())})}function DR(e){const{layer:t}=e,n=new Set,o=new Set,s=async l=>{if(!(!l.scriptUrl||o.has(l.scriptUrl))){try{await ue(l.scriptUrl,{translations:l.scriptTranslations,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter,deps:l.scriptDeps})}catch(d){T(m.SHELL_ERROR,{scope:"widget-script-load",id:l.id,error:d});return}o.add(l.scriptUrl)}},i=l=>(window.openStationWidgets||{})[l]??null,r=l=>({id:l.id,label:l.label,description:l.description,icon:l.icon,movable:l.movable,resizable:l.resizable,minWidth:l.minWidth||void 0,minHeight:l.minHeight||void 0,maxWidth:l.maxWidth||void 0,maxHeight:l.maxHeight||void 0,defaultWidth:l.defaultWidth||void 0,defaultHeight:l.defaultHeight||void 0,mount:async(d,u)=>{await s(l);const f=i(l.id);if(!f){const p=new Error(`[openstation] No mount callback on window.openStationWidgets["${l.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`);throw T(m.SHELL_ERROR,{scope:"widget-missing-mount",id:l.id,error:p}),p}return f(d,u)}}),a=async l=>{if(n.has(l.id))return;const d=r(l);try{za(d)}catch(u){T(m.SHELL_ERROR,{scope:"widget-register",id:l.id,error:u});return}n.add(l.id),pi(),t&&t.mountIfEnabled(l.id)},c=l=>{n.has(l)&&(t?.unmount(l),VA(l),n.delete(l),pi())};return async l=>{const d=new Set;for(const u of l)d.add(u.id);for(const u of Array.from(n))d.has(u)||c(u);for(const u of l)n.has(u.id)||await a(u)}}const Gw=new Set(Li),RR=2e3,dl=new Set,zw=new WeakSet;let jw=!1;function xR(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 c=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=c}}return s[o]}function MR(e){let t=null,n=1/0;for(const o of Gw){const s=xR(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function PR(e){return e.startsWith("os-")?e.slice(4):e}function WR(e,t){if(dl.has(e))return;if(dl.add(e),Gw.has(e)){const s=PR(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.
67
68 Fix โ€” side-effect-import the component module from wherever you render it:
69
70 import '<rel>/ui/components/${s}/${s}';
71
72 Or pull every os-* component in one go (heavier โ€” only do this from an entry bundle):
73
74 import '<rel>/ui/components';
75
76 See docs/components-reference.md for the full list.`,`
77 First offending element:`,t);return}const o=MR(e);if(o){console.error(`[wp.os] <${e}> is not a registered os-* component. Did you mean <${o}>?
78
79 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'.`,`
80 First offending element:`,t);return}console.error(`[wp.os] <${e}> looks like a os-* tag but no component by that name exists.
81
82 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.`,`
83 First offending element:`,t)}function Vw(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||dl.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||WR(t,e)},RR)}function Kw(e){e instanceof Element&&(Vw(e),e.shadowRoot&&Yi(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];Vw(o),o.shadowRoot&&Yi(o.shadowRoot)}}function Yi(e){if(zw.has(e))return;zw.add(e),Kw(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&&Kw(r)}}}).observe(e,{childList:!0,subtree:!0})}function $R(){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"&&Yi(s),s};n.__wpdPatched=!0,e.attachShadow=n}function UR(){jw||typeof document>"u"||(jw=!0,$R(),Yi(document))}const qw={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:3,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}},Q={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],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 ee(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function Yw(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 Xw(e,t){return typeof e=="boolean"?e:t}const BR=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function FR(e,t){return BR.includes(e)?e:t}function is(e,t=qw){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:ee(o.radius,t.appearance.radius,Q.radius),bodyColor:Yw(o.bodyColor,t.appearance.bodyColor),bodyAlpha:ee(o.bodyAlpha,t.appearance.bodyAlpha,Q.bodyAlpha),hueStart:ee(o.hueStart,t.appearance.hueStart,Q.hueStart),hueSpan:ee(o.hueSpan,t.appearance.hueSpan,Q.hueSpan),hueDrift:ee(o.hueDrift,t.appearance.hueDrift,Q.hueDrift),hueLoop:Xw(o.hueLoop,t.appearance.hueLoop),hueAngle:ee(o.hueAngle,t.appearance.hueAngle,Q.hueAngle),hueSpin:ee(o.hueSpin,t.appearance.hueSpin,Q.hueSpin),saturation:ee(o.saturation,t.appearance.saturation,Q.saturation),lightness:ee(o.lightness,t.appearance.lightness,Q.lightness),iridescence:ee(o.iridescence,t.appearance.iridescence,Q.iridescence),outlineWidth:ee(o.outlineWidth,t.appearance.outlineWidth,Q.outlineWidth),glow:ee(o.glow,t.appearance.glow,Q.glow),glowBlur:Xw(o.glowBlur,t.appearance.glowBlur),eyeColor:Yw(o.eyeColor,t.appearance.eyeColor),eyeScale:ee(o.eyeScale,t.appearance.eyeScale,Q.eyeScale)},r={points:Math.round(ee(s.points,t.physics.points,Q.points)),shapePreset:FR(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(ee(s.shapeLobes,t.physics.shapeLobes,Q.shapeLobes)),shapeAmount:ee(s.shapeAmount,t.physics.shapeAmount,Q.shapeAmount),shapeAngle:ee(s.shapeAngle,t.physics.shapeAngle,Q.shapeAngle),shapeShuffle:ee(s.shapeShuffle,t.physics.shapeShuffle,Q.shapeShuffle),radialStiffness:ee(s.radialStiffness,t.physics.radialStiffness,Q.radialStiffness),edgeStiffness:ee(s.edgeStiffness,t.physics.edgeStiffness,Q.edgeStiffness),bendStiffness:ee(s.bendStiffness,t.physics.bendStiffness,Q.bendStiffness),pressure:ee(s.pressure,t.physics.pressure,Q.pressure),damping:ee(s.damping,t.physics.damping,Q.damping),airDamping:ee(s.airDamping,t.physics.airDamping,Q.airDamping),magnetStrength:ee(s.magnetStrength,t.physics.magnetStrength,Q.magnetStrength),magnetRange:ee(s.magnetRange,t.physics.magnetRange,Q.magnetRange),magnetGrip:ee(s.magnetGrip,t.physics.magnetGrip,Q.magnetGrip),magnetDamping:ee(s.magnetDamping,t.physics.magnetDamping,Q.magnetDamping),floatAmplitude:ee(s.floatAmplitude,t.physics.floatAmplitude,Q.floatAmplitude),floatSpeed:ee(s.floatSpeed,t.physics.floatSpeed,Q.floatSpeed),idleWobble:ee(s.idleWobble,t.physics.idleWobble,Q.idleWobble),idleWobbleSpeed:ee(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,Q.idleWobbleSpeed),speedStretch:ee(s.speedStretch,t.physics.speedStretch,Q.speedStretch),friction:ee(s.friction,t.physics.friction,Q.friction),restitution:ee(s.restitution,t.physics.restitution,Q.restitution),dragStiffness:ee(s.dragStiffness,t.physics.dragStiffness,Q.dragStiffness),throwBoost:ee(s.throwBoost,t.physics.throwBoost,Q.throwBoost),minStretch:ee(s.minStretch,t.physics.minStretch,Q.minStretch),maxStretch:ee(s.maxStretch,t.physics.maxStretch,Q.maxStretch),minAngularGap:ee(s.minAngularGap,t.physics.minAngularGap,Q.minAngularGap),dragMaxAccel:ee(s.dragMaxAccel,t.physics.dragMaxAccel,Q.dragMaxAccel),limitIterations:Math.round(ee(s.limitIterations,t.physics.limitIterations,Q.limitIterations)),subStep:ee(s.subStep,t.physics.subStep,Q.subStep),maxSubSteps:Math.round(ee(s.maxSubSteps,t.physics.maxSubSteps,Q.maxSubSteps))};return{appearance:i,physics:r}}const Zw="desktop-mode-mio-position",Jw="os-mio",HR="os-mio-toggle",GR=`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
84 <defs><linearGradient id="mio" x1="19" y1="19" x2="5" y2="5" gradientUnits="userSpaceOnUse">
85 <stop offset="0" stop-color="#3f6dff"/><stop offset=".5" stop-color="#a855f7"/><stop offset="1" stop-color="#ff4fd8"/>
86 </linearGradient></defs>
87 <circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/>
88 <rect x="8" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/>
89 <rect x="13.1" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/>
90 </svg>`)}`;class zR{constructor(t){this.layer=null,this.handle=null,this.parked=null,this.generation=0,this.loading=null,this.look=qr(),this.options=t,this.enabled=t.enabled,this.look=af(t.savedLook),this.config=this.resolveConfig()}boot(){this.enabled&&this.mount()}api(){return{isEnabled:()=>this.enabled,enable:()=>this.setEnabled(!0),disable:()=>{this.setEnabled(!1)},toggle:()=>this.setEnabled(!this.enabled),getPosition:()=>this.handle?.getPosition()??null,setPosition:(t,n)=>this.handle?.setPosition(t,n),getConfig:()=>this.config,setConfig:t=>{this.config=is(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=B_(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=is({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=qr(),this.config=this.resolveConfig(),this.handle?.applyConfig(this.config),this.commitLook()}}}async setEnabled(t){t!==this.enabled&&(this.enabled=t,this.generation++,this.options.persist(t),T(t?"os.mio.enabled":"os.mio.disabled",{}),T(m.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount())}resolveConfig(){const t=is(this.options.serverConfig,qw),n=Z("os.mio.config",t),o=is(n,t);return is({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(Jw);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=Jw,n.className="os-mio",n.setAttribute("aria-hidden","true"),this.options.shell.appendChild(n),this.layer=n,n}async mount(){const t=this.generation;if(this.handle)return;const n=this.parked;if(n){this.parked=null,n.layer.style.removeProperty("display"),n.handle.applyConfig(this.config),n.handle.setAnimating(!0),this.handle=n.handle,this.layer=n.layer;return}try{await this.loadBundle()}catch(i){console.warn("[desktop-mode/mio] bundle failed to load.",i);return}if(t!==this.generation||!this.enabled)return;const o=window.openStationMountMio;if(typeof o!="function"){console.warn("[desktop-mode/mio] bundle loaded but did not publish window.openStationMountMio.");return}const s=await o({host:this.ensureLayer(),config:this.config,position:jR(),savePosition:Qw});if(!s){this.layer?.remove(),this.layer=null;return}if(t!==this.generation||!this.enabled){const i=this.layer;this.layer=null,s.setAnimating(!1),i?(i.style.display="none",this.parked={handle:s,layer:i}):s.destroy();return}this.handle=s}unmount(){const t=this.handle,n=this.layer;if(this.handle=null,this.layer=null,!t||!n){n?.remove();return}const o=t.getPosition();o&&Qw(o),t.setAnimating(!1),n.style.display="none",this.parked={handle:t,layer:n}}loadBundle(){if(typeof window.openStationMountMio=="function")return Promise.resolve();if(!this.loading){if(!this.options.bundleUrl)return Promise.reject(new Error("No Mio bundle URL in the shell config."));this.loading=ue(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function jR(){try{const e=window.localStorage.getItem(Zw);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 Qw(e){try{window.localStorage.setItem(Zw,JSON.stringify(e))}catch{}}const ey=8,VR=e=>`<rect x="28" y="5" width="8" height="12" rx="2" fill="currentColor" transform="rotate(${360/ey*e} 32 32)"/>`,KR='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'+Array.from({length:ey},(e,t)=>VR(t)).join("")+'<circle cx="32" cy="32" r="15.5" fill="none" stroke="currentColor" stroke-width="9"/></svg>',qR=`data:image/svg+xml;base64,${btoa(KR)}`,YR='<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>',XR=2400,ty="os-notch";function ZR(e,t){document.getElementById(ty)?.remove();const n=document.createElement("button");n.type="button",n.id=ty,n.className="os-notch",n.setAttribute("aria-label",k("Open the site assistant"));const o=document.createElement("span");o.className="os-notch__glyph",o.setAttribute("aria-hidden","true"),o.innerHTML=YR,n.appendChild(o);const s=document.createElement("span");s.className="os-notch__label",s.setAttribute("aria-hidden","true"),s.textContent=k("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=c=>{r!==null&&window.clearTimeout(r),i.textContent=c,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)},XR)};return e.appendChild(n),{say:a,destroy:()=>{r!==null&&window.clearTimeout(r),n.remove()}}}function JR(){return document.fullscreenElement!==null}function QR(){if(JR()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function ny(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 ex(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const l=document.createElement("h2");l.className="os-shortcuts__heading",l.textContent=e.heading,t.appendChild(l)}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 l of i){const d=document.createElement("th");d.scope="col",d.textContent=s[l]??"",a.appendChild(d)}r.appendChild(a),o.appendChild(r);const c=document.createElement("tbody");for(const l of e.rows??[]){const d=document.createElement("tr"),u=document.createElement("td");if(u.className="os-shortcuts__key-cell",u.appendChild(ny(l.keys??[])),l.note){const f=document.createElement("span");f.className="os-shortcuts__note",f.textContent=l.note,u.appendChild(f)}d.appendChild(u);for(const f of["outside","inside","showDesktop"]){const p=document.createElement("td");p.textContent=l[f]??"",d.appendChild(p)}c.appendChild(d)}return o.appendChild(c),n.appendChild(o),t.appendChild(n),t}function tx(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(ny(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 nx(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(ex(n.contextual)),n.general&&t.appendChild(tx(n.general)),e.appendChild(t)}const ul="openstation-shortcuts",ox=`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 sx(e){e({id:ul,baseId:ul,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:ox,native:!0,render:nx,width:760,height:560,minWidth:480,minHeight:360})}const oy="openstation-rebrand",ix=1200,rx="a[href], button:not([disabled])";async function ax(e){const t=e.seenIntrosUrl;if(t)try{await Be(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:oy})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function cx(){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(k("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=k("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=k("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",t.appendChild(a);const c=document.createElement("p");c.id="os-announce-desc",c.textContent=k("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(c);const l=document.createElement("p");l.textContent=k("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(l);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=k("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=k("Got it"),u.appendChild(f),e}async function lx(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(oy))return;await new Promise(l=>window.setTimeout(l,ix));const n=cx(),o=n.querySelector(".os-announce__card"),i=document.activeElement;let r=!1;const a=()=>{r||(r=!0,document.removeEventListener("keydown",c,!0),n.remove(),i?.focus?.(),ax(t))};function c(l){if(!n.isConnected){document.removeEventListener("keydown",c,!0);return}if(l.key==="Escape"){l.preventDefault(),a();return}if(l.key!=="Tab")return;const d=Array.from(n.querySelectorAll(rx));if(d.length===0)return;const u=d[0],f=d[d.length-1],p=n.ownerDocument.activeElement;l.shiftKey&&(p===u||!n.contains(p))?(l.preventDefault(),f.focus()):!l.shiftKey&&(p===f||!n.contains(p))&&(l.preventDefault(),u.focus())}n.addEventListener("click",l=>{o&&!o.contains(l.target)&&a()});for(const l of n.querySelectorAll("[data-rebrand-dismiss]"))l.addEventListener("click",a);document.addEventListener("keydown",c,!0),document.body.appendChild(n),n.querySelector(".os-announce__btn--primary")?.focus()}const dx=ie("desktop-mode/recycle-bin-payload-handlers",()=>({handlers:new Map}));function sy(){return dx.state.handlers}function ux(e){const t=sy().get(e.type);return t?t.accept(e.data):!1}function fx(e,t){const n=sy().get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}const px=new Set(["post"]);function iy(){const e=window.wp?.os?.myWordpress;return e&&typeof e.trashEntity=="function"?e:null}const fl="data-os-trash-drop-active",Zt="desktop-mode-recycle-bin",hx=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${Zt}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${Zt}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${Zt}"]`}];let ry=!1;const pl=new Map;let rs=null,ay=null;function mx(e){return e.payload.type==="desktop-file"}function gx(e){return e.payload.type==="shortcut"}function wx(e){if(!e.kind||!e.ref||!e.entityId||!px.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return!Number.isFinite(t)||t<=0?!1:iy()!==null}function cy(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:k("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=Mn(s);return r.length>1?r.every(a=>a.file?.ref!==Zt&&a.canTrash!==!1):i.file?.ref===Zt?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=Mi(s);return i.length>0&&i.every(r=>wx(r))}return ux(o)},onEnter:()=>{n.setAttribute(fl,"")},onLeave:()=>{n.removeAttribute(fl)},onDrop:(o,s)=>{if(n.removeAttribute(fl),mx(o)){qg(Mn(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&fx(o,s))&&gx(o)){const i=iy();if(!i?.trashEntity)return;const r=i.trashEntity,c=Mi(o.payload.data).map(l=>({entityId:l.entityId,ref:Number.parseInt(l.ref,10)})).filter(l=>!!l.entityId&&Number.isFinite(l.ref)&&l.ref>0);if(c.length===0)return;Promise.allSettled(c.map(l=>r(l.entityId,l.ref))).then(l=>{const d=l.filter(f=>f.status==="rejected");for(const f of d)console.error("[openstation] recycle-bin: shortcut trash failed:",f.reason);const u=c.length-d.length;(u>1||d.length>0)&&fe({message:d.length>0?`${u} moved to Trash ยท ${d.length} could not be moved`:`${u} items moved to Trash`,duration:d.length>0?6e3:4e3})})}}})}function yx(e){if(ry)return;ry=!0;const t=()=>{for(const{id:n,selector:o}of hx){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=pl.get(n);if(!i){r?.deregister(),pl.delete(n);continue}r&&r.el===i||(r?.deregister(),pl.set(n,{el:i,deregister:cy(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),ne(m.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),ne(m.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){ay=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;ay.observe(n,{childList:!0,subtree:!0})}ne(m.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==Zt)return;rs?.(),rs=null;const o=document.querySelector("[data-os-recycle-bin-root]");o instanceof HTMLElement&&(rs=cy(e,"recycle-bin-window",o))}),ne(m.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===Zt&&(rs?.(),rs=null)})}function hl(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function bx(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function ly(e){return{appliesTo(t){return hl(t)!==null},accept(t,n){const o=hl(n);if(!o)return!1;const s=Rg({type:e,data:t});return oO(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:k("Send to agent","desktop-mode"),onDrop(t,n,o){const s=hl(o);if(!s)return;const i=Rg({type:t.payload.type,data:t.payload.data}),r=bx();!i||!r||aO({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let dy=!1;function vx(){dy||(dy=!0,zc("shortcut",ly("shortcut")),zc("desktop-file",ly("desktop-file")))}let uy=!1,Jt=0;function Ex(){uy||(uy=!0,Te.contribute("openstation_files_subscribe",()=>{const e=St(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:Jt,sharesVersion:Vi().state.sharesVersion}}),Te.subscribe("openstation_files",e=>{_x(e)}))}function _x(e){const t=e.folders??[];for(const i of t)Uc(i,"remote"),i.updatedAtMs>Jt&&(Jt=i.updatedAtMs);const n=e.placements??[];for(const i of n)Wc(i,"remote"),i.updatedAtMs>Jt&&(Jt=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])Bc(i,"remote");for(const i of o.placements??[])Vo(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>Jt&&(Jt=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&Mw(s),e.truncated){const i=Array.from(St().hydratedFolders);for(const r of i)Oe(r).then(a=>{jt(r,a.placements)}).catch(()=>{})}}let fy=!1;const kx=[];function Sx(){if(fy)return;fy=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||Ax()};kx.push(yn("os.placement.changed",e),yn("os.shortcut.changed",e),yn("os.folder.changed",e))}function Ax(){Pg().then(t=>{$c(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from(St().hydratedFolders);for(const t of e)Oe(t).then(n=>{jt(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const as="os-wallpaper-menu";let $n=null;function py(){return $n!==null}let hy=0;function Ix(e,t,n,o={}){cs();const s=++hy;gs(()=>s===hy,()=>Cx(e,t,n,o))}function Cx(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,v=typeof f.sort=="number"?f.sort:100;return p!==v?p-v:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(as),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const c=()=>{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",my(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){l(u,f);return}c()}),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){c();return}const v=s.querySelector(`[data-menu-item-id="${p.id}"]`);v&&l(p,v);return}cs(),p.onClick(new MouseEvent("click"))}});function l(u,f){c();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(as,`${as}--flyout`),p.dataset.parentId=u.id;const v=(u.children??[]).slice().sort((b,w)=>{const g=typeof b.sort=="number"?b.sort:100,_=typeof w.sort=="number"?w.sort:100;return g!==_?g-_:b.label.localeCompare(w.label)});for(const b of v){const w=document.createElement("os-context-menu-option");w.dataset.menuItemId=b.id,w.setAttribute("value",b.id),b.icon&&w.setAttribute("icon",my(b.icon)),b.disabled&&w.setAttribute("disabled",""),b.checked&&w.setAttribute("checked",""),w.textContent=b.label,w.addEventListener("os-context-menu-pick",g=>{g.stopPropagation(),cs(),b.onClick(new MouseEvent("click"))}),p.appendChild(w)}document.body.appendChild(p),r=p,a=u,Qm(p,f)}e.appendChild(s),$n=s,cc(s);const d=Zm(s,{close:()=>cs(),siblingSelectors:[`.${as}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),T("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function cs(){$n&&(document.querySelectorAll(`.${as}--flyout`).forEach(e=>e.remove()),$n.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),$n.remove(),$n=null,T("os.wallpaper-menu.closed",{}))}function Lx(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=>Tx(i,e)),o=[...t,...n],s=Z("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function Tx(e,t){return{id:e.id,label:e.label,icon:e.icon,sort:e.sort,disabled:e.disabled,onClick:()=>{if(e.callbackId){const n=t.serverCallbacks?.[e.callbackId];if(typeof n=="function")return n()}T("os.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function my(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function ml(e){const t=e.dataTransfer?.types;return t?Array.from(t).includes("Files"):!1}function Nx(e){if(!e.bundleUrl)return()=>{};let t=null,n=!1;const o=[],s=()=>{window.removeEventListener("dragenter",r,!0),window.removeEventListener("dragover",a),window.removeEventListener("drop",c)},i=()=>(t||(t=ue(e.bundleUrl).then(()=>{const l=window.openStationFileDrop;if(l){l.boot(e.boot),n=!0,s();for(const d of o.splice(0))l.replayCapturedDrop(d)}}).catch(l=>{t=null,console.warn("[openstation] file-drop bundle failed to load",l),o.length>0&&(o.length=0,fe({message:k("That drop could not be processed โ€” please try again.","desktop-mode")}))})),t),r=l=>{ml(l)&&i()},a=l=>{!n&&ml(l)&&(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="copy"))},c=l=>{if(n||!ml(l))return;const d=l.defaultPrevented;l.preventDefault(),o.push({files:l.dataTransfer?Array.from(l.dataTransfer.files):[],clientX:l.clientX,clientY:l.clientY,target:l.target,alreadyClaimed:d}),i()};return window.addEventListener("dragenter",r,!0),window.addEventListener("dragover",a),window.addEventListener("drop",c),s}const gy=[];let gl=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(gl){Promise.resolve().then(o);return}gy.push(o)}},ready(o){n.whenReady(o)},isReady(){return gl}};t.wp.os=n})();const Xi="desktop-mode-os-settings";let wl=[],Zi=Number.POSITIVE_INFINITY,yl=!1;function ze(e,t=1500){if(wl.push(e),t<Zi&&(Zi=t),yl)return;yl=!0;const n=()=>{const o=wl;wl=[],Zi=Number.POSITIVE_INFINITY,yl=!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:Zi}):window.setTimeout(n,0)}function wy(){const e=window.openStationConfig;if(!e)return;const t=document.getElementById("os-area");if(!t)return;const n=new YE(t),o=document.getElementById("os-wallpaper"),s=e.pluginUrl||"";let i=null;o&&(i=new Zf(o,s));const r=document.getElementById("os-widgets");let a=null;CR(),Mk(),r&&(a=new vI(r,s)),Bf({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const c=new mS({mediaUrl:e.mediaUrl,restNonce:e.restNonce,canUpload:!!e.canUpload,isAdmin:!!e.currentUserIsAdmin,extendedOptions:e.extendedOptions??null,extendedOptionsUrl:e.extendedOptionsUrl??"",osSettingsPanelBundleUrl:e.osSettingsPanelBundleUrl??"",canManageDesktopThemes:!!e.canManageDesktopThemes,desktopThemesUrl:e.desktopThemesUrl??""},i??new Zf(document.createElement("div"),s));c.apply();const l=document.getElementById("os-shell"),d=new zR({shell:l??document.body,bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:c.state.mioEnabled,persist:y=>{c.state.mioEnabled=y,c.save()},savedLook:c.state.mioStyle,persistLook:y=>{c.state.mioStyle=y,c.save()}}),u=d.api();d.boot(),a&&OR({osSettings:c,layer:a});const f=new JI({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??"");f.attachAsk(oC({config:()=>e,fallbackContext:()=>({close:()=>f.close(),openInWindow:(y,x,q)=>{n.open({url:y,title:x,icon:q??"dashicons-admin-generic"})},confirm:y=>Bo({message:y})})}));const p=new JC,v=new hL;document.addEventListener(_e.START,y=>{const q=y.detail?.payload;if(!q||q.type!=="shortcut"&&q.type!=="desktop-file")return;const se=q.data?.bridgePayload;se&&p.start(se)}),document.addEventListener(_e.END,()=>{p.end()}),ze(()=>CL(v)),ze(()=>FL(n)),window.addEventListener("message",y=>{if(y.origin!==window.location.origin)return;const x=y.data;!x||x.type!=="os-drop-failed"||fe({message:"Could not insert into the editor."})}),Bm({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>f.open(),close:()=>f.close(),isOpen:()=>f.isOpen}),KL(),ZE(n),n_(n),ze(()=>{new NA({manager:n,adminUrl:e.adminUrl}).install(),OA(n);const y=new UA({manager:n,adminUrl:e.adminUrl});y.install(),document.addEventListener(yh,()=>y.install(),{once:!0})}),document.addEventListener("os-open-ai",()=>{oc("desktop-mode-ai-assistant")}),document.addEventListener("click",y=>{const x=y.target;!(x instanceof Element)||!x.closest("#wp-admin-bar-command-palette")||(y.preventDefault(),y.stopImmediatePropagation(),oc("desktop-mode-ai-assistant"))},!0);const b=document.getElementById("os-dock"),w=document.getElementById("os-shell"),g=w?.querySelector(".os-shell__body");let _=null,N=!1;const $=y=>y.some(x=>!!x.windowId&&n.getAllByBaseIdOnActiveDesktop(x.windowId).length>0),C=RI({manager:n,appendSystemTile:y=>_?.appendSystemTile(y),removeSystemTile:y=>_?.removeSystemTile(y)}),V=C.sync;a_({getSnapshot:()=>c.getOsSettingsSnapshot(),openById:(y,x)=>C.openById(y,x),adminUrl:e.adminUrl});const K=y=>{const x=le(y,e.adminUrl),q=_?_.getMenuItems():e.dockItems??[];for(const se of q){if(le(se.url,e.adminUrl)===x)return{title:se.title,icon:se.icon,url:se.url,submenu:se.submenu,selfLabel:se.selfLabel,multi:se.multi};for(const we of se.submenu??[])if(le(we.url,e.adminUrl)===x)return{title:we.title,icon:se.icon,url:se.url,multi:se.multi}}return null};if(A_({adminUrl:e.adminUrl,deriveSlug:y=>le(y,e.adminUrl),openWindow:y=>{n.open(y)},findDockEntry:K}),yt({id:"desktop-mode-dashboard",nativeWindowId:"desktop-mode-dashboard",matches:(y,x)=>d_(x),enabled:y=>y.stationHomeEnabled===!0}),yt({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(y,x)=>{if(!x.pathname.endsWith("/edit.php"))return!1;const q=x.searchParams.get("post_type");return!q||q==="post"},enabled:y=>y.nativePostsEnabled===!0}),yt({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(y,x)=>x.pathname.endsWith("/edit.php")?x.searchParams.get("post_type")==="page":!1,enabled:y=>y.nativePagesEnabled===!0}),yt({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(y,x)=>x.pathname.endsWith("/users.php"),enabled:y=>y.nativeUsersEnabled===!0}),yt({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(y,x)=>{if(r_(x))return!1;const q=x.pathname;return q.endsWith("/profile.php")?!0:q.endsWith("/user-edit.php")?x.searchParams.has("user_id"):!1},enabled:y=>y.nativeUsersEnabled===!0,onMatch:(y,x)=>{const q=parseInt(x.searchParams.get("user_id")??"0",10);q>0&&yS(q)}}),yt({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(y,x)=>x.pathname.endsWith("/edit-comments.php"),enabled:y=>y.nativeCommentsEnabled===!0,onMatch:(y,x)=>{const q=parseInt(x.searchParams.get("p")??"0",10);q>0?Yf(q):vS()}}),yt({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(y,x)=>{const q=x.pathname;return q.endsWith("/plugins.php")||q.endsWith("/plugin-install.php")},enabled:y=>y.nativePluginsEnabled===!0,onMatch:(y,x)=>{const q=x.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>Mx).then(se=>{se.setPluginsWindowTab(q)})}}),b&&w&&g&&e.dockItems){t.classList.add("os-area--with-dock");const y=c.getOsSettingsSnapshot(),x=y.desktopLayout,q=y.dockPlacement,se=be=>{jh(t,be,{openWindow:C.openById,manager:n,deriveWindowId:ve=>le(ve,e.adminUrl)})};_=qI({shellRoot:w,shellBody:g,bottomDockEl:b,desktopArea:t,windowManager:n,adminUrl:e.adminUrl,renderIcons:se,getSettings:()=>{const be=c.getOsSettingsSnapshot();return{navPlacement:be.navPlacement,navOrder:be.navOrder}}},x,e.dockItems,e.desktopIcons,q),NE({shell:w,shellBody:g,area:t}),W_({shellBody:g,getBehaviors:()=>({dock:c.state.dockBehavior,sidebar:c.state.sideDockBehavior})}),J0({bundleUrl:e.dockConstellationBundleUrl??"",deps:{windowManager:n,adminUrl:e.adminUrl,getMenuItems:()=>_?.getMenuItems()??[],getSystemItem:be=>_?.getSystemTile(be)??null}}),ZR(w,()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))});const we=GC(e.pwa?.appName||"WordPress",fe),ut={id:mv,title:"System",icon:wv,navKind:"control",placeable:!0,order:Is.system,onOpen:j,get submenu(){const be=[{title:"OpenStation Preferences",url:"",windowId:Xi,onSelect:()=>j()}];return e.homeUrl&&be.push({title:"View site",url:e.homeUrl}),be.push({title:"Fullscreen",url:"",onSelect:QR},{title:"Keyboard shortcuts",url:"",windowId:ul,onSelect:()=>sx(ve=>{n.open(ve)})},{title:"Report a bug",url:"",windowId:Do,onSelect:()=>F()}),!lm()&&!N&&be.push({title:we.title,url:"",onSelect:we.onOpen}),e.logoutUrl&&be.push({title:"Log out",url:"",onSelect:()=>{window.location.assign(e.logoutUrl)}}),be},isOpen:()=>$(ut.submenu??[])};_.appendSystemTile(ut),dm().then(be=>{N=be})}function j(y={}){const x={extended:"features",effects:"windows"},q=y.tabId?x[y.tabId]:void 0;q&&(y={...y,tabId:q}),y.tabId&&(c.activeTabId=y.tabId),n.open({id:Xi,baseId:Xi,url:"#os-settings",title:"OpenStation Preferences",icon:qR,native:!0,render:se=>c.renderPanel(se),width:820,height:720,minWidth:560,minHeight:480}),y.tabId&&c.focusTab(y.tabId)}function F(){io("desktop-mode-bug-report"),n.open({id:Do,baseId:Do,url:`#${Do}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:y=>_C(y),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("os-open-bug-report",()=>{F()}),_&&(_.appendSystemTile(bv()),_.appendSystemTile({id:HR,title:"Mio",icon:GR,navKind:"control",placeable:!0,order:Is.mio,isOpen:()=>u.isEnabled(),onOpen:()=>{u.toggle()}}),_.appendSystemTile({id:hv,title:"Overview",icon:gv,navKind:"control",placeable:!0,order:Is.overview,isOpen:()=>n._overviewActive,onOpen:()=>{n._overviewActive?n.exitOverview():n.enterOverview()}}));const E=_?.getPrimary()??null;V(Ph(Array.isArray(e.nativeWindows)?e.nativeWindows:[],e.nativeWindowScriptData));const B=VT(e.session);function P(y){return y==="desktop-mode-dashboard"&&c.getOsSettingsSnapshot().stationHomeEnabled!==!0?!1:y===Xi?(j(),!0):y===Do?(F(),!0):C.openById(y)}const h=typeof e.soloWindow=="string"?e.soloWindow:"";h&&queueMicrotask(()=>{if(P(h))return;const y=h.startsWith("os-game-")?h.slice(8):"";if(y){ip.launch(y).catch(x=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",x)});return}typeof console<"u"&&console.error(`[openstation] solo window "${h}" is not registered; nothing to paint.`)});const A=B&&!h?qT(n,e,t,P).catch(y=>{typeof console<"u"&&console.error("[openstation] session restore failed:",y)}):Promise.resolve(),O=e.defaultWindow?.enabled!==!1,G=e.defaultWindow?.url??"",Y=typeof G=="string"&&G.startsWith("native:");!h&&XT({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:B,defaultEnabled:O,isNativeDefault:Y})&&A.then(()=>YT(n,e).catch(y=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",y)}));const I=nN(n,e);sN(I);const S=async y=>{try{const x=await vc(n,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:y})},{source:"desktop-mode/default-window"});if(!x.ok)throw new Error(`HTTP ${x.status}`);const q=await x.json();e.defaultWindow=q,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:q}))}catch(x){T(m.SHELL_ERROR,{scope:"default-window-save",error:x}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",x)}};if(n.onToggleStartupRequested=y=>{const x=e.defaultWindow,q=!!y.config.native,se=q?`native:${y.id}`:y.getCurrentUrl(),we=q?x?.url===se:Ll(x?.url??"")===Ll(se),ut=!!x?.enabled&&we;S(ut?null:se)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!B&&Y){const y=G.slice(7);queueMicrotask(()=>{P(y)})}const M=y=>{_?.appendSystemTile(y)},D=DR({layer:a});D(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const U=zS({osSettings:c});U(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),ne(m.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",y=>{const x=y?.wallpapers;Array.isArray(x)&&U(x)});const H=VS();H(Array.isArray(e.serverGames)?e.serverGames:[]);const W=KS();W(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const L=a0();L(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const z=d0();z(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const R=m0();R(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const ae=E0();ae(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const X=F0();X(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const oe=V0();oe(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),X0({manager:n,osSettings:c}),Pv({osSettings:c}),k_({manager:n}),K0();{let y=!1;ne(m.WINDOW_LINK_GROUPS_CHANGED,"desktop-mode/window-link-visuals-sentinel",()=>{y||(y=!0,Gp().then(x=>{x&&window.openStationWindowLinkVisuals?.start({manager:n,osSettings:c})}).catch(()=>{y=!1}))})}A0({manager:n,openUrl:y=>{if(y.windowId&&C.openById(y.windowId,{source:"related-entities",...y.params?{params:y.params}:{}})||!y.url||Qe(y.url))return;const x=le(y.url,e.adminUrl);n.open({id:x,baseId:x,url:y.url,title:y.label,icon:y.icon||"dashicons-admin-links"})}}),W0({manager:n});const ce=Z0();ce(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),tA()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),sA(),iA()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),cA()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),uh(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),vA()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const Qt=SA(n);I0(n),ze(()=>C0()),o_(),ne("os.shell.toast","desktop-mode/shell-toast",y=>{!y||typeof y.message!="string"||fe({message:y.message,action:y.action,duration:y.duration})});const vl=e,Px=vl.recycleBinCount;aC(Number(Px)||0,typeof vl.recycleBinCountUrl=="string"?vl.recycleBinCountUrl:""),gC({getRecycleBinCount:rC}),window.__openStationConnectionBridge=Qt,ne(m.WINDOW_CLOSED,"desktop-mode/connection-cleanup",y=>{y?.windowId&&Qt.onWindowClosed(y.windowId)}),ne(m.IFRAME_READY,"desktop-mode/connection-rearm",y=>{y?.windowId&&Qt.onIframeReady(y.windowId)});const Wx=LI(n),$x=y=>{if(_){_.applyDesktopIcons(y);return}jh(t,y,{openWindow:C.openById,manager:n,deriveWindowId:x=>le(x,e.adminUrl)})},El=()=>{_&&_R(_.getNav().desktop,_.getNavItems(),c.getOsSettingsSnapshot().dockPromotedPositions)},Ux=jT({layoutDispatcher:_,desktopArea:t,config:e,syncNativeWindows:V,syncServerWidgets:D,syncServerWallpapers:U,syncServerCommands:L,syncServerSettingsTabs:z,syncServerTitleBarButtons:R,syncServerWindowActions:ae,syncServerUnfocusEffects:X,syncServerWindowLinkRenderers:oe,syncServerDockRailRenderers:ce,syncServerGames:H,syncServerDesktopThemes:W,renderIcons:$x,refreshRootPlacements:()=>{Oe(0).then(y=>{jt(0,y.placements)}).catch(()=>{})},syncShortcuts:El});document.addEventListener(Cf,()=>{_&&_.setLayout(_.getLayout());for(const y of n._stack)try{y.repaintWindowControls(),y.repaintThemedChrome()}catch(x){T(m.SHELL_ERROR,{scope:"desktop-theme-repaint",id:y.id,error:x})}}),c.subscribeOsSettings(y=>{if(!_)return;const x=_.getLayout(),q=_.getDockPlacement();_.setDockPlacement(y.dockPlacement),_.setLayout(y.desktopLayout),ps.dock=_.getPrimary(),ps.sideDock=_.getSide(),ps.desktopLayout=y.desktopLayout,ps.dockPlacement=_.getDockPlacement(),x===y.desktopLayout&&q===y.dockPlacement&&_.refresh(),El(),Eg(y.desktopLayout)}),kR(El),Eg(c.getOsSettingsSnapshot().desktopLayout);const ps=zN({manager:n,dock:E,layoutDispatcher:_,osSettings:c,iconsApi:HI,filesApi:$e,saveSession:I,widgetLayer:a,registerWindow:Wx,openWindowById:C.openById,openNewWindowById:C.openNewById,loadWindowScriptById:C.loadScriptById,placeSystemTile:M,setDefaultWindow:S,refreshMenu:Ux,openOsSettings:j,aiAssistant:f,dragBridge:p,dragManager:v,connect:Qt.connect,getConnection:Qt.getConnection,mio:u,wallpaperSuspend:{suspend:y=>i?.suspend(y),resume:y=>i?.resume(y),isSuspended:()=>i?.isSuspended()??!1},config:e});jN(ps),ze(()=>yx(v)),ze(()=>vx()),qS(),Nv(),e.gamesEnabled!==!1&&o0({currentUserId:Number(e.currentUserId)||0}),ze(()=>vT()),ze(()=>_T()),ze(()=>MT({currentUserId:Number(e.currentUserId)||0})),AR({bundleUrl:e.notesBundleUrl??"",hasNotes:!!e.hasNotes,host:t,config:e,onError:y=>{fe({message:y})}}),JN({openUrl:({id:y,url:x,title:q,icon:se})=>(Qe(x)||n.open({id:y,baseId:y,url:x,title:q,icon:se}),!0),openNativeWindow:y=>C.openById(y),deriveWindowId:y=>le(y,e.adminUrl)}),Ag(e.userFileAssociations??{}),TR({update:e.coreUpdate,openUrl:({url:y,title:x})=>{Qe(y)||n.open({id:"update-core",baseId:"update-core",url:y,title:x,icon:"dashicons-update"})}});const yy=({url:y,title:x})=>{if(Qe(y))return;const q=le(y,e.adminUrl);n.open({id:q,baseId:q,url:y,title:x,icon:"dashicons-info"})};if(Fw({notices:e.coreNotices,openUrl:yy}),Fw({notices:e.pluginNotices,openUrl:yy,keyPrefix:"plugin-notice"}),lx({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){Mg({baseUrl:e.filesUrl,nonce:e.restNonce});const y=document.getElementById("os-area");if(y){const x=fw(y,0),q=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},se=setTimeout(q,2e3);x.hydrated.then(()=>{clearTimeout(se),q()})}}ze(()=>Ex()),ze(()=>Sx()),ze(()=>XL()),T(m.COMPONENTS_REGISTERED,{tags:[...Li]}),GL(),KC(e,fe);const by=()=>{Py(e.shellOverlaysBundleUrl??""),xy(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(by,{timeout:1500}):window.setTimeout(by,0),T(m.INIT,{config:e}),gl=!0;const Bx=gy.splice(0);for(const y of Bx)try{y()}catch(x){T(m.SHELL_ERROR,{scope:"when-ready-cb",error:x}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",x)}c.apply(),a?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),a?.disposeAll()}),iN(),PT(n,e);const vy=(y,x=!0)=>{const q=$e.store.getState().placementsByFolder.get(0)??[],se=y(q),we=Ce(t),ut=Math.max(1,Math.floor((we.height-16)/110)),be=new Set;let ve=0;for(const je of se){const Ae=It(16+Math.floor(ve/ut)*96,16+ve%ut*110,be,we);be.add(`${Ae.col},${Ae.row}`),ve++,!(je.x===Ae.x&&je.y===Ae.y)&&($e.store.upsertPlacement({...je,x:Ae.x,y:Ae.y,sortOrder:ve}),!(!x||Wi(je))&&Dn(je.id,{x:Ae.x,y:Ae.y,sortOrder:ve}).catch(en=>{console.error("[openstation] relayout persist failed",en)}))}},Ey=y=>x=>{const q=x.slice();switch(y){case"name-asc":q.sort((se,we)=>se.file.title.localeCompare(we.file.title));break;case"name-desc":q.sort((se,we)=>we.file.title.localeCompare(se.file.title));break;case"date-asc":q.sort((se,we)=>se.updatedAtMs-we.updatedAtMs);break;case"date-desc":q.sort((se,we)=>we.updatedAtMs-se.updatedAtMs);break}return q},_l="desktop-mode:root-sort-mode",Fx=y=>y==="name-asc"||y==="name-desc"||y==="date-asc"||y==="date-desc";let er=(()=>{try{const y=window.localStorage.getItem(_l);return Fx(y)?y:null}catch{return null}})();const _y=y=>{er=y;try{y?window.localStorage.setItem(_l,y):window.localStorage.removeItem(_l)}catch{}};ne("os.files.tile-manually-placed","desktop-mode/root-sort-clear",y=>{y?.folderId===0&&_y(null)});{let y=Ce(t);const x=()=>{if(!er)return;const q=Ce(t);q.width===y.width&&q.height===y.height||(y=q,vy(Ey(er),!1))};typeof ResizeObserver<"u"&&new ResizeObserver(x).observe(t),Br(x)}let ky=!1;t.addEventListener("pointerdown",y=>{y.isPrimary&&(ky=y.target===t)}),t.addEventListener("click",y=>{c.state.showDesktopOnWallpaperClick&&y.target===t&&ky&&(t.classList.contains("os-area--overview")||py()||v.recentlyEndedDrag()||fT()||n.toggleShowDesktop())}),t.addEventListener("contextmenu",y=>{if(y.target!==t)return;y.preventDefault();const x=y.clientX,q=y.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(py()){cs();return}const se={x,y:q},we=()=>{const ve=t.getBoundingClientRect(),je=Math.max(0,se.x-ve.left),Ae=Math.max(0,se.y-ve.top),en=ew($e.store.getState().placementsByFolder.get(0)??[]);return It(je,Ae,en,Ce(t))},ut=(ve,je)=>{rR({title:ve,description:je,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:Ae,url:en})=>{const Sy=we(),Hx=await jo({type:"link",ref:en,parentId:0,x:Sy.x,y:Sy.y,meta:Ae?{name:Ae}:void 0});$e.store.upsertPlacement(Hx)}})},be=Lx({createFolder:()=>{Yc({onSubmit:async ve=>{const je=await Mc({name:ve}),Ae=we(),en=await jo({type:"folder",ref:String(je.id),parentId:0,x:Ae.x,y:Ae.y});$e.store.upsertFolder(je),$e.store.upsertPlacement(en)}})},createUrl:()=>ut("New URL","Opens the URL in a new browser tab."),addWidget:()=>a?.openPicker(),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>j(),sortIcons:ve=>{_y(ve),vy(Ey(ve))},currentSortMode:er,includeShowDesktop:!c.state.showDesktopOnWallpaperClick,position:{x,y:q},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??[]});Ix(document.body,{x,y:q},be)})()}),Nx({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:B}}))}UR(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",wy):wy();const Ox={tab:null,requestedAt:0};let Ji=null;function bl(){if(Ji)return Ji;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(Ji=t("desktop-mode/plugins-window/tab-target",()=>({...Ox})),Ji)}function Dx(e){const t=bl();if(t){t.state.tab=e,t.state.requestedAt=Date.now(),t.notify();return}const n=window;n._wpdPluginsWindowTab={tab:e,requestedAt:Date.now()}}function Rx(){const e=bl();if(e){const o=e.state.tab;return o!==null&&(e.state.tab=null,e.state.requestedAt=0,e.notify()),o}const t=window,n=t._wpdPluginsWindowTab;return n?(t._wpdPluginsWindowTab={tab:null,requestedAt:0},n.tab):null}function xx(e){const t=bl();return t?t.subscribe(n=>e({...n})):()=>{}}const Mx=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:Rx,setPluginsWindowTab:Dx,subscribePluginsWindowTab:xx},Symbol.toStringTag,{value:"Module"}));return tr.clampGeometryToViewport=yc,Object.defineProperty(tr,Symbol.toStringTag,{value:"Module"}),tr}({});
91