| @@ -1,248 +1,44 @@ | ||
| 1 | -var openStation=function(_r){"use strict";var Er=typeof document<"u"?document.currentScript:null;const Fb="desktop-mode-my-wordpress";function cd(){return window.wp?.os}async function Bb(){const e=cd();return typeof e?.loadWindowScript=="function"&&await e.loadWindowScript(Fb),cd()?.myWordpress}function Rs(e,t){return async(...n)=>{const o=await Bb();if(!o||o===t())return;const s=o[e];typeof s=="function"&&await s(...n)}}function Hb(){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:Rs("openDetail",s),openMedia:Rs("openMedia",s),openUserFootprint:Rs("openUserFootprint",s),trashEntity:Rs("trashEntity",s),registerEntityKind:(r,a)=>{const l={unregister:null},c={kind:r,renderer:a,slot:l};return o.push(c),()=>{if(l.unregister){l.unregister(),l.unregister=null;return}const d=o.indexOf(c);d!==-1&&o.splice(d,1)}},__pendingKinds:o};n.myWordpress=i}Hb();function Dt(){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 Xn(e,t,n,o){Dt().addFilter(e,t,n,o)}function Y(e,t,n,o){Dt().addAction(e,t,n,o)}function kr(e,t){return Dt().removeAction(e,t)}function q(e,t,...n){return Dt().applyFilters(e,t,...n)}function T(e,...t){Dt().doAction(e,...t)}function dd(e){return Dt().didAction(e)}function zb(){return Dt()}const v={INIT:"os.init",WALLPAPERS:"os.wallpapers",GAMES:"os.games",UNFOCUS_EFFECTS:"os.unfocus-effects",WINDOW_REVEALS:"os.window-reveals",WALLPAPER_MOUNTING:"os.wallpaper.mounting",WALLPAPER_MOUNTED:"os.wallpaper.mounted",WALLPAPER_UNMOUNTING:"os.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"os.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"os.wallpaper.visibility",WALLPAPER_SUSPEND:"os.wallpaper.suspend",WALLPAPER_PREVIEW_PARAMS:"os.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"os.wallpaper.settings-changed",IFRAME_READY:"os.iframe.ready",IFRAME_ERROR:"os.iframe.error",IFRAME_NETWORK_COMPLETED:"os.iframe.network-completed",SHELL_ERROR:"os.shell.error",BROADCAST:"os.broadcast",MONITOR_ENTRY:"os.monitor.entry",WALLPAPER_SURFACES:"os.wallpaper.surfaces",DESKTOP_THEME_CHANGED:"os.os-theme.changed",DESKTOP_THEME_ICON:"os.os-theme.icon",DESKTOP_THEME_ICON_COLOR:"os.os-theme.icon-color",WALLPAPERS_SERVER_CHANGED:"os.wallpapers.server-changed",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",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",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 Gb=0;function ud(e){if(dd(v.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++Gb}`;Y(v.INIT,t,e)}function jb(){return dd(v.INIT)>0}const fd=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"];fd.filter(e=>e!=="p");function pd(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 ce(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 l of fd){const c=n.searchParams.get(l);c&&r.set(l,c)}const a=r.toString();return pd(a?`${i}?${a}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),pd(o)}function hd(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function Vb(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 md(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 Os(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 gd(e){if(typeof e!="string"||e===""||typeof DOMParser>"u")return"";let t;try{t=new DOMParser().parseFromString(e,"image/svg+xml")}catch{return""}const n=t.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||t.getElementsByTagName("parsererror").length>0)return"";const o=new Set(["script","style","foreignobject","iframe","object","embed"]),s=i=>{const r=Array.from(i.children);for(const a of r){if(o.has(a.nodeName.toLowerCase())){a.remove();continue}for(const l of Array.from(a.attributes)){const c=l.name.toLowerCase(),d=l.value.trim().toLowerCase();if(c.startsWith("on")){a.removeAttribute(l.name);continue}d.startsWith("javascript:")&&a.removeAttribute(l.name)}s(a)}};s(n);for(const i of Array.from(n.attributes)){const r=i.name.toLowerCase(),a=i.value.trim().toLowerCase();(r.startsWith("on")||a.startsWith("javascript:"))&&n.removeAttribute(i.name)}return n.outerHTML}let nn=null;function Ms(){return!!window.openStationWindowSystem}function wd(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 qb(){return window.openStationConfig?.windowSystemBundleUrl??""}function Kb(e){!e||Ms()||nn||(nn=wd(e).catch(t=>{nn=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function Yb(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=wd(e)),await nn,window.openStationWindowSystem}let on=null;function Zn(){return!!window.openStationShellOverlays}function yd(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(Zn()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){Zn()?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 Xb(e){!e||Zn()||on||(on=yd(e).catch(t=>{on=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function Sr(e){return Zn()||!e?Promise.resolve():(on||(on=yd(e)),on)}function Ar(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function Ps(e,t){const n=Ar();if(Zn()||!n){t();return}Sr(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const bd="desktop-mode";function Cr(){return window.wp?.i18n}function E(e,t=bd){return Cr()?.__(e,t)??e}function sn(e,t,n,o=bd){return Cr()?._n(e,t,n,o)??(n===1?e:t)}function de(e,...t){const n=Cr()?.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]??"")})}function Zb(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 Jb(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 Qb(e,t,n){if(e<=1)return{cols:1,rows:1};const o=t/Math.max(1,n),s=6;let i={cols:e,rows:1,score:1/0};for(let r=1;r<=Math.min(s,e);r++){const a=Math.min(s,Math.ceil(e/r));if(r*a<e)continue;const l=t/r/Math.max(1,n/a),c=Math.abs(l-o),d=r*a-e,u=c+d*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function Ir(e,t,n=0){const o=e.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,l=34,c=(t.width-r*2-a*(s-1))/s,d=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-l);return e.map((f,p)=>{const g=p%s,m=Math.floor(p/s),h=t.left+r+g*(c+a),b=t.top+n+r+m*(d+a)+l,y=f.element.offsetWidth,I=f.element.offsetHeight,R=Math.min(c/y,u/I),k=y*R,M=I*R;return{win:f,x:h+(c-k)/2,y:b+(u-M)/2,scale:R}})}const ev=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],vd=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],tv=[...ev,...vd],_d={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 Ed(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function kd(e){return Object.prototype.hasOwnProperty.call(_d,e)?_d[e]:null}function nv(e){return kd(e)!==null}function rn(e,t={}){const n=kd(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="${Ed(s)}"`),i?a.push('role="img"',`aria-label="${Ed(i)}"`):a.push('aria-hidden="true"','focusable="false"');const l=r?`<g transform="rotate(${r} 12 12)">${n.b}</g>`:n.b;return`<svg ${a.join(" ")}>${l}</svg>`}function xr(e,t={}){const n=rn(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 ov(e,t={}){const n=rn(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const sv=Object.freeze({svg:rn,node:xr,dataUri:ov,names:Object.freeze([...tv]),ours:Object.freeze([...vd]),has:nv}),Sd=120,Ad="__openStationSharedStores";function iv(){const e=window;let t=e[Ad];return t||(t=new Map,e[Ad]=t),t}function le(e,t){const n=iv();let o=n.get(e);o||(o={state:t(),listeners:new Set,rebuild:t},n.set(e,o));const s={get state(){return o.state},set state(i){o.state=i},getState(){return o.state},notify(){for(const i of Array.from(o.listeners))try{i(o.state)}catch(r){console.error(`[desktop-mode/shared-store:${e}] subscriber threw:`,r)}},subscribe(i){return o.listeners.add(i),()=>{o.listeners.delete(i)}},setState(i){const r=o.state;if(typeof r!="object"||r===null){console.warn(`[desktop-mode/shared-store:${e}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(r,i),s.notify()},reset(){const i=o.rebuild(),r=o.state;if(typeof r=="object"&&r!==null&&typeof i=="object"&&i!==null){const a=r;for(const l of Object.keys(a))delete a[l];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}const Jn=le("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),lt=Jn.state.registry,Lr=Jn.state.listeners,rv=/^[a-z0-9_-]+$/;function Cd(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!rv.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).`);lt.set(e.id,e),Ws()}function av(e){lt.delete(e)&&Ws()}function lv(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(lt.entries()))o.owner===e&&(lt.delete(n),t++);return t>0&&Ws(),t}function cv(e){return lt.get(e)}function dv(){return Array.from(lt.values())}function uv(e){return Lr.add(e),()=>{Lr.delete(e)}}function fv(e){Jn.state.activeId!==e&&(Jn.state.activeId=e,Ws())}function Tr(){return lt.get(Jn.state.activeId)??lt.get("default")??lt.values().next().value}function Ws(){const e=Array.from(Lr);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function Rt(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 pv extends Error{constructor(t,n,o){super(`[openstation] ${t} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=t,this.errors=n,this.def=o}}function Ne(e,t,n){if(t.length!==0)throw new pv(e,t,n)}function Id(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const bt=[[0,0],[100,0],[100,100],[0,100]],hv=48,mv=80,Nr=6,Dr=8,xd=4,Ld=3,Td=64,Rr=105,vt=2;function Nd(e){return`${Math.round(e*1e3)/1e3}%`}function _t(e){return e.slice().reverse()}function Qn(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function gv(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 tt(e,t=[]){const n=[],o=s=>{n.push(`${Nd(s[0])} ${Nd(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 Dd(e){return tt(bt,[_t(gv(50,50,e,hv))])}function Rd(e){return tt(bt,[_t(Qn(50-e,-vt,50+e,100+vt))])}function Od(e){const t=100/Nr,n=[];for(let o=0;o<Nr;o++){const s=o*t;n.push(_t(Qn(-vt,s,100+vt,s+e)))}return tt(bt,n)}function Md(e){return tt(bt,[_t(Qn(-vt,50-e,100+vt,50+e))])}function Pd(e){const t=100/Dr,n=[];for(let o=0;o<Dr;o++){const s=o*t;n.push(_t(Qn(s,-vt,s+e,100+vt)))}return tt(bt,n)}function Wd(e){return tt(bt,[_t([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function $d(e){const t=100/xd,n=100/Ld,o=[];for(let s=0;s<Ld;s++)for(let i=0;i<xd;i++){const r=i*t+t/2,a=s*n+n/2,l=t/2*e,c=n/2*e;o.push(_t(Qn(r-l,a-c,r+l,a+c)))}return tt(bt,o)}function Ud(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<Td;s++){const i=t+s/(Td-1)*n;o.push([50+Math.cos(i)*Rr,50+Math.sin(i)*Rr])}return tt(bt,[_t(o)])}function wv(){return{from:Dd(0),to:Dd(mv)}}function yv(){return{from:Rd(0),to:Rd(52)}}function bv(){return{from:Od(0),to:Od(100/Nr+.5)}}function vv(){return{from:Md(0),to:Md(52)}}function _v(){return{from:Pd(0),to:Pd(100/Dr+.5)}}function Ev(){return{from:Wd(0),to:Wd(Rr)}}function kv(){return{from:$d(0),to:$d(1.04)}}function Sv(){return{from:Ud(0),to:Ud(360)}}function Av(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function Cv(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function Iv(){return{from:tt([[-60,0],[100,0],[100,100],[0,100]]),to:tt([[100,0],[260,0],[260,100],[160,100]])}}const Or=6,Mr=100,an=Mr/2,$s=200,Fd=90,Bd=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],xv="#101014",Lv=1.25,ln="http://www.w3.org/2000/svg";let Tv=0;function Us(e){return Math.round(e*1e3)/1e3}function Pr(e){return e/Or*Math.PI*2-Math.PI/2}function Nv(e){const n=Pr(e)+Math.PI/Or+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function Dv(e){const t=Pr(e),n=Pr(e+1);return[[an,an],[an+Math.cos(t)*$s,an+Math.sin(t)*$s],[an+Math.cos(n)*$s,an+Math.sin(n)*$s]]}function Hd(e,t){const n=Dv(e),o=document.createElementNS(ln,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${Us(s)} ${Us(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",Bd[e%Bd.length]),o.setAttribute("stroke",xv),o.setAttribute("stroke-width",String(Lv)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function Rv(){const e=`os-iris-${++Tv}`,t=document.createElementNS(ln,"svg");t.setAttribute("viewBox",`0 0 ${Mr} ${Mr}`),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(ln,"defs"),o=document.createElementNS(ln,"mask");o.setAttribute("id",e);const s=document.createElementNS(ln,"g"),i=document.createElementNS(ln,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let l=0;l<Or;l++){const c=Hd(l,!0),d=Hd(l,!1);s.appendChild(c),i.appendChild(d),r.push({el:c,index:l},{el:d,index:l})}o.appendChild(s),n.appendChild(o),t.appendChild(n),t.appendChild(i);const a=document.createElement("div");return a.appendChild(t),{element:a,play:l=>r.map(({el:c,index:d})=>{const u=Nv(d),f=Us(u.x*Fd),p=Us(u.y*Fd);return c.animate([{transform:"translate( 0px, 0px )"},{transform:`translate( ${f}px, ${p}px )`}],{duration:l.duration,easing:l.easing,delay:l.delay,fill:"both"})})}}const eo="none",Ov=460,Mv="cubic-bezier( 0.33, 0, 0.2, 1 )",zd=80,Gd=4e3,Pv=70,Wv=600,jd=le("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),Fs=jd.state.registry,$v=jd.state.listeners,Vd=/^[a-z0-9_/-]+$/;function qd(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function Uv(e){return typeof e!="number"||!Number.isFinite(e)?Ov:Math.min(Gd,Math.max(zd,e))}const Wr=0;function Kd(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?Wr:Math.min(Gd,Math.max(zd,e))}function cn(e){return typeof e!="number"||!Number.isFinite(e)?Pv:Math.min(Wv,Math.max(0,e))}function Yd(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 Xd(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=qd(e.from),r=qd(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 Fv(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function Ue(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Vd.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===eo&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Vd} — 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(...Xd(r,`layers[ ${a} ]`))})):t.push(...Xd(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):Fv(e.easing)||t.push("easing (not an easing the browser can parse — `Element.animate()` would throw at play time, with the covering surface already over the window)"))}Ne("WindowReveal",t,e);const n=e.id.trim().toLowerCase();Fs.set(n,{...e,id:n}),Qd()}function Bv(e){Fs.delete(e.toLowerCase())&&Qd()}function Zd(){const e=Array.from(Fs.values()),t=q(v.WINDOW_REVEALS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-reveals` filter returned a non-array; falling back to registry list."),e)}function Jd(e){return Zd().find(t=>t.id===e)}function Hv(e){return Fs.has(e)}function Qd(){const e=Array.from($v);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Ue({id:"sweep",label:E("Sweep"),description:E("A straight edge travels across the window, uncovering the page behind it."),...Cv(),duration:420}),Ue({id:"iris",label:E("Iris"),description:E("The page opens out from the centre of the window, like a camera shutter."),...wv(),duration:520}),Ue({id:"curtain",label:E("Curtain"),description:E("Two panels part from the middle of the window and slide off the sides."),...yv(),duration:480}),Ue({id:"blinds",label:E("Blinds"),description:E("Six horizontal slats retract at once, letting the page through between them."),...bv(),duration:560}),Ue({id:"diagonal",label:E("Diagonal"),description:E("A slanted edge sweeps off the trailing corner of the window."),...Iv(),duration:460}),Ue({id:"rise",label:E("Rise"),description:E("The page rises into the window from the bottom edge upward."),...Av(),duration:440}),Ue({id:"shutter",label:E("Shutter"),description:E("Two panels part from the middle of the window and slide off the top and bottom."),...vv(),duration:480}),Ue({id:"slats",label:E("Slats"),description:E("Eight vertical slats retract at once, letting the page through between them."),..._v(),duration:560}),Ue({id:"diamond",label:E("Diamond"),description:E("The page opens out from the centre of the window through a growing rhombus."),...Ev(),duration:520}),Ue({id:"mosaic",label:E("Mosaic"),description:E("The page arrives as a grid of tiles, each opening out from its own centre."),...kv(),duration:600}),Ue({id:"obturator",label:E("Camera shutter"),description:E("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:Rv,duration:720,edgeLag:0}),Ue({id:"radar",label:E("Radar"),description:E("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...Sv(),duration:760});const eu="desktop-mode-os-settings",zv="custom-gradient",tu="custom-image",$r="galaxy",nu="custom",ou=[{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 Ur(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return ou;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:ou}function su(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:$r}const Fr=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],Br=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],Bs=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],Gv=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],jv=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],ee={wallpaper:$r,accent:"pulse",customAccent:"#f252fc",dockSize:"default",windowRadius:"round",adminBarMode:"hidden",desktopLayout:"unified",dockPlacement:"bottom",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,showDesktopOnWallpaperClick:!1,mioEnabled:!1,mioStyle:{appearance:{},physics:{}},showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,navPlacement:{},navOrder:[],dockPromotedPositions:{}},iu={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},ru=["dockRailRenderer","windowReveal","accent"],au={windowRevealDuration:{min:80,max:4e3}},Vv=/^[a-z0-9_-]+$/;[...Object.keys(iu),...ru,...Object.keys(au)];function lu(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries(iu)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of ru){const i=t[s];typeof i=="string"&&Vv.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(au)){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 qv(e){const t=lu(e);return typeof t.dockRailRenderer=="string"&&cv(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==eo&&!Hv(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!Ur().some(n=>n.id===t.accent)&&delete t.accent,t}const Kv=/^[a-z0-9_-]+$/,cu=128;function Yv(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function du(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!Kv.test(n))return null;const o={};if(t.icons&&typeof t.icons=="object"){let l=0;for(const[c,d]of Object.entries(t.icons)){if(l>=cu)break;c===""||!Yv(d)||(o[c]=d,l+=1)}}const s={};if(t.tokens&&typeof t.tokens=="object")for(const[l,c]of Object.entries(t.tokens))typeof c=="string"&&(s[l]=c);const i=[];if(Array.isArray(t.fonts))for(const l of t.fonts)typeof l=="string"&&l!==""&&i.push(l);const r={};if(t.iconColors&&typeof t.iconColors=="object"){let l=0;for(const[c,d]of Object.entries(t.iconColors)){if(l>=cu)break;c===""||typeof d!="string"||d===""||(r[c]=d,l+=1)}}const a=l=>typeof t[l]=="string"?t[l]:"";return{id:a("id")||n,slug:n,name:a("name")||n,version:a("version"),author:a("author"),description:a("description"),previewUrl:a("previewUrl"),cssUrl:a("cssUrl"),cssText:a("cssText"),tokens:s,fonts:i,icons:o,iconColors:r,recommendedOsSettings:lu(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload"}}function Xv(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=du(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const dn=le("desktop-mode/desktop-themes",Xv);function Hs(){return dn}function Zv(){return dn.getState().themes.slice()}function uu(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return dn.getState().themes.find(n=>n.slug===t||n.id===e)??null}function Hr(){return dn.getState().activeId}function Jv(e){const t=[];for(const n of e){const o=du(n);o&&t.push(o)}dn.setState({themes:t})}function Qv(e){return dn.subscribe(e)}function zs(e){const t=Hs().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=q(v.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function zr(e){const t=Hs().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=q(v.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?e_(o):null}function e_(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 Ot={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"},t_={"desktop-mode-os-settings":Ot.OS_SETTINGS,"desktop-mode-recycle-bin":Ot.RECYCLE_BIN,"desktop-mode-bug-report":Ot.BUG_REPORT,"os-exit":Ot.EXIT_OPENSTATION,"os-pwa-install":Ot.PWA_INSTALL};function Gs(e){if(typeof e!="string"||e==="")return"";const t=t_[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function n_(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Ot.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Ot?n:""}const fu=new Map,o_=new Map;function Gr(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 pu(e,t,n,o){const s={channel:n,windowId:t},i=Gr(e,t,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel subscriber for "${n}" threw:`,l)}const r=Gr(e,t,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel wildcard subscriber for "${t}" threw:`,l)}}function s_(e,t,n){const o=Gr(fu,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function i_(e,t,n){pu(fu,e,t,n)}function r_(e,t,n){pu(o_,e,t,n)}const hu=new Set,a_=new Set,mu=new Map;function l_(e){if(!hu.has(e)){hu.add(e);const t=mu.get(e);if(t){mu.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)}}}a_.delete(e)&&(T(v.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const c_="os.activity.";function jr(e){return c_+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let d_=0;const Ee={publish(e,t){T(jr(e),t)},subscribe(e,t){const n=`os/activity-sub/${++d_}`,o=jr(e);Y(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,kr(o,n))}},filter(e,t,...n){return q(jr(e),t,...n)}},u_=4e3,f_=200,p_=1200;function Q(e){const t=Ee.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return Ps(()=>!n,()=>{o=h_(t)}),()=>{n=!0,o&&o()}}function h_(e){const t=y_(),n=document.createElement("os-toast");n.textContent=e.message,e.action&&(n.setAttribute("action",e.action.label),n.addEventListener("os-toast-action",()=>{e.action?.onClick(),l()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{e.onDismiss?.(),l()})),t.appendChild(n);let o=!1,s=null,i=e.duration??u_,r=0;const a=()=>{s!==null&&(window.clearTimeout(s),s=null)},l=()=>{o||(o=!0,a(),w_(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),g_()},f_))},c=()=>{o||e.persistent||s!==null||(r=Date.now(),s=window.setTimeout(l,i))},d=()=>{s!==null&&(i=Math.max(0,i-(Date.now()-r)),a())};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),n.addEventListener("os-toast-hold",u=>{if(u.detail?.held){d();return}i=Math.max(i,p_),c()}),m_(n),c(),Ee.publish("os/toast-shown",{...e}),l}let js=null,to=0;function gu(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(js=t))}function m_(e){to===0&&document.addEventListener("focusin",gu,!0),to+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(js=n)}function g_(){to=Math.max(0,to-1),to===0&&document.removeEventListener("focusin",gu,!0)}function w_(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||js?.isConnected===!0&&js.focus()}function y_(){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 wu="X-WP-Nonce";function yu(e,t){const n=b_();if(!n)return t;const o=v_(e);if(!o||!__(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(wu)?t:(i.set(wu,n),{...t??{},headers:i})}function b_(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function v_(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 __(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Fe(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=yu(e,t);return fetch(e,s)}const E_="http://localhost/";function nt(e,t){const n=typeof window<"u"&&window.location?window.location.href:E_,o=new URL(e,n),s=t.replace(/^\/+/,""),i=s.indexOf("?"),r=i===-1?s:s.slice(0,i),a=i===-1?"":s.slice(i+1);if(o.searchParams.has("rest_route")){const l=o.searchParams.get("rest_route")??"/",c=l.endsWith("/")?l:l+"/";o.searchParams.set("rest_route",c+r)}else{const l=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=l+r}return a&&new URLSearchParams(a).forEach((c,d)=>{o.searchParams.append(d,c)}),o.toString()}const k_="os-overview",S_="os-system",Vs={mio:10,overview:20,system:30,exit:35},A_=`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>')}`,C_=`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>')}`,I_="os-exit";function x_(){return{id:I_,title:E("Exit OpenStation"),navKind:"control",locked:!0,order:Vs.exit,icon:"dashicons-exit",onOpen:()=>{L_()}}}async function L_(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Vr(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{}Vr(o)}function Vr(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const bu=800;function T_(e,t=bu){window.setTimeout(()=>{if(e){Vr(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const N_="desktop_mode_nonces",D_="desktop-mode/v1",R_=3e4,O_=3,un=le("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function vu(){return window.wp?.os?.config??{}}function M_(){const e=vu().restUrl;return e?nt(e,D_):null}function P_(){un.state.negativeConfirms=0}async function W_(){const e=un.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=O_)return;const t=M_();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<R_)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await Fe(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}$_()}catch{}finally{e.confirmInFlight=!1}}}function $_(){if(!un.state.exiting){un.state.exiting=!0,T_(vu().adminUrl||"");try{Q({message:E("OpenStation is no longer active. Returning to the WordPress dashboard…"),duration:bu})}catch{}}}function U_(){if(un.state.booted)return;un.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[N_]!==void 0){P_();return}W_()}})}const F_=0,qr=40,_u=250,B_=120,H_=250,no="os-window__loading",qs="os-window__loading--visible",Ks=le("desktop-mode/window-reveal-active",()=>({id:eo,duration:Wr}));function Eu(e){Ks.state.id=typeof e=="string"&&e!==""?e:eo}function z_(){const e=Ks.state.id;return!e||e===eo?null:Jd(e)??null}function ku(e){Ks.state.duration=Kd(e)}function G_(){return Ks.state.duration}function j_({osSettings:e}){const t=e.getOsSettingsSnapshot();Eu(t.windowReveal),ku(t.windowRevealDuration),e.subscribeOsSettings(n=>{Eu(n.windowReveal),ku(n.windowRevealDuration)})}const fn="os-window__reveal",oo="os-window__reveal--edge",V_="os-window__reveal--custom",Mt="os-window__body--revealing",Kr="data-os-reveal",Yr="data-os-reveal-layer",Et=new WeakMap,Su=le("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function Au(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const q_="--os-window-reveal-duration",K_="--os-window-reveal-edge-thickness";function Cu(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 Y_(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return Kd(Cu(window.getComputedStyle(e).getPropertyValue(q_)))}catch{return 0}}function X_(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function Z_(e,t){const n=X_(e,K_);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=Cu(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?cn(i):null}function Iu(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 J_(e,t){const n=Uv(t.duration),o=G_(),s=o!==Wr?o:Y_(e)||n,i=Z_(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 xu(e){return e.querySelector(":scope .os-window__body")}function Q_(e){return e.querySelector(`:scope .${fn}:not( .${oo} )`)}function eE(e){return e.querySelector(`:scope .${oo}`)}function Lu(e){return Array.from(e.querySelectorAll(`:scope .${fn}:not( .${oo} )`))}function Tu(e){return Array.from(e.querySelectorAll(`:scope .${oo}`))}function Xr(e){return Array.from(e.querySelectorAll(`:scope .${fn}`))}function Nu(e,t,n,o){const s=document.createElement("div");s.className=o?`${fn} ${oo}`:fn;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(Kr,e.id),s.setAttribute(Yr,String(n)),s.style.clipPath=t.from,s}function tE(){const e=z_();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(fn),s.classList.add(V_),s.setAttribute("aria-hidden","true"),s.setAttribute(Kr,e.id),s.setAttribute(Yr,"0"),Su.set(s,o.play),[s]}const t=Yd(e);if(t.length===0)return[];const n=[];return cn(e.edgeLag)>0&&t.forEach((o,s)=>n.push(Nu(e,o,s,!0))),t.forEach((o,s)=>n.push(Nu(e,o,s,!1))),n}function nE(e){const t=xu(e);if(t){t.classList.remove(Mt);for(const n of Xr(t))Et.get(n)?.cancel(),Et.delete(n),n.remove();for(const n of tE())t.appendChild(n)}}function Du(e){const t=xu(e);if(!t)return;const n=Q_(t);if(!n)return;let o;try{o=Jd(n.getAttribute(Kr)??"")}catch(k){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",k)}if(!o){Xr(t).forEach(k=>k.remove());return}const i=!!t.querySelector(`:scope .${no}`)?.classList.contains(qs)?_u:0,{duration:r,edgeLag:a}=J_(t,o),l=o.easing??Mv,c=Su.get(n);if(c){t.classList.add(Mt);const k=()=>{Et.delete(n),n.remove(),t.classList.remove(Mt)};if(Au()||typeof n.animate!="function"){window.setTimeout(k,i);return}let M=[];try{M=c({duration:r,easing:l,delay:i})}catch(P){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,P)}if(M.length===0){k();return}M[0].addEventListener("finish",k),M[0].addEventListener("cancel",()=>{Et.delete(n),t.classList.remove(Mt)}),Et.set(n,M[0]);return}const d=eE(t);d&&(a<=0||Iu(d))&&Tu(t).forEach(k=>k.remove()),Iu(n)&&Lu(t).forEach(k=>k.remove());const u=Xr(t);if(u.length===0)return;t.classList.add(Mt);const f=()=>{for(const k of u)Et.delete(k),k.remove();t.classList.remove(Mt)};if(Au()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,g=Yd(o),m=(k,M)=>{const P=g[Number(k.getAttribute(Yr))];if(!P)return k.remove(),null;k.style.willChange="clip-path";let W;try{W=k.animate([{clipPath:P.from},{clipPath:P.to}],{duration:M,easing:p,delay:i,fill:"both"})}catch(_){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,_),k.remove(),null}return Et.set(k,W),W},h=Lu(t).map(k=>m(k,r)).filter(k=>k!==null),b=Tu(t).map(k=>m(k,r+a)).filter(k=>k!==null),y=h[0]??null,I=b[0]??null;if(!y&&!I){f();return}(I??y)?.addEventListener("finish",f);const R=()=>{for(const k of u)Et.delete(k);t.classList.remove(Mt)};y?.addEventListener("cancel",R),I?.addEventListener("cancel",R)}const oE="os-window-tab-change";function Ru(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function Ou(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function Mu(e,t){return`${e.id||"os-window"}-tab-${Ou(t)}`}function Pu(e,t){return`${e.id||"os-window"}-panel-${Ou(t)}`}function sE(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 iE(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 rE(e){const t=Ru(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 Wu(e){const t=new Map;for(const n of Ru(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function $u(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 aE(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of Wu(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 $u(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}rE(n),sE(n),e.dispatchEvent(new CustomEvent(oE,{bubbles:!0,detail:{value:t}}))}}function lE(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=Wu(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=Mu(e,d.value),u.setAttribute("aria-controls",Pu(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();iE(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of $u(e)){const u=d.getAttribute("for");u&&(d.id=Pu(e,u),a?d.setAttribute("aria-labelledby",Mu(e,u)):d.removeAttribute("aria-labelledby"))}const l=d=>d!==void 0&&t.some(u=>u.value===d),c=[n,i,t[0]?.value].find(l);c!==void 0&&aE(e,c)}const so="os-window__body--loading",Zr="os-window__body--loading-out",Jr="data-os-loading-at",Uu="data-os-loading-cycle";function Ys(e){return e.getAttribute(Uu)??"0"}function cE(e){e.setAttribute(Jr,String(Date.now())),e.setAttribute(Uu,String(Number(Ys(e))+1))}function dE(e,t){const n=Number(e.getAttribute(Jr)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=B_-o;if(s<=0){t.classList.add(qs);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(so)&&t.classList.add(qs)},s)}const uE=Symbol.for("desktop-mode/window-config");function fE(e){return e[uE]}function Qr(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function Fu(){const e=document.createElement("div");e.className=no,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",E("Loading window content")),e.appendChild(t),e}function pE(e){let t=Fu();const n={windowId:e.id,config:e};if(typeof e.loading?.render=="function")try{e.loading.render(t,n)}catch(o){typeof console<"u"&&console.error(`[openstation] loading.render threw for "${e.id}":`,o)}try{const o=q(v.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[openstation] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains(no)&&t.classList.add(no),t}function Bu(e){e.querySelector(":scope .os-window__loading")?.remove()}function Hu(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=fE(e),s=o?pE(o):Fu();t.appendChild(s),dE(t,s)}const zu=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],Xs="osHadFullscreenBeforeOverview";function Gu(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[Xs]="true",Qr()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function ju(e){if(e.element.dataset[Xs]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[Xs],Qr();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[Xs],Qr()}}function ea(e,t=!0){t&&ju(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function Vu(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function qu(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function hE(e){if(e._overviewActive)return;Ku(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,T(v.OVERVIEW_ENTERING,{});for(const c of zu){const d=document.getElementById(c);d&&(d.inert=!0)}Vu(!0),qu(e,!0),e._overviewSnapshot.clear();for(const c of t)e._overviewSnapshot.set(c.id,{transform:c.element.style.transform||"",transition:c.element.style.transition||""});for(const c of t)Gu(c);const n=e._desktop.getBoundingClientRect(),o=Array.from(document.querySelectorAll(".os-dock"));let s=0;for(const c of o){const d=c.getBoundingClientRect(),u=d.bottom>n.top&&d.top<n.bottom,f=d.height>d.width;u&&f&&(s+=d.width)}const i=new DOMRect(0,0,n.width+s,n.height);e._desktop.classList.add("os-area--overview"),document.getElementById("os-shell")?.classList.add("os-shell--overview"),e._overviewTopBar=Yu(e),e._desktop.appendChild(e._overviewTopBar);const a=Ir(t,i,Sd);e._overviewLabels.clear();for(const c of a){const d=c.win.element;d.classList.add("os-window--overview");const u=c.x-d.offsetLeft,f=c.y-d.offsetTop;d.style.transform=`translate(${u}px, ${f}px) scale(${c.scale})`;const p=na(c);d.insertAdjacentElement("afterend",p),e._overviewLabels.set(c.win.id,p)}const l=c=>{const d=c.target,u=d?.closest(".os-window--overview");return u?{id:u.id.replace(/^wp-window-/,""),element:u}:d===e._desktop?{id:"backdrop",element:e._desktop}:null};e._overviewPointerDownHandler=c=>{if(c.button!==0){e._overviewPressTarget=null;return}e._overviewPressTarget=l(c),e._overviewPressTarget&&(c.preventDefault(),c.stopPropagation())},e._overviewPointerUpHandler=c=>{if(c.button!==0)return;const d=e._overviewPressTarget;if(e._overviewPressTarget=null,!d)return;const u=d.element.getBoundingClientRect();if(!(c.clientX>=u.left&&c.clientX<=u.right&&c.clientY>=u.top&&c.clientY<=u.bottom))return;if(c.preventDefault(),c.stopPropagation(),d.id==="backdrop"){Pt(e);return}const p=e.getById(d.id);T(v.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),Pt(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){Pt(e);return}if(c.key==="Enter"){const u=c.target?.ownerDocument||document;if(u.activeElement&&u.activeElement.tagName==="BUTTON")return;if(c.preventDefault(),e._overviewAddTileFocused){Xu(e);return}Pt(e)}},e._desktop.addEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._desktop.addEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewClickBlocker=c=>{c.target?.closest(".os-overview-top-bar")||(c.stopPropagation(),c.preventDefault())},e._desktop.addEventListener("click",e._overviewClickBlocker,!0),document.addEventListener("keydown",e._overviewKeyHandler),e._lastOverviewHoverId=null,e._overviewMouseHandler=c=>{const u=c.target?.closest(".os-window--overview"),f=u?u.id.replace(/^wp-window-/,""):null;f!==e._lastOverviewHoverId&&(e._lastOverviewHoverId&&T(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&T(v.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&T(v.OVERVIEW_ENTERED,{})},300)}function Ku(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function mE(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 Yu(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(gE(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",E("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(),Xu(e)}),n.appendChild(o),t}function Xu(e){const t=ef(e);e._overviewAddTileFocused=!1,Zu(e,t.id)}function gE(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(E("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(),Zu(e,t.id)});const a=document.createElement("button");return a.type="button",a.className="os-overview-top-bar__tile-close",a.setAttribute("aria-label",de(E("Close %s"),t.label)),a.innerHTML=rn("close",{size:16}),a.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),nf(e,t.id),ta(e)}),n.appendChild(o),n.appendChild(a),n}function ta(e){if(!e._overviewTopBar)return;const t=Yu(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Zu(e,t){tf(e,t),Pt(e)}function na(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(sn("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function Pt(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,T(v.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of zu){const r=document.getElementById(i);r&&(r.inert=!1)}Vu(!1),qu(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"&&(ju(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"),ea(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(v.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>Ku(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(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function wE(e){return[...e._desktops]}function Ju(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function yE(e){return Ju(e).id}function Qu(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&ea(t)}function oa(e){for(const t of e._stack)Qu(e,t)}function ef(e){e._desktopSeq++;const t={id:`desktop-${e._desktopSeq}`,label:de(E("Desktop %d"),e._desktopSeq)};return e._desktops.push(t),T(v.DESKTOP_CREATED,{desktopId:t.id}),t}function tf(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)of(e),ta(e);else{oa(e),n?.direction&&bE(e,n.direction);const s=[...e._stack].reverse().find(i=>i.config.desktopId===t&&i.state!=="minimized");s&&e.focus(s)}T(v.DESKTOP_SWITCHED,{from:o,to:t})}function bE(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 nf(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?of(e):oa(e),T(v.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function of(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"),ea(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),oa(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||""}),Gu(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=Ir(t,o,Sd);for(const i of s){const r=i.win.element;r.classList.add("os-window--overview");const a=i.x-r.offsetLeft,l=i.y-r.offsetTop;r.style.transform=`translate(${a}px, ${l}px) scale(${i.scale})`;const c=na(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function vE(e,t,n){if(t.length===0)return;e._desktops=t.map(s=>({...s})),e._activeDesktopId=t.some(s=>s.id===n)?n:t[0].id;let o=0;for(const s of t){const i=s.id.match(/^desktop-(\d+)$/);if(i){const r=parseInt(i[1],10);Number.isFinite(r)&&r>o&&(o=r)}}e._desktopSeq=Math.max(e._desktopSeq,o)}function _E(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;T(v.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=e._desktop.getBoundingClientRect(),o=30,s=30,i=Math.min(Math.round(n.width*.7),1100),r=Math.min(Math.round(n.height*.75),750),a=Math.max(1,Math.floor((n.width-i-o)/s)),l=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(a,l);t.forEach((u,f)=>{const p=f%Math.max(1,c);u.element.style.left=`${o+p*s}px`,u.element.style.top=`${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(v.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function EE(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=e._desktop.getBoundingClientRect(),o=Qb(t.length,n.width,n.height),s=q(v.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=Zb(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;T(v.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,l=12,c=Math.floor((n.width-a*2-l*(i-1))/i),d=Math.floor((n.height-a*2-l*(r-1))/r);t.forEach((f,p)=>{const g=p%i,m=Math.floor(p/i);f.element.style.left=`${a+g*(c+l)}px`,f.element.style.top=`${a+m*(d+l)}px`,f.element.style.width=`${c}px`,f.element.style.height=`${d}px`});const u=e.getFocused();u&&e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"tile"}})),T(v.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}const sf="desktop-mode-snap-to-grid";function kE(){try{return window.localStorage.getItem(sf)==="1"}catch{return!1}}function SE(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(sf,t?"1":"0")}catch{}T(v.ARRANGE_SNAP_CHANGED,{enabled:t})}}function AE(e){if(!e._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const t=e._desktop.getBoundingClientRect(),n=t.width>=t.height?12:8,o={cellWidth:Math.max(40,Math.round(t.width/n)),cellHeight:Math.max(40,Math.round(t.height/Math.round(n*.66)))},s=q(v.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=Jb(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function CE(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){rf(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=NE(e,n),i=Ir(o,s,0);e._splitOverviewLabels.clear();for(const a of i){const l=a.win.element;l.classList.add("os-window--overview");const c=a.x-l.offsetLeft,d=a.y-l.offsetTop;l.style.transform=`translate(${c}px, ${d}px) scale(${a.scale})`;const u=na(a);l.insertAdjacentElement("afterend",u),e._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const l=a.target,c=l?.closest(".os-window--overview");return c?{id:c.id.replace(/^wp-window-/,""),element:c}:l?{id:"dismiss",element:e._desktop}:null};e._splitOverviewPointerDown=a=>{if(a.button!==0){e._splitOverviewPressTarget=null;return}e._splitOverviewPressTarget=r(a),e._splitOverviewPressTarget&&(a.preventDefault(),a.stopPropagation())},e._splitOverviewPointerUp=a=>{if(a.button!==0)return;const l=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!l)return;const c=l.element.getBoundingClientRect();if(!(a.clientX>=c.left&&a.clientX<=c.right&&a.clientY>=c.top&&a.clientY<=c.bottom))return;if(a.preventDefault(),a.stopPropagation(),l.id==="dismiss"){io(e);return}const u=e.getById(l.id);if(!u){io(e);return}IE(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&io(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 IE(e,t){const n=e._splitOverviewZone;if(!n){io(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(v.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),io(e)}function io(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();rf(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 rf(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const af=30,xE=260;function LE(e,t){return e<=t.left+af?"left":e>=t.right-af?"right":null}function TE(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 NE(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 DE(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=TE(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 sa(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()},xE)}function RE(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=LE(n,o),i=e._snapPendingZone;s?(DE(e,s),i!==s&&T(v.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(sa(e),T(v.SNAP_ZONE_CANCELED,{windowId:t.id}))}function OE(e,t){const n=e._snapPendingZone;return n?(sa(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(v.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{CE(e,t,n)}),!0):!1}function ME(e){e._snapPendingZone&&sa(e)}const lf="desktop-mode-native-window-geometry",cf=64,ot=8192;function Zs(){try{const e=window.localStorage.getItem(lf);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function df(e){try{window.localStorage.setItem(lf,JSON.stringify(e))}catch{}}function ia(e){if(!e)return null;const n=Zs()[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>ot||s>ot)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),a=Number(n.y),l=Number.isFinite(r)&&Number.isFinite(a)&&r>=0&&a>=0&&r<=ot&&a<=ot;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function uf(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>ot||o>ot)return;const s=Zs(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,l=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===l||(ro(s,e,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),ao(s))}function ff(e,t){if(!e)return;const n=Math.round(Number(t.x)),o=Math.round(Number(t.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>ot||o>ot)return;const s=Zs(),i=s[e];i&&(i.x===n&&i.y===o||(ro(s,e,{...i,x:n,y:o}),ao(s)))}function pf(e,t,n){if(!e)return;const o=Zs(),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>ot||r>ot)return;ro(o,e,{width:i,height:r,state:t}),ao(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;ro(o,e,r),ao(o);return}s.state!==t&&(ro(o,e,{...s,state:t}),ao(o))}function ro(e,t,n){delete e[t],e[t]=n}function ao(e){const t=Object.keys(e);if(t.length>cf){const n={};for(const o of t.slice(-cf))n[o]=e[o];df(n);return}df(e)}function PE(e,t,n,o,s){const i=qr-n,r=o-qr,a=Math.max(i,Math.min(e,r)),l=F_,c=s-qr,d=Math.max(l,Math.min(t,c));return{x:a,y:d}}const hf=100,Js=30;class WE{constructor(t){this._stack=[],this._cascadeMinimized=new WeakSet,this._cascadeDepth=0,this.cascadeIndex=0,this._pendingRestoreState=new Map,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=kE(),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){if(t.state==="maximized")t.element.classList.add("os-window--reflowing"),t.element.style.width=`${n.clientWidth}px`,t.element.style.height=`${n.clientHeight}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("os-window--reflowing");const o=Math.floor(n.clientWidth/2),s=n.clientHeight,i=t.state==="snapped-left"?0:o;t.element.style.left=`${i}px`,t.element.style.top="0px",t.element.style.width=`${o}px`,t.element.style.height=`${s}px`}else if(t.state==="normal"){const o=parseInt(t.element.style.left,10)||0,s=parseInt(t.element.style.top,10)||0,i=t.element.offsetWidth||0,r=PE(o,s,i,n.clientWidth,n.clientHeight);(o!==r.x||s!==r.y)&&(t.element.classList.add("os-window--reflowing"),t.element.style.left=`${r.x}px`,t.element.style.top=`${r.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 i=o.state==="minimized";this.focus(o),i&&o.restore();let r=!1;if(!o.config.native){const l=Os(t.url);l===Os(o.getCurrentUrl())||l===Os(o.config.url||"")||l===Os(o.config.parentUrl??o.config.url??"")||(r=o.navigateTo(t.url))}t.params&&(o.config.params={...t.params});const a={windowId:o.id,baseId:n,wasMinimized:i,navigated:r,params:o.config.params??{}};return document.dispatchEvent(new CustomEvent("os-window-reopened",{detail:a})),T(v.WINDOW_REOPENED,a),o}const s=this.getByBaseId(n)?this.nextInstanceId(n):t.id;return this.createWindow({...t,id:s,baseId:n})}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*Js,i=40+this.cascadeIndex%8*Js;return this.createWindow({initialState:"normal",x:s,y:i,...t,id:o,baseId:n})}async createWindow(t){const n=this._pendingRestoreState.get(t.id);n&&(this._pendingRestoreState.delete(t.id),t={...t,...n});const o=this._desktop.getBoundingClientRect(),s=Math.min(Math.round(o.width*.8),1200),i=Math.min(Math.round(o.height*.8),800),r=40+this.cascadeIndex%8*Js,a=40+this.cascadeIndex%8*Js,l=t.baseId||t.id,c=t.minWidth??320,d=t.minHeight??200,u=typeof t.width=="number",f=typeof t.height=="number",p=typeof t.x=="number",g=typeof t.y=="number",m=typeof t.initialState=="string",h=!u||!f||!m||!p||!g?ia(l):null,b=t.width??(h?Math.max(h.width,c):s),y=t.height??(h?Math.max(h.height,d):i),I=t.initialState??(h?.state==="maximized"?"maximized":void 0);let R,k;if(h&&typeof h.x=="number"&&typeof h.y=="number"){const V=Math.max(0,o.width-b-12),D=Math.max(0,o.height-y-12);R=Math.max(12,Math.min(h.x,V)),k=Math.max(12,Math.min(h.y,D))}const M=t.x??R??r,P=t.y??k??a,W=u||f||p||g||m,_=!!h,w={x:M,y:P,width:b,height:y,state:I};let L;try{L=q(v.WINDOW_GEOMETRY,w,{windowId:t.id,baseId:l,hasSavedGeometry:_,callerPinned:W,desktopRect:{width:o.width,height:o.height}})}catch(O){T(v.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:O}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,O),L=w}const A=(O,V)=>typeof O=="number"&&Number.isFinite(O)?O:V,C=L&&typeof L=="object"?L:w,$=Math.max(A(C.width,b),c),X=Math.max(A(C.height,y),d),Z=A(C.x,M),x=A(C.y,P),F=C.state??I,N={icon:t.icon||"dashicons-admin-generic",...t,x:Z,y:x,width:$,height:X,minWidth:c,minHeight:d,...F?{initialState:F}:{},baseId:l,desktopId:t.desktopId||this._activeDesktopId};this.cascadeIndex++;const[U]=await Promise.all([Yb(qb()),Sr(Ar())]),B=U.createWindow(N);B.onFocusRequest=O=>{this._cascadeDepth>0||this.focus(O)},B.onClose=O=>this.remove(O),B.onMinimize=O=>{this._cascadeDepth++;try{this.cascadeMinimize(O)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const V=this._stack.filter(D=>D.state!=="minimized");V.length>0&&this.focus(V[V.length-1])},B.onRestore=O=>{this._cascadeDepth++;try{this.cascadeRestore(O)}finally{this._cascadeDepth--}},B.onOpenAnother=O=>{const V=O.config.baseId||O.id;O.config.native&&window.wp?.os?.openNewWindow?.(V,{source:"open-another"})||this.openNew({id:V,baseId:V,url:O.config.url||"",title:O.config.title,icon:O.config.icon,submenu:O.config.submenu,multi:!0})},B.onOpenInNewWindow=O=>{const V=O.config.baseId||O.id;if(O.config.native&&window.wp?.os?.openNewWindow?.(V,{source:"open-in-new-window"}))return;const D=O.getCurrentUrl();this.openNew({id:V,baseId:V,url:D||O.config.url||"",title:O.config.title,icon:O.config.icon,submenu:O.config.submenu,multi:!0})},B.onToggleStartup=O=>{this.onToggleStartupRequested?.(O)},B.snapConfigProvider=()=>this.getSnapConfig(),B.onDragMove=(O,V)=>{RE(this,O,V)},B.onDragEnd=O=>this._snapPendingZone?OE(this,O):(ME(this),!1),this._stack.push(B),this._desktop.appendChild(B.element),Qu(this,B),B.hydrateNative(),this.focus(B);const H={windowId:B.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:H})),T(v.WINDOW_OPENED,H),B}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(v.WINDOW_CHILD_BLOCKED,{windowId:n.id,childWindowId:o.id}),document.dispatchEvent(new CustomEvent("os-window-child-blocked",{detail:{windowId:n.id,childWindowId:o.id}})));const s=this._stack.length>0?this._stack[this._stack.length-1]:null,i=this._stack.find(l=>l!==o&&l.isFocused()&&l.isFullscreen());i&&q(v.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:i.id,focusedTo:o.id})&&i.toggleFullscreen();const r=this._stack.indexOf(o);if(r>-1&&this._stack.splice(r,1),this._stack.push(o),this.enforceOwnershipOrder(),this._stack.forEach((l,c)=>{l.setZIndex(hf+c),l.setFocused(c===this._stack.length-1)}),s&&s!==o&&s.id!==o.id){const l={windowId:s.id,focusedTo:o.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:l})),T(v.WINDOW_BLURRED,l)}const a={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:a})),T(v.WINDOW_FOCUSED,a)}raise(t){const n=this.getById(t);if(!n||this._stack.length<2)return;const o=this._stack.indexOf(n);o===-1||o===this._stack.length-1||(this._stack.splice(o,1),this._stack.splice(this._stack.length-1,0,n),this.enforceOwnershipOrder(),this._stack.forEach((s,i)=>{s.setZIndex(hf+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=ia(n.baseId||n.id),i=!!s&&typeof s.x=="number"&&typeof s.y=="number";let r={};if(n.x===void 0&&n.y===void 0&&!i){const a=o.getSnapshot(),l=n.width??Math.round(a.width*.8),c=n.height??Math.round(a.height*.8),d=this._desktop.getBoundingClientRect(),u=Math.max(0,d.width-l),f=Math.max(0,d.height-c);r={width:l,height:c,x:Math.min(u,Math.max(0,Math.round(a.x+(a.width-l)/2))),y:Math.min(f,Math.max(0,Math.round(a.y+(a.height-c)/2)))}}return this.open({...n,...r,desktopId:o.config.desktopId,parentWindowId:t})}ownerOf(t){const n=t.config.parentWindowId;return n?this.getById(n):void 0}childrenOf(t){const n=typeof t=="string"?t:t.id;return this._stack.filter(o=>o.config.parentWindowId===n)}blockingChildOf(t){let n=t,o;const s=new Set([t]);for(;;){const i=this.childrenOf(n).filter(r=>r.state!=="minimized"&&!s.has(r));if(i.length===0)return o;n=i[i.length-1],s.add(n),o=n}}enforceOwnershipOrder(){if(!this._stack.some(s=>s.config.parentWindowId))return;const t=[],n=new Set,o=(s,i)=>{if(!(n.has(s)||i.has(s))){if(i.add(s),s.state!=="minimized"){const r=this.ownerOf(s);r&&r!==s&&o(r,i)}n.has(s)||(n.add(s),t.push(s))}};for(const s of this._stack)o(s,new Set);this._stack.length=0,this._stack.push(...t)}cascadeMinimize(t){for(const n of this.childrenOf(t))n.state!=="minimized"&&(this._cascadeMinimized.add(n),n.minimize())}cascadeRestore(t){for(const n of this.childrenOf(t))this._cascadeMinimized.has(n)&&(this._cascadeMinimized.delete(n),n.restore())}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);const o=this.childrenOf(t).slice();if(o.length>0){this._cascadeDepth++;try{for(const r of o)this._cascadeMinimized.delete(r),r.close()}finally{this._cascadeDepth--}}for(let r=this._stack.length-1;this._cascadeDepth===0&&r>=0;r--){const a=this._stack[r];if(!(a.state==="minimized"||(a.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(a);break}}const s={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("os-window-closing",{detail:s})),T(v.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),T(v.WINDOW_CLOSED,i)}getById(t){return this._stack.find(n=>n.id===t)}getByBaseId(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===t)return o}}getByBaseIdOnActiveDesktop(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==t)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(t){const n=o=>{if(o===t)return 1;const s=`${t}-`;if(o.startsWith(s)){const i=parseInt(o.slice(s.length),10);return Number.isFinite(i)?i:999}return 999};return this._stack.filter(o=>(o.config.baseId||o.id)===t).sort((o,s)=>n(o.id)-n(s.id))}getAllByBaseIdOnActiveDesktop(t){return this.getAllByBaseId(t).filter(n=>(n.config.desktopId||this._activeDesktopId)===this._activeDesktopId)}getAll(){return[...this._stack]}findByIframeSource(t){if(t)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===t)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(t){const n=this.getById(t);if(!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)return!1;const s=this.getFocused();return!!s&&s.id===t}isActiveByBaseId(t){const n=this.getFocused();return!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId?!1:(n.config.baseId||n.id)===t}getDesktops(){return wE(this)}getActiveDesktop(){return Ju(this)}getActiveDesktopId(){return yE(this)}createDesktop(){return ef(this)}switchDesktop(t,n){tf(this,t,n)}closeDesktop(t){nf(this,t)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=q(v.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(l=>!n.has(l.id));T(v.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=q(v.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(l=>!i.includes(l));let a=0;for(const l of i.slice())try{l.close(),a++}catch(c){typeof console<"u"&&console.error("[openstation] closeAll: window.close() threw for",l.id,c)}return T(v.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(){_E(this)}tile(){EE(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){SE(this,t)}getSnapConfig(){return AE(this)}enterOverview(){hE(this)}exitOverview(t,n=!1){Pt(this,t,n)}destroy(){this._overviewActive&&Pt(this),mE(this)}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(),l=!!i.config.native,c=i.config.params,d=l&&c?this.sanitizeParams(c):null;return{id:i.id,baseId:i.config.baseId||i.id,desktopId:i.config.desktopId||this._activeDesktopId,...l?{native:!0}:{},...d?{params:d}:{},url:l?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){vE(this,t,n)}}function $E(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 mf(e,t){if(e._overviewActive)return;const n=$E(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 gf=!1;function wf(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 UE(e){if(gf)return;gf=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(wf(document)||(n.preventDefault(),mf(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"||mf(e,o.direction==="prev"?"prev":"next")})}function yf(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 bf(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(l=>l.id===e.getActiveDesktopId());if(i===-1)return!1;const a=(i+(t==="next"?1:-1)+o)%o;return a===i?!1:a===s?(e._overviewAddTileFocused=!0,ta(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function FE(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function BE(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function vf(e){return e._overviewActive?(e.exitOverview(),!0):!1}function HE(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function zE(e){return HE(e)?(e.toggleShowDesktop(),!0):!1}let _f=!1;function GE(e){_f||(_f=!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"||wf(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?bf(e,"prev"):yf(e,"prev");break;case"ArrowRight":n=e._overviewActive?bf(e,"next"):yf(e,"next");break;case"ArrowUp":n=vf(e)||zE(e)||FE(e);break;case"ArrowDown":n=vf(e)||BE(e);break}n&&t.preventDefault()},!0))}const Ef=_u;let kf=!1;function Sf(e){return e?document.getElementById(`wp-window-${e}`):null}function jE(){kf||(kf=!0,VE())}function VE(){Y(v.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=Sf(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove(Zr),n.classList.add(so),cE(n),Hu(t),nE(t))}),Y(v.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=Sf(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 .${no}`)?.classList.contains(qs);if(n.classList.remove(so),n.removeAttribute(Jr),!o){Bu(t),Du(t);return}n.classList.add(Zr);const s=Ys(n);Du(t),window.setTimeout(()=>{Ys(n)===s&&(n.classList.contains(so)||Bu(t))},Ef),window.setTimeout(()=>{Ys(n)===s&&(n.classList.contains(so)||n.classList.remove(Zr))},Ef+H_)}),Y(v.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Af())})}function Af(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),Hu(n))})}const qE="os_person_view";function KE(e){return e.searchParams.has(qE)}const lo=le("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function YE(e){lo.state.deps=e}function kt(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=lo.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>XE(e.id)}function XE(e){const t=lo.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function ra(e){const{deps:t,remaps:n}=lo.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 Ge(e){const{deps:t,remaps:n}=lo.state;if(!t||!e)return!1;let o;try{o=new URL(e,t.adminUrl)}catch{return!1}const s=t.getSnapshot();for(const i of n){if(!i.matches(e,o)||i.enabled&&!i.enabled(s))continue;if(i.onMatch)try{i.onMatch(e,o)}catch(l){console.warn(`[openstation] URL remap onMatch hook threw for "${i.id}":`,l)}let r;if(i.params)try{r=i.params(e,o)??void 0}catch(l){console.warn(`[openstation] URL remap params hook threw for "${i.id}":`,l)}if(r?t.openById(i.nativeWindowId,{params:r}):t.openById(i.nativeWindowId))return!0}return!1}const ZE="desktop_mode_classic";function JE(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has(ZE)}const aa=le("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function QE(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=aa.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Cf(e.id)}function Cf(e){const t=aa.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function e0(){return aa.state.entries.slice()}const t0=32,n0=64,o0=/^[a-z0-9_/-]+$/,we=le("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function Wt(e){return`${e.type}:${e.id}`}function If(e){return e.root?Wt(e.root):Wt(e)}function xf(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&o0.test(o.trim().toLowerCase());return Rt(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 s0(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,t0).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,n0).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 Lf(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 la(e){return e?[Wt(e),If(e),...(e.links??[]).map(t=>Wt(t)+(t.rel==="child"?"!child":""))].join("|"):""}function Qs(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Ne("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=xf(t);if(a.length>0){o==="api"&&Ne("WindowContentRef",a,t),Id("WindowContentRef",a,t);return}s=s0(t,o)}if(s=q(v.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||xf(s).length>0)){Id("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=we.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&la(s)===la(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&Lf(s)===Lf(i))return;s===null?we.state.contentByWindow.delete(e):we.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(v.WINDOW_CONTENT_CHANGED,r),l0(),r0()}function ct(e){return we.state.contentByWindow.get(e)}function ei(){const e=new Map;for(const[s,i]of we.state.contentByWindow){const r=If(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=we.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=q(v.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[openstation] `os.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function Tf(e){return ei().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function Nf(e){const t=new Set,n=Tf(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of co())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function i0(e){const t=new Set;for(const n of co())n.fromWindowId===e?t.add(n.toWindowId):n.toWindowId===e&&t.add(n.fromWindowId);return t.delete(e),Array.from(t)}function co(){const e=we.state.focusSeq,t=new Map;for(const[a,l]of we.state.contentByWindow){const c=Wt(l),d=t.get(c);(!d||(e.get(a)??0)>(e.get(d)??0))&&t.set(c,a)}const n=new Map,o=(a,l)=>`${a}→${l}`;for(const[a,l]of we.state.contentByWindow){if(l.root){const c=t.get(Wt(l.root));c&&c!==a&&n.set(o(a,c),{fromWindowId:a,toWindowId:c,kind:"child-root",bidirectional:!1})}for(const c of l.links??[]){const d=t.get(Wt(c));if(!d||d===a)continue;if(c.rel==="child"){const f=o(d,a),p=n.get(f);(!p||p.kind!=="child-root")&&n.set(f,{fromWindowId:d,toWindowId:a,kind:"child-root",bidirectional:!1});continue}const u=o(a,d);n.has(u)||n.set(u,{fromWindowId:a,toWindowId:d,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[a,l]of n){if(i.has(a))continue;const c=o(l.toWindowId,l.fromWindowId),d=n.get(c);if(d&&l.kind==="reference"){if(d.kind==="reference"){i.add(c),s.push({...l,bidirectional:!0});continue}continue}s.push(l)}const r=q(v.WINDOW_LINK_EDGES,s);return Array.isArray(r)?r:(typeof console<"u"&&console.warn("[openstation] `os.window-links.edges` filter returned a non-array; falling back to derived edges."),s)}function Df(e){return we.state.listeners.add(e),()=>{we.state.listeners.delete(e)}}function r0(){for(const e of Array.from(we.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function a0(){return Array.from(we.state.contentByWindow).map(([e,t])=>`${e}=${la(t)}`).sort().join(";")}function l0(){const e=a0();if(e===we.state.lastGroupsSignature)return;we.state.lastGroupsSignature=e;const n={groups:ei()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),T(v.WINDOW_LINK_GROUPS_CHANGED,n)}const c0={get:ct,set:(e,t)=>Qs(e,t,{source:"api"}),groups:ei,edges:co,groupOf:Tf,related:Nf,subscribe:Df};function d0({manager:e}){we.state.manager=e,!we.state.started&&(we.state.started=!0,Y(v.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=we.state.manager?.getById(t.windowId)?.config?.content;o&&Qs(t.windowId,o,{source:"config"})}),Y(v.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(we.state.focusSeq.delete(t.windowId),Qs(t.windowId,null,{source:"config"}))}),Y(v.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(we.state.seq+=1,we.state.focusSeq.set(t.windowId,we.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=we.state.manager?.findByIframeSource?.(t.source);o&&Qs(o.id,n.identity??null,{source:"bridge"})}))}const u0=le("desktop-mode/admin-link-deps",()=>({deps:null}));function f0(e){u0.state.deps=e}const Rf=le("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),pn=Rf.state.seed,p0=Rf.state.listeners;function hn(e){Ne("Wallpaper",Rt(e,Wf),e);const t=pn.findIndex(n=>n.id===e.id);t>=0?pn[t]=e:pn.push(e),Mf()}function Of(e){const t=pn.findIndex(n=>n.id===e);t>=0&&(pn.splice(t,1),Mf())}function Mf(){const e=Array.from(p0);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function Pf(){const e=pn.slice(),t=q(v.WALLPAPERS,e);return Array.isArray(t)?t.filter(h0):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function ca(e){return Pf().find(t=>t.id===e)}const Wf=[{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 h0(e){return Rt(e,Wf).length===0}const $f=le("desktop-mode/wallpaper-settings",()=>({values:{}}));function m0(e){return{...$f.state.values[e]??{}}}function g0(e){const t=$f.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}function Uf(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const Ff=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","glow","glowBlur","eyeColor","eyeScale"],Bf=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function da(){return{appearance:{},physics:{}}}function w0(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function ti(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&&w0(i)&&Object.assign(n,{[s]:i})}return n}function Hf(e){if(!e||typeof e!="object"||Array.isArray(e))return da();const t=e;return{appearance:ti(t.appearance,Ff),physics:ti(t.physics,Bf)}}function y0(e){return{appearance:ti(e,Ff),physics:ti(e,Bf)}}function b0(){const e=v0();if(e){const t=zf(e);return fa(t),C0(t),t}try{const t=window.localStorage.getItem(eu);if(t)return zf(JSON.parse(t))}catch{}return N0()}function v0(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}function zf(e){const t=Ur();return{wallpaper:typeof e.wallpaper=="string"&&e.wallpaper!==""?e.wallpaper:su(),accent:e.accent===nu||t.some(n=>n.id===e.accent)?e.accent:ee.accent,customAccent:typeof e.customAccent=="string"&&/^#[0-9a-fA-F]{6}$/.test(e.customAccent)?e.customAccent:ee.customAccent,dockSize:Fr.some(n=>n.id===e.dockSize)?e.dockSize:ee.dockSize,windowRadius:Br.some(n=>n.id===e.windowRadius)?e.windowRadius:ee.windowRadius,adminBarMode:Bs.some(n=>n.id===e.adminBarMode)?e.adminBarMode:ee.adminBarMode,desktopLayout:jv.some(n=>n.id===e.desktopLayout)?e.desktopLayout:ee.desktopLayout,dockPlacement:Gv.some(n=>n.id===e.dockPlacement)?e.dockPlacement:ee.dockPlacement,dockRailRenderer:typeof e.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(e.dockRailRenderer)?e.dockRailRenderer:ee.dockRailRenderer,desktopTheme:typeof e.desktopTheme=="string"&&/^[a-z0-9_-]*$/.test(e.desktopTheme)?e.desktopTheme:ee.desktopTheme,appliedThemeRecommendations:Array.isArray(e.appliedThemeRecommendations)?Array.from(new Set(e.appliedThemeRecommendations.filter(n=>typeof n=="string"&&/^[a-z0-9_-]+$/.test(n)))).slice(-64):ee.appliedThemeRecommendations.slice(),unfocusEffect:typeof e.unfocusEffect=="string"&&/^[a-z0-9_/-]+$/.test(e.unfocusEffect)?e.unfocusEffect:ee.unfocusEffect,windowReveal:typeof e.windowReveal=="string"&&/^[a-z0-9_/-]+$/.test(e.windowReveal)?e.windowReveal:ee.windowReveal,windowRevealDuration:typeof e.windowRevealDuration=="number"&&Number.isFinite(e.windowRevealDuration)&&e.windowRevealDuration>0?Math.min(4e3,Math.max(80,Math.round(e.windowRevealDuration))):ee.windowRevealDuration,windowLinkRenderer:typeof e.windowLinkRenderer=="string"&&/^[a-z0-9_/-]+$/.test(e.windowLinkRenderer)?e.windowLinkRenderer:ee.windowLinkRenderer,windowLinkVisibility:e.windowLinkVisibility==="focus"||e.windowLinkVisibility==="always"||e.windowLinkVisibility==="off"?e.windowLinkVisibility:ee.windowLinkVisibility,windowLinksEnabled:typeof e.windowLinksEnabled=="boolean"?e.windowLinksEnabled:ee.windowLinksEnabled,windowLinkRaiseOnFocus:typeof e.windowLinkRaiseOnFocus=="boolean"?e.windowLinkRaiseOnFocus:ee.windowLinkRaiseOnFocus,windowLinkHighlight:typeof e.windowLinkHighlight=="boolean"?e.windowLinkHighlight:ee.windowLinkHighlight,customGradient:R0(e.customGradient),customImage:O0(e.customImage),wallpaperSettings:_0(e.wallpaperSettings),libraryHdOnly:typeof e.libraryHdOnly=="boolean"?e.libraryHdOnly:ee.libraryHdOnly,ai:D0(e.ai),heartbeatRate:e.heartbeatRate===15||e.heartbeatRate===30||e.heartbeatRate===45||e.heartbeatRate===60?e.heartbeatRate:ee.heartbeatRate,nativePostsEnabled:typeof e.nativePostsEnabled=="boolean"?e.nativePostsEnabled:ee.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(e.nativePostsHiddenColumns)?e.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):ee.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof e.nativePagesEnabled=="boolean"?e.nativePagesEnabled:ee.nativePagesEnabled,nativeUsersEnabled:typeof e.nativeUsersEnabled=="boolean"?e.nativeUsersEnabled:ee.nativeUsersEnabled,nativePluginsEnabled:typeof e.nativePluginsEnabled=="boolean"?e.nativePluginsEnabled:ee.nativePluginsEnabled,nativeCommentsEnabled:typeof e.nativeCommentsEnabled=="boolean"?e.nativeCommentsEnabled:ee.nativeCommentsEnabled,showDesktopOnWallpaperClick:typeof e.showDesktopOnWallpaperClick=="boolean"?e.showDesktopOnWallpaperClick:ee.showDesktopOnWallpaperClick,mioEnabled:typeof e.mioEnabled=="boolean"?e.mioEnabled:ee.mioEnabled,mioStyle:Hf(e.mioStyle),showPostStatusRibbons:typeof e.showPostStatusRibbons=="boolean"?e.showPostStatusRibbons:ee.showPostStatusRibbons,developerModeEnabled:typeof e.developerModeEnabled=="boolean"?e.developerModeEnabled:ee.developerModeEnabled,foldersSharingEnabled:typeof e.foldersSharingEnabled=="boolean"?e.foldersSharingEnabled:ee.foldersSharingEnabled,navPlacement:E0(e.navPlacement),navOrder:k0(e.navOrder),dockPromotedPositions:S0(e.dockPromotedPositions)}}function _0(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,l]of Object.entries(s)){if(r>=32)break;if(!(typeof a!="string"||a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof l=="boolean")i[a]=l;else if(typeof l=="number"&&Number.isFinite(l))i[a]=l;else if(typeof l=="string")i[a]=l.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function E0(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 k0(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 S0(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 ni=null;const A0=250;let $t=null;function C0(e){$t=ua(e)}function ua(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 I0(e,t={}){fa(e),x0(e,t.windowId)}function fa(e){try{window.localStorage.setItem(eu,JSON.stringify(e))}catch{}}function x0(e,t){ni!==null&&clearTimeout(ni),t&&(pa=t),Ut("pending"),ni=setTimeout(()=>{ni=null;const n=pa;pa=null,T0(e,n)},A0)}let pa=null;function L0(e){if(!$t)return{...e};const t=$t,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}function T0(e,t){const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Ut("saved");return}const i=L0(e);if(!i){Ut("saved");return}Ut("saving");const r=t||"desktop-mode-os-settings";Fe(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:i})},{windowId:r}).then(a=>{if(!a.ok)throw new Error(`${a.status} ${a.statusText}`);$t=ua(e),Ut("saved")}).catch(a=>{$t?(fa($t),Ut("failed",a instanceof Error?a.message:String(a),ua($t))):Ut("failed",a instanceof Error?a.message:String(a))})}function Ut(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 N0(){return{...ee,customGradient:{...ee.customGradient},customImage:null,wallpaperSettings:{...ee.wallpaperSettings},ai:{...ee.ai},appliedThemeRecommendations:[...ee.appliedThemeRecommendations],navPlacement:{...ee.navPlacement},navOrder:[...ee.navOrder],dockPromotedPositions:{...ee.dockPromotedPositions}}}function D0(e){if(!e||typeof e!="object")return{...ee.ai};const{enabled:t}=e;return{enabled:typeof t=="boolean"?t:ee.ai.enabled}}function R0(e){if(!e||typeof e!="object")return{...ee.customGradient};const{from:t,to:n,angle:o}=e;return{from:Uf(t)?t:ee.customGradient.from,to:Uf(n)?n:ee.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:ee.customGradient.angle}}function O0(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 mn(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 M0(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function uo(e,t,n){if(!M0(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 ha="data-os-constellation";function P0(){return document.body.hasAttribute(ha)}const oi="os-item-menu-opening",W0=180,$0=220,Gf=32;function jf(e){const{tile:t}=e;let n=null,o=null,s=null,i=!1,r=null;const a=()=>{o!==null&&(window.clearTimeout(o),o=null)},l=()=>{s!==null&&(window.clearTimeout(s),s=null)},c=()=>{a(),l(),t.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),r?.clear(),r=null,e.suppressTooltip(!1)},d=m=>{m.pointerType==="mouse"&&(P0()&&(t.dataset.menuSlug||t.dataset.constellationId)||U0(e)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},W0))))},u=m=>{n&&m.relatedTarget instanceof Node&&n.contains(m.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},$0)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=F0(e,()=>c(),r),document.body.appendChild(n),q0(n),K0(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,l()}),n.addEventListener("pointerleave",m=>{m.relatedTarget instanceof Node&&t.contains(m.relatedTarget)||(i=!1,f())})},g=()=>c();return t.addEventListener("pointerenter",d),t.addEventListener("pointerleave",u),document.addEventListener(oi,g),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(oi,g),c()}}function U0(e){return e.getInstances().length>=1}function F0(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",de(E("%s — open windows"),e.item.title));const s=document.createElement("div");s.className="os-dock-peek__cards",o.appendChild(s);const i=e.getInstances();let r=0;for(const a of i){const l=B0(a,e,r++,t,n);s.appendChild(l)}if(e.enableGhost!==!1){const a=z0(e,r,t);s.appendChild(a)}return o}function Vf(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function B0(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*Gf}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${mn(e.id||r)}`),i.style.setProperty("--peek-card-vt-name",`os-peek-card-${e.id}`);const a=document.createElement("span");a.className="os-dock-peek__card-titlebar";const l=document.createElement("span");l.className="os-dock-peek__card-dots",l.setAttribute("aria-hidden","true");for(let y=0;y<3;y++)l.appendChild(document.createElement("i"));a.appendChild(l);const c=document.createElement("span");c.className="os-dock-peek__card-icon",c.setAttribute("aria-hidden","true");const d=e.config.icon||t.item.icon;d.startsWith("dashicons-")?c.classList.add("dashicons",hd(d)):c.classList.add("dashicons","dashicons-admin-generic"),a.appendChild(c);const u=document.createElement("span");u.className="os-dock-peek__card-label",u.textContent=r,a.appendChild(u),i.appendChild(a);const f=document.createElement("span");f.className="os-dock-peek__card-body",f.setAttribute("aria-hidden","true");for(let y=0;y<3;y++){const I=document.createElement("span");I.className="os-dock-peek__card-line",f.appendChild(I)}const p={window:e,item:t.item},g=q(v.DOCK_PEEK_CARD_CONTENT,f,p);g!==f&&g.classList.add("os-dock-peek__card-body--custom"),i.appendChild(g),e.state==="minimized"&&(i.dataset.state="minimized");const m=()=>{s.delete(e.id),delete i.dataset.preview},h=y=>{if(m(),y.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(y.previouslyFocusedId){const I=t.windowManager.getById(y.previouslyFocusedId);I&&t.windowManager.focus(I)}};return i.addEventListener("click",()=>{m(),H0(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const y=e.state==="minimized",I=t.windowManager.getFocused(),R=I&&I!==e?I.id:null;(y||R!==null)&&(s.set(e.id,{wasMinimized:y,previouslyFocusedId:R}),i.dataset.preview=""),y?Vf(e,i):I&&I!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const y=s.get(e.id);y&&h(y)}),q(v.DOCK_PEEK_CARD_ELEMENT,i,p)}function H0(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),Vf(t,n),e.windowManager.focus(t)};if(typeof s.startViewTransition!="function"){r();return}const a=t.element;n.style.setProperty("view-transition-name",i),a.style.setProperty("view-transition-name",i);const l=s.startViewTransition(r),c=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},d=l;d.finished&&typeof d.finished.then=="function"?d.finished.then(c,c):Promise.resolve().then(c)}function z0(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*Gf}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(E("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{G0(e,n)}),o}function G0(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const j0=12,V0=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function q0(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of V0){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function K0(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(()=>Y0(e))}function Y0(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=j0;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 gn(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 ma=new Map;function X0(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 ke(e,t){const n=ma.get(e);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-os-vendor="${Z0(e)}"]`,a=document.querySelector(r);if(a){if(a.dataset.loaded==="1"){s();return}a.addEventListener("load",()=>s(),{once:!0}),a.addEventListener("error",()=>i(new Error(`Failed to load ${e}`)),{once:!0});return}const l=X0(e);if(l){l.dataset.osVendor=e,l.dataset.loaded="1",s();return}t?.translations&&si(t.translations);for(const d of t?.l10n??[])si(d);for(const d of t?.before??[])si(d);const c=document.createElement("script");c.src=e,c.async=!0,c.dataset.osVendor=e,c.addEventListener("load",()=>{c.dataset.loaded="1";for(const d of t?.after??[])si(d);s()},{once:!0}),c.addEventListener("error",()=>{ma.delete(e),c.remove(),i(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(c)});return ma.set(e,o),o}function si(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function Z0(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let qf=0;function Kf(){return window.openStationItemVisibilityMenu??null}function J0(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function Yf(e){const t=Kf();if(t){t.openItemVisibilityMenu(e);return}const n=J0();if(!n)return;const o=++qf;ke(n).then(()=>{o===qf&&Kf()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const Q0={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function ek(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function tk(e){return e==="core"?"core":e==="control"?"controls":"apps"}function Xf(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??Q0[e.kind]}function Zf(e){return e==="rail"||e==="both"}function nk(e){return e==="desktop"||e==="both"}function ok(e,t,n){return Zf(e)?"rail":"hidden"}function ga(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 sk(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 wa(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 ii(){return window.wp?.os??null}function ik(){const e=ii()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function rk(){return ii()?.getNavItems?.()??[]}function ak(e){const t=rk();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function lk(e){const t=ii();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 ck(e,t,n){const o=Array.isArray(e)?e:[e],s=ik().placement,i=[];for(const r of o){const a=typeof r=="string"?ak(r):r;a&&i.push({item:a,placement:ok(Xf(a,s))})}lk(i)}function dk(e){const t=ii();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:sk(n,e)})}const st=["core","apps","controls"];function Jf(e){const{items:t,config:n,layout:o,openWindows:s}=e,i={core:[],apps:[],controls:[]},r=[],a=[],l=new Set,c=new Set,d=new Map,u=new Set;for(const f of t){u.add(f.id),f.windowId&&!d.has(f.windowId)&&d.set(f.windowId,f);const p=Xf(f,n.placement);if(Zf(p)){c.add(f.id);const g=tk(f.kind);ek(f.kind,o)==="sidebar"?r.push(f):i[g].push(f)}nk(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(c.has(p.id)||l.has(p.id))continue;i.apps.push(p),l.add(p.id);continue}f.fromAdminUrl||l.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}),l.add(f.id))}for(const f of st)i[f]=ga(wa(i[f]),n.order);return{dock:i,sidebar:ga(wa(r),n.order),desktop:ga(wa(a),n.order),ephemeral:l}}function Qf(e){return e.navKind==="control"?"controls":"apps"}const We=class We{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/${++We.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 st)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[Qf(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 st){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(v.DOCK_ITEM_REMOVED,{id:t,placement:this.rail}))}setBadge(t,n){const o=this._resolveTileElement(t);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(t):this.badgeOverrides.set(t,s);const i=o.querySelector(".os-dock__item-primary");ep(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,Gs(n)),r=s.querySelector(".os-dock__item-mask, .os-dock__item-svg, .dashicons, img");r?r.replaceWith(i):s.prepend(i)}_declaredTitle(t){const n=this.items.find(s=>s.id===t);if(n)return n.title;const o=this.systemItems.find(s=>s.id===t);return o?o.title:""}setAttention(t,n,o={}){const s=this._resolveTileElement(t);if(!s)return;const i=this.attentionTimers.get(t);if(i!==void 0&&(window.clearTimeout(i),this.attentionTimers.delete(t)),s.classList.remove("os-dock__item--attention-pulse","os-dock__item--attention-shake","os-dock__item--attention-bounce","os-dock__item--intensity-subtle","os-dock__item--intensity-normal","os-dock__item--intensity-strong"),n===null)return;s.classList.add(`os-dock__item--attention-${n}`);const r=o.intensity??"normal";s.classList.add(`os-dock__item--intensity-${r}`);const a=o.durationMs??4e3;if(a>0){const l=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},a);this.attentionTimers.set(t,l)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}appendSystemItem(t){const n=Qf(t),o={type:"system",item:t};for(const a of st)this.zones[a]=this.zones[a].filter(l=>l.type!=="system"||l.item.id!==t.id);const s=this.zones[n],i=t.order??0,r=s.findIndex(a=>a.type==="system"&&(a.item.order??0)>i);r===-1?s.push(o):s.splice(r,0,o),this.render()}render(){if(We.activeDragReset){const o=We.activeDragReset;We.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 st)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(v.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of st){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(v.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}paintEntry(t,n,o,s){const i=t.item.id,r=t.type==="menu"?this.createItemButton(t.item):this.createSystemItemButton(t.item);r.dataset.zone=n,r.dataset.navId=i,t.type==="system"&&t.item.locked===!0?r.dataset.navLocked="true":(this.attachDragReorder(r,i,n),r.addEventListener("contextmenu",d=>{d.preventDefault(),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 l=this.badgeOverrides.get(i);if(l!==void 0){const d=r.querySelector(".os-dock__item-primary");ep(d??r,l)}const c=this.artOverrides.get(i);c&&this._paintArt(r,i,c),T(v.DOCK_TILE_RENDERED,{...s,item:t.item,isSystem:t.type==="system",el:r})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=q(v.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,Gs(t.id))),r.addEventListener("click",()=>t.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=jf({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:""},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(t.id),enableGhost:!!t.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(t.onOpenNew??t.onOpen)()},suppressTooltip:l=>{l&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),q(v.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];t.multi&&s.push("os-dock__item--multi");const i=q(v.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const a=this.resolveIcon(t.icon,t.title,t.url,Gs(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(sn("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const l=this.resolveItemBaseId(t),c=jf({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(l),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(t),suppressTooltip:d=>{d&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(t.id,c),q(v.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n,o){let r=!1,a=0,l=0,c=[],d=null,u=-1,f=null,p=!1;const g=()=>{r=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",R),document.removeEventListener("pointerup",W),document.removeEventListener("pointercancel",_),document.removeEventListener("keydown",w,!0),window.removeEventListener("blur",L),document.removeEventListener("visibilitychange",A),u=-1,f=null},m=o==="controls"?this.systemHost:this.itemHost,h=C=>!!C&&C instanceof HTMLElement&&C.classList.contains("os-dock__item")&&C.dataset.zone===o&&!!C.dataset.navId&&C.dataset.navLocked===void 0,b=C=>{for(const $ of Array.from(m.children))$ instanceof HTMLElement&&$!==t&&h($)&&C($)},y=()=>{const C=[];for(const $ of Array.from(m.children))h($)&&C.push($.dataset.navId);return C},I=C=>{b($=>{const X=C.get($);if(!X)return;const Z=$.getBoundingClientRect(),x=X.left-Z.left,F=X.top-Z.top;if(Math.abs(x)<.5&&Math.abs(F)<.5)return;$.style.transition="none",$.style.transform=`translate(${x}px, ${F}px)`,$.offsetHeight,$.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",$.style.transform="";const N=()=>{$.style.transition="",$.style.transform="",$.removeEventListener("transitionend",N)};$.addEventListener("transitionend",N)})},R=C=>{if(u!==-1&&C.pointerId!==u)return;if(!r){const H=C.clientX-a,O=C.clientY-l;if(H*H+O*O<5*5)return;r=!0,c=y(),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 $=C.clientX-a,X=C.clientY-l;t.style.transform=`translate(${$}px, ${X}px)`;const x=document.elementFromPoint(C.clientX,C.clientY)?.closest(".os-dock__item");if(!x||x===t||!h(x))return;const F=x.getBoundingClientRect();let N;this.orientation==="bottom"?N=C.clientX<F.left+F.width/2:N=C.clientY<F.top+F.height/2;const U=new Map;b(H=>{U.set(H,H.getBoundingClientRect())});let B=!1;if(N?x!==t.nextSibling&&(m.insertBefore(t,x),B=!0):x.nextSibling!==t&&(m.insertBefore(t,x.nextSibling),B=!0),B){t.style.transform="";const H=t.getBoundingClientRect();a=H.left+H.width/2,l=H.top+H.height/2,t.style.transform=`translate(${C.clientX-a}px, ${C.clientY-l}px)`,I(U)}},k=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",R),document.removeEventListener("pointerup",W),document.removeEventListener("pointercancel",_),document.removeEventListener("keydown",w,!0),window.removeEventListener("blur",L),document.removeEventListener("visibilitychange",A),u=-1,f=null,r=!1,We.activeDragReset===g&&(We.activeDragReset=null)},M=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const C=()=>{t.style.transition="",t.removeEventListener("transitionend",C)};t.addEventListener("transitionend",C)},P=C=>{dk(C)},W=C=>{if(u!==-1&&C.pointerId!==u)return;if(!r){k();return}p=!0;const $=y();M(),k(),$.length===c.length&&$.every((Z,x)=>Z===c[x])||P($),setTimeout(()=>{p=!1},200)},_=C=>{if(!(C&&u!==-1&&C.pointerId!==u)){if(r&&d!==void 0){const $=new Map;b(X=>{$.set(X,X.getBoundingClientRect())}),m.insertBefore(t,d),I($)}M(),k()}},w=C=>{C.key==="Escape"&&_()},L=()=>_(),A=()=>{document.visibilityState!=="visible"&&_()};t.addEventListener("pointerdown",C=>{if(C.button===0){if(We.activeDragReset){const $=We.activeDragReset;We.activeDragReset=null,$()}(r||u!==-1)&&g(),a=C.clientX,l=C.clientY,u=C.pointerId,r=!1,We.activeDragReset=g,document.addEventListener("pointermove",R),document.addEventListener("pointerup",W),document.addEventListener("pointercancel",_),document.addEventListener("keydown",w,!0),window.addEventListener("blur",L),document.addEventListener("visibilitychange",A)}}),t.addEventListener("click",C=>{p&&(C.preventDefault(),C.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=zs(s);a!==null&&(t=a,i=!0),r=zr(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if(uo(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(uo(s,o,"currentColor"))return s;const i=document.createElement("span");return i.className="os-dock__item-svg",i.style.backgroundImage=t.startsWith("url(")?t:`url("${t}")`,i.style.backgroundSize="contain",i.style.backgroundRepeat="no-repeat",i.style.backgroundPosition="center",i.setAttribute("aria-hidden","true"),i}_extractNativeMenuIcon(t){const n=document.getElementById("adminmenu");if(!n)return null;let o;try{const f=new URL(t,window.location.href);o=(f.pathname.split("/").pop()||"")+f.search}catch{return null}if(!o)return null;const s=n.querySelectorAll("li.menu-top > a");let i=null;for(const f of Array.from(s))if(f.href.endsWith(o)){i=f.closest("li.menu-top");break}if(!i)return null;const r=i.querySelector(".wp-menu-image");if(!r)return null;const a=r.querySelector("img");if(a&&a.src){const f=document.createElement("img");return f.className="os-dock__item-img",f.src=a.src,f.alt="",f.setAttribute("aria-hidden","true"),f}const l=r.className.match(/\bdashicons-[\w-]+\b/);if(l&&l[0]!=="dashicons-before"){const f=document.createElement("span");return f.className=`dashicons ${l[0]}`,f.setAttribute("aria-hidden","true"),f}const d=window.getComputedStyle(r,"::before").backgroundImage;if(d&&d!=="none"&&!d.includes('url("")'))return this._makeSvgIcon(d);const u=window.getComputedStyle(r).backgroundImage;return u&&u!=="none"&&!u.includes('url("")')?this._makeSvgIcon(u):null}createLetterBadge(t){const n=document.createElement("span");n.className="os-dock__item-letter",n.setAttribute("aria-hidden","true");const o=t.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=mn(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(t,n,o){const s=q(v.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("os-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("os-dock__tooltip--visible")}))}positionTooltip(t,n){const o=t.getBoundingClientRect();this.tooltip.textContent=n,this.orientation==="bottom"?(this.tooltip.style.left=`${o.left+o.width/2}px`,this.tooltip.style.top=`${o.top-14}px`):this.orientation==="right"?(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.left}px`):(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.right+8}px`)}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(gn(t.url)||Ge(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(gn(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=ra(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 ce(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:ra(t.url)??this.deriveWindowId(t.url)}bindWindowEvents(){const t=()=>this.updateActiveStates();this.boundRefresh=t,document.addEventListener("os-window-opened",t),document.addEventListener("os-window-closed",t),document.addEventListener("os-window-focused",t),window.wp?.hooks?.addAction?.("os.os.switched",this.hooksNamespace,t),window.wp?.hooks?.addAction?.("os.os.closed",this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.DOCK_REFRESH_ACTIVE,this.hooksNamespace,t)}destroy(){document.removeEventListener("os-window-opened",this.boundRefresh),document.removeEventListener("os-window-closed",this.boundRefresh),document.removeEventListener("os-window-focused",this.boundRefresh),window.wp?.hooks?.removeAction?.("os.os.switched",this.hooksNamespace),window.wp?.hooks?.removeAction?.("os.os.closed",this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.WINDOW_RESTORED,this.hooksNamespace);for(const t of this.attentionTimers.values())window.clearTimeout(t);this.attentionTimers.clear();for(const t of this.peekTeardowns.values())t();for(this.peekTeardowns.clear(),this.tooltip.remove();this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.itemElements.clear(),this.systemItemElements.clear(),this.systemItems=[],this.zones={core:[],apps:[],controls:[]},this.container.removeAttribute("data-os-dock-placement")}updateActiveStates(){const t=this.windowManager.getFocused(),n=this.windowManager.getActiveDesktopId(),o=i=>(i.config.desktopId||n)===n,s=i=>i.state==="minimized";for(const i of this.items){const r=this.itemElements.get(i.id);if(!r)continue;const a=this.resolveItemBaseId(i);let l=this.windowManager.getAllByBaseId(a).filter(o);if(l.length===0&&i.url){const f=this.deriveWindowId(i.url);l=this.windowManager.getAll().filter(p=>{const g=p.config.baseId||p.id;if(g===a||g===f||g===i.id||p.config.parentUrl&&this.deriveWindowId(p.config.parentUrl)===f)return!0;if(p.config.url){const m=this.deriveWindowId(p.config.url);return m===a||m===f}return!1}).filter(o)}const c=l.length>0,d=c&&l.every(s),u=!!t&&o(t)&&!s(t)&&l.some(f=>f.id===t.id||(t.config.baseId||t.id)===a);r.classList.toggle("os-dock__item--active",c),r.classList.toggle("os-dock__item--focused",u),r.classList.toggle("os-dock__item--all-minimized",d),r.classList.toggle("os-dock__item--stacked",c&&l.length>1)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const a=this.windowManager.getById(i.id),l=i.isOpen?i.isOpen():!!a,c=!!a&&s(a),d=!!t&&t.id===i.id&&!s(t);r.classList.toggle("os-dock__item--active",l),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",c)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("os-show-desktop-active",o)}};We.instanceCounter=0,We.activeDragReset=null;let ri=We;function ep(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(sn("%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(sn("%d notification","%d notifications",t),t)),e.appendChild(s)}const tp=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),ya={id:"default",label:"Icon strip",description:"The shipped baseline — icon tiles with badges, tooltips, multi-instance chips, and attention animations.",icon:"dashicons-menu-alt",apiVersion:1,mount(e){const t=new ri(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[tp]: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 np(e){if(!e)return null;const n=e[tp];return n instanceof ri?n:null}function uk(){Cd(ya)}const op="os-desktop-theme-css",fk="os-desktop-theme-inline-css",ba="data-os-desktop-theme-css",sp="os-desktop-theme-changed";function ip(){return document.getElementById("os-shell")}function rp(){const e=[];for(const t of[op,fk]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${ba}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function ap(){for(const e of rp())e.remove()}function pk(e){const t=ip();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:rp().length>0}function lp(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 va(e){const t=Hs(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:uu(o),i=s?s.slug:null;if(i===n)return;const r=ip();if(!s)r?.removeAttribute("data-os-desktop-theme"),lp(null),ap(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!pk(s.slug)){if(ap(),s.cssUrl!==""){const l=document.createElement("link");l.id=op,l.rel="stylesheet",l.href=s.cssUrl,l.setAttribute(ba,s.slug),document.head.appendChild(l)}else if(s.cssText!==""){const l=document.createElement("style");l.setAttribute(ba,s.slug),l.textContent=s.cssText,document.head.appendChild(l)}}r?.setAttribute("data-os-desktop-theme",s.slug),lp(s.slug),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};T(v.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(sp,{detail:a}))}function J(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function hk(e){return!!e&&e.__wpdHtml===!0}const mk="$$wpd$$",De=/\$\$wpd\$\$(\d+)\$\$/g;function gk(e){let t=e[0];for(let n=1;n<e.length;n++)t+=`${mk}${n-1}$$`+e[n];return t}const cp=new WeakMap;function dp(e){const t=cp.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=gk(e);const o=[],s=(a,l)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const f of Array.from(u.attributes)){const p=f.name,g=f.value,m=p[0];if(De.test(g))if(De.lastIndex=0,m==="@"){const h=De.exec(g);De.lastIndex=0,o.push({path:l,kind:"event",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else if(m==="."){const h=De.exec(g);De.lastIndex=0,o.push({path:l,kind:"prop",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else if(m==="?"){const h=De.exec(g);De.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else{const h=[],b=[];let y=0,I;for(De.lastIndex=0;(I=De.exec(g))!==null;)h.push(g.slice(y,I.index)),b.push(Number(I[1])),y=I.index+I[0].length;h.push(g.slice(y)),o.push({path:l,kind:"attr",name:p,template:h,valueIndices:b}),u.setAttribute(p,"")}}}const c=Array.from(a.childNodes);let d=0;for(let u=0;u<c.length;u++){const f=c[u],p=u+d;if(f.nodeType===Node.TEXT_NODE){const g=f.textContent||"";if(!De.test(g)){De.lastIndex=0;continue}De.lastIndex=0;const m=f.parentNode;let h=0,b;const y=[],I=[];for(De.lastIndex=0;(b=De.exec(g))!==null;){b.index>h&&y.push(document.createTextNode(g.slice(h,b.index)));const R=document.createTextNode("");y.push(R),I.push({path:[...l,p+y.length-1],kind:"node",valueIndex:Number(b[1])}),h=b.index+b[0].length}h<g.length&&y.push(document.createTextNode(g.slice(h)));for(const R of y)m.insertBefore(R,f);m.removeChild(f),d+=y.length-1,o.push(...I)}else s(f,[...l,p])}};s(n.content,[]);const r={template:n,buildParts:a=>{const l=[];for(const c of o){let d=a;for(const u of c.path)d=d.childNodes[u];c.kind==="node"?l.push({kind:"node",valueIndex:c.valueIndex,child:{anchor:d,state:null}}):c.kind==="attr"?l.push({kind:"attr",element:d,name:c.name,template:c.template,valueIndices:c.valueIndices}):c.kind==="event"?l.push({kind:"event",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="prop"?l.push({kind:"prop",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="bool"&&l.push({kind:"bool",valueIndex:c.valueIndex,element:d,name:c.name})}return l}};return cp.set(e,r),r}const up=new WeakMap;function wk(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function yk(e,t){const n=up.get(t);if(n&&n.strings===e.strings&&wk(n,t)){ai(n.parts,e.values);return}const o=dp(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),ai(i,e.values),up.set(t,{strings:e.strings,parts:i,nodes:r})}function ai(e,t){for(const n of e)if(n.kind==="node")_a(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+=fp(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 _a(e,t){if(t==null||t===!1){e.state&&(Ft(e.state),e.state=null);return}if(Array.isArray(t)){Ek(e,t);return}if(hk(t)){_k(e,t);return}if(t instanceof Node){bk(e,t);return}vk(e,fp(t))}function bk(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Ft(n),li(e,[t]),e.state={shape:"node",node:t})}function vk(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Ft(n);const o=document.createTextNode(t);li(e,[o]),e.state={shape:"text",node:o,text:t}}function _k(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){ai(n.parts,t.values);return}n&&Ft(n);const o=dp(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);li(e,[s]),ai(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function Ek(e,t){const n=e.state;if(n?.shape==="array"&&n.entries.length===t.length){for(let s=0;s<t.length;s++)_a(n.entries[s],t[s]);return}n&&Ft(n);const o=[];for(const s of t){const i=document.createTextNode("");li(e,[i]);const r={anchor:i,state:null};_a(r,s),o.push(r)}e.state={shape:"array",entries:o}}function li(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Ft(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&&(Ft(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&&Ft(t.state),t.anchor.remove()}function fp(e){return e==null||e===!1?"":String(e)}const Nt=class Nt 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(pp)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=kk(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=pp(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&&yk(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(!Nt._lightStylesAdopted.has(t)){Nt._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)}}}};Nt.props=[],Nt.styles=[],Nt.shadow=!0,Nt._lightStylesAdopted=new WeakSet;let Se=Nt;function xe(e,t){customElements.get(e)||customElements.define(e,t)}function pp(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function kk(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const Sk=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function ue(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(Sk){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function Ak(e){const t=[],n=[];let o=null,s=e.parentElement;for(;s&&!(s===document.body||s===document.documentElement);){const r=s.id||"";if(r.startsWith("wp-window-")){o=r.slice(10);break}if(s.tagName.toLowerCase()==="os-tabpanel"){const a=s.getAttribute("for");a&&n.unshift(a)}s=s.parentElement}o&&t.push(Ea(o));for(const r of n)t.push("tab-"+Ea(r));const i=e.getAttribute("label");return i&&t.push(Ea(i)),t.length===0?"os-unnamed":"os-"+t.filter(r=>r!=="").join("-")}function Ea(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function hp(e){if(e.id)return e.id;const t=Ak(e);return e.id=t,t}const ci=new Map;function mp(e){if(!e||typeof e.id!="string"||e.id===""){typeof console<"u"&&console.warn("[openstation] Ignored invalid module registration:",e);return}if(typeof e.url!="string"||e.url===""){typeof console<"u"&&console.warn(`[openstation] Module "${e.id}" has no url; ignored.`);return}ci.set(e.id,e)}function Ck(){return Array.from(ci.keys())}async function ka(e){if(!e||e.length===0)return;const t=e.filter(n=>!ci.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${Ck().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=ci.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():ke(o.url)}))}const wn=le("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function Ik(e){wn.state.pending.set(e.id,e)}function di(e){wn.state.pending.delete(e)}function xk(e){return(window.openStationWallpapers||{})[e]??null}function gp(e){const t=wn.state.inflight.get(e);if(t)return t;const n=wn.state.pending.get(e);if(!n)return Promise.resolve(null);const o=(async()=>{try{await ke(n.scriptUrl,{translations:n.scriptTranslations,l10n:n.scriptL10n,before:n.scriptBefore,after:n.scriptAfter})}catch(i){return T(v.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=xk(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return T(v.SHELL_ERROR,{scope:"wallpaper-missing-def",id:n.id,error:new Error(`[openstation] No wallpaper def on window.openStationWallpapers["${n.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)}),null;try{hn(s)}catch(i){return T(v.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return di(n.id),s})().finally(()=>{wn.state.inflight.delete(e)});return wn.state.inflight.set(e,o),o}function Lk(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 gp(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await ka(o.needs),o.mount(t,n))}}}const dt=ue`: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 ) )}`,Tk=ue` .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%}}`,Sa=ue` .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%}}`,wp=ue` .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}}`,yp=ue` .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}}`,bp=ue` .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}}`,vp=ue` .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%}}`,Nk=ue` .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}}`,Aa=ue` 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}}`,Dk=ue` 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}}`,_p=ue` @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}}`;ue` ${dt} ${Tk} ${Sa} ${wp} ${yp} ${bp} ${vp} ${Nk} ${Aa} ${Dk} ${_p} `;const Rk=ue` ${dt}: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}`,Ep='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',hs=class hs extends Se{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(Ep)),o=Array.from(t.querySelectorAll(Ep));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 J` | |
| 2 | - <div part="dialog" class="dialog" tabindex="-1"> | |
| 3 | - ${t?J` | |
| 4 | - <div class="header"> | |
| 5 | - <h2 class="title">${t}</h2> | |
| 6 | - <div class="header-actions"> | |
| 7 | - <slot name="header-actions"></slot> | |
| 8 | - ${n?J``:J`<button | |
| 9 | - type="button" | |
| 10 | - class="close" | |
| 11 | - aria-label="Close" | |
| 12 | - @click=${()=>this._cancel()} | |
| 13 | - >×</button>`} | |
| 14 | - </div> | |
| 15 | - </div> | |
| 16 | - `:J``} | |
| 17 | - <div class="body"> | |
| 18 | - <slot></slot> | |
| 19 | - </div> | |
| 20 | - <div class="footer"> | |
| 21 | - <slot name="footer"></slot> | |
| 22 | - </div> | |
| 23 | - </div> | |
| 24 | - `}};hs.props=["open","title","size","mandatory"],hs.styles=[Rk],hs.help=void 0;let Ca=hs;xe("os-modal",Ca);const Ok=ue` ${dt} ${Sa} ${wp} ${yp} ${bp} ${_p}: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 )}}`,ms=class ms extends Se{render(){const t=this.disabled!==null,n=this.busy!==null,o=this.type||"button";return J` | |
| 1 | +var openStation=function(oa){"use strict";var sa=typeof document<"u"?document.currentScript:null;function _t(){const e=window.wp?.hooks;if(!e)throw new Error("[openstation] `window.wp.hooks` is not available. The plugin declares `wp-hooks` as a script dependency; if you are seeing this error, verify the enqueue order.");return e}function pt(e,t,n,o){_t().addFilter(e,t,n,o)}function ee(e,t,n,o){_t().addAction(e,t,n,o)}function jt(e,t){return _t().removeAction(e,t)}function FE(e,t){return _t().removeFilter(e,t)}function J(e,t,...n){return _t().applyFilters(e,t,...n)}function A(e,...t){_t().doAction(e,...t)}function ou(e){return _t().didAction(e)}function HE(){return _t()}const v={INIT:"os.init",WALLPAPERS:"os.wallpapers",GAMES:"os.games",UNFOCUS_EFFECTS:"os.unfocus-effects",WINDOW_REVEALS:"os.window-reveals",WALLPAPER_MOUNTING:"os.wallpaper.mounting",WALLPAPER_MOUNTED:"os.wallpaper.mounted",WALLPAPER_UNMOUNTING:"os.wallpaper.unmounting",WALLPAPER_MOUNT_FAILED:"os.wallpaper.mount-failed",WALLPAPER_VISIBILITY:"os.wallpaper.visibility",WALLPAPER_SUSPEND:"os.wallpaper.suspend",WALLPAPER_PREVIEW_PARAMS:"os.wallpaper.preview-params",WALLPAPER_SETTINGS_CHANGED:"os.wallpaper.settings-changed",IFRAME_READY:"os.iframe.ready",IFRAME_ERROR:"os.iframe.error",IFRAME_NETWORK_COMPLETED:"os.iframe.network-completed",SHELL_ERROR:"os.shell.error",BROADCAST:"os.broadcast",MONITOR_ENTRY:"os.monitor.entry",WALLPAPER_SURFACES:"os.wallpaper.surfaces",DESKTOP_THEME_CHANGED:"os.os-theme.changed",DESKTOP_THEME_ICON:"os.os-theme.icon",DESKTOP_THEME_ICON_COLOR:"os.os-theme.icon-color",WALLPAPERS_SERVER_CHANGED:"os.wallpapers.server-changed",EXTENDED_OPTIONS_CHANGED:"os.extended-options.changed",WINDOW_GEOMETRY:"os.window.geometry",WINDOW_OPENED:"os.window.opened",WINDOW_CONTENT_LOADING:"os.window.content-loading",WINDOW_CONTENT_LOADED:"os.window.content-loaded",WINDOW_LOADING_OVERLAY:"os.window.loading-overlay",WINDOW_REOPENED:"os.window.reopened",WINDOW_MENU_OPENED:"os.window.menu-opened",WINDOW_CLOSING:"os.window.closing",WINDOW_CLOSED:"os.window.closed",WINDOW_FOCUSED:"os.window.focused",WINDOW_BLURRED:"os.window.blurred",WINDOW_MINIMIZED:"os.window.minimized",WINDOW_RESTORED:"os.window.restored",WINDOW_CHILD_BLOCKED:"os.window.child-blocked",WINDOW_MAXIMIZED:"os.window.maximized",WINDOW_UNMAXIMIZED:"os.window.unmaximized",WINDOW_FULLSCREEN_ENTERED:"os.window.fullscreen-entered",WINDOW_FULLSCREEN_EXITED:"os.window.fullscreen-exited",WINDOW_AUTO_EXIT_FULLSCREEN:"os.window.auto-exit-fullscreen",WINDOW_FOCUS_ON_DRAG_HOVER:"os.window.focus-on-drag-hover",WINDOW_BOUNDS_CHANGED:"os.window.bounds-changed",WINDOW_MOVED:"os.window.moved",WINDOW_RESIZED:"os.window.resized",WINDOW_DRAG_START:"os.window.drag-start",WINDOW_DRAG_END:"os.window.drag-end",WINDOW_RESIZE_START:"os.window.resize-start",WINDOW_RESIZE_END:"os.window.resize-end",WINDOW_DETACHED:"os.window.detached",WINDOW_RELOADED:"os.window.reloaded",WINDOW_TITLE_CHANGED:"os.window.title-changed",WINDOW_HIGHLIGHT_CHANGED:"os.window.highlight-changed",WINDOW_BODY_RESIZED:"os.window.body-resized",NATIVE_WINDOW_BEFORE_RENDER:"os.native-window.before-render",NATIVE_WINDOW_AFTER_RENDER:"os.native-window.after-render",NATIVE_WINDOW_BEFORE_CLOSE:"os.native-window.before-close",WINDOW_CHROME_THEME:"os.window.chrome.theme",WINDOW_CHROME_CONTROLS:"os.window.chrome.controls",WINDOW_CHROME_SLOT:"os.window.chrome.slot",WINDOW_CHROME_RENDER:"os.window.chrome.render",WINDOW_CHROME_APPLIED:"os.window.chrome.applied",WINDOW_CHROME_THEME_CHANGED:"os.window.chrome.theme-changed",DESKTOP_ICON_CLICKED:"os.os-icon.clicked",DESKTOP_ICONS_RENDERED:"os.os-icons.rendered",ICON_BADGE_CHANGED:"os.icon.badge-changed",COMPONENTS_REGISTERED:"os.components.registered",DOCK_ITEM_APPENDED:"os.dock.item-appended",DOCK_ITEM_REMOVED:"os.dock.item-removed",DOCK_BEFORE_RENDER:"os.dock.before-render",DOCK_AFTER_RENDER:"os.dock.after-render",DOCK_REFRESH_ACTIVE:"os.dock.refresh-active",DOCK_TILE_CLASS:"os.dock.tile-class",DOCK_TILE_ELEMENT:"os.dock.tile-element",DOCK_TILE_RENDERED:"os.dock.tile-rendered",DOCK_TILE_TOOLTIP:"os.dock.tile-tooltip",DOCK_PEEK_CARD_CONTENT:"os.dock.peek-card-content",DOCK_PEEK_CARD_ELEMENT:"os.dock.peek-card-element",CONSTELLATION_PANEL:"os.constellation.panel",CONSTELLATION_OPENED:"os.constellation.opened",CONSTELLATION_CLOSED:"os.constellation.closed",OVERVIEW_ENTERING:"os.overview.entering",OVERVIEW_ENTERED:"os.overview.entered",OVERVIEW_EXITING:"os.overview.exiting",OVERVIEW_EXITED:"os.overview.exited",OVERVIEW_WINDOW_HOVER:"os.overview.window-hover",OVERVIEW_WINDOW_UNHOVER:"os.overview.window-unhover",OVERVIEW_WINDOW_CLICK:"os.overview.window-click",WORK_AREA_CHANGED:"os.work-area.changed",ARRANGE_CASCADE_STARTING:"os.arrange.cascade.starting",ARRANGE_CASCADE_APPLIED:"os.arrange.cascade.applied",ARRANGE_TILE_STARTING:"os.arrange.tile.starting",ARRANGE_TILE_APPLIED:"os.arrange.tile.applied",ARRANGE_TILE_DIMENSIONS:"os.arrange.tile.dimensions",ARRANGE_COLUMNS_STARTING:"os.arrange.columns.starting",ARRANGE_COLUMNS_APPLIED:"os.arrange.columns.applied",ARRANGE_FOCUS_SPLIT:"os.arrange.focus.split",ARRANGE_FOCUS_STARTING:"os.arrange.focus.starting",ARRANGE_FOCUS_APPLIED:"os.arrange.focus.applied",ARRANGE_SNAP_CHANGED:"os.arrange.snap.changed",ARRANGE_SNAP_CELL_SIZE:"os.arrange.snap.cell-size",POINTER_SHAKE:"os.pointer.shake",GRID_SNAP_DIMENSIONS:"os.grid-snap.dimensions",GRID_SNAP_ARMED:"os.grid-snap.armed",GRID_SNAP_CHANGED:"os.grid-snap.changed",GRID_SNAP_ANCHOR_RESET:"os.grid-snap.anchor-reset",GRID_SNAP_CANCELED:"os.grid-snap.canceled",GRID_SNAP_COMMITTED:"os.grid-snap.committed",GRID_SNAP_REFLOWED:"os.grid-snap.reflowed",SNAP_ZONE_PENDING:"os.snap.zone-pending",SNAP_ZONE_CANCELED:"os.snap.zone-canceled",SNAP_ZONE_COMMITTED:"os.snap.zone-committed",SNAP_SPLIT_FILLED:"os.snap.split-filled",WIDGETS:"os.widgets",WIDGET_MOUNTING:"os.widget.mounting",WIDGET_MOUNTED:"os.widget.mounted",WIDGET_UNMOUNTING:"os.widget.unmounting",WIDGET_MOUNT_FAILED:"os.widget.mount-failed",WIDGET_ADDED:"os.widget.added",WIDGET_REMOVED:"os.widget.removed",DESKTOP_CREATED:"os.os.created",DESKTOP_CLOSED:"os.os.closed",DESKTOP_SWITCHED:"os.os.switched",DESKTOP_RENAMED:"os.os.renamed",WINDOW_DESKTOP_CHANGED:"os.os.window-moved",PRIMARY_DESKTOP_ID:"os.primary-desktop-id",WORKSPACE_PRESETS:"os.workspaces.presets",WORKSPACE_PROFILE:"os.workspaces.profile",WORKSPACE_UPDATED:"os.workspaces.updated",WORKSPACE_PROVISIONED:"os.workspaces.provisioned",WINDOWS_BEFORE_CLOSE_ALL:"os.windows.before-close-all",WINDOWS_CLOSE_ALL:"os.windows.close-all",WINDOWS_AFTER_CLOSE_ALL:"os.windows.after-close-all",COMMAND_BEFORE_RUN:"os.command.before-run",COMMAND_AFTER_RUN:"os.command.after-run",COMMAND_ERROR:"os.command.error",SHELL_RESIZED:"os.shell.resized",SHELL_VISIBILITY:"os.shell.visibility",CONNECTION_OPENED:"os.connection.opened",CONNECTION_CLOSED:"os.connection.closed",CONNECTION_MESSAGE:"os.connection.message",IFRAME_CONNECTION_REQUEST:"os.iframe.connection-request",WINDOW_CONTENT_CHANGED:"os.window-links.content-changed",WINDOW_LINK_GROUPS_CHANGED:"os.window-links.groups-changed",WINDOW_LINKS_CONTENT:"os.window-links.content",WINDOW_LINK_GROUPS:"os.window-links.groups",WINDOW_LINK_EDGES:"os.window-links.edges",RELATED_ENTITIES_ITEMS:"os.related-entities.items",WINDOW_LINK_RENDERERS:"os.window-links.renderers",WINDOW_LINK_RENDERER:"os.window-links.renderer",EDITOR_PREVIEW_WINDOW_CONFIG:"os.editor-preview.window-config",EDITOR_PREVIEW_LIVE:"os.editor-preview.live",EDITOR_PREVIEW_OPENED:"os.editor-preview.opened",EDITOR_PREVIEW_CLOSED:"os.editor-preview.closed",REVISIONS_WINDOW_CONFIG:"os.revisions.window-config",REVISIONS_OPENED:"os.revisions.opened",FILE_DROP_FILES_DETECTED:"os.drop.files-detected",FILE_DROP_FILES_REJECTED:"os.drop.files-rejected",FILE_DROP_DIALOG_FIELDS:"os.drop.dialog-fields",FILE_DROP_BEFORE_UPLOAD:"os.drop.before-upload",FILE_DROP_UPLOAD_STARTED:"os.drop.upload-started",FILE_DROP_UPLOAD_PROGRESS:"os.drop.upload-progress",FILE_DROP_AFTER_UPLOAD:"os.drop.after-upload",FILE_DROP_UPLOAD_FAILED:"os.drop.upload-failed",AUTH_LOST:"os.auth.lost",AUTH_RESTORED:"os.auth.restored",MODE_CHANGED:"os.mode.changed",SESSION_SNAPSHOT:"os.session.snapshot"};let GE=0;function su(e){if(ou(v.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++GE}`;ee(v.INIT,t,e)}function zE(){return ou(v.INIT)>0}const ia="data-os-mode";function iu(e,t){e.getAttribute(ia)!==t&&e.setAttribute(ia,t)}function Vt(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(ia)==="mobile"}const ra="data-os-display";function ru(e,t){e.getAttribute(ra)!==t&&e.setAttribute(ra,t)}function jE(e=typeof document<"u"?document.documentElement:null){return!!e&&e.getAttribute(ra)==="standalone"}const VE=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"],aa=[];function KE(e){if(!e.pathname.endsWith("/admin.php")||!e.searchParams.get("page"))return aa;const t=e.searchParams.get("action");return t==="edit"&&e.searchParams.get("id")?["id"]:t==="new"?["action"]:aa}function au(e){let t=e;try{t=decodeURIComponent(e)}catch{t=e}return t.replace(/\.php/g,"-php").replace(/[?&=/]/g,"-").replace(/[^a-zA-Z0-9_-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")||"index"}function fe(e,t){let n=null;try{n=new URL(e,t)}catch{n=null}if(n){const s=new URL(t).pathname,i=n.pathname.replace(s,"").replace(/^\/+/,""),r=new URLSearchParams,a=[...VE,...KE(n)];for(const c of a){const d=n.searchParams.get(c);d&&r.set(c,d)}const l=r.toString();return au(l?`${i}?${l}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),au(o)}function qE(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function YE(e){e.style.setProperty("--os-file-tile-enter-delay",`${(Math.random()*.25).toFixed(3)}s`),e.style.setProperty("--os-file-tile-enter-duration",`${(.3+Math.random()*.25).toFixed(3)}s`)}function cu(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("openstation_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function In(e){try{const t=new URL(e,window.location.origin);return t.searchParams.delete("openstation_chromeless"),t.searchParams.delete("desktop_mode_portal"),t.searchParams.delete("_wp_http_referer"),t.searchParams.sort(),t.pathname.replace(/\/+$/,"")+"?"+t.searchParams.toString()}catch{return e}}function lu(e){if(typeof e!="string"||e===""||typeof DOMParser>"u")return"";let t;try{t=new DOMParser().parseFromString(e,"image/svg+xml")}catch{return""}const n=t.documentElement;if(!n||n.nodeName.toLowerCase()!=="svg"||t.getElementsByTagName("parsererror").length>0)return"";const o=new Set(["script","style","foreignobject","iframe","object","embed"]),s=i=>{const r=Array.from(i.children);for(const a of r){if(o.has(a.nodeName.toLowerCase())){a.remove();continue}for(const l of Array.from(a.attributes)){const c=l.name.toLowerCase(),d=l.value.trim().toLowerCase();if(c.startsWith("on")){a.removeAttribute(l.name);continue}d.startsWith("javascript:")&&a.removeAttribute(l.name)}s(a)}};s(n);for(const i of Array.from(n.attributes)){const r=i.name.toLowerCase(),a=i.value.trim().toLowerCase();(r.startsWith("on")||a.startsWith("javascript:"))&&n.removeAttribute(i.name)}return n.outerHTML}let An=null;function oi(){return!!window.openStationWindowSystem}function du(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(oi()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){oi()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osWindowSystem="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load window-system bundle"))),document.head.appendChild(i)})}function XE(){return window.openStationConfig?.windowSystemBundleUrl??""}function ZE(e){!e||oi()||An||(An=du(e).catch(t=>{An=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function JE(e){if(oi())return window.openStationWindowSystem;if(!e){const t=window.openStationWindowSystem;if(t)return t;throw new Error("[openstation] ensureWindowSystemLoaded(): no bundle URL configured and `window.openStationWindowSystem` is not pre-registered.")}return An||(An=du(e)),await An,window.openStationWindowSystem}let Cn=null;function Lo(){return!!window.openStationShellOverlays}function uu(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(Lo()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not set `window.openStationShellOverlays`."))};if(o){Lo()?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osShellOverlays="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load shell-overlays bundle"))),document.head.appendChild(i)})}function QE(e){!e||Lo()||Cn||(Cn=uu(e).catch(t=>{Cn=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function ca(e){return Lo()||!e?Promise.resolve():(Cn||(Cn=uu(e)),Cn)}function la(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function si(e,t){const n=la();if(Lo()||!n){t();return}ca(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const fu="desktop-mode";function da(){return window.wp?.i18n}function b(e,t=fu){return da()?.__(e,t)??e}function Kt(e,t,n,o=fu){return da()?._n(e,t,n,o)??(n===1?e:t)}function le(e,...t){const n=da()?.sprintf;if(n)return n(e,...t);let o=0;return e.replace(/%(?:(\d+)\$)?[sd]/g,(s,i)=>{const r=i?Number.parseInt(i,10)-1:o++;return String(t[r]??"")})}const e_=900,t_=260,ua="os-desktop-name-hud";let Je=null,St=null;function n_(e,t){t.trim()&&(St!==null&&window.clearTimeout(St),Je||(Je=document.createElement("div"),Je.className=ua,Je.setAttribute("role","status")),Je.textContent=t,Je.classList.remove(`${ua}--out`),e.appendChild(Je),St=window.setTimeout(()=>{Je?.classList.add(`${ua}--out`),St=window.setTimeout(()=>{Je?.remove(),St=null},t_)},e_))}function o_(){St!==null&&(window.clearTimeout(St),St=null),Je?.remove(),Je=null}function s_(e,t){if(!e||typeof e!="object")return!1;const n=e.cols,o=e.rows;return typeof n!="number"||typeof o!="number"||!Number.isFinite(n)||!Number.isFinite(o)||n<1||o<1?!1:Math.floor(n)*Math.floor(o)>=t}function i_(e){if(!e||typeof e!="object")return!1;const t=e.cellWidth,n=e.cellHeight;return typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)?!1:t>0&&n>0}function r_(e,t,n){if(e<=1)return{cols:1,rows:1};const o=t/Math.max(1,n),s=6;let i={cols:e,rows:1,score:1/0};for(let r=1;r<=Math.min(s,e);r++){const a=Math.min(s,Math.ceil(e/r));if(r*a<e)continue;const l=t/r/Math.max(1,n/a),c=Math.abs(l-o),d=r*a-e,u=c+d*.05;u<i.score&&(i={cols:r,rows:a,score:u})}return{cols:i.cols,rows:i.rows}}function fa(e,t,n=0){const o=e.length;if(o===0)return[];const s=Math.ceil(Math.sqrt(o)),i=Math.ceil(o/s),r=40,a=24,l=34,c=(t.width-r*2-a*(s-1))/s,d=(t.height-r*2-n-a*(i-1))/i,u=Math.max(40,d-l);return e.map((f,p)=>{const g=p%s,h=Math.floor(p/s),m=t.left+r+g*(c+a),_=t.top+n+r+h*(d+a)+l,I=f.element.offsetWidth,O=f.element.offsetHeight,$=Math.min(c/I,u/O),S=I*$,R=O*$;return{win:f,x:m+(c-S)/2,y:_+(u-R)/2,scale:$}})}const a_=["close","check","chevron-right","arrow-up-right","plus","search","pin","trash","download","settings","info","bell","more","maximize","edit","color","wallpaper","warning","minimize"],pu=["window","windows","dock","spaces","copilot","snap","command","apps","widgets","user","lock"],c_=[...a_,...pu],hu={close:{a:'fill="currentColor"',b:'<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 mu(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function gu(e){return Object.prototype.hasOwnProperty.call(hu,e)?hu[e]:null}function l_(e){return gu(e)!==null}function qt(e,t={}){const n=gu(e);if(!n)return"";const{size:o=24,className:s,title:i,rotate:r}=t,a=['xmlns="http://www.w3.org/2000/svg"','viewBox="0 0 24 24"'];o!=null&&a.push(`width="${o}"`,`height="${o}"`),a.push(n.a),s&&a.push(`class="${mu(s)}"`),i?a.push('role="img"',`aria-label="${mu(i)}"`):a.push('aria-hidden="true"','focusable="false"');const l=r?`<g transform="rotate(${r} 12 12)">${n.b}</g>`:n.b;return`<svg ${a.join(" ")}>${l}</svg>`}function wu(e,t={}){const n=qt(e,t),o=document.createElement("div");o.innerHTML=n;const s=o.firstElementChild;return s instanceof SVGSVGElement?s:document.createElementNS("http://www.w3.org/2000/svg","svg")}function d_(e,t={}){const n=qt(e,t);return n?`data:image/svg+xml,${encodeURIComponent(n)}`:""}const u_=Object.freeze({svg:qt,node:wu,dataUri:d_,names:Object.freeze([...c_]),ours:Object.freeze([...pu]),has:l_}),f_=120,p_=56;function yu(e){return f_+(e?.querySelector(".os-overview-top-bar__header")?p_:0)}const h_="openstation";function Ln(e,t){let n;if(typeof e=="string")try{n=new URL(e,t??(typeof window<"u"?window.location.href:void 0))}catch{return!1}else n=e;return n.pathname.slice(n.pathname.lastIndexOf("/")+1)==="admin.php"&&n.searchParams.get("page")===h_}const vu=["target","intent","openstation_overview","openstation_hop","openstation_hop_from"];function m_(e,t){let n;try{n=new URL(typeof e=="string"?e:e.href,t??(typeof window<"u"?window.location.href:void 0))}catch{return null}return!Ln(n)||!vu.some(o=>n.searchParams.has(o))?null:(vu.forEach(o=>n.searchParams.delete(o)),n.href)}const bu="__openStationSharedStores";function g_(){const e=window;let t=e[bu];return t||(t=new Map,e[bu]=t),t}function ae(e,t){const n=g_();let o=n.get(e);o||(o={state:t(),listeners:new Set,rebuild:t},n.set(e,o));const s={get state(){return o.state},set state(i){o.state=i},getState(){return o.state},notify(){for(const i of Array.from(o.listeners))try{i(o.state)}catch(r){console.error(`[desktop-mode/shared-store:${e}] subscriber threw:`,r)}},subscribe(i){return o.listeners.add(i),()=>{o.listeners.delete(i)}},setState(i){const r=o.state;if(typeof r!="object"||r===null){console.warn(`[desktop-mode/shared-store:${e}] setState called on a primitive store; use the state setter instead.`);return}Object.assign(r,i),s.notify()},reset(){const i=o.rebuild(),r=o.state;if(typeof r=="object"&&r!==null&&typeof i=="object"&&i!==null){const a=r;for(const l of Object.keys(a))delete a[l];Object.assign(a,i)}else o.state=i;o.listeners.clear()}};return s}const w_="os_tab",y_="os_person_view";function v_(e){return e.searchParams.has(y_)}const To=ae("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function b_(e){To.state.deps=e}function ht(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.nativeWindowId!="string"||e.nativeWindowId==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=To.state.remaps,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>pa(e.id)}function pa(e){const t=To.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function Tn(e){const{deps:t,remaps:n}=To.state;if(!t||!e)return null;let o;try{o=new URL(e,t.adminUrl)}catch{return null}const s=t.getSnapshot();for(const i of n)if(i.matches(e,o)&&!(i.enabled&&!i.enabled(s)))return i.nativeWindowId;return null}function Me(e,t={}){const{deps:n,remaps:o}=To.state;if(!n||!e)return!1;let s;try{s=new URL(e,n.adminUrl)}catch{return!1}const i=n.getSnapshot();for(const r of o){if(!r.matches(e,s)||r.enabled&&!r.enabled(i))continue;if(r.onMatch)try{r.onMatch(e,s)}catch(u){console.warn(`[openstation] URL remap onMatch hook threw for "${r.id}":`,u)}let a;const l=s.searchParams.get(w_);if(r.params)try{a=r.params(e,s)??void 0}catch(u){console.warn(`[openstation] URL remap params hook threw for "${r.id}":`,u)}l&&/^[a-z0-9_-]+$/.test(l)&&(a={...a??{},tab:l});const c=t.newInstance&&n.openNewById?n.openNewById:n.openById;if(a?c(r.nativeWindowId,{params:a}):c(r.nativeWindowId))return!0}return!1}const Eu="X-WP-Nonce";function _u(e,t){const n=E_();if(!n)return t;const o=__(e);if(!o||!S_(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Eu)?t:(i.set(Eu,n),{...t??{},headers:i})}function E_(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function __(e){try{const t=typeof window<"u"&&window.location?window.location.href:void 0;return typeof e=="string"?new URL(e,t):e instanceof URL?e:typeof Request<"u"&&e instanceof Request?new URL(e.url,t):null}catch{return null}}function S_(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Ae(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=_u(e,t);return fetch(e,s)}class No extends Error{constructor(t,n){super(t||n.serverMessage||`HTTP ${n.status}`),this.name="RestError",this.status=n.status,this.code=n.code,this.data=n.data,this.serverMessage=n.serverMessage??""}}function Su(e){return e instanceof No}function ku(e){const t=typeof e=="object"&&e!==null?e:void 0;return{code:typeof t?.code=="string"?t.code:void 0,data:t?.data,serverMessage:typeof t?.message=="string"?t.message:""}}function mt(e,t,n=""){return new No(n,{status:e,...ku(t)})}async function Nn(e,t=""){let n=null;try{n=await e.json()}catch{n=null}return mt(e.status,n,t)}function Iu(e,t){return new No(t,{status:e,code:"openstation_bad_response"})}function k_(e){const{prefix:t,source:n,conflict:o}=e;return async(s,i={})=>{const r=new Headers(i.headers??{});r.set("X-WP-Nonce",e.nonce()),i.body&&!r.has("Content-Type")&&r.set("Content-Type","application/json");const a=await Ae(e.url(s),{...i,headers:r,credentials:"same-origin"},{source:n}),l=await a.text();let c=null,d=null;if(l)try{c=JSON.parse(l)}catch(u){d=u}if(!a.ok){if(a.status===409&&o){const p=o(c);if(p)throw p}const{code:u,serverMessage:f}=ku(c);throw mt(a.status,c,`${t} ${a.status}: ${u??""} ${f}`.trim())}if(c===null){if(d&&l){const u=l.slice(0,120).replace(/\s+/g," ");throw Iu(a.status,`${t} ${a.status} returned non-JSON body — ${d.message}. First 120 chars: ${u}`)}throw Iu(a.status,`${t} ${a.status}: empty or unparseable body.`)}return c}}const Oo=ae("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),gt=Oo.state.registry,ha=Oo.state.listeners,I_=/^[a-z0-9_-]+$/;function Au(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!I_.test(e.id))throw new TypeError(`[openstation] registerDockRailRenderer: id must match /^[a-z0-9_-]+$/, got: ${String(e.id)}`);if(typeof e.label!="string"||e.label==="")throw new TypeError("[openstation] registerDockRailRenderer: label must be a non-empty string.");if(typeof e.mount!="function")throw new TypeError("[openstation] registerDockRailRenderer: mount must be a function.");if(e.apiVersion!==void 0&&e.apiVersion!==1)throw new TypeError(`[openstation] registerDockRailRenderer: unsupported apiVersion ${e.apiVersion} (this shell speaks v1).`);gt.set(e.id,e),ii()}function A_(e){gt.delete(e)&&ii()}function C_(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(gt.entries()))o.owner===e&&(gt.delete(n),t++);return t>0&&ii(),t}function L_(e){return gt.get(e)}function T_(){return Array.from(gt.values())}function N_(e){return ha.add(e),()=>{ha.delete(e)}}function O_(e){Oo.state.activeId!==e&&(Oo.state.activeId=e,ii())}function ma(){return gt.get(Oo.state.activeId)??gt.get("default")??gt.values().next().value}function ii(){const e=Array.from(ha);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function Yt(e,t){if(!e||typeof e!="object")return["def (not an object)"];const n=e,o=[];for(const s of t)s.valid(n)||o.push(`${s.field} (${s.message})`);return o}class D_ extends Error{constructor(t,n,o){super(`[openstation] ${t} registration rejected — fields: `+n.join(", ")+"."),this.name="RegistrationError",this.kind=t,this.errors=n,this.def=o}}function Oe(e,t,n){if(t.length!==0)throw new D_(e,t,n)}function Cu(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const kt=[[0,0],[100,0],[100,100],[0,100]],R_=48,x_=80,ga=6,wa=8,Lu=4,Tu=3,Nu=64,ya=105,It=2;function Ou(e){return`${Math.round(e*1e3)/1e3}%`}function At(e){return e.slice().reverse()}function Do(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function M_(e,t,n,o){const s=[];for(let i=0;i<o;i++){const r=i/o*Math.PI*2;s.push([e+Math.cos(r)*n,t+Math.sin(r)*n])}return s}function it(e,t=[]){const n=[],o=s=>{n.push(`${Ou(s[0])} ${Ou(s[1])}`)};for(const s of e)o(s);if(t.length>0){o(e[0]);for(const s of t){for(const i of s)o(i);o(s[0]),o(e[0])}}return`polygon( ${n.join(", ")} )`}function Du(e){return it(kt,[At(M_(50,50,e,R_))])}function Ru(e){return it(kt,[At(Do(50-e,-It,50+e,100+It))])}function xu(e){const t=100/ga,n=[];for(let o=0;o<ga;o++){const s=o*t;n.push(At(Do(-It,s,100+It,s+e)))}return it(kt,n)}function Mu(e){return it(kt,[At(Do(-It,50-e,100+It,50+e))])}function Wu(e){const t=100/wa,n=[];for(let o=0;o<wa;o++){const s=o*t;n.push(At(Do(s,-It,s+e,100+It)))}return it(kt,n)}function Pu(e){return it(kt,[At([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function $u(e){const t=100/Lu,n=100/Tu,o=[];for(let s=0;s<Tu;s++)for(let i=0;i<Lu;i++){const r=i*t+t/2,a=s*n+n/2,l=t/2*e,c=n/2*e;o.push(At(Do(r-l,a-c,r+l,a+c)))}return it(kt,o)}function Uu(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<Nu;s++){const i=t+s/(Nu-1)*n;o.push([50+Math.cos(i)*ya,50+Math.sin(i)*ya])}return it(kt,[At(o)])}function W_(){return{from:Du(0),to:Du(x_)}}function P_(){return{from:Ru(0),to:Ru(52)}}function $_(){return{from:xu(0),to:xu(100/ga+.5)}}function U_(){return{from:Mu(0),to:Mu(52)}}function B_(){return{from:Wu(0),to:Wu(100/wa+.5)}}function F_(){return{from:Pu(0),to:Pu(ya)}}function H_(){return{from:$u(0),to:$u(1.04)}}function G_(){return{from:Uu(0),to:Uu(360)}}function z_(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function j_(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function V_(){return{from:it([[-60,0],[100,0],[100,100],[0,100]]),to:it([[100,0],[260,0],[260,100],[160,100]])}}const va=6,ba=100,On=ba/2,ri=200,Bu=90,Fu=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],K_="#101014",q_=1.25,Dn="http://www.w3.org/2000/svg";let Y_=0;function ai(e){return Math.round(e*1e3)/1e3}function Ea(e){return e/va*Math.PI*2-Math.PI/2}function X_(e){const n=Ea(e)+Math.PI/va+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function Z_(e){const t=Ea(e),n=Ea(e+1);return[[On,On],[On+Math.cos(t)*ri,On+Math.sin(t)*ri],[On+Math.cos(n)*ri,On+Math.sin(n)*ri]]}function Hu(e,t){const n=Z_(e),o=document.createElementNS(Dn,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${ai(s)} ${ai(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",Fu[e%Fu.length]),o.setAttribute("stroke",K_),o.setAttribute("stroke-width",String(q_)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function J_(){const e=`os-iris-${++Y_}`,t=document.createElementNS(Dn,"svg");t.setAttribute("viewBox",`0 0 ${ba} ${ba}`),t.setAttribute("preserveAspectRatio","none"),t.setAttribute("aria-hidden","true"),t.style.width="100%",t.style.height="100%",t.style.display="block";const n=document.createElementNS(Dn,"defs"),o=document.createElementNS(Dn,"mask");o.setAttribute("id",e);const s=document.createElementNS(Dn,"g"),i=document.createElementNS(Dn,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let l=0;l<va;l++){const c=Hu(l,!0),d=Hu(l,!1);s.appendChild(c),i.appendChild(d),r.push({el:c,index:l},{el:d,index:l})}o.appendChild(s),n.appendChild(o),t.appendChild(n),t.appendChild(i);const a=document.createElement("div");return a.appendChild(t),{element:a,play:l=>r.map(({el:c,index:d})=>{const u=X_(d),f=ai(u.x*Bu),p=ai(u.y*Bu);return c.animate([{transform:"translate( 0px, 0px )"},{transform:`translate( ${f}px, ${p}px )`}],{duration:l.duration,easing:l.easing,delay:l.delay,fill:"both"})})}}const Ro="none",Q_=460,eS="cubic-bezier( 0.33, 0, 0.2, 1 )",Gu=80,zu=4e3,tS=70,nS=600,ju=ae("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),ci=ju.state.registry,oS=ju.state.listeners,Vu=/^[a-z0-9_/-]+$/;function Ku(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function sS(e){return typeof e!="number"||!Number.isFinite(e)?Q_:Math.min(zu,Math.max(Gu,e))}const _a=0;function qu(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?_a:Math.min(zu,Math.max(Gu,e))}function Rn(e){return typeof e!="number"||!Number.isFinite(e)?tS:Math.min(nS,Math.max(0,e))}function Yu(e){return typeof e.render=="function"?[]:Array.isArray(e.layers)&&e.layers.length>0?e.layers:typeof e.from=="string"&&typeof e.to=="string"?[{from:e.from,to:e.to}]:[]}function Xu(e,t){const n=[],o=typeof e.from=="string"&&e.from.trim()!=="",s=typeof e.to=="string"&&e.to.trim()!=="";if(o||n.push(`${t}.from (missing — the clip-path covering the window)`),s||n.push(`${t}.to (missing — the clip-path uncovering the window)`),o&&s){const i=Ku(e.from),r=Ku(e.to);i===""||r===""?n.push(`${t}.from|to (must be shape functions, e.g. \`inset( … )\` or \`polygon( … )\` — bare keywords like \`none\` cannot be animated)`):i!==r&&n.push(`${t}.from|to (must use the same shape function to interpolate — got \`${i}()\` and \`${r}()\`)`)}return n}function iS(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function Be(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Vu.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Ro&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Vu} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)");const o=e.render!==void 0,s=Array.isArray(e.layers),i=e.from!==void 0||e.to!==void 0;o&&typeof e.render!="function"?t.push("render (not a function)"):o&&(s||i)?t.push("render|layers|from|to (supply exactly one of: a from/to pair, a layers array, or a render function)"):o||(s&&i?t.push("layers|from|to (supply EITHER a single from/to pair OR a layers array, not both)"):s?(e.layers.length===0&&t.push("layers (empty — supply at least one matched pair)"),e.layers.forEach((r,a)=>{if(!r||typeof r!="object"){t.push(`layers[ ${a} ] (not an object)`);return}t.push(...Xu(r,`layers[ ${a} ]`))})):t.push(...Xu(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):iS(e.easing)||t.push("easing (not an easing the browser can parse — `Element.animate()` would throw at play time, with the covering surface already over the window)"))}Oe("WindowReveal",t,e);const n=e.id.trim().toLowerCase();ci.set(n,{...e,id:n}),Qu()}function rS(e){ci.delete(e.toLowerCase())&&Qu()}function Zu(){const e=Array.from(ci.values()),t=J(v.WINDOW_REVEALS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-reveals` filter returned a non-array; falling back to registry list."),e)}function Ju(e){return Zu().find(t=>t.id===e)}function aS(e){return ci.has(e)}function Qu(){const e=Array.from(oS);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Be({id:"sweep",label:b("Sweep"),description:b("A straight edge travels across the window, uncovering the page behind it."),...j_(),duration:420}),Be({id:"iris",label:b("Iris"),description:b("The page opens out from the centre of the window, like a camera shutter."),...W_(),duration:520}),Be({id:"curtain",label:b("Curtain"),description:b("Two panels part from the middle of the window and slide off the sides."),...P_(),duration:480}),Be({id:"blinds",label:b("Blinds"),description:b("Six horizontal slats retract at once, letting the page through between them."),...$_(),duration:560}),Be({id:"diagonal",label:b("Diagonal"),description:b("A slanted edge sweeps off the trailing corner of the window."),...V_(),duration:460}),Be({id:"rise",label:b("Rise"),description:b("The page rises into the window from the bottom edge upward."),...z_(),duration:440}),Be({id:"shutter",label:b("Shutter"),description:b("Two panels part from the middle of the window and slide off the top and bottom."),...U_(),duration:480}),Be({id:"slats",label:b("Slats"),description:b("Eight vertical slats retract at once, letting the page through between them."),...B_(),duration:560}),Be({id:"diamond",label:b("Diamond"),description:b("The page opens out from the centre of the window through a growing rhombus."),...F_(),duration:520}),Be({id:"mosaic",label:b("Mosaic"),description:b("The page arrives as a grid of tiles, each opening out from its own centre."),...H_(),duration:600}),Be({id:"obturator",label:b("Camera shutter"),description:b("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:J_,duration:720,edgeLag:0}),Be({id:"radar",label:b("Radar"),description:b("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...G_(),duration:760});const ef="desktop-mode-os-settings",Ct="desktop-mode-os-settings",tf="custom-gradient",xo="custom-image",Sa="galaxy",nf="custom",of=[{id:"pulse",label:"Pulse",value:"#f252fc"},{id:"nebula",label:"Nebula",value:"#ec9bff"},{id:"sirius",label:"Sirius",value:"#9af2ff"},{id:"lagoon",label:"Lagoon",value:"#9f98ff"},{id:"starlight",label:"Starlight",value:"#fffbff"},{id:"wp-blue",label:"WordPress Blue",value:"#2271b1"},{id:"indigo",label:"Indigo",value:"#3858e9"},{id:"teal",label:"Teal",value:"#04a4cc"},{id:"emerald",label:"Emerald",value:"#059669"},{id:"amber",label:"Amber",value:"#d97706"},{id:"rose",label:"Rose",value:"#e11d48"}];function li(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return of;const n=[];for(const o of t)o&&typeof o=="object"&&typeof o.id=="string"&&typeof o.label=="string"&&typeof o.value=="string"&&o.id!==""&&o.label!==""&&/^#[0-9a-f]{3,8}$/i.test(o.value)&&n.push({id:o.id,label:o.label,value:o.value});return n.length>0?n:of}function ka(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:Sa}const Ia=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],Aa=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],di=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],ui=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"}],cS=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],lS=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],xn={wallpaper:Sa,accent:"pulse",customAccent:"#f252fc",dockSize:"default",windowRadius:"round",adminBarMode:"hidden",desktopLayout:"unified",dockPlacement:"bottom",dockBehavior:"static",sideDockBehavior:"static",dockRailRenderer:"default",desktopTheme:"",appliedThemeRecommendations:[],unfocusEffect:"darken",windowReveal:"none",windowRevealDuration:0,windowLinkRenderer:"svg-splines",windowLinkVisibility:"always",windowLinksEnabled:!0,windowLinkRaiseOnFocus:!0,windowLinkHighlight:!0,customGradient:{from:"#2271b1",to:"#7c3aed",angle:135},customImage:null,wallpaperSettings:{},libraryHdOnly:!0,ai:{enabled:!1},heartbeatRate:60,nativePostsEnabled:!1,nativePostsHiddenColumns:[],nativePagesEnabled:!1,nativePagesHiddenColumns:[],nativeUsersEnabled:!1,nativePluginsEnabled:!1,nativeCommentsEnabled:!1,stationHomeEnabled:!1,adminAssetCacheEnabled:!0,windowPrewarmEnabled:!0,showDesktopOnWallpaperClick:!1,confirmCloseAllWindows:!0,mioEnabled:!1,mioApiEnabled:!1,mioShowOnWallpaper:!0,mioStyle:{appearance:{},physics:{}},showPostStatusRibbons:!0,developerModeEnabled:!1,foldersSharingEnabled:!0,navPlacement:{},navOrder:[],mobileLayout:"auto",mobileTabs:[],dockPromotedPositions:{}},sf={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},rf=["dockRailRenderer","windowReveal","accent"],af={windowRevealDuration:{min:80,max:4e3}},dS=/^[a-z0-9_-]+$/;[...Object.keys(sf),...rf,...Object.keys(af)];function cf(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries(sf)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of rf){const i=t[s];typeof i=="string"&&dS.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(af)){const r=t[s];typeof r=="number"&&Number.isFinite(r)&&(o[s]=Math.min(i.max,Math.max(i.min,Math.round(r))))}return{...n,...o}}function uS(e){const t=cf(e);return typeof t.dockRailRenderer=="string"&&L_(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==Ro&&!aS(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!li().some(n=>n.id===t.accent)&&delete t.accent,t}const fS=/^[a-z0-9_-]+$/,lf=128;function pS(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function Ca(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!fS.test(n))return null;const o={};if(t.icons&&typeof t.icons=="object"){let l=0;for(const[c,d]of Object.entries(t.icons)){if(l>=lf)break;c===""||!pS(d)||(o[c]=d,l+=1)}}const s={};if(t.tokens&&typeof t.tokens=="object")for(const[l,c]of Object.entries(t.tokens))typeof c=="string"&&(s[l]=c);const i=[];if(Array.isArray(t.fonts))for(const l of t.fonts)typeof l=="string"&&l!==""&&i.push(l);const r={};if(t.iconColors&&typeof t.iconColors=="object"){let l=0;for(const[c,d]of Object.entries(t.iconColors)){if(l>=lf)break;c===""||typeof d!="string"||d===""||(r[c]=d,l+=1)}}const a=l=>typeof t[l]=="string"?t[l]:"";return{id:a("id")||n,slug:n,name:a("name")||n,version:a("version"),author:a("author"),description:a("description"),previewUrl:a("previewUrl"),cssUrl:a("cssUrl"),cssText:a("cssText"),tokens:s,fonts:i,icons:o,iconColors:r,recommendedOsSettings:cf(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload",cssDeferred:t.cssDeferred===!0}}function hS(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=Ca(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const Lt=ae("desktop-mode/desktop-themes",hS);function Mn(){return Lt}function mS(){return Lt.getState().themes.slice()}function La(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return Lt.getState().themes.find(n=>n.slug===t||n.id===e)??null}function Ta(){return Lt.getState().activeId}function gS(e){const t=Ca(e);if(!t)return null;const n=Lt.state.themes.slice(),o=n.findIndex(s=>s.slug===t.slug);return o>=0?n[o]=t:n.push(t),n.sort((s,i)=>s.name.localeCompare(i.name)),Lt.setState({themes:n}),t}let Mo=null;function df(){if(Mo)return Mo;const e=window.openStationConfig?.desktopThemesUrl;return e?(Mo=Ae(e,{method:"GET",credentials:"same-origin"},{source:"desktop-mode/desktop-themes"}).then(async t=>{if(!t.ok)throw await Nn(t);return t.json()}).then(t=>{for(const n of t?.themes??[])gS(n)}).catch(()=>{Mo=null}),Mo):Promise.resolve()}function wS(e){const t=[];for(const n of e){const o=Ca(n);o&&t.push(o)}Lt.setState({themes:t})}function yS(e){return Lt.subscribe(e)}function fi(e){const t=Mn().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=J(v.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function Na(e){const t=Mn().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=J(v.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?vS(o):null}function vS(e){const t=e.trim();if(t===""||t.length>64||/[;{}<>"'\\]/.test(t))return null;let n=0;for(const o of t)if(o==="(")n+=1;else if(o===")"&&(n-=1,n<0))return null;return n===0?t:null}const Xt={WINDOW_CONTROL_MINIMIZE:"WINDOW_CONTROL_MINIMIZE",WINDOW_CONTROL_MAXIMIZE:"WINDOW_CONTROL_MAXIMIZE",WINDOW_CONTROL_FULLSCREEN:"WINDOW_CONTROL_FULLSCREEN",WINDOW_CONTROL_FULLSCREEN_EXIT:"WINDOW_CONTROL_FULLSCREEN_EXIT",WINDOW_CONTROL_CLOSE:"WINDOW_CONTROL_CLOSE",WINDOW_CONTROL_MENU:"WINDOW_CONTROL_MENU",WINDOW_CONTROL_RELOAD:"WINDOW_CONTROL_RELOAD",WINDOW_CONTROL_DETACH:"WINDOW_CONTROL_DETACH",OS_SETTINGS:"OS_SETTINGS",RECYCLE_BIN:"RECYCLE_BIN",BUG_REPORT:"BUG_REPORT",EXIT_OPENSTATION:"EXIT_OPENSTATION",PWA_INSTALL:"PWA_INSTALL",DEFAULT_APP_ICON:"DEFAULT_APP_ICON",FOLDER:"FOLDER",FILE_SHORTCUT:"FILE_SHORTCUT",FILE_POST:"FILE_POST",FILE_ATTACHMENT:"FILE_ATTACHMENT",FILE_UPLOAD:"FILE_UPLOAD",FILE_USER:"FILE_USER",FILE_TERM:"FILE_TERM",FILE_COMMENT:"FILE_COMMENT",FILE_BOOKMARK:"FILE_BOOKMARK",FILE_LINK:"FILE_LINK",FILE_EMBED:"FILE_EMBED",RECYCLE_RESTORE:"RECYCLE_RESTORE",RECYCLE_DELETE:"RECYCLE_DELETE"},bS={"desktop-mode-os-settings":Xt.OS_SETTINGS,"desktop-mode-recycle-bin":Xt.RECYCLE_BIN,"desktop-mode-bug-report":Xt.BUG_REPORT,"os-exit":Xt.EXIT_OPENSTATION,"os-pwa-install":Xt.PWA_INSTALL};function pi(e){if(typeof e!="string"||e==="")return"";const t=bS[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function ES(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Xt.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Xt?n:""}const hi=ae("desktop-mode/window-channels",()=>({parentSubs:new Map,nativeSubs:new Map,readyWindows:new Set,loadingWindows:new Set,pendingSends:new Map}));function Oa(e,t,n,o){let s=e.get(t);if(!s){if(!o)return;s=new Map,e.set(t,s)}let i=s.get(n);if(!i){if(!o)return;i=new Set,s.set(n,i)}return i}function uf(e,t,n,o){const s={channel:n,windowId:t},i=Oa(e,t,n,!1);if(i)for(const a of Array.from(i))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel subscriber for "${n}" threw:`,l)}const r=Oa(e,t,"*",!1);if(r)for(const a of Array.from(r))try{a(o,s)}catch(l){typeof console<"u"&&console.error(`[openstation] window-channel wildcard subscriber for "${t}" threw:`,l)}}function _S(e,t,n){const o=Oa(hi.state.parentSubs,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function SS(e,t,n){uf(hi.state.parentSubs,e,t,n)}function kS(e,t,n){uf(hi.state.nativeSubs,e,t,n)}function IS(e){const{readyWindows:t,loadingWindows:n,pendingSends:o}=hi.state;if(!t.has(e)){t.add(e);const s=o.get(e);if(s){o.delete(e);for(const i of s)try{i.flush()}catch(r){typeof console<"u"&&console.error(`[openstation] flushing queued window-send for "${i.channel}" threw:`,r)}}}n.delete(e)&&(A(v.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const AS="os.activity.";function Da(e){return AS+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let CS=0;const _e={publish(e,t){A(Da(e),t)},subscribe(e,t){const n=`os/activity-sub/${++CS}`,o=Da(e);ee(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,jt(o,n))}},filter(e,t,...n){return J(Da(e),t,...n)}},LS=4e3,TS=200,NS=1200;function ue(e){const t=_e.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return si(()=>!n,()=>{o=RS(t)}),()=>{n=!0,o&&o()}}const OS={success:"positive",warning:"warning",error:"critical","shell-error":"critical"};function DS(e){return e?window.openStationConfig?.toastTypes?.find(o=>o.id===e)?.tone??OS[e]??null:null}function RS(e){const t=PS(),n=document.createElement("os-toast");n.textContent=e.message;const o=DS(e.type);o&&n.setAttribute("tone",o),e.action&&(n.setAttribute("action",e.action.label),n.addEventListener("os-toast-action",()=>{e.action?.onClick(),c()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{e.onDismiss?.(),c()})),t.appendChild(n);let s=!1,i=null,r=e.duration??LS,a=0;const l=()=>{i!==null&&(window.clearTimeout(i),i=null)},c=()=>{s||(s=!0,l(),WS(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),MS()},TS))},d=()=>{s||e.persistent||i!==null||(a=Date.now(),i=window.setTimeout(c,r))},u=()=>{i!==null&&(r=Math.max(0,r-(Date.now()-a)),l())};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),n.addEventListener("os-toast-hold",f=>{if(f.detail?.held){u();return}r=Math.max(r,NS),d()}),xS(n),d(),_e.publish("os/toast-shown",{...e}),c}let mi=null,Wo=0;function ff(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(mi=t))}function xS(e){Wo===0&&document.addEventListener("focusin",ff,!0),Wo+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(mi=n)}function MS(){Wo=Math.max(0,Wo-1),Wo===0&&document.removeEventListener("focusin",ff,!0)}function WS(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||mi?.isConnected===!0&&mi.focus()}function PS(){const e=document.querySelector("os-toast-container");if(e)return e;const t=document.createElement("os-toast-container");return document.body.appendChild(t),t}const $S="http://localhost/";function rt(e,t){const n=typeof window<"u"&&window.location?window.location.href:$S,o=new URL(e,n),s=t.replace(/^\/+/,""),i=s.indexOf("?"),r=i===-1?s:s.slice(0,i),a=i===-1?"":s.slice(i+1);if(o.searchParams.has("rest_route")){const l=o.searchParams.get("rest_route")??"/",c=l.endsWith("/")?l:l+"/";o.searchParams.set("rest_route",c+r)}else{const l=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=l+r}return a&&new URLSearchParams(a).forEach((c,d)=>{o.searchParams.append(d,c)}),o.toString()}const US="os-site-assistant",BS="os-overview",pf="os-system",Po={assistant:5,mio:10,overview:20,system:30,exit:35},FS=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round"><rect x="6" y="6" width="27" height="27" rx="5"/><rect x="43" y="6" width="15" height="15" rx="5"/><rect x="43" y="31" width="15" height="27" rx="5"/><rect x="6" y="43" width="27" height="15" rx="5"/></svg>')}`,HS=`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>')}`,GS=`data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M10 2.5Q10.9 8.5 17.5 10Q10.9 11.5 10 17.5Q9.1 11.5 2.5 10Q9.1 8.5 10 2.5Z"/><path d="M17.9 14Q18.35 17.1 21.5 17.6Q18.35 18.1 17.9 21.2Q17.45 18.1 14.3 17.6Q17.45 17.1 17.9 14Z"/></svg>')}`,zS="os-exit";function jS(){return{id:zS,title:b("Exit OpenStation"),navKind:"control",locked:!0,order:Po.exit,icon:"dashicons-exit",onOpen:()=>{VS()}}}async function VS(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Ra(t);return}const n=new URLSearchParams;n.set("action","save-openstation"),n.set("nonce",e.nonce),n.set("enabled",""),e.network&&n.set("network","1");let o=t;try{const s=await fetch(e.ajaxUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString(),credentials:"same-origin"});if(s.ok){const i=await s.json();i?.success&&i.data?.redirect&&(o=i.data.redirect)}}catch{}Ra(o)}function Ra(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const hf=800;function KS(e,t=hf){window.setTimeout(()=>{if(e){Ra(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const qS="desktop_mode_nonces",YS="desktop-mode/v1",XS=3e4,ZS=3,Wn=ae("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function mf(){return window.wp?.os?.config??{}}function JS(){const e=mf().restUrl;return e?rt(e,YS):null}function QS(){Wn.state.negativeConfirms=0}async function ek(){const e=Wn.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=ZS)return;const t=JS();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<XS)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await Ae(t,{credentials:"same-origin"},{silent:!0,source:"desktop-mode/plugin-presence"});if(o.status!==404){e.negativeConfirms+=1;return}if((await o.json())?.code!=="rest_no_route"){e.negativeConfirms+=1;return}tk()}catch{}finally{e.confirmInFlight=!1}}}function tk(){if(!Wn.state.exiting){Wn.state.exiting=!0,KS(mf().adminUrl||"");try{ue({message:b("OpenStation is no longer active. Returning to the WordPress dashboard…"),duration:hf})}catch{}}}function nk(){if(Wn.state.booted)return;Wn.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[qS]!==void 0){QS();return}ek()}})}const ok=0,xa=40,gf=250,sk=120,ik=250,$o="os-window__loading",gi="os-window__loading--visible",wi=ae("desktop-mode/window-reveal-active",()=>({id:Ro,duration:_a}));function wf(e){wi.state.id=typeof e=="string"&&e!==""?e:Ro}function rk(){const e=wi.state.id;return!e||e===Ro?null:Ju(e)??null}function yf(e){wi.state.duration=qu(e)}function ak(){return wi.state.duration}function ck({osSettings:e}){const t=e.getOsSettingsSnapshot();wf(t.windowReveal),yf(t.windowRevealDuration),e.subscribeOsSettings(n=>{wf(n.windowReveal),yf(n.windowRevealDuration)})}const Pn="os-window__reveal",Uo="os-window__reveal--edge",lk="os-window__reveal--custom",Zt="os-window__body--revealing",Ma="data-os-reveal",Wa="data-os-reveal-layer",Tt=new WeakMap,vf=ae("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function bf(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const dk="--os-window-reveal-duration",uk="--os-window-reveal-edge-thickness";function Ef(e){const t=e.trim();if(t==="")return 0;const n=/^(-?\d*\.?\d+)\s*(ms|s)?$/i.exec(t);if(!n)return 0;const o=Number(n[1]);return Number.isFinite(o)?n[2]?.toLowerCase()==="s"?o*1e3:o:0}function fk(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return qu(Ef(window.getComputedStyle(e).getPropertyValue(dk)))}catch{return 0}}function pk(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function hk(e,t){const n=pk(e,uk);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return Rn(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return Rn(t*Number(s[1]));const i=Ef(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?Rn(i):null}function _f(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return!1;try{const t=window.getComputedStyle(e),n=t.backgroundImage;if(n&&n!=="none")return!1;const o=/^rgba?\(([^)]+)\)$/.exec(t.backgroundColor.trim());if(!o)return!1;const s=o[1].split(/[,\s/]+/).filter(Boolean);return s.length>=4&&Number(s[3])===0}catch{return!1}}function mk(e,t){const n=sS(t.duration),o=ak(),s=o!==_a?o:fk(e)||n,i=hk(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=Rn(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:Rn(r*s/n)}}function Sf(e){return e.querySelector(":scope .os-window__body")}function gk(e){return e.querySelector(`:scope .${Pn}:not( .${Uo} )`)}function wk(e){return e.querySelector(`:scope .${Uo}`)}function kf(e){return Array.from(e.querySelectorAll(`:scope .${Pn}:not( .${Uo} )`))}function If(e){return Array.from(e.querySelectorAll(`:scope .${Uo}`))}function Pa(e){return Array.from(e.querySelectorAll(`:scope .${Pn}`))}function Af(e,t,n,o){const s=document.createElement("div");s.className=o?`${Pn} ${Uo}`:Pn;const i=o?e.edgeColor:t.color??e.surfaceColor;return typeof i=="string"&&i!==""&&(s.style.background=i),s.setAttribute("aria-hidden","true"),s.setAttribute(Ma,e.id),s.setAttribute(Wa,String(n)),s.style.clipPath=t.from,s}function yk(){const e=rk();if(!e)return[];if(typeof e.render=="function"){let o;try{o=e.render()}catch(i){return typeof console<"u"&&console.error(`[openstation] window reveal "${e.id}" render threw:`,i),[]}if(!o?.element||typeof o.play!="function")return[];const s=o.element;return s.classList.add(Pn),s.classList.add(lk),s.setAttribute("aria-hidden","true"),s.setAttribute(Ma,e.id),s.setAttribute(Wa,"0"),vf.set(s,o.play),[s]}const t=Yu(e);if(t.length===0)return[];const n=[];return Rn(e.edgeLag)>0&&t.forEach((o,s)=>n.push(Af(e,o,s,!0))),t.forEach((o,s)=>n.push(Af(e,o,s,!1))),n}function vk(e){const t=Sf(e);if(t){t.classList.remove(Zt);for(const n of Pa(t))Tt.get(n)?.cancel(),Tt.delete(n),n.remove();for(const n of yk())t.appendChild(n)}}function Cf(e){const t=Sf(e);if(!t)return;const n=gk(t);if(!n)return;let o;try{o=Ju(n.getAttribute(Ma)??"")}catch(S){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",S)}if(!o){Pa(t).forEach(S=>S.remove());return}const i=!!t.querySelector(`:scope .${$o}`)?.classList.contains(gi)?gf:0,{duration:r,edgeLag:a}=mk(t,o),l=o.easing??eS,c=vf.get(n);if(c){t.classList.add(Zt);const S=()=>{Tt.delete(n),n.remove(),t.classList.remove(Zt)};if(bf()||typeof n.animate!="function"){window.setTimeout(S,i);return}let R=[];try{R=c({duration:r,easing:l,delay:i})}catch(W){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,W)}if(R.length===0){S();return}R[0].addEventListener("finish",S),R[0].addEventListener("cancel",()=>{Tt.delete(n),t.classList.remove(Zt)}),Tt.set(n,R[0]);return}const d=wk(t);d&&(a<=0||_f(d))&&If(t).forEach(S=>S.remove()),_f(n)&&kf(t).forEach(S=>S.remove());const u=Pa(t);if(u.length===0)return;t.classList.add(Zt);const f=()=>{for(const S of u)Tt.delete(S),S.remove();t.classList.remove(Zt)};if(bf()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=l,g=Yu(o),h=(S,R)=>{const W=g[Number(S.getAttribute(Wa))];if(!W)return S.remove(),null;S.style.willChange="clip-path";let U;try{U=S.animate([{clipPath:W.from},{clipPath:W.to}],{duration:R,easing:p,delay:i,fill:"both"})}catch(F){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,F),S.remove(),null}return Tt.set(S,U),U},m=kf(t).map(S=>h(S,r)).filter(S=>S!==null),_=If(t).map(S=>h(S,r+a)).filter(S=>S!==null),I=m[0]??null,O=_[0]??null;if(!I&&!O){f();return}(O??I)?.addEventListener("finish",f);const $=()=>{for(const S of u)Tt.delete(S);t.classList.remove(Zt)};I?.addEventListener("cancel",$),O?.addEventListener("cancel",$)}const bk="os-window-tab-change";function Lf(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function Tf(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function Nf(e,t){return`${e.id||"os-window"}-tab-${Tf(t)}`}function Of(e,t){return`${e.id||"os-window"}-panel-${Tf(t)}`}function Ek(e){const t=e.querySelector(".os-window__tab-plate");if(!t)return;const n=e.querySelector(".os-window__tab--active");if(!n){t.dataset.empty="",e.dataset.tabPlateEmpty="";return}delete t.dataset.empty,delete e.dataset.tabPlateEmpty,e.style.setProperty("--_tab-plate-x",`${n.offsetLeft}px`),e.style.setProperty("--_tab-plate-w",`${n.offsetWidth}px`),e.style.setProperty("--_tab-strip-w",`${e.clientWidth}px`),n.offsetWidth>0&&(t.dataset.placed="")}function _k(e){if(e){if(e.querySelector(":scope > .os-window__tab")){e.setAttribute("role","tablist");const t=e.dataset.tablistLabel;t&&e.setAttribute("aria-label",t);return}e.setAttribute("role","presentation"),e.removeAttribute("aria-label")}}function Sk(e){const t=Lf(e);if(t.length===0)return;const n=t.find(o=>o.classList.contains("os-window__tab--active"))??t[0];for(const o of t){const s=o===n?0:-1;o.tabIndex!==s&&(o.tabIndex=s)}}function Df(e){const t=new Map;for(const n of Lf(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function Rf(e){const t=e.querySelector(".os-window__body");return t?Array.from(t.querySelectorAll("os-tabpanel[ for ]")).filter(n=>!n.parentElement?.closest("os-tabpanel, os-tabs")):[]}function kk(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of Df(n)){const r=s===t;o=o||r,i.classList.toggle("os-window__tab--active",r),i.setAttribute("aria-selected",r?"true":"false")}if(o){for(const s of Rf(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}Sk(n),Ek(n),e.dispatchEvent(new CustomEvent(bk,{bubbles:!0,detail:{value:t}}))}}function Ik(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=Df(o),i=Array.from(s.entries()).find(([,d])=>d.classList.contains("os-window__tab--active"))?.[0];let r=o.querySelector(".os-window__tab-plate");for(const d of t){let u=s.get(d.value);if(u)s.delete(d.value);else{const f=document.createElement("button");f.type="button",u=f,u.className="os-window__tab",u.dataset.kind="panel",u.dataset.panel=d.value,u.setAttribute("role","tab"),u.setAttribute("aria-selected","false"),u.tabIndex=-1}u.textContent!==d.label&&(u.textContent=d.label),u.id=Nf(e,d.value),u.setAttribute("aria-controls",Of(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();_k(o);const a=o.querySelector(":scope > .os-window__tab")!==null;for(const d of Rf(e)){const u=d.getAttribute("for");u&&(d.id=Of(e,u),a?d.setAttribute("aria-labelledby",Nf(e,u)):d.removeAttribute("aria-labelledby"))}const l=d=>d!==void 0&&t.some(u=>u.value===d),c=[n,i,t[0]?.value].find(l);c!==void 0&&kk(e,c)}const Bo="os-window__body--loading",$a="os-window__body--loading-out",Ua="data-os-loading-at",xf="data-os-loading-cycle";function yi(e){return e.getAttribute(xf)??"0"}function Ak(e){e.setAttribute(Ua,String(Date.now())),e.setAttribute(xf,String(Number(yi(e))+1))}function Ck(e,t){const n=Number(e.getAttribute(Ua)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=sk-o;if(s<=0){t.classList.add(gi);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(Bo)&&t.classList.add(gi)},s)}const Lk=Symbol.for("desktop-mode/window-config");function Tk(e){return e[Lk]}const Mf=window.location.origin;function Nk(e){const t=new URL(e,Mf);return t.origin!==Mf||Ln(t)?null:(t.searchParams.set("openstation_chromeless","1"),t.toString())}function Ba(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function Wf(){const e=document.createElement("div");e.className=$o,e.setAttribute("role","status"),e.setAttribute("aria-live","polite");const t=document.createElement("os-spinner");return t.setAttribute("preset","classic"),t.setAttribute("size","clamp(96px, 14vw, 192px)"),t.setAttribute("label",b("Loading window content")),e.appendChild(t),e}function Ok(e){let t=Wf();const n={windowId:e.id,config:e};if(typeof e.loading?.render=="function")try{e.loading.render(t,n)}catch(o){typeof console<"u"&&console.error(`[openstation] loading.render threw for "${e.id}":`,o)}try{const o=J(v.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[openstation] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains($o)&&t.classList.add($o),t}function Pf(e){e.querySelector(":scope .os-window__loading")?.remove()}function $f(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=Tk(e),s=o?Ok(o):Wf();t.appendChild(s),Ck(t,s)}const Dk=8,Uf=Object.freeze({top:0,right:0,bottom:0,left:0});function Bf(e,t,n,o){return{left:e,top:t,width:n,height:o,right:e+n,bottom:t+o}}function Rk(e,t){const n=t.left+t.width/2,o=t.top+t.height/2,s={top:Math.abs(o-e.top),bottom:Math.abs(e.bottom-o),left:Math.abs(n-e.left),right:Math.abs(e.right-n)},r=t.height>t.width?["left","right","top","bottom"]:["top","bottom","left","right"];let a=r[0];for(const l of r)s[l]<s[a]&&(a=l);return a}function xk(e,t,n=Dk){const o={top:0,right:0,bottom:0,left:0};if(e.width<=0||e.height<=0)return o;for(const r of t){if(r.width<=0||r.height<=0)continue;const a=Math.min(e.right,r.right)-Math.max(e.left,r.left),l=Math.min(e.bottom,r.bottom)-Math.max(e.top,r.top);if(!(a<=0||l<=0))switch(Rk(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 Ff(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 Mk(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 Wk(e,t){return e.top===t.top&&e.right===t.right&&e.bottom===t.bottom&&e.left===t.left}function Hf(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}const Pk="os-work-area-changed",$k="data-os-dock-behavior",Uk="os/work-area";function Bk(){return{insets:{...Uf},rect:{x:0,y:0,width:0,height:0},viewport:{x:0,y:0,width:0,height:0},area:{width:0,height:0}}}const wt=ae(Uk,()=>({snapshot:Bk(),installed:!1,areaEl:null})),$n={top:"--os-work-area-inset-top",right:"--os-work-area-inset-right",bottom:"--os-work-area-inset-bottom",left:"--os-work-area-inset-left",width:"--os-work-area-width",height:"--os-work-area-height"};function Fa(e){return{insets:{...e.insets},rect:{...e.rect},viewport:{...e.viewport},area:{...e.area}}}function Fk(){return Fa(wt.state.snapshot)}function ge(e){const t=e??wt.state.areaEl;if(!t)return{...wt.state.snapshot.rect};const n=t.clientWidth||t.getBoundingClientRect().width,o=t.clientHeight||t.getBoundingClientRect().height;return Ff(n,o,wt.state.snapshot.insets)}function Hk(e){const{installed:t,snapshot:n}=wt.state;if(!t)return{...Uf};const o=n.viewport;return Mk(Bf(o.x,o.y,o.width,o.height),e.getBoundingClientRect())}function Fo(e){return wt.subscribe(t=>{e(Fa(t.snapshot))})}function Gk(e){const t=zk(e),n=[],o=e.shellBody.querySelectorAll(e.chromeSelector??".os-dock");for(const l of Array.from(o))l.hidden||l.getAttribute($k)==="dynamic"||n.push(l.getBoundingClientRect());const s=xk(t,n),i=e.area.clientWidth||t.width,r=e.area.clientHeight||t.height,a=Ff(i,r,s);return{insets:s,rect:a,viewport:{x:t.left+a.x,y:t.top+a.y,width:a.width,height:a.height},area:{width:i,height:r}}}function zk(e){const{area:t}=e;if(t.offsetWidth>0&&t.offsetParent===e.shellBody){const n=e.shellBody.getBoundingClientRect();return Bf(n.left+t.offsetLeft,n.top+t.offsetTop,t.offsetWidth,t.offsetHeight)}return t.getBoundingClientRect()}function jk(e,t){e.style.setProperty($n.top,`${t.insets.top}px`),e.style.setProperty($n.right,`${t.insets.right}px`),e.style.setProperty($n.bottom,`${t.insets.bottom}px`),e.style.setProperty($n.left,`${t.insets.left}px`),e.style.setProperty($n.width,`${t.rect.width}px`),e.style.setProperty($n.height,`${t.rect.height}px`)}function Vk(e,t){return Wk(e.insets,t.insets)&&Hf(e.rect,t.rect)&&Hf(e.viewport,t.viewport)&&e.area.width===t.area.width&&e.area.height===t.area.height}function Kk(e){const t=new Map;let n=null,o=null,s=!1,i=!1,r=null;const a=()=>{if(s||i)return;const p=Gk(e);if(!!wt.state.installed&&Vk(wt.state.snapshot,p))return;jk(e.shell,p),wt.setState({snapshot:p,installed:!0,areaEl:e.area});const h=Fa(p);A(v.WORK_AREA_CHANGED,h),document.dispatchEvent(new CustomEvent(Pk,{detail:h}))},l=typeof ResizeObserver<"u",c=()=>{if(!l)return;const p=new Set(Array.from(e.shellBody.querySelectorAll(e.chromeSelector??".os-dock")));for(const[g,h]of t)p.has(g)||(h.disconnect(),t.delete(g));for(const g of p){if(t.has(g))continue;const h=new ResizeObserver(a);h.observe(g,{box:"border-box"}),t.set(g,h)}};l&&(n=new ResizeObserver(a),n.observe(e.area)),typeof MutationObserver<"u"&&(o=new MutationObserver(()=>{c(),a()}),o.observe(e.shellBody,{childList:!0}));const d=()=>{c(),a()};document.addEventListener("os-layout-changed",d),window.addEventListener("resize",a);const u=()=>{i=!0},f=()=>{i=!1,a()};return ee(v.OVERVIEW_ENTERING,vi,u),ee(v.OVERVIEW_EXITED,vi,f),c(),a(),r={refresh:a,destroy:()=>{s=!0,n?.disconnect(),o?.disconnect();for(const p of t.values())p.disconnect();t.clear(),document.removeEventListener("os-layout-changed",d),window.removeEventListener("resize",a),jt(v.OVERVIEW_ENTERING,vi),jt(v.OVERVIEW_EXITED,vi),bi===r&&(bi=null)}},bi=r,r}const vi="openstation/work-area";let bi=null;function qk(){bi?.refresh()}const Yk={get:Fk,rectOf:ge,insetsOf:Hk,subscribe:Fo};function Xk(e,t,n){if(e._splitOverviewActive)return;e._splitOverviewActive=!0,e._splitOverviewAnchor=t,e._splitOverviewZone=n;const o=e._stack.filter(a=>a!==t&&a.state!=="minimized"&&a.config.desktopId===e._activeDesktopId);if(o.length===0){Gf(e);return}e._splitOverviewSnapshot.clear();for(const a of o)e._splitOverviewSnapshot.set(a.id,{transform:a.element.style.transform||"",transition:a.element.style.transition||""});e._desktop.classList.add("os-area--split-overview");const s=tI(e,n),i=fa(o,s,0);e._splitOverviewLabels.clear();for(const a of i){const l=a.win.element;l.classList.add("os-window--overview");const c=a.x-l.offsetLeft,d=a.y-l.offsetTop;l.style.transform=`translate(${c}px, ${d}px) scale(${a.scale})`;const u=ec(a);l.insertAdjacentElement("afterend",u),e._splitOverviewLabels.set(a.win.id,u)}const r=a=>{const l=a.target,c=l?.closest(".os-window--overview");return c?{id:c.id.replace(/^wp-window-/,""),element:c}:l?{id:"dismiss",element:e._desktop}:null};e._splitOverviewPointerDown=a=>{if(a.button!==0){e._splitOverviewPressTarget=null;return}e._splitOverviewPressTarget=r(a),e._splitOverviewPressTarget&&(a.preventDefault(),a.stopPropagation())},e._splitOverviewPointerUp=a=>{if(a.button!==0)return;const l=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!l)return;const c=l.element.getBoundingClientRect();if(!(a.clientX>=c.left&&a.clientX<=c.right&&a.clientY>=c.top&&a.clientY<=c.bottom))return;if(a.preventDefault(),a.stopPropagation(),l.id==="dismiss"){Ho(e);return}const u=e.getById(l.id);if(!u){Ho(e);return}Zk(e,u)},e._splitOverviewKey=a=>{a.key==="Escape"&&Ho(e)},e._splitOverviewClickBlocker=a=>{a.stopPropagation(),a.preventDefault()},e._desktop.addEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._desktop.addEventListener("pointerup",e._splitOverviewPointerUp,!0),e._desktop.addEventListener("click",e._splitOverviewClickBlocker,!0),document.addEventListener("keydown",e._splitOverviewKey)}function Zk(e,t){const n=e._splitOverviewZone;if(!n){Ho(e);return}const o=n==="left"?"right":"left";t.element.style.transform="",t.element.classList.remove("os-window--overview"),t.applySnap(o),e._splitOverviewSnapshot.delete(t.id),e.focus(t),A(v.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),Ho(e)}function Ho(e){if(!e._splitOverviewActive)return;e._splitOverviewActive=!1;for(const[n,o]of e._splitOverviewSnapshot){const s=e.getById(n);s&&(s.element.style.transform=o.transform)}for(const n of e._splitOverviewLabels.values())n.classList.add("os-overview-label--out");e._desktop.classList.remove("os-area--split-overview"),window.setTimeout(()=>{for(const n of e._stack)e._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("os-window--overview");for(const n of e._splitOverviewLabels.values())n.remove();Gf(e)},260),e._splitOverviewPointerDown&&(e._desktop.removeEventListener("pointerdown",e._splitOverviewPointerDown,!0),e._splitOverviewPointerDown=null),e._splitOverviewPointerUp&&(e._desktop.removeEventListener("pointerup",e._splitOverviewPointerUp,!0),e._splitOverviewPointerUp=null),e._splitOverviewClickBlocker&&(e._desktop.removeEventListener("click",e._splitOverviewClickBlocker,!0),e._splitOverviewClickBlocker=null),e._splitOverviewKey&&(document.removeEventListener("keydown",e._splitOverviewKey),e._splitOverviewKey=null),e._splitOverviewPressTarget=null}function Gf(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const zf=30,Jk=260;function Qk(e,t){return e<=t.left+zf?"left":e>=t.right-zf?"right":null}function eI(e,t){const n=ge(e._desktop),o=Math.floor(n.width/2),s=Math.floor(n.height);return{x:t==="left"?n.x:n.x+n.width-o,y:n.y,width:o,height:s}}function tI(e,t){const n=e._desktop.getBoundingClientRect(),o=Math.floor(n.width/2),s=Math.floor(n.height);return t==="left"?new DOMRect(o,0,o,s):new DOMRect(0,0,o,s)}function nI(e,t){if(e._snapPendingZone===t&&e._snapPreviewEl)return;if(e._snapPendingZone=t,!e._snapPreviewEl){const o=document.createElement("div");o.className="os-snap-preview",o.setAttribute("aria-hidden","true"),e._desktop.appendChild(o),e._snapPreviewEl=o,Promise.resolve().then(()=>{o.classList.add("os-snap-preview--visible")})}const n=eI(e,t);e._snapPreviewEl.style.left=`${n.x}px`,e._snapPreviewEl.style.top=`${n.y}px`,e._snapPreviewEl.style.width=`${n.width}px`,e._snapPreviewEl.style.height=`${n.height}px`,e._snapPreviewEl.dataset.zone=t}function Ha(e){if(!e._snapPreviewEl){e._snapPendingZone=null;return}const t=e._snapPreviewEl;e._snapPreviewEl=null,e._snapPendingZone=null,t.classList.remove("os-snap-preview--visible"),window.setTimeout(()=>{t.remove()},Jk)}function oI(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=Qk(n,o),i=e._snapPendingZone;s?(nI(e,s),i!==s&&A(v.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(Ha(e),A(v.SNAP_ZONE_CANCELED,{windowId:t.id}))}function sI(e,t){const n=e._snapPendingZone;return n?(Ha(e),t.snapTo(n),A(v.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{Xk(e,t,n)}),!0):!1}function jf(e){e._snapPendingZone&&Ha(e)}const iI=6,rI=6,aI=8,cI={Shake:"shake"},Vf="os-window--grid-snapping",Kf="os-area--grid-snapping";function lI(e){const t={cols:iI,rows:rI},n=J(v.GRID_SNAP_DIMENSIONS,t,{areaWidth:e.width,areaHeight:e.height});return!!n&&Number.isInteger(n.cols)&&Number.isInteger(n.rows)&&n.cols>=1&&n.rows>=1&&n.cols<=24&&n.rows<=24?{cols:n.cols,rows:n.rows}:t}function Ga(e,t,n,o){const s=(e-n.x)/Math.max(1,n.width),i=(t-n.y)/Math.max(1,n.height);return{col:qf(Math.floor(s*o.cols),o.cols),row:qf(Math.floor(i*o.rows),o.rows)}}function qf(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t-1,e)):0}function dI(e,t,n,o){const s=Math.min(e.col,t.col),i=Math.max(e.col,t.col)+1,r=Math.min(e.row,t.row),a=Math.max(e.row,t.row)+1,l=n.x+Math.round(n.width*s/o.cols),c=n.x+Math.round(n.width*i/o.cols),d=n.y+Math.round(n.height*r/o.rows),u=n.y+Math.round(n.height*a/o.rows);return{x:l,y:d,width:c-l,height:u-d}}function Ei(e,t,n,o){const s=dI(e,t,n,o),i=Math.round(aI/2);return s.width<=i*4||s.height<=i*4?s:{x:s.x+i,y:s.y+i,width:s.width-i*2,height:s.height-i*2}}function uI(e,t){return e.col===t.col&&e.row===t.row}function za(e,t,n){const o=e._desktop.getBoundingClientRect();return{x:t-o.left,y:n-o.top}}function ja(e,t){const{overlayEl:n,targetEl:o,dims:s,rect:i}=e;n.style.left=`${t.x}px`,n.style.top=`${t.y}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`,n.style.setProperty("--os-grid-snap-cols",String(s.cols)),n.style.setProperty("--os-grid-snap-rows",String(s.rows)),o.style.left=`${i.x-t.x}px`,o.style.top=`${i.y-t.y}px`,o.style.width=`${i.width}px`,o.style.height=`${i.height}px`,o.dataset.cols=String(Math.abs(e.cursor.col-e.anchor.col)+1),o.dataset.rows=String(Math.abs(e.cursor.row-e.anchor.row)+1)}function fI(e,t,n,o){if(e._gridSnap)return;jf(e);const s=ge(e._desktop),i=lI(s),r=za(e,n,o),a=Ga(r.x,r.y,s,i),l=document.createElement("div");l.className="os-grid-snap",l.setAttribute("aria-hidden","true");const c=document.createElement("div");c.className="os-grid-snap__target",l.appendChild(c),e._desktop.appendChild(l);const d={windowId:t.id,dims:i,anchor:a,cursor:a,rect:Ei(a,a,s,i),overlayEl:l,targetEl:c,windowEl:t.element};e._gridSnap=d,t.element.classList.add(Vf),e._desktop.classList.add(Kf),ja(d,s),requestAnimationFrame(()=>{e._gridSnap===d&&l.classList.add("os-grid-snap--visible")}),A(v.GRID_SNAP_ARMED,{windowId:t.id,anchor:{...a},dims:{...i}}),A(v.GRID_SNAP_CHANGED,{windowId:t.id,anchor:{...a},cursor:{...a},rect:{...d.rect}})}function pI(e,t,n){const o=e._gridSnap;if(!o)return;const s=ge(e._desktop),i=za(e,t,n),r=Ga(i.x,i.y,s,o.dims),a=Ei(o.anchor,r,s,o.dims),l=!uI(r,o.cursor),c=a.x!==o.rect.x||a.y!==o.rect.y||a.width!==o.rect.width||a.height!==o.rect.height;o.cursor=r,o.rect=a,ja(o,s),(l||c)&&A(v.GRID_SNAP_CHANGED,{windowId:o.windowId,anchor:{...o.anchor},cursor:{...r},rect:{...a}})}function hI(e,t,n,o){const s=e._gridSnap;if(!s)return;const i=ge(e._desktop),r=za(e,t,n),a=Ga(r.x,r.y,i,s.dims);s.anchor=a,s.cursor=a,s.rect=Ei(a,a,i,s.dims),ja(s,i),s.targetEl.classList.remove("os-grid-snap__target--reset"),s.targetEl.offsetWidth,s.targetEl.classList.add("os-grid-snap__target--reset"),A(v.GRID_SNAP_ANCHOR_RESET,{windowId:s.windowId,anchor:{...a},reason:o}),A(v.GRID_SNAP_CHANGED,{windowId:s.windowId,anchor:{...a},cursor:{...a},rect:{...s.rect}})}const mI=200;function Yf(e){const t=e._gridSnap;if(!t)return null;e._gridSnap=null,t.windowEl.classList.remove(Vf),e._desktop.classList.remove(Kf);const n=t.overlayEl;return n.classList.remove("os-grid-snap--visible"),window.setTimeout(()=>n.remove(),mI),t}function gI(e){const t=Yf(e);t&&A(v.GRID_SNAP_CANCELED,{windowId:t.windowId})}function wI(e,t){const n=Yf(e);if(!n)return!1;const{rect:o}=n;t.state==="normal"&&(t._savedGeometry=null),t.element.style.left=`${o.x}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${o.width}px`,t.element.style.height=`${o.height}px`,t._emitChange("moved"),t._emitChange("resized"),t._gridSpan={anchor:{...n.anchor},cursor:{...n.cursor},cols:n.dims.cols,rows:n.dims.rows};const s={windowId:t.id,x:o.x,y:o.y,width:o.width,height:o.height};return A(v.GRID_SNAP_COMMITTED,{...s,anchor:{...n.anchor},cursor:{...n.cursor},dims:{...n.dims}}),A(v.WINDOW_DRAG_END,{windowId:t.id,x:o.x,y:o.y}),A(v.WINDOW_MOVED,{windowId:t.id,x:o.x,y:o.y}),A(v.WINDOW_RESIZED,{windowId:t.id,width:o.width,height:o.height}),!0}function Xf(e,t){return Ei(e.anchor,e.cursor,t,{cols:e.cols,rows:e.rows})}function Zf(e,t){const n=e._gridSpan;if(!n||e.state!=="normal"&&e.state!=="minimized")return!1;const o=Xf(n,t),s=e.element,i={left:`${o.x}px`,top:`${o.y}px`,width:`${o.width}px`,height:`${o.height}px`};return s.style.left===i.left&&s.style.top===i.top&&s.style.width===i.width&&s.style.height===i.height?!1:(s.style.left=i.left,s.style.top=i.top,s.style.width=i.width,s.style.height=i.height,!0)}function yI(e){const t=ge(e._desktop),n=[];for(const o of e._stack)Zf(o,t)&&(o._emitChange("moved"),n.push(o.id));return n.length>0&&A(v.GRID_SNAP_REFLOWED,{windowIds:n}),n}function vI(e){return Fo(()=>{yI(e)})}function bI(e){return[e.id,e.menu?.url??"",e.entry?.url??"",e.windowId??"",e.title].join(` | |
| 2 | +`).toLowerCase()}function Jf(e,t){const n=t.trim().toLowerCase();return n?bI(e).includes(n):!1}function EI(e,t){if(t.length===0)return[];const n=[],o=new Set;for(const s of e)o.has(s.id)||t.some(i=>Jf(s,i))&&(o.add(s.id),n.push(s.id));return n}function Qf(e,t){const n=[];for(const o of t){const s=e.find(i=>Jf(i,o.match));s&&n.push({item:s,url:o.url??s.menu?.url??s.entry?.url??"",title:o.title??s.title,...o.gridSpan?{gridSpan:o.gridSpan}:{},...o.place?{place:o.place}:{}})}return n}const _I=["index.php","upload.php","options-general.php"];function SI(){return[{id:"commerce",label:b("Commerce"),description:b("A shop floor. WooCommerce orders, products and analytics side by side; everything that is not commerce leaves the rails."),icon:"dashicons-cart",color:"#7f54b3",defaultLabel:b("Commerce"),order:10,apps:["woocommerce","wc-admin","wc-orders","wc-reports","wc-settings","post_type=product","post_type=shop_order","post_type=shop_coupon","edit-tags.php?taxonomy=product_cat","users.php"],widgets:["clock","desktop-mode/site-views"],appearance:{wallpaper:"dark",accent:"indigo"},windows:[{match:"wc-orders"},{match:"post_type=product",url:"edit.php?post_type=product"},{match:"wc-admin"}],layout:"columns"},{id:"learning",label:b("Learning"),description:b("A course studio. Sensei courses, lessons and learners tiled together, so moving between them is a glance rather than a navigation."),icon:"dashicons-welcome-learn-more",color:"#43a047",defaultLabel:b("Learning"),order:20,apps:["sensei","post_type=course","post_type=lesson","post_type=question","post_type=sensei_message","sensei_learner_admin","sensei-settings","users.php"],widgets:["clock","desktop-mode/heartbeat","desktop-mode/recent-comments"],appearance:{wallpaper:"aurora",accent:"emerald"},windows:[{match:"post_type=course",url:"edit.php?post_type=course"},{match:"post_type=lesson",url:"edit.php?post_type=lesson"},{match:"sensei"}],layout:"tile"},{id:"publishing",label:b("Publishing"),description:b("A writing desk. A blank page takes two thirds of the screen, the library sits in the margin, and the rest of the admin is somewhere else."),icon:"dashicons-edit-page",color:"#c8102e",defaultLabel:b("Publishing"),order:30,apps:["edit.php","post-new.php","upload.php","edit-comments.php","edit-tags.php","post_type=page"],widgets:["desktop-mode/drafts","desktop-mode/post-stats","desktop-mode/focus-timer","desktop-mode/notes"],appearance:{wallpaper:"mono",accent:"rose",dockBehavior:"dynamic"},windows:[{match:"edit.php",url:"post-new.php",title:b("New draft")},{match:"edit.php",url:"edit.php"}],layout:"focus"}]}const Va=new Map;function ep(e){e?.id&&Va.set(e.id,e)}function Ka(e){Va.delete(e)}function Go(){const e=[...SI(),...Va.values()],t=J(v.WORKSPACE_PRESETS,e);return(Array.isArray(t)?t.slice():e).map((o,s)=>({preset:o,index:s})).sort((o,s)=>(o.preset.order??0)-(s.preset.order??0)||o.index-s.index).map(o=>o.preset)}function kI(e){return Go().find(t=>t.id===e)??null}function tp(e,t){const n=[...e.apps,...e.apps.length?_I:[]],o=EI(t,n),s=e.widgets??[];return{preset:e.id,icon:e.icon,color:e.color,apps:{mode:e.apps.length>0?"only":"all",ids:o},widgets:{mode:s.length>0?"only":"all",ids:s.slice()},appearance:{...e.appearance??{}},windows:e.windows.map(i=>({...i})),layout:e.layout,provisioned:!1}}const II=12,AI=["free","cascade","tile","columns","focus"],np=["wallpaper","wallpaperSettings","customGradient","customImage","accent","customAccent","desktopTheme","desktopLayout","dockPlacement","dockSize","dockBehavior","sideDockBehavior","windowRadius","windowReveal","unfocusEffect","adminBarMode"];function op(){return{preset:"",icon:"dashicons-desktop",color:"",apps:{mode:"all",ids:[]},widgets:{mode:"all",ids:[]},appearance:{},windows:[],layout:"free",provisioned:!0}}function CI(e){return e.kind!=="control"&&!e.locked}function LI(e,t,n){if(!n||n.apps.mode!=="only")return e;const o=new Set(n.apps.ids),s={...e};for(const i of t)o.has(i.id)||!CI(i)||(s[i.id]="hidden");return s}function TI(e){const t=e?.widgets;return!t||t.mode!=="only"?null:t.ids}function NI(e){const t=e?.appearance;if(!t)return null;const n={};for(const o of np)t[o]!==void 0&&(n[o]=t[o]);return Object.keys(n).length>0?n:null}function sp(e){const t={};for(const n of np)e[n]!==void 0&&(t[n]=e[n]);return t}function OI(e,t,n){const o=e.widgets;return!o||o.mode!=="only"||o.ids.includes(t)===n?e:{...e,widgets:{mode:"only",ids:[...o.ids,t]}}}function Jt(e,t){return e.getDesktops().find(n=>n.id===t)?.profile??null}function DI(e){return Jt(e,e.getActiveDesktopId())}function Un(e,t,n){const o=e.manager._desktops.find(s=>s.id===t);return o?(n?o.profile=n:delete o.profile,e.refreshLayout(),t===e.manager.getActiveDesktopId()&&qa(e,t),A(v.WORKSPACE_UPDATED,{desktopId:t,profile:n}),!0):!1}function RI(e,t){e.setVisibleWidgets?.(TI(Jt(e.manager,t)))}function xI(e,t){e.setAppearance?.(NI(Jt(e.manager,t)))}function qa(e,t){xI(e,t),RI(e,t)}function _i(e,t={}){const n=t.preset?kI(t.preset):null;let o=t.profile??null;!o&&n&&(o=J(v.WORKSPACE_PROFILE,tp(n,e.getNavItems()),n));const i=(t.desktopId?e.manager.getDesktops().find(a=>a.id===t.desktopId):void 0)??e.manager.createDesktop(),r=t.label??n?.defaultLabel??n?.label??"";return r&&e.manager.renameDesktop(i.id,r),o&&Un(e,i.id,o),t.activate!==!1&&e.manager.switchDesktop(i.id),i}function ip(e,t){switch(t){case"cascade":e.cascade();break;case"tile":e.tile();break;case"columns":e.columns();break;case"focus":e.focusLayout();break}}function rp(e,t,n){const o=n.item.menu?.url;return Tn(t)??e.deriveWindowId(o?Si(o,e.adminUrl):t)}function ap(e,t,n,o){const s=[(r,a)=>r.id===a,(r,a)=>e.deriveWindowId(r.config.url??"")===a,()=>!0],i=new Map;for(const r of s)for(const a of t){if(!a.url||i.has(a))continue;const l=Si(a.url,e.adminUrl),c=e.deriveWindowId(l),d=e.manager.getAllByBaseId(rp(e,l,a)).find(u=>!o.has(u.id)&&(!u.config.desktopId||u.config.desktopId===n)&&r(u,c));d&&(o.add(d.id),i.set(a,d))}return i}function cp(e,t,n,o,s){const i=Tn(t);if(i){const a=new Set(e.manager.getAllByBaseId(i).map(l=>l.id));if(Me(t,{newInstance:!0}))return Za(e.manager,i,l=>!a.has(l.id)&&!s.has(l.id))}const r=n.item.menu;return e.manager.openNew({id:e.deriveWindowId(t),baseId:rp(e,t,n),url:t,parentUrl:r?.url??t,title:n.title??n.item.title,icon:n.item.icon,submenu:r?.submenu,selfLabel:r?.selfLabel,multi:!!r?.multi,desktopId:o})}function Ya(e,t,n={}){const o=Jt(e.manager,t);if(!o||o.provisioned&&!n.force)return;Un(e,t,{...o,provisioned:!0});const s=Qf(e.getNavItems(),o.windows),i=new Set,r=ap(e,s,t,i),a=[];let l=0;for(const[d,u]of s.entries()){if(u.url){const f=Si(u.url,e.adminUrl);l++;const p=r.get(u);if(p){a[d]=p.id,zo(e.manager,p,u);continue}cp(e,f,u,t,i).then(g=>{g&&(i.add(g.id),a[d]=g.id,zo(e.manager,g,u))}).catch(()=>{});continue}u.item.windowId&&(l++,e.openNative(u.item.windowId),Za(e.manager,u.item.windowId).then(f=>{f&&(a[d]=f.id,zo(e.manager,f,u))}))}dp(()=>{lp(e.manager,o.layout,a),A(v.WORKSPACE_PROVISIONED,{desktopId:t,opened:l,layout:o.layout})})}function lp(e,t,n){const o=n.find(Boolean);t==="focus"&&o&&e.focus(o),ip(e,t)}function dp(e){typeof requestAnimationFrame<"u"?requestAnimationFrame(()=>requestAnimationFrame(e)):e()}function MI(e,t){const n=Jt(e.manager,t);if(!n||!n.provisioned||n.windows.length===0)return;const o=Qf(e.getNavItems(),n.windows),s=new Set,i=ap(e,o,t,s),r=[],a=[];for(const[l,c]of o.entries()){if(c.url){const d=Si(c.url,e.adminUrl),u=i.get(c);if(u){r[l]=u.id;continue}a.push(cp(e,d,c,t,s).then(f=>{f&&(s.add(f.id),r[l]=f.id,zo(e.manager,f,c))}).catch(()=>{}));continue}if(c.item.windowId){if(e.manager.getById(c.item.windowId)){r[l]=c.item.windowId;continue}e.openNative(c.item.windowId),a.push(Za(e.manager,c.item.windowId).then(d=>{d&&(r[l]=d.id,zo(e.manager,d,c))}))}}a.length>0&&Promise.all(a).then(()=>dp(()=>{e.manager.getActiveDesktopId()===t&&lp(e.manager,n.layout,r)}))}function Xa(e,t){const n=[],o=new Set,s=ge(e._desktop);for(const i of e.getAll()){if((i.config.desktopId||e.getActiveDesktopId())!==t)continue;const r=i.config.baseId||i.id;if(o.has(r))continue;o.add(r);const a={match:r,title:i.config.title||r};if(i.config.native!==!0&&i.config.url&&(a.url=i.config.url),i._gridSpan)a.gridSpan={...i._gridSpan};else if(i.state==="normal"&&s.width>0&&s.height>0){const l=i.element;a.place=WI({x:(l.offsetLeft-s.x)/s.width,y:(l.offsetTop-s.y)/s.height,width:l.offsetWidth/s.width,height:l.offsetHeight/s.height})}if(n.push(a),n.length>=II)break}return n}function WI(e){const t=n=>Number.isFinite(n)?Math.min(1,Math.max(0,n)):0;return{x:t(e.x),y:t(e.y),width:Math.max(.05,t(e.width)),height:Math.max(.05,t(e.height))}}function zo(e,t,n){const o=ge(e._desktop);if(n.gridSpan){t._gridSpan={anchor:{...n.gridSpan.anchor},cursor:{...n.gridSpan.cursor},cols:n.gridSpan.cols,rows:n.gridSpan.rows},Zf(t,o),t._emitChange("moved");return}if(n.place){const s=n.place;t.element.style.left=`${Math.round(o.x+s.x*o.width)}px`,t.element.style.top=`${Math.round(o.y+s.y*o.height)}px`,t.element.style.width=`${Math.round(s.width*o.width)}px`,t.element.style.height=`${Math.round(s.height*o.height)}px`,t._emitChange("moved")}}function Za(e,t,n,o=8e3){const s=()=>n?e.getAllByBaseId(t).find(n)??null:e.getById(t)??null,i=s();return i?Promise.resolve(i):new Promise(r=>{const a=d=>{document.removeEventListener("os-window-opened",l),window.clearTimeout(c),r(d)},l=d=>{const u=d.detail;if(n||u?.windowId===t){const f=s();f&&a(f)}},c=window.setTimeout(()=>a(null),o);document.addEventListener("os-window-opened",l)})}function PI(e,t,n={}){const o=e.manager._desktops.find(r=>r.id===t);if(!o)return null;const i={...o.profile??op(),windows:Xa(e.manager,t),layout:"free",provisioned:!0};if(n.visibleAppIds){const r=new Set(e.getNavItems().filter(a=>a.kind==="control"||a.locked).map(a=>a.id));i.apps={mode:"only",ids:n.visibleAppIds.filter(a=>!r.has(a))}}return n.mountedWidgetIds&&(i.widgets={mode:"only",ids:[...n.mountedWidgetIds]}),Un(e,t,i),i}function Si(e,t){if(/^https?:\/\//i.test(e))return e;try{return new URL(e,t).href}catch{return t}}let Nt=null;function $I(e){return Nt=e,()=>{Nt=null}}function UI(){return Nt!==null}function BI(e){return Nt?(Nt.openCreator(e),!0):!1}function FI(e){return Nt?(Nt.openEditor(e),!0):!1}function up(e){const t=e.profile;return t?t.windows.length>0||t.layout!=="free"||t.widgets?.mode==="only"||Object.keys(t.appearance??{}).length>0:!1}function HI(e){const t=Nt;return t?(t.manager.switchDesktop(e),qa(t,e),Ya(t,e,{force:!0}),!0):!1}const fp=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],ki="osHadFullscreenBeforeOverview",GI=250;function pp(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[ki]="true",Ba()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function hp(e){if(e.element.dataset[ki]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[ki],Ba();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[ki],Ba()}}function Ja(e,t=!0){t&&hp(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function mp(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function gp(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function zI(e){if(e._overviewActive)return;wp(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,A(v.OVERVIEW_ENTERING,{}),A(v.DOCK_REFRESH_ACTIVE,{});for(const c of fp){const d=document.getElementById(c);d&&(d.inert=!0)}mp(!0),gp(e,!0),e._overviewSnapshot.clear();for(const c of t)e._overviewSnapshot.set(c.id,{transform:c.element.style.transform||"",transition:c.element.style.transition||""});for(const c of t)pp(c);const n=e._desktop.getBoundingClientRect(),o=Array.from(document.querySelectorAll(".os-dock"));let s=0;for(const c of o){const d=c.getBoundingClientRect(),u=d.bottom>n.top&&d.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=yp(e),e._desktop.appendChild(e._overviewTopBar);const a=fa(t,i,yu(e._overviewTopBar));e._overviewLabels.clear();for(const c of a){const d=c.win.element;d.classList.add("os-window--overview");const u=c.x-d.offsetLeft,f=c.y-d.offsetTop;d.style.transform=`translate(${u}px, ${f}px) scale(${c.scale})`;const p=ec(c);d.insertAdjacentElement("afterend",p),e._overviewLabels.set(c.win.id,p)}const l=c=>{const d=c.target,u=d?.closest(".os-window--overview");return u?{id:u.id.replace(/^wp-window-/,""),element:u}:d===e._desktop?{id:"backdrop",element:e._desktop}:null};e._overviewPointerDownHandler=c=>{if(c.button!==0){e._overviewPressTarget=null;return}e._overviewPressTarget=l(c),e._overviewPressTarget&&(c.preventDefault(),c.stopPropagation())},e._overviewPointerUpHandler=c=>{if(c.button!==0)return;const d=e._overviewPressTarget;if(e._overviewPressTarget=null,!d)return;const u=d.element.getBoundingClientRect();if(!(c.clientX>=u.left&&c.clientX<=u.right&&c.clientY>=u.top&&c.clientY<=u.bottom))return;if(c.preventDefault(),c.stopPropagation(),d.id==="backdrop"){Ot(e);return}const p=e.getById(d.id);A(v.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),Ot(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){Ot(e);return}if(c.key==="Enter"){const u=c.target?.ownerDocument||document;if(u.activeElement&&u.activeElement.tagName==="BUTTON")return;if(c.preventDefault(),e._overviewAddTileFocused){vp(e);return}Ot(e)}},e._desktop.addEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._desktop.addEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewClickBlocker=c=>{c.target?.closest(".os-overview-top-bar")||(c.stopPropagation(),c.preventDefault())},e._desktop.addEventListener("click",e._overviewClickBlocker,!0),document.addEventListener("keydown",e._overviewKeyHandler),e._lastOverviewHoverId=null,e._overviewMouseHandler=c=>{const u=c.target?.closest(".os-window--overview"),f=u?u.id.replace(/^wp-window-/,""):null;f!==e._lastOverviewHoverId&&(e._lastOverviewHoverId&&A(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&A(v.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&A(v.OVERVIEW_ENTERED,{})},300)}function wp(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function jI(e){e._overviewEnterTimeoutId!==null&&(window.clearTimeout(e._overviewEnterTimeoutId),e._overviewEnterTimeoutId=null),e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null),e._overviewExitFinalizer=null}let Qa=null;function VI(e){return Qa=e,()=>{Qa=null}}function yp(e){const t=document.createElement("div");t.className="os-overview-top-bar";const n=Qa?.();if(n){const a=document.createElement("div");a.className="os-overview-top-bar__header",a.appendChild(n),t.appendChild(a)}const o=document.createElement("div");o.className="os-overview-top-bar__list",t.appendChild(o),e._desktops.some(up)&&o.classList.add("os-overview-top-bar__list--restorable");for(const a of e._desktops)o.appendChild(KI(e,a));const s=document.createElement("button");s.type="button",s.className="os-overview-top-bar__tile os-overview-top-bar__tile--add",e._overviewAddTileFocused&&s.classList.add("os-overview-top-bar__tile--cursor"),s.setAttribute("aria-label",b("Add new workspace")),s.innerHTML='<span class="os-overview-top-bar__tile-preview"><span class="os-overview-top-bar__tile-plus" aria-hidden="true">+</span></span><span class="os-overview-top-bar__tile-label" aria-hidden="true"> </span>',s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),vp(e)});const i=document.createElement("div");i.className="os-overview-top-bar__tile-wrapper os-overview-top-bar__tile-wrapper--add",i.appendChild(s);const r=document.createElement("div");return r.className="os-overview-top-bar__tile-actions",i.appendChild(r),o.appendChild(i),t}function vp(e){e._overviewAddTileFocused=!1;const t=_p(e);Ii(e,t.id),BI(t.id)}function KI(e,t){const n=document.createElement("div");n.className="os-overview-top-bar__tile-wrapper";const o=document.createElement("button");o.type="button",o.className="os-overview-top-bar__tile",o.dataset.desktopId=t.id,t.id===e._activeDesktopId&&!e._overviewAddTileFocused&&o.classList.add("os-overview-top-bar__tile--active"),o.setAttribute("aria-label",le(b("Switch to %s"),t.label));const s=t.profile;s?.color&&(n.style.setProperty("--os-workspace-accent",s.color),o.classList.add("os-overview-top-bar__tile--tinted"));const i=document.createElement("span");if(i.className="os-overview-top-bar__tile-preview",s?.icon){const p=document.createElement("span");p.className=`os-overview-top-bar__tile-glyph dashicons ${s.icon}`,p.setAttribute("aria-hidden","true"),i.appendChild(p)}const r=e._stack.filter(p=>p.config.desktopId===t.id).length;if(r>0){const p=document.createElement("span");p.className="os-overview-top-bar__tile-count",p.textContent=String(r),i.appendChild(p)}o.appendChild(i);const a=document.createElement("span");a.className="os-overview-top-bar__tile-label",a.textContent=t.label,a.title=le(b("%s — double-click to rename"),t.label),o.appendChild(a);let l;a.addEventListener("click",p=>{a.hasAttribute("contenteditable")||(p.preventDefault(),p.stopPropagation(),l===void 0&&(l=window.setTimeout(()=>{l=void 0,e._overviewActive&&Ii(e,t.id)},GI)))}),a.addEventListener("dblclick",p=>{a.hasAttribute("contenteditable")||(p.preventDefault(),p.stopPropagation(),window.clearTimeout(l),l=void 0,bp(e,a,t))}),o.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),!a.hasAttribute("contenteditable")&&Ii(e,t.id)});const c=UI(),d=document.createElement("button");d.type="button",d.className="os-overview-top-bar__tile-edit",c?d.setAttribute("aria-label",le(b("Edit %s — its apps, widgets, look and windows"),t.label)):d.setAttribute("aria-label",le(b("Rename %s"),t.label)),d.title=d.getAttribute("aria-label")??"",d.innerHTML=qt("edit",{size:14}),d.addEventListener("click",p=>{if(p.preventDefault(),p.stopPropagation(),!c){bp(e,a,t);return}Ii(e,t.id),FI(t.id)});const u=document.createElement("button");u.type="button",u.className="os-overview-top-bar__tile-close",u.setAttribute("aria-label",le(b("Close %s"),t.label)),u.innerHTML=qt("close",{size:16}),u.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),Ap(e,t.id),jo(e)}),n.appendChild(o),n.appendChild(d),n.appendChild(u);const f=document.createElement("div");if(f.className="os-overview-top-bar__tile-actions",up(t)){const p=document.createElement("button");p.type="button",p.className="os-overview-top-bar__tile-action os-overview-top-bar__tile-restore",p.setAttribute("aria-label",le(b("Restore %s — reopen its windows, widgets and look"),t.label)),p.title=p.getAttribute("aria-label")??"",p.innerHTML=`${qt("windows",{size:12})}<span>${b("Restore")}</span>`,p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),HI(t.id)&&Ot(e)}),f.appendChild(p)}return f.childElementCount>0&&n.appendChild(f),n}function bp(e,t,n){if(t.hasAttribute("contenteditable"))return;t.setAttribute("contenteditable","true");try{t.contentEditable="plaintext-only"}catch{}t.spellcheck=!1,t.focus();const o=t.ownerDocument.defaultView,s=t.ownerDocument.createRange();s.selectNodeContents(t);const i=o?.getSelection();i?.removeAllRanges(),i?.addRange(s);let r=!1;const a=l=>{r||(r=!0,t.removeAttribute("contenteditable"),l&&kp(e,n.id,t.textContent??""),e._overviewActive&&jo(e))};t.addEventListener("keydown",l=>{l.stopPropagation(),(l.key==="Enter"||l.key==="Escape")&&(l.preventDefault(),a(l.key==="Enter"))}),t.addEventListener("blur",()=>a(!0)),t.addEventListener("click",l=>l.stopPropagation())}function jo(e){if(!e._overviewTopBar)return;const t=yp(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Ii(e,t){Ip(e,t),Ot(e)}function ec(e){const t=document.createElement("div");t.className="os-overview-label",t.dataset.windowId=e.win.id;const n=e.win.element.offsetWidth*e.scale;t.style.left=`${e.x}px`,t.style.top=`${e.y-34}px`,t.style.width=`${n}px`;const o=e.win.config.icon||"dashicons-admin-generic",s=document.createElement("span");s.className=`os-overview-label__icon dashicons ${o}`,s.setAttribute("aria-hidden","true"),t.appendChild(s);const i=document.createElement("span");i.className="os-overview-label__title",i.textContent=e.win.config.title,t.appendChild(i);const r=e.win.getExternalTabCount();if(r>0){const a=document.createElement("span");a.className="os-overview-label__meta",a.textContent=le(Kt("· %d open tab","· %d open tabs",r),r),t.appendChild(a)}return t}function Ot(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,A(v.OVERVIEW_EXITING,{windowId:t?t.id:void 0,reason:t?"select":"cancel"}),A(v.DOCK_REFRESH_ACTIVE,{}),e._desktop.classList.remove("os-area--overview"),document.getElementById("os-shell")?.classList.remove("os-shell--overview");for(const i of fp){const r=document.getElementById(i);r&&(r.inert=!1)}mp(!1),gp(e,!1);for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform)}t&&(t.state==="minimized"&&(hp(t),t.restore()),e.focus(t),n&&t.maximize());for(const i of e._stack)i.state==="minimized"&&i.element.classList.remove("os-window--overview");for(const i of e._overviewLabels.values())i.classList.add("os-overview-label--out");e._overviewTopBar&&e._overviewTopBar.classList.add("os-overview-top-bar--out");const s=280;e._overviewExitFinalizer=()=>{for(const i of e._stack)i.element.classList.remove("os-window--overview"),Ja(i,i.config.desktopId===e._activeDesktopId);for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),e._overviewTopBar&&(e._overviewTopBar.remove(),e._overviewTopBar=null),e._overviewClickBlocker&&(e._desktop.removeEventListener("click",e._overviewClickBlocker,!0),e._overviewClickBlocker=null),A(v.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>wp(e),s),e._overviewPointerDownHandler&&(e._desktop.removeEventListener("pointerdown",e._overviewPointerDownHandler,!0),e._overviewPointerDownHandler=null),e._overviewPointerUpHandler&&(e._desktop.removeEventListener("pointerup",e._overviewPointerUpHandler,!0),e._overviewPointerUpHandler=null),e._overviewPressTarget=null,e._overviewKeyHandler&&(document.removeEventListener("keydown",e._overviewKeyHandler),e._overviewKeyHandler=null),e._overviewMouseHandler&&(e._desktop.removeEventListener("mouseover",e._overviewMouseHandler),e._overviewMouseHandler=null),e._lastOverviewHoverId&&(A(v.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function qI(e){return[...e._desktops]}function Ep(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function YI(e){return Ep(e).id}function Ai(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&Ja(t)}function tc(e){for(const t of e._stack)Ai(e,t)}function XI(e,t,n){const o=e._stack.find(i=>i.id===t);if(!o||!e._desktops.some(i=>i.id===n))return!1;const s=o.config.desktopId||e._activeDesktopId;return s===n||(o.config.desktopId=n,e._overviewActive?nc(e):Ai(e,o),A(v.WINDOW_DESKTOP_CHANGED,{windowId:t,from:s,to:n})),!0}function _p(e,t){e._desktopSeq++;const n={id:`desktop-${e._desktopSeq}`,label:t?.label?.trim().slice(0,Sp)||le(b("Workspace %d"),e._desktopSeq)};return e._desktops.push(n),A(v.DESKTOP_CREATED,{desktopId:n.id}),n}const Sp=64;function kp(e,t,n){const o=e._desktops.find(r=>r.id===t);if(!o)return!1;const s=n.trim().slice(0,Sp);if(!s||s===o.label)return!1;const i=o.label;return o.label=s,A(v.DESKTOP_RENAMED,{desktopId:t,label:s,previousLabel:i}),!0}function Ip(e,t,n){if(t===e._activeDesktopId||!e._desktops.some(s=>s.id===t))return;const o=e._activeDesktopId;if(e._activeDesktopId=t,e._overviewActive)nc(e),jo(e);else{tc(e),n?.direction&&ZI(e,n.direction);const s=[...e._stack].reverse().find(r=>r.config.desktopId===t&&r.state!=="minimized");s&&e.focus(s);const i=e._desktops.find(r=>r.id===t);i&&n_(e._desktop,i.label)}A(v.DESKTOP_SWITCHED,{from:o,to:t})}function ZI(e,t){const n=e._desktop,o=t==="next"?"os-area--sliding-from-right":"os-area--sliding-from-left";n.classList.remove("os-area--sliding-from-right","os-area--sliding-from-left"),n.offsetWidth,n.classList.add(o);const s=i=>{i.animationName.startsWith("os-area-slide-from-")&&(n.classList.remove(o),n.removeEventListener("animationend",s))};n.addEventListener("animationend",s)}function Ap(e,t){if(e._desktops.length<=1)return;const n=e._desktops.findIndex(r=>r.id===t);if(n===-1)return;const o=n>0?n-1:1,s=e._desktops[o];for(const r of e._stack)r.config.desktopId===t&&(r.config.desktopId=s.id);e._desktops.splice(n,1);const i=e._activeDesktopId===t;i&&(e._activeDesktopId=s.id),e._overviewActive?nc(e):tc(e),A(v.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id}),i&&A(v.DESKTOP_SWITCHED,{from:t,to:s.id})}function nc(e){for(const[i,r]of e._overviewSnapshot){const a=e.getById(i);a&&(a.element.style.transform=r.transform,a.element.style.transition=r.transition,a.element.classList.remove("os-window--overview"),Ja(a,a.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),tc(e);const t=e._stack.filter(i=>i.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const i of t)e._overviewSnapshot.set(i.id,{transform:i.element.style.transform||"",transition:i.element.style.transition||""}),pp(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=fa(t,o,yu(e._overviewTopBar));for(const i of s){const r=i.win.element;r.classList.add("os-window--overview");const a=i.x-r.offsetLeft,l=i.y-r.offsetTop;r.style.transform=`translate(${a}px, ${l}px) scale(${i.scale})`;const c=ec(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function JI(e,t,n){if(t.length===0)return;e._desktops=t.map(s=>({...s})),e._activeDesktopId=t.some(s=>s.id===n)?n:t[0].id;let o=0;for(const s of t){const i=s.id.match(/^desktop-(\d+)$/);if(i){const r=parseInt(i[1],10);Number.isFinite(r)&&r>o&&(o=r)}}e._desktopSeq=Math.max(e._desktopSeq,o)}function QI(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;A(v.ARRANGE_CASCADE_STARTING,{windowCount:t.length});for(const u of t)u.state==="minimized"&&u.restore(),u.state==="fullscreen"&&u.toggleFullscreen(),u.state==="maximized"&&u.toggleMaximize();const n=ge(e._desktop),o=30,s=30,i=Math.min(Math.round(n.width*.7),1100),r=Math.min(Math.round(n.height*.75),750),a=Math.max(1,Math.floor((n.width-i-o)/s)),l=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(a,l);t.forEach((u,f)=>{const p=f%Math.max(1,c);u._gridSpan=null,u.element.style.left=`${n.x+o+p*s}px`,u.element.style.top=`${n.y+o+p*s}px`,u.element.style.width=`${i}px`,u.element.style.height=`${r}px`});const d=e.getFocused();d&&e.focus(d),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"cascade"}})),A(v.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function Cp(e){const t=e._stack.filter(f=>f.config.desktopId===e._activeDesktopId);if(t.length===0)return;for(const f of t)f.state==="minimized"&&f.restore(),f.state==="fullscreen"&&f.toggleFullscreen(),f.state==="maximized"&&f.toggleMaximize();const n=ge(e._desktop),o=r_(t.length,n.width,n.height),s=J(v.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=s_(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;A(v.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const a=16,l=12,c=Math.floor((n.width-a*2-l*(i-1))/i),d=Math.floor((n.height-a*2-l*(r-1))/r);t.forEach((f,p)=>{const g=p%i,h=Math.floor(p/i);f._gridSpan=null,f.element.style.left=`${n.x+a+g*(c+l)}px`,f.element.style.top=`${n.y+a+h*(d+l)}px`,f.element.style.width=`${c}px`,f.element.style.height=`${d}px`});const u=e.getFocused();u&&e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"tile"}})),A(v.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}function Lp(e){const t=e._stack.filter(n=>n.config.desktopId===e._activeDesktopId);if(t.length===0)return[];for(const n of t)n.state==="minimized"&&n.restore(),n.state==="fullscreen"&&n.toggleFullscreen(),n.state==="maximized"&&n.toggleMaximize(),n._gridSpan=null;return t}function eA(e,t){const n=e.getFocused();n&&e.focus(n),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:t}}))}const tA=4;function nA(e){const t=Lp(e);if(t.length===0)return;if(t.length>tA){Cp(e);return}const n=t.length;A(v.ARRANGE_COLUMNS_STARTING,{windowCount:t.length,cols:n});const o=ge(e._desktop),s=16,i=12,r=Math.floor((o.width-s*2-i*(n-1))/n),a=Math.floor(o.height-s*2);t.forEach((l,c)=>{l.element.style.left=`${o.x+s+c*(r+i)}px`,l.element.style.top=`${o.y+s}px`,l.element.style.width=`${r}px`,l.element.style.height=`${a}px`}),eA(e,"columns"),A(v.ARRANGE_COLUMNS_APPLIED,{windowCount:t.length,cols:n})}const Tp=.64;function oA(e){const t=Lp(e);if(t.length===0)return;const n=ge(e._desktop),o=J(v.ARRANGE_FOCUS_SPLIT,Tp,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),s=Number.isFinite(o)&&o>=.3&&o<=.9?o:Tp;A(v.ARRANGE_FOCUS_STARTING,{windowCount:t.length,split:s});const i=16,r=12,a=n.width-i*2,l=n.height-i*2,c=e.getFocused(),d=c&&t.includes(c)?t.indexOf(c):0,u=t[d],f=t.filter((g,h)=>h!==d),p=f.length===0?a:Math.floor(a*s);if(u.element.style.left=`${n.x+i}px`,u.element.style.top=`${n.y+i}px`,u.element.style.width=`${p}px`,u.element.style.height=`${l}px`,f.length>0){const g=n.x+i+p+r,h=a-p-r,m=Math.floor((l-r*(f.length-1))/f.length);f.forEach((_,I)=>{_.element.style.left=`${g}px`,_.element.style.top=`${n.y+i+I*(m+r)}px`,_.element.style.width=`${h}px`,_.element.style.height=`${m}px`})}e.focus(u),document.dispatchEvent(new CustomEvent("os-window-changed",{detail:{reason:"focus"}})),A(v.ARRANGE_FOCUS_APPLIED,{windowCount:t.length,split:s})}const Np="desktop-mode-snap-to-grid";function sA(){try{return window.localStorage.getItem(Np)==="1"}catch{return!1}}function iA(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(Np,t?"1":"0")}catch{}A(v.ARRANGE_SNAP_CHANGED,{enabled:t})}}function rA(e){if(!e._snapEnabled)return{enabled:!1,cellWidth:0,cellHeight:0};const t=e._desktop.getBoundingClientRect(),n=t.width>=t.height?12:8,o={cellWidth:Math.max(40,Math.round(t.width/n)),cellHeight:Math.max(40,Math.round(t.height/Math.round(n*.66)))},s=J(v.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=i_(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}const Op="desktop-mode-native-window-geometry",Dp=64,at=8192;function Ci(){try{const e=window.localStorage.getItem(Op);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function Rp(e){try{window.localStorage.setItem(Op,JSON.stringify(e))}catch{}}function Li(e){if(!e)return null;const n=Ci()[e];if(!n)return null;const o=Number(n.width),s=Number(n.height);if(!Number.isFinite(o)||!Number.isFinite(s)||o<=0||s<=0||o>at||s>at)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),a=Number(n.y),l=Number.isFinite(r)&&Number.isFinite(a)&&r>=0&&a>=0&&r<=at&&a<=at;return{width:Math.round(o),height:Math.round(s),...l?{x:Math.round(r),y:Math.round(a)}:{},...i?{state:i}:{}}}function xp(e,t){if(!e)return;const n=Math.round(Number(t.width)),o=Math.round(Number(t.height));if(!Number.isFinite(n)||!Number.isFinite(o)||n<=0||o<=0||n>at||o>at)return;const s=Ci(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,a=typeof i?.x=="number"?i.x:void 0,l=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===a&&i.y===l||(Vo(s,e,{width:n,height:o,...typeof a=="number"&&typeof l=="number"?{x:a,y:l}:{},...r?{state:r}:{}}),Ko(s))}function Mp(e,t){if(!e)return;const n=Math.round(Number(t.x)),o=Math.round(Number(t.y));if(!Number.isFinite(n)||!Number.isFinite(o)||n<0||o<0||n>at||o>at)return;const s=Ci(),i=s[e];i&&(i.x===n&&i.y===o||(Vo(s,e,{...i,x:n,y:o}),Ko(s)))}function Wp(e,t,n){if(!e)return;const o=Ci(),s=o[e];if(!s){if(t===null||!n)return;const i=Math.round(Number(n.width)),r=Math.round(Number(n.height));if(!Number.isFinite(i)||!Number.isFinite(r)||i<=0||r<=0||i>at||r>at)return;Vo(o,e,{width:i,height:r,state:t}),Ko(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;Vo(o,e,r),Ko(o);return}s.state!==t&&(Vo(o,e,{...s,state:t}),Ko(o))}function Vo(e,t,n){delete e[t],e[t]=n}function Ko(e){const t=Object.keys(e);if(t.length>Dp){const n={};for(const o of t.slice(-Dp))n[o]=e[o];Rp(n);return}Rp(e)}function aA(e,t,n,o){const s=o.x+xa-n,i=o.x+o.width-xa,r=Math.max(s,Math.min(e,i)),a=o.y+ok,l=o.y+o.height-xa,c=Math.max(a,Math.min(t,l));return{x:r,y:c}}const Pp=100,Ti=30;class cA{constructor(t){this._stack=[],this._cascadeMinimized=new WeakSet,this._cascadeDepth=0,this.cascadeIndex=0,this._pendingRestoreState=new Map,this._reservedRestoreIds=new Set,this._openingWindowIds=new Set,this._openingBaseIds=new Set,this._prewarmed=null,this._prewarmInFlight=!1,this._desktops=[{id:"desktop-1",label:"Workspace 1"}],this._activeDesktopId="desktop-1",this._desktopSeq=1,this.onToggleStartupRequested=null,this.desktopResizeObserver=null,this._reflowRestoreTimer=null,this._snapEnabled=sA(),this._overviewActive=!1,this._overviewSnapshot=new Map,this._overviewLabels=new Map,this._overviewPointerDownHandler=null,this._overviewPointerUpHandler=null,this._overviewKeyHandler=null,this._overviewPressTarget=null,this._overviewClickBlocker=null,this._overviewTopBar=null,this._overviewMouseHandler=null,this._lastOverviewHoverId=null,this._overviewAddTileFocused=!1,this._overviewEnterTimeoutId=null,this._overviewExitTimeoutId=null,this._overviewExitFinalizer=null,this._snapPendingZone=null,this._snapPreviewEl=null,this._gridSnap=null,this._splitOverviewActive=!1,this._splitOverviewAnchor=null,this._splitOverviewZone=null,this._splitOverviewSnapshot=new Map,this._splitOverviewLabels=new Map,this._splitOverviewPointerDown=null,this._splitOverviewPointerUp=null,this._splitOverviewPressTarget=null,this._splitOverviewClickBlocker=null,this._splitOverviewKey=null,this._desktop=t,typeof ResizeObserver<"u"&&(this.desktopResizeObserver=new ResizeObserver(()=>this.reflowStatefulWindows()),this.desktopResizeObserver.observe(t)),this._unsubscribeWorkArea=Fo(()=>this.reflowStatefulWindows()),this.installIframeFocusBridge()}installIframeFocusBridge(){window.addEventListener("blur",()=>{window.setTimeout(()=>{const t=this._desktop.ownerDocument?.activeElement??null;if(!t||t.tagName!=="IFRAME")return;const n=t.closest(".os-window");if(!n)return;const o=n.id.replace(/^wp-window-/,""),s=this.getById(o);s&&(this._overviewActive||this.getFocused()!==s&&this.focus(s))},0)})}reflowStatefulWindows(){if(!this._overviewActive){for(const t of this._stack){const n=t.element.parentElement;if(!n)continue;const o=ge(n);if(t.state==="maximized")t.element.classList.add("os-window--reflowing"),t.element.style.left=`${o.x}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${o.width}px`,t.element.style.height=`${o.height}px`;else if(t.state==="snapped-left"||t.state==="snapped-right"){t.element.classList.add("os-window--reflowing");const s=Math.floor(o.width/2),i=o.height,r=t.state==="snapped-left"?o.x:o.x+o.width-s;t.element.style.left=`${r}px`,t.element.style.top=`${o.y}px`,t.element.style.width=`${s}px`,t.element.style.height=`${i}px`}else if(t.state==="normal"){const s=parseInt(t.element.style.left,10)||0,i=parseInt(t.element.style.top,10)||0,r=t.element.offsetWidth||0,a=aA(s,i,r,{x:0,y:0,width:n.clientWidth,height:n.clientHeight});(s!==a.x||i!==a.y)&&(t.element.classList.add("os-window--reflowing"),t.element.style.left=`${a.x}px`,t.element.style.top=`${a.y}px`)}}this._reflowRestoreTimer!==null&&window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=window.setTimeout(()=>{this._reflowRestoreTimer=null;for(const t of this._stack)t.element.classList.remove("os-window--reflowing")},140)}}async open(t){if(!t||typeof t!="object")throw new TypeError("windowManager.open() requires a config object with at least { id, url, title }; received "+(t===null?"null":typeof t));if(typeof t.id!="string"||t.id==="")throw new TypeError("windowManager.open(): config.id must be a non-empty string.");if(typeof t.url!="string"||t.url==="")throw new TypeError('windowManager.open(): config.url must be a non-empty string. Pass an admin URL (e.g. "/wp-admin/edit.php") or a hash fragment (e.g. "#my-window") for native windows.');if(typeof t.title!="string")throw new TypeError("windowManager.open(): config.title must be a string.");const n=t.baseId||t.id,o=this.getByBaseIdOnActiveDesktop(n);if(o){const r=o.state==="minimized";this.focus(o),r&&o.restore();let a=!1;if(!o.config.native){const c=In(t.url);c===In(o.getCurrentUrl())||c===In(o.config.url||"")||c===In(o.config.parentUrl??o.config.url??"")||(a=o.navigateTo(t.url))}t.params&&(o.config.params={...t.params});const l={windowId:o.id,baseId:n,wasMinimized:r,navigated:a,params:o.config.params??{}};return document.dispatchEvent(new CustomEvent("os-window-reopened",{detail:l})),A(v.WINDOW_REOPENED,l),o}const s=this.adoptPrewarmed(n,t);if(s)return s;const i=this.getByBaseId(n)?this.nextInstanceId(n):t.id;return this.createWindow({...t,id:i,baseId:n})}async prewarm(t){const n=t.baseId||t.id;if(t.native||this._prewarmInFlight||this._prewarmed?.baseId===n||this.getByBaseId(n))return!1;this._prewarmInFlight=!0;try{this.discardPrewarmed();const o=await this.createWindow({...t,id:t.id,baseId:n},{prewarm:!0});if(this.getByBaseId(n))return this.teardownSpeculativeWindow(o),!1;const s=window.setTimeout(()=>this.discardPrewarmed(),45e3);return this._prewarmed={baseId:n,win:o,timer:s},!0}finally{this._prewarmInFlight=!1}}adoptPrewarmed(t,n){const o=this._prewarmed;if(!o||o.baseId!==t)return null;const s=o.win;if(In(n.url)!==In(s.config.url||"")||this.getById(s.id))return this.discardPrewarmed(),null;window.clearTimeout(o.timer),this._prewarmed=null,s.config.desktopId=this._activeDesktopId,s.element.style.display="",s.element.removeAttribute("aria-hidden"),this._stack.push(s),Ai(this,s),this.focus(s);const i={windowId:s.id,page:s.config.url??n.url,title:s.config.title,url:s.config.url??n.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:i})),A(v.WINDOW_OPENED,i),s}discardPrewarmed(){const t=this._prewarmed;t&&(this._prewarmed=null,window.clearTimeout(t.timer),this.teardownSpeculativeWindow(t.win))}teardownSpeculativeWindow(t){try{globalThis.__openStationConnectionBridge?.onWindowClosed?.(t.id)}catch{}t.onClose=null;try{t.destroy()}catch{}t.element.remove()}async openNew(t){const n=t.baseId||t.id,o=t.id!==n&&!this.getById(t.id)&&!this._openingWindowIds.has(t.id)?t.id:this.nextInstanceId(n),s=!!this.getByBaseIdOnActiveDesktop(n)||this._openingBaseIds.has(n);if(!s){const a=this.adoptPrewarmed(n,t);if(a)return a}const i=40+this.cascadeIndex%8*Ti,r=40+this.cascadeIndex%8*Ti;return this.createWindow({...s?{initialState:"normal",x:i,y:r}:{},...t,id:o,baseId:n})}async createWindow(t,n={}){const o=this._pendingRestoreState.get(t.id);o&&(this._pendingRestoreState.delete(t.id),this._reservedRestoreIds.delete(t.id),t={...t,...o});const s=this._desktop.getBoundingClientRect(),i=ge(this._desktop),r=12,a=Math.min(Math.round(i.width*.8),1200),l=Math.min(Math.round(i.height*.8),800),c=i.x+40+this.cascadeIndex%8*Ti,d=i.y+40+this.cascadeIndex%8*Ti,u=t.baseId||t.id,f=t.minWidth??320,p=t.minHeight??200,g=typeof t.width=="number",h=typeof t.height=="number",m=typeof t.x=="number",_=typeof t.y=="number",I=typeof t.initialState=="string",O=!g||!h||!I||!m||!_?Li(u):null;let $=t.width??(O?Math.max(O.width,f):a),S=t.height??(O?Math.max(O.height,p):l);!m&&!_&&!O&&($=Math.max(f,Math.min($,i.width-r*2)),S=Math.max(p,Math.min(S,i.height-r*2)));const W=Math.max(i.x+r,Math.min(c,i.x+i.width-$-r)),U=Math.max(i.y+r,Math.min(d,i.y+i.height-S-r)),F=t.initialState??(O?.state==="maximized"?"maximized":void 0);let K,Q;if(O&&typeof O.x=="number"&&typeof O.y=="number"){const q=Math.max(i.x,i.x+i.width-$-r),se=Math.max(i.y,i.y+i.height-S-r);K=Math.max(i.x+r,Math.min(O.x,q)),Q=Math.max(i.y+r,Math.min(O.y,se))}const Z=t.x??K??W,C=t.y??Q??U,D=g||h||m||_||I,V=!!O,j={x:Z,y:C,width:$,height:S,state:F};let te;try{te=J(v.WINDOW_GEOMETRY,j,{windowId:t.id,baseId:u,hasSavedGeometry:V,callerPinned:D,desktopRect:{width:s.width,height:s.height},workArea:{...i}})}catch(q){A(v.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:q}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,q),te=j}const N=(q,se)=>typeof q=="number"&&Number.isFinite(q)?q:se,L=te&&typeof te=="object"?te:j,M=Math.max(N(L.width,$),f),P=Math.max(N(L.height,S),p),H=N(L.x,Z),z=N(L.y,C),y=L.state??F,E={icon:t.icon||"dashicons-admin-generic",...t,x:H,y:z,width:M,height:P,minWidth:f,minHeight:p,...y?{initialState:y}:{},baseId:u,desktopId:t.desktopId||this._activeDesktopId};if(t.gridSpan){const q=Xf(t.gridSpan,ge(this._desktop));E.x=q.x,E.y=q.y,E.width=q.width,E.height=q.height}this.cascadeIndex++,this._openingWindowIds.add(t.id),this._openingBaseIds.add(u);const T=Promise.all([JE(XE()),ca(la())]);let x;try{x=await T}catch(q){throw this._openingWindowIds.delete(t.id),this._openingBaseIds.delete(u),q}this._openingWindowIds.delete(t.id),this._openingBaseIds.delete(u);const[X]=x,Y=X.createWindow(E);if(t.gridSpan&&(Y._gridSpan={anchor:{...t.gridSpan.anchor},cursor:{...t.gridSpan.cursor},cols:t.gridSpan.cols,rows:t.gridSpan.rows}),Y.onFocusRequest=q=>{this._cascadeDepth>0||this.focus(q)},Y.onClose=q=>this.remove(q),Y.onMinimize=q=>{this._cascadeDepth++;try{this.cascadeMinimize(q)}finally{this._cascadeDepth--}if(this._cascadeDepth>0)return;const se=this._stack.filter(Ee=>Ee.state!=="minimized");se.length>0&&this.focus(se[se.length-1])},Y.onRestore=q=>{this._cascadeDepth++;try{this.cascadeRestore(q)}finally{this._cascadeDepth--}},Y.onOpenAnother=q=>{const se=q.config.baseId||q.id;q.config.native&&window.wp?.os?.openNewWindow?.(se,{source:"open-another"})||this.openNew({id:se,baseId:se,url:q.config.url||"",title:q.config.title,icon:q.config.icon,submenu:q.config.submenu,multi:!0})},Y.onOpenInNewWindow=q=>{const se=q.config.baseId||q.id;if(q.config.native&&window.wp?.os?.openNewWindow?.(se,{source:"open-in-new-window"}))return;const Ee=q.getCurrentUrl();this.openNew({id:se,baseId:se,url:Ee||q.config.url||"",title:q.config.title,icon:q.config.icon,submenu:q.config.submenu,multi:!0})},Y.onToggleStartup=q=>{this.onToggleStartupRequested?.(q)},Y.snapConfigProvider=()=>this.getSnapConfig(),Y.onDragMove=(q,se,Ee)=>{if(this._gridSnap){pI(this,se,Ee);return}oI(this,q,se)},Y.onDragGesture=(q,se)=>{switch(se.type){case"modifier":se.active?fI(this,q,se.clientX,se.clientY):gI(this);break;case"shake":hI(this,se.clientX,se.clientY,cI.Shake);break}},Y.onDragEnd=q=>this._gridSnap?wI(this,q):this._snapPendingZone?sI(this,q):(jf(this),!1),n.prewarm)return Y.element.style.display="none",Y.element.setAttribute("aria-hidden","true"),this._desktop.appendChild(Y.element),Y;this._stack.push(Y),this._desktop.appendChild(Y.element),Ai(this,Y),Y.hydrateNative(),this.focus(Y);const ce={windowId:Y.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:ce})),A(v.WINDOW_OPENED,ce),Y}nextInstanceId(t){const n=new Set([...this._stack.map(s=>s.id),...this._openingWindowIds,...this._reservedRestoreIds]);if(!n.has(t))return t;let o=2;for(;n.has(`${t}-${o}`);)o++;return`${t}-${o}`}focus(t){const n=typeof t=="string"?this.getById(t):t;if(!n||typeof n.setZIndex!="function"){t&&typeof t!="string"&&console.warn("[openstation] windowManager.focus() expects a Window or a window id; received",t);return}const o=this.blockingChildOf(n)??n;o!==n&&(o.shake?.(),A(v.WINDOW_CHILD_BLOCKED,{windowId:n.id,childWindowId:o.id}),document.dispatchEvent(new CustomEvent("os-window-child-blocked",{detail:{windowId:n.id,childWindowId:o.id}})));const s=this._stack.length>0?this._stack[this._stack.length-1]:null,i=this._stack.find(l=>l!==o&&l.isFocused()&&l.isFullscreen());i&&J(v.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:i.id,focusedTo:o.id})&&i.toggleFullscreen();const r=this._stack.indexOf(o);if(r>-1&&this._stack.splice(r,1),this._stack.push(o),this.enforceOwnershipOrder(),this._stack.forEach((l,c)=>{l.setZIndex(Pp+c),l.setFocused(c===this._stack.length-1)}),s&&s!==o&&s.id!==o.id){const l={windowId:s.id,focusedTo:o.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:l})),A(v.WINDOW_BLURRED,l)}const a={windowId:o.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:a})),A(v.WINDOW_FOCUSED,a)}raise(t){const n=this.getById(t);if(!n||this._stack.length<2)return;const o=this._stack.indexOf(n);o===-1||o===this._stack.length-1||(this._stack.splice(o,1),this._stack.splice(this._stack.length-1,0,n),this.enforceOwnershipOrder(),this._stack.forEach((s,i)=>{s.setZIndex(Pp+i)}))}async openChild(t,n){const o=this.getById(t);if(!o)throw new Error(`windowManager.openChild(): no open window with id "${t}". Open the owner first, or use open() for a standalone window.`);const s=Li(n.baseId||n.id),i=!!s&&typeof s.x=="number"&&typeof s.y=="number";let r={};if(n.x===void 0&&n.y===void 0&&!i){const a=o.getSnapshot(),l=n.width??Math.round(a.width*.8),c=n.height??Math.round(a.height*.8),d=ge(this._desktop),u=Math.max(d.x,d.x+d.width-l),f=Math.max(d.y,d.y+d.height-c);r={width:l,height:c,x:Math.min(u,Math.max(d.x,Math.round(a.x+(a.width-l)/2))),y:Math.min(f,Math.max(d.y,Math.round(a.y+(a.height-c)/2)))}}return this.open({...n,...r,desktopId:o.config.desktopId,parentWindowId:t})}ownerOf(t){const n=t.config.parentWindowId;return n?this.getById(n):void 0}childrenOf(t){const n=typeof t=="string"?t:t.id;return this._stack.filter(o=>o.config.parentWindowId===n)}blockingChildOf(t){let n=t,o;const s=new Set([t]);for(;;){const i=this.childrenOf(n).filter(r=>r.state!=="minimized"&&!s.has(r));if(i.length===0)return o;n=i[i.length-1],s.add(n),o=n}}enforceOwnershipOrder(){if(!this._stack.some(s=>s.config.parentWindowId))return;const t=[],n=new Set,o=(s,i)=>{if(!(n.has(s)||i.has(s))){if(i.add(s),s.state!=="minimized"){const r=this.ownerOf(s);r&&r!==s&&o(r,i)}n.has(s)||(n.add(s),t.push(s))}};for(const s of this._stack)o(s,new Set);this._stack.length=0,this._stack.push(...t)}cascadeMinimize(t){for(const n of this.childrenOf(t))n.state!=="minimized"&&(this._cascadeMinimized.add(n),n.minimize())}cascadeRestore(t){for(const n of this.childrenOf(t))this._cascadeMinimized.has(n)&&(this._cascadeMinimized.delete(n),n.restore())}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);const o=this.childrenOf(t).slice();if(o.length>0){this._cascadeDepth++;try{for(const r of o)this._cascadeMinimized.delete(r),r.close()}finally{this._cascadeDepth--}}for(let r=this._stack.length-1;this._cascadeDepth===0&&r>=0;r--){const a=this._stack[r];if(!(a.state==="minimized"||(a.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(a);break}}const s={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("os-window-closing",{detail:s})),A(v.WINDOW_CLOSING,s);const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:i})),A(v.WINDOW_CLOSED,i)}getById(t){return this._stack.find(n=>n.id===t)}getByBaseId(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)===t)return o}}getByBaseIdOnActiveDesktop(t){for(let n=this._stack.length-1;n>=0;n--){const o=this._stack[n];if((o.config.baseId||o.id)!==t)continue;if((o.config.desktopId||this._activeDesktopId)===this._activeDesktopId)return o}}getAllByBaseId(t){const n=o=>{if(o===t)return 1;const s=`${t}-`;if(o.startsWith(s)){const i=parseInt(o.slice(s.length),10);return Number.isFinite(i)?i:999}return 999};return this._stack.filter(o=>(o.config.baseId||o.id)===t).sort((o,s)=>n(o.id)-n(s.id))}getAllByBaseIdOnActiveDesktop(t){return this.getAllByBaseId(t).filter(n=>(n.config.desktopId||this._activeDesktopId)===this._activeDesktopId)}getAll(){return[...this._stack]}findByIframeSource(t){if(t)return this._stack.find(n=>n.iframe!==null&&n.iframe.contentWindow===t)}getFocused(){return this._stack.length>0?this._stack[this._stack.length-1]:void 0}isActive(t){const n=this.getById(t);if(!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)return!1;const s=this.getFocused();return!!s&&s.id===t}isActiveByBaseId(t){const n=this.getFocused();return!n||n.state==="minimized"||(n.config.desktopId||this._activeDesktopId)!==this._activeDesktopId?!1:(n.config.baseId||n.id)===t}getDesktops(){return qI(this)}getActiveDesktop(){return Ep(this)}getActiveDesktopId(){return YI(this)}createDesktop(t){return _p(this,t)}switchDesktop(t,n){Ip(this,t,n)}closeDesktop(t){Ap(this,t)}renameDesktop(t,n){return kp(this,t,n)}moveWindowToDesktop(t,n){return XI(this,t,n)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=J(v.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(c=>!n.has(c.id));A(v.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=J(v.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(c=>!i.includes(c));let a=0;const l=[];for(const c of i.slice())try{c.close(),c._isDestroyed||c._closePending?a++:l.push(c)}catch(d){l.push(c),typeof console<"u"&&console.error("[openstation] closeAll: window.close() threw for",c.id,d)}return A(v.WINDOWS_AFTER_CLOSE_ALL,{closed:a,skipped:r,refused:l}),a}minimizeAll(){const t=[];for(const n of this._stack.slice())if((n.config.desktopId||this._activeDesktopId)===this._activeDesktopId&&n.state!=="minimized")try{n.minimize(),t.push(n)}catch(s){typeof console<"u"&&console.error("[openstation] minimizeAll: window.minimize() threw for",n.id,s)}return t}restoreFrom(t){if(!Array.isArray(t))return;const n=new Set(this._stack);for(const o of t)if(!(!n.has(o)||(o.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)&&o.state==="minimized")try{o.restore()}catch(i){typeof console<"u"&&console.error("[openstation] restoreFrom: window.restore() threw for",o.id,i)}}toggleShowDesktop(){const t=this._stack.filter(o=>(o.config.desktopId||this._activeDesktopId)===this._activeDesktopId);if(t.length===0)return!1;if(t.every(o=>o.state==="minimized")){for(const o of t)try{o.restore()}catch{}return!1}return this.minimizeAll(),!0}cascade(){QI(this)}tile(){Cp(this)}columns(){nA(this)}focusLayout(){oA(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){iA(this,t)}getSnapConfig(){return rA(this)}enterOverview(){if(Vt()){document.dispatchEvent(new CustomEvent("os-mobile-open-switcher"));return}zI(this)}exitOverview(t,n=!1){Ot(this,t,n)}destroy(){this._unsubscribeWorkArea(),this.desktopResizeObserver?.disconnect(),this._reflowRestoreTimer!==null&&(window.clearTimeout(this._reflowRestoreTimer),this._reflowRestoreTimer=null),this._overviewActive&&Ot(this),this.discardPrewarmed(),jI(this),o_()}getVisibleRects(){return this._stack.map(t=>{const n=t.getSnapshot();return{windowId:t.id,rect:{x:n.x,y:n.y,width:n.width,height:n.height},state:n.state,element:t.element}})}sanitizeParams(t){const n={};for(const[o,s]of Object.entries(t))(typeof s=="string"||typeof s=="boolean"||typeof s=="number"&&Number.isFinite(s))&&(n[o]=s);return Object.keys(n).length>0?n:void 0}snapshot(){const t=this.getFocused(),o=this._stack.filter(a=>!a.config.ephemeral&&!a.config.parentWindowId).map(a=>{const l=a.getSnapshot(),c=a.getExternalTabsSnapshot(),d=!!a.config.native,u=a.config.params,f=d&&u?this.sanitizeParams(u):null;return{id:a.id,baseId:a.config.baseId||a.id,desktopId:a.config.desktopId||this._activeDesktopId,...d?{native:!0}:{},...f?{params:f}:{},url:d?a.config.url||`#${a.id}`:a.getCurrentUrl(),title:a.config.title,icon:a.config.icon,state:l.state,x:l.x,y:l.y,width:l.width,height:l.height,...c.length>0?{externalTabs:c}:{},...a._gridSpan?{gridSpan:{...a._gridSpan}}:{}}}),s=t&&!t.config.ephemeral&&!t.config.parentWindowId?t.id:"",i={windows:o,desktops:this.getDesktops(),activeDesktop:this._activeDesktopId,focused:s,updated:Date.now()},r=J(v.SESSION_SNAPSHOT,i);return r&&Array.isArray(r.windows)?r:i}seedWindowRestoreState(t,n={}){this._pendingRestoreState=new Map(Object.entries(t)),this._reservedRestoreIds=n.reserveIds?new Set(Object.keys(t)):new Set}discardWindowRestoreState(t){if(t){this._pendingRestoreState.delete(t),this._reservedRestoreIds.delete(t);return}this._pendingRestoreState.clear(),this._reservedRestoreIds.clear()}seedDesktops(t,n){JI(this,t,n)}}function lA(e){const t=e.getActiveDesktopId(),n=Array.from(e._desktop.children);return e.getAll().filter(o=>(o.config.desktopId||t)===t).sort((o,s)=>n.indexOf(o.element)-n.indexOf(s.element))}function $p(e,t){if(e._overviewActive)return;const n=lA(e);if(n.length<2)return;const o=e.getFocused(),r=((o?n.indexOf(o):-1)+(t==="next"?1:-1)+n.length)%n.length,a=n[r];a.state==="minimized"?a.restore():e.focus(a)}let Up=!1;function oc(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;return Bp(t)}function Bp(e){if(!e)return!1;if(e instanceof HTMLIFrameElement||e instanceof HTMLTextAreaElement)return!0;if(e instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(e.type);if(e instanceof HTMLElement&&e.isContentEditable===!0)return!0;const t=e.getAttribute("contenteditable");return t!==null&&t!=="false"}function dA(e){if(Up)return;Up=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(oc(document)||(n.preventDefault(),$p(e,n.shiftKey?"prev":"next")))},!0);const t=window.location.origin;window.addEventListener("message",n=>{if(n.origin!==t)return;const o=n.data;!o||o.type!=="os-window-switch"||$p(e,o.direction==="prev"?"prev":"next")})}let qo=null;function uA(e){if(e.ctrlKey||e.metaKey||e.altKey||e.key.length!==1)return!1;const t=e.composedPath(),n=t.length>0?t[0]:null;return!(n instanceof Element)||!(n.getRootNode()instanceof ShadowRoot)?!1:Bp(n)}function fA(e=window){if(qo)return qo;const t=o=>{uA(o)&&o.stopPropagation()};e.addEventListener("keydown",t,!0);const n=()=>{e.removeEventListener("keydown",t,!0),qo===n&&(qo=null)};return qo=n,n}function Fp(e,t){const n=e.getDesktops();if(n.length<2)return!1;const o=e.getActiveDesktopId(),s=n.findIndex(a=>a.id===o);if(s===-1)return!1;const r=(s+(t==="next"?1:-1)+n.length)%n.length;return r===s?!1:(e.switchDesktop(n[r].id,{direction:t}),!0)}function Hp(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(l=>l.id===e.getActiveDesktopId());if(i===-1)return!1;const a=(i+(t==="next"?1:-1)+o)%o;return a===i?!1:a===s?(e._overviewAddTileFocused=!0,jo(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[a].id,{direction:t}),!0)}function pA(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function hA(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Gp(e){return e._overviewActive?(e.exitOverview(),!0):!1}function mA(){return document.querySelector("os-modal[open], os-confirm-dialog[open]")!==null}function gA(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function wA(e){return gA(e)?(e.toggleShowDesktop(),!0):!1}let zp=!1;function yA(e){zp||(zp=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||Vt()||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||oc(document)||mA())return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Hp(e,"prev"):Fp(e,"prev");break;case"ArrowRight":n=e._overviewActive?Hp(e,"next"):Fp(e,"next");break;case"ArrowUp":n=Gp(e)||wA(e)||pA(e);break;case"ArrowDown":n=Gp(e)||hA(e);break}n&&t.preventDefault()},!0))}async function Qt(e){return await ca(la()),new Promise(t=>{const n=document.createElement("os-confirm-dialog");n.setAttribute("open",""),e.title&&n.setAttribute("title",e.title),n.setAttribute("message",e.message),e.confirmLabel&&n.setAttribute("confirm-label",e.confirmLabel),e.cancelLabel&&n.setAttribute("cancel-label",e.cancelLabel),e.danger&&n.setAttribute("danger",""),e.hideCancel&&n.setAttribute("hide-cancel",""),e.dismissable&&n.setAttribute("dismissable",""),e.rememberLabel&&n.setAttribute("remember-label",e.rememberLabel);const o=s=>{n.remove(),t(s)};n.addEventListener("os-confirm",s=>{e.onRemember?.(s.detail?.remember===!0),o(!0)}),n.addEventListener("os-cancel",()=>o(!1)),document.body.appendChild(n)})}const vA="os-window-close-all";function bA(e){return e.code!=="KeyW"||e.getModifierState?.("AltGraph")||!(e.ctrlKey||e.metaKey)?!1:e.altKey&&!e.shiftKey}let sc=!1;function jp(e){const t=e.getActiveDesktopId();return e.getAll().filter(n=>(n.config.desktopId||t)===t)}async function Vp(e,t){if(sc)return 0;const n=jp(e);if(n.length===0)return 0;if(t&&!t.shouldAsk())return Kp(e);const o=t?{rememberLabel:b("Don't ask again"),onRemember:i=>{i&&t.setAsk(!1)}}:{};sc=!0;let s=!1;try{s=await Qt({title:b("Close all windows?"),message:le(Kt("%d open window on this desktop will be closed.","%d open windows on this desktop will be closed.",n.length),n.length),confirmLabel:b("Close all"),danger:!0,...o})}finally{sc=!1}return s?Kp(e):0}const EA=700,_A=50;function SA(e,t){const n=()=>t.filter(o=>!e.getById(o)).length;return new Promise(o=>{const s=Date.now()+EA,i=()=>{const r=n();if(r===t.length||Date.now()>=s){o(r);return}setTimeout(i,_A)};i()})}async function Kp(e){e._overviewActive&&e.exitOverview();const t=jp(e).map(s=>s.id),n=e.getAll().map(s=>s.id).filter(s=>!t.includes(s));e.closeAll({exceptIds:n});const o=await SA(e,t);return o>0&&ue({message:le(Kt("Closed %d window.","Closed %d windows.",o),o)}),o}let qp=!1;function kA(e,t){if(qp)return;qp=!0,document.addEventListener("keydown",o=>{bA(o)&&(o.preventDefault(),o.stopImmediatePropagation(),Vp(e,t))},!0);const n=window.location.origin;window.addEventListener("message",o=>{if(o.origin!==n)return;const s=o.data;!s||s.type!==vA||Vp(e,t)})}const Yp=gf;let Xp=!1;function Zp(e){return e?document.getElementById(`wp-window-${e}`):null}function IA(){Xp||(Xp=!0,AA())}function AA(){ee(v.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=Zp(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove($a),n.classList.add(Bo),Ak(n),$f(t),vk(t))}),ee(v.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=Zp(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");if(!n)return;t.removeAttribute("aria-busy");const o=!!n.querySelector(`:scope .${$o}`)?.classList.contains(gi);if(n.classList.remove(Bo),n.removeAttribute(Ua),!o){Pf(t),Cf(t);return}n.classList.add($a);const s=yi(n);Cf(t),window.setTimeout(()=>{yi(n)===s&&(n.classList.contains(Bo)||Pf(t))},Yp),window.setTimeout(()=>{yi(n)===s&&(n.classList.contains(Bo)||n.classList.remove($a))},Yp+ik)}),ee(v.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>Jp())})}function Jp(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),$f(n))})}const CA="desktop_mode_classic";function LA(e){return e.pathname.endsWith("/index.php")&&!e.searchParams.has("page")&&!e.searchParams.has(CA)}const ic=ae("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function TA(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=ic.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>Qp(e.id)}function Qp(e){const t=ic.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function NA(){return ic.state.entries.slice()}const OA=32,DA=64,RA=/^[a-z0-9_/-]+$/,ye=ae("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function en(e){return`${e.type}:${e.id}`}function eh(e){return e.root?en(e.root):en(e)}function th(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&RA.test(o.trim().toLowerCase());return Yt(e,[{field:"type",valid:o=>n(o.type),message:"must match /^[a-z0-9_/-]+$/ — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-type"},{field:"id",valid:o=>t(o.id),message:"must be a finite number or non-empty string"},{field:"root",valid:o=>o.root===void 0||!!o.root&&typeof o.root=="object"&&n(o.root.type)&&t(o.root.id),message:"when present, must be { type, id } with the same shapes as the ref itself"},{field:"related",valid:o=>o.related===void 0||Array.isArray(o.related)&&o.related.every(s=>!!s&&typeof s=="object"&&typeof s.id=="string"&&s.id.trim()!==""&&typeof s.group=="string"&&s.group.trim()!==""&&typeof s.label=="string"&&s.label.trim()!==""&&typeof s.url=="string"&&s.url.trim()!==""&&(s.groupLabel===void 0||typeof s.groupLabel=="string")&&(s.icon===void 0||typeof s.icon=="string")&&(s.count===void 0||typeof s.count=="number"&&Number.isFinite(s.count))),message:"when present, must be an array of { id, group, label, url, groupLabel?, icon?, count? } entries with non-empty strings"},{field:"links",valid:o=>o.links===void 0||Array.isArray(o.links)&&o.links.every(s=>!!s&&typeof s=="object"&&n(s.type)&&t(s.id)&&(s.rel===void 0||s.rel==="references"||s.rel==="child")),message:"when present, must be an array of { type, id, rel?: 'references'|'child' } entries"},{field:"revisionCount",valid:o=>o.revisionCount===void 0||typeof o.revisionCount=="number"&&Number.isFinite(o.revisionCount),message:"when present, must be a finite number"}])}function nh(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function xA(e,t){const n={type:e.type.trim().toLowerCase(),id:e.id,source:t};e.root&&(n.root={type:e.root.type.trim().toLowerCase(),id:e.root.id}),Array.isArray(e.links)&&e.links.length>0&&(n.links=e.links.slice(0,OA).map(i=>{const r={type:i.type.trim().toLowerCase(),id:i.id};return i.rel==="child"&&(r.rel="child"),r})),typeof e.label=="string"&&e.label!==""&&(n.label=e.label);const o=nh(e.previewUrl);o&&(n.previewUrl=o);const s=nh(e.revisionsUrl);return s&&(n.revisionsUrl=s,typeof e.revisionCount=="number"&&Number.isFinite(e.revisionCount)&&(n.revisionCount=Math.max(0,Math.trunc(e.revisionCount)))),Array.isArray(e.related)&&e.related.length>0&&(n.related=e.related.slice(0,DA).map(i=>{const r={id:i.id,group:i.group,label:i.label,url:i.url};return typeof i.groupLabel=="string"&&i.groupLabel!==""&&(r.groupLabel=i.groupLabel),typeof i.icon=="string"&&i.icon!==""&&(r.icon=i.icon),typeof i.count=="number"&&(r.count=i.count),r})),n}function oh(e){return!e||!e.related?"":e.related.map(t=>`${t.id}\0${t.group}\0${t.label}\0${t.url}\0${t.groupLabel??""}\0${t.icon??""}\0${t.count??""}`).join("|")}function rc(e){return e?[en(e),eh(e),...(e.links??[]).map(t=>en(t)+(t.rel==="child"?"!child":""))].join("|"):""}function Ni(e,t,n={}){const o=n.source??"api";if(typeof e!="string"||e===""){Oe("WindowContentRef",["windowId (must be a non-empty string)"],t);return}let s=null;if(t!=null){const a=th(t);if(a.length>0){o==="api"&&Oe("WindowContentRef",a,t),Cu("WindowContentRef",a,t);return}s=xA(t,o)}if(s=J(v.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||th(s).length>0)){Cu("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=ye.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&rc(s)===rc(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&s.revisionsUrl===i.revisionsUrl&&s.revisionCount===i.revisionCount&&oh(s)===oh(i))return;s===null?ye.state.contentByWindow.delete(e):ye.state.contentByWindow.set(e,s);const r={windowId:e,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("os-window-content-changed",{detail:r})),A(v.WINDOW_CONTENT_CHANGED,r),UA(),PA()}function ze(e){return ye.state.contentByWindow.get(e)}function ac(){const e=new Map;for(const[s,i]of ye.state.contentByWindow){const r=eh(i);let a=e.get(r);a||(a={key:r,root:i.root?{...i.root}:{type:i.type,id:i.id},rootWindowIds:[],children:[]},e.set(r,a)),i.root?a.children.push({windowId:s,content:i}):a.rootWindowIds.push(s)}const t=ye.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=J(v.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[openstation] `os.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function sh(e){return ac().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function MA(e){const t=new Set,n=sh(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of ih())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function ih(){const e=ye.state.focusSeq,t=new Map;for(const[a,l]of ye.state.contentByWindow){const c=en(l),d=t.get(c);(!d||(e.get(a)??0)>(e.get(d)??0))&&t.set(c,a)}const n=new Map,o=(a,l)=>`${a}→${l}`;for(const[a,l]of ye.state.contentByWindow){if(l.root){const c=t.get(en(l.root));c&&c!==a&&n.set(o(a,c),{fromWindowId:a,toWindowId:c,kind:"child-root",bidirectional:!1})}for(const c of l.links??[]){const d=t.get(en(c));if(!d||d===a)continue;if(c.rel==="child"){const f=o(d,a),p=n.get(f);(!p||p.kind!=="child-root")&&n.set(f,{fromWindowId:d,toWindowId:a,kind:"child-root",bidirectional:!1});continue}const u=o(a,d);n.has(u)||n.set(u,{fromWindowId:a,toWindowId:d,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[a,l]of n){if(i.has(a))continue;const c=o(l.toWindowId,l.fromWindowId),d=n.get(c);if(d&&l.kind==="reference"){if(d.kind==="reference"){i.add(c),s.push({...l,bidirectional:!0});continue}continue}s.push(l)}const r=J(v.WINDOW_LINK_EDGES,s);return Array.isArray(r)?r:(typeof console<"u"&&console.warn("[openstation] `os.window-links.edges` filter returned a non-array; falling back to derived edges."),s)}function WA(e){return ye.state.listeners.add(e),()=>{ye.state.listeners.delete(e)}}function PA(){for(const e of Array.from(ye.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function $A(){return Array.from(ye.state.contentByWindow).map(([e,t])=>`${e}=${rc(t)}`).sort().join(";")}function UA(){const e=$A();if(e===ye.state.lastGroupsSignature)return;ye.state.lastGroupsSignature=e;const n={groups:ac()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),A(v.WINDOW_LINK_GROUPS_CHANGED,n)}const BA={get:ze,set:(e,t)=>Ni(e,t,{source:"api"}),groups:ac,edges:ih,groupOf:sh,related:MA,subscribe:WA};function FA({manager:e}){ye.state.manager=e,!ye.state.started&&(ye.state.started=!0,ee(v.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=ye.state.manager?.getById(t.windowId)?.config?.content;o&&Ni(t.windowId,o,{source:"config"})}),ee(v.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(ye.state.focusSeq.delete(t.windowId),Ni(t.windowId,null,{source:"config"}))}),ee(v.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(ye.state.seq+=1,ye.state.focusSeq.set(t.windowId,ye.state.seq))}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t.data;if(!n||n.type!=="os-content-identity")return;const o=ye.state.manager?.findByIframeSource?.(t.source);o&&Ni(o.id,n.identity??null,{source:"bridge"})}))}const HA=ae("desktop-mode/admin-link-deps",()=>({deps:null}));function GA(e){HA.state.deps=e}const rh=ae("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),Bn=rh.state.seed,zA=rh.state.listeners;function Fn(e){Oe("Wallpaper",Yt(e,lh),e);const t=Bn.findIndex(n=>n.id===e.id);t>=0?Bn[t]=e:Bn.push(e),ch()}function ah(e){const t=Bn.findIndex(n=>n.id===e);t>=0&&(Bn.splice(t,1),ch())}function ch(){const e=Array.from(zA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function cc(){const e=Bn.slice(),t=J(v.WALLPAPERS,e);return Array.isArray(t)?t.filter(jA):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function Yo(e){return cc().find(t=>t.id===e)}const lh=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"preview",message:"missing or not a non-empty string",valid:e=>typeof e.preview=="string"&&e.preview!==""},{field:"type",message:'must be "css" or "canvas"',valid:e=>e.type==="css"||e.type==="canvas"},{field:"value/resolveValue/mount",message:"css types need `value` or `resolveValue`; canvas types need `mount`",valid:e=>e.type==="css"?typeof e.value=="string"||typeof e.resolveValue=="function":e.type==="canvas"?typeof e.mount=="function":!0}];function jA(e){return Yt(e,lh).length===0}const dh=ae("desktop-mode/wallpaper-settings",()=>({values:{}}));function VA(e){return{...dh.state.values[e]??{}}}function KA(e){const t=dh.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}const qA=20,lc=1,Oi=24,Hn="os-dock--revealed",Xo="data-os-dock-behavior",YA="os-dock",uh="os-side-dock",Di="os-dock-vt",XA=".os-constellation, .os-dock-peek";function ZA(e){const t=e.getAttribute("data-os-dock-placement");if(t==="left"||t==="right"){const n=getComputedStyle(e).direction==="rtl";return t==="left"!==n?"left":"right"}return"bottom"}function fh(e){return e.getAttribute(Xo)==="dynamic"}function JA(e,t,n,o,s,i=qA){switch(e){case"bottom":return n>=s-i;case"left":return t<=i;case"right":return t>=o-i}return!1}function QA(e,t,n,o){const s=e.getBoundingClientRect();if(s.width<=0||s.height<=0)return!1;let i=s.top-Oi;const r=s.bottom+Oi;let a=s.left-Oi,l=s.right+Oi;switch(t){case"bottom":i=s.top-s.height*lc;break;case"left":l=s.right+s.width*lc;break;case"right":a=s.left-s.width*lc;break}return n>=a&&n<=l&&o>=i&&o<=r}function e0(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function t0(e){let t=!1,n=null,o=!1;const s=new Map,i=new Map;let r=!1,a=!1;const l=()=>Array.from(e.shellBody.querySelectorAll(".os-dock")),c=S=>{const R=e.getBehaviors(),W=S.id===uh?R.sidebar:R.dock;S.getAttribute(Xo)!==W&&S.setAttribute(Xo,W)},d=S=>{const R=S.ownerDocument.activeElement;if(R&&S.contains(R))return!0;if(!n)return!1;if(o)return S.classList.contains(Hn);const W=ZA(S);return JA(W,n.x,n.y,window.innerWidth,window.innerHeight)||S.classList.contains(Hn)&&QA(S,W,n.x,n.y)},u=(S,R)=>{if(S.classList.contains(Hn)===R){i.delete(S);return}if(!R&&r){a=!0;return}if(s.has(S)){i.set(S,R);return}const W=()=>{S.classList.toggle(Hn,R)},U=document;if(typeof U.startViewTransition!="function"||e0()){W();return}const F=`os-dock-${S.id||"rail"}`;S.style.setProperty("view-transition-name",F),document.documentElement.classList.add(Di);let K;try{K=U.startViewTransition(W)}catch{S.style.removeProperty("view-transition-name"),document.documentElement.classList.remove(Di),W();return}const Q=K.finished&&typeof K.finished.then=="function"?K.finished:Promise.resolve(),Z=()=>{S.style.removeProperty("view-transition-name"),s.delete(S),s.size===0&&document.documentElement.classList.remove(Di);const C=i.get(S);i.delete(S),!t&&C!==void 0&&u(S,C)};s.set(S,Q.then(Z,Z))},f=()=>{if(!t)for(const S of l()){if(c(S),!fh(S)){S.classList.remove(Hn);continue}u(S,d(S))}},p=S=>{if(t||!l().some(fh))return;n={x:S.clientX,y:S.clientY};const R=S.target;o=R instanceof Element&&R.closest(XA)!==null,f()};let g=0;const h=()=>{g||(g=requestAnimationFrame(()=>{g=0,f()}))},m=()=>f(),_=()=>{r=!0},I=()=>{r=!1,a&&(a=!1,f())};document.addEventListener("pointerdown",_,{capture:!0,passive:!0}),document.addEventListener("pointerup",I,{capture:!0,passive:!0}),document.addEventListener("pointercancel",I,{capture:!0,passive:!0}),document.addEventListener("pointermove",p,{passive:!0}),document.addEventListener("pointerdown",p,{passive:!0}),document.addEventListener("focusin",h),document.addEventListener("focusout",h),document.addEventListener("os-layout-changed",m);let O=null;typeof MutationObserver<"u"&&(O=new MutationObserver(f),O.observe(e.shellBody,{childList:!0})),f();const $={refresh:f,destroy:()=>{t=!0,g&&(cancelAnimationFrame(g),g=0),O?.disconnect(),document.removeEventListener("pointerdown",_,{capture:!0}),document.removeEventListener("pointerup",I,{capture:!0}),document.removeEventListener("pointercancel",I,{capture:!0}),document.removeEventListener("pointermove",p),document.removeEventListener("pointerdown",p),document.removeEventListener("focusin",h),document.removeEventListener("focusout",h),document.removeEventListener("os-layout-changed",m);for(const S of l())S.classList.remove(Hn),S.style.removeProperty("view-transition-name");i.clear(),document.documentElement.classList.remove(Di),Ri===$&&(Ri=null)}};return Ri=$,$}let Ri=null;function n0(){Ri?.refresh()}function ph(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const hh=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","linerWidth","linerColor","glow","glowBlur","eyeColor","eyeScale"],mh=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function dc(){return{appearance:{},physics:{}}}function o0(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function xi(e,t){const n={};if(!e||typeof e!="object"||Array.isArray(e))return n;const o=e;for(const s of t){const i=o[s];i!==void 0&&o0(i)&&Object.assign(n,{[s]:i})}return n}function gh(e){if(!e||typeof e!="object"||Array.isArray(e))return dc();const t=e;return{appearance:xi(t.appearance,hh),physics:xi(t.physics,mh)}}function s0(e){return{appearance:xi(e,hh),physics:xi(e,mh)}}function i0(){const e=r0();if(e){const t=fc(e,uc());return pc(t),f0(t),t}try{const t=window.localStorage.getItem(ef);if(t)return fc(JSON.parse(t),uc())}catch{}return uc()}function uc(){const e=Eh();return e.wallpaper=ka(),e}function r0(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}const je=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Se=(e,t)=>typeof e=="boolean"?e:t,tn=e=>(t,n)=>e.some(o=>o.id===t)?t:n,Gn=e=>(t,n)=>typeof t=="string"&&e.test(t)?t:n,Mi=/^[a-z0-9_/-]+$/,wh={wallpaper:(e,t)=>typeof e=="string"&&e!==""?e:t,accent:(e,t)=>e===nf||li().some(n=>n.id===e)?e:t,customAccent:Gn(/^#[0-9a-fA-F]{6}$/),dockSize:tn(Ia),windowRadius:tn(Aa),adminBarMode:tn(di),desktopLayout:tn(lS),dockPlacement:tn(cS),dockBehavior:tn(ui),sideDockBehavior:tn(ui),dockRailRenderer:Gn(/^[a-z0-9_-]+$/),desktopTheme:Gn(/^[a-z0-9_-]*$/),appliedThemeRecommendations:(e,t)=>Array.isArray(e)?Array.from(new Set(e.filter(n=>typeof n=="string"&&/^[a-z0-9_-]+$/.test(n)))).slice(-64):t.slice(),unfocusEffect:Gn(Mi),windowReveal:Gn(Mi),windowRevealDuration:(e,t)=>typeof e!="number"||!Number.isFinite(e)?t:e>0?Math.min(4e3,Math.max(80,Math.round(e))):0,windowLinkRenderer:Gn(Mi),windowLinkVisibility:(e,t)=>e==="focus"||e==="always"||e==="off"?e:t,windowLinksEnabled:Se,windowLinkRaiseOnFocus:Se,windowLinkHighlight:Se,customGradient:(e,t)=>je(e)?w0(e):{...t},customImage:(e,t)=>e===null||je(e)?y0(e):t,wallpaperSettings:(e,t)=>je(e)?c0(e):t,libraryHdOnly:Se,ai:(e,t)=>g0(e,t),heartbeatRate:(e,t)=>e===15||e===30||e===45||e===60?e:t,nativePostsEnabled:Se,nativePostsHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativePagesEnabled:Se,nativePagesHiddenColumns:(e,t)=>Array.isArray(e)?e.filter(n=>typeof n=="string"&&n!=="").slice(0,32):t.slice(),nativeUsersEnabled:Se,nativePluginsEnabled:Se,nativeCommentsEnabled:Se,stationHomeEnabled:Se,adminAssetCacheEnabled:Se,windowPrewarmEnabled:Se,showDesktopOnWallpaperClick:Se,confirmCloseAllWindows:Se,mioEnabled:Se,mioApiEnabled:Se,mioShowOnWallpaper:Se,mioStyle:(e,t)=>je(e)?gh(e):t,showPostStatusRibbons:Se,developerModeEnabled:Se,foldersSharingEnabled:Se,navPlacement:(e,t)=>je(e)?l0(e):t,navOrder:(e,t)=>Array.isArray(e)?vh(e):t,mobileLayout:(e,t)=>e==="auto"||e==="desktop"||e==="mobile"?e:t,mobileTabs:(e,t)=>Array.isArray(e)?vh(e).slice(0,3):t,dockPromotedPositions:(e,t)=>je(e)?d0(e):t},yh=Object.keys(wh);function fc(e,t){const n=on(t),o=e,s=wh;for(const i of yh)i in o&&(n[i]=s[i](o[i],n[i]));return typeof o.mioEnabled=="boolean"?n.mioEnabled=o.mioEnabled:typeof o.mioApiEnabled=="boolean"&&(n.mioEnabled=o.mioApiEnabled),n.mioApiEnabled=n.mioEnabled,n}const a0=new Set(["wallpaper","accent","customAccent","customGradient","customImage","wallpaperSettings","dockSize","windowRadius","adminBarMode","desktopLayout","dockPlacement","dockBehavior","sideDockBehavior","dockRailRenderer","desktopTheme"]);function c0(e){if(!je(e))return{};const t={};let n=0;for(const[o,s]of Object.entries(e)){if(n>=64)break;if(o===""||!Mi.test(o)||!je(s))continue;const i={};let r=0;for(const[a,l]of Object.entries(s)){if(r>=32)break;if(!(a===""||!/^[a-zA-Z0-9_-]+$/.test(a))){if(typeof l=="boolean")i[a]=l;else if(typeof l=="number"&&Number.isFinite(l))i[a]=l;else if(typeof l=="string")i[a]=l.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function l0(e){const t=["both","rail","desktop","hidden"],n={};let o=0;for(const[s,i]of Object.entries(e)){if(o>=256)break;s===""||typeof i!="string"||!t.includes(i)||(n[s]=i,o++)}return n}function vh(e){const t=[],n=new Set;for(const o of e)if(!(typeof o!="string"||o===""||n.has(o))&&(n.add(o),t.push(o),t.length>=256))break;return t}function d0(e){const t={};let n=0;const o=1e5;for(const[s,i]of Object.entries(e)){if(n>=256)break;if(s===""||!je(i))continue;const r=i;typeof r.x!="number"||typeof r.y!="number"||!Number.isFinite(r.x)||!Number.isFinite(r.y)||Math.abs(r.x)>o||Math.abs(r.y)>o||(t[s]={x:r.x,y:r.y},n++)}return t}let Wi=null;const u0=250;let nn=null;function f0(e){nn=on(e)}function on(e){return{...e,customGradient:{...e.customGradient},customImage:e.customImage?{...e.customImage}:null,wallpaperSettings:Object.fromEntries(Object.entries(e.wallpaperSettings).map(([t,n])=>[t,{...n}])),ai:{...e.ai},mioStyle:{appearance:{...e.mioStyle.appearance},physics:{...e.mioStyle.physics}},appliedThemeRecommendations:e.appliedThemeRecommendations.slice(),nativePostsHiddenColumns:e.nativePostsHiddenColumns.slice(),nativePagesHiddenColumns:e.nativePagesHiddenColumns.slice(),navPlacement:{...e.navPlacement},navOrder:e.navOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function p0(e,t={}){pc(e),h0(e,t.windowId)}function pc(e){try{window.localStorage.setItem(ef,JSON.stringify(e))}catch{}}function h0(e,t){Wi!==null&&clearTimeout(Wi),t&&(hc=t),Dt("pending"),Wi=setTimeout(()=>{Wi=null;const n=hc;hc=null,bh(e,n)},u0)}let hc=null;function m0(e){if(!nn)return{...e};const t=nn,n={};let o=!1;for(const s of Object.keys(e))JSON.stringify(e[s])!==JSON.stringify(t[s])&&(Object.assign(n,{[s]:e[s]}),o=!0);return o?n:null}let mc=!1,gc=null;function bh(e,t){if(mc){gc={state:e,windowId:t},Dt("pending");return}const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Dt("saved",void 0,void 0,e);return}const i=m0(e);if(!i){Dt("saved",void 0,void 0,e);return}Dt("saving"),mc=!0;const r=on(e),a=t||Ct;Ae(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:i})},{windowId:a}).then(async l=>{if(!l.ok)throw await Nn(l);nn=r,Dt("saved",void 0,void 0,r)}).catch(l=>{Pi=!0,nn?(pc(nn),Dt("failed",l instanceof Error?l.message:String(l),on(nn))):Dt("failed",l instanceof Error?l.message:String(l))}).finally(()=>{mc=!1;const l=gc;if(gc=null,l&&Pi){Pi=!1;return}Pi=!1,l&&bh(l.state,l.windowId)})}let Pi=!1;function Dt(e,t,n,o){const s={phase:e};o&&(s.savedSettings=on(o)),t&&(s.error=t),n&&(s.rolledBackTo=n),document.dispatchEvent(new CustomEvent("os-settings-save-lifecycle",{detail:s}))}function Eh(){return on(xn)}function g0(e,t=xn.ai){if(!je(e))return{...t};const{enabled:n}=e;return{enabled:typeof n=="boolean"?n:t.enabled}}function w0(e){if(!je(e))return{...xn.customGradient};const{from:t,to:n,angle:o}=e;return{from:ph(t)?t:xn.customGradient.from,to:ph(n)?n:xn.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:xn.customGradient.angle}}function y0(e){if(!je(e))return null;const{id:t,url:n}=e;return typeof t!="number"||!Number.isFinite(t)||t<=0||typeof n!="string"||!/^https?:\/\//i.test(n)?null:{id:t,url:n}}function wc(e){if(!e)return 214;let t=5381;for(let n=0;n<e.length;n++)t=Math.imul(t,33)+e.charCodeAt(n);return(t%360+360)%360}function v0(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function $i(e,t,n){if(!v0(t))return!1;const o=`url("${t}") center / contain no-repeat`;return e.style.backgroundImage="none",e.style.backgroundColor=n,e.style.setProperty("-webkit-mask",o),e.style.setProperty("mask",o),!0}const b0="data-os-constellation";function E0(){return document.body.hasAttribute(b0)}const _h="os-item-menu-opening",_0=180,S0=220,Sh=32;function kh(e){const{tile:t}=e;let n=null,o=null,s=null,i=!1,r=null;const a=()=>{o!==null&&(window.clearTimeout(o),o=null)},l=()=>{s!==null&&(window.clearTimeout(s),s=null)},c=()=>{a(),l(),t.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),r?.clear(),r=null,e.suppressTooltip(!1)},d=h=>{h.pointerType==="mouse"&&(E0()&&(t.dataset.menuSlug||t.dataset.constellationId)||k0(e)&&(i=!0,l(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},_0))))},u=h=>{n&&h.relatedTarget instanceof Node&&n.contains(h.relatedTarget)||(i=!1,a(),f())},f=()=>{l(),s=window.setTimeout(()=>{s=null,!i&&c()},S0)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=I0(e,()=>c(),r),document.body.appendChild(n),D0(n),R0(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,l()}),n.addEventListener("pointerleave",h=>{h.relatedTarget instanceof Node&&t.contains(h.relatedTarget)||(i=!1,f())})},g=()=>c();return t.addEventListener("pointerenter",d),t.addEventListener("pointerleave",u),document.addEventListener(_h,g),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(_h,g),c()}}function k0(e){return e.getInstances().length>=1}function I0(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",le(b("%s — open windows"),e.item.title));const s=document.createElement("div");s.className="os-dock-peek__cards",o.appendChild(s);const i=e.getInstances();let r=0;for(const a of i){const l=A0(a,e,r++,t,n);s.appendChild(l)}if(e.enableGhost!==!1){const a=L0(e,r,t);s.appendChild(a)}return o}function Ih(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function A0(e,t,n,o,s){const i=document.createElement("button");i.type="button",i.setAttribute("role","menuitem"),i.className="os-dock-peek__card os-dock-peek__card--instance",i.style.setProperty("--peek-card-index",String(n)),i.style.setProperty("--peek-card-delay",`${n*Sh}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${wc(e.id||r)}`),i.style.setProperty("--peek-card-vt-name",`os-peek-card-${e.id}`);const a=document.createElement("span");a.className="os-dock-peek__card-titlebar";const l=document.createElement("span");l.className="os-dock-peek__card-dots",l.setAttribute("aria-hidden","true");for(let I=0;I<3;I++)l.appendChild(document.createElement("i"));a.appendChild(l);const c=document.createElement("span");c.className="os-dock-peek__card-icon",c.setAttribute("aria-hidden","true");const d=e.config.icon||t.item.icon;d.startsWith("dashicons-")?c.classList.add("dashicons",qE(d)):c.classList.add("dashicons","dashicons-admin-generic"),a.appendChild(c);const u=document.createElement("span");u.className="os-dock-peek__card-label",u.textContent=r,a.appendChild(u),i.appendChild(a);const f=document.createElement("span");f.className="os-dock-peek__card-body",f.setAttribute("aria-hidden","true");for(let I=0;I<3;I++){const O=document.createElement("span");O.className="os-dock-peek__card-line",f.appendChild(O)}const p={window:e,item:t.item},g=J(v.DOCK_PEEK_CARD_CONTENT,f,p);g!==f&&g.classList.add("os-dock-peek__card-body--custom"),i.appendChild(g),e.state==="minimized"&&(i.dataset.state="minimized");const h=()=>{s.delete(e.id),delete i.dataset.preview},m=I=>{if(h(),I.wasMinimized)e.minimize(),i.dataset.state="minimized";else if(I.previouslyFocusedId){const O=t.windowManager.getById(I.previouslyFocusedId);O&&t.windowManager.focus(O)}};return i.addEventListener("click",()=>{h(),C0(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const I=e.state==="minimized",O=t.windowManager.getFocused(),$=O&&O!==e?O.id:null;(I||$!==null)&&(s.set(e.id,{wasMinimized:I,previouslyFocusedId:$}),i.dataset.preview=""),I?Ih(e,i):O&&O!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const I=s.get(e.id);I&&m(I)}),J(v.DOCK_PEEK_CARD_ELEMENT,i,p)}function C0(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),Ih(t,n),e.windowManager.focus(t)};if(typeof s.startViewTransition!="function"){r();return}const a=t.element;n.style.setProperty("view-transition-name",i),a.style.setProperty("view-transition-name",i);const l=s.startViewTransition(r),c=()=>{n.style.removeProperty("view-transition-name"),a.style.removeProperty("view-transition-name")},d=l;d.finished&&typeof d.finished.then=="function"?d.finished.then(c,c):Promise.resolve().then(c)}function L0(e,t,n){const o=document.createElement("button");o.type="button",o.setAttribute("role","menuitem"),o.className="os-dock-peek__card os-dock-peek__card--ghost",o.style.setProperty("--peek-card-index",String(t)),o.style.setProperty("--peek-card-delay",`${t*Sh}ms`);const s=document.createElement("span");s.className="os-dock-peek__card-plus",s.setAttribute("aria-hidden","true"),s.textContent="+",o.appendChild(s);const i=document.createElement("span");return i.className="os-dock-peek__card-label",i.textContent=le(b("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{T0(e,n)}),o}function T0(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const N0=12,O0=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function D0(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of O0){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function R0(e,t,n){const o=t.getBoundingClientRect();e.dataset.orientation=n,n==="bottom"?(e.style.left=`${o.left+o.width/2}px`,e.style.top=`${o.top-12}px`):n==="right"?(e.style.top=`${o.top}px`,e.style.left=`${o.left-12}px`):(e.style.top=`${o.top}px`,e.style.left=`${o.right+12}px`),requestAnimationFrame(()=>x0(e))}function x0(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=N0;let r=0,a=0;n.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 zn(e){try{const t=new URL(e,window.location.origin);return t.origin===window.location.origin?!1:(window.open(t.toString(),"_blank","noopener,noreferrer"),!0)}catch{return!1}}function Ah(e){let t,n;try{const s=new URL(e,document.baseURI);t=s.origin,n=s.pathname}catch{return null}if(!n)return null;const o=document.querySelectorAll("script[src]");for(const s of Array.from(o))try{const i=new URL(s.src,document.baseURI);if(i.origin===t&&i.pathname===n)return s}catch{}return null}const Ch=new Map;function M0(e){const t=Ch.get(e);if(t)return t;let n=[];try{const o=new URL(e,document.baseURI);if(o.pathname.endsWith("/load-scripts.php")){const s=[];o.searchParams.forEach((i,r)=>{if(r!=="load"&&!r.startsWith("load["))return;const a=/(\d+)/.exec(r);s.push({order:a?Number(a[1]):s.length,value:i})}),s.sort((i,r)=>i.order-r.order),n=s.map(i=>i.value).join("").split(",").map(i=>i.trim()).filter(Boolean)}}catch{}return Ch.set(e,n),n}function W0(){const e=new Set,t=document.querySelectorAll('script[src*="load-scripts.php"]');for(const n of Array.from(t))for(const o of M0(n.src))e.add(o);return e}const P0=["-js","-js-before","-js-after","-js-extra","-js-translations"];function $0(e){return e?P0.some(t=>{const n=document.getElementById(e+t);return!!n&&n.tagName==="SCRIPT"}):!1}function yc(e){return e.url&&Ah(e.url)?!0:e.handle?W0().has(e.handle)||$0(e.handle):!1}const Ui=new Map,Lh=new Set;function pe(e,t){const n=Ui.get(e);if(n)return n;const o=t?.deps;if(o&&o.length>0){const i=a=>yc(a)?Promise.resolve():a.url?pe(a.url,{...a,deps:void 0}):(U0(a),Promise.resolve()),r=o.reduce((a,l)=>a.then(()=>i(l)),Promise.resolve(void 0)).then(()=>Th(e,t));return Ui.set(e,r),r}const s=Th(e,t);return Ui.set(e,s),s}function U0(e){if(e.handle){if(Lh.has(e.handle))return;Lh.add(e.handle)}for(const t of e.l10n??[])Rt(t);for(const t of e.before??[])Rt(t);for(const t of e.after??[])Rt(t)}function Th(e,t){return new Promise((n,o)=>{const s=`script[data-os-vendor="${B0(e)}"]`,i=document.querySelector(s);if(i){if(i.dataset.loaded==="1"){n();return}i.addEventListener("load",()=>n(),{once:!0}),i.addEventListener("error",()=>o(new Error(`Failed to load ${e}`)),{once:!0});return}const r=Ah(e);if(r){r.dataset.osVendor=e,r.dataset.loaded="1",n();return}if(yc({handle:t?.handle})){n();return}t?.translations&&Rt(t.translations);for(const l of t?.l10n??[])Rt(l);for(const l of t?.before??[])Rt(l);const a=document.createElement("script");a.src=e,a.async=!0,a.dataset.osVendor=e,a.addEventListener("load",()=>{a.dataset.loaded="1";for(const l of t?.after??[])Rt(l);n()},{once:!0}),a.addEventListener("error",()=>{Ui.delete(e),a.remove(),o(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(a)})}function Rt(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function Nh(e){Rt(e)}function B0(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let Oh=0;function Dh(){return window.openStationItemVisibilityMenu??null}function F0(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function Rh(e){const t=Dh();if(t){t.openItemVisibilityMenu(e);return}const n=F0();if(!n)return;const o=++Oh;pe(n).then(()=>{o===Oh&&Dh()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const H0={core:"rail",plugin:"rail",app:"desktop",control:"rail"};function G0(e,t){return e==="core"&&t==="classic"?"sidebar":"dock"}function xh(e){return e==="core"?"core":e==="control"?"controls":"apps"}function Mh(e,t){return e.locked?"rail":t[e.id]??e.defaultPlacement??H0[e.kind]}function Wh(e){return e==="rail"||e==="both"}function z0(e){return e==="desktop"||e==="both"}function j0(e,t,n){return Wh(e)?"rail":"hidden"}function Ph(e,t){if(t.length===0||e.length<=1)return e.slice();const n=new Map;for(const i of e)n.set(i.id,i);const o=[],s=new Set;for(const i of t){const r=n.get(i);r&&!s.has(i)&&(o.push(r),s.add(i))}for(const i of e)s.has(i.id)||o.push(i);return o}function V0(e,t){const n=new Set(t),o=t.slice(),s=[];for(const i of e){if(!n.has(i)){s.push(i);continue}const r=o.shift();r!==void 0&&s.push(r)}return s.push(...o),s}function $h(e){return e.map((t,n)=>({item:t,index:n})).sort((t,n)=>(t.item.order??0)-(n.item.order??0)||t.index-n.index).map(t=>t.item)}function Bi(){return window.wp?.os??null}function K0(){const e=Bi()?.getOsSettings?.();return{placement:e?.navPlacement??{},order:e?.navOrder??[]}}function q0(){return Bi()?.getNavItems?.()??[]}function Y0(e){const t=q0();return t.find(n=>n.id===e)??t.find(n=>n.entry?.id===e)??null}function X0(e){const t=Bi();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n={...t.getOsSettings().navPlacement??{}};let o=!1;for(const{item:s,placement:i}of e)s.locked||(n[s.id]=i,o=!0);o&&t.updateOsSettings({navPlacement:n})}function Z0(e,t,n){const o=Array.isArray(e)?e:[e],s=K0().placement,i=[];for(const r of o){const a=typeof r=="string"?Y0(r):r;a&&i.push({item:a,placement:j0(Mh(a,s))})}X0(i)}function J0(e){const t=Bi();if(!t?.getOsSettings||!t?.updateOsSettings)return;const n=t.getOsSettings().navOrder??[];t.updateOsSettings({navOrder:V0(n,e)})}const ct=["core","apps","controls"];function Uh(e){const{items:t,config:n,layout:o,openWindows:s}=e,i={core:[],apps:[],controls:[]},r=[],a=[],l=new Set,c=new Set,d=new Map,u=new Set;for(const p of t){u.add(p.id),p.windowId&&!d.has(p.windowId)&&d.set(p.windowId,p);const g=Mh(p,n.placement);if(Wh(g)){c.add(p.id);const h=xh(p.kind);G0(p.kind,o)==="sidebar"?r.push(p):i[h].push(p)}z0(g)&&a.push(p)}for(const p of t)for(const g of p.answersFor??[])d.has(g)||d.set(g,p);for(const p of s){const g=d.get(p.id);if(g){if(c.has(g.id)||l.has(g.id))continue;i.apps.push(g),l.add(g.id);continue}p.fromAdminUrl||l.has(p.id)||u.has(p.id)||(i.apps.push({id:p.id,kind:"app",title:p.title,icon:p.icon,windowId:p.id,transient:!0}),l.add(p.id))}const f=p=>Ph(Q0($h(p)),n.order);for(const p of ct)i[p]=f(i[p]);return{dock:i,sidebar:f(r),desktop:Ph($h(a),n.order),ephemeral:l}}function Q0(e){const t=e.filter(o=>o.kind==="core"&&o.tile),n=e.filter(o=>!t.includes(o));return t.length===0||n.length===0?e:[n[0],...t,...n.slice(1)]}const eC=["action","action2","_wpnonce","nonce","delete_all"];function tC(e){const t=e.slice(e.lastIndexOf("/")+1);return/-new\.php$/.test(t)}function nC(e){if(tC(e.pathname))return!0;for(const t of eC)if(e.searchParams.has(t))return!0;return!1}function Bh(e){return xh(e.navKind??"app")}const Ue=class Ue{constructor(t,n,o,s,i="left"){this.itemElements=new Map,this.systemItems=[],this.systemItemElements=new Map,this.zones={core:[],apps:[],controls:[]},this.badgeOverrides=new Map,this.artOverrides=new Map,this.attentionTimers=new Map,this.peekTeardowns=new Map,this.boundRefresh=()=>{},this.container=t,this.windowManager=n,this.items=o,this.adminUrl=s,this.orientation=i,this.rail=i==="bottom"?"taskbar":"dock",this.hooksNamespace=`desktop-mode/dock/${++Ue.instanceCounter}`,this.container.classList.add("os-dock--no-transition"),this.container.setAttribute("data-os-dock-placement",i),this.container.offsetWidth,this.container.classList.remove("os-dock--no-transition");const r=document.createElement("div");r.className="os-dock__scroll";const a=document.createElement("div");a.className="os-dock__pinned",t.appendChild(r),t.appendChild(a),this.itemHost=r,this.systemHost=a,this.tooltip=document.createElement("div"),this.tooltip.className="os-dock__tooltip",this.tooltip.setAttribute("role","tooltip"),i==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):i==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"),document.body.appendChild(this.tooltip),this.zones=this.zonesFromMenu(o,[]),this.render(),this.bindWindowEvents()}buildHookContextBase(){return{rail:this.rail,orientation:this.orientation,dockId:this.container.id,container:this.container}}setOrientation(t){this.orientation!==t&&(this.orientation=t,this.container.setAttribute("data-os-dock-placement",t),this.tooltip.classList.remove("os-dock__tooltip--above","os-dock__tooltip--before","os-dock__tooltip--after"),t==="bottom"?this.tooltip.classList.add("os-dock__tooltip--above"):t==="right"?this.tooltip.classList.add("os-dock__tooltip--before"):this.tooltip.classList.add("os-dock__tooltip--after"))}replaceItems(t){this.zones=this.zonesFromMenu(t,this.systemEntries()),this.render()}setZones(t){this.zones={core:t.core.slice(),apps:t.apps.slice(),controls:t.controls.slice()},this.render()}systemEntries(){const t=[];for(const n of ct)for(const o of this.zones[n])o.type==="system"&&t.push(o);return t}zonesFromMenu(t,n){const o={core:[],apps:[],controls:[]};for(const s of t)o[s.isCore?"core":"apps"].push({type:"menu",item:s});for(const s of n)s.type==="system"&&o[Bh(s.item)].push(s);return o}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(t){let n=!1;for(const o of ct){const s=this.zones[o].filter(i=>i.type!=="system"||i.item.id!==t);s.length!==this.zones[o].length&&(n=!0),this.zones[o]=s}n&&(this.badgeOverrides.delete(t),this.artOverrides.delete(t),this.render(),A(v.DOCK_ITEM_REMOVED,{id:t,placement:this.rail}))}setBadge(t,n){const o=this._resolveTileElement(t);if(!o)return;const s=Math.max(0,Math.floor(Number(n)||0));s===0?this.badgeOverrides.delete(t):this.badgeOverrides.set(t,s);const i=o.querySelector(".os-dock__item-primary");Fh(i??o,s),_e.publish("os/badge-changed",{itemId:t,count:s,rail:this.rail})}clearBadge(t){this.setBadge(t,0)}setArt(t,n){if(!n){if(!this.artOverrides.delete(t))return;const s=this._resolveTileElement(t),i=this._declaredIcon(t);s&&i&&this._paintArt(s,t,i),_e.publish("os/art-changed",{itemId:t,icon:"",rail:this.rail});return}this.artOverrides.set(t,n);const o=this._resolveTileElement(t);o&&(this._paintArt(o,t,n),_e.publish("os/art-changed",{itemId:t,icon:n,rail:this.rail}))}getArt(t){return this.artOverrides.get(t)??""}_declaredIcon(t){const n=this.items.find(s=>s.id===t);if(n)return n.icon;const o=this.systemItems.find(s=>s.id===t);return o?o.icon:""}_paintArt(t,n,o){const s=t.querySelector(".os-dock__item-primary")??t,i=this.resolveIcon(o,this._declaredTitle(n),void 0,pi(n)),r=s.querySelector(".os-dock__item-mask, .os-dock__item-svg, .dashicons, img");r?r.replaceWith(i):s.prepend(i)}_declaredTitle(t){const n=this.items.find(s=>s.id===t);if(n)return n.title;const o=this.systemItems.find(s=>s.id===t);return o?o.title:""}setAttention(t,n,o={}){const s=this._resolveTileElement(t);if(!s)return;const i=this.attentionTimers.get(t);if(i!==void 0&&(window.clearTimeout(i),this.attentionTimers.delete(t)),s.classList.remove("os-dock__item--attention-pulse","os-dock__item--attention-shake","os-dock__item--attention-bounce","os-dock__item--intensity-subtle","os-dock__item--intensity-normal","os-dock__item--intensity-strong"),n===null)return;s.classList.add(`os-dock__item--attention-${n}`);const r=o.intensity??"normal";s.classList.add(`os-dock__item--intensity-${r}`);const a=o.durationMs??4e3;if(a>0){const l=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},a);this.attentionTimers.set(t,l)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}appendSystemItem(t){const n=Bh(t),o={type:"system",item:t};for(const a of ct)this.zones[a]=this.zones[a].filter(l=>l.type!=="system"||l.item.id!==t.id);const s=this.zones[n],i=t.order??0,r=s.findIndex(a=>a.type==="system"&&(a.item.order??0)>i);r===-1?s.push(o):s.splice(r,0,o),this.render()}render(){if(Ue.activeDragReset){const o=Ue.activeDragReset;Ue.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="",this.systemHost.innerHTML="",this.itemElements.clear(),this.systemItemElements.clear(),this.items=[],this.systemItems=[];for(const o of ct)for(const s of this.zones[o])s.type==="menu"?this.items.push(s.item):this.systemItems.push(s.item);const t=this.buildHookContextBase();A(v.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of ct){const s=this.zones[o];if(s.length===0)continue;const i=o==="controls"?this.systemHost:this.itemHost;if(n){const r=document.createElement("div");r.className=o==="controls"?"os-dock__separator":"os-dock__separator os-dock__separator--group",r.setAttribute("aria-hidden","true"),i.appendChild(r)}for(const r of s)this.paintEntry(r,o,i,t);n=!0}this.updateActiveStates(),A(v.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}paintEntry(t,n,o,s){const i=t.item.id,r=t.type==="menu"?this.createItemButton(t.item):this.createSystemItemButton(t.item);r.dataset.zone=n,r.dataset.navId=i,t.type==="system"&&t.item.locked===!0?r.dataset.navLocked="true":(this.attachDragReorder(r,i,n),r.addEventListener("contextmenu",d=>{d.preventDefault(),Rh({x:d.clientX,y:d.clientY,id:i,title:t.item.title,surface:"dock",pluginFile:t.type==="menu"?t.item.pluginFile??null:null,pluginName:t.type==="menu"?t.item.pluginName??null:null})})),t.type==="menu"?this.itemElements.set(i,r):this.systemItemElements.set(i,r),o.appendChild(r);const l=this.badgeOverrides.get(i);if(l!==void 0){const d=r.querySelector(".os-dock__item-primary");Fh(d??r,l)}const c=this.artOverrides.get(i);c&&this._paintArt(r,i,c),A(v.DOCK_TILE_RENDERED,{...s,item:t.item,isSystem:t.type==="system",el:r})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=J(v.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id,o.dataset.osWindowBaseId=t.id,t.submenu&&t.submenu.length>0&&(o.dataset.constellationId=t.id);const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title,void 0,pi(t.id))),r.addEventListener("click",l=>t.onOpen(l)),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=kh({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:""},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(t.id),enableGhost:!!t.multi,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>{(t.onOpenNew??t.onOpen)()},suppressTooltip:l=>{l&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,a),this.bindPrewarmDwell(o,()=>this.prewarmNativeWindow(t.id)),J(v.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];t.multi&&s.push("os-dock__item--multi");const i=J(v.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const a=this.resolveIcon(t.icon,t.title,t.url,pi(t.id));if(r.appendChild(a),t.badge>0){const d=t.badge>99?"99+":String(t.badge),u=document.createElement("span");u.className="os-dock__badge",u.textContent=d,u.setAttribute("aria-label",le(Kt("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const l=this.resolveItemBaseId(t);o.dataset.osWindowBaseId=l;const c=kh({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(l),enableGhost:!0,windowManager:this.windowManager,getOrientation:()=>this.orientation,openNew:()=>this.openNewInstance(t),suppressTooltip:d=>{d&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(t.id,c),this.bindHoverPrewarm(o,t),J(v.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n,o){let r=!1,a=0,l=0,c=[],d=null,u=-1,f=null,p=!1;const g=()=>{r=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",U),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",K,!0),window.removeEventListener("blur",Q),document.removeEventListener("visibilitychange",Z),u=-1,f=null},h=o==="controls"?this.systemHost:this.itemHost,m=C=>!!C&&C instanceof HTMLElement&&C.classList.contains("os-dock__item")&&C.dataset.zone===o&&!!C.dataset.navId&&C.dataset.navLocked===void 0,_=C=>{for(const D of Array.from(h.children))D instanceof HTMLElement&&D!==t&&m(D)&&C(D)},I=()=>{const C=[];for(const D of Array.from(h.children))m(D)&&C.push(D.dataset.navId);return C},O=C=>{_(D=>{const V=C.get(D);if(!V)return;const j=D.getBoundingClientRect(),te=V.left-j.left,N=V.top-j.top;if(Math.abs(te)<.5&&Math.abs(N)<.5)return;D.style.transition="none",D.style.transform=`translate(${te}px, ${N}px)`,D.offsetHeight,D.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",D.style.transform="";const L=()=>{D.style.transition="",D.style.transform="",D.removeEventListener("transitionend",L)};D.addEventListener("transitionend",L)})},$=C=>{if(u!==-1&&C.pointerId!==u)return;if(!r){const H=C.clientX-a,z=C.clientY-l;if(H*H+z*z<5*5)return;r=!0,c=I(),d=t.nextSibling,f=t.getBoundingClientRect(),t.classList.add("os-dock__item--dragging"),this.tooltip.classList.remove("os-dock__tooltip--visible")}if(!f)return;const D=C.clientX-a,V=C.clientY-l;t.style.transform=`translate(${D}px, ${V}px)`;const te=document.elementFromPoint(C.clientX,C.clientY)?.closest(".os-dock__item");if(!te||te===t||!m(te))return;const N=te.getBoundingClientRect();let L;this.orientation==="bottom"?L=C.clientX<N.left+N.width/2:L=C.clientY<N.top+N.height/2;const M=new Map;_(H=>{M.set(H,H.getBoundingClientRect())});let P=!1;if(L?te!==t.nextSibling&&(h.insertBefore(t,te),P=!0):te.nextSibling!==t&&(h.insertBefore(t,te.nextSibling),P=!0),P){t.style.transform="";const H=t.getBoundingClientRect();a=H.left+H.width/2,l=H.top+H.height/2,t.style.transform=`translate(${C.clientX-a}px, ${C.clientY-l}px)`,O(M)}},S=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",U),document.removeEventListener("pointercancel",F),document.removeEventListener("keydown",K,!0),window.removeEventListener("blur",Q),document.removeEventListener("visibilitychange",Z),u=-1,f=null,r=!1,Ue.activeDragReset===g&&(Ue.activeDragReset=null)},R=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const C=()=>{t.style.transition="",t.removeEventListener("transitionend",C)};t.addEventListener("transitionend",C)},W=C=>{J0(C)},U=C=>{if(u!==-1&&C.pointerId!==u)return;if(!r){S();return}p=!0;const D=I();R(),S(),D.length===c.length&&D.every((j,te)=>j===c[te])||W(D),setTimeout(()=>{p=!1},200)},F=C=>{if(!(C&&u!==-1&&C.pointerId!==u)){if(r&&d!==void 0){const D=new Map;_(V=>{D.set(V,V.getBoundingClientRect())}),h.insertBefore(t,d),O(D)}R(),S()}},K=C=>{C.key==="Escape"&&F()},Q=()=>F(),Z=()=>{document.visibilityState!=="visible"&&F()};t.addEventListener("pointerdown",C=>{if(!(C.button!==0||Vt())){if(Ue.activeDragReset){const D=Ue.activeDragReset;Ue.activeDragReset=null,D()}(r||u!==-1)&&g(),a=C.clientX,l=C.clientY,u=C.pointerId,r=!1,Ue.activeDragReset=g,document.addEventListener("pointermove",$),document.addEventListener("pointerup",U),document.addEventListener("pointercancel",F),document.addEventListener("keydown",K,!0),window.addEventListener("blur",Q),document.addEventListener("visibilitychange",Z)}}),t.addEventListener("click",C=>{p&&(C.preventDefault(),C.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const a=fi(s);a!==null&&(t=a,i=!0),r=Na(s)}if(r!==null&&!t.startsWith("dashicons-")){const a=this._makeMaskSpan();if($i(a,t,r))return a}if(t.startsWith("dashicons-")&&(i||t!=="dashicons-admin-generic")){const a=document.createElement("span");return a.className=`dashicons ${t}`,a.setAttribute("aria-hidden","true"),r!==null&&(a.style.color=r),a}if(t.startsWith("data:image/svg+xml;base64,")){const a=t.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(a))return this._makeSvgIcon(t)}if(t.startsWith("url("))return this._makeSvgIcon(t);if(t.startsWith("http://")||t.startsWith("https://")){const a=document.createElement("img");return a.className="os-dock__item-img",a.src=t,a.alt="",a.setAttribute("aria-hidden","true"),a}if(o&&!i){const a=this._extractNativeMenuIcon(o);if(a)return a}if(t==="dashicons-admin-generic"){const a=document.createElement("span");return a.className="dashicons dashicons-admin-generic",a.setAttribute("aria-hidden","true"),a}return this.createLetterBadge(n)}_makeMaskSpan(){const t=document.createElement("span");return t.className="os-dock__item-mask",t.setAttribute("aria-hidden","true"),t.style.width="var( --os-dock-icon-size, 20px )",t.style.height="var( --os-dock-icon-size, 20px )",t.style.display="block",t.style.flexShrink="0",t}_makeSvgIcon(t){const n=/^url\(\s*(['"]?)(.+?)\1\s*\)$/.exec(t),o=n?n[2]:t,s=this._makeMaskSpan();if($i(s,o,"currentColor"))return s;const i=document.createElement("span");return i.className="os-dock__item-svg",i.style.backgroundImage=t.startsWith("url(")?t:`url("${t}")`,i.style.backgroundSize="contain",i.style.backgroundRepeat="no-repeat",i.style.backgroundPosition="center",i.setAttribute("aria-hidden","true"),i}_extractNativeMenuIcon(t){const n=document.getElementById("adminmenu");if(!n)return null;let o;try{const f=new URL(t,window.location.href);o=(f.pathname.split("/").pop()||"")+f.search}catch{return null}if(!o)return null;const s=n.querySelectorAll("li.menu-top > a");let i=null;for(const f of Array.from(s))if(f.href.endsWith(o)){i=f.closest("li.menu-top");break}if(!i)return null;const r=i.querySelector(".wp-menu-image");if(!r)return null;const a=r.querySelector("img");if(a&&a.src){const f=document.createElement("img");return f.className="os-dock__item-img",f.src=a.src,f.alt="",f.setAttribute("aria-hidden","true"),f}const l=r.className.match(/\bdashicons-[\w-]+\b/);if(l&&l[0]!=="dashicons-before"){const f=document.createElement("span");return f.className=`dashicons ${l[0]}`,f.setAttribute("aria-hidden","true"),f}const d=window.getComputedStyle(r,"::before").backgroundImage;if(d&&d!=="none"&&!d.includes('url("")'))return this._makeSvgIcon(d);const u=window.getComputedStyle(r).backgroundImage;return u&&u!=="none"&&!u.includes('url("")')?this._makeSvgIcon(u):null}createLetterBadge(t){const n=document.createElement("span");n.className="os-dock__item-letter",n.setAttribute("aria-hidden","true");const o=t.trim(),s=o?Array.from(o)[0]:"?";n.textContent=s.toUpperCase();const i=wc(o);return n.style.background=`linear-gradient(135deg, hsl(${i} 62% 55%), hsl(${(i+24)%360} 58% 42%))`,n}bindTooltipFiltered(t,n,o){const s=J(v.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("os-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("os-dock__tooltip--visible")}))}positionTooltip(t,n){const o=t.getBoundingClientRect();this.tooltip.textContent=n,this.orientation==="bottom"?(this.tooltip.style.left=`${o.left+o.width/2}px`,this.tooltip.style.top=`${o.top-14}px`):this.orientation==="right"?(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.left}px`):(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.right+8}px`)}bindHoverPrewarm(t,n){if(!n.url){const{windowId:o}=n;o&&this.bindPrewarmDwell(t,()=>this.prewarmNativeWindow(o));return}this.bindPrewarmDwell(t,()=>{const o=Tn(n.url);if(o){this.prewarmNativeWindow(o);return}try{const i=new URL(n.url,window.location.href);if(i.origin!==window.location.origin||nC(i)||Ln(i))return}catch{return}const s=this.deriveWindowId(n.url);this.windowManager.prewarm({id:s,baseId:s,url:n.url,parentUrl:n.url,title:n.title,icon:n.icon.startsWith("dashicons-")?n.icon:"dashicons-admin-generic",submenu:n.submenu,selfLabel:n.selfLabel,multi:!!n.multi})})}bindPrewarmDwell(t,n){let s;const i=()=>{s!==void 0&&(window.clearTimeout(s),s=void 0)};t.addEventListener("pointerenter",r=>{r.pointerType!=="mouse"||!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled||(i(),s=window.setTimeout(()=>{s=void 0,n()},180))}),t.addEventListener("pointerleave",i),t.addEventListener("pointerdown",i)}prewarmNativeWindow(t){if(this.windowManager.getById(t))return;window.wp?.os?.prewarmWindow?.(t)}openPage(t){if(t.windowId&&!t.url){const o=this.windowManager.getById(t.windowId);if(o){const i=o.state==="minimized";this.windowManager.focus(o),i&&o.restore();return}window.wp?.os?.openWindow?.(t.windowId);return}if(zn(t.url)||Me(t.url))return;const n=this.deriveWindowId(t.url);this.windowManager.open({id:n,baseId:n,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}openNewInstance(t){if(zn(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=Tn(t.url);if(o&&n?.(o,{source:"dock-peek"}))return;const s=this.deriveWindowId(t.url);this.windowManager.openNew({id:s,baseId:s,url:t.url,parentUrl:t.url,title:t.title,icon:t.icon.startsWith("dashicons-")?t.icon:"dashicons-admin-generic",submenu:t.submenu,selfLabel:t.selfLabel,multi:!0})}deriveWindowId(t){return fe(t,this.adminUrl)}resolveItemBaseId(t){return t.windowId?t.windowId:Tn(t.url)??this.deriveWindowId(t.url)}bindWindowEvents(){const t=()=>this.updateActiveStates();this.boundRefresh=t,document.addEventListener("os-window-opened",t),document.addEventListener("os-window-closed",t),document.addEventListener("os-window-focused",t),window.wp?.hooks?.addAction?.("os.os.switched",this.hooksNamespace,t),window.wp?.hooks?.addAction?.("os.os.closed",this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(v.DOCK_REFRESH_ACTIVE,this.hooksNamespace,t)}destroy(){document.removeEventListener("os-window-opened",this.boundRefresh),document.removeEventListener("os-window-closed",this.boundRefresh),document.removeEventListener("os-window-focused",this.boundRefresh),window.wp?.hooks?.removeAction?.("os.os.switched",this.hooksNamespace),window.wp?.hooks?.removeAction?.("os.os.closed",this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(v.WINDOW_RESTORED,this.hooksNamespace);for(const t of this.attentionTimers.values())window.clearTimeout(t);this.attentionTimers.clear();for(const t of this.peekTeardowns.values())t();for(this.peekTeardowns.clear(),this.tooltip.remove();this.container.firstChild;)this.container.removeChild(this.container.firstChild);this.itemElements.clear(),this.systemItemElements.clear(),this.systemItems=[],this.zones={core:[],apps:[],controls:[]},this.container.removeAttribute("data-os-dock-placement")}updateActiveStates(){const t=this.windowManager.getFocused(),n=this.windowManager.getActiveDesktopId(),o=i=>(i.config.desktopId||n)===n,s=i=>i.state==="minimized";for(const i of this.items){const r=this.itemElements.get(i.id);if(!r)continue;const a=this.resolveItemBaseId(i);let l=this.windowManager.getAllByBaseId(a).filter(o);if(l.length===0&&i.url){const f=this.deriveWindowId(i.url);l=this.windowManager.getAll().filter(p=>{const g=p.config.baseId||p.id;if(g===a||g===f||g===i.id||p.config.parentUrl&&this.deriveWindowId(p.config.parentUrl)===f)return!0;if(p.config.url){const h=this.deriveWindowId(p.config.url);return h===a||h===f}return!1}).filter(o)}const c=l.length>0,d=c&&l.every(s),u=!!t&&o(t)&&!s(t)&&l.some(f=>f.id===t.id||(t.config.baseId||t.id)===a);r.classList.toggle("os-dock__item--active",c),r.classList.toggle("os-dock__item--focused",u),r.classList.toggle("os-dock__item--all-minimized",d),r.classList.toggle("os-dock__item--stacked",c&&l.length>1)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const a=this.windowManager.getById(i.id),l=i.isOpen?i.isOpen():!!a,c=!!a&&s(a),d=!!t&&t.id===i.id&&!s(t);r.classList.toggle("os-dock__item--active",l),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",c)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("os-show-desktop-active",o)}};Ue.instanceCounter=0,Ue.activeDragReset=null;let Fi=Ue;function Fh(e,t){const n=e.querySelector(":scope > .os-dock__badge");if(t<=0){n?.remove();return}const o=t>99?"99+":String(t);if(n){n.textContent!==o&&(n.textContent=o),n.setAttribute("aria-label",le(Kt("%d notification","%d notifications",t),t));return}const s=document.createElement("span");s.className="os-dock__badge",s.textContent=o,s.setAttribute("aria-label",le(Kt("%d notification","%d notifications",t),t)),e.appendChild(s)}const Hh=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),vc={id:"default",label:"Icon strip",description:"The shipped baseline — icon tiles with badges, tooltips, multi-instance chips, and attention animations.",icon:"dashicons-menu-alt",apiVersion:1,mount(e){const t=new Fi(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[Hh]:t,replaceItems:o=>t.replaceItems(o),setZones:o=>t.setZones(o),appendSystemItem:o=>t.appendSystemItem(o),removeSystemItem:o=>t.removeSystemItem(o),setBadge:(o,s)=>t.setBadge(o,s),setAttention:(o,s,i)=>t.setAttention(o,s,i),setOrientation:o=>t.setOrientation(o),destroy:()=>t.destroy()}}};function Gh(e){if(!e)return null;const n=e[Hh];return n instanceof Fi?n:null}function oC(){Au(vc)}const zh="os-desktop-theme-css",sC="os-desktop-theme-inline-css",bc="data-os-desktop-theme-css",jh="os-desktop-theme-changed";function Vh(){return document.getElementById("os-shell")}function Kh(){const e=[];for(const t of[zh,sC]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${bc}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function Ec(){for(const e of Kh())e.remove()}function iC(e){const t=Vh();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:Kh().length>0}function qh(e){if(e.cssUrl!==""){const t=document.createElement("link");t.id=zh,t.rel="stylesheet",t.href=e.cssUrl,t.setAttribute(bc,e.slug),document.head.appendChild(t)}else if(e.cssText!==""){const t=document.createElement("style");t.setAttribute(bc,e.slug),t.textContent=e.cssText,document.head.appendChild(t)}}function Yh(e){const t=document.body;if(!t)return;const n=[];t.classList.forEach(o=>{o.startsWith("os-desktop-theme-")&&n.push(o)});for(const o of n)(e===null||o!==`os-desktop-theme-${e}`)&&t.classList.remove(o);e!==null&&t.classList.add(`os-desktop-theme-${e}`)}function _c(e){const t=Mn(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:La(o),i=s?s.slug:null;if(i===n)return;const r=Vh();if(!s)r?.removeAttribute("data-os-desktop-theme"),Yh(null),Ec(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!iC(s.slug))if(s.cssDeferred&&s.cssUrl===""&&s.cssText===""){const l=s.slug,c=()=>df().then(()=>{if(Mn().state.activeId!==l)return;const d=La(l);if(!d||d.cssDeferred)throw new Error(`theme "${l}" resolved without a stylesheet`);Ec(),qh(d)}).catch(d=>{Mn().state.activeId===l&&(ue({message:b("Could not load that desktop theme — the previous one is still showing."),action:{label:b("Retry"),onClick:()=>void c()},persistent:!0,dismissible:!0}),console.warn("[openstation] desktop theme stylesheet failed to load",d))});c()}else Ec(),qh(s);r?.setAttribute("data-os-desktop-theme",s.slug),Yh(s.slug),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const a={themeId:i,previous:n};A(v.DESKTOP_THEME_CHANGED,a),typeof document<"u"&&document.dispatchEvent(new CustomEvent(jh,{detail:a}))}function rC(e={}){const t=e.deactivate??(()=>_c(""));return function(o){wS(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=Mn().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const aC="",cC="system-default",lC={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function dC(e,t,n={}){const o=t===aC,s=o?null:La(t);if(!o&&!s)return{};const i=o?cC:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=uS(o?lC:s.recommendedOsSettings),l=Object.keys(a);if(l.length===0)return{};const c=e,d={};for(const u of l){const f=a[u];typeof f!="string"&&typeof f!="number"||!(u in e)||typeof c[u]!=typeof f||(c[u]=f,d[u]=f)}return Object.keys(d).length===0?{}:(r||(e.appliedThemeRecommendations=[...e.appliedThemeRecommendations,i].slice(-64)),d)}function Xh(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}function uC(e,t){Fn({id:tf,label:b("Custom gradient"),type:"css",preview:Xh(e()),description:b("Mix your own two-colour gradient and set the angle — your desk, your palette."),resolveValue:()=>Xh(e())})}function fC(e){if(!e.customImage){Yo(xo)&&ah(xo);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`,o=Yo(xo);o&&o.type==="css"&&o.value===n||Fn({id:xo,label:b("Custom image"),type:"css",value:n,preview:n,description:b("Any image from your media library or an upload, sized to cover the whole desk.")})}function pC(e){const t=/^#?([0-9a-f]{6})$/i.exec(e.trim());if(!t)return!1;const n=i=>{const r=parseInt(i,16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4},o=t[1];return .2126*n(o.slice(0,2))+.7152*n(o.slice(2,4))+.0722*n(o.slice(4,6))>.35}function Zh(e){return JSON.parse(JSON.stringify(e))}function hC(e,t){return e===t?!0:typeof e!="object"||typeof t!="object"||e===null||t===null?!1:JSON.stringify(e)===JSON.stringify(t)}class mC{constructor(t){this.listeners=new Set,this.baseState=null,this.overridePatch=null,this.layer=t,this.state=i0(),document.addEventListener("os-settings-save-lifecycle",n=>{const o=n.detail;!o||(window.wp?.os?.windowManager?.getById(Ct)?.markActivity(o.phase,{error:o.error}),o.phase!=="failed"||!o.rolledBackTo)||(this.state=o.rolledBackTo,this.apply(),this.notify())}),uC(()=>this.state)}getOsSettingsSnapshot(){return on(this.state)}subscribeOsSettings(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}apply(){const t=document.getElementById("os-shell");if(!t)return;KA(this.state.wallpaperSettings),fC(this.state);const n=Yo(this.state.wallpaper)||Yo(ka())||Yo(Sa)||cc()[0];n&&this.layer.apply(n);const o=li(),s=o.find(g=>g.id===this.state.accent)??o[0],i=this.state.accent===nf?this.state.customAccent:s.value,r=Ia.find(g=>g.id===this.state.dockSize)??Ia[1],a=Aa.find(g=>g.id===this.state.windowRadius)??Aa[1],l=document.body;l.style.setProperty("--wp-admin-theme-color",i),l.style.setProperty("--os-ui-accent",i);const c=pC(i)?"#0c0b0f":"#fffbff";l.style.setProperty("--os-ui-accent-ink",c);const u=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;u===null?l.style.removeProperty("--os-ui-accent-dim"):l.style.setProperty("--os-ui-accent-dim",u),t.style.setProperty("--os-ui-accent",i),t.style.setProperty("--os-ui-accent-ink",c),u===null?t.style.removeProperty("--os-ui-accent-dim"):t.style.setProperty("--os-ui-accent-dim",u),l.style.setProperty("--os-dock-width",`${r.width}px`),l.style.setProperty("--os-dock-icon-size",`${r.icon}px`),t.style.setProperty("--os-dock-width",`${r.width}px`),t.style.setProperty("--os-dock-icon-size",`${r.icon}px`),l.style.setProperty("--os-window-radius",`${a.value}px`),t.style.setProperty("--os-window-radius",`${a.value}px`);const f=di.find(g=>g.id===this.state.adminBarMode)??di[0];for(const g of di)document.body.classList.toggle(`os-admin-bar-${g.id}`,g.id===f.id);const p=g=>(ui.find(h=>h.id===g)??ui[0]).id;document.getElementById(YA)?.setAttribute(Xo,p(this.state.dockBehavior)),document.getElementById(uh)?.setAttribute(Xo,p(this.state.sideDockBehavior)),n0(),qk(),t.setAttribute("data-os-layout",this.state.desktopLayout),O_(this.state.dockRailRenderer),_c(this.state.desktopTheme)}setWorkspaceAppearance(t){const n=this.baseState??this.state;if(!t||Object.keys(t).length===0){if(!this.baseState)return;this.state=n,this.baseState=null,this.overridePatch=null}else this.baseState=n,this.overridePatch=Zh(t),this.state={...n,...Zh(t)};this.apply(),this.notify()}save(t={}){p0(this._persistableState(),t),this.notify()}_persistableState(){const t=this.baseState,n=this.overridePatch;if(!t||!n)return this.state;const o={...this.state},s=n,i=t;for(const r of Object.keys(s))hC(o[r],s[r])&&(o[r]=i[r]);return o}update(t,n={}){const o={...t};delete o.appliedThemeRecommendations,delete o.adminAssetCacheEnabled,delete o.windowPrewarmEnabled;const s=fc(o,this.state),i=yh.filter(r=>r in o);Object.assign(this.state,s),this.save(n),i.some(r=>a0.has(r))&&this.apply()}applyThemeRecommendations(t){const n=dC(this.state,t,{force:!0});return Object.keys(n).length>0&&(this.save(),this.apply()),n}reset(t={}){const n=Eh();n.wallpaper=ka(),n.customImage=this.state.customImage,n.adminAssetCacheEnabled=this.state.adminAssetCacheEnabled,n.windowPrewarmEnabled=this.state.windowPrewarmEnabled,Object.assign(this.state,n),this.save(t),this.apply()}notify(){if(this.listeners.size===0)return;const t=this.getOsSettingsSnapshot();for(const n of Array.from(this.listeners))try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] os-settings listener threw:",o)}}}const gC="os-network-admin";function wC(e,t){const n=e.networkAdmin;return!n||e.isNetworkAdmin?null:{id:gC,title:b("Network Admin"),icon:"dashicons-admin-multisite",placeable:!0,navKind:"core",onOpen:o=>t(n.url,o),get submenu(){return n.rows.map(({title:o,url:s})=>({title:o,url:s,onSelect:i=>t(s,i)}))}}}function Jh(e){return!!e&&(e.metaKey||e.ctrlKey||e.shiftKey||e.button===1)}function Sc(e,t){if(Jh(t)){window.open(e,"_blank","noopener,noreferrer");return}window.location.assign(e)}function yC(e){return async(t,n)=>{try{const o=await Ae(e.hopUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({target:t,direction:n})},{source:"desktop-mode/network-hop"});if(!o.ok)return null;const s=await o.json();return typeof s.url=="string"&&s.url!==""?s.url:null}catch{return null}}}const vC=220,bC=360,EC=4e3,kc="openstation-hop-direction",Ic="os-shell--arriving",Qh="os-shell--revealing";function Ac(){return document.getElementById("os-shell")}function em(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function _C(e){try{window.sessionStorage.setItem(kc,e)}catch{}const t=Ac();return!t||em()?Promise.resolve():(t.classList.add(`os-shell--hop-out-${e}`),new Promise(n=>{window.setTimeout(n,vC)}))}function SC(){try{const e=window.sessionStorage.getItem(kc);return window.sessionStorage.removeItem(kc),e==="next"||e==="prev"?e:null}catch{return null}}function kC(e=null){const t=Ac();if(!t||!t.classList.contains(Ic))return;const n=SC()??e;n&&t.classList.add(`os-shell--arriving-${n}`),window.setTimeout(tm,EC)}function tm(){const e=Ac();!e||!e.classList.contains(Ic)||(e.classList.remove(Ic,"os-shell--arriving-next","os-shell--arriving-prev"),!em()&&(e.classList.add(Qh),window.setTimeout(()=>e.classList.remove(Qh),bC)))}function jn(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function IC(e){return!!e&&e.__wpdHtml===!0}const AC="$$wpd$$",De=/\$\$wpd\$\$(\d+)\$\$/g,CC="$$wpd-node$$",LC=/^\$\$wpd-node\$\$(\d+)\$\$$/,TC=new Set(["style","script","textarea","title"]);function NC(e){let t="",n=!1,o=null,s=!1,i=null,r="",a=!1;for(let l=0;l<e.length;l++){const c=e[l];t+=c;for(let d=0;d<c.length;d++){const u=c[d];if(s){c.startsWith("-->",d)&&(s=!1,d+=2);continue}if(i!==null){u==="<"&&c[d+1]==="/"&&c.slice(d+2,d+2+i.length).toLowerCase()===i&&(d+=1+i.length,i=null,n=!0,a=!1,r="");continue}if(o!==null){u===o&&(o=null);continue}if(n){u==='"'||u==="'"?(o=u,a=!1):u===">"?(n=!1,a=!1,TC.has(r)&&(i=r),r=""):a&&(/[a-zA-Z0-9-]/.test(u)?r+=u.toLowerCase():a=!1);continue}if(c.startsWith("<!--",d)){s=!0,d+=3;continue}const f=c[d+1]??"";u==="<"&&/[a-zA-Z/!]/.test(f)&&(n=!0,r="",a=/[a-zA-Z]/.test(f))}l<e.length-1&&(t+=n||s||i!==null?`${AC}${l}$$`:`<!--${CC}${l}$$-->`)}return t}const nm=new WeakMap;function om(e){const t=nm.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=NC(e);const o=[],s=(a,l)=>{if(a.nodeType===Node.ELEMENT_NODE){const u=a;for(const f of Array.from(u.attributes)){const p=f.name,g=f.value,h=p[0];if(De.test(g))if(De.lastIndex=0,h==="@"){const m=De.exec(g);De.lastIndex=0,o.push({path:l,kind:"event",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else if(h==="."){const m=De.exec(g);De.lastIndex=0,o.push({path:l,kind:"prop",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else if(h==="?"){const m=De.exec(g);De.lastIndex=0,o.push({path:l,kind:"bool",name:p.slice(1),valueIndex:m?Number(m[1]):0}),u.removeAttribute(p)}else{const m=[],_=[];let I=0,O;for(De.lastIndex=0;(O=De.exec(g))!==null;)m.push(g.slice(I,O.index)),_.push(Number(O[1])),I=O.index+O[0].length;m.push(g.slice(I)),o.push({path:l,kind:"attr",name:p,template:m,valueIndices:_}),u.setAttribute(p,"")}}}const c=Array.from(a.childNodes);let d=0;for(let u=0;u<c.length;u++){const f=c[u],p=u+d;if(f.nodeType===Node.COMMENT_NODE){const g=LC.exec(f.data);if(g){const h=document.createTextNode("");f.parentNode.replaceChild(h,f),o.push({path:[...l,p],kind:"node",valueIndex:Number(g[1])})}continue}if(f.nodeType===Node.TEXT_NODE){const g=f.textContent||"";if(!De.test(g)){De.lastIndex=0;continue}De.lastIndex=0;const h=f.parentNode;let m=0,_;const I=[],O=[];for(De.lastIndex=0;(_=De.exec(g))!==null;){_.index>m&&I.push(document.createTextNode(g.slice(m,_.index)));const $=document.createTextNode("");I.push($),O.push({path:[...l,p+I.length-1],kind:"node",valueIndex:Number(_[1])}),m=_.index+_[0].length}m<g.length&&I.push(document.createTextNode(g.slice(m)));for(const $ of I)h.insertBefore($,f);h.removeChild(f),d+=I.length-1,o.push(...O)}else s(f,[...l,p])}};s(n.content,[]);const r={template:n,buildParts:a=>{const l=[];for(const c of o){let d=a;for(const u of c.path)d=d.childNodes[u];c.kind==="node"?l.push({kind:"node",valueIndex:c.valueIndex,child:{anchor:d,state:null}}):c.kind==="attr"?l.push({kind:"attr",element:d,name:c.name,template:c.template,valueIndices:c.valueIndices}):c.kind==="event"?l.push({kind:"event",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="prop"?l.push({kind:"prop",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="bool"&&l.push({kind:"bool",valueIndex:c.valueIndex,element:d,name:c.name})}return l}};return nm.set(e,r),r}const sm=new WeakMap;function OC(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function DC(e,t){const n=sm.get(t);if(n&&n.strings===e.strings&&OC(n,t)){Hi(n.parts,e.values);return}const o=om(e.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(s),Hi(i,e.values),sm.set(t,{strings:e.strings,parts:i,nodes:r})}function Hi(e,t){for(const n of e)if(n.kind==="node")Gi(n.child,t[n.valueIndex]);else if(n.kind==="attr"){let o=n.template[0];for(let s=0;s<n.valueIndices.length;s++)o+=im(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 Gi(e,t){if(t==null||t===!1){e.state&&(xt(e.state),e.state=null);return}if(Array.isArray(t)){WC(e,t);return}if(IC(t)){MC(e,t);return}if(t instanceof Node){RC(e,t);return}xC(e,im(t))}function RC(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&xt(n),Zo(e,[t]),e.state={shape:"node",node:t})}function xC(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&xt(n);const o=document.createTextNode(t);Zo(e,[o]),e.state={shape:"text",node:o,text:t}}function MC(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){Hi(n.parts,t.values);return}n&&xt(n);const o=om(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);Zo(e,[s]),Hi(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function WC(e,t){const n=e.state;if(n?.shape==="array"){const s=Math.min(n.entries.length,t.length);for(let i=0;i<s;i++)Gi(n.entries[i],t[i]);if(t.length<n.entries.length){for(let i=t.length;i<n.entries.length;i++){const r=n.entries[i];r.state&&xt(r.state),r.anchor.remove()}n.entries.length=t.length}else for(let i=n.entries.length;i<t.length;i++){const r=document.createTextNode("");Zo(e,[r]);const a={anchor:r,state:null};Gi(a,t[i]),n.entries.push(a)}return}n&&xt(n);const o=[];for(const s of t){const i=document.createTextNode("");Zo(e,[i]);const r={anchor:i,state:null};Gi(r,s),o.push(r)}e.state={shape:"array",entries:o}}function Zo(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function xt(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&&(xt(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&&xt(t.state),t.anchor.remove()}function im(e){return e==null||e===!1?"":String(e)}const Gt=class Gt 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(rm)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=PC(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=rm(n);Object.defineProperty(this,n,{get:()=>n in this._propValues?this._propValues[n]:this.getAttribute(o),set:s=>{let i;s==null||s===!1?i=null:s===!0?i="":i=String(s),this._propValues[n]=i,i===null?this.removeAttribute(o):this.setAttribute(o,i),this.requestUpdate()},enumerable:!0,configurable:!0})}}_scheduleRender(){this._renderScheduled||!this.isConnected||(this._renderScheduled=!0,queueMicrotask(()=>{this._renderScheduled=!1,this.isConnected&&DC(this.render(),this._renderRoot)}))}_adoptStyles(){const t=this.constructor;if(t.styles.length!==0)if(t.shadow&&this.shadowRoot){const n=t.styles.map(o=>o.sheet).filter(o=>o!==null);if(this.shadowRoot.adoptedStyleSheets=n,n.length!==t.styles.length){for(const o of t.styles)if(!o.sheet){const s=document.createElement("style");s.textContent=o.cssText,this.shadowRoot.appendChild(s)}}}else this._adoptLightStyles(t)}_adoptLightStyles(t){if(!Gt._lightStylesAdopted.has(t)){Gt._lightStylesAdopted.add(t);for(const n of t.styles){const o=document.createElement("style");o.dataset.osUi=this.tagName.toLowerCase(),o.textContent=n.cssText,document.head.appendChild(o)}}}};Gt.props=[],Gt.styles=[],Gt.shadow=!0,Gt._lightStylesAdopted=new WeakSet;let sn=Gt;function Jo(e,t){customElements.get(e)||customElements.define(e,t)}function rm(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function PC(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const $C=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function Le(e,...t){let n=e[0];for(let o=1;o<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($C){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}const Cc=Le`: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 ) )}`,UC=Le` .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%}}`,am=Le` .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%}}`,BC=Le` .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}}`,FC=Le` .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}}`,HC=Le` .os-holo-ring{position:absolute;inset:0;border-radius:inherit;box-shadow:0 0 0 0 var( --_holo-ring-color );opacity:0;pointer-events:none}:active:not(:disabled )>.os-holo-ring,:host(:active:not( [ disabled ] ) )>.os-holo-ring{animation:os-holo-ring var( --_holo-t-slow ) var( --_holo-ease )}@keyframes os-holo-ring{0%{opacity:0.45;box-shadow:0 0 0 0 var( --_holo-ring-color )}100%{opacity:0;box-shadow:0 0 0 10px transparent}}@media ( prefers-reduced-motion:reduce ){:active:not(:disabled )>.os-holo-ring,:host(:active:not( [ disabled ] ) )>.os-holo-ring{animation:none}}`,GC=Le` .os-holo-shimmer{background-image:var( --_holo-fill );background-size:300% 300%;background-repeat:no-repeat;animation:os-holo-shimmer 2.4s var( --_holo-loop ) infinite}@keyframes os-holo-shimmer{0%{background-position:0% 50%}100%{background-position:100% 50%}}@media ( prefers-reduced-motion:reduce ){.os-holo-shimmer{animation:none;background-position:30% 50%}}`,zC=Le` .os-holo-enter{animation:os-holo-enter var( --_holo-t ) var( --_holo-spring )}@keyframes os-holo-enter{from{opacity:0;transform:scale( 0.96 )}}@media ( prefers-reduced-motion:reduce ){.os-holo-enter{animation:none}}`,jC=Le` input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ),select,textarea{transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):hover:not(:disabled ),select:hover:not(:disabled ),textarea:hover:not(:disabled ){border-color:var( --os-ui-border-strong,#8c8f94 )}input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):focus,input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):focus-visible,select:focus,select:focus-visible,textarea:focus,textarea:focus-visible{outline:none;border-color:var( --os-ui-accent,#2271b1 );box-shadow:var( --_holo-focus-field )}input::placeholder,textarea::placeholder{color:var( --os-ui-fg-faint,#8c8f94 );opacity:1}input::selection,textarea::selection{background:var( --os-ui-selection-bg,rgba( 159,152,255,0.6 ) );color:var( --os-ui-selection-fg,#fffbff )}@media ( prefers-reduced-motion:reduce ){input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ),select,textarea{transition-duration:1ms}}`,VC=Le` input[ type='checkbox' ],input[ type='radio' ]{appearance:none;-webkit-appearance:none;position:relative;flex:0 0 auto;box-sizing:border-box;width:16px;height:16px;margin:0;padding:0;border:1px solid var( --_holo-track-edge );border-radius:4px;background-color:var( --_holo-track );background-image:none;background-repeat:no-repeat;cursor:inherit;transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input[ type='radio' ]{border-radius:50%}input[ type='checkbox' ]:hover:not(:disabled ),input[ type='radio' ]:hover:not(:disabled ){border-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:focus-visible,input[ type='radio' ]:focus-visible{outline:none;box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked,input[ type='checkbox' ]:indeterminate,input[ type='radio' ]:checked{border-color:transparent;background-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:checked:focus-visible,input[ type='radio' ]:checked:focus-visible{box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:46%;width:3.5px;height:7.5px;border:solid var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );border-width:0 2px 2px 0;transform:translate( -50%,-50% ) rotate( 45deg );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:indeterminate::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:8px;height:2px;border:0;border-radius:1px;background:var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );transform:translate( -50%,-50% )}input[ type='radio' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:50%;width:6px;height:6px;border-radius:50%;background:var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) );transform:translate( -50%,-50% );animation:os-holo-tick 180ms cubic-bezier( 0.3,1.4,0.6,1 )}input[ type='checkbox' ]:disabled,input[ type='radio' ]:disabled{cursor:not-allowed}@keyframes os-holo-tick{from{opacity:0;transform:translate( -50%,-50% ) rotate( 45deg ) scale( 0.4 )}}@media ( prefers-reduced-motion:reduce ){input[ type='checkbox' ]:checked::after,input[ type='radio' ]:checked::after{animation:none}}`,KC=Le` @keyframes os-holo-drift{0%{background-position:16% 26%}50%{background-position:84% 74%}100%{background-position:16% 26%}}.os-holo-alive{animation:os-holo-drift var( --_holo-t-ambient ) var( --_holo-loop ) infinite}@media ( prefers-reduced-motion:reduce ){.os-holo-alive{animation:none}}`;Le` ${Cc} ${UC} ${am} ${BC} ${FC} ${HC} ${GC} ${zC} ${jC} ${VC} ${KC} `;const qC=Le` ${Cc}:host{display:inline-flex;position:relative;padding:3px;background:var( --os-ui-segmented-bg,var( --os-ui-hover,rgba( 0,0,0,0.05 ) ) );border-radius:8px;gap:2px;box-shadow:var( --os-ui-segmented-edge,none )}.os-segmented__thumb{position:absolute;top:3px;bottom:3px;left:0;width:var( --_thumb-w,0px );border-radius:6px;background-color:var( --os-ui-segmented-selected-bg,color-mix( in srgb,var( --os-ui-accent,#2271b1 ) var( --os-ui-segmented-selected-accent,100% ),var( --os-ui-segmented-selected-base,var( --os-ui-surface,#fff ) ) ) );background-image:var( --os-ui-segmented-selected-image,none );box-shadow:var( --os-ui-segmented-selected-shadow,none );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;transform:translateX( var( --_thumb-x,0px ) );pointer-events:none;opacity:0}:host( [ data-thumb ] ) .os-segmented__thumb{opacity:1}:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition:transform var( --_holo-t-slow ) var( --_holo-spring ),width var( --_holo-t-slow ) var( --_holo-ease ),opacity var( --_holo-t-fast ) linear}@media ( prefers-reduced-motion:reduce ){:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition-duration:1ms}}`,YC=Le` ${Cc} ${am}:host{flex:1 1 auto;min-width:0;--_holo-sheen:var( --os-ui-segmented-hover-sheen,var( --os-ui-holo-sheen,linear-gradient( 124deg,rgba( 159,214,255,0.1 ) 0%,rgba( 236,155,255,0.12 ) 34%,rgba( 242,82,252,0.1 ) 58%,rgba( 147,240,198,0.09 ) 100% ) ) )}button{appearance:none;display:block;width:100%;padding:6px 13px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --os-ui-fg-muted,#646970 );cursor:pointer;border-radius:6px;transition:background-color var( --_holo-t ) ease,color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,background-position var( --_holo-t ) ease;white-space:nowrap}button:hover{color:var( --os-ui-fg,#1d2327 )}:host(:not( [ aria-checked='true' ] ) ) button:hover{background-color:var( --os-ui-segmented-hover-bg,transparent )}button:focus-visible{outline:none;box-shadow:var( --_holo-focus )}:host( [ aria-checked='true' ] ) button{color:var( --os-ui-segmented-selected-fg,color-mix( in srgb,var( --os-ui-accent-ink,var( --os-ui-fg-on-accent,#fff ) ) var( --os-ui-segmented-selected-accent,100% ),var( --os-ui-fg,#1d2327 ) ) );transition-duration:var( --_holo-t-fast )}:host( [ aria-checked='true' ] ) button::before{display:none}`,Xs=class Xs extends sn{render(){return this.setAttribute("role","radio"),jn` | |
| 25 | 3 | <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?J`<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 | - `}};ms.props=["variant","disabled","type","busy","fill-cell"],ms.styles=[Ok],ms.help=void 0;let Ia=ms;xe("os-button",Ia);function kp(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}const Mk=()=>E("Mix your own two-colour gradient and set the angle — your desk, your palette.");function Pk(e){hn({id:zv,label:E("Custom gradient"),type:"css",preview:kp(e.state),description:Mk(),resolveValue:()=>kp(e.state)})}function Wk(e){if(!e.customImage){Of(tu);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`;hn({id:tu,label:E("Custom image"),type:"css",value:n,preview:n,description:E("Any image from your media library or an upload, sized to cover the whole desk.")})}let ui=null;function $k(e){return window.openStationRenderOsSettingsPanel?Promise.resolve(window.openStationRenderOsSettingsPanel):ui||(ui=new Promise((t,n)=>{const o=document.querySelector('script[data-os-settings-panel="1"]'),s=()=>{const r=window.openStationRenderOsSettingsPanel;if(!r){n(new Error("[openstation] os-settings-panel bundle loaded but did not register openStationRenderOsSettingsPanel"));return}t(r)};if(o){window.openStationRenderOsSettingsPanel?s():(o.addEventListener("load",s),o.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))));return}const i=document.createElement("script");i.src=e,i.async=!0,i.dataset.osSettingsPanel="1",i.addEventListener("load",s),i.addEventListener("error",()=>n(new Error("failed to load os-settings-panel bundle"))),document.head.appendChild(i)}),ui)}class Uk{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=b0(),document.addEventListener("os-settings-save-lifecycle",o=>{const s=o.detail;!s||s.phase!=="failed"||!s.rolledBackTo||(this.state=s.rolledBackTo,this.apply(),this._lastRenderedBody?.isConnected&&this.renderPanel(this._lastRenderedBody))}),Pk(this),Wk(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,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,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;g0(this.state.wallpaperSettings);const n=ca(this.state.wallpaper)||ca(su())||ca($r)||Pf()[0];n&&this.layer.apply(n);const o=Ur(),s=o.find(f=>f.id===this.state.accent)??o[0],i=this.state.accent===nu?this.state.customAccent:s.value,r=Fr.find(f=>f.id===this.state.dockSize)??Fr[1],a=Br.find(f=>f.id===this.state.windowRadius)??Br[1],l=document.body;l.style.setProperty("--wp-admin-theme-color",i),l.style.setProperty("--os-ui-accent",i);const d=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;d===null?l.style.removeProperty("--os-ui-accent-dim"):l.style.setProperty("--os-ui-accent-dim",d),t.style.setProperty("--os-ui-accent",i),d===null?t.style.removeProperty("--os-ui-accent-dim"):t.style.setProperty("--os-ui-accent-dim",d),l.style.setProperty("--os-dock-width",`${r.width}px`),l.style.setProperty("--os-dock-icon-size",`${r.icon}px`),l.style.setProperty("--os-window-radius",`${a.value}px`),t.style.setProperty("--os-window-radius",`${a.value}px`);const u=Bs.find(f=>f.id===this.state.adminBarMode)??Bs[0];for(const f of Bs)document.body.classList.toggle(`os-admin-bar-${f.id}`,f.id===u.id);t.setAttribute("data-os-layout",this.state.desktopLayout),fv(this.state.dockRailRenderer),va(this.state.desktopTheme)}save(t={}){if(I0(this.state,t),this.osSettingsListeners.size>0){const n=this.getOsSettingsSnapshot(),o=Array.from(this.osSettingsListeners);for(const s of o)try{s(n)}catch(i){typeof console<"u"&&console.error("[openstation] os-settings listener threw:",i)}}}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){this._lastRenderedBody=t;const n=window.openStationRenderOsSettingsPanel;if(n){n(this,t);return}$k(this.config.osSettingsPanelBundleUrl??"").then(o=>{t.isConnected&&o(this,t)}).catch(o=>{typeof console<"u"&&console.error("[openstation] OpenStation Preferences panel failed to load:",o)})}}const Fk={userId:null,requestedAt:0,tabRequested:!1};let fi=null;function Bk(){if(fi)return fi;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(fi=t("desktop-mode/user-edit/target",()=>({...Fk})),fi)}function Hk(e){const t=Bk();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 pi=null;function zk(){if(pi)return pi;const e=window.wp?.os?.createSharedStore;return typeof e!="function"?null:(pi=e("desktop-mode/comments/post-filter",()=>({postId:0})),pi)}function Sp(e){const t=zk();t&&(t.state.postId=e,t.notify())}function Gk(){Sp(0)}function Ap(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:jk(),visible:!document.hidden,settings:m0(e)}}function jk(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class Cp{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(v.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){T(v.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(t){const n=t.resolveValue?t.resolveValue(Ap(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=Ap(t.id,this.pluginUrl);T(v.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?ka(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},T(v.WALLPAPER_MOUNTED,{id:t.id,container:this.element,ctx:o}),this.isEffectivelyHidden()&&this.emitEffectiveVisibility()};s.then(()=>{if(n!==this.generation)return;let r;try{r=t.mount(this.element,o)}catch(a){this.handleMountFailure(t.id,a);return}if(Vk(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(v.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){T(v.WALLPAPER_SUSPEND,{id:this.active?.id??null,suspended:this.isSuspended(),reasons:Array.from(this.suspendReasons.keys())})}installFreezeOverlay(){if(this.freezeOverlay||!this.active)return;const t=this.element.querySelector("canvas");if(!(!t||t.width===0||t.height===0))try{const n=document.createElement("canvas");n.width=t.width,n.height=t.height;const o=n.getContext("2d");if(!o)return;o.drawImage(t,0,0),n.className="os-wallpaper-freeze",n.style.position="absolute",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.setAttribute("aria-hidden","true"),this.element.appendChild(n),t.style.visibility="hidden",this.freezeOverlay=n,this.frozenCanvas=t}catch{}}removeFreezeOverlay(){this.freezeOverlay?.remove(),this.freezeOverlay=null,this.frozenCanvas&&(this.frozenCanvas.style.visibility="",this.frozenCanvas=null)}handleMountFailure(t,n){this.element.innerHTML="",T(v.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),T(v.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function Vk(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const Ip=le("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),yn=Ip.state.seed,xa=Ip.state.listeners;function La(e){Ne("Game",Rt(e,Np),e);const t=yn.findIndex(n=>n.id===e.id);t>=0?yn[t]=e:yn.push(e),Lp()}function xp(e){const t=yn.findIndex(n=>n.id===e);t>=0&&(yn.splice(t,1),Lp())}function qk(e){return xa.add(e),()=>{xa.delete(e)}}function Lp(){const e=Array.from(xa);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function Tp(){const e=yn.slice(),t=q(v.GAMES,e);return Array.isArray(t)?t.filter(Kk):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function hi(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 Kk(e){return Rt(e,Np).length===0}const Yk="desktop-mode/games";function Xk(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function fo(e,t={},n={}){const{restUrl:o,restNonce:s}=Xk(),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 Fe(nt(o,e),{...t,headers:i,credentials:"same-origin"},{source:Yk,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok){const l=a?.message||`Games request failed (${r.status})`,c=new Error(l);throw c.status=r.status,c}return a}function Zk(e,t,n={}){return fo(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function Jk(){return fo("desktop-mode/v1/games/playtime")}function Qk(e,t,n={}){return fo(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function eS(e){return fo(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function tS(e,t,n={}){return fo(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const nS=6e4;function oS(e,t={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const l=Date.now();o+=Math.max(0,l-n),n=l},r=()=>{i();const l=Math.floor(o/1e3);l<1||(o-=l*1e3,Qk(e,l,{windowId:t.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,nS);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const bn=le("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function sS(){return bn.state}function Ta(e){const t=bn.state;let n=!1;for(const o of e){if(!o||typeof o.id!="number")continue;const s=t.rows.get(o.id);(!s||s.updatedAtMs!==o.updatedAtMs)&&(t.rows.set(o.id,o),n=!0),o.updatedAtMs>t.version&&(t.version=o.updatedAtMs)}n&&rS()}function iS(e){return bn.state.listeners.add(e),()=>{bn.state.listeners.delete(e)}}function rS(){for(const e of Array.from(bn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function aS(){return Array.from(bn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function Dp(){return window.wp?.os??{}}const lS=760,cS=560,dS=480,uS=380;async function fS(e){if(typeof e.render=="function")return e;const t=Dp().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 La(s),s}async function Rp(e,t={}){const n=Dp();let o=hi(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);o=await fS(o);const s=o.render;if(typeof s!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);if(typeof n.registerWindow!="function")throw new Error("[openstation] wp.os.registerWindow is missing — the shell must boot before launching games.");const i=`os-game-${e}`,r=`game:${i}`,a=n.windowManager,l=a?.getByBaseId?.(i)??a?.getById(i);if(l){const m=l.config?.desktopId;m&&a?.switchDesktop&&m!==a?.getActiveDesktopId?.()&&a.switchDesktop(m),n.registerWindow({id:i,title:o.title,icon:o.icon,render:()=>{}});return}n.wallpaper?.suspend(r);let c=!1;const d=()=>{c||(c=!0,n.wallpaper?.resume(r))};let u=null;const f=()=>{u?.stop(),u=null};n.onWindow?.(i,{closed:()=>{f(),d()},minimized:()=>u?.pause(),restored:()=>u?.resume()});const p=(m,h)=>{n.activity?.publish("os/game-score-recorded",{game:e,score:m.score,meta:m.meta??{},windowId:i,challengeId:h})},g=m=>{if(t.challenge){const h=t.challenge.id;return tS(h,m,{windowId:i}).then(({challenge:b})=>{Ta([b]),p(m,h)})}return Zk(e,m,{windowId:i}).then(()=>p(m))};try{await n.registerWindow({id:i,title:o.title,icon:o.icon,width:o.window?.width??lS,height:o.window?.height??cS,minWidth:o.window?.minWidth??dS,minHeight:o.window?.minHeight??uS,render:m=>{const h={windowId:i,container:m,config:o.config??{},challenge:t.challenge,submitScore:g,close:()=>{n.windowManager?.getById(i)?.close()}};u=oS(e,{windowId:i});const b=s(h);return()=>{try{b?.()}finally{f(),d()}}}})}catch(m){throw f(),d(),m}}const Op={register:La,unregister:xp,list:Tp,get:hi,subscribe:qk,launch:Rp,getPlaytime:()=>Jk().then(e=>e.playtime)};function pS(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;Ik(r);const l=r.preview!==""||r.value!=="";if(l){try{hn(Lk(r))}catch(c){T(v.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:c}),di(r.id);return}n.add(r.id)}if(!l||t.state.wallpaper===r.id){const c=await gp(r.id);if(!l){if(!c){di(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(Of(r),di(r),n.delete(r),t.apply())};return async r=>{const a=new Set;for(const l of r)a.add(l.id);for(const l of Array.from(n))a.has(l)||i(l);for(const l of r)n.has(l.id)||await s(l)}}function hS(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??{},scriptUrl:e.scriptUrl,scriptTranslations:e.scriptTranslations,scriptL10n:e.scriptL10n,scriptBefore:e.scriptBefore,scriptAfter:e.scriptAfter}}function mS(){const e=new Set,t=o=>{try{const s=hi(o.id),i=hS(o);La(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)&&(xp(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 gS(e={}){const t=e.deactivate??(()=>va(""));return function(o){Jv(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=Hs().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const mi=new Map,Na=new Map;let Mp=!1;const Le={contribute(e,t){return mi.set(e,t),()=>{mi.get(e)===t&&mi.delete(e)}},subscribe(e,t){let n=Na.get(e);return n||(n=new Set,Na.set(e,n)),n.add(t),()=>{n.delete(t)}}};function wS(){if(Mp)return;Mp=!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 mi)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 Na){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 gi=null,wi={installHintDismissed:!1,notificationsEnabled:!1};const Da=new Set;function Pp(e){if(!e){gi=null;return}gi=e,wi={...e.state},$p()}function po(){return{...wi}}function Ra(e){if(wi={...wi,...e},$p(),!gi)return po();const t=JSON.stringify(e),n=yS();return fetch(gi.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)}),po()}function Wp(e){return Da.add(e),()=>{Da.delete(e)}}function $p(){const e=po();for(const t of Array.from(Da))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function yS(){return window.openStationConfig?.restNonce??""}const bS=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:po,initPwaState:Pp,subscribePwaState:Wp,updatePwaState:Ra},Symbol.toStringTag,{value:"Module"}));function Oa(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=Q({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=Up(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){Ra({notificationsEnabled:!0}),o=Up(t),o||r();return}r()}}),i)}function Up(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 vS(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&Ra({notificationsEnabled:!0}),e}function _S(){return typeof Notification>"u"?"unsupported":Notification.permission}function ES(e){return hi(e)?.title||e}const Fp=new Set,Bp=new Set;async function kS(e){const{challenge:t}=await eS(e.id);Ta([t]),await Rp(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function SS(e){const t=de(E("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,ES(e.game),String(e.scoreToBeat));Oa({title:E("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),Q({message:t,persistent:!0,dismissible:!0,action:{label:E("Accept & Play"),onClick:()=>{kS(e).catch(n=>{Q({message:n instanceof Error?n.message:E("Could not accept the challenge.")})})}}})}function AS(e){let t;e.result==="beaten"?t=E("%1$s beat your score: %2$s vs your %3$s."):t=E("%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));Oa({title:E("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),Q({message:n})}function CS(e){const{currentUserId:t}=e;if(!t)return;Le.contribute("openstation_games_subscribe",()=>({challengesVersion:sS().version})),Le.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&Ta(o.challenges)});const n=()=>{for(const o of aS())o.state==="pending"&&o.recipientId===t&&!Fp.has(o.id)&&(Fp.add(o.id),SS(o)),o.state==="completed"&&o.challengerId===t&&!Bp.has(o.id)&&(Bp.add(o.id),AS(o))};iS(n),n()}const Hp=/^[a-z0-9_/-]+$/,zp=le("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),Bt=zp.state.registry,IS=zp.state.listeners;function yi(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)"):Hp.test(n)||t.push(`slug (must match ${Hp} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.run!="function"&&t.push("run (must be a function)")),Ne("Command",t,e),Bt.set(n,{...e,slug:n}),Ma()}function Gp(e){Bt.delete(e.toLowerCase())&&Ma()}function bi(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Bt.entries()))o.owner===e&&(Bt.delete(n),t++);return t>0&&Ma(),t}function jp(){return Array.from(Bt.values())}function xS(){const e=[];for(const t of Bt.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function LS(e){return Bt.get(e.toLowerCase())??null}function Ma(){const e=Array.from(IS);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function TS(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(v.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.slug)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.slug)}return a},i=r=>{const a=new Set;for(const c of jp())c.owner===r&&a.add(c.slug);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))Gp(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Vp=le("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),ho=Vp.state.registry,NS=Vp.state.listeners;function qp(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}ho.set(t,{...e,id:t}),Pa()}function Kp(e){ho.delete(e.toLowerCase())&&Pa()}function DS(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ho.entries()))o.owner===e&&(ho.delete(n),t++);return t>0&&Pa(),t}function Yp(){return Array.from(ho.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Pa(){const e=Array.from(NS);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function RS(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(v.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{DS(r);const a=n.get(r);if(a){const l=new Set(Yp().map(c=>c.id));for(const c of a)l.has(c)&&Kp(c)}};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))l.has(c)||(i(c),e.delete(c));for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Xp=le("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),mo=Xp.state.registry,OS=Xp.state.listeners,Zp=/^[a-z0-9_/-]+$/;function vi(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):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.icon!="string"||e.icon.trim()==="")&&t.push("icon (missing)"),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)")),Ne("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();mo.set(n,{...e,id:n}),_i()}function MS(e){mo.delete(e.toLowerCase())&&_i()}function PS(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&&_i(),t}function WS(){return Array.from(mo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function _i(){const e=Array.from(OS);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"&&_i()});function $S(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(v.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(PS(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Jp=le("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),go=Jp.state.registry,US=Jp.state.listeners,Qp=/^[a-z0-9_/-]+$/;function Wa(){for(const e of Array.from(US))try{e()}catch{}}function FS(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Qp.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Qp} — 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)")),Ne("WindowAction",t,e);const n=e.id.trim().toLowerCase();go.set(n,{...e,id:n}),Wa()}function BS(e){go.delete(String(e||"").toLowerCase())&&Wa()}function HS(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&&Wa(),t}function zS(){return Array.from(go.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function GS(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(v.SHELL_ERROR,{scope:"window-action-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(HS(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const vn="none",$a="svg-splines",eh=le("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),wo=eh.state.registry,Ua=eh.state.listeners,th=/^[a-z0-9_/-]+$/;function nh(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())?e.id.trim().toLowerCase()===vn&&t.push('id ("none" is reserved)'):t.push(`id (must match ${th} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.mount!="function"&&t.push("mount (not a function)")),Ne("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();wo.set(n,{...e,id:n}),Ba()}function jS(e){wo.delete(e.toLowerCase())&&Ba()}function VS(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&&Ba(),t}function oh(){const e=Array.from(wo.values()),t=q(v.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function Fa(e){return oh().find(t=>t.id===e)}function qS(e){return Ua.add(e),()=>{Ua.delete(e)}}function Ba(){const e=Array.from(Ua);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}const KS=16;function YS(e,t){const n=t.map(i=>({start:Math.max(e.start,i.start),end:Math.min(e.end,i.end)})).filter(i=>i.end>i.start).sort((i,r)=>i.start-r.start),o=[];let s=e.start;for(const i of n)i.start>s&&o.push({start:s,end:i.start}),s=Math.max(s,i.end);return s<e.end&&o.push({start:s,end:e.end}),o}function XS(e,t){const n=e.x+e.width/2,o=e.y+e.height/2,s=t.x-n,i=t.y-o;if(s===0&&i===0)return{x:n,y:o,side:"right"};const r=s!==0?e.width/2/Math.abs(s):1/0,a=i!==0?e.height/2/Math.abs(i):1/0,l=Math.min(r,a),c=n+s*l,d=o+i*l;let u;return r<=a?u=s>0?"right":"left":u=i>0?"bottom":"top",{x:c,y:d,side:u}}function sh(e,t,n,o){for(const s of n)if(!(s.windowId===o||s.zIndex<=t)&&e.x>=s.rect.x&&e.x<=s.rect.x+s.rect.width&&e.y>=s.rect.y&&e.y<=s.rect.y+s.rect.height)return!1;return!0}function ZS(e,t,n,o,s){const i=n.filter(c=>c.windowId!==o&&c.zIndex>t),r=[{side:"top",base:{start:e.x,end:e.x+e.width},at:e.y,horizontal:!0},{side:"bottom",base:{start:e.x,end:e.x+e.width},at:e.y+e.height,horizontal:!0},{side:"left",base:{start:e.y,end:e.y+e.height},at:e.x,horizontal:!1},{side:"right",base:{start:e.y,end:e.y+e.height},at:e.x+e.width,horizontal:!1}];let a=null,l=1/0;for(const{side:c,base:d,at:u,horizontal:f}of r){const p=[];for(const{rect:g}of i)(f?g.y<=u&&u<=g.y+g.height:g.x<=u&&u<=g.x+g.width)&&p.push(f?{start:g.x,end:g.x+g.width}:{start:g.y,end:g.y+g.height});for(const g of YS(d,p)){if(g.end-g.start<KS)continue;const m=(g.start+g.end)/2,h=f?m:u,b=f?u:m,y=Math.hypot(s.x-h,s.y-b);y<l&&(l=y,a={x:h,y:b,side:c})}}return a}function JS(e,t){const n=Math.max(t.x-(e.x+e.width),e.x-(t.x+t.width)),o=Math.max(t.y-(e.y+e.height),e.y-(t.y+t.height));if(n<0&&o<0)return null;const s=Math.max(e.x,t.x),i=Math.min(e.x+e.width,t.x+t.width),r=Math.max(e.y,t.y),a=Math.min(e.y+e.height,t.y+t.height);let l,c;i>=s?l=c=(s+i)/2:t.x>e.x?(l=e.x+e.width,c=t.x):(l=e.x,c=t.x+t.width);let d,u;a>=r?d=u=(r+a)/2:t.y>e.y?(d=e.y+e.height,u=t.y):(d=e.y,u=t.y+t.height);const f=n>=o,p=(g,m,h)=>f?m<=g.x?"left":"right":h<=g.y?"top":"bottom";return{from:{x:l,y:d,side:p(e,l,d)},to:{x:c,y:u,side:p(t,c,u)}}}function ih(e,t){const n=Math.min(160,Math.max(24,.4*t));switch(e.side){case"left":return{x:e.x-n,y:e.y};case"right":return{x:e.x+n,y:e.y};case"top":return{x:e.x,y:e.y-n};default:return{x:e.x,y:e.y+n}}}function QS(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}const _n="http://www.w3.org/2000/svg";let eA=0;function rh(e,t,n,o,s){const i=XS(e,s);return t===null||sh(i,t,o,n)?i:ZS(e,t,o,n,s)??i}function tA(e,t){const n=document.createElementNS(_n,"defs"),o=(a,l,c)=>{const d=`${t}-${a}`,u=document.createElementNS(_n,"marker");u.setAttribute("id",d),u.setAttribute("viewBox","0 0 10 10"),u.setAttribute("refX","5"),u.setAttribute("refY","5"),u.setAttribute("markerWidth",c),u.setAttribute("markerHeight",c),u.setAttribute("markerUnits","strokeWidth");const f=document.createElementNS(_n,"circle");return f.setAttribute("cx","5"),f.setAttribute("cy","5"),f.setAttribute("r","4"),f.classList.add(l),u.appendChild(f),n.appendChild(u),d},s="os-window-link__endpoint",i=`${s}--active`,r={dot:{normal:o("dot",s,"7"),active:o("dot-active",i,"7")},port:{normal:o("port",s,"4.5"),active:o("port-active",i,"4.5")}};return e.appendChild(n),r}nh({id:"svg-splines",label:E("Splines"),description:E("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 t=++eA,n=(a,l)=>{const c=document.createElementNS(_n,"svg");return c.classList.add("os-window-links__svg"),a.appendChild(c),{svg:c,markers:tA(c,`os-window-link-${t}${l}`)}},o={base:n(e.container,""),elevated:n(e.elevatedContainer,"-elevated")},s=new Map,i=a=>{for(const{svg:c}of[o.base,o.elevated])c.setAttribute("width",String(a.container.width)),c.setAttribute("height",String(a.container.height)),c.setAttribute("viewBox",`0 0 ${a.container.width} ${a.container.height}`);const l=new Set;for(const c of a.edges){if(!c.from||!c.to)continue;const d=`${c.fromWindowId}→${c.toWindowId}:${c.kind}`;l.add(d);const u=c.elevated?"elevated":"base";let f=s.get(d);if(f&&f.surface!==u&&(f.group.remove(),s.delete(d),f=void 0),!f){const P=document.createElementNS(_n,"g");P.classList.add("os-window-link");const W=document.createElementNS(_n,"path");W.classList.add("os-window-link__path"),P.appendChild(W),o[u].svg.appendChild(P),f={group:P,path:W,surface:u},s.set(d,f)}const p=a.obstacles??[],g=JS(c.from,c.to),m=(P,W,_)=>W===null||sh(P,W,p,_);let h=null;g&&m(g.from,c.fromZIndex,c.fromWindowId)&&(h=g.from),h||(h=rh(c.from,c.fromZIndex,c.fromWindowId,p,g?{x:g.to.x,y:g.to.y}:QS(c.to)));let b=null;g&&m(g.to,c.toZIndex,c.toWindowId)&&(b=g.to),b||(b=rh(c.to,c.toZIndex,c.toWindowId,p,{x:h.x,y:h.y}));const y=Math.hypot(b.x-h.x,b.y-h.y),I=ih(h,y),R=ih(b,y);f.path.setAttribute("d",`M ${h.x} ${h.y} C ${I.x} ${I.y}, ${R.x} ${R.y}, ${b.x} ${b.y}`);const k=o[f.surface].markers,M=c.focused?"active":"normal";f.path.setAttribute("marker-end",`url(#${k.dot[M]})`),f.path.setAttribute("marker-start",`url(#${c.bidirectional?k.dot[M]:k.port[M]})`),f.group.classList.toggle("os-window-link--active",c.focused)}for(const[c,d]of Array.from(s))l.has(c)||(d.group.remove(),s.delete(c))},r=e.onFrame(i);return i(e.getFrame()),()=>{r(),s.clear(),o.base.svg.remove(),o.elevated.svg.remove()}}});const ah="os-window-links",lh="os-window--linked",ch="os-window-links--visible";let dh=!1;function nA({manager:e,osSettings:t}){if(dh)return;dh=!0;let n=t.getOsSettingsSnapshot(),o=null,s=null,i=null,r=null,a=0;const l=new Set;let c=!1;const d=new Set;let u=!1;const f=A=>{const C=A.element;return!C||!C.isConnected||A.state==="minimized"||C.offsetParent===null?null:{x:C.offsetLeft,y:C.offsetTop,width:C.offsetWidth,height:C.offsetHeight}},p=A=>A.state==="snapped-left"||A.state==="snapped-right"?null:f(A),g=()=>{const A=[];for(const x of ei()){if(x.rootWindowIds.length===0||x.children.length===0)continue;const F=[],N=(U,B,H)=>{const O=e.getById(U);!O||!H||F.push({windowId:U,role:B,content:H,rect:p(O),focused:O.isFocused(),state:O.state})};for(const U of x.rootWindowIds)N(U,"root",ct(U));for(const U of x.children)N(U.windowId,"child",U.content);F.length>0&&A.push({key:x.key,root:x.root,members:F})}const C=x=>{const F=Number.parseInt(x.element?.style.zIndex||"",10);return Number.isFinite(F)?F:null},$=e.getFocused()?.id??null,X=[];for(const x of co()){const F=e.getById(x.fromWindowId),N=e.getById(x.toWindowId);if(!F||!N)continue;const U=F.isFocused()||N.isFocused();X.push({fromWindowId:x.fromWindowId,toWindowId:x.toWindowId,kind:x.kind,bidirectional:x.bidirectional,focused:U,from:p(F),to:p(N),fromZIndex:C(F),toZIndex:C(N),elevated:$!==null&&(x.fromWindowId===$||x.toWindowId===$)})}const Z=[];for(const x of e.getAll()){const F=f(x);F&&Z.push({windowId:x.id,rect:F,zIndex:C(x)??0})}return{groups:A,edges:X,obstacles:Z,container:{width:o?.offsetWidth??0,height:o?.offsetHeight??0}}},m=()=>{c||l.size===0||(c=!0,requestAnimationFrame(()=>{if(c=!1,!i)return;const A=g();for(const C of Array.from(l))try{C(A)}catch($){typeof console<"u"&&console.error("[openstation] window-link frame subscriber threw:",$)}}))},h=()=>{if(o&&o.isConnected&&s?.isConnected)return o;const A=document.getElementById("os-area");if(!A)return null;o=document.createElement("div"),o.id=ah,o.className="os-window-links",o.setAttribute("aria-hidden","true"),s=document.createElement("div"),s.id=`${ah}-elevated`,s.className="os-window-links os-window-links--elevated",s.setAttribute("aria-hidden","true");const C=document.getElementById("os-widgets");return C&&C.parentElement===A?(C.insertAdjacentElement("afterend",s),C.insertAdjacentElement("afterend",o)):A.prepend(o,s),o},b=()=>co().length>0,y=()=>{let A=n.windowLinkRenderer||$a;return A=q(v.WINDOW_LINK_RENDERER,A),A===vn?vn:Fa(A)?A:Fa($a)?$a:vn},I=()=>{if(a++,l.clear(),c=!1,r){try{r()}catch(A){T(v.SHELL_ERROR,{scope:"window-link-renderer-teardown",error:A})}r=null}i=null,o?.replaceChildren(),s?.replaceChildren()},R=A=>{const C=Fa(A),$=h();if(!C||!$||!s)return;i=A;const X=++a,Z={container:$,elevatedContainer:s,getFrame:g,onFrame:x=>(l.add(x),()=>{l.delete(x)})};try{const x=C.mount(Z);x instanceof Promise?x.then(F=>{if(X!==a){typeof F=="function"&&F();return}typeof F=="function"&&(r=F)}).catch(F=>{T(v.SHELL_ERROR,{scope:"window-link-renderer-mount",error:F}),X===a&&(i=null)}):typeof x=="function"&&(r=x)}catch(x){T(v.SHELL_ERROR,{scope:"window-link-renderer-mount",error:x}),i=null}m()},k=()=>{const A=e.getFocused();return A?new Set(Nf(A.id)):new Set},M=()=>n.windowLinksEnabled!==!1,P=()=>{if(!o)return;const A=!u&&M()&&(n.windowLinkVisibility==="always"||n.windowLinkVisibility==="focus"&&k().size>0);o.classList.toggle(ch,A),s?.classList.toggle(ch,A)},W=()=>{if(!M()||n.windowLinkRaiseOnFocus===!1||n.windowLinkVisibility==="off")return;const A=e.getFocused();if(A)for(const C of i0(A.id)){const $=e.getById(C);$&&$.state!=="minimized"&&e.raise(C)}},_=()=>{if(!s)return;const A=e.getFocused(),C=k();if(!A||C.size===0||!M()||n.windowLinkVisibility==="off"){s.style.zIndex="";return}let $=-1/0;for(const X of[A.id,...C]){const Z=e.getById(X),x=Z?.element;if(!x||Z.state==="minimized")continue;const F=Number.parseInt(x.style.zIndex||"",10);Number.isFinite(F)&&($=Math.max($,F))}s.style.zIndex=Number.isFinite($)?String($):""},w=()=>{const A=M()&&n.windowLinkHighlight!==!1&&n.windowLinkVisibility!=="off"?k():new Set;for(const C of d)A.has(C)||e.getById(C)?.element?.classList.remove(lh);for(const C of A)e.getById(C)?.element?.classList.add(lh);d.clear();for(const C of A)d.add(C)},L=()=>{const A=M()&&n.windowLinkVisibility!=="off"&&b()?y():vn;A===vn?i&&I():A!==i&&(I(),R(A)),P(),w(),_(),m()};Y(v.WINDOW_BOUNDS_CHANGED,"desktop-mode/window-links-frame",()=>m());for(const A of[v.WINDOW_MOVED,v.WINDOW_RESIZED,v.WINDOW_MINIMIZED,v.WINDOW_RESTORED,v.WINDOW_MAXIMIZED,v.WINDOW_UNMAXIMIZED,v.WINDOW_FULLSCREEN_ENTERED,v.WINDOW_FULLSCREEN_EXITED,v.SNAP_ZONE_COMMITTED,v.SNAP_SPLIT_FILLED,v.DESKTOP_SWITCHED,v.SHELL_RESIZED])Y(A,"desktop-mode/window-links-frame",()=>m());Y(v.WINDOW_FOCUSED,"desktop-mode/window-links-focus",()=>{W(),P(),w(),_(),m()}),Y(v.WINDOW_BLURRED,"desktop-mode/window-links-blur",()=>{P(),w(),_(),m()}),Y(v.OVERVIEW_ENTERING,"desktop-mode/window-links-overview",()=>{u=!0,P()}),Y(v.OVERVIEW_EXITED,"desktop-mode/window-links-overview",()=>{u=!1,P(),m()}),Df(L),qS(L),t.subscribeOsSettings(A=>{const C=A.windowLinkRenderer!==n.windowLinkRenderer,$=C||A.windowLinkVisibility!==n.windowLinkVisibility||A.windowLinksEnabled!==n.windowLinksEnabled||A.windowLinkRaiseOnFocus!==n.windowLinkRaiseOnFocus||A.windowLinkHighlight!==n.windowLinkHighlight;n=A,$&&(C&&i&&I(),L())}),L()}function uh(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function oA({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)=>uh(r[0])-uh(a[0])),i=[];for(const[,r]of s){const a=r.find(l=>typeof l.groupLabel=="string"&&l.groupLabel!=="")?.groupLabel;if(a){const l=document.createElement("div");l.className="os-window__related-group",l.setAttribute("role","presentation"),l.textContent=a,n.appendChild(l)}for(const l of r){const c=document.createElement("os-menu-item");c.setAttribute("role","menuitem"),c.setAttribute("value",l.id),c.tabIndex=-1,l.icon&&c.setAttribute("icon",l.icon),c.classList.add("os-window__related-item"),c.textContent=typeof l.count=="number"?`${l.label} (${l.count})`:l.label,c.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),t(l)}),i.push(c),n.appendChild(c)}}return n.addEventListener("keydown",r=>{const a=r,l=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const c=a.key==="ArrowDown";let d=i[c?0:i.length-1];l!==-1&&(d=i[(l+(c?1:-1)+i.length)%i.length]),d?.focus()}else if(a.key==="Home"||a.key==="End")a.preventDefault(),a.stopPropagation(),i[a.key==="Home"?0:i.length-1]?.focus();else if(a.key==="Enter"||a.key===" "){const c=i[l];c&&(a.preventDefault(),a.stopPropagation(),c.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function fh(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 ph(e){const t=ct(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=q(v.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(fh):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(fh))}function Ha(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function sA(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function iA(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=ph(t.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",a),l.remove(),e.setAttribute("aria-expanded","false")},a=c=>{c.key==="Escape"&&(c.stopPropagation(),r(),e.focus())},l=oA({items:s,onPick:c=>{r(),sA(o),n(c)}});l._wpdRelatedClose=r,o.appendChild(l),o.addEventListener("keydown",a),e.setAttribute("aria-expanded","true"),i=c=>{const d=c.target;!d||l.contains(d)||e.contains(d)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),l.querySelector('[role="menuitem"]')?.focus()}function rA({manager:e,openUrl:t}){vi({id:"desktop-mode/related-entities",label:E("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>ph(n.id).length>0,render:(n,o)=>{Ha(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")){Ha(o.element);return}iA(n,o,t)})}}),Y(v.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(Ha(o.element),o.renderCustomTitleBarButtons?.())})}const za="os-broadcast",hh="os-broadcast",mh=window.location.origin;let Ga=null;function aA(e){Ga=e}function ja(e,t){const n=String(q("os.broadcast.topic",e,{payload:t})??e),o=q("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(za,{detail:s})),T(v.BROADCAST,s),Ee.publish(n,o),!Ga)return;const i={type:hh,topic:n,payload:o};for(const r of Ga._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,mh)}catch{}}}function En(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(v.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(za,n),()=>document.removeEventListener(za,n)}function lA(){window.addEventListener("message",e=>{if(e.origin!==mh)return;const t=e.data;!t||t.type!==hh||t._fromParent||typeof t.topic=="string"&&ja(t.topic,t.payload)})}const cA=new Set(["saved","no-editor","not-dirty","error"]);let gh=0;function wh(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function dA(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});gh+=1;const o=`os-editor-preview-${Date.now()}-${gh}`;return new Promise(s=>{let i=null,r=!1;const a=c=>{r||(r=!0,window.removeEventListener("message",l),i!==null&&window.clearTimeout(i),s(c))},l=c=>{if(c.origin!==window.location.origin)return;const d=c?.data;if(!d||typeof d!="object"||d.type!=="os-editor-autosave-response"||d.requestId!==o)return;const u=typeof d.status=="string"&&cA.has(d.status)?d.status:"error",f=wh(d.previewUrl);a(f?{status:u,previewUrl:f}:{status:u})};window.addEventListener("message",l),i=window.setTimeout(()=>a({status:"timeout"}),t);try{n.postMessage({type:"os-editor-autosave-request",requestId:o},window.location.origin)}catch{a({status:"no-editor"})}})}const Oe=le("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),uA=400,yh=1500;function yo(e){return e?`${e.type}:${e.id}`:""}function fA(e){for(const t of Oe.state.pairings.values())if(t.previewWindowId===e)return t}function pA(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function hA(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 Ei(e,t,n,o){Oe.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(vh(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(v.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function Va(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||ct(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?.()},uA)}function mA(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=En(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||Va(e,t)})}let bh=0;function vh(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 _h(e,t,n){vh(e,t);const o=q(v.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:yh},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;bh+=1;const i=`${t.previewWindowId}-watch-${bh}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:yh},window.location.origin),t.watchId=i}catch{}}let gA=dA;async function wA(e,t){const n=Oe.state.pairings.get(t.id);if(n){Ei(e,n,"toggled","close");return}if(Oe.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=ct(t.id);if(!o?.previewUrl){Q({message:E("No preview is available for this content.")});return}Oe.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=pA();s||t.applySnap?.("left");const i=gA(t);i.then(f=>{f.status==="error"&&Q({message:E("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{Oe.state.busyEditors.delete(t.id),e.getById(t.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=E("Preview");o.label&&(a=de(E("Preview: %s"),o.label));let l={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=q(v.EDITOR_PREVIEW_WINDOW_CONFIG,l,{editorWindowId:t.id,content:o});if(c&&typeof c=="object"&&typeof c.id=="string"&&c.id!==""&&typeof c.url=="string"&&c.url!==""?l=c:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await e.open(l),!e.getById(t.id)||yo(ct(t.id))!==yo(o)){e.getById(l.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:l.id,postKey:yo(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};mA(e,d,o),_h(e,d,o),Oe.state.pairings.set(t.id,d);const u={editorWindowId:t.id,previewWindowId:l.id,content:o};document.dispatchEvent(new CustomEvent("os-editor-preview-opened",{detail:u})),T(v.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Oe.state.pairings.get(t.id)===d&&f.status==="saved"&&Va(e,d,f.previewUrl)})}function yA({manager:e}){vi({id:"desktop-mode/editor-preview",label:E("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!ct(t.id)?.previewUrl||hA(t)),render:(t,n)=>{if(!ct(n.id)?.previewUrl){const i=E("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(),Q({message:E("The preview opens once the post has been saved.")})});return}const o=Oe.state.pairings.has(n.id),s=Oe.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(),wA(e,n)})}}),Y(v.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);n&&yo(t.content)!==n.postKey&&Ei(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),Y(v.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);if(n){Ei(e,n,"editor-closed","destroy");return}const o=fA(t.windowId);o&&Ei(e,o,"preview-closed","none")}),Y(v.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);if(n){const o=ct(t.windowId);o&&yo(o)===n.postKey&&_h(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 Oe.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){Va(e,o,wh(n.previewUrl));return}}})}const Eh="none",kh=le("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),bo=kh.state.registry,qa=kh.state.listeners,Sh=/^[a-z0-9_/-]+$/;function ki(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Sh.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===Eh&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Sh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.className!="string"&&typeof e.apply!="function"&&t.push("className|apply (at least one must be provided — a CSS class to toggle or an apply callback)")),Ne("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();bo.set(n,{...e,id:n}),Ya()}function bA(e){bo.delete(e.toLowerCase())&&Ya()}function vA(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(bo.entries()))o.owner===e&&(bo.delete(n),t++);return t>0&&Ya(),t}function Ka(){const e=Array.from(bo.values()),t=q(v.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function Ah(e){return Ka().find(t=>t.id===e)}function _A(e){return qa.add(e),()=>{qa.delete(e)}}function Ya(){const e=Array.from(qa);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}ki({id:"darken",label:E("Darken"),description:E("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),ki({id:"frost",label:E("Frost"),description:E("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"}),ki({id:"grayscale",label:E("Grayscale"),description:E("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 EA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(v.SHELL_ERROR,{scope:"unfocus-effect-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(vA(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function kA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(v.SHELL_ERROR,{scope:"window-link-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(VS(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Xa="data-desktop-unfocus-effect",Za="data-desktop-unfocus-effect-class";let Ch=!1;function SA(e){return e.querySelector("canvas")!==null}function AA({manager:e,osSettings:t}){if(Ch)return;Ch=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(Za);l&&(r.classList.remove(l),r.removeAttribute(Za));const c=r.getAttribute(Xa);c&&Ah(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(Xa)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Za,a.className)),r.setAttribute(Xa,a.id),a.apply?.(r)},i=()=>{const r=n===Eh?void 0:Ah(n),a=Ka();for(const l of e.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(SA(c)||s(c,r)))}};for(const r of["os-window-opened","os-window-reopened","os-window-closed","os-window-focused","os-window-blurred"])document.addEventListener(r,()=>i());t.subscribeOsSettings(r=>{n=r.unfocusEffect,i()}),_A(()=>i()),i()}function CA(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await ke(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){T(v.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(lv(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function Ih(e){return e.startsWith("dashicons-")?e:"dashicons-admin-generic"}function IA(e,t){if(t.url&&gn(t.url)||t.url&&Ge(t.url))return;const n=ce(t.url,e.adminUrl);e.windowManager.open({id:n,baseId:n,url:t.url,parentUrl:t.url,title:t.title,icon:Ih(t.icon),submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}function xA(e,t,n){gn(n.url)||Ge(n.url)||e.windowManager.open({id:ce(n.url,e.adminUrl),baseId:ce(t.url,e.adminUrl),url:n.url,parentUrl:t.url,title:t.title,icon:Ih(t.icon),submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}const LA=130,TA=240,NA=160,Si=14,xh=18,St=12,DA=160,RA="os-constellation-open",Ai=e=>e.dataset.menuSlug??e.dataset.constellationId??"",Ja=e=>{const t=e.closest(".os-dock")?.getAttribute("data-os-dock-placement");return t==="left"?"right":t==="right"?"left":"top"},OA={top:"ArrowUp",right:"ArrowRight",left:"ArrowLeft"};function MA(){return typeof window.matchMedia=="function"&&window.matchMedia("( prefers-reduced-motion: reduce )").matches}function PA(e){let t=null,n=null,o="",s=null,i=null;const r=()=>{s!==null&&(window.clearTimeout(s),s=null)},a=()=>{i!==null&&(window.clearTimeout(i),i=null)},l=I=>{if(!(I instanceof Element))return null;const R=I.closest(".os-dock__item");return!R||!Ai(R)||!R.closest(".os-dock")?null:R},c=new Set,d=()=>{document.body.classList.toggle(RA,t!==null||c.size>0)},u=(I,R={})=>{if(!t)return;const k=n,M=t;t=null,n=null,o="",k?.removeAttribute("data-constellation-open"),I==="cut"||MA()?M.remove():(M.classList.remove("os-constellation--open"),M.classList.add("os-constellation--closing"),c.add(M),window.setTimeout(()=>{M.remove(),c.delete(M),d()},NA)),d(),R.restoreFocus&&k&&k.querySelector(".os-dock__item-primary")?.focus(),T(v.CONSTELLATION_CLOSED,{menuSlug:k?Ai(k):"",handoff:R.handoff===!0})},f=(I=!1,R=!1)=>{r(),a(),u(R?"cut":"exit",{restoreFocus:I})},p=(I,R=!1)=>{r(),a();const k=Ai(I);if(t&&o===k){R&&kn(t,0);return}const M=WA(e,I);if(!M){f();return}const P=t!==null;u("exit",{handoff:P});const W=$A(e,M);t=FA(e,M,W,I,f);for(const _ of Qa(t))_.tabIndex=-1;n=I,o=k,t.dataset.osCnSide=Ja(I),document.body.appendChild(t),d(),I.setAttribute("data-constellation-open",""),qA(t),KA(t,I),requestAnimationFrame(()=>{t?.classList.add("os-constellation--open"),R&&t&&kn(t,0)}),T(v.CONSTELLATION_OPENED,{menuSlug:k,item:M,instances:W,handoff:P})},g=I=>{if(I.pointerType&&I.pointerType!=="mouse")return;if(t&&I.target instanceof Node&&t.contains(I.target)){a();return}const R=l(I.target);R&&(a(),!(t&&o===Ai(R))&&(r(),s=window.setTimeout(()=>{s=null,p(R)},t?0:LA)))},m=I=>{const R=I.relatedTarget;R instanceof Node&&(t&&t.contains(R)||n&&n.contains(R)||l(R))||(r(),a(),i=window.setTimeout(()=>{i=null,f()},TA))},h=I=>{if(t&&I.target instanceof Node&&t.contains(I.target)){const k=Qa(t),M=k.indexOf(I.target);I.key==="Escape"?(I.preventDefault(),f(!0)):I.key==="ArrowDown"?(I.preventDefault(),kn(t,M+1)):I.key==="ArrowUp"?(I.preventDefault(),M<=0?f(!0):kn(t,M-1)):I.key==="Home"?(I.preventDefault(),kn(t,0)):I.key==="End"?(I.preventDefault(),kn(t,k.length-1)):I.key==="Tab"&&f(!0);return}const R=l(I.target);R&&(I.key===OA[Ja(R)]?(I.preventDefault(),p(R,!0)):I.key==="Escape"&&f())},b=()=>f(!1,!0),y=I=>{!t||!(I.target instanceof Element)||t.contains(I.target)||I.target.closest(".os-dock__item")&&f()};return document.body.setAttribute(ha,""),document.addEventListener("pointerover",g),document.addEventListener("pointerout",m),document.addEventListener("click",y),document.addEventListener("keydown",h),window.addEventListener("resize",b),window.addEventListener("blur",b),document.addEventListener("os-layout-changed",b),document.addEventListener(oi,b),document.addEventListener("scroll",b,!0),()=>{f(!1,!0);for(const I of c)I.remove();c.clear(),d(),document.body.removeAttribute(ha),document.removeEventListener(oi,b),document.removeEventListener("pointerover",g),document.removeEventListener("pointerout",m),document.removeEventListener("click",y),document.removeEventListener("keydown",h),window.removeEventListener("resize",b),window.removeEventListener("blur",b),document.removeEventListener("os-layout-changed",b),document.removeEventListener("scroll",b,!0)}}function WA(e,t){const n=t.dataset.menuSlug;if(n){const i=e.getMenuItems().find(a=>a.id===n);if(!i)return null;const r=i.selfLabel?[{title:i.selfLabel,url:i.url},...i.submenu]:i.submenu;return{id:i.id,title:i.title,icon:i.icon,submenu:r,menuItem:i}}const o=t.dataset.constellationId;if(!o)return null;const s=e.getSystemItem?.(o);return s?.submenu?.length?{id:s.id,title:s.title,icon:s.icon,submenu:s.submenu,menuItem:null}:null}function $A(e,t){const n=new Set;if(t.menuItem){const o=UA(e,t.menuItem);for(const i of e.windowManager.getAllByBaseIdOnActiveDesktop(o))n.add(i);const s=ce(t.menuItem.url,e.adminUrl);if(s){const i=e.windowManager.getActiveDesktopId();for(const r of e.windowManager.getAll())(r.config.desktopId||i)===i&&r.config.parentUrl&&ce(r.config.parentUrl,e.adminUrl)===s&&n.add(r)}return Array.from(n)}for(const o of t.submenu)if(o.windowId)for(const s of e.windowManager.getAllByBaseIdOnActiveDesktop(o.windowId))n.add(s);return Array.from(n)}function UA(e,t){return t.windowId?t.windowId:ce(t.url,e.adminUrl)}function FA(e,t,n,o,s){const i=document.createElement("div");i.className="os-constellation",i.setAttribute("role","menu"),i.setAttribute("aria-label",de(E("%s menu"),t.title)),i.style.setProperty("--os-cn-hue",String(mn(t.title)));const r=document.createElement("div");r.className="os-constellation__surface",i.appendChild(r),r.appendChild(BA(e,t,s));let a=0;const l=()=>a++;n.length>0&&r.appendChild(HA(e,t,n,s,l)),t.submenu.length>0&&r.appendChild(zA(e,t,s,l)),r.addEventListener("pointermove",f=>{const p=r.getBoundingClientRect();!p.width||!p.height||(r.style.setProperty("--os-cn-x",`${(f.clientX-p.left)/p.width*100}%`),r.style.setProperty("--os-cn-y",`${(f.clientY-p.top)/p.height*100}%`))});const c=document.createElement("span");c.className="os-constellation__sheen",c.setAttribute("aria-hidden","true"),i.appendChild(c);const d=document.createElement("span");d.className="os-constellation__beam",d.setAttribute("aria-hidden","true"),i.appendChild(d);const u={item:t,instances:n,tile:o};return q(v.CONSTELLATION_PANEL,i,u)}function BA(e,t,n){const o=document.createElement("button");o.type="button",o.className="os-constellation__head os-constellation__row",o.setAttribute("role","menuitem");const s=document.createElement("span");s.className="os-constellation__head-icon",s.setAttribute("aria-hidden","true"),s.appendChild(jA(t.icon)),o.appendChild(s);const i=document.createElement("span");i.className="os-constellation__head-text";const r=document.createElement("span");return r.className="os-constellation__head-title",r.textContent=t.title,i.appendChild(r),o.appendChild(i),o.addEventListener("click",()=>{if(n(),t.menuItem){IA(e,t.menuItem);return}Lh(e,t,t.submenu[0])}),o}function Lh(e,t,n){if(n){if(n.onSelect){n.onSelect();return}if(t.menuItem){xA(e,t.menuItem,n);return}n.url&&window.open(n.url,"_blank","noopener,noreferrer")}}function HA(e,t,n,o,s){const i=document.createElement("div");i.className="os-constellation__group os-constellation__group--live",i.setAttribute("role","group"),i.setAttribute("aria-label",E("Open windows")),i.appendChild(Th(de(sn("%d open window","%d open windows",n.length),n.length)));for(const r of n){const a=document.createElement("button");a.type="button",a.className="os-constellation__row os-constellation__row--live",a.setAttribute("role","menuitem"),a.style.setProperty("--os-cn-row",String(s())),r.state==="minimized"&&(a.dataset.state="minimized");const l=document.createElement("span");l.className="os-constellation__pip",l.setAttribute("aria-hidden","true"),a.appendChild(l);const c=document.createElement("span");c.className="os-constellation__row-label",c.textContent=r.config.title||t.title,a.appendChild(c);const d=document.createElement("span");d.className="os-constellation__row-meta",d.textContent=r.state==="minimized"?E("Minimized"):E("Open"),a.appendChild(d),a.addEventListener("click",()=>{o(),r.state==="minimized"&&r.restore(),e.windowManager.focus(r)}),i.appendChild(a)}return i}function zA(e,t,n,o){const s=document.createElement("div");s.className="os-constellation__group",s.setAttribute("role","group"),s.setAttribute("aria-label",t.title),s.appendChild(Th(E("Open")));for(const i of t.submenu)s.appendChild(GA(e,t,i,n,o()));return s}function GA(e,t,n,o,s){const i=document.createElement("button");i.type="button",i.className="os-constellation__row os-constellation__row--sub",i.setAttribute("role","menuitem"),i.style.setProperty("--os-cn-row",String(s)),i.style.setProperty("--os-cn-row-hue",String(mn(n.title)));const r=document.createElement("span");r.className="os-constellation__orbit",r.setAttribute("aria-hidden","true"),i.appendChild(r);const a=document.createElement("span");if(a.className="os-constellation__row-label",a.textContent=n.title,i.appendChild(a),n.offSite){const l=document.createElement("span");l.className="dashicons dashicons-external os-constellation__row-offsite",l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-constellation__row-note",c.textContent=E("(opens in a new tab)"),i.appendChild(c)}return i.addEventListener("click",()=>{o(),Lh(e,t,n)}),i}function Th(e){const t=document.createElement("span");return t.className="os-constellation__legend",t.textContent=e,t}function jA(e){if(!e.startsWith("dashicons-")){const n=document.createElement("span");if(n.className="os-constellation__head-art",uo(n,e,"currentColor"))return n}const t=document.createElement("span");return t.className="dashicons",t.classList.add(e.startsWith("dashicons-")?hd(e):"dashicons-admin-generic"),t}function Qa(e){return Array.from(e.querySelectorAll(".os-constellation__row"))}function kn(e,t){const n=Qa(e);if(n.length===0)return;const o=Math.max(0,Math.min(n.length-1,t));n[o].focus()}const VA=["--wp-admin-theme-color","--os-titlebar-bg-focused","--os-titlebar-color-focused"];function qA(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of VA){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function KA(e,t){const n=t.getBoundingClientRect(),o=Ja(t),s=o==="top"?n.top-Si-St:window.innerHeight-St*2;if(e.style.setProperty("--os-cn-max-h",`${Math.max(DA,s)}px`),o!=="top"){e.style.left=o==="right"?`${n.right+Si}px`:`${n.left-Si}px`;const i=e.offsetHeight,r=window.innerHeight,a=Math.max(St,Math.min(n.top,r-St-i));e.style.top=`${a}px`;const l=Math.max(xh,Math.min(n.top+n.height/2-a,i-xh));e.style.setProperty("--os-cn-beam-y",`${l}px`);return}e.style.left=`${n.left+n.width/2}px`,e.style.top=`${n.top-Si}px`,requestAnimationFrame(()=>{const i=e.getBoundingClientRect(),r=window.innerWidth;let a=0;i.left<St?a=St-i.left:i.right>r-St&&(a=r-St-i.right),a!==0&&(e.style.setProperty("--os-cn-shift",`${a}px`),e.style.setProperty("--os-cn-beam-x",`${-a}px`))})}const Nh=le("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),vo=Nh.state.registry,YA=Nh.state.listeners,Dh=/^[a-z0-9_/-]+$/;function Rh(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)"):Dh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Dh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!e.tokens||typeof e.tokens!="object")t.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(e.tokens))if(!o.startsWith("--")){t.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof e.match!="function"&&t.push("match (must be a function)")}Ne("WindowTheme",t,e);const n=e.id.trim().toLowerCase();vo.set(n,{...e,id:n}),el()}function Oh(e){vo.delete(e.toLowerCase())&&el()}function XA(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&&el(),t}function Mh(){return Array.from(vo.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function el(){const e=Array.from(YA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function ZA(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async l=>{if(!l.scriptUrl||t.has(l.scriptUrl)){e.add(l.handle);return}try{await ke(l.scriptUrl,{translations:l.scriptTranslations,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){T(v.SHELL_ERROR,{scope:"window-theme-script-load",handle:l.handle,url:l.scriptUrl,error:c});return}t.add(l.scriptUrl),e.add(l.handle)},i=l=>{const c=new Map;if(!l)return c;for(const d of l){if(!d.scriptHandle||!d.id)continue;let u=c.get(d.scriptHandle);u||(u=new Set,c.set(d.scriptHandle,u)),u.add(d.id)}return c},r=l=>{const c=new Set;for(const u of Mh())u.owner===l&&c.add(u.id);const d=n.get(l);if(d)for(const u of d)c.add(u);return c},a=l=>{if(l){for(const c of l)if(!(!c.id||!c.tokens))try{Rh({id:c.id,label:c.label,tokens:c.tokens,priority:c.priority,match:()=>!0,owner:c.scriptHandle||void 0}),o.add(c.id)}catch(d){T(v.SHELL_ERROR,{scope:"window-theme-shell-register",id:c.id,error:d})}}};return async(l,c)=>{const d=new Set;for(const u of l)u.handle&&d.add(u.handle);for(const u of Array.from(e)){if(d.has(u))continue;const f=r(u);for(const p of f)Oh(p),o.delete(p);XA(u),e.delete(u)}a(c);for(const u of l)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const Ph=le("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),_o=Ph.state.registry,JA=Ph.state.listeners,Wh=/^[a-z0-9_/-]+$/;function Eo(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Wh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Wh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)"),typeof e.render!="function"&&(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (required when render is omitted)"),typeof e.match!="function"&&t.push("match (must be a function)"),e.placement!==void 0&&e.placement!=="left"&&e.placement!=="right"&&e.placement!=="controls"&&t.push('placement (must be "left", "right", or "controls")')),Ne("WindowControl",t,e);const n=e.id.trim().toLowerCase();_o.set(n,{...e,id:n}),tl()}function $h(e){_o.delete(e.toLowerCase())&&tl()}function QA(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&&tl(),t}function Uh(){return Array.from(_o.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function tl(){const e=Array.from(JA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function eC(){Eo({id:"core/minimize",label:E("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),Eo({id:"core/maximize",label:E("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),Eo({id:"core/focus-tab",label:E("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),Eo({id:"core/close",label:E("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function tC(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(v.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of Uh())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))$h(d);QA(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Fh=le("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),ko=Fh.state.registry,nC=Fh.state.listeners,Bh=/^[a-z0-9_/-]+$/,Hh=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function zh(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Bh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Bh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):Hh.has(e.slot)||t.push(`slot (must be one of ${Array.from(Hh).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Ne("WindowSlot",t,e);const n=e.id.trim().toLowerCase();ko.set(n,{...e,id:n}),ol()}function nl(e){ko.delete(e.toLowerCase())&&ol()}function oC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ko.entries()))o.owner===e&&(ko.delete(n),t++);return t>0&&ol(),t}function Gh(){return Array.from(ko.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function ol(){const e=Array.from(nC);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function sC(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(v.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of Gh())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))nl(d);oC(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const iC="desktop-mode-notice-dismissed";function rC(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function jh(){return`${iC}:${rC()}`}function sl(){try{const e=window.localStorage.getItem(jh());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function Vh(e){try{window.localStorage.setItem(jh(),JSON.stringify(e))}catch{}}function Ci(e){return e?sl()[e]===!0:!1}function Ii(e){if(!e)return;const t=sl();t[e]=!0,Vh(t)}function qh(e){if(!e)return;const t=sl();t[e]&&(delete t[e],Vh(t))}const aC=ue`:host{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:10px 14px;font:var( --os-ui-notice-font,13px/1.5 var( --os-font,system-ui ) );color:var( --os-ui-notice-color,var( --os-ui-fg,#1d2327 ) );background:var( --os-ui-notice-bg,var( --os-ui-hover,rgba( 0,0,0,0.04 ) ) );border-block-end:1px solid var( --os-ui-notice-border,var( --os-ui-border,rgba( 0,0,0,0.08 ) ) );border-inline-start:4px solid var( --os-ui-notice-accent,var( --os-ui-border,#646970 ) )}:host( [ hidden ] ){display:none}.os-notice__icon{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:var( --os-ui-notice-accent,var( --os-ui-accent,#646970 ) )}.os-notice__icon[ hidden ]{display:none}.os-notice__label{flex:1;min-width:0;word-wrap:break-word}::slotted( a ){color:var( --os-ui-notice-link,var( --wp-admin-theme-color,#2271b1 ) );border-radius:2px}::slotted( a:hover ),::slotted( a:focus-visible ){color:var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) )}::slotted( a:focus-visible ){outline:2px solid var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) );outline-offset:2px}::slotted( p:first-child ){margin-block-start:0}::slotted( p:last-child ){margin-block-end:0}.os-notice__close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;background:transparent;color:inherit;opacity:0.6;cursor:pointer;border-radius:4px;transition:opacity 0.12s ease,background-color 0.12s ease}.os-notice__close:hover{opacity:1;background:var( --os-ui-hover,rgba( 0,0,0,0.06 ) )}.os-notice__close:focus-visible{opacity:1;outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:1px}.os-notice__close[ hidden ]{display:none}.os-notice__close svg{width:14px;height:14px}:host( [ tone='info' ] ){--os-ui-notice-accent:var( --os-ui-notice-info,var( --os-ui-info-fg,#0969da ) );--os-ui-notice-bg:var( --os-ui-notice-info-bg,rgba( 9,105,218,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-info-border,rgba( 9,105,218,0.16 ) )}:host( [ tone='success' ] ){--os-ui-notice-accent:var( --os-ui-notice-success,var( --os-ui-success-fg,#1a7f37 ) );--os-ui-notice-bg:var( --os-ui-notice-success-bg,rgba( 26,127,55,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-success-border,rgba( 26,127,55,0.16 ) )}:host( [ tone='warning' ] ){--os-ui-notice-accent:var( --os-ui-notice-warning,var( --os-ui-warning-fg,#9a6700 ) );--os-ui-notice-bg:var( --os-ui-notice-warning-bg,rgba( 154,103,0,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-warning-border,rgba( 154,103,0,0.16 ) )}:host( [ tone='error' ] ),:host( [ tone='danger' ] ){--os-ui-notice-accent:var( --os-ui-notice-error,var( --os-ui-danger,#cf222e ) );--os-ui-notice-bg:var( --os-ui-notice-error-bg,rgba( 207,34,46,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-error-border,rgba( 207,34,46,0.16 ) )}:host( [ tone='neutral' ] ){--os-ui-notice-accent:var( --os-ui-notice-neutral,var( --os-ui-fg-muted,#57606a ) );--os-ui-notice-bg:var( --os-ui-notice-neutral-bg,rgba( 87,96,106,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-neutral-border,rgba( 87,96,106,0.16 ) )}`,gs=class gs extends Se{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&Ci(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&Ii(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&qh(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return J` | |
| 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 | 4 | type="button" |
| 53 | - class="os-notice__close" | |
| 54 | - ?hidden=${!n} | |
| 55 | - aria-label=${E("Dismiss notice")} | |
| 56 | - @click=${o=>this._onDismiss(o)} | |
| 57 | - > | |
| 58 | - ${xr("close",{size:null})} | |
| 59 | - </button> | |
| 60 | - `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};gs.props=["tone","notDismissible","icon","noticeId"],gs.styles=[aC],gs.help=void 0;let il=gs;xe("os-notice",il);const So=le("desktop-mode/window-notices",()=>({entries:new Map})),lC=/^[a-z0-9_/-]+$/;function Kh(e){return`os-notice/${e.toLowerCase()}`}function cC(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 Yh(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!lC.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};So.state.entries.set(t,n);const o=Kh(t);return zh({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=So.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=So.state.entries.get(t);i&&s.appendChild(cC(i))}}),()=>rl(t)}function rl(e){const t=String(e??"").trim().toLowerCase();t&&So.state.entries.delete(t)&&nl(Kh(t))}function Xh(){return Array.from(So.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 dC(e){const t=String(e??"").trim().toLowerCase();t&&Ii(t)}function uC(e){const t=String(e??"").trim().toLowerCase();t&&qh(t)}function fC(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 Zh(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),Yh({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:fC(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of Xh())n.owner==="__server__"&&(t.has(n.id)||rl(n.id))}const Jh=le("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),Ao=Jh.state.registry,pC=Jh.state.listeners,Qh=/^[a-z0-9_/-]+$/;function hC(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Qh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Qh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Ne("WindowChrome",t,e);const n=e.id.trim().toLowerCase();Ao.set(n,{...e,id:n}),al()}function em(e){Ao.delete(e.toLowerCase())&&al()}function mC(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(Ao.entries()))o.owner===e&&(Ao.delete(n),t++);return t>0&&al(),t}function tm(){return Array.from(Ao.values()).sort((e,t)=>e.id.localeCompare(t.id))}function al(){const e=Array.from(pC);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function gC(){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 ke(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){T(v.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of tm())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))em(d);mC(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const ll=window.location.origin;let wC=0;const Sn=new Map,An=new Map,Co=new Map;function yC(e,t){return Co.set(e,t),()=>{Co.get(e)===t&&Co.delete(e)}}function bC(){return`os-conn-${++wC}`}function vC(e){const t=(l,c)=>{try{l.contentWindow?.postMessage(c,ll)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=bC(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let g=!1,m=!1;const h=()=>{const P=Co.get(l);return P||(e.getById(l)?.iframe??null)},b=()=>{if(h())return!1;const P=e.getById(l);return!!P&&P.config?.native===!0},y=[],I=()=>{const P=h();if(P)for(;p.length;){const W=p.shift();t(P,{type:"os-bridge-publish",connectionId:d,topic:W.topic,payload:W.payload})}},R={id:d,target:l,isOpen:()=>g,subscribe(P,W){const _=W;if(b()){const L=s_(l,P,(A,C)=>{T(v.CONNECTION_MESSAGE,{connectionId:d,topic:C.channel,direction:"in"});try{_(A,{topic:C.channel})}catch($){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",$)}});return y.push(L),L}let w=f.get(P);return w||(w=new Set,f.set(P,w)),w.add(_),()=>{w?.delete(_)}},send(P,W){if(m)return;if(T(v.CONNECTION_MESSAGE,{connectionId:d,topic:P,direction:"out"}),b()){r_(l,P,W);return}if(!g){p.push({topic:P,payload:W});return}const _=h();_&&t(_,{type:"os-bridge-publish",connectionId:d,topic:P,payload:W})},disconnect(){R._destroy("disconnect")},_targetWindow:h,_handleIframeMessage(P){if(!P||typeof P!="object")return;const W=P;if(W.type==="os-bridge-handshake-ack"){if(g)return;g=!0,T(v.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:R});try{c.onOpen?.()}catch(_){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",_)}I();return}if(W.type==="os-bridge-publish"){const _=P,w=typeof _.topic=="string"?_.topic:"";if(!w)return;T(v.CONNECTION_MESSAGE,{connectionId:d,topic:w,direction:"in"});const L=f.get(w);if(L)for(const C of Array.from(L))try{C(_.payload,{topic:w})}catch($){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",$)}const A=f.get("*");if(A)for(const C of Array.from(A))try{C(_.payload,{topic:w})}catch($){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",$)}return}W.type==="os-bridge-disconnect"&&R._destroy("disconnect")},_destroy(P){if(m)return;m=!0;const W=g;g=!1,Sn.delete(d);const _=An.get(l);_&&(_.delete(d),_.size===0&&An.delete(l));for(const w of y.splice(0))try{w()}catch{}if(W){const w=h();w&&t(w,{type:"os-bridge-disconnect",connectionId:d})}T(v.CONNECTION_CLOSED,{connectionId:d,reason:P});try{c.onClose?.(P)}catch(w){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",w)}}};Sn.set(d,R);let k=An.get(l);if(k||(k=new Set,An.set(l,k)),k.add(d),b())return Promise.resolve().then(()=>{if(!(m||g)){g=!0,T(v.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(P){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",P)}}}),R;const M=h();return M&&t(M,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),R},o=(l,c)=>{if(!l||typeof l!="object")return;const d=l;if(typeof d.type!="string"||!d.type.startsWith("os-bridge-"))return;if(d.type==="os-bridge-connection-request"&&typeof d.requestId=="string"&&typeof c=="string"&&c!==""){s(c,d.requestId,Array.isArray(d.topics)?d.topics:[]);return}if(typeof d.connectionId!="string")return;Sn.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=Co.get(l)??e.getById(l)?.iframe??null;if(!f)return;const p=q(v.IFRAME_CONNECTION_REQUEST,!0,{windowId:l,requestId:c,topics:d.slice()});if(p===!1){try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!1,reason:"rejected"},ll)}catch{}return}const g=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,m=n(l,{topics:g});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:m.id},ll)}catch{}};return{connect:n,getConnection:l=>Sn.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=An.get(l);if(c)for(const d of Array.from(c)){const u=Sn.get(d);if(!u||u.isOpen())continue;const f=u._targetWindow();f&&t(f,{type:"os-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:l=>{const c=An.get(l);if(c)for(const d of Array.from(c))Sn.get(d)?._destroy("window-closed")}}}const _C={};function EC(...e){(typeof{url:Er&&Er.tagName.toUpperCase()==="SCRIPT"&&Er.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&_C?"production":void 0)!=="production"&&console.log(...e)}const kC="iframe:";function cl(e){return kC+e}function nm(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function SC(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const AC=250;class CC{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"&&(bi(cl(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&&bi(cl(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()},AC)}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){EC("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=cl(t);bi(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=SC(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?gd(s.iconSvg):"",a={slug:i,label:s.label,icon:nm(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,nm(s)):this.runProxy(t,s.name)};try{yi(a)}catch(l){console.error("[openstation] iframe-bridge: dropping bad command",a,l)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Ge(t))return;const r=ce(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 IC(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 om="global",xC=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,LC=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,TC=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,NC=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,DC=/getSiteEditorPage\s*\(|site-editor\.php/,RC=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function OC(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 MC{constructor(t){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=t.manager,this.adminUrl=t.adminUrl}install(){this.tryMount(0)}tryMount(t){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){t<40&&window.setTimeout(()=>this.tryMount(t+1),150);return}this.mount()}mount(){const t=window.wp,n=t.element,o=t.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,l=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof l!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const c=document.createElement("div");c.setAttribute("aria-hidden","true"),c.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(c),this.host=c;const d={perLoader:{},statics:[],loadersList:[]},u=m=>{if(!Array.isArray(m)||m.length===0)return"";const h=new Array(m.length);for(let b=0;b<m.length;b++){const y=m[b];h[b]=y&&y.name?y.name:""}return h.join("|")},f=()=>{let m=[];for(const h of d.loadersList){const b=d.perLoader[h];Array.isArray(b)&&(m=m.concat(b))}Array.isArray(d.statics)&&(m=m.concat(d.statics)),this.callbackCache=Object.create(null);for(const h of m)h&&h.name&&typeof h.callback=="function"&&(this.callbackCache[h.name]=h.callback);this.publish(m)},p=m=>{const h=m.loader;let b=null;try{b=h.hook({search:""})}catch{}const y=b&&Array.isArray(b.commands)?b.commands:[],I=a(()=>u(y),[y]);return i(()=>{d.perLoader[h.name]=y,f()},[I]),i(()=>()=>{delete d.perLoader[h.name],f()},[]),null},g=()=>{const m=l(k=>{const M=k("core/commands");return!M||typeof M.getCommandLoaders!="function"?[]:[...M.getCommandLoaders(!1)||[],...M.getCommandLoaders(!0)||[]]},[]),h=l(k=>{const M=k("core/commands");return!M||typeof M.getCommands!="function"?[]:[...M.getCommands(!1)||[],...M.getCommands(!0)||[]]},[]),b=a(()=>Array.isArray(m)?m.map(k=>k&&k.name||""):[],[m]),y=b.join("|");i(()=>{d.loadersList=b,f()},[y]);const I=a(()=>u(Array.isArray(h)?h:[]),[h]);if(i(()=>{d.statics=Array.isArray(h)?h:[],f()},[I]),!Array.isArray(m)||m.length===0)return null;const R=[];for(const k of m)!k||typeof k.hook!="function"||R.push(s(p,{key:k.name,loader:k}));return s(n.Fragment||"div",null,R)};try{this.root=n.createRoot(c),this.root.render(s(g))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(t){const n=Object.create(null),o=[];for(const i of t)!i||!i.name||!i.label||i.disabled||n[i.name]||(n[i.name]=!0,o.push(this.classify(i)));let s="";for(const i of o)s+=`${i.name}|${i.kind}|${i.url||""} | |
| 61 | -`;if(s!==this.lastFingerprint){this.lastFingerprint=s,bi(om);for(const i of o){if(i.kind==="skip")continue;const r=`global-${i.name.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}`,a=this.iconFor(i),l={slug:r,label:i.label,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?gd(i.iconSvg):void 0,owner:om,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name,i.label,a)};try{yi(l)}catch(c){console.error("[openstation] shell-harvester: dropping bad command",l,c)}}}}classify(t){const n={name:String(t.name),label:String(t.label),icon:typeof t.icon=="string"?t.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof t.callback=="function"?t.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=OC(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(xC)||i.match(LC)||i.match(TC);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(NC.test(i)){const l=DC.test(i)?n.name.match(RC):null;if(l){const c=l[1],d=l[2],u=`/${c}/${d}`;try{const f=new URL("site-editor.php",this.adminUrl);f.searchParams.set("p",u),f.searchParams.set("canvas","edit"),n.url=f.toString(),n.kind="navigate"}catch{n.kind="skip"}}else n.kind="skip"}}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}renderIcon(t){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(t);if(typeof o=="string"&&o.toLowerCase().startsWith("<svg"))return o}catch{}return""}iconFor(t){return t.icon&&t.icon.startsWith("dashicons-")?t.icon:t.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Ge(t))return;const r=ce(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 l=ce(a,this.adminUrl);this.manager.open({id:l,baseId:l,url:a,title:n,icon:o})}}}runWithNavCapture(t){let n=null;const o=l=>{n===null&&typeof l=="string"&&l!==""&&(n=l)},s=window.location,i=new Proxy(s,{get(l,c){const d=l[c];return c==="assign"||c==="replace"?u=>o(u):typeof d=="function"?d.bind(l):d},set(l,c,d){return c==="href"&&o(d),!0}}),r=[],a=l=>{try{Object.defineProperty(l,"location",{configurable:!0,get:()=>i,set:c=>o(c)}),r.push({obj:l,key:"location"})}catch{}};a(document),a(window);try{t({close:()=>{}})}catch{}finally{for(const l of r)try{delete l.obj[l.key]}catch{}}return n}}const Cn=[];function dl(e){Ne("Widget",Rt(e,im),e);const t=Cn.findIndex(n=>n.id===e.id);t>=0?Cn[t]=e:Cn.push(e)}function PC(e){const t=Cn.findIndex(n=>n.id===e);t>=0&&Cn.splice(t,1)}function sm(){const e=Cn.slice(),t=q(v.WIDGETS,e);return Array.isArray(t)?t.filter(WC):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function Io(e){return sm().find(t=>t.id===e)}const im=[{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 WC(e){return Rt(e,im).length===0}let Ye=null;function $C(e){if(Ye)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",E("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=E("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),rm(o,e),document.body.appendChild(t),UC(t,e.anchor);const s=a=>{const l=a.target;l&&(t.contains(l)||e.anchor.contains(l)||ul())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&ul()};document.addEventListener("keydown",i),Ye={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function xi(){if(!Ye)return;const e=Ye.panel.querySelector(".os-widget-picker__list");e&&rm(e,Ye.options)}function ul(){if(!Ye)return;document.removeEventListener("pointerdown",Ye.onOutsidePointerDown,!0),document.removeEventListener("keydown",Ye.onKeyDown),Ye.panel.remove();const{onClose:e}=Ye.options;Ye=null,e?.()}function rm(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=E("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(E("%s (already added)"),s.label):a=de(E("Add %s"),s.label),i.setAttribute("aria-label",a);const l=document.createElement("span");l.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-widget-picker__entry-text";const d=document.createElement("span");if(d.className="os-widget-picker__entry-label",d.textContent=s.label,c.appendChild(d),s.description){const u=document.createElement("span");u.className="os-widget-picker__entry-description",u.textContent=s.description,c.appendChild(u)}if(i.appendChild(c),r){const u=document.createElement("span");u.className="os-widget-picker__entry-status",u.textContent=E("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function UC(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.style.visibility="hidden";const o=e.getBoundingClientRect(),s=o.width||320,i=o.height||200,r=6;let a=n.right-s,l=n.top-i-r;a<8&&(a=8),l<8&&(l=n.bottom+r),e.style.left=`${Math.round(a)}px`,e.style.top=`${Math.round(l)}px`,e.style.visibility=""}const Li="os-widgets__card--floating",FC="os-widgets__card--movable",BC="os-widgets__card--resizable",am="os-widgets__card--dragging",lm="os-widgets__card--resizing",HC=160,cm=80,zC=280,GC=180,In=20,Ht=20,dm=5,jC=dm*dm,VC='input, textarea, select, button, a, [contenteditable="true"]';function qC(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(FC),i&&o.classList.add(BC),s?o.appendChild(KC(e,n.onRemove,n.onRedock)):o.appendChild(XC(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(fl(o,nI(t.geometry,t.floatingParent)),o.classList.add(Li)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${tI(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(Li),l=[];if(i)for(const d of QC()){const u=document.createElement("div");u.className=`os-widgets__resize os-widgets__resize--${d}`,u.setAttribute("aria-hidden","true"),u.dataset.dir=d,o.appendChild(u),l.push(JC(o,u,d,e,t,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=ZC(o,d,e,t,n))}return{card:o,body:r,dispose:()=>{for(const d of l)try{d()}catch{}if(c)try{c()}catch{}o.remove()}}}function KC(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(YC(e,n));const r=um(e,t);return o.appendChild(r),o}function YC(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",de(E("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 XC(e,t){const n=um(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function um(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",de(E("Remove %s"),e.label)),n.innerHTML=rn("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function ZC(e,t,n,o,s){let i=null,r=0,a=0,l=0,c=0,d=!1;const u=m=>{if(m.button!==0)return;const h=m.target;h&&h.closest(VC)||(m.preventDefault(),i=m.pointerId,r=m.clientX,a=m.clientY,d=!1,l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0,t.setPointerCapture(i))},f=()=>{if(!e.classList.contains(Li)){const m=o.floatingParent.getBoundingClientRect(),h=e.getBoundingClientRect(),b={x:h.left-m.left,y:h.top-m.top,width:h.width||n.defaultWidth||zC,height:h.height||n.defaultHeight||GC};fl(e,b),e.classList.add(Li),s.onLiberate(b),l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(am)},p=m=>{if(i===null||m.pointerId!==i)return;const h=m.clientX-r,b=m.clientY-a;if(!d){if(h*h+b*b<jC)return;d=!0,f()}const y=hm(xn(l+h),xn(c+b),e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${pm(y.x)}px`,e.style.top=`${pm(y.y)}px`},g=m=>{if(!(i===null||m.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(am),s.onGeometryChanged(fm(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g)}}function JC(e,t,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const g=b=>{if(b.button!==0||!r()&&!eI(n))return;b.preventDefault(),b.stopPropagation(),a=b.pointerId,l=b.clientX,c=b.clientY;const y=e.getBoundingClientRect(),I=s.floatingParent.getBoundingClientRect();d=y.left-I.left,u=y.top-I.top,f=y.width,p=y.height,t.setPointerCapture(a),e.classList.add(lm)},m=b=>{if(a===null||b.pointerId!==a)return;const y=b.clientX-l,I=b.clientY-c,R=oI(n,y,I,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${R.x}px`,e.style.top=`${R.y}px`,e.style.width=`${R.width}px`),e.style.height=`${R.height}px`},h=b=>{if(!(a===null||b.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(lm),r()?i.onGeometryChanged(fm(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",g),t.addEventListener("pointermove",m),t.addEventListener("pointerup",h),t.addEventListener("pointercancel",h),()=>{t.removeEventListener("pointerdown",g),t.removeEventListener("pointermove",m),t.removeEventListener("pointerup",h),t.removeEventListener("pointercancel",h)}}function QC(){return["n","e","s","w","ne","nw","se","sw"]}function eI(e){return e==="s"}function fl(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 fm(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function tI(e,t){return Ln(e,t.minHeight??cm,t.maxHeight??1/0)}function nI(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=hm(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function xn(e){return Math.round(e/Ht)*Ht}function pm(e){const t=Math.floor(e/Ht)*Ht;return t>=In?t:Math.min(e,In)}function hm(e,t,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,a=Math.max(0,i-n-In),l=Math.max(0,r-o-In);return{x:Math.min(Math.max(In,e),a),y:Math.min(Math.max(In,t),l)}}function oI(e,t,n,o,s,i,r,a,l,c){const d=a.minWidth??HC,u=a.minHeight??cm,f=a.maxWidth??1/0,p=a.maxHeight??1/0,g=l.clientWidth||l.getBoundingClientRect().width,m=l.clientHeight||l.getBoundingClientRect().height;let h=o,b=s,y=i,I=r;if((e==="e"||e==="ne"||e==="se")&&(c?y=Ti(xn(o+i+t),o+d,Math.min(o+f,g))-o:y=Ln(i+t,d,Math.min(f,g-o))),e==="w"||e==="nw"||e==="sw"){const R=o+i;if(c)h=Ti(xn(o+t),Math.max(0,R-Math.min(f,R)),R-d),y=R-h;else{const k=Ln(i-t,d,Math.min(f,R));h=o+(i-k),y=k}}if((e==="s"||e==="se"||e==="sw")&&(c?I=Ti(xn(s+r+n),s+u,Math.min(s+p,m))-s:I=Ln(r+n,u,Math.min(p,m-s))),e==="n"||e==="ne"||e==="nw"){const R=s+r;if(c)b=Ti(xn(s+n),Math.max(0,R-Math.min(p,R)),R-u),I=R-b;else{const k=Ln(r-n,u,Math.min(p,R));b=s+(r-k),I=k}}return c||(y=i,h=o),{x:h,y:b,width:y,height:I}}function Ti(e,t,n){const o=Ln(e,t,n),s=Math.floor(o/Ht)*Ht;if(s>=t)return s;const i=s+Ht;return i<=n?i:o}function Ln(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const mm="desktop-mode-widgets",gm="desktop-mode-widgets-geometry",wm="desktop-mode-widgets-docked-heights";function ym(){try{return window.localStorage.getItem(mm)}catch{return null}}function sI(){const e=ym();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function pl(e){try{window.localStorage.setItem(mm,JSON.stringify(e))}catch{}}function iI(){try{const e=window.localStorage.getItem(gm);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=aI(s);i&&(n[o]=i)}return n}catch{return{}}}function hl(e){try{window.localStorage.setItem(gm,JSON.stringify(e))}catch{}}function rI(){try{const e=window.localStorage.getItem(wm);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 bm(e){try{window.localStorage.setItem(wm,JSON.stringify(e))}catch{}}function aI(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 lI(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 cI=["clock"],Ni=40,dI=12;class uI{constructor(t,n,o){this.mounted=new Map,this.generation=0,this.unwatchPointer=null,this.root=t,this.pluginUrl=n,this.enabledIds=sI(),this.geometry=iI(),this.dockedHeights=rI(),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(){ym()===null&&(this.enabledIds=cI.filter(t=>!!Io(t)),pl(this.enabledIds));for(const t of this.enabledIds)this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){this.enabledIds.includes(t)||Io(t)&&(this.enabledIds.push(t),pl(this.enabledIds),this.mountById(t),this.paintEmptyState(),T(v.WIDGET_ADDED,{id:t}))}remove(t){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(pl(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],hl(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],bm(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),T(v.WIDGET_REMOVED,{id:t}),xi())}getEnabledIds(){return[...this.enabledIds]}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),$C({anchor:this.addTile,registry:()=>sm(),enabledIds:()=>[...this.enabledIds],onAdd:t=>{this.add(t),ul(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){Io(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 Io(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=Io(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=qC(n,{floatingParent:this.floatingHost,geometry:s,dockedHeight:this.dockedHeights[t]},{onRemove:()=>this.remove(t),onGeometryChanged:u=>this.persistGeometry(t,u),onDockedHeightChanged:u=>this.persistDockedHeight(t,u),onLiberate:u=>this.liberate(t,u),onRedock:()=>this.redock(t)}),r=!!s,a={id:t,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(t,a),this.placeCard(i.card,r);const l={id:t,pluginUrl:this.pluginUrl,storage:lI(t)};T(v.WIDGET_MOUNTING,{id:t,container:i.body,ctx:l});const c=u=>{const f=this.mounted.get(t);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,this.positionAddTile(),T(v.WIDGET_MOUNTED,{id:t,container:i.body,ctx:l})};let d;try{d=n.mount(i.body,l)}catch(u){this.handleMountFailure(t,u);return}if(fI(d)){d.then(c,u=>{this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,u)});return}c(d)}unmountById(t){const n=this.mounted.get(t);if(n){T(v.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){T(v.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(v.WIDGET_MOUNT_FAILED,{id:t,error:n}),T(v.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="os-widgets__add",t.setAttribute("aria-label",E("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=E("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 c=l.clientX>=t.left-Ni&&l.clientX<=t.right+Ni&&l.clientY>=t.top-Ni&&l.clientY<=t.bottom+Ni;this.root.classList.toggle("os-widgets--hovered",c),c&&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)),this.unwatchPointer=()=>{n&&(cancelAnimationFrame(n),n=0),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),fl(o.frame.card,n),this.persistGeometry(t,n),this.paintEmptyState())}redock(t){const n=this.mounted.get(t);if(!n||!n.floating)return;n.floating=!1,this.geometry[t]&&(delete this.geometry[t],hl(this.geometry));const o=n.frame.card;o.classList.remove("os-widgets__card--floating"),o.style.left="",o.style.top="",o.style.width="";const s=this.dockedHeights[t];o.style.height=s!==void 0?`${s}px`:"",this.listEl.appendChild(o),this.paintEmptyState()}persistGeometry(t,n){this.geometry[t]=n,hl(this.geometry),this.positionAddTile()}positionAddTile(){const t=this.root.getBoundingClientRect();if(!t.height)return;let n=this.listEl.offsetTop+this.listEl.offsetHeight;for(const i of this.mounted.values()){if(!i.floating)continue;const r=i.frame.card.getBoundingClientRect();Math.min(r.right,t.right)-Math.max(r.left,t.left)<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+dI,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,bm(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 fI(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const pI=280,hI=220,mI=520,gI=400;function wI(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function yI(e,t,n){return o=>{const s=wI(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=yC(s,i);t.push(r);let a;try{a=new URL(e.url,window.location.origin).origin}catch{a=window.location.origin}let l=null;const c=new Promise(f=>{l=f}),d=()=>{if(e.bridge)try{const f=i.contentDocument;if(f&&!f.querySelector("script[data-os-iframe-bridge]")){const p=window.openStationConfig?.iframeBridgeUrl;if(p){const g=f.createElement("script");g.src=p,g.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(g)}}}catch{}l_(s),l?.()};i.addEventListener("load",d);const u=f=>{if(!i.contentWindow||f.source!==i.contentWindow||f.origin!==a&&f.origin!==window.location.origin)return;const p=f.data;p&&typeof p=="object"&&typeof p.type=="string"&&p.type.startsWith("os-bridge-")&&window.__openStationConnectionBridge?.routeIncomingFromIframe(p,s),p&&typeof p=="object"&&p.type==="os-window-publish"&&typeof p.channel=="string"&&p.channel!==""&&i_(s,p.channel,p.payload);try{e.onMessage?.(f.data)}catch(g){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",g)}};return window.addEventListener("message",u),t.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),c}}function bI(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=yI(t.iframeContent,s,t.id));const i=t.onClose,r=t.iframeContent?()=>{for(const l of s)try{l()}catch{}i?.()}:i;return await e.open({id:t.id,baseId:t.baseId||t.id,native:!0,url:t.url||`#${t.id}`,title:t.title,icon:t.icon,x:t.x??0,y:t.y??0,width:t.width??mI,height:t.height??gI,minWidth:t.minWidth??pI,minHeight:t.minHeight??hI,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let vI=0;function _I(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++vI}`,s=n.persistent===!0,i=[["opened",v.WINDOW_OPENED],["reopened",v.WINDOW_REOPENED],["focused",v.WINDOW_FOCUSED],["blurred",v.WINDOW_BLURRED],["closing",v.WINDOW_CLOSING],["closed",v.WINDOW_CLOSED],["minimized",v.WINDOW_MINIMIZED],["restored",v.WINDOW_RESTORED],["maximized",v.WINDOW_MAXIMIZED],["unmaximized",v.WINDOW_UNMAXIMIZED],["fullscreenEntered",v.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",v.WINDOW_FULLSCREEN_EXITED],["resized",v.WINDOW_RESIZED],["bodyResized",v.WINDOW_BODY_RESIZED],["boundsChanged",v.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const l=()=>{if(!a){a=!0;for(const c of r)kr(c,o)}};for(const[c,d]of i){const u=t[c];u&&(r.push(d),Y(d,o,f=>{const p=f;if(p.windowId!==e)return;const{windowId:g,...m}=p;u(m),c==="closed"&&!s&&l()}))}return l}function EI(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function kI(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&lE(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function SI(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,a=new Map,l=new Set,c=new Map,d=_=>{const w=ia(_.id);return w?{width:Math.max(w.width,_.minWidth),height:Math.max(w.height,_.minHeight)}:{width:_.width,height:_.height}},u=_=>{if(i.has(_.templateId))return;if(document.getElementById(_.templateId)){i.add(_.templateId);return}if(!_.templateHtml)return;const w=document.createElement("template");w.id=_.templateId,w.innerHTML=_.templateHtml,document.body.appendChild(w),i.add(_.templateId)},f=_=>{const w=_.styleUrl;if(!w||l.has(w))return;const L=w.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${L}"]`)){const C=document.createElement("link");C.rel="stylesheet",C.href=w,_.styleHandle&&(C.dataset.osStyleHandle=_.styleHandle),document.head.appendChild(C)}if(Array.isArray(_.styleInline))for(const C of _.styleInline){if(typeof C!="string"||C==="")continue;const $=document.createElement("style");_.styleHandle&&($.dataset.osStyleHandle=_.styleHandle),$.textContent=C,document.head.appendChild($)}l.add(w)},p=(_,w)=>{const L=w.scriptUrl;if(r.has(L))return Promise.resolve();const A=a.get(L);if(A)return A;const C=ke(L,{translations:w.scriptTranslations,l10n:w.scriptL10n,before:w.scriptBefore,after:w.scriptAfter}).catch($=>{T(v.SHELL_ERROR,{scope:"native-window-script-load",id:_,error:$})}).then(()=>{r.add(L),a.delete(L)});return a.set(L,C),C},g=async _=>{for(const w of _.companionScripts??[])w.scriptUrl&&await p(_.id,w);_.scriptUrl&&await p(_.id,_)},m=async _=>{_.preloadScript&&await g(_)},h=_=>async(w,L)=>{w.appendChild(vm(_.templateId)),kI(w,_),await g(_);const A=EI()[_.id];return A?.(w,L)},b=(_,w)=>{const L=h(_),A=d(_);t.open({id:_.id,baseId:_.id,native:!0,url:`#${_.id}`,title:_.title,icon:_.icon,width:A.width,height:A.height,minWidth:_.minWidth,minHeight:_.minHeight,render:L,autofocus:_.autofocus,ownerHandle:_.ownerHandle||_.scriptHandle,...w?{params:w}:{}})},y=(_,w)=>{const L=h(_),A=d(_);t.openNew({id:_.id,baseId:_.id,native:!0,url:`#${_.id}`,title:_.title,icon:_.icon,width:A.width,height:A.height,minWidth:_.minWidth,minHeight:_.minHeight,initialState:"normal",render:L,autofocus:_.autofocus,ownerHandle:_.ownerHandle||_.scriptHandle,...w?{params:w}:{}})},I=async _=>{if(!s.has(_.id)){if(_.placement==="none"){u(_),f(_),await m(_),s.add(_.id);return}u(_),f(_),await m(_),n({id:_.id,title:_.title,icon:_.icon,windowId:_.id,navKind:_.navKind==="control"?"control":"app",defaultPlacement:"rail",order:_.dockOrder,placeable:_.placeable===!0,isOpen:()=>!!t.getById(_.id),onOpen:()=>b(_)}),T(v.DOCK_ITEM_APPENDED,{id:_.id}),s.add(_.id)}},R=_=>{s.has(_)&&(o(_),s.delete(_),c.delete(_))},k=async _=>{const w=new Set;for(const L of _)w.add(L.id),c.set(L.id,L);for(const L of Array.from(s))w.has(L)||R(L);for(const L of _)s.has(L.id)||await I(L)},M=(_,w={})=>{const L=c.get(_);return L?(Ee.publish("os/open-requested",{windowId:_,source:w.source??"api"}),b(L,w.params),!0):!1},P=(_,w={})=>{const L=c.get(_);return L?(Ee.publish("os/open-requested",{windowId:_,source:w.source??"api"}),y(L,w.params),!0):!1};return Y(v.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",_=>{const w=_,L=w?.windowId,A=w?.width,C=w?.height;if(!L||typeof A!="number"||typeof C!="number")return;const $=t.getById(L);if(!$||$.state!=="normal")return;const X=$.config.baseId||$.id;uf(X,{width:A,height:C}),$.element&&ff(X,{x:$.element.offsetLeft,y:$.element.offsetTop})}),Y(v.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",_=>{const w=_?.windowId;if(!w)return;const L=t.getById(w);if(!L||L.state!=="normal"||!L.element)return;const A=L.config.baseId||L.id;uf(A,{width:L.element.offsetWidth,height:L.element.offsetHeight}),ff(A,{x:L.element.offsetLeft,y:L.element.offsetTop})}),Y(v.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",_=>{const w=_?.windowId;if(!w)return;const L=t.getById(w);if(!L)return;const A=L.config.baseId||L.id,C=c.get(A),$=C?{width:C.width,height:C.height}:{width:L.config.width,height:L.config.height};pf(A,"maximized",$)}),Y(v.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",_=>{const w=_?.windowId;if(!w)return;const L=t.getById(w);if(!L)return;const A=L.config.baseId||L.id;pf(A,null)}),{sync:k,openById:M,openNewById:P,loadScriptById:async _=>{const w=c.get(_);return w?(await g(w),!0):!1}}}function vm(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 _m(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=ce(e,o);return s.find(r=>ce(r.url,o)===i||(r.submenu??[]).some(a=>ce(a.url,o)===i))??null}const Em="data:image/svg+xml;base64,",Di=new Map;function AI(e){const t=Di.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(Em.length)).includes("currentColor")}catch{}return Di.size>=256&&Di.clear(),Di.set(e,n),n}function xo(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const l=zs(t.slot);l!==null&&(e=l),s=zr(t.slot)}if(typeof e=="string"&&e.startsWith("dashicons-")){const l=document.createElement("span");return l.className=`dashicons ${e} ${n}`.trim(),l.setAttribute("aria-hidden","true"),s!==null&&(l.style.color=s),l}if(s!==null&&typeof e=="string"){const l=document.createElement("span");if(l.className=n,l.setAttribute("aria-hidden","true"),l.style.display="inline-block",uo(l,e,s))return l}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const l=e.slice(Em.length);if(/^[A-Za-z0-9+/=]+$/.test(l)){const c=document.createElement("span");return c.className=n,c.setAttribute("aria-hidden","true"),c.style.display="inline-block",AI(e)&&uo(c,e,"currentColor")||(c.style.backgroundImage=`url("${e}")`,c.style.backgroundRepeat="no-repeat",c.style.backgroundPosition="center",c.style.backgroundSize="contain"),c}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const l=e.indexOf(","),c=l>=0?e.slice(l+1):"";if(/^[A-Za-z0-9+/=]+$/.test(c))return km(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return km(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=CI(o);i.textContent=r;const a=mn(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 km(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 CI(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 Sm="os-icon__badge",Lo=new Map,To=new Map;function II(e){return Math.max(0,Math.floor(Number(e)||0))}function Am(e,t){if(!e)return;const n=Lm(e);if(!n)return;const o=II(t),s=Lo.get(e)??0;o!==s&&(o===0?Lo.delete(e):Lo.set(e,o),Tm(n,o),Ee.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),T(v.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function xI(e){Am(e,0)}function LI(e){return Lo.get(e)??0}function TI(e,t){if(e){if(!t){To.delete(e);return}To.get(e)!==t&&(To.set(e,t),DI(e,t),Ee.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function Cm(e){return To.get(e)??""}function NI(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function DI(e,t){const o=Lm(e)?.querySelector(".os-icon__image");if(o){const s=xo(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${NI(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const RI={setBadge:Am,clearBadge:xI,getBadge:LI,setArt:TI,getArt:Cm};function OI(e){return!e||e.length===0?"":`${Hr()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let Im="";function xm(e,t,n){const o=OI(t);if(o===Im&&e.querySelector(":scope > .os-icons"))return;Im=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",E("Desktop icons"));const r=[...t].sort((l,c)=>{const d=l.pinned?0:1,u=c.pinned?0:1;return d-u}),a=new Map;for(const l of r){const c=PI(l,n),d=Lo.get(l.id)??0;d>0&&Tm(c,d);const u=To.get(l.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(xo(u,{className:"os-icon__image",title:""}))}i.appendChild(c),a.set(l.id,c)}e.appendChild(i),T(v.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(l=>l.id),container:i,tiles:a})}function Lm(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${MI(e)}"]`):null}function Tm(e,t){const n=e.querySelector(`:scope > .${Sm}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=de(sn("%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=Sm,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function MI(e){const t=window.CSS;return t?.escape?t.escape(e):e}function PI(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=xo(e.icon,{title:e.title,className:"os-icon__image",slot:Gs(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(v.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),WI(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 WI(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(gn(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=_m(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 $I(e){const t=[],n=new Map,o=s=>{t.push(s),n.set(s.id,s)};for(const s of e.menuItems)n.has(s.id)||o({id:s.id,kind:s.isCore?"core":"plugin",title:s.title,icon:s.icon,windowId:e.resolveMenuWindowId?.(s)||void 0,menu:s});for(const s of e.systemTiles){const i=n.get(s.item.id);if(i){i.tile=s.item;continue}const a=(s.item.submenu??[]).map(l=>l.windowId).filter(l=>!!l);o({id:s.item.id,kind:s.kind,title:s.item.title,icon:s.item.icon,locked:s.locked,defaultPlacement:s.item.defaultPlacement,windowId:s.item.windowId,answersFor:a.length>0?a:void 0,order:s.item.order,tile:s.item})}for(const s of e.icons){const i=s.window?n.get(s.id)??n.get(s.window):n.get(s.id);if(i){i.entry=s,s.window&&(i.windowId=s.window);continue}o({id:s.id,kind:"app",title:s.title,icon:s.icon,windowId:s.window||void 0,entry:s})}return t}const Nm="os-side-dock";function UI(e,t,n,o,s="bottom"){let i=t,r=s,a=n,l=o??[],c=null,d=null,u=null,f=null,p=null;const g=new Map;let m=[],h=Jf({items:[],config:{placement:{},order:[]},layout:i,openWindows:[]});const b=()=>e.getSettings?.()??{navPlacement:{},navOrder:[]},y=()=>{const D=e.windowManager.getActiveDesktopId(),j=[],G=new Set;for(const ae of e.windowManager.getAll()){if((ae.config.desktopId||D)!==D)continue;const fe=ae.config.baseId||ae.id;G.has(fe)||(G.add(fe),j.push({id:fe,title:ae.config.title||fe,icon:ae.config.icon||"dashicons-admin-generic",fromAdminUrl:ae.config.native!==!0}))}return j},I=D=>D.windowId?D.windowId:ra(D.url)??ce(D.url,e.adminUrl),R=()=>{const D=[];for(const G of g.values())D.push({item:G,kind:G.navKind==="control"?"control":"app",locked:G.locked});m=$I({menuItems:a,systemTiles:D,icons:l,resolveMenuWindowId:I});const j=b();h=Jf({items:m,config:{placement:j.navPlacement,order:j.navOrder},layout:i,openWindows:y()})},k=D=>D.tile?{type:"system",item:D.tile}:D.menu?{type:"menu",item:D.windowId?{...D.menu,windowId:D.windowId}:D.menu}:{type:"menu",item:{id:D.id,title:D.title,icon:D.icon,url:D.entry?.url||"",windowId:D.windowId,badge:0,submenu:[],isCore:!1}},M=D=>!!D.entry||!!D.windowId||!!D.menu?.url,P=(D,j)=>D.entry?D.entry:{id:D.id,title:D.title,icon:D.icon,window:D.windowId??"",url:D.menu?.url||"",position:2e3+j},W=D=>({core:(D.core??[]).map(k),apps:(D.apps??[]).map(k),controls:(D.controls??[]).map(k)}),_=(D,j,G)=>{if(!D)return;if(D.setZones){D.setZones(j),G.clear();for(const pe of st)for(const re of j[pe])re.type==="system"&&G.add(re.item.id);return}const ae=[],fe=new Set;for(const pe of st)for(const re of j[pe])re.type==="menu"?ae.push(re.item):fe.add(re.item.id);D.replaceItems(ae);for(const pe of Array.from(G))fe.has(pe)||(D.removeSystemItem(pe),G.delete(pe));for(const pe of st)for(const re of j[pe])re.type==="system"&&!G.has(re.item.id)&&(D.appendSystemItem(re.item),G.add(re.item.id))},w=new Set,L=new Set,A=()=>{R(),_(c,W(h.dock),w),_(d,{core:h.sidebar.map(k),apps:[],controls:[]},L),e.renderIcons(h.desktop.filter(M).map(P))},C=()=>Array.from(h.ephemeral).sort().join(","),$=()=>{const D=document.getElementById(Nm);if(D)return D;const j=document.createElement("nav");return j.id=Nm,j.className="os-dock",j.setAttribute("role","toolbar"),j.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(j,e.shellBody.firstChild),j},X=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},Z=()=>{if(c){try{c.destroy()}catch(D){T(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:D})}c=null,u=null}if(d){try{d.destroy()}catch(D){T(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:D})}d=null,f=null}w.clear(),L.clear()},x=D=>{const j=Tr();if(!j)return T(v.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return j.mount(D)}catch(G){if(T(v.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:j.id,error:G}),j===ya)return null;try{return ya.mount(D)}catch{return null}}},F=(D,j)=>({container:D,items:[],fullMenu:a.slice(),fullSystemTiles:m.filter(G=>!!G.tile).filter(G=>N(G.id)).map(G=>G.tile),orientation:j,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:G=>{const ae=ce(G.url,e.adminUrl);e.windowManager.open({id:ae,baseId:ae,url:G.url,parentUrl:G.url,title:G.title,icon:G.icon.startsWith("dashicons-")?G.icon:"dashicons-admin-generic",submenu:G.submenu,selfLabel:G.selfLabel,multi:!!G.multi})},openSubmenuPick:(G,ae)=>{gn(ae.url)||e.windowManager.open({id:ce(ae.url,e.adminUrl),baseId:ce(G.url,e.adminUrl),url:ae.url,parentUrl:G.url,title:G.title,icon:G.icon.startsWith("dashicons-")?G.icon:"dashicons-admin-generic",submenu:G.submenu,selfLabel:G.selfLabel,multi:!!G.multi})},openSystemItem:G=>G.onOpen()}),N=D=>{for(const j of st)if(h.dock[j].some(G=>G.id===D))return!0;return h.sidebar.some(j=>j.id===D)},U=()=>i==="classic"?"bottom":r,B=()=>{Z(),R(),i==="classic"?(p=$(),d=x(F(p,"left")),f=np(d)):X(),c=x(F(e.bottomDockEl,U())),u=np(c),A()},H=()=>{document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:U(),primary:u,side:f}}))},O={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:D=>{D!==i&&(i=D,e.shellRoot.setAttribute("data-os-layout",D),B(),H())},getDockPlacement:()=>r,setDockPlacement:D=>{if(D===r)return;const j=U();r=D,U()!==j&&(B(),H())},applyDockItems:D=>{a=D,A()},applyDesktopIcons:D=>{l=D??[],A()},appendSystemTile:D=>{g.set(D.id,D),A()},removeSystemTile:D=>{g.delete(D)&&A()},listSystemTiles:()=>Array.from(g.values()).map(D=>({id:D.id,title:D.title,icon:D.icon,navKind:D.navKind==="control"?"control":"app",placeable:D.placeable===!0,locked:D.locked===!0})),getSystemTile:D=>g.get(D)??null,getMenuItems:()=>a.slice(),getNavItems:()=>m.slice(),getNav:()=>h,refresh:A,destroy:()=>{Z(),X()}};for(const D of["os-window-opened","os-window-closed"])document.addEventListener(D,()=>{const j=C();R(),C()!==j&&A()});e.shellRoot.setAttribute("data-os-layout",i),B();let V=Tr()?.id??null;return uv(()=>{const D=Tr()?.id??null;D!==V&&(V=D,B(),H())}),O}function FI(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 BI{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 this._loadPromise?this._loadPromise:(this._loadPromise=FI(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._ensure().then(t=>t.open())}close(){this._intendOpen=!1,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 Dm=e=>!e||typeof e!="object"?!1:e.name==="AbortError",HI=e=>{if(!e)return[];const t=xS();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}}):[]},zI=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 GI(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 jI(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function VI(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",l=r.restNonce??"";if(!a||!l)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Fe(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":l},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw Dm(c)?c:new Error(`[openstation] wp.os.ai.ask: network error — ${String(c?.message??c)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",l=LS(r);if(!l)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??e.fallbackContext();let d;try{d=await Promise.resolve(l.run(a,c))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:d}},o=async(s,i,r,a,l,c)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:jI(a)}};l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);let u;try{u=await t(d,c)}catch(g){if(Dm(g))throw g;return null}if(!u.ok)return null;const f=await u.json().catch(()=>({}));return(typeof f.message=="string"?f.message.trim():"")!==""?f.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[openstation] wp.os.ai.ask: empty query passed with non-default options — likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const l=HI(r.tools),c=zI(r.systemPrompt),d={query:a};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),l.length>0&&(d.command_tools=l),c&&(d.system_prompt_text=c.text,d.system_prompt_mode=c.mode);const u=await t(d,r.signal);if(!u.ok){const y=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[openstation] wp.os.ai.ask: HTTP ${u.status} — ${y.message??u.statusText}`)}const f=await u.json();if(f.answer_type!=="tool_call"||!f.tool)return{answer_type:f.answer_type,message:f.message??"",entity:f.entity??null,admin_links:f.admin_links??null,request_id:f.request_id,continue:f.continue??null};const p=await n(f,r);if(!p.ok)return p.response;const{slug:g,args:m,result:h}=p;let b=GI(f.message,h);if(r.followUp===!0){const y=await o(a,g,m,h,c,r.signal);y!==null&&(b=y)}return{answer_type:"tool_call",message:b,entity:null,admin_links:null,toolCall:{slug:g,args:m,result:h},request_id:f.request_id}}}const Rm="[os-bin badge]";function it(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(Rm,...e)}catch{}}function Ri(...e){console.warn(Rm,...e)}const No="desktop-mode-recycle-bin",qI="openstation_recycle_bin_seen_ts";function KI(){return window.wp?.os}const me=le("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function Do(e){const t=Math.max(0,Math.floor(e)),n=me.state.current;me.state.current=t,it("setRecycleBinCount",{prev:n,next:t}),ml(t)}function Om(e){Do(me.state.current+e)}function YI(){return me.state.current}function ml(e){const t=e>0?me.state.fullArt:me.state.emptyArt;if(it("paintIconState",{count:e,full:e>0,hasArt:!!t}),!t)return;const n=KI();n?.dock?.setArt?.(No,t),n?.taskbar?.setArt?.(No,t),n?.icons?.setArt?.(No,t)}function XI(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;me.state.emptyArt=String(o?.recycleBinIconEmpty??""),me.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;it("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:me.state.started,cfgCount:s,cfgUrl:i,cfgDebug:r,readyState:document.readyState});const a=Number(s);if((typeof s=="number"||typeof s=="string")&&Number.isFinite(a)||Ri("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),me.state.started){Do(n);return}me.state.started=!0,me.state.countUrl=t,me.state.seenTs=Date.now(),Do(n),ZI(),JI(),QI(),ex(),tx()}function ZI(){Y(v.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===No&&ml(me.state.current)})}function JI(){Y(v.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(No)&&ml(me.state.current)})}function QI(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":Om(+r);break;case"untrashed":case"deleted":Om(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])En(`os.${s}.changed`,e)}function ex(){const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;if(!n||n.type!=="os-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=me.state.seenTs){it("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:me.state.seenTs});return}it("postMessage triggers refetch",{ts:o,prevSeenTs:me.state.seenTs}),me.state.seenTs=o,nx()})}function tx(){const e=window.jQuery;if(!e){Ri("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}it("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[qI]=me.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;it("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>me.state.seenTs&&(me.state.seenTs=o.ts),typeof o.count=="number"&&Do(o.count))})}async function nx(){if(!me.state.countUrl){it("refetchCount: no countUrl, skip");return}it("refetchCount: hitting",me.state.countUrl);try{const e=await fetch(me.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){Ri("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();it("refetchCount: response",t),typeof t.count=="number"&&Do(t.count)}catch(e){Ri("refetchCount: fetch failed",e)}}const ox="desktop-mode-os-settings",sx="desktop-mode-recycle-bin";function ix(e){const t=lx();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===ox?rx():i===sx?ax(s,e.getRecycleBinCount):n})}function rx(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=E("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 ax(e,t){const n=document.createElement("span");n.className="os-dock-peek__card-body os-dock-peek__card-body--recycle-bin",n.setAttribute("aria-hidden","true");const o=Math.max(0,Math.floor(t()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="os-dock-peek__bin-stage";const i=document.createElement("span");i.className="os-dock-peek__bin-stack";for(let l=0;l<3;l++){const c=document.createElement("span");c.className="os-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="os-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="os-dock-peek__bin-label",o===0?a.textContent=E("Trash — empty"):o===1?a.textContent=E("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function lx(){return window.wp?.hooks??null}const Ro="desktop-mode-bug-report",cx="WordPress",dx="openstation",Mm=6e3;function ux(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=E("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(fx()),t.appendChild(px("title",E("Title"),{placeholder:E("A short summary"),required:!0})),t.appendChild(Pm("description",E("What happened? What did you expect?"),{placeholder:E("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(Pm("steps",E("Steps to reproduce (bug only)"),{placeholder:E("One step per line"),rows:4}));const o=hx();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=E("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=E("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const l=gx(t);if(!l.title.trim()||!l.description.trim()){mx(t,E("Title and description are both required."));return}const c=wx(l);window.open(c,"_blank","noopener")}),e.appendChild(t)}function fx(){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=E("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:E("Bug"),checked:!0},{value:"feature",label:E("Feature request")},{value:"question",label:E("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 px(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 Pm(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 hx(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=E("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=$m(Wm()),e.appendChild(n),e}function mx(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 gx(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 wx(e){const t=yx(e.type),n=bx(e),o=new URLSearchParams;return o.set("title",e.title.trim()),o.set("body",n),t.length&&o.set("labels",t.join(",")),`https://github.com/${cx}/${dx}/issues/new?${o.toString()}`}function yx(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function bx(e){const t=[];t.push(e.description.trim()),e.type==="bug"&&e.steps.trim()&&(t.push(""),t.push("## Steps to reproduce"),t.push(""),t.push(e.steps.trim())),t.push(""),t.push("<details><summary>Environment</summary>"),t.push(""),t.push("```"),t.push($m(Wm())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(` | |
| 62 | -`);return n.length>Mm&&(n=n.slice(0,Mm)+` | |
| 63 | - | |
| 64 | -…(truncated to fit GitHub URL length limit)`),n}function Wm(){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 $m(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 Oi=null,Um=!1,Fm=!1,Bm=!1,zt="pending";function vx(){if(Fm)return;Fm=!0;const e=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{e&&(Bm||Ex()||(kx(),Bm=!0,setTimeout(()=>window.location.reload(),0)))})}const Hm="os-sw-reload-ts",_x=3e4;function Ex(){try{const e=sessionStorage.getItem(Hm),t=e?Number.parseInt(e,10):0;return!Number.isFinite(t)||t<=0?!1:Date.now()-t<_x}catch{return!1}}function kx(){try{sessionStorage.setItem(Hm,String(Date.now()))}catch{}}async function Sx(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return zt="unsupported",null;if(Oi||Um)return Oi;if(!t.forceReplace){const o=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(s=>{const i=s.active?.scriptURL??s.installing?.scriptURL??"";return i!==""&&i!==e.swUrl});if(o)return zt="foreign-sw",typeof console<"u"&&console.warn("[openstation] another service worker is already registered ("+o.scope+"); skipping openstation SW. Set openstation_pwa_force_replace_sw=true to override."),null}try{return Oi=await navigator.serviceWorker.register(e.swUrl,{scope:"/",updateViaCache:"none"}),zt="registered",vx(),Oi}catch(n){return Um=!0,zt="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",n),null}}function Ax(){return zt}const Cx="os-pwa-install";function zm(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Gm(){if(zm())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 At=null;function Ix(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(),At=s}function o(){At=null,t({message:de(E("Installed %s as an app."),e)})}}function xx(e,t){return{id:Cx,title:E("Install web app"),icon:"dashicons-download",onOpen:()=>{Lx(e,t)}}}async function Lx(e,t){if(At){const n=At;At=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:E("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await Gm()){t({message:de(E("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(Ax()==="foreign-sw"){t({message:E("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:E("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 Tx(){if(!At)return"unavailable";const e=At;At=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function Nx(){Promise.resolve().then(()=>bS).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function Dx(e,t){e.pwa&&(Pp(e.pwa),Ix(e.pwa.appName||"WordPress",t),Sx(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw}))}const Tn={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function Rx(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function Ox(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function Mx(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function Px(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 Wx{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(Rx(n)){this._startDrag(n.payload);return}if(Ox(n)){this._endDrag();return}if(Mx(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=Px(t);this._payload=n,document.dispatchEvent(new CustomEvent(Tn.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(Tn.END,{detail:{payload:t}}))}}class $x{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 Ux="os-drag-ghost",jm="os-drag-ghost--accept",Vm="os-drag-ghost--reject",Fx="os-drag-hint",qm="os-drag-hint--accept",Km="os-drag-hint--reject",Ym="os-drag-hint--neutral",Bx=16,Hx=18;function zx(e,t,n){const o=Yx(e),s=e.ghost?.offsetX??Xx(e.source),i=e.ghost?.offsetY??Zx(e.source);o.classList.add(Ux),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=jx(e),a=r?Gx():null;a&&document.body.appendChild(a);const l={get element(){return o},moveTo(c,d){o.style.transform=`translate3d(${c-s}px, ${d-i}px, 0)`,a&&(a.style.transform=`translate3d(${c+Bx}px, ${d+Hx}px, 0)`)},setMode(c,d){o.classList.remove(jm,Vm),c==="accept"?o.classList.add(jm):c==="reject"&&o.classList.add(Vm),a&&r&&(a.classList.remove(qm,Km,Ym),c==="accept"?(a.classList.add(qm),a.textContent=d?.acceptLabel??r.accept):c==="reject"?(a.classList.add(Km),a.textContent=r.reject):(a.classList.add(Ym),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(c){const d=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return c()}finally{o.style.visibility=d,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return l.moveTo(t,n),l.setMode("neutral"),l}function Gx(){const e=document.createElement("div");return e.className=Fx,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 jx(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??Vx(e),reject:t?.reject??qx(),neutral:t?.neutral??Kx(e)}}function Vx(e){return e.type==="shortcut"?E("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?E("Drop here to move","desktop-mode"):E("Drop here","desktop-mode")}function qx(e){return E("Can’t drop here","desktop-mode")}function Kx(e){return e.type==="shortcut"?E("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?E("Drop in a folder","desktop-mode"):""}function Yx(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 Xx(e){return e.offsetWidth/2}function Zx(e){return e.offsetHeight/2}let Xm=!1;function Jx(e){Xm||(Xm=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const Zm=4,be={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"},Mi="os-file-tile--dragging",Jm="os-file-tile--drop-target",Qm="data-os-trash-drop-active",eg="data-files-drop-active",tg="data-os-dragging",ng="data-os-drag-type",gl="data-os-drag-mode";class Qx{constructor(){this._registry=new $x,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)<Zm&&Math.abs(s)<Zm)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),ut(be.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(),Jx(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:()=>og(),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(Mi),t._ghost=zx(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(tg,""),document.body.setAttribute(ng,String(t.payload.type)),document.body.setAttribute(gl,"neutral")),ut(be.START,{payload:t.payload})}_hitTestNow(t,n,o){const s=()=>{const i=document.elementFromPoint(n,o),r=this._registry.hitTest(i);if(!r)return{target:null,accepted:!1};let a=!1;try{a=r.accept(t.payload)}catch(l){console.error("[openstation] drop target accept() threw:",r.id,l)}return{target:r,accepted:a}};return t._ghost?t._ghost.withHidden(s):s()}_updateHover(t,n,o){const s=this._hitTestNow(t,n,o),i=t._currentTarget;if(s.target===i&&s.accepted===t._currentAccepted)return;i&&wl(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(eL(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),ut(be.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(gl,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),wl(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)}ut(be.COMMIT,{payload:t.payload,targetId:n.id}),ut(be.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&&wl(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}ut(be.CANCEL,{payload:t.payload,reason:n}),ut(be.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(Mi)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(tg),document.body.removeAttribute(ng),document.body.removeAttribute(gl)),tL()}}function ut(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function eL(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}ut(be.ENTER,{payload:t.payload,targetId:e.id})}function wl(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}ut(be.LEAVE,{payload:t.payload,targetId:e.id})}function og(){if(typeof document>"u")return[];const e=[];for(const t of[`.${Mi}`,`.${Jm}`,`[${Qm}]`,`[${eg}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function tL(){for(const e of og())e.classList.remove(Mi,Jm),e.removeAttribute(Qm),e.removeAttribute(eg)}const nL=".os-window",sg="wp-window-";function ig(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(nL);return o instanceof HTMLElement?o:null}function oL(e){if(!e.id.startsWith(sg))return null;const t=e.id.slice(sg.length);return t.length>0?t:null}const sL="desktop-mode-iframe-drop-",Pi="iframe.os-window__iframe",yl="data-os-iframe-drop-active";let bl=!1,rg=null;const je=new Map,Gt=new Map;let ft=null,jt=null;function iL(){document.querySelectorAll(Pi).forEach(t=>{je.has(t)||(je.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function rL(){je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear()}function ag(e,t){const n=ig(e,t);if(!n)return null;const o=n.querySelector(Pi);return o instanceof HTMLIFrameElement?o:null}const lg=e=>{if(!ft)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=ag(e.clientX,e.clientY);t!==jt&&(jt&&Vt(jt,{type:"os-drag-leave"}),jt=t,t&&Vt(t,{type:"os-drag-over",payload:ft}))},cg=e=>{if(!ft)return;const t=ag(e.clientX,e.clientY);if(!t){e.preventDefault(),Wi();return}e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const n=ft;Wi();const o=t.getBoundingClientRect();Vt(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},dg=()=>{Wi()};function aL(e){if(ft){ft=e;return}ft=e,iL(),document.addEventListener("dragover",lg,!0),document.addEventListener("drop",cg,!0),document.addEventListener("dragend",dg,!0)}function Wi(){ft&&(ft=null,jt&&(Vt(jt,{type:"os-drag-leave"}),jt=null),document.removeEventListener("dragover",lg,!0),document.removeEventListener("drop",cg,!0),document.removeEventListener("dragend",dg,!0),rL())}function $i(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function Vt(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function lL(e,t,n,o){return e.registerDropTarget({id:`${sL}${o}`,element:n,accept:s=>!!$i(s),onEnter:s=>{const i=$i(s.payload);i&&(n.setAttribute(yl,""),Vt(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(yl),Vt(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(yl);const r=$i(s.payload);if(!r)return;const a=t.getBoundingClientRect();Vt(t,{type:"os-drop",payload:r,position:{x:i.clientX-a.left,y:i.clientY-a.top}})}})}function ug(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 cL(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 dL(e){const t=rg;if(!t)return;const n=document.querySelectorAll(Pi),o=!!$i(e);cL(n.length,o,e),n.forEach(s=>{if(je.has(s)||(je.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||Gt.has(s))return;const i=s.parentElement;if(!i)return;const r=ug(s),a=lL(t,s,i,r);Gt.set(s,a)})}function uL(){je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear(),Gt.forEach(e=>{try{e()}catch{}}),Gt.clear()}function fL(e){bl||(bl=!0,rg=e,document.addEventListener(be.START,t=>{const n=t.detail;dL(n?.payload)}),document.addEventListener(be.END,()=>{uL()}),document.addEventListener(Tn.START,t=>{const n=t.detail;n?.payload&&aL(n.payload)}),document.addEventListener(Tn.END,()=>{Wi()}),Y(v.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(je))t.isConnected||je.delete(t);for(const[t,n]of Array.from(Gt))if(!t.isConnected){try{n()}catch{}Gt.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:bl,iframesInDom:document.querySelectorAll(Pi).length,suppressedCount:je.size,registeredCount:Gt.size,suppressedIframeIds:Array.from(je.keys()).map(ug)}))}const pL=250,hL=1e3,mL="os-drag-hover";let fg=!1,vl=null,_l=null,Oo=null,Mo=null,El=null;function pg(){Oo!==null&&(clearTimeout(Oo),Oo=null)}function hg(){Mo!==null&&(clearTimeout(Mo),Mo=null)}function Po(){pg(),hg(),_l=null}function mg(){hg(),Mo=setTimeout(()=>{Mo=null,Po()},hL)}function gL(e,t){const n=vl?.getById(e);if(!(!n||n.isFocused()||!q(v.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{vl?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function gg(e,t){e!==_l&&(pg(),_l=e,e!==null&&(Oo=setTimeout(()=>{Oo=null,gL(e,t)},pL)))}function wg(e,t,n){const o=ig(e,t);gg(o?oL(o):null,n)}const wL=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||wg(t.clientX,t.clientY,t.payload?.type??"")},yL=()=>{Po()};function bL(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 vL=e=>{mg();const t=El??(bL(e)?"os-file":"external");wg(e.clientX,e.clientY,t)},yg=()=>{Po()},_L=e=>{e.relatedTarget===null&&Po()};function EL(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 kL=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==mL)return;const n=EL(e.source);n&&(mg(),gg(n,typeof t.payloadType=="string"?t.payloadType:"external"))},SL=e=>{const t=e.detail;t?.payload&&(El=t.payload.kind??"")},AL=()=>{El=null,Po()};function CL(e){fg||(fg=!0,vl=e,document.addEventListener(be.MOVE,wL),document.addEventListener(be.END,yL),document.addEventListener(Tn.START,SL),document.addEventListener(Tn.END,AL),document.addEventListener("dragover",vL,!0),document.addEventListener("drop",yg,!0),document.addEventListener("dragend",yg,!0),document.addEventListener("dragleave",_L,!0),window.addEventListener("message",kL))}function bg(){const e=window.wp?.os;if(!e)return[];const t=e.windowManager,n=e.config;if(!t||!n)return[];const o=[],s=(r,a)=>({id:r.id,label:r.title,description:a,icon:r.icon,open:()=>t.open({id:r.id,baseId:r.id,url:r.url,title:r.title,icon:r.icon})});for(const r of n.dockItems??[])o.push(s(r,"Admin menu"));const i=q("os.open-command.items",o);return Array.isArray(i)?i:o}const IL={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=bg();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=bg(),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 xL(){yi(IL)}const Ae=[],LL=new Set;function vg(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=Ae.findIndex(n=>n.id===e.id);return t>=0?Ae[t]=e:Ae.push(e),kl(),()=>{const n=Ae.findIndex(o=>o.id===e.id);n>=0&&(Ae.splice(n,1),kl())}}function TL(e){const t=Ae.findIndex(n=>n.id===e);t>=0&&(Ae.splice(t,1),kl())}function NL(){return Ae.slice()}function kl(){for(const e of Array.from(LL))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 _g(){if(Ae.length===0)return;const e=Ae.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{Ae[0].open(),Wo(Ae[0].id,!0)}catch{}return}try{Ae[e].close(),Wo(Ae[e].id,!1)}catch{}const t=e+1;if(t<Ae.length)try{Ae[t].open(),Wo(Ae[t].id,!0)}catch{}}function Sl(e){const t=Ae.find(n=>n.id===e);if(t){for(const n of Ae)if(n.id!==e)try{n.isOpen()&&(n.close(),Wo(n.id,!1))}catch{}try{t.open(),Wo(t.id,!0)}catch{}}}let Eg=!1;function DL(){if(Eg)return;Eg=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),_g())},!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"&&_g()})}const Xe=le("os/presence",()=>({byUser:new Map,serverTimeMs:0})),RL=5*60*1e3;let kg=Date.now(),Sg=!1;function Ui(){kg=Date.now()}function OL(e){if(!e||!e.snapshot)return;const t=Xe.state.byUser,n=new Map(t),o=[];for(const[s,i]of Object.entries(e.snapshot)){const r=Number(s);if(!Number.isFinite(r)||r<=0)continue;const l={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=t.get(r);n.set(r,l),(!c||c.status!==l.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:l.status,entry:l})}Xe.state.byUser=n,typeof e.serverTimeMs=="number"&&(Xe.state.serverTimeMs=e.serverTimeMs),Xe.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 ML(){Sg||(Sg=!0,document.addEventListener("pointerdown",Ui,{capture:!0,passive:!0}),document.addEventListener("keydown",Ui,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||Ui()}),Le.contribute("openstation_presence_active",()=>!0),Le.contribute("openstation_user_active",()=>Date.now()-kg<RL),Le.subscribe("openstation_presence",e=>{OL(e)}))}function PL(e){const t=Xe.state.byUser.get(e);return t?t.status:"offline"}function WL(){return new Map(Xe.state.byUser)}function $L(e){return Xe.state.byUser.get(e)??null}function UL(e){return Xe.subscribe(t=>e(t))}function FL(){Ui()}function BL(e){if(!Array.isArray(e)||e.length===0)return;const t=Xe.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)){Xe.state.byUser=n,Xe.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 HL=Object.freeze({getStatus:PL,getAll:WL,getEntry:$L,subscribe:UL,markActive:FL,applyBatch:BL});function Ag(e){const t=new Set;let n=null;const o=new Set;e.onChange&&o.add(e.onChange);const s=()=>e.order().filter(a=>t.has(a)),i=()=>{const a=s();for(const l of o)try{l(a)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=a=>{const l=t.size,c=Array.from(t);a(),!(t.size===l&&c.every(d=>t.has(d)))&&i()};return{keys:s,has:a=>t.has(a),size:()=>t.size,anchor:()=>n,set(a){r(()=>{t.clear();for(const l of a)t.add(l)}),n=a.length>0?a[a.length-1]:null},add(a){r(()=>{t.add(a)}),n=a},remove(a){r(()=>{t.delete(a)}),n===a&&(n=null)},toggle(a){r(()=>{t.has(a)?t.delete(a):t.add(a)}),n=a},selectRange(a,l=!1){const c=e.order(),d=c.indexOf(a),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{l||t.clear(),t.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{l||t.clear();for(let g=f;g<=p;g+=1)t.add(c[g])})},selectAll(){const a=e.order();r(()=>{for(const l of a)t.add(l)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const a=new Set(e.order());let l=!1;return r(()=>{for(const c of Array.from(t))a.has(c)||(t.delete(c),l=!0)}),n!==null&&!a.has(n)&&(n=null),l},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const zL=".os-file-tile",GL="os-file-tile--selected",jL="os-selection-marquee",Cg=4,Ig=36,xg=12,Lg="data-os-marquee";function VL(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function qL(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(Lg,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(Lg)}}const KL=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note",YL="os-area--overview";function XL(e,t){const n=t.itemSelector??zL,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??KL,r=()=>Array.from(e.querySelectorAll(n)).filter(N=>t.keyOf(N)!==null),a=()=>{const N=[],U=new Map;r().forEach((H,O)=>{const V=H.parentElement??e;let D=U.get(V);D||(D=[],U.set(V,D),N.push(V)),D.push({key:t.keyOf(H),top:parseFloat(H.style.top)||0,left:parseFloat(H.style.left)||0,index:O})});const B=[];for(const H of N){const O=U.get(H)??[];O.sort((V,D)=>V.top!==D.top?V.top-D.top:V.left!==D.left?V.left-D.left:V.index-D.index);for(const V of O)B.push(V.key)}return B},l=t.order??a,c=Ag({order:l,onChange:N=>{p(),t.onChange?.(N),u(N)}}),d={},u=N=>{typeof document>"u"||(Nn={surface:t.surface??"",scope:t.scope??"",keys:N.slice(),count:N.length},Cl=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:Nn})))},f=N=>r().find(U=>t.keyOf(U)===N)??null,p=()=>{for(const N of r()){const U=t.keyOf(N),B=c.has(U);B!==N.hasAttribute("selected")&&(B?N.setAttribute("selected",""):N.removeAttribute("selected")),N.classList.toggle(GL,B),N.hasAttribute("selectable")||N.setAttribute("selectable","");const H=B?"true":"false";N.getAttribute("aria-selected")!==H&&N.setAttribute("aria-selected",H)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let g=null;const m=N=>{if(!(N.target instanceof Element))return;const U=N.target.closest(n);if(U&&e.contains(U)){const B=t.keyOf(U);if(B===null)return;if(g=B,N.stopPropagation(),N.shiftKey){c.selectRange(B,N.ctrlKey||N.metaKey);return}if(N.ctrlKey||N.metaKey){c.toggle(B);return}c.set([B]);return}if(R){R=!1;return}c.clear()};o.addEventListener("click",m);let h=null,b=null,y=null,I=[],R=!1,k=0,M=null,P=null;const W=N=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(N),P=N}catch{}},_=()=>{if(P===null||typeof o.releasePointerCapture!="function"){P=null;return}try{o.hasPointerCapture?.(P)&&o.releasePointerCapture(P)}catch{}P=null},w=(N,U)=>{const B=o.getBoundingClientRect();return{x:N-B.left+o.scrollLeft,y:U-B.top+o.scrollTop}},L=()=>{h?.remove(),h=null,b=null,y=null,M?.(),M=null,_(),k&&(cancelAnimationFrame(k),k=0),document.removeEventListener("pointermove",$),document.removeEventListener("pointerup",X),document.removeEventListener("pointercancel",Z),o.removeEventListener("lostpointercapture",Z),o.removeEventListener("scroll",A),window.removeEventListener("blur",Z)};function A(){if(!b||!y)return;const N=w(y.x,y.y),U=N.x-b.x,B=N.y-b.y;if(!h&&Math.abs(U)<Cg&&Math.abs(B)<Cg)return;h||(h=document.createElement("div"),h.className=jL,h.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(h),R=!0,M=qL(o),C());const H=Math.min(b.x,N.x),O=Math.min(b.y,N.y),V=Math.abs(U),D=Math.abs(B);h.style.left=`${H}px`,h.style.top=`${O}px`,h.style.width=`${V}px`,h.style.height=`${D}px`;const j=o.getBoundingClientRect(),G=j.left-o.scrollLeft,ae=j.top-o.scrollTop,fe={left:H+G,top:O+ae,right:H+V+G,bottom:O+D+ae},pe=[];for(const re of r()){const Ce=re.getBoundingClientRect();Ce.left<fe.right&&Ce.right>fe.left&&Ce.top<fe.bottom&&Ce.bottom>fe.top&&pe.push(t.keyOf(re))}c.set(Array.from(new Set([...I,...pe])))}function C(){if(k||typeof requestAnimationFrame!="function")return;const N=()=>{if(k=0,!h||!y)return;const U=o.getBoundingClientRect();if(VL(o)){let H=0;if(y.y<U.top+Ig?H=-xg:y.y>U.bottom-Ig&&(H=xg),H!==0){const O=o.scrollTop;o.scrollTop+=H,o.scrollTop!==O&&A()}}k=requestAnimationFrame(N)};k=requestAnimationFrame(N)}const $=N=>{b&&(y={x:N.clientX,y:N.clientY},A())},X=()=>{h&&(Al=Date.now()),L()},Z=()=>{L()},x=N=>{if(!s||N.button!==0||!(N.target instanceof Element)||o.classList.contains(YL)||N.target.closest(n))return;const U=N.target.closest(i);U&&U!==o&&o.contains(U)||(b=w(N.clientX,N.clientY),y={x:N.clientX,y:N.clientY},typeof N.pointerId=="number"&&W(N.pointerId),I=N.ctrlKey||N.metaKey||N.shiftKey?c.keys():[],I.length===0&&c.clear(),document.addEventListener("pointermove",$),document.addEventListener("pointerup",X),document.addEventListener("pointercancel",Z),o.addEventListener("lostpointercapture",Z),window.addEventListener("blur",Z),o.addEventListener("scroll",A,{passive:!0}))};o.addEventListener("pointerdown",x);const F=N=>{if(N.key==="a"&&(N.ctrlKey||N.metaKey)){N.preventDefault(),c.selectAll();return}if(N.key==="Escape"){if(h||b){L();return}c.size()>0&&c.clear();return}const U=N.key==="ArrowRight"||N.key==="ArrowDown",B=N.key==="ArrowLeft"||N.key==="ArrowUp";if(!U&&!B)return;const H=U?1:-1,O=l();if(O.length===0)return;const V=g??c.anchor(),D=V===null?-1:O.indexOf(V),j=Math.min(O.length-1,Math.max(0,D<0?0:D+H));N.preventDefault();const G=O[j];g=G,N.shiftKey?c.selectRange(G):c.set([G]),f(G)?.focus()};return e.addEventListener("keydown",F),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){L(),o.removeEventListener("click",m),o.removeEventListener("pointerdown",x),e.removeEventListener("keydown",F),Cl===d&&(Nn=null,Cl=null)}}}let Al=0;function ZL(){return Al>0&&Date.now()-Al<500}let Nn=null,Cl=null;function JL(){return Nn?{...Nn,keys:Nn.keys.slice()}:null}function Il(e){return typeof e.sort=="number"?e.sort:100}function QL(e,t){return de(E("%1$s (%2$d items)","desktop-mode"),e,t)}function Tg(e,t){if(e.length===0)return[];const n=e.map(a=>{const l=t(a);return Array.isArray(l)?l:[]});if(e.length===1)return n[0];const o=e.length,s=[],i=a=>a.multiId??a.id;for(const a of n[0]){const l=i(a),c=[];let d=!1;for(const p of n){const g=p.find(m=>i(m)===l);if(!g||g.multi!==!0){d=!0;break}c.push(g)}if(d||s.some(p=>p.id===l))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):QL(u.label,o);s.push({id:l,label:f,icon:u.icon,disabled:c.some(p=>p.disabled===!0),danger:c.some(p=>p.danger===!0),sort:Math.min(...c.map(Il)),multi:!0,onClick:async p=>{const g=new Map,m=[];c.forEach((h,b)=>{const y=h.bulk;if(typeof y!="function"){m.push(h);return}const I=g.get(y);I?I.push(e[b]):g.set(y,[e[b]])});for(const[h,b]of g)try{await h(b)}catch(y){console.error(`[openstation] selection action '${l}' failed for a batch:`,y)}for(const h of m)try{await h.onClick(p)}catch(b){console.error(`[openstation] selection action '${l}' failed for one item:`,b)}}})}s.sort((a,l)=>{const c=Il(a),d=Il(l);return c!==d?c-d:a.label.localeCompare(l.label)});const r=q("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function Ng(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 xl=8;function Dg(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function Ll(e){Dg(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-xl)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-xl)}px`)})}function Rg(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,Dg(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-xl)}px`)})}const e1="os-wallpaper-menu";let Dn=null,Tl=null,Og=0;function Nl(){if(!Dn)return;const e=Dn.dataset.menuScope??"selection",t=Tl;Dn.dispatchEvent(new CustomEvent("tile-menu-closed")),Dn.remove(),Dn=null,Tl=null,t?.(),T(`os.${e}.menu.closed`,{})}function t1(e,t){Nl();const n=++Og;Ps(()=>n===Og,()=>n1(e,t))}function n1(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(e1),o&&a.classList.add(o),a.dataset.menuScope=s;for(const[u,f]of Object.entries(n??{}))a.dataset[u]=f;a.style.left=`${e.x}px`,a.style.top=`${e.y}px`;const l=new Map;for(const u of t){l.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.danger&&f.setAttribute("danger",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",o1(u.icon)),f.textContent=u.label,a.appendChild(f)}a.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=l.get(f.id);p&&(Nl(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(g=>{console.error(`[openstation] menu action '${p.id}' threw:`,g)}))}),document.body.appendChild(a),Dn=a,Tl=r??null,Ll(a);const c=Ng(a,{close:()=>Nl()});a.addEventListener("tile-menu-closed",c);const d=t.map(u=>u.id);i?.(d),T(`os.${s}.menu.opened`,{items:d,count:t.length})}function o1(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const s1={active:JL,resolveCommonActions:Tg,createModel:Ag};let $o=null;function i1(){Le.contribute("openstation_content_changes_seen_ts",()=>$o===null?0:$o),Le.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===""||(ja(`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 r1="desktop_mode_nonces",Dl=new Map;let Mg=!1;function Rl(e,t){if(typeof e!="string"||e==="")return()=>{};let n=Dl.get(e);return n||(n=new Set,Dl.set(e,n)),n.add(t),()=>{n.delete(t)}}function a1(){Mg||(Mg=!0,Le.subscribe(r1,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=Dl.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)}}}),l1())}function l1(){Rl("wp_rest",c1),Rl("desktop-mode-plugins",e=>{Pg("desktop-mode-plugins","ajaxNonce",e)}),Rl("updates",e=>{Pg("desktop-mode-plugins","updatesNonce",e)})}function c1(e){const t=d1();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=Wg();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Pg(e,t,n){const s=Wg()?.[e];s&&typeof s=="object"&&(s[t]=n)}function d1(){if(!(typeof window>"u"))return window.openStationConfig}function Wg(){if(!(typeof window>"u"))return window.openStationWindowConfig}const u1="desktop_mode_auth",f1=5e3,$g=1e3,p1=1e4;let Ug=!1,Fi=!1,Ol=!1,Bi=0,Fg=0,Uo=0,Rn=null,Bg=0,Hg=null,zg=null,Gg=()=>{try{window.location.reload()}catch{}};function Ml(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function Pl(e=$g){const t=Date.now();if(t<Uo){Rn===null&&(Rn=window.setTimeout(()=>{Rn=null,Uo=Date.now()+$g,Ml()},Uo-t));return}Uo=t+e,Ml()}function h1(){Fi=!0,!Ol&&(Ol=!0,T(v.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function m1(){for(const e of g1())try{e.contentWindow?.location.reload()}catch{}}function g1(){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 Wl(){const e=Date.now();e-Bg<p1||(Bg=e,Fi=!1,Ol=!1,Rn!==null&&(window.clearTimeout(Rn),Rn=null),Uo=0,Pl(),m1(),T(v.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function w1(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(Bi<=0){Bi=t;return}t!==Bi&&Gg()}}function y1(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<Fg||(Fg=o+f1,Ml())}function b1(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");zg=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&Pl(),t=n}),zg.observe(e,{attributes:!0,attributeFilter:["class"]})}function v1(e={}){Ug||(Ug=!0,Bi=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(Gg=e.reloadShell),Le.subscribe("wp-auth-check",t=>{if(t===!1){h1();return}t===!0&&Fi&&Wl()}),Le.subscribe("nonces_expired",()=>{if(Fi){Wl();return}Pl()}),Le.subscribe(u1,w1),Hg=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&Wl()},window.addEventListener("message",Hg),b1())}const On=12;function $l(e,t){const n=ce(e,t.adminUrl);return(t.dockItems||[]).find(o=>ce(o.url,t.adminUrl)===n||(o.submenu||[]).some(s=>ce(s.url,t.adminUrl)===n))}function Ul(e,t){const n=Math.max(200,t.width-On*2),o=Math.max(200,t.height-On*2),s=Math.min(e.width,n),i=Math.min(e.height,o),r=Math.max(0,t.width-s-On),a=Math.max(0,t.height-i-On),l=Math.max(On,Math.min(e.x,r)),c=Math.max(On,Math.min(e.y,a));return{x:l,y:c,width:s,height:i}}const jg=window.location.origin;function _1(e,t){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let l;try{l=new URL(a,window.location.href)}catch(m){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",a,m);return}if(l.origin!==jg)return;let c;try{c=new URL(t.adminUrl).pathname}catch(m){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,m),c="/wp-admin/"}if(!l.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(l.pathname)||l.searchParams.has("action")&&l.searchParams.get("action")==="logout"||l.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Ge(l.href)))return;const d=ce(l.href,t.adminUrl),u=$l(l.href,t),f=(i.textContent||"").trim()||u?.title||"",p=!!i.closest("#wp-admin-bar-new-content"),g={id:d,baseId:d,multi:!!u?.multi||p,url:l.href,parentUrl:u?.url??l.href,title:u?.title||f,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu,selfLabel:u?.selfLabel};if(p){e.openNew(g);return}e.open(g)},!0)}function E1(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.total!="number"||!Number.isFinite(t.total)?null:{total:Math.max(0,Math.floor(t.total)),formatted:typeof t.formatted=="string"&&t.formatted!==""?t.formatted:String(t.total),text:typeof t.text=="string"?t.text:"",url:typeof t.url=="string"?t.url:""}}function k1(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 S1(e){const t=E1(e);if(!t)return;let n=document.getElementById("wp-admin-bar-updates");if(t.total<=0){n&&(n.style.display="none");return}if(!n){const i=document.getElementById("wp-admin-bar-root-default");if(!i||(n=k1(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 A1="os-registry-changed";function C1(e,t){const n=new Set;if(Array.isArray(e))for(const r of e)r&&typeof r.id=="string"&&n.add(r.id);const o=new Set;for(const r of t)r&&typeof r.id=="string"&&o.add(r.id);const s=[];for(const r of o)n.has(r)||s.push(r);const i=[];for(const r of n)o.has(r)||i.push(r);return{added:s,removed:i}}function Fl(e,t,n){const{added:o,removed:s}=C1(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(A1,{detail:i}))}function I1(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:l,syncServerWindowActions:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:g,renderIcons:m,syncShortcuts:h}=e;return function(y){const I=y.dockItems,R=y.nativeWindows,k=y.serverWidgets,M=y.serverWallpapers,P=y.serverCommandScripts,W=y.serverCommands,_=y.serverSettingsTabScripts,w=y.serverSettingsTabs,L=y.serverDockRailRendererScripts,A=y.serverTitleBarButtonScripts,C=y.serverWindowActionScripts,$=y.serverUnfocusEffectScripts,X=y.serverWindowLinkRendererScripts,Z=y.serverWindowNotices,x=y.serverGames,F=y.serverDesktopThemes,N=y.desktopIcons;if(!Array.isArray(I)||I.length===0)return;const U=n.dockItems;if(t(I),n.dockItems=I,Fl("dock-items",U,I),h?.(),Array.isArray(R)){const B=n.nativeWindows;o(R),n.nativeWindows=R,Fl("native-windows",B,R)}if(Array.isArray(k)&&(s(k),n.serverWidgets=k),Array.isArray(M)&&(i(M),n.serverWallpapers=M),Array.isArray(x)&&(p(x),n.serverGames=x),Array.isArray(F)&&(g?.(F),n.serverDesktopThemes=F),Array.isArray(P)&&(r(P,Array.isArray(W)?W:void 0),n.serverCommandScripts=P,Array.isArray(W)&&(n.serverCommands=W)),Array.isArray(_)&&(a(_,Array.isArray(w)?w:void 0),n.serverSettingsTabScripts=_,Array.isArray(w)&&(n.serverSettingsTabs=w)),Array.isArray(A)&&(l(A),n.serverTitleBarButtonScripts=A),Array.isArray(C)&&(c(C),n.serverWindowActionScripts=C),Array.isArray($)&&(d($),n.serverUnfocusEffectScripts=$),Array.isArray(X)&&(u(X),n.serverWindowLinkRendererScripts=X),Array.isArray(L)&&(f(L),n.serverDockRailRendererScripts=L),Array.isArray(Z)&&(Zh(Z),n.serverWindowNotices=Z),Array.isArray(N)){const B=n.desktopIcons;m(N),n.desktopIcons=N,Fl("desktop-icons",B,N)}S1(y.updateCounts)}}const x1=8e3,L1=600;function T1(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:m,renderIcons:h,syncShortcuts:b}=e,y=I1({applyDockItems:L=>t?.applyDockItems(L),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:m,renderIcons:h,syncShortcuts:b});let I=typeof o.menuSig=="string"?o.menuSig:"",R=!1,k=null,M=!1,P=!1;const W=()=>{if(!o.adminUrl)return Promise.resolve();const L=(()=>{try{const A=new URL("admin.php",o.adminUrl);return A.searchParams.set("openstation_chromeless","1"),A.searchParams.set("openstation_menu_refresh","1"),A.toString()}catch{return null}})();return L?new Promise(A=>{const C=document.createElement("iframe");C.setAttribute("aria-hidden","true"),C.tabIndex=-1,C.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",C.src=L;let $=!1;const X=()=>{$||($=!0,window.clearTimeout(x),window.removeEventListener("message",Z),C.parentNode&&C.parentNode.removeChild(C),A())},Z=F=>{if(F.source!==C.contentWindow)return;const N=F.data;!N||N.type!=="os-plugins-changed"||X()},x=window.setTimeout(()=>{T(v.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),X()},x1);window.addEventListener("message",Z),document.body.appendChild(C)}):Promise.resolve()},_=()=>{if(M){P=!0;return}M=!0,W().finally(()=>{M=!1,P&&(P=!1,_())})},w=()=>{k!==null&&window.clearTimeout(k),k=window.setTimeout(()=>{k=null,_()},L1)};return window.addEventListener("message",L=>{if(L.origin!==jg)return;const A=L.data;if(A){if(A.type==="os-plugins-changed"){A.payload&&(y(A.payload),typeof A.payload.menuSig=="string"&&(I=A.payload.menuSig));return}if(A.type==="os-updates-changed"){w();return}if(A.type==="os-menu-signature"){const C=A.sig;typeof C=="string"&&C!==""&&C!==I&&!R&&(R=!0,W().finally(()=>{R=!1}))}}}),W}function N1(e){if(!e)return!1;if(Array.isArray(e.windows)&&e.windows.length>0)return!0;if(typeof e.updated!="number"||e.updated<=0||!Array.isArray(e.desktops)||e.desktops.length===0)return!1;if(e.desktops.length>1)return!0;const t=e.desktops[0];return t?.id&&t.id!=="desktop-1"?!0:!!e.activeDesktop&&e.activeDesktop!=="desktop-1"}function D1(e,t,n=5e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=l=>{window.clearTimeout(a),document.removeEventListener("os-window-opened",r),s(l)},r=l=>{l.detail?.windowId===t&&i(e.getById(t)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function R1(e,t,n,o){const s=n.getBoundingClientRect();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=Ul(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 D1(e,r.id);continue}const a=Ul(r,s),l=$l(r.url,t),c=await e.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!l?.multi,url:r.url,parentUrl:l?.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:l?.submenu,selfLabel:l?.selfLabel});if(Array.isArray(r.externalTabs))for(const d of r.externalTabs)d&&typeof d.url=="string"&&d.url!==""&&c.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 O1(e,t){if(Ge(t.currentPage))return;const n=ce(t.currentPage,t.adminUrl),o=$l(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 M1(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function Bl(e,t,n,o){const s=yu(t,n),i=window.fetch(t,s);if(i.then(a=>{if(a.status===401||a.status===403){let l;typeof t=="string"?l=t:t instanceof URL?l=t.href:l=t.url,y1(a.status,l)}},()=>{}),o?.silent)return i;let r=o?.window;return!r&&o?.windowId&&(r=e.getById(o.windowId)??null),r||(r=e.getFocused()),r&&typeof r.trackActivity=="function"&&r.trackActivity(i.then(a=>{if(!a.ok)throw new Error(P1(a));return a})).catch(()=>{}),i}function P1(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return de(E("Request failed (HTTP %s)."),t)}const W1=500,$1=1500;function U1(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 c=e.snapshot();try{await Bl(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:c}),keepalive:!0},{silent:!0})}catch(d){T(v.SHELL_ERROR,{scope:"session-save",error:d})}finally{o=!1,s&&(s=!1,l())}},a=()=>{n!==null&&(clearTimeout(n),n=null),s=!1;const c=e.snapshot(),d=new Blob([JSON.stringify({session:c})],{type:"application/json"}),u=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);navigator.sendBeacon&&navigator.sendBeacon(u,d)||r()},l=()=>{n!==null&&clearTimeout(n);let c=W1;if(i!==0){const d=Date.now()-i;c=Math.max(c,$1-d)}n=window.setTimeout(()=>{n=null,r()},c)};return window.addEventListener("pagehide",a),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&a()}),l}const F1=120;function B1(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),Y(v.DESKTOP_CREATED,"desktop-mode/session-save",e),Y(v.DESKTOP_CLOSED,"desktop-mode/session-save",e),Y(v.DESKTOP_SWITCHED,"desktop-mode/session-save",e)}function H1(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;T(v.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,F1)}),document.addEventListener("visibilitychange",()=>{T(v.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function z1(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return q(v.DOCK_TILE_CLASS,e,o)}function G1(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return q(v.DOCK_TILE_ELEMENT,e,o)}function j1(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};return q(v.DOCK_TILE_TOOLTIP,e,o)}function V1(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(v.DOCK_TILE_RENDERED,{...o,el:e})}const q1=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),Hl=new Set;function K1(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(q1))return!0;for(const n of Hl)if(t.closest(n))return!0;return!1}function Y1(e){return typeof e!="string"||e.trim()===""?()=>{}:(Hl.add(e),()=>{Hl.delete(e)})}const pt=new Map,X1=window.location.origin;function Vg(e){let t=pt.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},pt.set(e,t)),Z1(e,t),t}function Z1(e,t){const n=zl(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(()=>Mn(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function J1(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function zl(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 Q1(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 Mn(e){const t=zl(e);if(!t||!t.contentWindow)return;const n=pt.get(e),o=n?Q1(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},X1)}catch{}}Y(v.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&pt.has(t.windowId)&&Mn(t.windowId)}),Y(v.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=pt.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const Ct=new Map,eT=1e3;function qg(e,t,n){const o=Ct.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,!!Ct.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const l=o.channels.get(a.channel);if(l)for(const c of l)try{c(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=Ct.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>qg(e,t,n),eT))})}function tT(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function nT(e,t){const n=Ct.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let oT=0;const Kg={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=Vg(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),Mn(e),()=>{const r=pt.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const l=a.indexOf(s);l>=0&&a.splice(l,1),a.length===0&&r.headers.delete(t),Mn(e),Yg(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=Vg(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,Mn(e)),()=>{const i=pt.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),Mn(e)),Yg(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=zl(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=Kg.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",l=new URL(a,window.location.origin);l.searchParams.set(i,t),o.src=l.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const e=window.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(e,t,n){nT(e,{id:++oT,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=Ct.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},Ct.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=tT();r&&qg(e,r.restUrl,r.restNonce)}return()=>{const r=Ct.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),Ct.delete(e))}}}};function Yg(e){const t=pt.get(e);t&&t.headers.size===0&&t.observers.size===0&&(J1(t),pt.delete(e))}async function Pn(e){return await Sr(Ar()),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 sT(e){const t=[];for(const l of e.getVisibleRects()){if(l.state==="minimized"||l.element.offsetParent===null)continue;const c=l.element.getBoundingClientRect();t.push({id:`window:${l.windowId}`,kind:"window",rect:Xg(c),face:"top",element:l.element})}const n=document.getElementById("os-shell");if(n){const l=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:l.left,y:l.bottom-1,width:l.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const l of Array.from(o)){const c=l.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const d=l.getAttribute("data-os-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,d==="bottom"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:c.width,height:1},face:"top",element:l}):d==="right"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:l}):t.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:l})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(l=>{const c=l.getBoundingClientRect();if(c.width===0&&c.height===0)return;const d=l.dataset.widgetId??String(r++);t.push({id:`widget:${d}`,kind:"widget",rect:Xg(c),face:"top",element:l})});const a=q(v.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function Xg(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const iT="__openstationKeyedListKey",rT="__openstationKeyedListData";function aT(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function lT(e,t,n){const o=aT(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const l of t){const c=String(n.keyOf(l));a.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),a.add(c);const d=s.get(c);if(d){const f=d.data;n.updateItem?.(d.el,l,f),d.data=l,i.set(c,d),r.push(d.el);continue}const u=n.buildItem(l);u[iT]=c,u[rT]=l,i.set(c,{el:u,data:l}),r.push(u)}for(const[l,c]of s)i.has(l)||c.el.remove();for(let l=0;l<r.length;l++){const c=r[l],d=e.children[l];d!==c&&e.insertBefore(c,d??null)}o.byKey=i}function cT(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function dT(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:l=W=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",W)}}=e;let c=e.sentinel??null;c||(c=document.createElement("div"),c.dataset.osInfiniteListSentinel="",c.style.height="1px",t.appendChild(c));const d=new Set;let u=r,f=!0,p=!1,g=null,m=0,h=!1,b=null;const y=W=>{if(p!==W){p=W;try{a(W)}catch(_){l(_)}}},I=()=>{b&&(b.disconnect(),b=null)},R=()=>{b||!c||h||(b=new IntersectionObserver(W=>{for(const _ of W)_.isIntersecting&&k()},{rootMargin:i}),b.observe(c))},k=async()=>{if(h||p||!f)return;y(!0),g=new AbortController;const W=g;try{const _=await n(u,W.signal);if(h||W!==g)return;let w=0;const L=document.createDocumentFragment();for(const A of _.items??[]){const C=String(o(A));if(d.has(C))continue;d.add(C);const $=s(A,m+w);L.appendChild($),w++}w>0&&(c&&c.parentNode===t?t.insertBefore(L,c):t.appendChild(L),m+=w),u=_.nextCursor??null,u||(f=!1,I())}catch(_){if(_?.name==="AbortError")return;l(_)}finally{W===g&&(y(!1),g=null)}},M=()=>{if(h)return;g?.abort(),g=null,d.clear(),u=r,f=!0,m=0;const W=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);W&&c&&t.appendChild(c),y(!1),R(),k()},P=()=>{h||(h=!0,I(),g?.abort(),g=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,y(!1))};return R(),k(),{reset:M,loadMore:k,hasMore:()=>f,isLoading:()=>p,destroy:P}}const uT=520,fT=720,pT=500;function hT(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=gT(),o=wT();return Fe(nt(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:e})},{source:"desktop-mode/oauth-start"}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`[openstation] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>mT(s,e,t))}function mT(e,t,n){return new Promise((o,s)=>{const i=n.width??uT,r=n.height??fT,a=Math.max(0,Math.floor((window.screen.width-i)/2)),l=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${l}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(e.authorize_url,`os-oauth-${t}`,c);if(!d){s(new Error("[openstation] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let f=null,p=!1;const g=()=>{p||(p=!0,window.removeEventListener("message",m),f!==null&&(window.clearInterval(f),f=null))},m=h=>{if(h.origin!==u)return;const b=h.data;if(!b||b.type!=="os-oauth-callback")return;const y=b.payload;if(g(),y&&y.ok)o(y);else{const I=y?.reason??"unknown",R=y?.message??"OAuth flow failed",k=new Error(`[openstation] startOAuth(${t}) failed: ${I} — ${R}`);k.cause=y,s(k)}};window.addEventListener("message",m),f=window.setInterval(()=>{d.closed&&(g(),s(new Error(`[openstation] startOAuth(${t}) cancelled — popup closed before completing.`)))},pT)})}function Zg(){return window.openStationConfig??{}}function gT(){const e=Zg().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function wT(){const e=Zg().restNonce;return typeof e=="string"&&e!==""?e:null}const yT="",bT="system-default",vT={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function _T(e,t,n={}){const o=t===yT,s=o?null:uu(t);if(!o&&!s)return{};const i=o?bT:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const a=qv(o?vT:s.recommendedOsSettings),l=Object.keys(a);if(l.length===0)return{};const c=e,d={};for(const u of l){const f=a[u];typeof f!="string"&&typeof f!="number"||!(u in e)||typeof c[u]!=typeof f||(c[u]=f,d[u]=f)}return Object.keys(d).length===0?{}:(r||(e.appliedThemeRecommendations=[...e.appliedThemeRecommendations,i].slice(-64)),d)}const Hi=["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-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"],Jg=new Set(Hi);let zi=null;function Gl(){return!!window.openStationComponents}function ET(){return window.openStationConfig?.componentsBundleUrl??""}function kT(e){return new Promise((t,n)=>{const o=()=>{if(Gl()){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){Gl()?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 ST(e){const t=e.filter(n=>!Jg.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 ${Hi.length} tags; see docs/components-reference.md for the list. The others in this call still loaded.`)}async function AT(e){if(e){if(ST(e),e.filter(o=>Jg.has(o)&&!customElements.get(o)).length===0)return}else if(Gl())return;const t=ET();t&&(zi||(zi=kT(t).catch(n=>{throw zi=null,n})),await zi)}const CT=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","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","selection","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","getWindowParams","debug","registerNativeUrlRemap","fetch"]);function IT(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:l,registerWindow:c,openWindowById:d,openNewWindowById:u,loadWindowScriptById:f,placeSystemTile:p,setDefaultWindow:g,refreshMenu:m,openOsSettings:h,aiAssistant:b,dragBridge:y,dragManager:I,connect:R,getConnection:k,wallpaperSuspend:M,mio:P,config:W}=e,_={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,iconSet:sv,files:r,confirm:Pn,saveSession:a,hooks:zb(),HOOKS:v,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:w=>{hn(w),s.apply()},registerWidget:w=>{dl(w)},widgetLayer:l,widgets:{redock:w=>{l?.redock(w)}},loadVendorScript:ke,getWallpaperSurfaces:()=>sT(t),wallpaper:M,mio:P,games:Op,registerWindow:c,openWindow:d,openNewWindow:u,loadWindowScript:f,loadComponents:AT,fetch:(w,L,A)=>Bl(t,w,L,A),repaintLoadingOverlays:Af,cloneTemplate:vm,onWindow:_I,createInfiniteList:dT,startOAuth:hT,registerSystemTile:w=>{p(w),T(v.DOCK_ITEM_APPENDED,{id:w.id})},registerModule:mp,loadModules:ka,whenReady:ud,ready:ud,isReady:jb,setDefaultWindow:g,refreshMenu:m,config:W,ai:b,dragBridge:y,dragManager:I,registerCommand:yi,unregisterCommand:Gp,listCommands:jp,registerDestructiveAdminAction:QE,unregisterDestructiveAdminAction:Cf,listDestructiveAdminActions:e0,registerSettingsTab:qp,unregisterSettingsTab:Kp,listSettingsTabs:Yp,registerDockRailRenderer:Cd,unregisterDockRailRenderer:av,listDockRailRenderers:dv,openOsSettings:h,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:w=>s.subscribeOsSettings(w),updateOsSettings:(w,L={})=>{if(typeof w.wallpaper=="string"&&(s.state.wallpaper=w.wallpaper),typeof w.accent=="string"&&(s.state.accent=w.accent),typeof w.dockSize=="string"&&(s.state.dockSize=w.dockSize),typeof w.windowRadius=="string"&&(s.state.windowRadius=w.windowRadius),typeof w.adminBarMode=="string"&&(s.state.adminBarMode=w.adminBarMode),typeof w.desktopLayout=="string"&&(s.state.desktopLayout=w.desktopLayout),typeof w.dockPlacement=="string"&&(s.state.dockPlacement=w.dockPlacement),typeof w.desktopTheme=="string"&&(s.state.desktopTheme=w.desktopTheme),typeof w.unfocusEffect=="string"&&(s.state.unfocusEffect=w.unfocusEffect),typeof w.windowReveal=="string"&&(s.state.windowReveal=w.windowReveal),typeof w.windowRevealDuration=="number"&&(s.state.windowRevealDuration=w.windowRevealDuration),typeof w.dockRailRenderer=="string"&&(s.state.dockRailRenderer=w.dockRailRenderer),typeof w.windowLinkRenderer=="string"&&(s.state.windowLinkRenderer=w.windowLinkRenderer),(w.windowLinkVisibility==="focus"||w.windowLinkVisibility==="always"||w.windowLinkVisibility==="off")&&(s.state.windowLinkVisibility=w.windowLinkVisibility),typeof w.windowLinksEnabled=="boolean"&&(s.state.windowLinksEnabled=w.windowLinksEnabled),typeof w.windowLinkRaiseOnFocus=="boolean"&&(s.state.windowLinkRaiseOnFocus=w.windowLinkRaiseOnFocus),typeof w.windowLinkHighlight=="boolean"&&(s.state.windowLinkHighlight=w.windowLinkHighlight),w.ai&&typeof w.ai=="object"&&(s.state.ai={...s.state.ai,...w.ai}),typeof w.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=w.nativePostsEnabled),typeof w.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=w.nativePagesEnabled),typeof w.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=w.nativeUsersEnabled),typeof w.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=w.nativePluginsEnabled),typeof w.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=w.nativeCommentsEnabled),typeof w.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=w.foldersSharingEnabled),typeof w.showPostStatusRibbons=="boolean"&&(s.state.showPostStatusRibbons=w.showPostStatusRibbons),typeof w.developerModeEnabled=="boolean"&&(s.state.developerModeEnabled=w.developerModeEnabled),Array.isArray(w.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=w.nativePostsHiddenColumns.filter(A=>typeof A=="string"&&A!=="").slice(0,32)),w.navPlacement&&typeof w.navPlacement=="object"){const A=["both","rail","desktop","hidden"],C={};for(const[$,X]of Object.entries(w.navPlacement))typeof $!="string"||$===""||typeof X!="string"||!A.includes(X)||(C[$]=X);s.state.navPlacement=C}if(Array.isArray(w.navOrder)&&(s.state.navOrder=w.navOrder.filter(A=>typeof A=="string"&&A!=="").slice(0,256)),w.dockPromotedPositions&&typeof w.dockPromotedPositions=="object"){const C={};for(const[$,X]of Object.entries(w.dockPromotedPositions)){if(typeof $!="string"||$===""||!X||typeof X!="object")continue;const Z=X;if(!(typeof Z.x!="number"||typeof Z.y!="number"||!Number.isFinite(Z.x)||!Number.isFinite(Z.y)||Math.abs(Z.x)>1e5||Math.abs(Z.y)>1e5)&&(C[$]={x:Z.x,y:Z.y},Object.keys(C).length>=256))break}s.state.dockPromotedPositions=C}s.save(L),(typeof w.wallpaper=="string"||typeof w.accent=="string"||typeof w.dockSize=="string"||typeof w.windowRadius=="string"||typeof w.adminBarMode=="string"||typeof w.desktopLayout=="string"||typeof w.dockPlacement=="string"||typeof w.dockRailRenderer=="string"||typeof w.desktopTheme=="string")&&s.apply(),(w.navPlacement||w.navOrder)&&o?.refresh()},deriveWindowId:(w,L)=>ce(w,L??W.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:w=>o?.getSystemTile(w)??null,getMenuItems:()=>o?.getMenuItems()??[],getNavItems:()=>o?.getNavItems()??[],getNav:()=>o?.getNav()??null,renderIcon:xo,applyTileClasses:z1,applyTileElement:G1,applyTileTooltip:j1,dispatchTileRendered:V1,isDockElement:K1,registerDockSelector:Y1,registerTitleBarButton:vi,unregisterTitleBarButton:MS,listTitleBarButtons:WS,registerWindowAction:FS,unregisterWindowAction:BS,listWindowActions:zS,registerUnfocusEffect:ki,unregisterUnfocusEffect:bA,listUnfocusEffects:Ka,registerWindowReveal:Ue,unregisterWindowReveal:Bv,listWindowReveals:Zd,relations:c0,registerWindowLinkRenderer:nh,unregisterWindowLinkRenderer:jS,listWindowLinkRenderers:oh,registerWindowTheme:Rh,unregisterWindowTheme:Oh,listWindowThemes:Mh,desktopThemes:{list:Zv,getActive:Hr,setActive:va,subscribe:Qv,resolveIcon:zs,resolveIconColor:zr,applyRecommendedOsSettings:w=>{const L=w??Hr()??"";if(L==="")return{};const A=_T(s.state,L,{force:!0});return Object.keys(A).length>0&&(s.save(),s.apply()),A}},applyWindowTheme:(w,L)=>{const A=t.getById(w);A&&A.setAppearanceTheme(L)},registerWindowControl:Eo,unregisterWindowControl:$h,listWindowControls:Uh,applyWindowControls:(w,L)=>{const A=t.getById(w);A&&A.setAppearanceControls(L)},registerWindowSlot:zh,unregisterWindowSlot:nl,listWindowSlots:Gh,applyWindowSlot:(w,L,A)=>{const C=t.getById(w);C&&C.setAppearanceSlot(L,A)},registerWindowNotice:Yh,unregisterWindowNotice:rl,listWindowNotices:Xh,dismissWindowNotice:dC,undismissWindowNotice:uC,registerWindowChrome:hC,unregisterWindowChrome:em,listWindowChromes:tm,applyWindowChrome:(w,L)=>{const A=t.getById(w);A&&A.setAppearanceChrome(L)},connect:R,getConnection:k,broadcast:ja,subscribe:En,registerPalette:vg,unregisterPalette:TL,listPalettes:NL,openPalette:Sl,devtools:Kg,createSharedStore:le,presence:HL,selection:s1,activity:Ee,heartbeat:Le,showToast:Q,notify:Oa,pwa:{promptInstall:Tx,undismissInstallHint:Nx,getState:po,subscribe:Wp,requestNotificationPermission:vS,getNotificationPermission:_S},renderKeyedList:lT,clearKeyedList:cT,registerNamespace:(w,L)=>{if(typeof w!="string"||w===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!L||typeof L!="object"){console.warn(`[openstation] registerNamespace("${w}"): api must be an object`);return}if(CT.has(w)){console.warn(`[openstation] registerNamespace("${w}"): name is reserved by the shell — pick a plugin-specific key`);return}_[w]=L},getWindowConfig:w=>{const L=window.openStationWindowConfig;if(!L||typeof L!="object")return;const A=L[w];return A===void 0?void 0:A},getWindowParams:w=>{const L=t.getById(w);if(L)return{...L.config.params??{}}},registerNativeUrlRemap:kt,debug:{window:w=>{const L=(W.nativeWindows??[]).find(x=>x.id===w);if(!L)return null;const A=L.scriptUrl||"";let C="unknown",$=!1;A&&(document.querySelector(`script[data-os-vendor="${A.replace(/"/g,'\\"')}"]`)?(C="lazy",$=!0):Array.from(document.querySelectorAll("script[src]")).find(N=>N.src===A)&&(C="eager",$=!0));const X=window.openStationWindowConfig,Z=!!(X&&typeof X=="object"&&Object.prototype.hasOwnProperty.call(X,w));return{id:w,scriptHandle:L.scriptHandle||"",scriptUrl:A,loadPath:C,tagInDom:$,configPresent:Z,extras:{hasTranslations:!!L.scriptTranslations,l10nCount:(L.scriptL10n??[]).length,beforeCount:(L.scriptBefore??[]).length,afterCount:(L.scriptAfter??[]).length}}}}};return _}function xT(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const jl=le("desktop-mode/layout",()=>({layout:"classic"}));function Qg(e){jl.state.layout!==e&&(jl.state.layout=e,jl.notify())}class ew{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 LT extends ew{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const Fo=new Map,Vl=new Set;function Ve(e){if(!e.type)throw new Error("[openstation] registerType: `type` is required.");if(!e.label)throw new Error("[openstation] registerType: `label` is required.");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),nw()}function TT(e){Fo.delete(e)&&(T("os.files.type-unregistered",e),nw())}function NT(e){const t=Fo.get(e);return t||null}function tw(){const e=Array.from(Fo.values()).slice(),t=q("os.files.types",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>o.sort!==s.sort?o.sort-s.sort:o.label.localeCompare(s.label)),n}function It(e){const t=Fo.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new LT(e,e.type)}function DT(e){return Vl.add(e),()=>Vl.delete(e)}function nw(){for(const e of Vl)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const Gi=new Map,ql=new Set;let Kl={};function ow(e){Kl={...e},Jl()}function Yl(){return{...Kl}}function Be(e){if(!e.id)throw new Error("[openstation] registerOpener: `id` is required.");if(!e.label)throw new Error("[openstation] registerOpener: `label` is required.");if(!Array.isArray(e.types)||e.types.length===0)throw new Error("[openstation] registerOpener: `types` must be a non-empty array.");if(!e.handler||typeof e.handler!="object")throw new Error("[openstation] registerOpener: `handler` is required.");Gi.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),Jl()}function RT(e){Gi.delete(e)&&(T("os.files.opener-unregistered",e),Jl())}function OT(e){return Gi.get(e)??null}function sw(){const e=Array.from(Gi.values()).slice(),t=q("os.files.openers",e),n=Array.isArray(t)?t:e;return n.sort((o,s)=>{const i=typeof o.sort=="number"?o.sort:100,r=typeof s.sort=="number"?s.sort:100;return i!==r?i-r:o.label.localeCompare(s.label)}),n}function Xl(e,t){return sw().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function Zl(e,t){const n=Xl(e,t);if(n.length===0)return null;const o=Kl[e];let s=null;return o&&(s=n.find(r=>r.id===o)??null),s||(s=n.find(r=>r.isDefault)??null),s||(s=n[0]),q("os.files.resolve-opener",s,e)??null}function MT(e){return ql.add(e),()=>ql.delete(e)}function Jl(){for(const e of ql)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let Bo=null;function PT(e){Bo=e}async function Ho(e,t){if(!Bo)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=Zl(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):Bo.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),l=Bo.openUrl({id:i,url:s,title:r,icon:a});return T("os.files.opened",{file:e,openerId:n.id,kind:"url"}),l}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=Bo.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 WT="dashicons-portfolio";function $T(){Ve({type:"shortcut",label:"Plugin shortcut",sort:1}),Ve({type:"folder",label:"Folder",sort:5}),Ve({type:"post",label:"Post",sort:10}),Ve({type:"attachment",label:"Media",sort:20}),Ve({type:"upload",label:"Uploaded file",sort:25}),Ve({type:"user",label:"User",sort:30}),Ve({type:"term",label:"Taxonomy term",sort:40}),Ve({type:"comment",label:"Comment",sort:50}),Ve({type:"bookmark",label:"Bookmark",sort:60}),Ve({type:"link",label:"Web link",sort:70}),Ve({type:"embed",label:"Embedded web window",sort:80})}const qe=le("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function iw(e){qe.state.activeAgent=e,qe.state.transcripts[e.id]||(qe.state.transcripts[e.id]=[]),qe.state.conversationIds||(qe.state.conversationIds={},qe.state.conversationsRev=0),qe.notify()}const rw="desktop-mode/v1/agents/conversations";async function aw(e,t,n={}){const o=await Fe(nt(e.restRoot,t),{...n,headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce,...n.headers??{}}},{source:"desktop-mode/agents",silent:!0}),s=await o.json().catch(()=>null);if(!o.ok){const i=s&&typeof s=="object"&&typeof s.message=="string"?s.message:`HTTP ${o.status}`;throw new Error(i)}return s}function UT(e){return e.filter(t=>!t.pending)}async function FT(e,t){const n=qe.state,o=UT(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await aw(t,`${rw}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await aw(t,rw,{method:"POST",body:JSON.stringify({agentId:e.id,messages:o})});n.conversationIds[e.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,qe.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const lw={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function cw(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function dw(e){if(e.type==="shortcut"){const t=e.data;let n=lw[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=cw(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=lw[String(n.type??"")],s=cw(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function BT(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function HT(e){return de(E('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 zT(e){return{kind:e.kind,id:e.id,title:e.title}}function uw(e,t="agents"){iw(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function GT(e,t,n,o,s){iw(e);const i=qe.state.transcripts[e.id],r=i.filter(l=>!l.pending&&l.role!=="error").map(l=>({role:l.role,text:l.text}));i.push({role:"user",text:t,at:Date.now(),attachment:s});const a={role:"agent",text:E("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(a),qe.notify();try{const l=await Fe(nt(n.restRoot,`desktop-mode/v1/agents/${e.id}/invoke`),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":n.restNonce},body:JSON.stringify({message:t,source:o,history:r})},{source:"desktop-mode/agents"}),c=await l.json().catch(()=>null);if(!l.ok){const u=c&&typeof c=="object"&&typeof c.message=="string"?c.message:`HTTP ${l.status}`;throw new Error(u)}const d=c;a.text=d.text||E("The agent finished without a text answer.","desktop-mode"),a.toolCalls=d.toolCalls,Array.isArray(d.callToActions)&&d.callToActions.length>0&&(a.callToActions=d.callToActions)}catch(l){a.role="error",a.text=l instanceof Error?l.message:String(l)}a.pending=!1,qe.notify(),FT(e,n)}function jT(e,t,n){return uw(e,"agents-drop"),GT(e,HT(t),n,"drag",zT(t))}let Ql=null;function fw(e){Ql=e}function zo(){if(!Ql)throw new Error("[openstation] files REST client called before installRestDeps().");return Ql}function VT(){return zo()}class ec 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 ge(e,t){const{baseUrl:n,nonce:o}=zo(),s=nt(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 Fe(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),a=await r.text();let l=null,c=null;if(a)try{l=JSON.parse(a)}catch(d){l=null,c=d}if(!r.ok){if(r.status===409){const u=l?.data?.data??l?.data;if(u&&typeof u=="object")throw new ec(u)}const d=l;throw new Error(`[openstation] files REST ${r.status}: ${d?.code??""} ${d?.message??""}`.trim())}if(l===null){if(c&&a){const d=a.slice(0,120).replace(/\s+/g," ");throw new Error(`[openstation] files REST ${r.status} returned non-JSON body — ${c.message}. First 120 chars: ${d}`)}throw new Error(`[openstation] files REST ${r.status}: empty or unparseable body.`)}return l}function Te(e=0){return ge(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function Go(e){return ge("/placements",{method:"POST",body:JSON.stringify(e)})}function Wn(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),ge(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function tc(e){return ge(`/placements/${e}`,{method:"DELETE"})}async function ji(e,t){const{baseUrl:n,nonce:o}=zo(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Fe(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 nc(){return ge("/folders",{method:"GET"})}function oc(e){return ge("/folders",{method:"POST",body:JSON.stringify(e)})}function pw(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),ge(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function sc(e){return ge(`/folders/${e}`,{method:"DELETE"})}function hw(e){return ge("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function mw(e){return ge(`/folders/${e}/shares`,{method:"GET"})}function gw(e,t){return ge(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function ww(e,t,n){return ge(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function yw(e,t){return ge(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function bw(e,t){return ge(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function vw(e,t){return ge(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function _w(e){return ge(`/folders/${e}/leave`,{method:"POST"})}function qT(){return ge("/folder-sharing-tables/purge",{method:"POST"})}function Ew(e){return ge(`/uploads/${e}/shares`,{method:"GET"})}function kw(e,t){return ge(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function Sw(e,t){return ge(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function Aw(e,t){return ge(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function Cw(e,t){return ge(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function Iw(e){return ge(`/uploads/${e}/leave`,{method:"POST"})}function KT(e,t){return ge(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function xw(e,t){return ge("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function qt(e){const{baseUrl:t,nonce:n}=zo(),o=nt(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function Lw(e){const{baseUrl:t,nonce:n}=zo(),o=nt(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const YT=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:ec,acceptFileShare:Aw,acceptShare:bw,createFolder:oc,createPlacement:Go,deleteFolder:sc,deletePlacement:tc,denyFileShare:Cw,denyShare:vw,ensureUploadPath:xw,getFilesRestDeps:VT,getFolderZipUrl:Lw,getUploadDownloadUrl:qt,installRestDeps:fw,inviteFileShare:kw,inviteShare:gw,leaveFileShare:Iw,leaveShare:_w,listFileShares:Ew,listFolders:nc,listPlacements:Te,listShares:mw,purgeFolderSharingTables:qT,renameUpload:KT,restoreTrashedItem:ji,revokeFileShare:Sw,revokeShare:yw,saveAssociations:hw,updateFolder:pw,updatePlacement:Wn,updateShareCapability:ww},Symbol.toStringTag,{value:"Module"})),XT="desktop-mode/files";function Ze(){return le(XT,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function $n(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function ht(e,t){const n=Ze(),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(),$n({kind:"placements-set",folderId:e})}function Vi(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=Ze(),o=new Map(n.state.placementsByFolder);for(const[a,l]of o)if(l.findIndex(d=>d&&d.id===e.id)>=0&&a!==e.parentId){const d=l.filter(Boolean),u=d.findIndex(f=>f.id===e.id);u>=0&&d.splice(u,1),o.set(a,d)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),$n({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function jo(e,t="local"){const n=Ze(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(l=>l&&l.id===e)>=0){const l=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,l),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),$n({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function qi(e){const t=Ze(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),$n({kind:"folders-set"})}function ic(e,t="local"){const n=Ze(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),$n({kind:"folder-upserted",folderRowId:e.id,source:t})}function rc(e,t="local"){const n=Ze(),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(),$n({kind:"folder-removed",folderRowId:e,source:t})}function ac(e){return Ze().subscribe(e)}function xt(){return Ze().getState()}function Tw(e){const t=xt(),n=t.placementsByFolder.get(e.parentId)?.find(o=>o&&o.id===e.id);if(n)return n;for(const o of t.placementsByFolder.values()){const s=o.find(i=>i&&i.id===e.id);if(s)return s}return e}const se={getState:xt,subscribe:ac,setFolderPlacements:ht,upsertPlacement:Vi,upsertFolder:ic,removePlacement:jo,removeFolder:rc,currentPlacement:Tw},ZT=ue`:host{display:inline-block}`,JT=ue`: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 ) )}`,ws=class ws extends Se{render(){return J`<span class="banner" part="banner"><slot></slot></span>`}};ws.props=["placement","tone"],ws.styles=[JT],ws.help=void 0;let lc=ws;xe("os-ribbon",lc);const ie="os-file-tile",Nw={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function QT(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function eN(){return window.wp?.os?.dragManager??null}const tN=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],Yn=class Yn extends Se{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(`${ie}--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 J``}_paint(){const t=this.getAttribute("type")??"",n=this.getAttribute("ref")??"",o=this.getAttribute("label")??"",s=this.getAttribute("icon")??"",i=this.getAttribute("thumbnail")??"",r=this.getAttribute("kind")??"entry",a=this.getAttribute("status")??"",l=this.hasAttribute("selected"),c=this.hasAttribute("selectable"),d=this.hasAttribute("missing"),u=this.hasAttribute("access-gated"),f=[ie,`${ie}--folder`,`${ie}--missing`,`${ie}--access-gated`,`${ie}--selected`];for(const b of f)this.classList.remove(b);this.classList.add(ie),r==="folder"&&this.classList.add(`${ie}--folder`),d&&this.classList.add(`${ie}--missing`),u&&this.classList.add(`${ie}--access-gated`),l&&this.classList.add(`${ie}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",c?"option":"listitem"),c?this.setAttribute("aria-selected",l?"true":"false"):this.removeAttribute("aria-selected"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const g=[`${ie}__visual`,`${ie}__label`,`${ie}__lock`];for(const b of g)this.querySelectorAll(`:scope > .${b}`).forEach(y=>y.remove());this.querySelectorAll(":scope > os-ribbon").forEach(b=>b.remove());const m=document.createElement("span");if(m.className=`${ie}__visual`,i){const b=document.createElement("img");b.src=i,b.alt="",b.loading="lazy",b.decoding="async",b.className=`${ie}__preview`,b.draggable=!1,m.appendChild(b)}else if(s){const b=xo(s,{title:o,className:`${ie}__icon`});m.appendChild(b)}this.appendChild(m);const h=document.createElement("span");if(h.className=`${ie}__label`,h.textContent=o,this.appendChild(h),u){const b=document.createElement("span");b.className=`${ie}__lock dashicons dashicons-lock`,b.setAttribute("aria-hidden","true"),this.appendChild(b)}if(a&&a!=="publish"&&Nw[a]&&QT()){const b=document.createElement("os-ribbon");b.setAttribute("placement","top-end"),b.setAttribute("tone",nN(a)),b.textContent=Nw[a],this.appendChild(b)}Vb(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=eN();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,a=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,l=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-l.left,offsetY:o.clientY-l.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};Yn.shadow=!1,Yn.props=tN,Yn.styles=[ZT],Yn.help=void 0;let cc=Yn;function nN(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}xe("os-tile",cc);function oN(e){const t=document.createElement("os-tile");if(t.setAttribute("type",e.type),t.setAttribute("ref",e.ref),t.setAttribute("label",e.label),e.icon&&t.setAttribute("icon",e.icon),e.thumbnail&&t.setAttribute("thumbnail",e.thumbnail),e.role&&t.setAttribute("kind",e.role),e.status&&t.setAttribute("status",e.status),e.missing&&t.setAttribute("missing",""),e.accessGated&&t.setAttribute("access-gated",""),e.dataset)for(const[o,s]of Object.entries(e.dataset))s!=null&&(t.dataset[o]=String(s));if(Array.isArray(e.extraClasses))for(const o of e.extraClasses)o&&t.classList.add(o);const n=q("os.tile.class",t.className,e);return n&&n!==t.className&&(t.className=n),typeof e.x=="number"&&typeof e.y=="number"&&(t.style.position="absolute",t.style.left=`${e.x}px`,t.style.top=`${e.y}px`),t}function sN(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(`${ie}--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 Dw(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:It(e.file).title()}function iN(e,t){const n=It(e.file),o=n.previewUrl(),s=Dw(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:Cm(e.file.ref)||i||zs(n_(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 rN(e,t){const n=oN(iN(e,t)),o=q("os.files.tile-class",ie,e);o&&o!==ie&&(n.className=o);const s=q("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=Tw(e),a=It(r.file);if(r.accessGated){Q({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}Ho(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 mt(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const Vo=new Map;function Ki(e,t){const n=Vo.get(e);return n?n.push(t):Vo.set(e,[t]),()=>{const o=Vo.get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&Vo.delete(e)}}function dc(e,t){const n=Vo.get(e);if(n)return n.find(o=>o.appliesTo(t))}function aN(e,t){return dc(e,t)?.acceptLabel}function lN(e,t){const n=dc(e.type,t);return n?n.accept(e.data,t):!1}function cN(e,t,n){const o=dc(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function dN(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&&t1(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 uc(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function Kt(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function Yi(e){const t=()=>{const n=e.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};t()||queueMicrotask(()=>void t())}const Me="os-create-folder-dialog";let qo=null;function fc(){qo&&(qo.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),qo.remove(),qo=null,T("os.files.create-folder.closed",{}))}function pc(e){if(fc(),q("os.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${Me}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=Me,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${Me}-title`);const i=document.createElement("h2");i.id=`${Me}-title`,i.className=`${Me}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${Me}__field`,r.id=`${Me}-input`,r.setAttribute("label",e.label??"Folder name"),r.setAttribute("value",n),r.setAttribute("autocomplete","off"),r.setAttribute("spellcheck","false"),s.appendChild(r);const a=document.createElement("p");a.className=`${Me}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const l=document.createElement("div");l.className=`${Me}__actions`;const c=document.createElement("os-button");c.className=`${Me}__btn ${Me}__btn--secondary`,c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className=`${Me}__btn ${Me}__btn--primary`,d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(d),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),qo=o,Yi(r),T("os.files.create-folder.opened",{});const u=h=>{Kt(r,h),Kt(c,h),Kt(d,h),s.classList.toggle(`${Me}--busy`,h)},f=h=>{a.textContent=h,a.hidden=!1},p=()=>{fc(),e.onCancel?.()},g=async()=>{const h=uc(r).trim();if(!h){f("Please enter a name."),Yi(r);return}a.hidden=!0,u(!0);try{await e.onSubmit(h),fc()}catch(b){u(!1),f(b instanceof Error?b.message:"Could not create the folder."),Yi(r)}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void g()),o.addEventListener("click",h=>{h.target===o&&p()});const m=h=>{h.key==="Escape"?(h.preventDefault(),p()):h.key==="Enter"&&!h.isComposing&&(h.preventDefault(),g())};s.addEventListener("keydown",m),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",m)})}function Xi(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function uN(e){return e.id<=0||Xi(e)!==null}function Rw(e){e.length!==0&&ck(e)}function Un(e,t,n){window.wp?.os?.broadcast?.(`os.${e}.changed`,{source:"desktop-files",action:t,ids:n})}function Zi(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 hc(e,t){const n=window.wp?.os;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function Ow(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";se.removePlacement(t);try{await tc(t),Un(s,"trashed",[t]),hc(`"${o}" moved to Trash`,async()=>{try{await ji(t,"placement");const i=await Te(n);se.setFolderPlacements(n,i.placements),Un(s,"untrashed",[t])}catch(i){console.error("[openstation] restore failed:",i)}})}catch(i){console.error("[openstation] deletePlacement failed:",i),Zi(i),Te(n).then(r=>{se.setFolderPlacements(n,r.placements)})}}async function Mw(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";se.removePlacement(n),se.removeFolder(t);try{await sc(t),Un("folder","trashed",[t]),hc(`"${s}" moved to Trash`,async()=>{try{await ji(t,"folder");const i=await Te(o);se.setFolderPlacements(o,i.placements),Un("folder","untrashed",[t])}catch(i){console.error("[openstation] restore folder failed:",i)}})}catch(i){console.error("[openstation] deleteFolder failed:",i),Zi(i),Te(o).then(r=>{se.setFolderPlacements(o,r.placements)})}}async function Pw(e){if(e.length===0)return;if(e.length===1)return fN(e[0]);const t=new Set;for(const l of e)if(t.add(l.parentId),se.removePlacement(l.id),l.file?.type==="folder"){const c=parseInt(l.file.ref,10);c&&se.removeFolder(c)}const n=async()=>{for(const l of t)try{const c=await Te(l);se.setFolderPlacements(l,c.placements)}catch(c){console.error("[openstation] files: re-hydrate failed:",c)}},o=await Promise.allSettled(e.map(async l=>{if(l.file?.type==="folder"){const c=parseInt(l.file.ref,10);if(!c)throw new Error("folder placement without a folder id");return await sc(c),{id:c,kind:"folder",restoreId:c,restoreKind:"folder"}}return await tc(l.id),{id:l.id,kind:l.file?.type==="shortcut"?"shortcut":"placement",restoreId:l.id,restoreKind:"placement"}})),s=[];let i=0;for(const l of o)l.status==="fulfilled"?s.push(l.value):(i+=1,console.error("[openstation] trash (bulk) failed for one item:",l.reason));if(i>0&&n(),s.length===0){Zi(o.find(l=>l.status==="rejected")?.reason);return}for(const l of["placement","shortcut","folder"]){const c=s.filter(d=>d.kind===l).map(d=>d.id);c.length>0&&Un(l,"trashed",c)}const r=s.length===1?"item":"items",a=i>0?`${s.length} ${r} moved to Trash · ${i} could not be moved`:`${s.length} ${r} moved to Trash`;hc(a,async()=>{const l=await Promise.allSettled(s.map(u=>ji(u.restoreId,u.restoreKind)));await n();const c=s.filter((u,f)=>l[f].status==="fulfilled"),d=s.length-c.length;for(const u of l)u.status==="rejected"&&console.error("[openstation] restore (bulk) failed for one item:",u.reason);for(const u of["placement","shortcut","folder"]){const f=c.filter(p=>p.kind===u).map(p=>p.id);f.length>0&&Un(u,"untrashed",f)}d>0&&Zi(new Error(`${d} of ${s.length} items could not be restored.`))})}function fN(e){return e.file?.type==="folder"?Mw(e):Ow(e)}const pN=5,Ww=e=>Pw(e);async function hN(e){if(!(e.length>pN&&!await Pn({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await Ho(It(t.file))}function mN(e){const t=parseInt(e.file.ref,10);t&&pc({title:"Rename folder",label:"New name",submitLabel:"Rename",initialName:e.file.title,onSubmit:async n=>{const o=n.trim();if(!o||o===e.file.title)return;const s=e.file.title,i={...e,file:{...e.file,title:o}};se.upsertPlacement(i);try{const r=se.getState().folders.get(t)?.updatedAtMs??0,a=await pw(t,{name:o},r);se.upsertFolder(a);const l=await Te(e.parentId);se.setFolderPlacements(e.parentId,l.placements)}catch(r){console.error("[openstation] rename folder failed:",r),se.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function gN(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 wN(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>hN(i),onClick:()=>{Ho(It(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>gN(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>mN(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:Ww,onClick:()=>Mw(e)});else{const i=Xi(e),r=e.file.type==="shortcut";if(i||r){const a=i??e.file.ref;t.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,multi:!0,bulkLabel:l=>`Hide ${l} items from desktop`,bulk:l=>{Rw(l.map(c=>Xi(c)??c.file.ref).filter(c=>!!c))},onClick:()=>Rw([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:Ww,onClick:()=>Ow(e)})}const o=q("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const He=16,yN=88,bN=104,vN=20,_N=16,Lt=yN+vN,Fn=bN+_N;function Ko(e,t){const n=Math.max(0,Math.round((e-He)/Lt)),o=Math.max(0,Math.round((t-He)/Fn));return Bn(n,o)}function Bn(e,t){return{col:e,row:t,x:He+e*Lt,y:He+t*Fn}}function Tt(e,t,n,o){const s=Ko(e,t);if(!n.has(_e(s.col,s.row)))return s;const i=o?Math.max(1,Math.floor((o.clientHeight-He)/Fn)):999;for(let r=0;r<999;r++)for(let a=0;a<i;a++)if(!n.has(_e(r,a)))return Bn(r,a);return s}function $w(e,t){const n=t?Math.max(1,Math.floor((t.clientWidth-He)/Lt)):4,o=Math.max(1,n);for(let s=0;s<999;s++)for(let i=0;i<o;i++)if(!e.has(_e(i,s)))return Bn(i,s);return Bn(0,0)}function Uw(e,t){const n=new Set;for(const o of e){const s=Ko(o.x,o.y);n.add(_e(s.col,s.row))}return n}function _e(e,t){return`${e},${t}`}function EN(e){const t=String(e),{placementsByFolder:n}=Ze().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 kN(e,t){const n=EN(e);if(n)return It(n);const o=Ze().state.folders.get(e);return It({type:"folder",ref:String(e),title:o?.name||t||"Folder",icon:WT,previewUrl:"",exists:!0})}function Fw(e){return e instanceof ec}function SN(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 Bw(e){const t=SN(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{Ho(kN(n,e.detail.current.parentName))}}),Q({message:t,action:o,duration:7e3})}const Yo=new Map;function Hw(e,t){return Yo.set(e,t),()=>{Yo.get(e)===t&&Yo.delete(e)}}function AN(e,t){const n=Yo.get(e.type);return n?n.accept(e.data,t):!1}function CN(e,t,n){const o=Yo.get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function Hn(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function Ji(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}const zw="application/x-wp-media-attachment",Gw="data-files-drop-active";function jw(){const e=window.wp?.os?.dragBridge;if(!e)return null;try{return e.getPayload()}catch{return null}}function Vw(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 IN(e){if(!e)return null;let t="";try{t=e.getData(zw)}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 qw(e){const t=e.dataTransfer?.types,n=t?Array.from(t):[];return n.includes("Files")?!1:n.includes(zw)?!0:Vw(jw())!==null}function Kw(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 Yw(e,t){if(!(e instanceof Element))return null;const n=e.closest(`.${ie}`);return!(n instanceof HTMLElement)||!t.contains(n)?null:n.dataset.fileType==="folder"?n:null}function xN(e){const{host:t,container:n,folderId:o}=e;let s=null;const i=()=>{t.removeAttribute(Gw),s&&(s.classList.remove(`${ie}--drop-target`),s=null)},r=c=>{if(!qw(c))return;if(!Kw(c.target,t,n)){i();return}c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),t.setAttribute(Gw,"");const d=Yw(c.target,n);d!==s&&(s?.classList.remove(`${ie}--drop-target`),d?.classList.add(`${ie}--drop-target`),s=d)},a=c=>{const d=c.relatedTarget;d instanceof Node&&t.contains(d)||i()},l=c=>{if(!qw(c))return;if(!Kw(c.target,t,n)){i();return}i(),c.preventDefault(),c.stopPropagation();const d=Vw(jw())??IN(c.dataTransfer);if(!d)return;const u=Yw(c.target,n);let f=o;if(u){const p=parseInt(u.getAttribute("ref")??"",10);!Number.isNaN(p)&&p>0&&(f=p)}e.fileEntities([d],f)};return t.addEventListener("dragover",r),t.addEventListener("dragleave",a),t.addEventListener("drop",l),()=>{i(),t.removeEventListener("dragover",r),t.removeEventListener("dragleave",a),t.removeEventListener("drop",l)}}function LN(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 Xo(){return window.wp?.os?.dragManager??null}const TN="os-files-layer";function NN(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function Xw(e,t=0){const n=document.createElement("div");n.className=TN,n.setAttribute("role","list"),n.dataset.folderId=String(t),e.appendChild(n);let o="";const s=x=>{const F=se.getState().placementsByFolder.get(t)??[],N=new Map;for(const U of F)U&&N.set(String(U.id),U);return x.map(U=>N.get(U)).filter(U=>!!U)},i=new Set,r=new Set,a=XL(n,{itemSelector:`.${ie}`,background:e,surface:"files",scope:String(t),keyOf:x=>x.dataset.placementId??null,onChange:x=>{const F=s(x),N=F.length===1?F[0]:null;for(const U of i)try{U(N)}catch(B){console.error("[openstation] files: selection listener threw:",B)}for(const U of r)try{U(F)}catch(B){console.error("[openstation] files: selection listener threw:",B)}}}),l=()=>s(a.keys()),c=x=>{const F=new Map,N=new Set;let U=0;for(const H of x){if(!Pe(H))continue;const O=Bn(0,U);F.set(H.id,{x:O.x,y:O.y}),N.add(_e(O.col,O.row)),U+=1}const B=new Map;for(const H of x){if(F.has(H.id))continue;const O=Ko(H.x,H.y),V=_e(O.col,O.row);if(!N.has(V)){N.add(V);continue}const D=Tt(H.x,H.y,N,e);N.add(_e(D.col,D.row)),B.set(H.id,{x:D.x,y:D.y})}return{pinnedSlots:F,displaced:B}},d=(x,F,N,U)=>{const B=N.get(F.id),H=U.get(F.id);B?mt(x,B.x,B.y):H?mt(x,H.x,H.y):mt(x,F.x,F.y)},u=(x,F,N)=>{const U=rN(x,t),B=F.get(x.id);if(B){if(mt(U,B.x,B.y),U.classList.add(`${ie}--pinned`),ty(U,x,a,l),Zw(x)){const O=Xo();O&&h.set(x.id,ey(O,U,x))}return U}const H=N.get(x.id);if(H&&mt(U,H.x,H.y),WN(U,x,t,a,l),ty(U,x,a,l),x.file.type==="folder"){const O=parseInt(x.file.ref,10);if(O>0){const V=Xo();if(V){const D=PN(V,U,O);m.set(x.id,D)}}}else if(Zw(x)){const O=Xo();O&&h.set(x.id,ey(O,U,x))}return U},f=x=>{const F=new Map;for(const H of n.querySelectorAll("[data-placement-id]")){const O=H.dataset.placementId??"",V=parseInt(O,10);if(O===""||Number.isNaN(V)&&O!=="-0")return!1;F.set(V,H)}const N=new Set;for(const H of x)N.add(H.id);for(const H of x){const O=F.get(H.id);if(!O)continue;if(O.dataset.fileType!==H.file.type||O.dataset.fileRef!==H.file.ref||O.classList.contains(`${ie}--pinned`)!==Pe(H))return!1}for(const[H,O]of F){if(N.has(H))continue;const V=m.get(H);if(V){try{V()}catch{}m.delete(H)}const D=h.get(H);if(D){try{D()}catch{}h.delete(H)}O.remove()}const{pinnedSlots:U,displaced:B}=c(x);for(const H of x){const O=F.get(H.id);if(O){d(O,H,U,B),Qw(O,H);continue}n.appendChild(u(H,U,B))}return a.refresh(),T("os.files.grid-rendered",{folderId:t,count:x.length}),!0},p=x=>{const N=(x.placementsByFolder.get(t)??[]).slice().sort((O,V)=>{const D=Pe(O)?0:1,j=Pe(V)?0:1;return D-j}),U=DN(N);if(U===o||(o=U,MN(N,n,e))||f(N))return;n.replaceChildren();for(const[,O]of m)try{O()}catch{}m.clear();for(const[,O]of h)try{O()}catch{}h.clear();const{pinnedSlots:B,displaced:H}=c(N);for(const O of N)n.appendChild(u(O,B,H));a.refresh(),T("os.files.grid-rendered",{folderId:t,count:N.length})},g=[],m=new Map,h=new Map;let b=null,y=null;const I=x=>{if(b||x.payload.type!=="desktop-file")return;const F=document.createElement("div");F.className="os-files-drop-preview",F.setAttribute("aria-hidden","true"),n.appendChild(F),b=F;const N=x.payload.ghost,U=N?.offsetX??0,B=N?.offsetY??0,O=x.payload.data?.placement?.id,V=(G,ae)=>{const fe=n.getBoundingClientRect(),pe=Math.max(0,G-fe.left-U),re=Math.max(0,ae-fe.top-B),Ce=se.getState().placementsByFolder.get(t)??[],Ls=er(Ce,O),$e=Tt(pe,re,Ls,e);F.style.transform=`translate3d(${$e.x}px, ${$e.y}px, 0)`},D=x.payload.source.getBoundingClientRect();V(D.left+U,D.top+B);const j=G=>{V(G.clientX,G.clientY)};document.addEventListener("pointermove",j),y=j},R=()=>{y&&(document.removeEventListener("pointermove",y),y=null),b&&(b.remove(),b=null)},k={id:`os-files-canvas-${t}`,element:e,accept:x=>{if(x.type!=="desktop-file"&&x.type!=="shortcut")return AN(x,{folderId:t,host:e});if(t>0&&x.type==="desktop-file"){const F=x.data;for(const N of Hn(F)){if(N.file?.type!=="folder")continue;const U=parseInt(N.file.ref,10);if(!Number.isNaN(U)&&Jw(U,t))return!1}}return!0},onEnter:x=>{e.setAttribute("data-files-drop-active",""),(x.payload.type==="desktop-file"||x.payload.type==="shortcut")&&I(x)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),R()},onDrop:(x,F)=>{if(e.removeAttribute("data-files-drop-active"),R(),x.payload.type!=="desktop-file"&&x.payload.type!=="shortcut"){CN(x,F,{folderId:t,host:e});return}const N=n.getBoundingClientRect(),U=x.payload.ghost,B=U?.offsetX??0,H=U?.offsetY??0,O=Math.max(0,F.clientX-N.left-B),V=Math.max(0,F.clientY-N.top-H),D=se.getState().placementsByFolder.get(t)??[];if(x.payload.type==="desktop-file"){const j=x.payload.data,G=Hn(j),ae=new Set(G.map(re=>re.id)),fe=er(D,ae),pe=Tt(O,V,fe,e);fe.add(_e(pe.col,pe.row));for(const re of G){let Ce=pe;if(re.id!==j.placement.id){const $e=re.x-j.placement.x,Db=re.y-j.placement.y;Ce=Tt(Math.max(0,pe.x+$e),Math.max(0,pe.y+Db),fe,e),fe.add(_e(Ce.col,Ce.row))}const Ls={...re,x:Ce.x,y:Ce.y,parentId:t};if(se.upsertPlacement(Ls),T("os.files.tile-manually-placed",{folderId:t,placementId:re.id}),Qi(re)){const $e=Xi(re);$e&&ON($e,Ce.x,Ce.y);continue}Wn(re.id,{x:Ce.x,y:Ce.y,parentId:t},re.updatedAtMs).then($e=>{se.upsertPlacement($e,"remote")}).catch($e=>{Fw($e)?Bw($e):console.error("[openstation] files: drag persist failed",$e),se.upsertPlacement(re)})}return}if(x.payload.type==="shortcut"){const j=x.payload.data;mc(Ji(j),t,e)}}},M=Xo();if(M&&g.push(M.registerDropTarget(k)),g.push(xN({host:e,container:n,folderId:t,fileEntities:(x,F)=>{mc(x,F,F===t?e:null)}})),!se.getState().hydratedFolders.has(t)){const x=NN(t);x&&se.setFolderPlacements(t,x)}p(se.getState()),queueMicrotask(()=>C());const P=se.subscribe(x=>{p(x),C()});let W=()=>{};const _=new Promise(x=>{W=x});se.getState().hydratedFolders.has(t)?queueMicrotask(W):Te(t).then(x=>{se.setFolderPlacements(t,x.placements)}).catch(x=>{console.error("[openstation] files: failed to hydrate folder",t,x)}).finally(()=>{W()});const w=()=>{const x=e.clientWidth>0?e.clientWidth:4*Lt;return Math.max(1,Math.floor((x-He)/Lt))},L=(x,F)=>{const N=x.slice();switch(F){case"name-asc":N.sort((U,B)=>U.file.title.localeCompare(B.file.title));break;case"name-desc":N.sort((U,B)=>B.file.title.localeCompare(U.file.title));break;case"date-asc":N.sort((U,B)=>U.updatedAtMs-B.updatedAtMs);break;case"date-desc":N.sort((U,B)=>B.updatedAtMs-U.updatedAtMs);break}return N},A=x=>{const F=se.getState().placementsByFolder.get(t);if(!F||F.length===0)return;const N=F.filter(j=>Pe(j)),U=F.filter(j=>!Pe(j)),B=L(U,x),H=w(),O=new Set;for(let j=0;j<N.length;j+=1)O.add(_e(0,j));let V=0;const D=()=>{for(;;){const j=Math.floor(V/H),G=V%H;if(V+=1,!O.has(_e(G,j)))return{col:G,row:j}}};B.forEach((j,G)=>{const ae=D(),fe=He+ae.col*Lt,pe=He+ae.row*Fn,re={...j,x:fe,y:pe,sortOrder:G};se.upsertPlacement(re),!Qi(j)&&Wn(j.id,{x:fe,y:pe,sortOrder:G}).catch(Ce=>{console.error("[openstation] files: sort persist failed",Ce)})})},C=()=>{const x=se.getState().placementsByFolder.get(t);if(!x||x.length===0)return;const F=e.clientWidth>0?e.clientWidth:1/0,N=e.clientHeight>0?e.clientHeight:1/0;if(!x.some(G=>G.x+Lt>F||G.y+Fn>N))return;const B=w(),H=x.filter(G=>Pe(G)),O=x.filter(G=>!Pe(G)),V=new Set;for(let G=0;G<H.length;G+=1)V.add(_e(0,G));let D=0;const j=()=>{for(;;){const G=Math.floor(D/B),ae=D%B;if(D+=1,!V.has(_e(ae,G)))return{col:ae,row:G}}};for(const G of O){const ae=j(),fe=He+ae.col*Lt,pe=He+ae.row*Fn,re=n.querySelector(`[data-placement-id="${G.id}"]`);re&&mt(re,fe,pe)}};let $=e.clientWidth,X=e.clientHeight,Z=null;return typeof ResizeObserver<"u"&&(Z=new ResizeObserver(()=>{const x=e.clientWidth,F=e.clientHeight;x===$&&F===X||($=x,X=F,C())}),Z.observe(e)),{host:e,folderId:t,onSelectionChange(x){return i.add(x),()=>{i.delete(x)}},onSelectionChanged(x){return r.add(x),()=>{r.delete(x)}},getSelection:l,selectAll:()=>a.model.selectAll(),clearSelection:()=>a.model.clear(),sort:A,reflow:C,hydrated:_,dispose(){P(),Z?.disconnect(),Z=null;for(const x of g)try{x()}catch{}g.length=0;for(const x of m.values())try{x()}catch{}m.clear();for(const x of h.values())try{x()}catch{}h.clear(),a.destroy(),i.clear(),r.clear(),n.remove()}}}function DN(e){if(e.length===0)return"0";const t=[];for(const n of e)t.push(`${n.id}:${n.parentId}:${n.x}:${n.y}:${n.sortOrder}:${n.updatedAtMs}:${n.file.type}:${n.file.ref}:${n.file.title}:${n.file.icon}:${Pe(n)?1:0}`);return t.join("|")}function Pe(e){return!!e.file.pinned}function Qi(e){return uN(e)}const RN="desktop-mode-recycle-bin";function Zw(e){return!(e.file?.type==="folder"||e.file?.ref===RN)}function er(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,a)=>{const l=Pe(r)?0:1,c=Pe(a)?0:1;return l-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(Pe(r))s.add(_e(0,i)),i+=1;else{const a=Ko(r.x,r.y);s.add(_e(a.col,a.row))}return s}function mc(e,t,n){const o=se.getState().placementsByFolder.get(t)??[],s=er(o);for(const i of e){const r=$w(s,n);s.add(_e(r.col,r.row)),Go({parentId:t,type:i.kind,ref:i.ref,x:r.x,y:r.y}).then(a=>{se.upsertPlacement(a),T("os.files.shortcut-dropped",{folderId:t,placement:a})}).catch(a=>{console.error("[openstation] shortcut drop failed:",a)})}}function Jw(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=se.getState();for(const a of o.placementsByFolder.values())for(const l of a){if(l.file?.type!=="folder")continue;const c=parseInt(l.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,l.parentId)}const s=new Set;let i=t,r=256;for(;i>0&&r-- >0;){if(i===e||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function ON(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 MN(e,t,n){const o=Array.from(t.querySelectorAll("[data-placement-id]"));if(o.length!==e.length)return!1;const s=new Map;for(const c of o){const d=c.dataset.placementId??"",u=parseInt(d,10);if(d===""||Number.isNaN(u)&&d!=="-0")return!1;s.set(u,c)}for(const c of e){const d=s.get(c.id);if(!d||d.dataset.fileType!==c.file.type||d.dataset.fileRef!==c.file.ref||d.classList.contains(`${ie}--pinned`)!==Pe(c))return!1}const i=new Map,r=new Set;let a=0;for(const c of e){if(!Pe(c))continue;const d=Bn(0,a);i.set(c.id,{x:d.x,y:d.y}),r.add(_e(d.col,d.row)),a+=1}const l=new Map;for(const c of e){if(i.has(c.id))continue;const d=Ko(c.x,c.y),u=_e(d.col,d.row);if(!r.has(u)){r.add(u);continue}const f=Tt(c.x,c.y,r,n);r.add(_e(f.col,f.row)),l.set(c.id,{x:f.x,y:f.y})}for(const c of e){const d=s.get(c.id);if(!d)continue;const u=i.get(c.id),f=l.get(c.id);u?mt(d,u.x,u.y):f?mt(d,f.x,f.y):mt(d,c.x,c.y),Qw(d,c)}return!0}function Qw(e,t){const n=Dw(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function ey(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?aN(s,o):void 0},accept:i=>(s=i.type,lN(i,o)),onEnter:()=>{t.classList.add(`${ie}--drop-target`)},onLeave:()=>{t.classList.remove(`${ie}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${ie}--drop-target`),cN(i,r,o)}})}function PN(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 Hn(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||Qi(a))return!1;if(a.file.type==="folder"){const l=parseInt(a.file.ref,10);if(!Number.isNaN(l)&&Jw(l,n))return!1}}}return!0},onEnter:()=>{t.classList.add(`${ie}--drop-target`)},onLeave:()=>{t.classList.remove(`${ie}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${ie}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a=se.getState().placementsByFolder.get(n)??[],l=er(a);for(const c of Hn(r)){const d=$w(l);l.add(_e(d.col,d.row)),se.upsertPlacement({...c,x:d.x,y:d.y,parentId:n}),Wn(c.id,{x:d.x,y:d.y,parentId:n},c.updatedAtMs).then(u=>{se.upsertPlacement(u,"remote")}).catch(u=>{Fw(u)?Bw(u):console.error("[openstation] files: move-into-folder persist failed",u),se.upsertPlacement(c)})}return}if(i.payload.type==="shortcut"){const r=i.payload.data;mc(Ji(r),n)}}};return e.registerDropTarget(s)}function WN(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=Xo();if(!r)return;const l=se.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||l.x,parseFloat(e.style.top)||l.y;const c=o.model.has(String(l.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===l.id)?d:[l];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(l.id)])};document.addEventListener("os.drag.start",f);const p=()=>{document.removeEventListener("os.drag.start",f),document.removeEventListener("pointerup",p)};document.addEventListener("pointerup",p)}if(u.length>1){const f=[],p=()=>{for(const m of f)m.classList.remove(`${ie}--dragging`);f.length=0,document.removeEventListener("os.drag.start",g),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},g=()=>{for(const m of u){const h=e.parentElement?.querySelector(`[data-placement-id="${m.id}"]`);h&&h!==e&&(h.classList.add(`${ie}--dragging`),f.push(h))}};document.addEventListener("os.drag.start",g),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:e,data:{placement:l,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:LN(l)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?sN(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 ty(e,t,n,o){e.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=se.currentPlacement(t);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),a=r.length>0?r:[i],l=Tg(a,wN);dN({x:s.clientX,y:s.clientY},l,{placementIds:a.map(c=>c.id)})})}function Yt(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 zn="os-folder-status-bar";function $N(e,t,n={}){const o=document.createElement("div");o.className=zn,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const a=xt().placementsByFolder.get(t)??[],l=a.filter(p=>p.file.type==="folder").length,c=a.length-l;let d=0;for(const p of a)if(p.file.type==="upload"){const g=Number(p.file.sizeBytes??0);Number.isFinite(g)&&g>0&&(d+=g)}const u={folderId:t,selectedCount:n.selection?.count()??0,totals:{files:c,folders:l,total:a.length,bytes:d}},f=UN(u);FN(o,f)};s();const i=ac(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function UN(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:oy(n,"file","files")+(t>0?`, ${oy(t,"folder","folders")}`:"")+(o>0?` (${Yt(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=q("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function FN(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,l=typeof r.sort=="number"?r.sort:100;return a!==l?a-l:i.label.localeCompare(r.label)},o=t.filter(i=>(i.align??"start")==="start").sort(n),s=t.filter(i=>i.align==="end").sort(n);e.replaceChildren(),e.appendChild(ny("start",o)),e.appendChild(ny("end",s))}function ny(e,t){const n=document.createElement("div");n.className=`${zn}__cluster ${zn}__cluster--${e}`;for(const o of t)n.appendChild(BN(o));return n}function BN(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${zn}__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=`${zn}__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=`${zn}__label`,o.textContent=e.label,n.appendChild(o),n}function oy(e,t,n){return`${e} ${e===1?t:n}`}const tr="os-icon-canvas-menu";let Zo=null,nr=null,gc=null,Jo=null,Qo=null;function HN(e,t){t.openOnBackgroundClick;const n=i=>{zN(i.target)||sy(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(gc===e&&Zo){Xt();return}const a=GN(t),l=q("os.icon-canvas.menu",a,t.scope),c=Array.isArray(l)?l:a,d=++o;Ps(()=>d===o,()=>jN(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),Xt()}}}function zN(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function sy(e){return e instanceof Element?e.closest(`.${tr}`)!==null:!1}function GN(e){const n=[{id:"sort-by",label:E("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:E("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:E("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:E("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:E("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function iy(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 jN(e,t,n){if(Xt(),e.length===0)return;gc=n;const o=iy(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(tr),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=ry(s,r);or(r)&&a.addEventListener("mouseenter",()=>{ay(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,l=i.get(a.id);if(l){if(or(l)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${l.id}"]`);c&&ay(l,c);return}Xt(),l.onClick?.()}}),document.body.appendChild(s),Zo=s,Ll(s),queueMicrotask(()=>{Jo=r=>{sy(r.target)||Xt()},Qo=r=>{r.key==="Escape"&&Xt()},document.addEventListener("mousedown",Jo),document.addEventListener("keydown",Qo)})}function ry(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",VN(t.icon)),or(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function ay(e,t){if(ly(),!or(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(tr,`${tr}--flyout`);const o=new Map;for(const s of iy(e.children??[]))o.set(s.id,s),ry(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),Xt(),r.onClick?.())}),document.body.appendChild(n),nr=n,Rg(n,t)}function or(e){return Array.isArray(e.children)&&e.children.length>0}function ly(){nr&&(nr.remove(),nr=null)}function Xt(){ly(),Zo&&(Zo.remove(),Zo=null),gc=null,Jo&&(document.removeEventListener("mousedown",Jo),Jo=null),Qo&&(document.removeEventListener("keydown",Qo),Qo=null)}function VN(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const Zt="os-breadcrumbs";function qN(e,t,n={}){if(e.replaceChildren(),e.classList.add(Zt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${Zt}__back`,s.setAttribute("aria-label",E("Back","desktop-mode")),s.title=E("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=`${Zt}__crumbs`,o.setAttribute("aria-label",E("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const l=document.createElement("span");l.className=`${Zt}__sep`,l.setAttribute("aria-hidden","true"),l.textContent="›",o.appendChild(l)}if(!s.onClick){const l=document.createElement("span");l.className=`${Zt}__crumb ${Zt}__crumb--current`,l.setAttribute("aria-current","page"),l.textContent=s.label,o.appendChild(l);return}const r=document.createElement("button");r.type="button",r.className=`${Zt}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}function sr(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 es(e,t={}){const n=await Fe(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":KN(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function KN(){return window.wp?.os?.config?.restNonce??""}function YN(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function ts(e){return nt(YN(),e)}function XN(e,t){const n=q("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(ZN(e));return}t.replaceChildren(lD()),JN(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(cD(o))})}function ZN(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 JN(e){const t=e.file;switch(t.type){case"post":return QN(t.ref,t);case"folder":return iD(t);case"shortcut":return rD(t);case"attachment":return oD(t.ref,t);case"upload":return sD(t);case"user":return eD(t.ref,t);case"term":return tD(t);case"comment":return nD(t.ref,t);case"bookmark":return aD(t);default:return Je(t)}}async function QN(e,t){const n=parseInt(e,10);if(!n)return Je(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await es(ts(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return Je(t);const s=rt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=ir(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(cy(o.date)),o.status&&o.status!=="publish"&&a.push(o.status),r.textContent=a.join(" · "),s.appendChild(r),o.content?.rendered){const u=document.createElement("div");u.className="os-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const c=window.wp?.os?.myWordpress;if(c){const u=document.createElement("os-button");u.setAttribute("variant","secondary"),u.textContent=E("Explore details","desktop-mode"),u.title=E("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";c.openDetail({entityId:f==="page"?"pages":"posts",postId:n,postTitle:ir(o.title.rendered)||`#${n}`})}),l.appendChild(u)}const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=E("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,m=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${m}-edit-${n}`,url:f,title:ir(o.title.rendered),icon:t.icon})}),l.appendChild(d),s.appendChild(l),s}async function eD(e,t){const n=parseInt(e,10);if(!n)return Je(t);let o=null;try{o=await es(ts(`desktop-mode/v1/user-stats/${n}`))}catch{return Je(t)}const s=rt("os-my-wordpress__user"),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.profile.avatarUrl){const c=document.createElement("img");c.className="os-my-wordpress__user-avatar",c.src=o.profile.avatarUrl,c.alt="",i.appendChild(c)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");if(a.className="os-my-wordpress__article-title",a.textContent=o.profile.name||t.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const c=document.createElement("div");c.className="os-my-wordpress__user-roles";for(const d of o.profile.roleLabels){const u=document.createElement("span");u.className="os-my-wordpress__user-role",u.textContent=d,c.appendChild(u)}r.appendChild(c)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const c=document.createElement("div");c.className="os-my-wordpress__user-bio",c.textContent=o.profile.description,s.appendChild(c)}const l=document.createElement("div");return l.className="os-my-wordpress__user-stats",l.appendChild(Gn(o.counts.posts.total.toLocaleString(),E("Posts","desktop-mode"))),l.appendChild(Gn(o.counts.pages.total.toLocaleString(),E("Pages","desktop-mode"))),l.appendChild(Gn(o.counts.commentsReceived.toLocaleString(),E("Comments received","desktop-mode"))),s.appendChild(l),s}async function tD(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return Je(e);let o=null;try{o=await es(ts(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return Je(e)}const s=rt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=o.profile.name||e.title||`#${t}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const l=document.createElement("div");l.className="os-my-wordpress__article-content",l.innerHTML=o.profile.description,s.appendChild(l)}const a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(Gn(o.counts.posts.total.toLocaleString(),E("Posts","desktop-mode"))),a.appendChild(Gn(o.counts.commentsReceived.toLocaleString(),E("Comments","desktop-mode"))),a.appendChild(Gn(o.counts.distinctAuthors.toLocaleString(),E("Authors","desktop-mode"))),s.appendChild(a),s}async function nD(e,t){const n=parseInt(e,10);if(!n)return Je(t);let o=null;try{o=await es(ts(`desktop-mode/v1/comment-stats/${n}`))}catch{return Je(t)}const s=rt(),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.author.avatarUrl){const d=document.createElement("img");d.className="os-my-wordpress__user-avatar",d.src=o.author.avatarUrl,d.alt="",i.appendChild(d)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");a.className="os-my-wordpress__article-title",a.textContent=o.author.name,r.appendChild(a);const l=document.createElement("p");l.className="os-my-wordpress__article-meta",l.textContent=`${cy(o.comment.date)} · ${o.comment.status}`,r.appendChild(l),i.appendChild(r),s.appendChild(i);const c=document.createElement("div");if(c.className="os-my-wordpress__article-content",c.innerHTML=o.comment.rendered,s.appendChild(c),o.post){const d=document.createElement("div");d.className="os-my-wordpress__comment-post";const u=document.createElement("a");u.className="os-my-wordpress__comment-post-title",u.href=o.post.link,u.target="_blank",u.rel="noopener noreferrer",u.textContent=o.post.title,d.appendChild(u),s.appendChild(d)}return s}async function oD(e,t){const n=parseInt(e,10);if(!n)return Je(t);let o=null;try{o=await es(ts(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return Je(t)}const s=rt(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=ir(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="os-my-wordpress__article-hero";const l=o.media_details?.sizes;a.src=l?.large?.source_url??l?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),l=document.createElement("a");l.href=o.source_url,l.textContent=o.source_url,l.target="_blank",l.rel="noopener noreferrer",a.appendChild(l),s.appendChild(a)}return s}function sD(e){const t=rt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("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?Yt(s):""].filter(Boolean).join(" · "),t.appendChild(r);const a=parseInt(e.ref,10),l=()=>{const c=document.createElement("p");return c.className="os-my-wordpress__article-meta os-files__no-preview",c.textContent=E("No preview available for this file type.","desktop-mode"),c};if(a>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=qt(a),c.alt=e.title||"",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="video"){const c=document.createElement("video");c.className="os-my-wordpress__article-hero",c.controls=!0,c.preload="metadata",c.src=qt(a),c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="audio"){const c=document.createElement("audio");c.controls=!0,c.preload="metadata",c.src=qt(a),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else t.appendChild(l());if(a>0){const c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=E("Download","desktop-mode"),d.addEventListener("click",()=>{sr(qt(a))}),c.appendChild(d),t.appendChild(c)}return t}function iD(e){const t=rt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=E("Double-click to open.","desktop-mode"),t.appendChild(o),t}function rD(e){const t=rt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=E("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function aD(e){const t=rt(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||E("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 Je(e){const t=rt(),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(E("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=E("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function rt(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function Gn(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 lD(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function cD(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:E("Unknown error.","desktop-mode"),t}function ir(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function cy(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function dy(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=E("Select an item to preview it here.","desktop-mode"),e}function dD(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=de(E("%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 rr="desktop-mode-embed-",uD=800,fD=600,wc=360,yc=240,ar=16,bc=new Map;function pD(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?`${rr}${s.id}`:`${rr}anon-${wD(n)}`,a=i?.name?.trim()??"",l=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:l,icon:e.icon(),minWidth:wc,minHeight:yc},d=i?.window,u=document.getElementById("os-area"),f=u?.clientWidth??window.innerWidth,p=u?.clientHeight??window.innerHeight;if(d&&Number.isFinite(d.width)&&Number.isFinite(d.height)){const{x:g,y:m,width:h,height:b}=gD(d,f,p);c.x=g,c.y=m,c.width=h,c.height=b}else c.width=Math.min(uD,Math.max(wc,f-ar*2)),c.height=Math.min(fD,Math.max(yc,p-ar*2));s&&d&&bc.set(r,{...d}),o.open(c)}let uy=!1;function hD(){if(uy)return;uy=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(rr))return;const s=o.slice(rr.length),i=parseInt(s,10);if(!i)return;const l=window.wp?.os?.windowManager?.getById?.(o)?.element;if(!l)return;const c={x:l.offsetLeft,y:l.offsetTop,width:l.offsetWidth,height:l.offsetHeight},d=bc.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(bc.set(o,c),mD(i,c))};Y(v.WINDOW_DRAG_END,"os-embed-persist",e),Y(v.WINDOW_RESIZE_END,"os-embed-persist",e)}async function mD(e,t){try{const i={...(await Te(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await Wn(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function gD(e,t,n){const o=Math.max(wc,Math.min(e.width,t-ar)),s=Math.max(yc,Math.min(e.height,n-ar)),i=Math.max(0,Math.min(e.x,Math.max(0,t-o))),r=Math.max(0,Math.min(e.y,Math.max(0,n-s)));return{x:i,y:r,width:o,height:s}}function wD(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 ns(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function fy(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 yD(){Be({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ns()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Be({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ns()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Be({id:"agent-chat",label:E("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;uw({id:Number.parseInt(t.ref,10),name:t.title,description:t.agentDescription??"",avatarUrl:t.previewUrl??""},"agents-open")}}}),Be({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ns()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),Be({id:"wp-term-editor",label:"Term editor",types:["term"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>{const[t,n]=e.ref().split(":");return`${ns()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Be({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${ns()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),Be({id:"desktop-mode-upload-download",label:"Download",types:["upload"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);t&&sr(qt(t))}}}),Be({id:"desktop-mode-folder-window",label:"Open folder",types:["folder"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);if(!t)return;const n=window.wp?.os?.windowManager;if(!n)return;const o=`os-folder-${t}`,s=se.getState().folders.get(t),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),l=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:l,icon:e.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window");const d=[{folderId:t,title:e.title()}];let u=null;const f=document.createElement("header");c.appendChild(f);const p=document.createElement("div");p.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",c.appendChild(p);const g=()=>{const h=d.map((b,y)=>y===d.length-1?{label:b.title}:{label:b.title,onClick:()=>{d.length=y+1,m()}});qN(f,h,{onBack:()=>{d.length<=1||(d.pop(),m())},backDisabled:d.length<=1})},m=()=>{u?.(),u=null,p.replaceChildren();const h=document.createElement("div");h.className="os-folder-window__split",p.appendChild(h);const b=document.createElement("div");b.className="os-folder-window__layer",h.appendChild(b);const y=document.createElement("div");y.className="os-folder-window__preview",y.appendChild(dy()),h.appendChild(y);const I=d[d.length-1],R=Xw(b,I.folderId),k=R.onSelectionChanged(_=>{if(_.length===0){y.replaceChildren(dy());return}if(_.length>1){y.replaceChildren(dD(_));return}XN(_[0],y)}),M=_=>{if(!(_.target instanceof Element))return;const w=_.target.closest(".os-file-tile");if(!w||w.dataset.fileType!=="folder")return;const L=parseInt(w.dataset.fileRef??"",10);if(!L)return;_.preventDefault(),_.stopPropagation();const A=w.querySelector(".os-file-tile__label")?.textContent??`#${L}`;d.push({folderId:L,title:A}),m()};b.addEventListener("dblclick",M,!0);const P=HN(b,{scope:`os-folder:${I.folderId}`,onSort:_=>R.sort(_),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{pc({onSubmit:async _=>{const w=await oc({name:_}),L=se.getState().placementsByFolder.get(I.folderId)??[],A=Uw(L),C=Tt(He,He,A,b),$=await Go({type:"folder",ref:String(w.id),parentId:I.folderId,x:C.x,y:C.y});se.upsertFolder(w),se.upsertPlacement($)}})}}]}),W=$N(p,I.folderId,{selection:{count:()=>R.getSelection().length,subscribe:_=>R.onSelectionChanged(()=>_())}});u=()=>{k(),P.dispose(),W.dispose(),b.removeEventListener("dblclick",M,!0),R.dispose()},g()};m()},width:720,height:480,minWidth:360,minHeight:240})}}}),Be({id:"desktop-mode-shortcut-opener",label:"Open shortcut",types:["shortcut"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=e.shape,n=window.wp?.os;if(n){if(t.shortcutSystemTile&&n.getSystemTile){n.getSystemTile(t.shortcutSystemTile)?.onOpen();return}if(t.shortcutWindow&&n.openWindow){n.openWindow(t.shortcutWindow);return}if(t.shortcutUrl&&n.windowManager)try{const o=new URL(t.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}if(Ge(o.toString()))return;const s=n.config?.adminUrl,i=s?ce(o.toString(),s):`desktop-icon-${e.ref()}`,r=_m(o.toString());n.windowManager.open({id:i,baseId:i,url:o.toString(),parentUrl:r?.url??o.toString(),title:e.title(),icon:e.icon(),submenu:r?.submenu,selfLabel:r?.selfLabel,multi:!!r?.multi})}catch{}}}}}),Be({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=fy(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=fy(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Be({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{pD(e,t)}}})}const bD="os-file-associations";function vD(){qp({id:bD,label:"File Associations",order:50,render(e){_D(e)}})}function _D(e){e.replaceChildren();const t=tw();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=Yl(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(ED(i.type,i.label,o));e.appendChild(s)}function ED(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=Xl(e);if(i.length===0){const c=document.createElement("span");return c.className="os-file-associations__none",c.textContent="No app available",o.appendChild(c),o}const r=Zl(e),a=n[e]??r?.id??"",l=document.createElement("os-select");l.setAttribute("value",a),l.setAttribute("aria-label",`Default app for ${t}`),l.className="os-file-associations__select",s.htmlFor=`assoc-${e}`,l.id=`assoc-${e}`;for(const c of i){const d=document.createElement("os-option");d.setAttribute("value",c.id),d.textContent=c.isDefault?`${c.label} (default)`:c.label,l.appendChild(d)}return l.addEventListener("os-pick",c=>{const d=c.detail?.value;if(!d)return;const u={...Yl(),[e]:d};ow(u),hw(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(l),o}function kD(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,qi(t),!0)}let vc=null;function Qe(){return vc||(vc=le("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),vc}function SD(e,t){const n=Qe();n.state.byFolder.set(e,t),n.notify()}function AD(e){if(!e||typeof e.folderId!="number")return;const t=Qe(),o=(t.state.byFolder.get(e.folderId)??[]).filter(s=>s.id!==e.id);o.push(e),t.state.byFolder.set(e.folderId,o),t.notify()}function CD(e,t){const n=Qe(),o=n.state.byFolder.get(e)??[];n.state.byFolder.set(e,o.filter(s=>s.id!==t)),n.notify()}function ID(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 py(e){const t=Qe(),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(ID(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 lr(e,t={}){const n=Qe();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 xD=ue`:host{display:block;position:relative;font-size:13px}.input{width:100%;padding:8px 10px;background:var( --os-ui-input-bg,var( --os-ui-hover,rgba( 255,255,255,0.06 ) ) );color:inherit;border:1px solid var( --os-ui-border,rgba( 255,255,255,0.12 ) );border-radius:6px;font:inherit;box-sizing:border-box}.input:focus{outline:none;border-color:var( --os-ui-accent,#2271b1 );box-shadow:var( --os-ui-focus-ring-field,0 0 0 1px #2271b1,0 0 0 4px rgba( 34,113,177,0.18 ) )}.dropdown{background:var( --os-bg,#1d2327 );color:var( --os-fg,#fff );border:1px solid var( --os-ui-border,rgba( 255,255,255,0.18 ) );border-radius:6px;overflow:auto;z-index:11000;box-shadow:0 12px 32px rgba( 0,0,0,0.5 )}.empty.error{color:var( --os-ui-danger-hover,#ff8080 )}.item{display:flex;align-items:center;gap:10px;padding:8px 10px;cursor:pointer;border:0;background:transparent;color:inherit;width:100%;text-align:start;font:inherit}.item:hover,.item:focus{background:var( --os-ui-hover,rgba( 255,255,255,0.06 ) );outline:none}.avatar{width:24px;height:24px;border-radius:50%;flex:0 0 auto;background:var( --os-ui-hover,rgba( 255,255,255,0.1 ) )}.name{font-weight:500}.slug{opacity:0.6;font-size:12px}.empty{padding:12px;color:var( --os-ui-fg-muted,rgba( 255,255,255,0.5 ) );font-size:12px}`,ys=class ys extends Se{constructor(){super(...arguments),this._timer=null,this._abort=null,this._results=[],this._query="",this._open=!1,this._phase="idle",this._error="",this._dropdownStyle="",this._onScrollOrResize=()=>{},this._onInput=t=>{const n=t.target.value;this._query=n,this._scheduleSearch(n)},this._onFocus=()=>{if(this._results.length===0&&this._phase==="idle"){this._scheduleSearch(this._query);return}this._open=!0,this._positionDropdown(),this.requestUpdate()},this._onBlur=()=>{setTimeout(()=>{this._open=!1,this.requestUpdate()},150)},this._pick=t=>{this.emit("os-user-pick",{user:t}),this._results=[],this._open=!1,this._phase="idle",this._query="";const n=this.shadowRoot?.querySelector(".input");n&&(n.value=""),this.requestUpdate()}}connectedCallback(){super.connectedCallback(),this._onScrollOrResize=()=>{this._open&&(this._positionDropdown(),this.requestUpdate())},window.addEventListener("resize",this._onScrollOrResize),window.addEventListener("scroll",this._onScrollOrResize,!0)}disconnectedCallback(){this._timer&&clearTimeout(this._timer),this._abort&&this._abort.abort(),window.removeEventListener("resize",this._onScrollOrResize),window.removeEventListener("scroll",this._onScrollOrResize,!0)}_endpoint(){const t=this.getAttribute("endpoint");return t||window.openStationConfig?.filesUsersSearchUrl||""}_scheduleSearch(t){this._timer&&clearTimeout(this._timer),this._phase="loading",this._open=!0,this._positionDropdown(),this.requestUpdate(),this._timer=setTimeout(()=>this._runSearch(t),200)}async _runSearch(t){const n=this._endpoint();if(!n){this._phase="error",this._error="Search endpoint is not configured.",this._results=[],this._open=!0,this.requestUpdate();return}this._abort&&this._abort.abort();const o=new AbortController;this._abort=o;const s=this.getAttribute("exclude")||"",i=n+"?q="+encodeURIComponent(t)+"&exclude="+encodeURIComponent(s);try{const r={signal:o.signal,credentials:"same-origin"},a=await Fe(i,r,{source:"desktop-mode/files-user-search",silent:!0});if(!a.ok)throw new Error(`HTTP ${a.status}`);const l=await a.json();this._results=l&&Array.isArray(l.users)?l.users:[],this._phase="ready",this._error="",this._open=!0}catch(r){if(r.name==="AbortError")return;this._results=[],this._phase="error",this._error=r.message||"Search failed.",this._open=!0}this._positionDropdown(),this.requestUpdate()}_positionDropdown(){const t=this.shadowRoot?.querySelector(".input");if(!t)return;const n=t.getBoundingClientRect(),o=n.bottom+4,s=n.left,i=n.width,a=window.innerHeight-n.bottom,l=n.top,c=Math.max(120,Math.min(280,Math.max(a,l)-16));a<200&&l>a?this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${n.top-4-c}px`,`width:${i}px`,`max-height:${c}px`].join(";"):this._dropdownStyle=["position:fixed",`left:${s}px`,`top:${o}px`,`width:${i}px`,`max-height:${c}px`].join(";")}_dropdownContent(){if(this._phase==="loading")return J`<div class="empty">Searching…</div>`;if(this._phase==="error")return J`<div class="empty error">${this._error}</div>`;if(this._results.length===0){const t=this._query?"No matches.":"No users available.";return J`<div class="empty">${t}</div>`}return this._results.map(t=>J` | |
| 66 | - <button | |
| 67 | - type="button" | |
| 68 | - class="item" | |
| 69 | - role="option" | |
| 70 | - @mousedown=${n=>n.preventDefault()} | |
| 71 | - @click=${()=>this._pick(t)} | |
| 72 | - > | |
| 73 | - <img class="avatar" src=${t.avatarUrl} alt="" /> | |
| 74 | - <div> | |
| 75 | - <div class="name">${t.name}</div> | |
| 76 | - <div class="slug">${t.slug}</div> | |
| 77 | - </div> | |
| 78 | - </button> | |
| 79 | - `)}render(){const t=this.getAttribute("placeholder")||"Search users…";return J` | |
| 80 | - <input | |
| 81 | - class="input" | |
| 82 | - type="search" | |
| 83 | - placeholder=${t} | |
| 84 | - autocomplete="off" | |
| 85 | - @input=${this._onInput} | |
| 86 | - @focus=${this._onFocus} | |
| 87 | - @blur=${this._onBlur} | |
| 88 | - .value=${this._query} | |
| 89 | - /> | |
| 90 | - ${this._open?J` | |
| 91 | - <div class="dropdown" role="listbox" style=${this._dropdownStyle}> | |
| 92 | - ${this._dropdownContent()} | |
| 93 | - </div> | |
| 94 | - `:J``} | |
| 95 | - `}};ys.props=["placeholder","exclude","endpoint"],ys.styles=[xD],ys.help=void 0;let _c=ys;xe("os-user-search",_c);const LD=ue`:host{display:flex;flex-wrap:wrap;gap:6px;font-size:13px}.chip{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;background:var( --os-ui-hover,rgba( 255,255,255,0.06 ) );color:inherit;border:1px solid var( --os-ui-border,rgba( 255,255,255,0.12 ) );cursor:pointer;font:inherit}.chip:hover{background:var( --os-ui-hover,rgba( 255,255,255,0.12 ) )}.chip[ aria-pressed='true' ]{background:var( --wp-admin-theme-color,#2271b1 );border-color:var( --wp-admin-theme-color,#2271b1 );color:var( --os-ui-fg-on-accent,#fff )}.empty{color:var( --os-ui-fg-muted,rgba( 255,255,255,0.5 ) );font-size:12px}`,bs=class bs extends Se{constructor(){super(...arguments),this._onToggle=t=>{const n=!this._selectedSet().has(t);this.emit("os-role-toggle",{slug:t,selected:n})}}_selectedSet(){const t=this.getAttribute("selected")||"";return new Set(t.split(",").map(n=>n.trim()).filter(n=>n!==""))}_roles(){const t=this.getAttribute("roles");if(t)try{const n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return window.openStationConfig?.shareEligibleRoles||[]}render(){const t=this._roles();if(t.length===0)return J`<span class="empty">No eligible roles.</span>`;const n=this._selectedSet();return J` | |
| 96 | - ${t.map(o=>{const s=n.has(o.slug);return J` | |
| 97 | - <button | |
| 98 | - type="button" | |
| 99 | - class="chip" | |
| 100 | - aria-pressed=${s?"true":"false"} | |
| 101 | - @click=${()=>this._onToggle(o.slug)} | |
| 102 | - >${o.name}</button> | |
| 103 | - `})} | |
| 104 | - `}};bs.props=["selected","roles"],bs.styles=[LD],bs.help=void 0;let Ec=bs;xe("os-role-picker",Ec);const TD=ue` ${dt}:host{display:inline-flex;position:relative;padding:3px;background:var( --os-ui-segmented-bg,var( --os-ui-hover,rgba( 0,0,0,0.05 ) ) );border-radius:8px;gap:2px}.os-segmented__thumb{position:absolute;top:3px;bottom:3px;left:0;width:var( --_thumb-w,0px );border-radius:6px;background-color:var( --os-ui-segmented-selected-bg,var( --os-ui-accent,#2271b1 ) );background-image:var( --os-ui-segmented-selected-image,none );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;transform:translateX( var( --_thumb-x,0px ) );pointer-events:none;opacity:0}:host( [ data-thumb ] ) .os-segmented__thumb{opacity:1}:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition:transform var( --_holo-t-slow ) var( --_holo-spring ),width var( --_holo-t-slow ) var( --_holo-ease ),opacity var( --_holo-t-fast ) linear}@media ( prefers-reduced-motion:reduce ){:host( [ data-thumb-ready ] ) .os-segmented__thumb{transition-duration:1ms}}`,ND=ue` ${dt} ${Sa}:host{flex:1 1 auto;min-width:0}button{appearance:none;display:block;width:100%;padding:6px 13px;background:transparent;border:0;font:inherit;font-size:13px;color:var( --os-ui-fg-muted,#646970 );cursor:pointer;border-radius:6px;transition:background-color var( --_holo-t ) ease,color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,background-position var( --_holo-t ) ease;white-space:nowrap}button:hover{color:var( --os-ui-fg,#1d2327 )}button:focus-visible{outline:none;box-shadow:var( --_holo-focus )}:host( [ aria-checked='true' ] ) button{color:var( --os-ui-segmented-selected-fg,var( --os-ui-fg-on-accent,#fff ) );transition-duration:var( --_holo-t-fast )}:host( [ aria-checked='true' ] ) button::before{display:none}`,vs=class vs extends Se{render(){return this.setAttribute("role","radio"),J` | |
| 105 | - <button | |
| 106 | - type="button" | |
| 107 | 5 | class="os-holo-sheen" |
| 108 | 6 | @click=${()=>this._onPick()} |
| 109 | 7 | > |
| 110 | 8 | <slot></slot> |
| 111 | 9 | </button> |
| 112 | - `}_onPick(){this.emit("os-segment-pick",{value:this.value})}};vs.props=["value"],vs.styles=[ND],vs.help=void 0;let kc=vs;xe("os-segment",kc);const _s=class _s extends Se{constructor(){super(...arguments),this._resizeObserver=null}connectedCallback(){super.connectedCallback(),this.addEventListener("os-segment-pick",t=>{const n=t.detail;t.stopPropagation(),this.value=n.value,this.emit("os-pick",{value:n.value})}),typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._placeThumb()),this._resizeObserver.observe(this))}disconnectedCallback(){this._resizeObserver?.disconnect(),this._resizeObserver=null}_placeThumb(){if(!this.shadowRoot?.querySelector(".os-segmented__thumb"))return;const n=this.value,o=Array.from(this.querySelectorAll(":scope > os-segment")).find(c=>c.getAttribute("value")===n);if(!o||this.offsetWidth===0){this.removeAttribute("data-thumb");return}const s=this.getBoundingClientRect(),i=s.width/this.offsetWidth,r=Math.abs(i-1)<.02?1:i;if(!(r>0))return;const a=o.getBoundingClientRect(),l=c=>`${Math.round(c*100)/100}px`;this.style.setProperty("--_thumb-x",l((a.left-s.left)/r)),this.style.setProperty("--_thumb-w",l(a.width/r)),this.setAttribute("data-thumb",""),this.hasAttribute("data-thumb-ready")||requestAnimationFrame(()=>this.setAttribute("data-thumb-ready",""))}set items(t){const n=this.querySelectorAll(":scope > os-segment");for(const i of Array.from(n))i.remove();for(const i of t){const r=document.createElement("os-segment");r.setAttribute("value",i.value),r.textContent=i.label,this.appendChild(r)}const o=this.value;!(o!==null&&t.some(i=>i.value===o))&&t.length>0?this.value=t[0].value:this.requestUpdate()}render(){const t=this.label||"";t&&this.setAttribute("aria-label",t),this.setAttribute("role","radiogroup");const n=this.value;return queueMicrotask(()=>{const o=this.querySelectorAll("os-segment");for(const s of Array.from(o)){const i=s.getAttribute("value");s.setAttribute("aria-checked",i===n?"true":"false")}this._placeThumb()}),J`<span class="os-segmented__thumb" aria-hidden="true"></span | |
| 113 | - ><slot></slot>`}};_s.props=["value","label"],_s.styles=[TD],_s.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <os-segment> children where exactly one is active.",status:"stable",props:[{name:"value",type:"string",description:"Currently selected segment value. Mirrored onto child aria-checked."},{name:"label",type:"string",description:"aria-label for the radiogroup."}],slots:[{name:"(default)",description:'<os-segment value="…"> children.'}],events:[{name:"os-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--os-window-bg",description:"Pill background."},{name:"--os-ui-fg",description:"Active label colour."},{name:"--os-ui-fg-muted",description:"Inactive label colour."}],example:J` | |
| 10 | + `}_onPick(){this.emit("os-segment-pick",{value:this.value})}};Xs.props=["value"],Xs.styles=[YC],Xs.help=void 0;let Lc=Xs;Jo("os-segment",Lc);const Zs=class Zs extends sn{constructor(){super(...arguments),this._resizeObserver=null}connectedCallback(){super.connectedCallback(),this.addEventListener("os-segment-pick",t=>{const n=t.detail;t.stopPropagation(),this.value=n.value,this.emit("os-pick",{value:n.value})}),typeof ResizeObserver<"u"&&(this._resizeObserver=new ResizeObserver(()=>this._placeThumb()),this._resizeObserver.observe(this))}disconnectedCallback(){this._resizeObserver?.disconnect(),this._resizeObserver=null}_placeThumb(){if(!this.shadowRoot?.querySelector(".os-segmented__thumb"))return;const n=this.value,o=Array.from(this.querySelectorAll(":scope > os-segment")).find(c=>c.getAttribute("value")===n);if(!o||this.offsetWidth===0){this.removeAttribute("data-thumb");return}const s=this.getBoundingClientRect(),i=s.width/this.offsetWidth,r=Math.abs(i-1)<.02?1:i;if(!(r>0))return;const a=o.getBoundingClientRect(),l=c=>`${Math.round(c*100)/100}px`;this.style.setProperty("--_thumb-x",l((a.left-s.left)/r)),this.style.setProperty("--_thumb-w",l(a.width/r)),this.setAttribute("data-thumb",""),this.hasAttribute("data-thumb-ready")||requestAnimationFrame(()=>this.setAttribute("data-thumb-ready",""))}set items(t){const n=this.querySelectorAll(":scope > os-segment");for(const i of Array.from(n))i.remove();for(const i of t){const r=document.createElement("os-segment");r.setAttribute("value",i.value),r.textContent=i.label,this.appendChild(r)}const o=this.value;!(o!==null&&t.some(i=>i.value===o))&&t.length>0?this.value=t[0].value:this.requestUpdate()}render(){const t=this.label||"";t&&this.setAttribute("aria-label",t),this.setAttribute("role","radiogroup");const n=this.value;return queueMicrotask(()=>{const o=this.querySelectorAll("os-segment");for(const s of Array.from(o)){const i=s.getAttribute("value");s.setAttribute("aria-checked",i===n?"true":"false")}this._placeThumb()}),jn`<span class="os-segmented__thumb" aria-hidden="true"></span | |
| 11 | + ><slot></slot>`}};Zs.props=["value","label"],Zs.styles=[qC],Zs.help={title:"Segmented",summary:"iOS-style segmented radio group. Pill-shaped bar of equal-width <os-segment> children where exactly one is active.",status:"stable",props:[{name:"value",type:"string",description:"Currently selected segment value. Mirrored onto child aria-checked."},{name:"label",type:"string",description:"aria-label for the radiogroup."}],slots:[{name:"(default)",description:'<os-segment value="…"> children.'}],events:[{name:"os-pick",description:"Fires when the selected segment changes.",detail:"{ value: string }"}],cssProps:[{name:"--os-window-bg",description:"Pill background."},{name:"--os-ui-fg",description:"Active label colour."},{name:"--os-ui-fg-muted",description:"Inactive label colour."}],example:jn` | |
| 114 | 12 | <os-segmented value="md" label="Dock size"> |
| 115 | 13 | <os-segment value="sm">Small</os-segment> |
| 116 | 14 | <os-segment value="md">Medium</os-segment> |
| 117 | 15 | <os-segment value="lg">Large</os-segment> |
| 118 | 16 | </os-segmented> |
| 119 | - `};let Sc=_s;xe("os-segmented",Sc);const DD=ue`:host{position:fixed;top:calc( var( --wp-admin--admin-bar--height,32px ) + 16px );inset-inline-end:16px;display:flex;flex-direction:column;gap:8px;z-index:calc( var( --os-z-fullscreen,99999 ) + 10 );pointer-events:none}`,RD=ue` ${dt}:host{display:flex;align-items:center;gap:12px;min-width:280px;max-width:420px;padding:10px 14px;background-color:var( --os-ui-toast-bg,var( --os-ui-modal-bg,#1d2327 ) );background-image:var( --os-ui-toast-bg-image,none );background-repeat:var( --os-ui-toast-bg-image-repeat,repeat );background-size:var( --os-ui-toast-bg-image-size,auto );background-position:var( --os-ui-toast-bg-image-position,center );color:var( --os-ui-fg-on-accent,#fff );border-radius:10px;border:1px solid var( --os-ui-border,rgba( 255,255,255,0.12 ) );box-shadow:0 10px 30px rgba( 0,0,0,0.4 ),0 2px 6px rgba( 0,0,0,0.18 ),inset 0 0 0 1px rgba( 255,255,255,0.04 );font-size:13px;line-height:1.4;opacity:0;transform:translateY( -10px ) scale( 0.97 );transition:opacity var( --_holo-t-fast ) linear,transform var( --_holo-t ) var( --_holo-spring );pointer-events:auto}:host( [ state='in' ] ){opacity:1;transform:translateY( 0 ) scale( 1 )}:host( [ state='out' ] ){opacity:0;transform:translateX( 16px ) scale( 0.97 );transition:opacity var( --_holo-t-fast ) linear,transform var( --_holo-t ) var( --_holo-ease )}.os-toast__label{flex:1}button[ hidden ]{display:none}button{flex-shrink:0;padding:4px 10px;border:none;border-radius:4px;background:var( --os-ui-hover,rgba( 255,255,255,0.12 ) );color:var( --os-ui-fg-on-accent,#fff );font:inherit;font-size:12px;font-weight:500;cursor:pointer;transition:background-color 0.12s ease}button:hover{background:var( --os-ui-scrim,rgba( 255,255,255,0.22 ) )}button:focus-visible{outline:2px solid var( --os-ui-border,rgba( 255,255,255,0.6 ) );outline-offset:2px}.os-toast__close{display:inline-flex;align-items:center;justify-content:center;padding:4px;border-radius:6px;background:transparent;color:var( --os-ui-fg-muted,rgba( 255,255,255,0.7 ) )}.os-toast__close:hover{background:var( --os-ui-hover,rgba( 255,255,255,0.14 ) );color:var( --os-ui-fg-on-accent,#fff )}@media ( prefers-reduced-motion:reduce ){:host{transition-duration:0.01ms}}`,br=class br extends Se{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return J`<slot></slot>`}};br.styles=[DD],br.help=void 0;let Ac=br;xe("os-toast-container",Ac);const Es=class Es extends Se{constructor(){super(...arguments),this._hovered=!1,this._focused=!1,this._onEnter=()=>{this._hovered=!0,this._syncHold()},this._onLeave=()=>{this._hovered=!1,this._syncHold()},this._onFocusIn=()=>{this._focused=!0,this._syncHold()},this._onFocusOut=t=>{const n=t.relatedTarget;n instanceof Node&&this._containsDeep(n)||(this._focused=!1,this._syncHold())}}connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.addEventListener("mouseenter",this._onEnter),this.addEventListener("mouseleave",this._onLeave),this.addEventListener("focusin",this._onFocusIn),this.addEventListener("focusout",this._onFocusOut)}disconnectedCallback(){this.removeEventListener("mouseenter",this._onEnter),this.removeEventListener("mouseleave",this._onLeave),this.removeEventListener("focusin",this._onFocusIn),this.removeEventListener("focusout",this._onFocusOut)}_containsDeep(t){let n=t;for(;n;){if(n===this)return!0;const o=n.parentNode;n=o instanceof ShadowRoot?o.host:o}return!1}_syncHold(){const t=this._hovered||this._focused;t!==this.hasAttribute("held")&&(t?this.setAttribute("held",""):this.removeAttribute("held"),this.emit("os-toast-hold",{held:t}))}render(){const t=this.action||"",n=this.hasAttribute("dismissible");return J` | |
| 120 | - <span class="os-toast__label"><slot></slot></span> | |
| 121 | - <button | |
| 122 | - type="button" | |
| 17 | + `};let Tc=Zs;Jo("os-segmented",Tc);const XC="openstation_overview",ZC="openstation_hop_from";function cm(e,t){try{const n=new URL(e,window.location.href);return n.searchParams.set(XC,"1"),t&&n.origin!==window.location.origin&&n.searchParams.set(ZC,t),n.toString()}catch{return e}}function Nc(e){const t=[];e.networkAdmin?.shellUrl&&t.push({value:"network",label:b("Network Admin"),shellUrl:e.networkAdmin.shellUrl,external:!1,foreign:e.networkAdmin.foreign===!0});for(const n of e.sites??[])t.push({value:n.id,label:n.name,shellUrl:n.shellUrl,external:n.kind==="member",foreign:n.foreign===!0,tabUrl:n.active===!1?n.adminUrl:void 0});return t}function Oc(e,t,n={}){const o=n.hop??Sc,s=Nc(e),i=e.current??"",r=s.findIndex(f=>f.value===t);if(r<0||t===i)return!1;const a=s[r];if(a.tabUrl)return window.open(a.tabUrl,"_blank","noopener"),!0;const l=s.findIndex(f=>f.value===i),c=r>l?"next":"prev",d=cm(a.shellUrl,c),u=n.mint&&a.foreign?n.mint(a.shellUrl,c).catch(()=>null):Promise.resolve(null);return Promise.all([_C(c),u]).then(([,f])=>o(f??d)),!0}function JC(e){const t=n=>{if(n.key!=="Tab"||n.ctrlKey||n.metaKey||n.altKey||n.defaultPrevented)return;const o=e.multisite();if(!o||!e.isShown()||oc(document))return;const i=(n.target?.ownerDocument??document).activeElement;if(i&&i.closest(".os-overview-top-bar")&&!i.closest(".os-site-switcher"))return;const r=o.current??"",a=Nc(o).filter(u=>!u.tabUrl||u.value===r);if(a.length<2)return;const l=a.findIndex(u=>u.value===r),c=n.shiftKey?-1:1,d=a[(l+c+a.length)%a.length];n.preventDefault(),Oc(o,d.value,e)};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)}function lm(){const e=document.createElement("span");return e.className="dashicons dashicons-external os-site-switcher__mark",e.setAttribute("aria-hidden","true"),e}function QC(e,t={}){const n=t.hop??Sc,o=Nc(e);if(o.length<2)return null;const s=e.current??"",i=new Map(o.map(c=>[c.value,c])),r=document.createElement("os-segmented");r.className="os-site-switcher",r.setAttribute("label",b("Site")),r.setAttribute("value",s);let a=!1;for(const c of o){if(c.external&&!a){a=!0;const u=document.createElement("span");u.className="os-site-switcher__divider",u.setAttribute("role","separator"),u.setAttribute("aria-orientation","vertical"),r.appendChild(u)}const d=document.createElement("os-segment");if(d.setAttribute("value",c.value),c.external){d.setAttribute("data-external",""),d.title=b("External site"),d.appendChild(lm());const u=document.createElement("span");u.className="screen-reader-text",u.textContent=b("External site:")+" ",d.appendChild(u)}else if(c.tabUrl){d.setAttribute("data-opens-tab",""),d.title=b("OpenStation is not active on this site. Opens its admin in a new tab."),d.appendChild(lm());const u=document.createElement("span");u.className="screen-reader-text",u.textContent=b("Opens in a new tab:")+" ",d.appendChild(u)}d.appendChild(document.createTextNode(c.label)),r.appendChild(d)}const l=c=>{const d=c.target?.closest("os-segment"),u=d?i.get(d.getAttribute("value")??""):void 0;if(!u)return;if(u.tabUrl&&(c.type==="click"||c.button===1)){c.preventDefault(),c.stopPropagation(),window.open(u.tabUrl,"_blank","noopener");return}if(!Jh(c))return;c.preventDefault(),c.stopPropagation();const f=cm(u.shellUrl);if(!t.mint||!u.foreign){n(f,c);return}const p=window.open("","_blank");t.mint(u.shellUrl,"next").catch(()=>null).then(g=>{p?p.location.href=g??f:n(f,c)})};return r.addEventListener("click",l,!0),r.addEventListener("auxclick",l,!0),r.addEventListener("os-pick",c=>{const d=c.detail?.value;d&&Oc(e,d,t)}),r}function eL(e){return(t,n)=>Ae(t,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e},body:JSON.stringify({accept:n})},{source:"desktop-mode/network"})}async function tL(e,t){const n=e.email?`${e.name} (${e.email})`:e.name,o=await t.confirm({title:b("Arrive logged in next time?"),message:b("%1$s just switched here from %2$s while you were logged in. Link that account to yours, and a switch from there logs you in as you. You can undo this in the Network window.").replace("%1$s",n).replace("%2$s",e.site),confirmLabel:b("Link accounts")});try{await t.post(e.url,o)}catch{}return o}const zi=new Map;function dm(e){if(!e||typeof e.id!="string"||e.id===""){typeof console<"u"&&console.warn("[openstation] Ignored invalid module registration:",e);return}if(typeof e.url!="string"||e.url===""){typeof console<"u"&&console.warn(`[openstation] Module "${e.id}" has no url; ignored.`);return}zi.set(e.id,e)}function nL(){return Array.from(zi.keys())}async function Dc(e){if(!e||e.length===0)return;const t=e.filter(n=>!zi.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${nL().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=zi.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():pe(o.url)}))}const oL="os-wallpaper-light",sL=.185,Vn=32,iL=3e3,rL=new Set([xo,tf]),um=new Map;function fm(e,t,n){const o=s=>{const i=s/255;return i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4)};return .2126*o(e)+.7152*o(t)+.0722*o(n)}function pm(e){return e>sL?"light":"dark"}function aL(e){const t=[],n=/#([0-9a-f]{3}|[0-9a-f]{6})\b/gi;let o=n.exec(e);for(;o!==null;){const i=o[1],r=i.length===3?i.split("").map(a=>a+a).join(""):i;t.push([parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]),o=n.exec(e)}const s=/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/gi;for(o=s.exec(e);o!==null;)t.push([Number(o[1]),Number(o[2]),Number(o[3])]),o=s.exec(e);return t}function cL(e){const t=/url\(\s*(['"]?)([^'")]+)\1\s*\)/i.exec(e);return t?t[2].trim():null}function lL(e){const t=aL(e);if(t.length===0)return null;const n=t.reduce((o,[s,i,r])=>o+fm(s,i,r),0);return pm(n/t.length)}async function dL(e){const t=um.get(e);if(t)return t;try{const n=new Image;if(n.crossOrigin="anonymous",!await new Promise(d=>{const u=setTimeout(()=>d(!1),iL),f=p=>()=>{clearTimeout(u),d(p)};n.onload=f(!0),n.onerror=f(!1),n.src=e}))return null;const s=document.createElement("canvas");s.width=Vn,s.height=Vn;const i=s.getContext("2d");if(!i)return null;i.drawImage(n,0,0,Vn,Vn);const{data:r}=i.getImageData(0,0,Vn,Vn);let a=0,l=0;for(let d=0;d<r.length;d+=4)r[d+3]!==0&&(a+=fm(r[d],r[d+1],r[d+2]),l++);if(l===0)return null;const c=pm(a/l);return um.set(e,c),c}catch{return null}}async function uL(e){if(e.tone==="light"||e.tone==="dark")return e.tone;if(e.type!=="css"||!rL.has(e.id))return"dark";let t="";try{t=e.resolveValue?"":e.value??""}catch{t=""}if(t===""&&(t=fL()),t==="")return"dark";const n=cL(t);return n!==null?await dL(n)??"dark":lL(t)??"dark"}function fL(){if(typeof document>"u")return"";const t=document.getElementById("os-shell")??document.body;return t?t.style.getPropertyValue("--os-bg").trim():""}function pL(e){typeof document>"u"||!document.body||document.body.classList.toggle(oL,e==="light")}function hm(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:hL(),visible:!document.hidden,settings:VA(e)}}function hL(){return typeof window.matchMedia!="function"?!1:window.matchMedia("( prefers-reduced-motion: reduce )").matches}class mm{constructor(t,n){this.generation=0,this.active=null,this.suspendReasons=new Map,this.freezeOverlay=null,this.frozenCanvas=null,this.boundVisibilityChange=()=>{this.emitEffectiveVisibility()},this.element=t,this.pluginUrl=n,document.addEventListener("visibilitychange",this.boundVisibilityChange)}apply(t){const n=++this.generation;if(this.teardownActive(),t.type==="css"){this.applyCss(t),this.applyTone(t,n);return}this.applyCanvas(t,n),this.applyTone(t,n)}applyTone(t,n){uL(t).then(o=>{n===this.generation&&pL(o)})}suspend(t){const n=this.isSuspended();this.suspendReasons.set(t,(this.suspendReasons.get(t)??0)+1),!n&&(this.installFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}resume(t){const n=this.suspendReasons.get(t);if(n!==void 0){if(n>1){this.suspendReasons.set(t,n-1);return}this.suspendReasons.delete(t),!this.isSuspended()&&(this.removeFreezeOverlay(),this.emitSuspendAction(),this.emitEffectiveVisibility())}}isSuspended(){return this.suspendReasons.size>0}teardownActive(){if(this.removeFreezeOverlay(),!this.active)return;const{id:t,teardown:n}=this.active;this.active=null,A(v.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){A(v.SHELL_ERROR,{scope:"wallpaper-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" teardown threw:`,o)}this.element.innerHTML=""}dispose(){this.teardownActive(),document.removeEventListener("visibilitychange",this.boundVisibilityChange)}applyCss(t){const n=t.resolveValue?t.resolveValue(hm(t.id,this.pluginUrl)):t.value;typeof n=="string"&&(this.element.style.setProperty("--os-bg",n),document.getElementById("os-shell")?.style.setProperty("--os-bg",n))}applyCanvas(t,n){const o=hm(t.id,this.pluginUrl);A(v.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?Dc(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},A(v.WALLPAPER_MOUNTED,{id:t.id,container:this.element,ctx:o}),this.isEffectivelyHidden()&&this.emitEffectiveVisibility()};s.then(()=>{if(n!==this.generation)return;let r;try{r=t.mount(this.element,o)}catch(a){this.handleMountFailure(t.id,a);return}if(mL(r)){r.then(i,a=>{n===this.generation&&this.handleMountFailure(t.id,a)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(t.id,r)})}isEffectivelyHidden(){return document.hidden||this.isSuspended()}emitEffectiveVisibility(){this.active&&A(v.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){A(v.WALLPAPER_SUSPEND,{id:this.active?.id??null,suspended:this.isSuspended(),reasons:Array.from(this.suspendReasons.keys())})}installFreezeOverlay(){if(this.freezeOverlay||!this.active)return;const t=this.element.querySelector("canvas");if(!(!t||t.width===0||t.height===0))try{const n=document.createElement("canvas");n.width=t.width,n.height=t.height;const o=n.getContext("2d");if(!o)return;o.drawImage(t,0,0),n.className="os-wallpaper-freeze",n.style.position="absolute",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.pointerEvents="none",n.setAttribute("aria-hidden","true"),this.element.appendChild(n),t.style.visibility="hidden",this.freezeOverlay=n,this.frozenCanvas=t}catch{}}removeFreezeOverlay(){this.freezeOverlay?.remove(),this.freezeOverlay=null,this.frozenCanvas&&(this.frozenCanvas.style.visibility="",this.frozenCanvas=null)}handleMountFailure(t,n){this.element.innerHTML="",A(v.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),A(v.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function mL(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const gm=ae("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),Kn=gm.state.seed,Rc=gm.state.listeners;function xc(e){Oe("Game",Yt(e,bm),e);const t=Kn.findIndex(n=>n.id===e.id);t>=0?Kn[t]=e:Kn.push(e),ym()}function wm(e){const t=Kn.findIndex(n=>n.id===e);t>=0&&(Kn.splice(t,1),ym())}function gL(e){return Rc.add(e),()=>{Rc.delete(e)}}function ym(){const e=Array.from(Rc);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function vm(){const e=Kn.slice(),t=J(v.GAMES,e);return Array.isArray(t)?t.filter(wL):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function ji(e){return vm().find(t=>t.id===e)}const bm=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"title",message:"missing or not a non-empty string",valid:e=>typeof e.title=="string"&&e.title!==""},{field:"scoreColumns",message:"must be an array",valid:e=>Array.isArray(e.scoreColumns)},{field:"render/scriptUrl",message:"needs a `render` callback or a `scriptUrl` to lazily load one",valid:e=>typeof e.render=="function"||typeof e.scriptUrl=="string"&&e.scriptUrl!==""}];function wL(e){return Yt(e,bm).length===0}const Em=new Set;function Vi(e){if(Em.has(e))return;const n=window.openStationConfig?.deferredStyles?.[e];if(!n?.url)return;Em.add(e);const o=n.url.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${o}"]`)){const i=document.createElement("link");i.rel="stylesheet",i.href=n.url,i.dataset.osStyleHandle=e,document.head.appendChild(i)}for(const i of n.inline??[]){if(typeof i!="string"||i==="")continue;const r=document.createElement("style");r.dataset.osStyleHandle=e,r.textContent=i,document.head.appendChild(r)}}const yL="desktop-mode/games";function vL(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function Qo(e,t={},n={}){const{restUrl:o,restNonce:s}=vL(),i=new Headers(t.headers??{});i.set("X-WP-Nonce",s),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Ae(rt(o,e),{...t,headers:i,credentials:"same-origin"},{source:yL,windowId:n.windowId,silent:n.silent}),a=await r.json().catch(()=>null);if(!r.ok)throw mt(r.status,a);return a}function bL(e,t,n={}){return Qo(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function EL(){return Qo("desktop-mode/v1/games/playtime")}function _L(e,t,n={}){return Qo(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function SL(e){return Qo(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function kL(e,t,n={}){return Qo(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const IL=6e4;function AL(e,t={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const l=Date.now();o+=Math.max(0,l-n),n=l},r=()=>{i();const l=Math.floor(o/1e3);l<1||(o-=l*1e3,_L(e,l,{windowId:t.windowId,silent:!0}).catch(()=>{o+=l*1e3}))},a=setInterval(r,IL);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(a),i(),n=null,r())}}}const qn=ae("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function CL(){return qn.state}function Mc(e){const t=qn.state;let n=!1;for(const o of e){if(!o||typeof o.id!="number")continue;const s=t.rows.get(o.id);(!s||s.updatedAtMs!==o.updatedAtMs)&&(t.rows.set(o.id,o),n=!0),o.updatedAtMs>t.version&&(t.version=o.updatedAtMs)}n&&TL()}function LL(e){return qn.state.listeners.add(e),()=>{qn.state.listeners.delete(e)}}function TL(){for(const e of Array.from(qn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function NL(){return Array.from(qn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function _m(){return window.wp?.os??{}}const OL=760,DL=560,RL=480,xL=380;function ML(){const e=window.openStationConfig?.gameStyleHandles??[];for(const t of e)Vi(t)}async function WL(e){if(typeof e.render=="function")return e;const t=_m().loadVendorScript;if(!e.scriptUrl||typeof t!="function")throw new Error(`[openstation] Game "${e.id}" has no render callback and no loadable script.`);await t(e.scriptUrl,{translations:e.scriptTranslations,deps:e.scriptDeps,l10n:e.scriptL10n,before:e.scriptBefore,after:e.scriptAfter});const o=window.openStationGames?.[e.id];if(!o||typeof o.render!="function")throw new Error(`[openstation] No game def on window.openStationGames["${e.id}"]. Script loaded but didn't publish a def — check the plugin's global assignment.`);const s={...e,render:o.render,window:o.window??e.window};return xc(s),s}async function Sm(e,t={}){const n=_m(),o=ji(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);if(ML(),typeof n.registerWindow!="function")throw new Error("[openstation] wp.os.registerWindow is missing — the shell must boot before launching games.");const s=`os-game-${e}`,i=`game:${s}`,r=n.windowManager,a=r?.getByBaseId?.(s)??r?.getById(s);if(a){const g=a.config?.desktopId;g&&r?.switchDesktop&&g!==r?.getActiveDesktopId?.()&&r.switchDesktop(g),n.registerWindow({id:s,title:o.title,icon:o.icon,render:()=>{}});return}n.wallpaper?.suspend(i);let l=!1;const c=()=>{l||(l=!0,n.wallpaper?.resume(i))};let d=null;const u=()=>{d?.stop(),d=null};n.onWindow?.(s,{closed:()=>{u(),c()},minimized:()=>d?.pause(),restored:()=>d?.resume()});const f=(g,h)=>{n.activity?.publish("os/game-score-recorded",{game:e,score:g.score,meta:g.meta??{},windowId:s,challengeId:h})},p=g=>{if(t.challenge){const h=t.challenge.id;return kL(h,g,{windowId:s}).then(({challenge:m})=>{Mc([m]),f(g,h)})}return bL(e,g,{windowId:s}).then(()=>f(g))};try{await n.registerWindow({id:s,title:o.title,icon:o.icon,width:o.window?.width??OL,height:o.window?.height??DL,minWidth:o.window?.minWidth??RL,minHeight:o.window?.minHeight??xL,render:async g=>{const h=await WL(o),m=h.render;if(typeof m!="function")throw new Error(`[openstation] Game "${e}" did not provide a render callback.`);const _={windowId:s,container:g,config:h.config??{},challenge:t.challenge,submitScore:p,close:()=>{n.windowManager?.getById(s)?.close()}};d=AL(e,{windowId:s});const I=m(_);return()=>{try{I?.()}finally{u(),c()}}}})}catch(g){throw u(),c(),g}}const km={register:xc,unregister:wm,list:vm,get:ji,subscribe:gL,launch:Sm,getPlaytime:()=>EL().then(e=>e.playtime)},Yn=ae("desktop-mode/wallpaper-lazy",()=>({pending:new Map,inflight:new Map}));function PL(e){Yn.state.pending.set(e.id,e)}function Ki(e){Yn.state.pending.delete(e)}function $L(e){return(window.openStationWallpapers||{})[e]??null}function Im(e){const t=Yn.state.inflight.get(e);if(t)return t;const n=Yn.state.pending.get(e);if(!n)return Promise.resolve(null);const o=(async()=>{try{await pe(n.scriptUrl,{translations:n.scriptTranslations,deps:n.scriptDeps,l10n:n.scriptL10n,before:n.scriptBefore,after:n.scriptAfter})}catch(i){return A(v.SHELL_ERROR,{scope:"wallpaper-script-load",id:n.id,error:i}),null}let s=$L(n.id);if(s&&!s.description&&n.description&&(s={...s,description:n.description}),!s)return A(v.SHELL_ERROR,{scope:"wallpaper-missing-def",id:n.id,error:new Error(`[openstation] No wallpaper def on window.openStationWallpapers["${n.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)}),null;try{Fn(s)}catch(i){return A(v.SHELL_ERROR,{scope:"wallpaper-register",id:n.id,error:i}),null}return Ki(n.id),s})().finally(()=>{Yn.state.inflight.delete(e)});return Yn.state.inflight.set(e,o),o}function UL(e){return{id:e.id,label:e.label,type:"canvas",preview:e.preview!==""?e.preview:e.value,description:e.description||void 0,mount:async(t,n)=>{const o=await Im(e.id);return!o||o.type!=="canvas"?()=>{}:(o.needs&&o.needs.length>0&&await Dc(o.needs),o.mount(t,n))}}}function BL(e){const{osSettings:t}=e,n=new Set,o=r=>r.type!=="css"||r.value===""?null:{id:r.id,label:r.label,type:"css",value:r.value,preview:r.preview!==""?r.preview:r.value,description:r.description||void 0,tone:r.tone==="light"||r.tone==="dark"?r.tone:void 0},s=async r=>{if(n.has(r.id))return;const a=o(r);if(a){Fn(a),n.add(r.id),t.apply();return}if(!r.scriptUrl)return;PL(r);const l=r.preview!==""||r.value!=="";if(l){try{Fn(UL(r))}catch(c){A(v.SHELL_ERROR,{scope:"wallpaper-register",id:r.id,error:c}),Ki(r.id);return}n.add(r.id)}if(!l||t.state.wallpaper===r.id){const c=await Im(r.id);if(!l){if(!c){Ki(r.id);return}n.add(r.id)}}t.apply()},i=r=>{n.has(r)&&(ah(r),Ki(r),n.delete(r),t.apply())};return async r=>{const a=new Set;for(const l of r)a.add(l.id);for(const l of Array.from(n))a.has(l)||i(l);for(const l of r)n.has(l.id)||await s(l)}}function FL(e){return{id:e.id,title:e.title,icon:e.icon,description:e.description||void 0,scoreColumns:Array.isArray(e.scoreColumns)?e.scoreColumns:[],config:e.config??{},window:e.window&&Object.keys(e.window).length>0?e.window:void 0,scriptUrl:e.scriptUrl,scriptTranslations:e.scriptTranslations,scriptL10n:e.scriptL10n,scriptBefore:e.scriptBefore,scriptAfter:e.scriptAfter,scriptDeps:e.scriptDeps}}function HL(){const e=new Set,t=o=>{try{const s=ji(o.id),i=FL(o);xc(s&&typeof s.render=="function"?{...i,render:s.render,window:s.window}:i)}catch(s){typeof console<"u"&&console.error(`[openstation] Server game "${o.id}" failed to register:`,s);return}e.add(o.id)},n=o=>{e.has(o)&&(wm(o),e.delete(o))};return async o=>{const s=new Set;for(const i of o)i&&typeof i.id=="string"&&i.id!==""&&s.add(i.id);for(const i of Array.from(e))s.has(i)||n(i);for(const i of o)s.has(i.id)&&t(i)}}const yt=ae("desktop-mode/heartbeat-bus",()=>({suppliers:new Map,subscribers:new Map,booted:!1})),Re={contribute(e,t){return yt.state.suppliers.set(e,t),()=>{yt.state.suppliers.get(e)===t&&yt.state.suppliers.delete(e)}},subscribe(e,t){let n=yt.state.subscribers.get(e);return n||(n=new Set,yt.state.subscribers.set(e,n)),n.add(t),()=>{n.delete(t)}}};function GL(){if(yt.state.booted)return;yt.state.booted=!0;const e=window.jQuery;if(!e){console.warn("[desktop-mode/heartbeat] jQuery missing — Heartbeat bus disabled.");return}e(document).on("heartbeat-send",(...t)=>{const n=t[1];if(n)for(const[o,s]of yt.state.suppliers)try{n[o]=s()}catch(i){console.error(`[desktop-mode/heartbeat] supplier for "${o}" threw:`,i)}}),e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n)for(const[o,s]of yt.state.subscribers){const i=n[o];if(i!==void 0)for(const r of s)try{r(i)}catch(a){console.error(`[desktop-mode/heartbeat] subscriber for "${o}" threw:`,a)}}})}let qi=null,Yi={installHintDismissed:!1,notificationsEnabled:!1};const Wc=new Set;function Am(e){if(!e){qi=null;return}qi=e,Yi={...e.state},Lm()}function es(){return{...Yi}}function Pc(e){if(Yi={...Yi,...e},Lm(),!qi)return es();const t=JSON.stringify(e),n=zL();return fetch(qi.stateUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",...n?{"X-WP-Nonce":n}:{}},body:t}).catch(o=>{typeof console<"u"&&console.warn("[openstation] pwa-state write failed:",o)}),es()}function Cm(e){return Wc.add(e),()=>{Wc.delete(e)}}function Lm(){const e=es();for(const t of Array.from(Wc))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function zL(){return window.openStationConfig?.restNonce??""}const jL=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:es,initPwaState:Am,subscribePwaState:Cm,updatePwaState:Pc},Symbol.toStringTag,{value:"Module"}));function $c(e){const t=_e.filter("os/notification-requested",{...e});if(!t||t.cancel===!0||!t.title)return()=>{};let n=!1,o=null,s=null;const i=()=>{n||(n=!0,o&&o(),s&&s())},r=()=>{s=ue({message:t.body?t.title+" — "+t.body:t.title}),_e.publish("os/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const a=Notification.permission;return a==="granted"?(o=Tm(t),o||r(),i):a==="denied"?(r(),i):(Notification.requestPermission().then(l=>{if(!n){if(l==="granted"){Pc({notificationsEnabled:!0}),o=Tm(t),o||r();return}r()}}),i)}function Tm(e){let t=null;try{t=new Notification(e.title,{body:e.body,icon:e.icon,tag:e.tag,requireInteraction:e.requireInteraction})}catch(n){return typeof console<"u"&&console.warn("[openstation] Notification ctor threw:",n),null}if(e.onClick){const n=e.onClick;t.onclick=()=>{try{n(t)}catch(o){typeof console<"u"&&console.error("[openstation] notification onClick threw:",o)}}}return _e.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function VL(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&Pc({notificationsEnabled:!0}),e}function KL(){return typeof Notification>"u"?"unsupported":Notification.permission}function qL(e){return ji(e)?.title||e}const Nm=new Set,Om=new Set;async function YL(e){const{challenge:t}=await SL(e.id);Mc([t]),await Sm(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function XL(e){const t=le(b("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,qL(e.game),String(e.scoreToBeat));$c({title:b("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),ue({message:t,persistent:!0,dismissible:!0,action:{label:b("Accept & Play"),onClick:()=>{YL(e).catch(n=>{ue({message:n instanceof Error?n.message:b("Could not accept the challenge.")})})}}})}function ZL(e){let t;e.result==="beaten"?t=b("%1$s beat your score: %2$s vs your %3$s."):t=b("%1$s did not beat your score: %2$s vs your %3$s.");const n=le(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));$c({title:b("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),ue({message:n})}function JL(e){const{currentUserId:t}=e;if(!t)return;Re.contribute("openstation_games_subscribe",()=>({challengesVersion:CL().version})),Re.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&Mc(o.challenges)});const n=()=>{for(const o of NL())o.state==="pending"&&o.recipientId===t&&!Nm.has(o.id)&&(Nm.add(o.id),XL(o)),o.state==="completed"&&o.challengerId===t&&!Om.has(o.id)&&(Om.add(o.id),ZL(o))};LL(n),n()}const Dm=/^[a-z0-9_/-]+$/,Rm=ae("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),rn=Rm.state.registry,QL=Rm.state.listeners;function Xn(e){const t=[],n=typeof e?.slug=="string"?e.slug.trim().toLowerCase():"";!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.slug!="string"||e.slug.trim()===""?t.push("slug (missing)"):Dm.test(n)||t.push(`slug (must match ${Dm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.run!="function"&&t.push("run (must be a function)")),Oe("Command",t,e),rn.set(n,{...e,slug:n}),Uc()}function xm(e){rn.delete(e.toLowerCase())&&Uc()}function Xi(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(rn.entries()))o.owner===e&&(rn.delete(n),t++);return t>0&&Uc(),t}function Mm(){return Array.from(rn.values())}function eT(){const e=[];for(const t of rn.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function tT(e){return rn.get(e.toLowerCase())??null}function Uc(){const e=Array.from(QL);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function nT(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.slug)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.slug)}return a},i=r=>{const a=new Set;for(const c of Mm())c.owner===r&&a.add(c.slug);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))xm(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Wm=ae("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),ts=Wm.state.registry,oT=Wm.state.listeners;function Pm(e){if(!e||typeof e.id!="string"||e.id.trim()===""||typeof e.label!="string"||e.label.trim()===""||typeof e.render!="function")return;const t=e.id.trim().toLowerCase();if(!/^[a-z0-9_\-]+$/.test(t)){typeof console<"u"&&console.warn("[openstation] registerSettingsTab: id must be [a-z0-9_-]+, got",e.id);return}ts.set(t,{...e,id:t}),Bc()}function $m(e){ts.delete(e.toLowerCase())&&Bc()}function sT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ts.entries()))o.owner===e&&(ts.delete(n),t++);return t>0&&Bc(),t}function Um(){return Array.from(ts.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Bc(){const e=Array.from(oT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function iT(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{sT(r);const a=n.get(r);if(a){const l=new Set(Um().map(c=>c.id));for(const c of a)l.has(c)&&$m(c)}};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))l.has(c)||(i(c),e.delete(c));for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Bm=ae("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),ns=Bm.state.registry,rT=Bm.state.listeners,Fm=/^[a-z0-9_/-]+$/;function os(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Fm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Fm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (missing)"),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)")),Oe("TitleBarButton",t,e);const n=e.id.trim().toLowerCase();ns.set(n,{...e,id:n}),Zi()}function Hm(e){ns.delete(e.toLowerCase())&&Zi()}function aT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ns.entries()))o.owner===e&&(ns.delete(n),t++);return t>0&&Zi(),t}function cT(){return Array.from(ns.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function Zi(){const e=Array.from(rT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] title-bar-button registry listener threw:",n)}}typeof document<"u"&&document.addEventListener("os-settings-save-lifecycle",e=>{const t=e.detail;t&&t.phase==="saved"&&Zi()});function lT(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"titlebar-button-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(aT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Gm=ae("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),ss=Gm.state.registry,dT=Gm.state.listeners,zm=/^[a-z0-9_/-]+$/;function Fc(){for(const e of Array.from(dT))try{e()}catch{}}function jm(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):zm.test(e.id.trim().toLowerCase())||t.push(`id (must match ${zm} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.label!="string"&&typeof e.label!="function"?t.push("label (must be a string or a function)"):typeof e.label=="string"&&e.label.trim()===""&&t.push("label (empty)"),typeof e.onSelect!="function"&&t.push("onSelect (must be a function)"),e.isVisible!==void 0&&typeof e.isVisible!="function"&&t.push("isVisible (must be a function when set)"),e.checked!==void 0&&typeof e.checked!="function"?t.push("checked (must be a function when set)"):e.checkable&&typeof e.checked!="function"&&t.push("checked (required when checkable is set)")),Oe("WindowAction",t,e);const n=e.id.trim().toLowerCase();ss.set(n,{...e,id:n}),Fc()}function uT(e){ss.delete(String(e||"").toLowerCase())&&Fc()}function fT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ss.entries()))o.owner===e&&(ss.delete(n),t++);return t>0&&Fc(),t}function pT(){return Array.from(ss.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function hT(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"window-action-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(fT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function Vm(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function mT({items:e,onPick:t}){const n=document.createElement("os-menu");n.classList.add("os-window__menu-panel"),n.classList.add("os-window__related-panel");const o=new Map;for(const r of e){const a=o.get(r.group);a?a.push(r):o.set(r.group,[r])}const s=Array.from(o.entries()).sort((r,a)=>Vm(r[0])-Vm(a[0])),i=[];for(const[,r]of s){const a=r.find(l=>typeof l.groupLabel=="string"&&l.groupLabel!=="")?.groupLabel;if(a){const l=document.createElement("div");l.className="os-window__related-group",l.setAttribute("role","presentation"),l.textContent=a,n.appendChild(l)}for(const l of r){const c=document.createElement("os-menu-item");c.setAttribute("role","menuitem"),c.setAttribute("value",l.id),c.tabIndex=-1,l.icon&&c.setAttribute("icon",l.icon),c.classList.add("os-window__related-item"),c.textContent=typeof l.count=="number"?`${l.label} (${l.count})`:l.label,c.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),t(l)}),i.push(c),n.appendChild(c)}}return n.addEventListener("keydown",r=>{const a=r,l=i.indexOf(n.ownerDocument.activeElement);if(a.key==="ArrowDown"||a.key==="ArrowUp"){a.preventDefault(),a.stopPropagation();const c=a.key==="ArrowDown";let d=i[c?0:i.length-1];l!==-1&&(d=i[(l+(c?1:-1)+i.length)%i.length]),d?.focus()}else if(a.key==="Home"||a.key==="End")a.preventDefault(),a.stopPropagation(),i[a.key==="Home"?0:i.length-1]?.focus();else if(a.key==="Enter"||a.key===" "){const c=i[l];c&&(a.preventDefault(),a.stopPropagation(),c.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function Km(e){if(!e||typeof e!="object")return!1;const t=e,n=o=>typeof o=="string"&&o.trim()!=="";return n(t.id)&&n(t.group)&&n(t.label)&&(n(t.url)||n(t.windowId))&&(t.url===void 0||typeof t.url=="string")&&(t.windowId===void 0||typeof t.windowId=="string")&&(t.params===void 0||!!t.params&&typeof t.params=="object")&&(t.groupLabel===void 0||typeof t.groupLabel=="string")&&(t.icon===void 0||typeof t.icon=="string")&&(t.count===void 0||typeof t.count=="number"&&Number.isFinite(t.count))}function qm(e){const t=ze(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=J(v.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(Km):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(Km))}function Hc(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function gT(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function wT(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=qm(t.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",a),l.remove(),e.setAttribute("aria-expanded","false")},a=c=>{c.key==="Escape"&&(c.stopPropagation(),r(),e.focus())},l=mT({items:s,onPick:c=>{r(),gT(o),n(c)}});l._wpdRelatedClose=r,o.appendChild(l),o.addEventListener("keydown",a),e.setAttribute("aria-expanded","true"),i=c=>{const d=c.target;!d||l.contains(d)||e.contains(d)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),l.querySelector('[role="menuitem"]')?.focus()}function yT({manager:e,openUrl:t}){os({id:"desktop-mode/related-entities",label:b("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>qm(n.id).length>0,render:(n,o)=>{Hc(o.element),n.setAttribute("aria-haspopup","menu"),n.setAttribute("aria-expanded","false"),n.addEventListener("click",s=>{if(s.stopPropagation(),o.element?.querySelector(".os-window__related-panel")){Hc(o.element);return}wT(n,o,t)})}}),ee(v.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(Hc(o.element),o.renderCustomTitleBarButtons?.())})}const Gc="os-broadcast",Ym="os-broadcast",Xm=window.location.origin;let zc=null;function vT(e){zc=e}function Ji(e,t){const n=String(J("os.broadcast.topic",e,{payload:t})??e),o=J("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Gc,{detail:s})),A(v.BROADCAST,s),_e.publish(n,o),!zc)return;const i={type:Ym,topic:n,payload:o};for(const r of zc._stack){const a=r.iframe?.contentWindow;if(a)try{a.postMessage(i,Xm)}catch{}}}function Zn(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){A(v.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Gc,n),()=>document.removeEventListener(Gc,n)}function bT(){window.addEventListener("message",e=>{if(e.origin!==Xm)return;const t=e.data;!t||t.type!==Ym||t._fromParent||typeof t.topic=="string"&&Ji(t.topic,t.payload)})}function Zm(e,t,n,o=""){const s=(Array.isArray(n)?n:[n]).map(r=>Math.floor(Number(r))).filter(r=>Number.isFinite(r)&&r>0),i=String(e).trim();i===""||s.length===0||Ji(`os.${i}.changed`,{source:o,action:t,ids:s})}const ET=new Set(["saved","no-editor","not-dirty","error"]);let Jm=0;function Qm(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function _T(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Jm+=1;const o=`os-editor-preview-${Date.now()}-${Jm}`;return new Promise(s=>{let i=null,r=!1;const a=c=>{r||(r=!0,window.removeEventListener("message",l),i!==null&&window.clearTimeout(i),s(c))},l=c=>{if(c.origin!==window.location.origin)return;const d=c?.data;if(!d||typeof d!="object"||d.type!=="os-editor-autosave-response"||d.requestId!==o)return;const u=typeof d.status=="string"&&ET.has(d.status)?d.status:"error",f=Qm(d.previewUrl);a(f?{status:u,previewUrl:f}:{status:u})};window.addEventListener("message",l),i=window.setTimeout(()=>a({status:"timeout"}),t);try{n.postMessage({type:"os-editor-autosave-request",requestId:o},window.location.origin)}catch{a({status:"no-editor"})}})}const We=ae("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),ST=400,eg=1500;function is(e){return e?`${e.type}:${e.id}`:""}function kT(e){for(const t of We.state.pairings.values())if(t.previewWindowId===e)return t}function IT(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function AT(e){const t=e.getCurrentUrl?.()??"";if(!t)return!1;try{return new URL(t,window.location.origin).pathname.endsWith("/post-new.php")}catch{return!1}}function Qi(e,t,n,o){We.state.pairings.delete(t.editorWindowId),t.reloadTimer!==null&&(window.clearTimeout(t.reloadTimer),t.reloadTimer=null);try{t.unsubscribe()}catch{}if(ng(e,t),o!=="none"){const i=e.getById(t.previewWindowId);i&&(o==="destroy"?i.destroy?.():i.close?.())}const s={editorWindowId:t.editorWindowId,previewWindowId:t.previewWindowId,reason:n};document.dispatchEvent(new CustomEvent("os-editor-preview-closed",{detail:s})),A(v.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function jc(e,t,n){t.reloadTimer!==null&&window.clearTimeout(t.reloadTimer),t.reloadTimer=window.setTimeout(()=>{t.reloadTimer=null;const o=e.getById(t.previewWindowId);if(!o)return;const s=n||ze(t.editorWindowId)?.previewUrl,i=s&&s!==t.openUrl?s:void 0;typeof o.swapReload=="function"?(i&&(t.openUrl=i),o.swapReload(i)):i&&o.navigateTo?(t.openUrl=i,o.navigateTo(i)):o.reload?.()},ST)}function CT(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=Zn(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(a=>String(a)===s)||jc(e,t)})}let tg=0;function ng(e,t){if(!t.watchId)return;const n=e.getById(t.editorWindowId);try{n?.iframe?.contentWindow?.postMessage({type:"os-editor-live-unwatch",watchId:t.watchId},window.location.origin)}catch{}t.watchId=""}function og(e,t,n){ng(e,t);const o=J(v.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:eg},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;tg+=1;const i=`${t.previewWindowId}-watch-${tg}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:eg},window.location.origin),t.watchId=i}catch{}}let LT=_T;async function TT(e,t){const n=We.state.pairings.get(t.id);if(n){Qi(e,n,"toggled","close");return}if(We.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=ze(t.id);if(!o?.previewUrl){ue({message:b("No preview is available for this content.")});return}We.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=IT();s||t.applySnap?.("left");const i=LT(t);i.then(f=>{f.status==="error"&&ue({message:b("Couldn't save your latest changes — the preview shows the last saved version.")})}).finally(()=>{We.state.busyEditors.delete(t.id),e.getById(t.id)?.renderCustomTitleBarButtons?.()});const r=`editor-preview-${String(o.type).replace(/\//g,"-")}-${o.id}`;let a=b("Preview");o.label&&(a=le(b("Preview: %s"),o.label));let l={id:r,baseId:r,url:o.previewUrl,title:a,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=J(v.EDITOR_PREVIEW_WINDOW_CONFIG,l,{editorWindowId:t.id,content:o});if(c&&typeof c=="object"&&typeof c.id=="string"&&c.id!==""&&typeof c.url=="string"&&c.url!==""?l=c:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await e.open(l),!e.getById(t.id)||is(ze(t.id))!==is(o)){e.getById(l.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:l.id,postKey:is(o),openUrl:l.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};CT(e,d,o),og(e,d,o),We.state.pairings.set(t.id,d);const u={editorWindowId:t.id,previewWindowId:l.id,content:o};document.dispatchEvent(new CustomEvent("os-editor-preview-opened",{detail:u})),A(v.EDITOR_PREVIEW_OPENED,u),i.then(f=>{We.state.pairings.get(t.id)===d&&f.status==="saved"&&jc(e,d,f.previewUrl)})}function NT({manager:e}){os({id:"desktop-mode/editor-preview",label:b("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!ze(t.id)?.previewUrl||AT(t)),render:(t,n)=>{if(!ze(n.id)?.previewUrl){const i=b("Save the post to enable its preview");t.setAttribute("aria-disabled","true"),t.setAttribute("aria-label",i),t.setAttribute("title",i),t.classList.add("os-window__btn--disabled"),t.addEventListener("click",r=>{r.stopPropagation(),ue({message:b("The preview opens once the post has been saved.")})});return}const o=We.state.pairings.has(n.id),s=We.state.busyEditors.has(n.id);t.setAttribute("aria-pressed",String(o)),s&&(t.setAttribute("aria-busy","true"),t.classList.add("os-window__btn--busy")),t.addEventListener("click",i=>{i.stopPropagation(),TT(e,n)})}}),ee(v.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=We.state.pairings.get(t.windowId);n&&is(t.content)!==n.postKey&&Qi(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),ee(v.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=We.state.pairings.get(t.windowId);if(n){Qi(e,n,"editor-closed","destroy");return}const o=kT(t.windowId);o&&Qi(e,o,"preview-closed","none")}),ee(v.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=We.state.pairings.get(t.windowId);if(n){const o=ze(t.windowId);o&&is(o)===n.postKey&&og(e,n,o)}e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t?.data;if(!(!n||typeof n!="object"||n.type!=="os-editor-live-saved"||typeof n.watchId!="string")){for(const o of We.state.pairings.values())if(o.watchId&&o.watchId===n.watchId){jc(e,o,Qm(n.previewUrl));return}}})}const sg=16,Ve=16,OT=1100,DT=860;function RT(e,t){const n=Math.max(0,t.width-Ve*2),o=Math.max(320,Math.min(OT,Math.round(n*.5))),s=Math.max(200,Math.min(DT,Math.round(t.height*.8))),i=xT(e.y,Ve,Math.max(Ve,t.height-s-Ve)),r=e.x+e.width+sg;if(r+o+Ve<=t.width)return{x:r,y:i,width:o,height:s};const a=e.x-sg-o;if(a>=Ve)return{x:a,y:i,width:o,height:s};const l=e.x+e.width/2,c=e.y+e.height/2,d=l<=t.width/2,u=c<=t.height/2;return{x:d?Math.max(Ve,t.width-o-Ve):Ve,y:u?Math.max(Ve,t.height-s-Ve):Ve,width:o,height:s}}function xT(e,t,n){return Math.min(Math.max(e,t),n)}function MT(e){return`revisions-${String(e.type).replace(/\//g,"-")}-${e.id}`}function WT(e){const t=e?.revisionCount;return typeof t=="number"&&t>0?le(b("View revisions (%d)"),t):b("View revisions")}function PT(e,t,n){if(Li(n))return{};if(typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches)return{};const o=e.getById(t)?.element,s=document.getElementById("os-area");return!o||!s||o.offsetParent===null||o.offsetWidth===0?{}:RT({x:o.offsetLeft,y:o.offsetTop,width:o.offsetWidth,height:o.offsetHeight},{width:s.clientWidth,height:s.clientHeight})}async function $T(e,t){const n=ze(t.id);if(!n?.revisionsUrl){ue({message:b("No revisions are available for this content.")});return}const o=MT(n);let s=b("Revisions");n.label&&(s=le(b("Revisions: %s"),n.label));let i={id:o,baseId:o,url:n.revisionsUrl,title:s,icon:"dashicons-backup",content:{type:"revisions",id:n.id,root:{type:n.type,id:n.id},label:s},...PT(e,t.id,o)};const r=J(v.REVISIONS_WINDOW_CONFIG,i,{editorWindowId:t.id,content:n});r&&typeof r=="object"&&typeof r.id=="string"&&r.id!==""&&typeof r.url=="string"&&r.url!==""?i=r:typeof console<"u"&&console.warn("[openstation] `os.revisions.window-config` filter returned an invalid config; using the default."),await e.open(i);const a={editorWindowId:t.id,revisionsWindowId:i.id,content:n};document.dispatchEvent(new CustomEvent("os-revisions-opened",{detail:a})),A(v.REVISIONS_OPENED,a)}function UT({manager:e}){jm({id:"desktop-mode/view-revisions",label:t=>WT(ze(t.id)),icon:"dashicons-backup",order:60,isVisible:t=>!!ze(t.id)?.revisionsUrl,onSelect:t=>{$T(e,t)}})}const ig="none",rg=ae("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),rs=rg.state.registry,Vc=rg.state.listeners,ag=/^[a-z0-9_/-]+$/;function er(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):ag.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===ig&&t.push('id ("none" is reserved)'):t.push(`id (must match ${ag} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.className!="string"&&typeof e.apply!="function"&&t.push("className|apply (at least one must be provided — a CSS class to toggle or an apply callback)")),Oe("UnfocusEffect",t,e);const n=e.id.trim().toLowerCase();rs.set(n,{...e,id:n}),qc()}function BT(e){rs.delete(e.toLowerCase())&&qc()}function FT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(rs.entries()))o.owner===e&&(rs.delete(n),t++);return t>0&&qc(),t}function Kc(){const e=Array.from(rs.values()),t=J(v.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function cg(e){return Kc().find(t=>t.id===e)}function HT(e){return Vc.add(e),()=>{Vc.delete(e)}}function qc(){const e=Array.from(Vc);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}er({id:"darken",label:b("Darken"),description:b("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),er({id:"frost",label:b("Frost"),description:b("Throw unfocused windows out of focus — a soft, frosted-glass blur, as if you were looking at them through an iced-over pane."),className:"os-window--fx-frost"}),er({id:"grayscale",label:b("Grayscale"),description:b("Drain the colour from unfocused windows so the focused one is the only thing still in colour — your eye snaps right to it."),className:"os-window--fx-grayscale"});function GT(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"unfocus-effect-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(FT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const zT="none",lg=ae("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),as=lg.state.registry,jT=lg.state.listeners,dg=/^[a-z0-9_/-]+$/;function ug(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):dg.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===zT&&t.push('id ("none" is reserved)'):t.push(`id (must match ${dg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.mount!="function"&&t.push("mount (not a function)")),Oe("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();as.set(n,{...e,id:n}),Xc()}function VT(e){as.delete(e.toLowerCase())&&Xc()}function KT(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(as.entries()))o.owner===e&&(as.delete(n),t++);return t>0&&Xc(),t}function Yc(){const e=Array.from(as.values()),t=J(v.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function Xc(){const e=Array.from(jT);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}function qT(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"window-link-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(KT(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}let an=null;function fg(){if(an)return an;if(window.openStationWindowLinkVisuals)return an=Promise.resolve(!0),an;const t=window.openStationConfig?.windowLinkVisualsBundleUrl;return t?(an=pe(t).then(()=>!0).catch(n=>{throw an=null,n}),an):Promise.resolve(!1)}const Zc="svg-splines";function YT(){if(Yc().some(t=>t.id===Zc))return;const e=async t=>{if(!await fg())return;const o=Yc().find(s=>s.id===Zc);if(!(!o||o.mount===e))return o.mount(t)};ug({id:Zc,label:b("Splines"),description:b("Curved connectors between related windows, ending in circular dots — the larger dot sits on the window the content belongs to; windows that reference each other get large dots on both ends."),mount:e})}const Jc="data-desktop-unfocus-effect",Qc="data-desktop-unfocus-effect-class";let pg=!1;function XT(e){return e.querySelector("canvas")!==null}function ZT(e){return e.state==="snapped-left"||e.state==="snapped-right"}function JT({manager:e,osSettings:t}){if(pg)return;pg=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,a)=>{const l=r.getAttribute(Qc);l&&(r.classList.remove(l),r.removeAttribute(Qc));const c=r.getAttribute(Jc);c&&cg(c)?.clear?.(r);for(const d of a)d.className&&r.classList.remove(d.className);r.removeAttribute(Jc)},s=(r,a)=>{a.className&&(r.classList.add(a.className),r.setAttribute(Qc,a.className)),r.setAttribute(Jc,a.id),a.apply?.(r)},i=()=>{const r=n===ig?void 0:cg(n),a=Kc();for(const l of e.getAll()){const c=l.element;c&&(o(c,a),!(!r||l.isFocused()||l.state==="minimized")&&(ZT(l)||XT(c)||s(c,r)))}};for(const r of["os-window-opened","os-window-reopened","os-window-closed","os-window-focused","os-window-blurred"])document.addEventListener(r,()=>i());document.addEventListener("os-window-changed",r=>{r.detail?.reason==="state"&&i()}),t.subscribeOsSettings(r=>{n=r.unfocusEffect,i()}),HT(()=>i()),i()}function QT(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await pe(o.scriptUrl,{translations:o.scriptTranslations,deps:o.scriptDeps,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){A(v.SHELL_ERROR,{scope:"dock-rail-renderer-script-load",handle:o.handle,url:o.scriptUrl,error:s});return}t.add(o.scriptUrl),e.add(o.handle)};return async o=>{const s=new Set;for(const i of o)i.handle&&s.add(i.handle);for(const i of Array.from(e))s.has(i)||(C_(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function eN(e){if(!e.bundleUrl)return()=>{};let t=!1;const n=o=>{const s=o.target;t||!(s instanceof Element)||!s.closest(".os-dock")||(t=!0,pe(e.bundleUrl).then(()=>{document.removeEventListener("pointerover",n,!0),document.removeEventListener("focusin",n,!0),window.openStationDockConstellation?.mount(e.deps)}).catch(()=>{t=!1}))};return document.addEventListener("pointerover",n,!0),document.addEventListener("focusin",n,!0),()=>{document.removeEventListener("pointerover",n,!0),document.removeEventListener("focusin",n,!0)}}const hg=ae("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),cs=hg.state.registry,tN=hg.state.listeners,mg=/^[a-z0-9_/-]+$/;function gg(e){const t=[];if(!e||typeof e!="object")t.push("def (not an object)");else{if(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):mg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${mg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),!e.tokens||typeof e.tokens!="object")t.push("tokens (must be an object of CSS custom-property → value)");else for(const o of Object.keys(e.tokens))if(!o.startsWith("--")){t.push(`tokens.${o} (CSS custom-property keys must start with "--")`);break}typeof e.match!="function"&&t.push("match (must be a function)")}Oe("WindowTheme",t,e);const n=e.id.trim().toLowerCase();cs.set(n,{...e,id:n}),el()}function wg(e){cs.delete(e.toLowerCase())&&el()}function nN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(cs.entries()))o.owner===e&&(cs.delete(n),t++);return t>0&&el(),t}function yg(){return Array.from(cs.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function el(){const e=Array.from(tN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function oN(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async l=>{if(!l.scriptUrl||t.has(l.scriptUrl)){e.add(l.handle);return}try{await pe(l.scriptUrl,{translations:l.scriptTranslations,deps:l.scriptDeps,l10n:l.scriptL10n,before:l.scriptBefore,after:l.scriptAfter})}catch(c){A(v.SHELL_ERROR,{scope:"window-theme-script-load",handle:l.handle,url:l.scriptUrl,error:c});return}t.add(l.scriptUrl),e.add(l.handle)},i=l=>{const c=new Map;if(!l)return c;for(const d of l){if(!d.scriptHandle||!d.id)continue;let u=c.get(d.scriptHandle);u||(u=new Set,c.set(d.scriptHandle,u)),u.add(d.id)}return c},r=l=>{const c=new Set;for(const u of yg())u.owner===l&&c.add(u.id);const d=n.get(l);if(d)for(const u of d)c.add(u);return c},a=l=>{if(l){for(const c of l)if(!(!c.id||!c.tokens))try{gg({id:c.id,label:c.label,tokens:c.tokens,priority:c.priority,match:()=>!0,owner:c.scriptHandle||void 0}),o.add(c.id)}catch(d){A(v.SHELL_ERROR,{scope:"window-theme-shell-register",id:c.id,error:d})}}};return async(l,c)=>{const d=new Set;for(const u of l)u.handle&&d.add(u.handle);for(const u of Array.from(e)){if(d.has(u))continue;const f=r(u);for(const p of f)wg(p),o.delete(p);nN(u),e.delete(u)}a(c);for(const u of l)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const vg=ae("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),ls=vg.state.registry,sN=vg.state.listeners,bg=/^[a-z0-9_/-]+$/;function ds(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):bg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${bg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.onClick!="function"&&typeof e.render!="function"&&t.push("onClick|render (at least one must be a function)"),typeof e.render!="function"&&(typeof e.icon!="string"||e.icon.trim()==="")&&t.push("icon (required when render is omitted)"),typeof e.match!="function"&&t.push("match (must be a function)"),e.placement!==void 0&&e.placement!=="left"&&e.placement!=="right"&&e.placement!=="controls"&&t.push('placement (must be "left", "right", or "controls")')),Oe("WindowControl",t,e);const n=e.id.trim().toLowerCase();ls.set(n,{...e,id:n}),tl()}function Eg(e){ls.delete(e.toLowerCase())&&tl()}function iN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ls.entries()))o.owner===e&&(ls.delete(n),t++);return t>0&&tl(),t}function _g(){return Array.from(ls.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function tl(){const e=Array.from(sN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function rN(){ds({id:"core/minimize",label:b("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),ds({id:"core/maximize",label:b("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),ds({id:"core/focus-tab",label:b("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),ds({id:"core/close",label:b("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function aN(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of _g())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))Eg(d);iN(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const Sg=ae("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),us=Sg.state.registry,cN=Sg.state.listeners,kg=/^[a-z0-9_/-]+$/,Ig=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Ag(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):kg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${kg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):Ig.has(e.slot)||t.push(`slot (must be one of ${Array.from(Ig).join(", ")})`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Oe("WindowSlot",t,e);const n=e.id.trim().toLowerCase();us.set(n,{...e,id:n}),ol()}function nl(e){us.delete(e.toLowerCase())&&ol()}function lN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(us.entries()))o.owner===e&&(us.delete(n),t++);return t>0&&ol(),t}function Cg(){return Array.from(us.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function ol(){const e=Array.from(cN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function dN(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of Cg())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))nl(d);lN(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const uN="desktop-mode-notice-dismissed";function fN(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function Lg(){return`${uN}:${fN()}`}function sl(){try{const e=window.localStorage.getItem(Lg());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function Tg(e){try{window.localStorage.setItem(Lg(),JSON.stringify(e))}catch{}}function tr(e){return e?sl()[e]===!0:!1}function nr(e){if(!e)return;const t=sl();t[e]=!0,Tg(t)}function Ng(e){if(!e)return;const t=sl();t[e]&&(delete t[e],Tg(t))}const pN=Le`:host{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:10px 14px;font:var( --os-ui-notice-font,13px/1.5 var( --os-font,system-ui ) );color:var( --os-ui-notice-color,var( --os-ui-fg,#1d2327 ) );background:var( --os-ui-notice-bg,var( --os-ui-hover,rgba( 0,0,0,0.04 ) ) );border-block-end:1px solid var( --os-ui-notice-border,var( --os-ui-border,rgba( 0,0,0,0.08 ) ) );border-inline-start:4px solid var( --os-ui-notice-accent,var( --os-ui-border,#646970 ) )}:host( [ hidden ] ){display:none}.os-notice__icon{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:var( --os-ui-notice-accent,var( --os-ui-accent,#646970 ) )}.os-notice__icon[ hidden ]{display:none}.os-notice__label{flex:1;min-width:0;word-wrap:break-word}::slotted( a ){color:var( --os-ui-notice-link,var( --wp-admin-theme-color,#2271b1 ) );border-radius:2px}::slotted( a:hover ),::slotted( a:focus-visible ){color:var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) )}::slotted( a:focus-visible ){outline:2px solid var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) );outline-offset:2px}::slotted( p:first-child ){margin-block-start:0}::slotted( p:last-child ){margin-block-end:0}.os-notice__close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;background:transparent;color:inherit;opacity:0.6;cursor:pointer;border-radius:4px;transition:opacity 0.12s ease,background-color 0.12s ease}.os-notice__close:hover{opacity:1;background:var( --os-ui-hover,rgba( 0,0,0,0.06 ) )}.os-notice__close:focus-visible{opacity:1;outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:1px}.os-notice__close[ hidden ]{display:none}.os-notice__close svg{width:14px;height:14px}:host( [ tone='info' ] ){--os-ui-notice-accent:var( --os-ui-notice-info,var( --os-ui-info-fg,#0969da ) );--os-ui-notice-bg:var( --os-ui-notice-info-bg,rgba( 9,105,218,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-info-border,rgba( 9,105,218,0.16 ) )}:host( [ tone='success' ] ){--os-ui-notice-accent:var( --os-ui-notice-success,var( --os-ui-success-fg,#1a7f37 ) );--os-ui-notice-bg:var( --os-ui-notice-success-bg,rgba( 26,127,55,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-success-border,rgba( 26,127,55,0.16 ) )}:host( [ tone='warning' ] ){--os-ui-notice-accent:var( --os-ui-notice-warning,var( --os-ui-warning-fg,#9a6700 ) );--os-ui-notice-bg:var( --os-ui-notice-warning-bg,rgba( 154,103,0,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-warning-border,rgba( 154,103,0,0.16 ) )}:host( [ tone='error' ] ),:host( [ tone='danger' ] ){--os-ui-notice-accent:var( --os-ui-notice-error,var( --os-ui-danger,#cf222e ) );--os-ui-notice-bg:var( --os-ui-notice-error-bg,rgba( 207,34,46,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-error-border,rgba( 207,34,46,0.16 ) )}:host( [ tone='neutral' ] ){--os-ui-notice-accent:var( --os-ui-notice-neutral,var( --os-ui-fg-muted,#57606a ) );--os-ui-notice-bg:var( --os-ui-notice-neutral-bg,rgba( 87,96,106,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-neutral-border,rgba( 87,96,106,0.16 ) )}`,Js=class Js extends sn{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&tr(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&nr(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&Ng(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return jn` | |
| 18 | + <span | |
| 19 | + class="os-notice__icon dashicons ${t??""}" | |
| 123 | 20 | ?hidden=${!t} |
| 124 | - @click=${o=>this._onAction(o)} | |
| 125 | - > | |
| 126 | - ${t} | |
| 127 | - </button> | |
| 21 | + aria-hidden="true" | |
| 22 | + ></span> | |
| 23 | + <span class="os-notice__label"><slot></slot></span> | |
| 128 | 24 | <button |
| 129 | 25 | type="button" |
| 130 | - class="os-toast__close" | |
| 131 | - aria-label=${E("Dismiss")} | |
| 26 | + class="os-notice__close" | |
| 132 | 27 | ?hidden=${!n} |
| 28 | + aria-label=${b("Dismiss notice")} | |
| 133 | 29 | @click=${o=>this._onDismiss(o)} |
| 134 | 30 | > |
| 135 | - ${xr("close",{size:16})} | |
| 31 | + ${wu("close",{size:null})} | |
| 136 | 32 | </button> |
| 137 | - `}_onAction(t){t.preventDefault(),t.stopPropagation(),this.emit("os-toast-action",{})}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.emit("os-toast-dismiss",{})}};Es.props=["action","state","dismissible"],Es.styles=[RD],Es.help={title:"Toast",summary:'Single transient notification. Message is slotted; fade-in / fade-out is CSS-driven by flipping the state attribute between "in" and "out". Usually created via the showToast() helper rather than authored by hand.',status:"stable",props:[{name:"action",type:"string",description:"Optional action button label. When set, a button renders on the right and emits os-toast-action on click."},{name:"state",type:"'in' | 'out'",description:'Drives the CSS fade transition. Set to "in" when rendered, flip to "out" before removal.'},{name:"dismissible",type:"boolean",description:"When set, a close (×) button renders on the right and emits os-toast-dismiss on click. Use for persistent toasts the user must be able to close."},{name:"held",type:"boolean (reflected, read-only)",description:"Set by the component while the pointer is over the toast or focus is inside it. showToast() pauses the auto-dismiss timer for as long as it is present. Do not set it by hand — pass `persistent` for a toast that should never expire."}],slots:[{name:"(default)",description:"Message text."}],events:[{name:"os-toast-action",description:"Fires when the action button is clicked.",detail:"{}"},{name:"os-toast-dismiss",description:"Fires when the close (×) button is clicked.",detail:"{}"},{name:"os-toast-hold",description:"Fires when the toast starts or stops being attended to — pointer over it, or focus inside it. showToast() pauses the auto-dismiss timer while held is true.",detail:"{ held: boolean }"}],example:J` | |
| 138 | - <os-toast state="in" action="Undo">Post moved to trash.</os-toast> | |
| 139 | - `};let Cc=Es;xe("os-toast",Cc);function hy(e,t){const n=document.createElement("os-segmented");n.setAttribute("value",e),n.setAttribute("label","Capability"),n.style.setProperty("--os-ui-segmented-bg","rgba(255,255,255,0.06)"),n.style.setProperty("--os-window-bg","var(--wp-admin-theme-color, #2271b1)"),n.style.setProperty("--os-ui-fg","#fff"),n.style.setProperty("--os-ui-fg-muted","rgba(255,255,255,0.65)");const o=document.createElement("os-segment");o.setAttribute("value","read"),o.textContent="Read",n.appendChild(o);const s=document.createElement("os-segment");return s.setAttribute("value","write"),s.textContent="Read + Write",n.appendChild(s),n.addEventListener("os-pick",i=>{const r=i.detail;t(r.value)}),n}function Ic(e,t,n={}){const o=document.createElement("os-button");o.setAttribute("variant","ghost"),o.setAttribute("aria-label",n.danger?"Remove":"Dismiss"),o.textContent=e;const s=n.danger?"#ff8080":"rgba(255,255,255,0.75)",i=n.danger?"1px solid rgba(255,128,128,0.45)":"1px solid rgba(255,255,255,0.18)";return o.style.setProperty("--os-ui-button-fg",s),o.style.setProperty("--os-ui-button-border",i),o.style.setProperty("--os-ui-button-padding","6px 12px"),o.style.setProperty("--os-ui-button-border-radius","7px"),o.style.setProperty("--os-ui-button-min-height","34px"),o.style.minWidth="34px",o.style.fontSize="18px",o.style.lineHeight="1",o.addEventListener("click",t),o}async function xc(e){const t=document.createElement("os-modal");t.setAttribute("open",""),t.setAttribute("size","lg"),t.setAttribute("title",`Share "${e.folderName}"`),document.body.appendChild(t);let n=[],o=[];const s=()=>{t.innerHTML="";const l=document.createElement("div");l.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",l.textContent=e.ownerName?`Owner: ${e.ownerName} — cannot be changed`:"Owner cannot be changed",t.appendChild(l);const c=document.createElement("div");c.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const d=document.createElement("div");d.textContent="Add people",d.style.cssText="font-weight:600;",c.appendChild(d);const u=document.createElement("os-user-search"),f=n.filter(k=>k.principalType==="user").map(k=>k.principalRef).concat(o.filter(k=>k.kind==="user").map(k=>k.ref));u.setAttribute("exclude",f.join(",")),u.setAttribute("placeholder","Search users…"),u.addEventListener("os-user-pick",k=>{const M=k.detail;o.push({kind:"user",ref:String(M.user.id),label:M.user.name,cap:"read"}),s()}),c.appendChild(u),t.appendChild(c);const p=document.createElement("div");p.style.cssText="display:flex;flex-direction:column;gap:6px;margin-bottom:14px;";const g=document.createElement("div");g.textContent="Add roles",g.style.cssText="font-weight:600;",p.appendChild(g);const m=document.createElement("os-role-picker"),h=n.filter(k=>k.principalType==="role").map(k=>k.principalRef),b=o.filter(k=>k.kind==="role").map(k=>k.ref);if(m.setAttribute("selected",[...h,...b].join(",")),m.addEventListener("os-role-toggle",k=>{const M=k.detail,P=n.find(W=>W.principalType==="role"&&W.principalRef===M.slug);if(P){M.selected||r(P);return}if(M.selected){const W=(window.openStationConfig?.shareEligibleRoles??[]).find(_=>_.slug===M.slug);o.push({kind:"role",ref:M.slug,label:W?W.name:M.slug,cap:"read"})}else o=o.filter(W=>!(W.kind==="role"&&W.ref===M.slug));s()}),p.appendChild(m),t.appendChild(p),o.length>0){const k=document.createElement("div");k.style.cssText="border:1px dashed rgba(255,255,255,0.18);border-radius:8px;padding:10px;margin-bottom:14px;";const M=document.createElement("div");M.textContent="New invites (not sent yet)",M.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",k.appendChild(M);for(const W of o){const _=document.createElement("div");_.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const w=document.createElement("span");w.textContent=W.kind==="role"?`Role: ${W.label}`:W.label,w.style.flex="1",_.appendChild(w);const L=hy(W.cap,C=>{W.cap=C});_.appendChild(L);const A=Ic("×",()=>{o=o.filter(C=>!(C.kind===W.kind&&C.ref===W.ref)),s()});_.appendChild(A),k.appendChild(_)}const P=document.createElement("os-button");P.setAttribute("variant","primary"),P.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,P.style.marginTop="8px",P.addEventListener("click",async()=>{if(o.length===0)return;P.setAttribute("busy",""),P.setAttribute("disabled","");const W=o.slice();let _=0,w=null;for(const L of W)try{await gw(e.folderId,{principalType:L.kind,principalRef:L.ref,capability:L.cap}),_++}catch(A){w=A;break}_>0&&(o=o.slice(_));try{await i()}catch{}Q(w?{message:`Could not send invites: ${w.message}`}:{message:_===1?"Invite sent.":`${_} invites sent.`}),P.removeAttribute("busy"),P.removeAttribute("disabled"),s()}),k.appendChild(P),t.appendChild(k)}const y=document.createElement("div");if(y.textContent="Who has access",y.style.cssText="font-weight:600;margin:8px 0 6px;",t.appendChild(y),n.length===0){const k=document.createElement("div");k.textContent="Only you can see this folder.",k.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(k)}else for(const k of n){const M=document.createElement("div");M.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const P=document.createElement("div");if(P.style.flex="1",P.textContent=k.principalType==="role"?`Role: ${k.displayName}`:k.displayName,k.state==="pending"){const L=document.createElement("span");L.textContent=" · pending",L.style.cssText="opacity:0.6;font-size:12px;",P.appendChild(L)}else if(k.state==="denied"){const L=document.createElement("span");L.textContent=" · denied",L.style.cssText="color:#d63638;font-size:12px;",P.appendChild(L)}M.appendChild(P);const W=k.capability==="write"?"write":"read",_=hy(W,L=>{a(k,L)});M.appendChild(_);const w=Ic("×",()=>{r(k)},{danger:!0});M.appendChild(w),t.appendChild(M)}const I=document.createElement("div");I.setAttribute("slot","footer"),I.style.display="flex",I.style.justifyContent="flex-end",I.style.gap="10px",I.style.flexWrap="wrap";const R=document.createElement("os-button");R.setAttribute("variant","secondary"),R.textContent="Done",R.addEventListener("click",()=>t.remove()),I.appendChild(R),t.appendChild(I)},i=async()=>{try{n=(await mw(e.folderId)).shares,SD(e.folderId,n)}catch(l){Q({message:`Could not load shares: ${l.message}`})}s()},r=async l=>{try{await yw(e.folderId,l.id),CD(e.folderId,l.id),await i(),Q({message:"Access revoked."})}catch(c){Q({message:`Could not revoke: ${c.message}`})}},a=async(l,c)=>{try{const d=await ww(e.folderId,l.id,c);AD(d),await i()}catch(d){Q({message:`Could not update capability: ${d.message}`})}};t.addEventListener("os-modal-cancel",()=>t.remove()),s(),await i()}async function OD(e){const t=document.createElement("os-modal");t.setAttribute("open",""),t.setAttribute("size","md"),t.setAttribute("title",`Share "${e.fileName}"`),document.body.appendChild(t);let n=[];const o=async()=>{try{n=(await Ew(e.fileId)).shares}catch(i){Q({message:`Could not load shares: ${i.message}`})}s()},s=()=>{t.innerHTML="";const i=document.createElement("div");i.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",i.textContent="People you share with can view and download this file. Only you can move, rename, or delete it.",t.appendChild(i);const r=document.createElement("div");r.textContent="Add people",r.style.cssText="font-weight:600;margin-bottom:6px;",t.appendChild(r);const a=document.createElement("os-user-search");a.setAttribute("exclude",n.map(u=>u.principalRef).join(",")),a.setAttribute("placeholder","Search users…"),a.addEventListener("os-user-pick",u=>{const f=u.detail;(async()=>{try{await kw(e.fileId,f.user.id),Q({message:`Invite sent to ${f.user.name}.`})}catch(p){Q({message:`Could not invite: ${p.message}`})}await o()})()}),t.appendChild(a);const l=document.createElement("div");if(l.textContent="Who has access",l.style.cssText="font-weight:600;margin:14px 0 6px;",t.appendChild(l),n.length===0){const u=document.createElement("div");u.textContent="Only you can see this file.",u.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(u)}else for(const u of n){const f=document.createElement("div");f.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const p=document.createElement("div");p.style.flex="1";const g=u.displayName;if(p.textContent=g||`User #${u.principalRef}`,u.state==="pending"){const b=document.createElement("span");b.textContent=" · pending",b.style.cssText="opacity:0.6;font-size:12px;",p.appendChild(b)}else if(u.state==="denied"){const b=document.createElement("span");b.textContent=" · denied",b.style.cssText="color:#d63638;font-size:12px;",p.appendChild(b)}f.appendChild(p);const m=document.createElement("span");m.textContent="Read + download",m.style.cssText="opacity:0.6;font-size:12px;",f.appendChild(m);const h=Ic("×",()=>{(async()=>{try{await Sw(e.fileId,u.id),Q({message:"Access revoked."})}catch(b){Q({message:`Could not revoke: ${b.message}`})}await o()})()},{danger:!0});f.appendChild(h),t.appendChild(f)}const c=document.createElement("div");c.setAttribute("slot","footer"),c.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;";const d=document.createElement("os-button");d.setAttribute("variant","secondary"),d.textContent="Done",d.addEventListener("click",()=>t.remove()),c.appendChild(d),t.appendChild(c)};t.addEventListener("os-modal-cancel",()=>t.remove()),s(),await o()}function my(e){return new Promise(t=>{const n=document.createElement("os-modal");n.setAttribute("open",""),n.setAttribute("title",e.fileName?`${e.ownerName??"Someone"} shared "${e.fileName}" with you`:"File shared with you");const o=document.createElement("div");o.innerHTML=` | |
| 140 | - <p style="margin: 0 0 12px;">Accept the invite to add this file to your desktop.</p> | |
| 141 | - <p style="margin: 0; opacity: 0.75;">Access level: <strong>Read + download</strong></p> | |
| 142 | - `,n.appendChild(o);const s=document.createElement("div");s.setAttribute("slot","footer"),s.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;";const i=document.createElement("os-button");i.setAttribute("variant","secondary"),i.textContent="Decide later",i.addEventListener("click",()=>{n.remove(),t("dismissed")});const r=document.createElement("os-button");r.setAttribute("variant","danger"),r.textContent="Deny",r.addEventListener("click",async()=>{r.setAttribute("busy",""),r.setAttribute("disabled","");try{await Cw(e.fileId,e.id),Qe().state.deniedFiles.add(e.fileId),Qe().notify(),n.remove(),t("denied")}catch(l){Q({message:`Could not deny: ${l.message}`}),r.removeAttribute("busy"),r.removeAttribute("disabled")}});const a=document.createElement("os-button");a.setAttribute("variant","primary"),a.textContent="Accept",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await Aw(e.fileId,e.id);try{const l=await Te(0);ht(0,l.placements)}catch{}n.remove(),t("accepted")}catch(l){Q({message:`Could not accept: ${l.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}}),s.appendChild(i),s.appendChild(r),s.appendChild(a),n.appendChild(s),n.addEventListener("os-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}function gy(e){return new Promise(t=>{const n=document.createElement("os-modal");n.setAttribute("open",""),n.setAttribute("title",e.folderName?`${e.ownerName??"Someone"} shared "${e.folderName}" with you`:"Folder shared with you");const o=document.createElement("div"),s=e.capability==="write"?"Read + Write":"Read";o.innerHTML=` | |
| 143 | - <p style="margin: 0 0 12px;">Accept the invite to add this folder to your desktop.</p> | |
| 144 | - <p style="margin: 0; opacity: 0.75;">Access level: <strong>${s}</strong></p> | |
| 145 | - `,n.appendChild(o);const i=document.createElement("div");i.setAttribute("slot","footer"),i.style.display="flex",i.style.justifyContent="flex-end",i.style.gap="10px",i.style.flexWrap="wrap";const r=document.createElement("os-button");r.setAttribute("variant","secondary"),r.textContent="Decide later",r.addEventListener("click",()=>{n.remove(),t("dismissed")});const a=document.createElement("os-button");a.setAttribute("variant","danger"),a.textContent="Deny",a.addEventListener("click",async()=>{a.setAttribute("busy",""),a.setAttribute("disabled","");try{await vw(e.folderId,e.id),Qe().state.deniedFolders.add(e.folderId),Qe().notify(),n.remove(),t("denied")}catch(c){Q({message:`Could not deny: ${c.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}});const l=document.createElement("os-button");l.setAttribute("variant","primary"),l.textContent="Accept",l.addEventListener("click",async()=>{l.setAttribute("busy",""),l.setAttribute("disabled","");try{await bw(e.folderId,e.id);try{const c=await Te(0);ht(0,c.placements)}catch{}n.remove(),t("accepted")}catch(c){Q({message:`Could not accept: ${c.message}`}),l.removeAttribute("busy"),l.removeAttribute("disabled")}}),i.appendChild(r),i.appendChild(a),i.appendChild(l),n.appendChild(i),n.addEventListener("os-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}const MD=Object.freeze(Object.defineProperty({__proto__:null,openFileShareModal:OD,openPendingFileInviteModal:my,openPendingInviteModal:gy,openShareSettingsModal:xc},Symbol.toStringTag,{value:"Module"}));function wy(){return Number(window.openStationConfig?.currentUserId??0)}function PD(e){window.wp?.os?.windowManager?.getById?.(e)?.close?.()}function Lc(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function yy(e){const t=xt().folders.get(e);return t?Number(t.ownerId):0}function by(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function WD(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function $D(e){return Number(e.file.ownerId??0)}function UD(){Xn("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!Lc())return e;const n=WD(t);if(n===null)return e;const o=yy(n)||$D(t),s=wy();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:()=>{xc({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 Pn({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 _w(n),jo(t.id);try{const a=await Te(0);ht(0,a.placements)}catch{}const r=`os-folder-${n}`;PD(r),Q({message:"You left the shared folder."})}catch(r){Q({message:`Could not leave: ${r.message}`})}}});return e}),vi({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!Lc())return!1;const t=e.config.baseId??e.id,n=by(t);return n===null?!1:yy(n)===wy()},onClick:e=>{if(!Lc())return;const t=e.config.baseId??e.id,n=by(t);n!==null&&xc({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),Y("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)})}const vy=new Set;function FD(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function BD(){const e=Qe(),t=n=>{if(FD()){for(const o of n.pending)if(!vy.has(o.id)){if(vy.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;my({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?lr(o.id):i==="denied"&&lr(o.id,{denied:!0,fileId:s})});continue}gy({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?lr(o.id):s==="denied"&&lr(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function HD(){return Number(window.openStationConfig?.currentUserId??0)}function _y(){return window.openStationConfig?.desktopStorage??{}}function zD(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function GD(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function jD(){Xn("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&_y().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:()=>{sr(Lw(i))}}),e}const n=GD(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{sr(qt(n))}});const o=Number(t.file.ownerId??0),s=HD();return o===s&&zD()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{Promise.resolve().then(()=>MD).then(i=>{i.openFileShareModal({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 Pn({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 Iw(n),jo(t.id);try{const r=await Te(0);ht(0,r.placements)}catch{}Q({message:"You left the shared file."})}catch(r){Q({message:`Could not leave: ${r.message}`})}}}),e}),Xn("os.wallpaper-context-menu","desktop-mode/uploads",e=>(_y().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>Ey(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>Ey(!0)})),e))}function Ey(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&&VD(n,e)}),t.click()}async function VD(e,t){const n=window.openStationConfig,o=n?.dropConfig??{enabled:!1,allowedMimes:[],maxSize:0},s=await Promise.resolve().then(()=>EM),{accepted:i,rejected:r}=s.partitionByPolicy(e,o);if(r.length>0&&Q({message:r.length===1?r[0].message:`${r.length} files can't be uploaded.`}),i.length===0)return;const a=i.map(({file:c,mime:d})=>({file:c,mime:d,fields:s.defaultFields(c,d),relativePath:t?c.webkitRelativePath??"":""}));await(await Promise.resolve().then(()=>Tb)).openUploadDialog({entries:a,context:{surface:"folder",folderId:0,x:0,y:0},mediaUrl:n?.mediaUrl??"",restNonce:n?.restNonce??"",filesUrl:n?.filesUrl,storage:n?.desktopStorage,forceDesktop:t,preferDesktop:!0,mediaMaxBytes:o.maxSize})}$T(),yD(),hD(),vD(),kD(),UD(),jD();const Tc=window.openStationConfig?.serverPendingShares;Array.isArray(Tc)&&Tc.length>0&&py(Tc),BD();const ze={DesktopFile:ew,registerType:Ve,unregisterType:TT,getType:NT,getTypes:tw,resolve:It,subscribe:DT,registerOpener:Be,unregisterOpener:RT,getOpener:OT,getOpeners:sw,getOpenersForType:Xl,resolveOpener:Zl,subscribeOpeners:MT,getUserAssociations:Yl,open:Ho,registerTilePayloadHandler:Ki,rest:YT,store:{get:Ze,getState:xt,subscribe:ac,setFolderPlacements:ht,upsertPlacement:Vi,removePlacement:jo,setFolders:qi,upsertFolder:ic,removeFolder:rc}},ky="__synthFromDockItem";function qD(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function KD(e,t){const n=!!e.tile,o=t[e.id];return{id:qD(e.id),parentId:0,x:o?o.x:0,y:o?o.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[ky]: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 Nc=!1;const Dc=new Map;function YD(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 XD(e,t,n={}){if(!Nc){Nc=!0;try{const s=ze.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[ky]:null;typeof u=="string"&&r.set(u,d)}const a=new Set;for(const d of t)d.entry&&a.add(d.entry.id);const l=new Map;for(const d of s){const u=d?.file?.ref;typeof u=="string"&&a.has(u)&&l.set(u,d)}for(const d of e)d.entry||r.has(d.id)||ze.store.upsertPlacement(KD(d,n));const c=[];for(const[d,u]of r)i.has(d)||(ze.store.removePlacement(u.id),n[d]&&c.push(d));c.length>0&&YD(c);for(const d of t){const u=d.entry;if(!u)continue;const f=l.get(u.id);if(!i.has(d.id)){f&&(Dc.set(u.id,f),ze.store.removePlacement(f.id));continue}if(!f){const p=Dc.get(u.id);p&&(ze.store.upsertPlacement(p),Dc.delete(u.id))}}}finally{Nc=!1}}}function ZD(e){queueMicrotask(e);const t=ze.store.subscribe(e),n="desktop-mode/shortcuts-sync";return Y(v.DOCK_ITEM_APPENDED,n,e),()=>{t(),kr(v.DOCK_ITEM_APPENDED,n)}}const JD=ue`:host{display:inline-flex;position:relative;width:var( --os-ui-avatar-size,32px );height:var( --os-ui-avatar-size,32px );flex:0 0 auto;vertical-align:middle;line-height:0;perspective:calc( var( --os-ui-avatar-size,32px ) * 8 );--os-ui-avatar-tilt-x:0deg;--os-ui-avatar-tilt-y:0deg;--os-ui-avatar-hover:0;--os-ui-avatar-glare-x:50%;--os-ui-avatar-glare-y:50%}:host( [ hidden ] ){display:none}.os-avatar__tile{position:relative;width:100%;height:100%;border-radius:50%;overflow:hidden;background:var( --os-window-bg,#f0f0f1 );color:var( --os-ui-fg-on-accent,#fff );display:flex;align-items:center;justify-content:center;font-weight:700;font-size:calc( var( --os-ui-avatar-size,32px ) * 0.48 );line-height:1;letter-spacing:0;font-feature-settings:'tnum' 1;user-select:none;transform-style:preserve-3d;transform:rotateX( var( --os-ui-avatar-tilt-x ) ) rotateY( var( --os-ui-avatar-tilt-y ) ) scale( calc( 1 + var( --os-ui-avatar-hover ) * 0.07 ) );transition:transform 220ms cubic-bezier( 0.2,0.8,0.2,1 ),box-shadow 220ms cubic-bezier( 0.2,0.8,0.2,1 );box-shadow:inset 0 0 0 1px rgba( 255,255,255,calc( 0.18 + 0.22 * var( --os-ui-avatar-hover ) ) ),inset 0 0 0 calc( 1px + var( --os-ui-avatar-hover ) * 1px ) rgba( 0,0,0,calc( 0.08 + 0.04 * var( --os-ui-avatar-hover ) ) ),0 calc( 1px + var( --os-ui-avatar-hover ) * 8px ) calc( 6px + var( --os-ui-avatar-hover ) * 18px ) rgba( 0,0,0,calc( 0.08 + 0.18 * var( --os-ui-avatar-hover ) ) )}.os-avatar__tile::after{content:'';position:absolute;inset:0;border-radius:50%;background:radial-gradient( circle at var( --os-ui-avatar-glare-x ) var( --os-ui-avatar-glare-y ),var( --os-ui-scrim,rgba( 255,255,255,0.55 ) ) 0%,var( --os-ui-hover,rgba( 255,255,255,0 ) ) 55% );opacity:var( --os-ui-avatar-hover );mix-blend-mode:overlay;pointer-events:none;transition:opacity 220ms cubic-bezier( 0.2,0.8,0.2,1 )}.os-avatar__tile::before{content:'';position:absolute;inset:calc( var( --os-ui-avatar-hover ) * -3px );border-radius:50%;background:radial-gradient( circle at var( --os-ui-avatar-glare-x ) var( --os-ui-avatar-glare-y ),color-mix( in srgb,var( --os-ui-avatar-halo,rgb( 99,102,241 ) ) calc( 35% * var( --os-ui-avatar-hover ) ),transparent ) 0%,transparent 70% );filter:blur( 4px );pointer-events:none;z-index:-1;transition:inset 220ms cubic-bezier( 0.2,0.8,0.2,1 ),background 220ms}.os-avatar__tile img{width:calc( 100% + 2px );height:calc( 100% + 2px );margin:-1px;object-fit:cover;display:block;transform:translateZ( 1px )}.os-avatar__dot{position:absolute;bottom:0;inset-inline-end:0;width:calc( var( --os-ui-avatar-size,32px ) * 0.32 );height:calc( var( --os-ui-avatar-size,32px ) * 0.32 );min-width:8px;min-height:8px;border-radius:50%;box-sizing:border-box;border:2px solid var( --os-ui-avatar-dot-ring,var( --os-window-bg,#fff ) );background:var( --os-ui-avatar-dot-color,transparent );z-index:2}.os-avatar__dot--online{background:var( --os-ui-success-fg,#00a32a )}.os-avatar__dot--online::after{content:'';position:absolute;inset:-2px;border-radius:50%;border:1px solid var( --os-ui-success-fg,#00a32a );animation:os-avatar-presence 6s var( --os-ui-ease-out,cubic-bezier( 0.22,0.9,0.28,1 ) ) infinite;pointer-events:none}@keyframes os-avatar-presence{0%{opacity:0.6;transform:scale( 1 )}20%{opacity:0;transform:scale( 2.2 )}100%{opacity:0;transform:scale( 2.2 )}}.os-avatar__dot--inactive{background:var( --os-ui-warning-fg,#dba617 )}.os-avatar__dot--offline{background:var( --os-ui-fg-muted,#8c8f94 )}@media ( prefers-reduced-motion:reduce ){.os-avatar__dot--online::after{animation:none;opacity:0.6}.os-avatar__tile{transform:none;transition:box-shadow 200ms}.os-avatar__tile::after,.os-avatar__tile::before{display:none}}`,Sy={xs:20,sm:24,md:40,lg:64,xl:96},Ay=new Set(["online","inactive","offline"]),ks=class ks extends Se{constructor(){super(...arguments),this._presenceHandler=null,this._imgFailed=!1,this._onPointerMove=null,this._onPointerEnter=null,this._onPointerLeave=null,this._tiltRaf=0,this._pendingTiltX="0deg",this._pendingTiltY="0deg",this._pendingGlareX="50%",this._pendingGlareY="50%"}connectedCallback(){super.connectedCallback(),this._maybeAttachPresenceListener(),this._attachHoverEffect()}disconnectedCallback(){this._presenceHandler&&(document.removeEventListener("os-presence-changed",this._presenceHandler),this._presenceHandler=null),this._detachHoverEffect()}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),t==="src"&&(this._imgFailed=!1),(t==="user-id"||t==="presence")&&this._maybeAttachPresenceListener()}render(){const t=this._attr("src"),n=this._attr("name")||"",o=this._attr("alt"),s=o!==null?o:n,i=this._attr("size"),r=this._resolveSize(i),a=this._presenceForRender(),l=this._attr("clickable")!==null;this.style.setProperty("--os-ui-avatar-size",`${r}px`);const c=t&&!this._imgFailed?"":this._initialsBg(n),d=t&&!this._imgFailed?J`<img | |
| 146 | - src=${t} | |
| 147 | - alt=${s} | |
| 148 | - @error=${()=>this._onImgError()} | |
| 149 | - loading="lazy" | |
| 150 | - />`:this._initials(n),u=a?J`<span | |
| 151 | - class=${`os-avatar__dot os-avatar__dot--${a}`} | |
| 152 | - aria-label=${this._presenceLabel(a)} | |
| 153 | - ></span>`:J``;return l?J` | |
| 154 | - <button | |
| 155 | - type="button" | |
| 156 | - class="os-avatar__tile" | |
| 157 | - aria-label=${s||"User"} | |
| 158 | - style=${c?`background:${c};`:""} | |
| 159 | - @click=${f=>this._onClick(f)} | |
| 160 | - >${d}</button> | |
| 161 | - ${u} | |
| 162 | - `:J` | |
| 163 | - <div | |
| 164 | - class="os-avatar__tile" | |
| 165 | - role="img" | |
| 166 | - aria-label=${s||"User"} | |
| 167 | - style=${c?`background:${c};`:""} | |
| 168 | - >${d}</div> | |
| 169 | - ${u} | |
| 170 | - `}_attr(t){return this.getAttribute(t)}_resolveSize(t){if(!t)return 32;if(t in Sy)return Sy[t];const n=Number(t);return Number.isFinite(n)&&n>0?n:32}_initials(t){const n=t.trim();return n?Array.from(n)[0]?.toUpperCase()??"?":"?"}_initialsBg(t){const n=mn(t);return`linear-gradient(135deg, hsl(${n} 62% 55%), hsl(${(n+24)%360} 58% 42%))`}_presenceForRender(){const t=this._attr("presence");return t&&Ay.has(t)?t:null}_presenceLabel(t){switch(t){case"online":return"Online";case"inactive":return"Inactive";case"offline":return"Offline"}}_onImgError(){this._imgFailed=!0,this.requestUpdate()}_onClick(t){const n=this._attr("user-id"),o={userId:n!==null&&Number(n)||null,originalEvent:t};this.emit("os-avatar-click",o)}_attachHoverEffect(){typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches||(this._onPointerEnter=()=>{this.style.setProperty("--os-ui-avatar-hover","1")},this._onPointerLeave=()=>{this.style.setProperty("--os-ui-avatar-hover","0"),this._pendingTiltX="0deg",this._pendingTiltY="0deg",this._pendingGlareX="50%",this._pendingGlareY="50%",this._flushTilt()},this._onPointerMove=n=>{const o=this.getBoundingClientRect();if(o.width===0||o.height===0)return;const s=(n.clientX-o.left)/o.width-.5,i=(n.clientY-o.top)/o.height-.5,r=14;this._pendingTiltY=`${(s*r).toFixed(2)}deg`,this._pendingTiltX=`${(-i*r).toFixed(2)}deg`;const a=Math.max(0,Math.min(100,(s+.5)*100)),l=Math.max(0,Math.min(100,(i+.5)*100));this._pendingGlareX=`${a.toFixed(1)}%`,this._pendingGlareY=`${l.toFixed(1)}%`,this._tiltRaf||(this._tiltRaf=requestAnimationFrame(()=>this._flushTilt()))},this.addEventListener("pointerenter",this._onPointerEnter),this.addEventListener("pointerleave",this._onPointerLeave),this.addEventListener("pointermove",this._onPointerMove))}_flushTilt(){this._tiltRaf=0,this.style.setProperty("--os-ui-avatar-tilt-x",this._pendingTiltX),this.style.setProperty("--os-ui-avatar-tilt-y",this._pendingTiltY),this.style.setProperty("--os-ui-avatar-glare-x",this._pendingGlareX),this.style.setProperty("--os-ui-avatar-glare-y",this._pendingGlareY)}_detachHoverEffect(){this._onPointerMove&&(this.removeEventListener("pointermove",this._onPointerMove),this._onPointerMove=null),this._onPointerEnter&&(this.removeEventListener("pointerenter",this._onPointerEnter),this._onPointerEnter=null),this._onPointerLeave&&(this.removeEventListener("pointerleave",this._onPointerLeave),this._onPointerLeave=null),this._tiltRaf&&(cancelAnimationFrame(this._tiltRaf),this._tiltRaf=0)}_maybeAttachPresenceListener(){const t=this._attr("user-id"),n=this._attr("presence"),o=!!t&&!n;o&&!this._presenceHandler?(this._presenceHandler=s=>{const i=s.detail;i&&String(i.userId)===String(t)&&i.newStatus&&Ay.has(i.newStatus)&&this.setAttribute("presence",i.newStatus)},document.addEventListener("os-presence-changed",this._presenceHandler)):!o&&this._presenceHandler&&(document.removeEventListener("os-presence-changed",this._presenceHandler),this._presenceHandler=null)}};ks.props=["src","alt","name","size","presence","userId","clickable"],ks.styles=[JD],ks.help=void 0;let Rc=ks;xe("os-avatar",Rc);const QD=ue`:host{display:inline-flex;align-items:center;gap:6px;font-size:var( --os-ui-save-status-font-size,11px );line-height:1;color:var( --os-ui-save-status-fg,currentColor );vertical-align:middle;min-width:0;opacity:1;pointer-events:auto}.os-save-status__indicator{display:inline-flex;align-items:center;justify-content:center;width:var( --os-ui-save-status-size,12px );height:var( --os-ui-save-status-size,12px );border-radius:50%;flex-shrink:0;box-sizing:border-box;background:var( --os-ui-save-status-bg,transparent );border:2px solid var( --os-ui-save-status-idle-color,color-mix( in srgb,var( --wp-admin-theme-color,#2271b1 ) 55%,transparent ) );color:var( --wp-admin-theme-color,#2271b1 );transition:background-color 0.2s ease,border-color 0.2s ease,box-shadow 0.2s ease}:host( [ phase='pending' ] ) .os-save-status__indicator,:host( [ phase='saving' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:os-save-status-pulse 1.2s ease-in-out infinite}:host( [ animation='modem' ][ phase='pending' ] ) .os-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;color:var( --wp-admin-theme-color,#2271b1 );animation:os-save-status-modem-stutter 1.8s ease-in-out infinite,os-save-status-modem-glow 2.4s ease-in-out infinite}@keyframes os-save-status-modem-stutter{0%,4%{opacity:1}5%,30%{opacity:0.22}31%,36%{opacity:1}37%,39%{opacity:0.22}40%,44%{opacity:1}45%,67%{opacity:0.22}68%,76%{opacity:1}77%,100%{opacity:0.22}}@keyframes os-save-status-modem-glow{0%,12%{box-shadow:0 0 0 0 transparent}13%,22%{box-shadow:0 0 4px 0 currentColor}23%,50%{box-shadow:0 0 0 0 transparent}51%,58%{box-shadow:0 0 4px 0 currentColor}59%,84%{box-shadow:0 0 0 0 transparent}85%,94%{box-shadow:0 0 5px 0 currentColor}95%,100%{box-shadow:0 0 0 0 transparent}}@media ( prefers-reduced-motion:reduce ){:host( [ phase='pending' ] ) .os-save-status__indicator,:host( [ phase='saving' ] ) .os-save-status__indicator,:host( [ animation='modem' ][ phase='pending' ] ) .os-save-status__indicator,:host( [ animation='modem' ][ phase='saving' ] ) .os-save-status__indicator{animation:none;opacity:0.85}}:host( [ phase='saved' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-saved-bg,var( --os-ui-success-fg,#1d6f42 ) );border-color:transparent;color:var( --os-ui-save-status-saved-bg,var( --os-ui-success-fg,#1d6f42 ) )}:host( [ phase='failed' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) );border-color:transparent;color:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) );animation:os-save-status-pulse 0.8s ease-in-out 2}:host( [ variant='ring' ] ) .os-save-status__indicator{background:transparent}:host( [ variant='ring' ][ phase='pending' ] ) .os-save-status__indicator,:host( [ variant='ring' ][ phase='saving' ] ) .os-save-status__indicator{background:transparent;border-color:var( --os-ui-save-status-ring-color,var( --os-ui-save-status-bg,var( --wp-admin-theme-color,#2271b1 ) ) );animation:os-save-status-ring-pulse 1.6s var( --os-ui-ease-loop,ease-in-out ) infinite}:host( [ variant='ring' ][ phase='failed' ] ) .os-save-status__indicator{background:transparent;border-color:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) );animation:os-save-status-ring-alert 0.62s var( --os-ui-ease-out,ease-out ) 1}:host( [ variant='ring' ][ phase='failed' ] ) .os-save-status__glyph{color:var( --os-ui-save-status-failed-bg,var( --os-ui-danger,#d63638 ) )}:host( [ variant='ring' ][ phase='saved' ] ) .os-save-status__indicator{background:var( --os-ui-save-status-saved-bg,var( --wp-admin-theme-color,#2271b1 ) );border-color:transparent;animation:os-save-status-ring-land 0.42s var( --os-ui-ease-out,ease-out ) 1}:host( [ variant='ring' ][ phase='saved' ] ) .os-save-status__glyph,:host( [ variant='ring' ][ phase='failed' ] ) .os-save-status__glyph{animation:os-save-status-glyph-in 0.24s var( --os-ui-ease-out,ease-out ) 0.08s 1 backwards}@keyframes os-save-status-ring-pulse{0%,100%{opacity:0.45;scale:0.9}50%{opacity:1;scale:1}}@keyframes os-save-status-ring-land{0%{scale:0.82}55%{scale:1.06}100%{scale:1}}@keyframes os-save-status-ring-alert{0%{scale:0.9}25%{scale:1.08}50%{scale:0.98}75%{scale:1.04}100%{scale:1}}@keyframes os-save-status-glyph-in{0%{opacity:0;scale:0.4}100%{opacity:1;scale:1}}@media ( prefers-reduced-motion:reduce ){:host( [ variant='ring' ] ) .os-save-status__indicator,:host( [ variant='ring' ] ) .os-save-status__glyph{animation:none;opacity:1;scale:1}}@keyframes os-save-status-pulse{0%,100%{opacity:0.55;transform:scale( 0.9 )}50%{opacity:1;transform:scale( 1 )}}:host( [ mode='pill' ] ) .os-save-status{display:inline-flex;align-items:center;gap:6px;padding:2px 10px;border-radius:999px;background:var( --os-ui-save-status-pill-bg,transparent );font-weight:500;white-space:nowrap}:host( [ mode='pill' ][ phase='saving' ] ) .os-save-status,:host( [ mode='pill' ][ phase='pending' ] ) .os-save-status{background:var( --os-ui-save-status-pill-bg,var( --os-ui-hover,rgba( 0,0,0,0.04 ) ) );color:var( --os-ui-save-status-pill-fg,var( --os-ui-fg-muted,#50575e ) )}:host( [ mode='pill' ][ phase='saved' ] ) .os-save-status{background:var( --os-ui-save-status-pill-bg,rgba( 30,132,73,0.12 ) );color:var( --os-ui-save-status-pill-fg,var( --os-ui-success-fg,#1d6f42 ) )}:host( [ mode='pill' ][ phase='failed' ] ) .os-save-status{background:var( --os-ui-save-status-pill-bg,rgba( 214,54,56,0.12 ) );color:var( --os-ui-save-status-pill-fg,var( --os-ui-danger-hover,#a02622 ) )}.os-save-status__label{min-width:0;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}:host( [ phase='saved' ] ) .os-save-status__glyph,:host( [ phase='failed' ] ) .os-save-status__glyph{display:inline-block;color:var( --os-ui-fg-on-accent,#fff );width:calc( var( --os-ui-save-status-size,12px ) * 0.66 );height:calc( var( --os-ui-save-status-size,12px ) * 0.66 )}.os-save-status__glyph{display:none}.os-save-status__glyph svg{display:block;width:100%;height:100%}`,Cy="os-settings-save-lifecycle",eR=2200,tR=6e3,Ss=class Ss extends Se{constructor(){super(...arguments),this._autoTimer=null,this._docListener=null}connectedCallback(){super.connectedCallback(),this.auto!==null&&this._installAutoListener()}disconnectedCallback(){this._removeAutoListener(),this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null)}attributeChangedCallback(t,n,o){if(super.attributeChangedCallback(t,n,o),(t==="auto"||t==="event")&&(this._removeAutoListener(),this.auto!==null&&this._installAutoListener()),t==="phase"){this._scheduleAutoClear();const s={phase:this.phase??"idle",error:this.error??void 0};this.emit("os-save-status-change",s)}}render(){const t=this.phase??"idle",n=this.mode??"dot",s=(this.error??"")||this._labelForPhase(t);return s?this.setAttribute("title",s):this.removeAttribute("title"),this.setAttribute("aria-live",t==="failed"?"assertive":"polite"),this.setAttribute("role",t==="failed"?"alert":"status"),J` | |
| 171 | - <span class="os-save-status"> | |
| 172 | - <span class="os-save-status__indicator" aria-hidden="true"> | |
| 173 | - <span class="os-save-status__glyph">${this._renderGlyph(t)}</span> | |
| 174 | - </span> | |
| 175 | - ${n==="pill"?J`<span class="os-save-status__label" | |
| 176 | - >${this._labelForPhase(t)}</span | |
| 177 | - >`:J``} | |
| 178 | - </span> | |
| 179 | - `}_renderGlyph(t){return t==="saved"?nR():t==="failed"?oR():""}_labelForPhase(t){switch(t){case"pending":case"saving":return this["saving-label"]??"Saving…";case"saved":return this["saved-label"]??"Saved";case"failed":return(this.error??"")||"Couldn’t save";default:return this["idle-label"]??""}}_installAutoListener(){const t=this.event||Cy;this._docListener=n=>{const o=n.detail;!o||typeof o.phase!="string"||(this.phase=o.phase,o.error?this.error=o.error:o.phase!=="failed"&&this.error&&this.removeAttribute("error"))},document.addEventListener(t,this._docListener)}_removeAutoListener(){if(!this._docListener)return;const t=this.event||Cy;document.removeEventListener(t,this._docListener),this._docListener=null}_scheduleAutoClear(){this._autoTimer!==null&&(window.clearTimeout(this._autoTimer),this._autoTimer=null);const t=this.phase??"idle",n=this._autoClearMsFor(t);n<=0||(this._autoTimer=window.setTimeout(()=>{this._autoTimer=null,this.phase="idle"},n))}_autoClearMsFor(t){if(t==="saved"){const n=this["auto-clear-saved-ms"];return parseInt(n||"",10)||eR}if(t==="failed"){const n=this["auto-clear-failed-ms"];return parseInt(n||"",10)||tR}return 0}};Ss.props=["phase","mode","variant","animation","auto","event","error","saving-label","saved-label","idle-label","auto-clear-saved-ms","auto-clear-failed-ms"],Ss.styles=[QD],Ss.help=void 0;let Oc=Ss;xe("os-save-status",Oc);function nR(){return J` | |
| 180 | - <svg | |
| 181 | - viewBox="0 0 12 12" | |
| 182 | - aria-hidden="true" | |
| 183 | - focusable="false" | |
| 184 | - fill="none" | |
| 185 | - stroke="currentColor" | |
| 186 | - stroke-width="2" | |
| 187 | - stroke-linecap="round" | |
| 188 | - stroke-linejoin="round" | |
| 189 | - > | |
| 190 | - <path d="M2.5 6 L5 8.5 L9.5 4" /> | |
| 191 | - </svg> | |
| 192 | - `}function oR(){return J` | |
| 193 | - <svg | |
| 194 | - viewBox="0 0 12 12" | |
| 195 | - aria-hidden="true" | |
| 196 | - focusable="false" | |
| 197 | - fill="currentColor" | |
| 198 | - > | |
| 199 | - <path | |
| 200 | - d="M5 2 H7 V7 H5 z M5 8.5 H7 V10.5 H5 z" | |
| 201 | - /> | |
| 202 | - </svg> | |
| 203 | - `}const sR=ue` ${dt} ${Aa}:host{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var( --os-ui-fg,#1d2327 );min-width:0}:host( [ hidden ] ){display:none}.os-textarea__label{font-size:12px;color:var( --os-ui-fg-muted,#646970 )}textarea{appearance:none;-webkit-appearance:none;display:block;width:100%;min-width:0;box-sizing:border-box;padding:8px 10px;background:var( --os-window-bg,#fff );border:1px solid var( --os-ui-border,#dcdcde );border-radius:6px;font:inherit;font-size:13px;line-height:1.45;color:var( --os-ui-fg,#1d2327 );resize:vertical}textarea:disabled{opacity:0.55;cursor:not-allowed;background:var( --os-ui-hover,rgba( 0,0,0,0.03 ) )}textarea[ aria-invalid='true' ],textarea[ aria-invalid='true' ]:hover:not(:disabled ){border-color:var( --os-ui-danger,#d63638 )}textarea[ aria-invalid='true' ]:focus,textarea[ aria-invalid='true' ]:focus-visible{border-color:var( --os-ui-danger,#d63638 );box-shadow:0 0 0 1px var( --os-ui-danger,#d63638 ),0 0 0 4px rgba( 214,54,56,0.18 )}:host( [ auto-grow ] ) textarea{resize:none;overflow:hidden}`,As=class As extends Se{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),hp(this)}render(){const t=this._attr("label")||"",n=this._attr("value")??"",o=this._attr("placeholder")||"",s=this._boolAttr("disabled"),i=this._boolAttr("readonly"),r=this._attr("aria-label")||t,a=this._attr("name")||"",l=Number(this._attr("rows"))||3,c=this._attr("maxlength"),d=this._attr("minlength"),u=this._boolAttr("invalid"),p=`${this.id||"os-unnamed"}__field`;return J` | |
| 204 | - ${t?J`<label class="os-textarea__label" for=${p}>${t}</label>`:J``} | |
| 205 | - <textarea | |
| 206 | - id=${p} | |
| 207 | - part="textarea" | |
| 208 | - .value=${n} | |
| 209 | - placeholder=${o} | |
| 210 | - ?disabled=${s} | |
| 211 | - ?readonly=${i} | |
| 212 | - rows=${l} | |
| 213 | - maxlength=${c??""} | |
| 214 | - minlength=${d??""} | |
| 215 | - name=${a} | |
| 216 | - aria-invalid=${u?"true":"false"} | |
| 217 | - aria-label=${r||""} | |
| 218 | - @input=${g=>this._onInput(g)} | |
| 219 | - @change=${g=>this._onChange(g)} | |
| 220 | - @keydown=${g=>this._onKeyDown(g)} | |
| 221 | - ></textarea> | |
| 222 | - `}_attr(t){return this.getAttribute(t)}_boolAttr(t){return this.getAttribute(t)!==null}_onInput(t){const n=t.target;this._textareaEl=n,this.setAttribute("value",n.value),this.emit("os-input-change",{value:n.value}),this._boolAttr("auto-grow")&&this._autosize(n)}_onChange(t){const n=t.target;this.emit("os-input-commit",{value:n.value})}_onKeyDown(t){if(this._boolAttr("submit-on-enter")&&t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey&&!t.ctrlKey){t.preventDefault();const n=t.target;this.emit("os-submit",{value:n.value})}}_autosize(t){const n=Number(this._attr("max-rows"))||8,o=window.getComputedStyle(t),s=parseFloat(o.fontSize)||13,i=o.lineHeight,r=i==="normal"?s*1.45:parseFloat(i)||s*1.45,a=parseFloat(o.paddingTop)||0,l=parseFloat(o.paddingBottom)||0,c=r*n+a+l;t.style.height="auto";const d=Math.min(t.scrollHeight,c);t.style.height=`${d}px`}refreshAutosize(){this._textareaEl&&this._boolAttr("auto-grow")&&this._autosize(this._textareaEl)}focusInput(){(this.shadowRoot??this).querySelector("textarea")?.focus()}clear(){this.setAttribute("value","");const n=(this.shadowRoot??this).querySelector("textarea");n&&(n.value="",this._boolAttr("auto-grow")&&this._autosize(n))}};As.props=["label","value","placeholder","disabled","readonly","ariaLabel","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],As.styles=[sR],As.help=void 0;let Mc=As;xe("os-textarea",Mc);const iR=ue`:host{display:inline-flex}button{display:flex;align-items:center;justify-content:center;width:30px;height:30px;padding:0;border:none;border-radius:var( --os-ui-btn-radius,5px );background-color:var( --os-ui-btn-bg,transparent );background-image:var( --os-ui-btn-bg-image,none );background-repeat:var( --os-ui-btn-bg-image-repeat,no-repeat );background-size:var( --os-ui-btn-bg-image-size,auto );background-position:var( --os-ui-btn-bg-image-position,center );color:var( --os-ui-btn-color,currentColor );cursor:pointer;transition:background-color 0.15s ease,color 0.15s ease,transform 80ms ease}button:active{transform:scale( 0.9 )}@media ( prefers-reduced-motion:reduce ){button:active{transform:none}}button:hover{color:var( --os-ui-btn-color-hover,currentColor );background-color:var( --os-ui-btn-bg-hover,var( --os-ui-hover,rgba( 0,0,0,0.06 ) ) )}button:focus-visible{color:var( --os-ui-btn-color-hover,currentColor );background-color:var( --os-ui-btn-bg-hover,var( --os-ui-hover,rgba( 0,0,0,0.06 ) ) );outline:2px solid var( --os-ui-btn-outline,currentColor );outline-offset:1px}:host( [ active ] ) button{color:var( --os-ui-btn-color-hover,currentColor );background-color:var( --os-ui-btn-bg-active,var( --os-ui-hover,rgba( 0,0,0,0.08 ) ) )}:host( [ danger ] ) button:hover{color:var( --os-ui-fg-on-accent,#fff );background-color:var( --os-ui-btn-danger-hover,var( --os-ui-danger,#d63638 ) )}svg{display:block;pointer-events:none;flex-shrink:0}svg:empty{display:none}.themed-icon{display:block;width:14px;height:14px;flex-shrink:0;pointer-events:none;background-color:var( --os-ui-btn-icon-color,currentColor )}::slotted( span ){line-height:1}::slotted( svg ){display:block}`,rR={minimize:'<path d="M3 6h6" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>',maximize:'<rect x="3" y="3" width="6" height="6" rx="1" stroke="currentColor" stroke-width="1.25" fill="none"/>',fullscreen:'<path d="M4.5 2H2v2.5M10 4.5V2H7.5M4.5 10H2V7.5M10 7.5V10H7.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',"fullscreen-exit":'<path d="M2 4.5H4.5V2M7.5 2V4.5H10M2 7.5H4.5V10M7.5 10V7.5H10" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',detach:'<path d="M5 2H2.5v7.5H10V7M6.5 2H10v3.5M10 2L5.5 6.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',reload:'<g transform="translate(0.6 0.6) scale(0.021)" fill="currentColor"><path d="m504.554 233.704-76.447 91.467c-6.329 7.572-15.417 11.479-24.571 11.479a31.872 31.872 0 0 1-20.504-7.447l-91.467-76.447c-13.561-11.334-15.366-31.515-4.032-45.075s31.515-15.366 45.075-4.032l37.506 31.347c-10.274-74.891-74.668-132.774-152.337-132.774C132.984 102.223 64 171.207 64 256s68.984 153.777 153.777 153.777c17.673 0 32 14.327 32 32s-14.327 32-32 32c-58.17 0-112.859-22.653-153.991-63.785C22.653 368.859 0 314.17 0 256s22.653-112.859 63.786-153.992c41.132-41.132 95.821-63.785 153.991-63.785s112.859 22.653 153.992 63.785c32.517 32.516 53.471 73.508 60.829 117.991l22.849-27.339c11.334-13.56 31.515-15.364 45.075-4.032 13.56 11.335 15.365 31.516 4.032 45.076z"/></g>',close:'<path d="M3.25 3.25l5.5 5.5M3.25 8.75l5.5-5.5" stroke="currentColor" stroke-width="1.25" stroke-linecap="round"/>',menu:'<circle cx="3" cy="6" r="1.2" fill="currentColor"/><circle cx="6" cy="6" r="1.2" fill="currentColor"/><circle cx="9" cy="6" r="1.2" fill="currentColor"/>'};function aR(e){const t=(e??"").trim();return t===""||t.length>4096||!/^(https?:\/\/|data:image\/)/i.test(t)||/['"()\\<>\s]/.test(t)?"":t}const Cs=class Cs extends Se{constructor(){super(...arguments),this._activateWired=!1}static get observedAttributes(){return[...super.observedAttributes,"aria-label"]}render(){const t=aR(this["icon-src"]||this.getAttribute("icon-src")||""),n=t?"":this.icon||"",o=rR[n]||"",s=this.getAttribute("aria-label")||"";return t?J` | |
| 223 | - <button type="button" aria-label="${s}"> | |
| 224 | - <span | |
| 225 | - class="themed-icon" | |
| 226 | - aria-hidden="true" | |
| 227 | - style="-webkit-mask: url('${t}') center / contain no-repeat; mask: url('${t}') center / contain no-repeat;" | |
| 228 | - ></span> | |
| 229 | - <slot></slot> | |
| 230 | - </button> | |
| 231 | - `:J` | |
| 232 | - <button type="button" aria-label="${s}"> | |
| 233 | - <svg | |
| 234 | - width="14" | |
| 235 | - height="14" | |
| 236 | - viewBox="0 0 12 12" | |
| 237 | - aria-hidden="true" | |
| 238 | - focusable="false" | |
| 239 | - ></svg> | |
| 240 | - <slot></slot> | |
| 241 | - </button> | |
| 242 | - <span data-svg-buffer style="display:none">${o}</span> | |
| 243 | - `}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paintSvg()),queueMicrotask(()=>this._wireActivateEvent())}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),queueMicrotask(()=>this._paintSvg())}_paintSvg(){const t=this.shadowRoot;if(!t)return;const n=t.querySelector("svg"),o=t.querySelector("[data-svg-buffer]");if(n&&o){const s=o.textContent||"";n.innerHTML!==s&&(n.innerHTML=s)}}_wireActivateEvent(){if(this._activateWired)return;const t=this.shadowRoot;if(!t)return;const n=t.querySelector("button");n&&(this._activateWired=!0,n.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("os-button-activate",{bubbles:!0,composed:!0,cancelable:!0}))}))}};Cs.props=["icon","icon-src","active","danger"],Cs.styles=[iR],Cs.help=void 0;let Pc=Cs;xe("os-window-button",Pc);const Jt=["butter","blush","sky","mint","lilac","peach"];function lR(e){return Jt.includes(e)?e:Jt[0]}function Wc(e){return e.toLowerCase().replace(/[^a-z0-9_-]/g,"")||Jt[0]}function Iy(e){const t=Jt.indexOf(lR(e));return Jt[(t+1)%Jt.length]}const xy="cubic-bezier(0.2, 0.7, 0.2, 1)",Ly="cubic-bezier(0.5, 0, 0.9, 0.4)",cR="cubic-bezier(0.2, 0.7, 0.3, 1.15)";function jn(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function at(e,t,n){return typeof e.animate!="function"?Promise.resolve():e.animate(t,n).finished.then(()=>{}).catch(()=>{})}async function dR(e){const t=e.restRotation??0;if(jn()){Ty(e.rippleHost,400);return}const n=e.tempo??1,o=e.fallDistance??30;await at(e.pin,[{opacity:0,transform:`translate(8px, ${-o}px) rotate(${t-16}deg) scale(1.9)`},{opacity:1,offset:.35},{opacity:1,transform:`translate(0, 0) rotate(${t}deg) scale(0.92)`}],{duration:170*n,easing:Ly,fill:"forwards"}),Ty(e.rippleHost,420*n);const s=at(e.paper,[{transform:"scale(1) translateY(0) skewX(0)"},{transform:"scale(0.982) translateY(2px) skewX(0)",offset:.08},{transform:"scale(1.01) translateY(0) skewX(0.6deg)",offset:.32},{transform:"scale(0.996) translateY(0) skewX(-0.4deg)",offset:.55},{transform:"scale(1) translateY(0) skewX(0)"}],{duration:370*n,easing:"linear"}),i=at(e.pin,[{transform:`rotate(${t}deg) scale(0.92)`},{transform:`rotate(${t+1.5}deg) scale(1.07)`,offset:.25},{transform:`rotate(${t-1}deg) scale(0.98)`,offset:.5},{transform:`rotate(${t}deg) scale(1)`}],{duration:370*n,easing:xy,fill:"forwards"});await Promise.all([s,i])}function Ty(e,t){const n=document.createElement("span");n.className="os-pinned-note__ripple",n.setAttribute("aria-hidden","true"),e.appendChild(n),at(n,[{boxShadow:"0 0 0 0 rgba(0, 0, 0, 0.28)",opacity:.35},{boxShadow:"0 0 0 26px rgba(0, 0, 0, 0)",opacity:0}],{duration:t,easing:"ease-out"}).then(()=>n.remove()),window.setTimeout(()=>n.remove(),t+100)}function uR(e){if(jn())return{onPointerMove:()=>{},setBias:()=>{},stop:()=>{}};const t=14;let n=0,o=0,s=0,i=0,r=null,a=0,l=0,c=0,d=0,u=!0;const f=p=>{if(!u)return;const g=Math.min(.05,d?(p-d)/1e3:.016);d=p,p-a>80&&(l*=.85),s=Math.max(-14,Math.min(14,-l*.055))+i,o+=(-120*(n-s)-t*o)*g,n+=o*g,e.style.transform=`rotate(${n.toFixed(2)}deg)`,c=window.requestAnimationFrame(f)};return c=window.requestAnimationFrame(f),{onPointerMove(p){const g=performance.now();if(r!==null&&g>a){const m=(p-r)/(g-a)*16.7;l=l*.7+m*.3}r=p,a=g},setBias(p){i=p},stop(){u=!1,window.cancelAnimationFrame(c),e.style.transform=""}}}async function fR(e){if(jn()){await at(e.flyback,[{opacity:1},{opacity:0}],{duration:120,easing:"linear",fill:"forwards"});return}const t=e.swing?at(e.swing,[{transform:"rotate(0deg)"},{transform:"rotate(9deg)",offset:.35},{transform:"rotate(-4deg)",offset:.7},{transform:"rotate(0deg)"}],{duration:330,easing:"linear",fill:"forwards"}):Promise.resolve(),n=at(e.flyback,[{left:`${e.flyback.offsetLeft}px`,top:`${e.flyback.offsetTop}px`},{left:`${e.homeX}px`,top:`${e.homeY}px`}],{duration:330,easing:cR,fill:"forwards"});await Promise.all([n,t])}async function pR(e){if(jn()){await at(e.clone,[{opacity:1},{opacity:0}],{duration:150,easing:"linear",fill:"forwards"});return}e.pin&&at(e.pin,[{transform:"translate(0, 0) rotate(0deg)",opacity:1},{transform:"translate(2px, -16px) rotate(-30deg)",opacity:0}],{duration:200,easing:xy,fill:"forwards"});const t=e.clone.getBoundingClientRect(),n=e.binX-(t.left+t.width/2),o=e.binY-(t.top+t.height/2),s="polygon(4% 8%, 38% 2%, 68% 7%, 96% 3%, 98% 42%, 92% 71%, 97% 94%, 60% 98%, 30% 93%, 3% 97%, 6% 62%, 2% 34%)",i="polygon(10% 14%, 42% 6%, 64% 12%, 90% 8%, 94% 38%, 86% 66%, 92% 88%, 58% 94%, 34% 86%, 10% 92%, 14% 58%, 8% 36%)";await at(e.paper,[{transform:"translate(0, 0) scale(0.88) rotate(0deg)",borderRadius:"2px",opacity:1},{transform:`translate(${n*.3}px, ${o*.3}px) scale(0.6) rotate(12deg)`,clipPath:s,offset:.3},{transform:`translate(${n*.6}px, ${o*.6}px) scale(0.34) rotate(24deg)`,clipPath:i,offset:.6,opacity:1},{transform:`translate(${n}px, ${o}px) scale(0.12) rotate(38deg)`,borderRadius:"50%",clipPath:i,opacity:0}],{duration:400,easing:Ly,delay:60,fill:"forwards"})}function hR(e){let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619)>>>0;return t>>>1||1}function Ny(e){let t=2166136261;const n=`os-note-${e}`;for(let i=0;i<n.length;i++)t^=n.charCodeAt(i),t=Math.imul(t,16777619)>>>0;const o=t>>>3,s=t>>>5;return{rotation:(t%45-22)/10,pinOffsetX:o%21-10,pinRotation:s%17-8}}const mR=.57,gR=.525,wR=56,yR=52;function bR(e){return`${e.replace(/\/$/,"")}/assets/images/pushpin.svg`}function vR(e){const t=document.createElement("img");return t.src=bR(e),t.alt="",t.width=wR,t.height=yR,t.draggable=!1,t.className="os-pinned-note__pin-img",t}let $c=null;function _R(e){$c=e}function ER(){if(!$c)throw new Error("[openstation] notes REST client called before installNotesRestDeps().");return $c}function kR(e){const t=window.openStationConfig;return typeof t?.restNonce=="string"&&t.restNonce?t.restNonce:e}class Dy extends Error{constructor(t){super("Note was changed by another session."),this.status=409,this.name="NotesConflictError",this.current=t}}function SR(e){return e instanceof Dy}async function Vn(e,t){const{baseUrl:n,nonce:o}=ER(),s=e?nt(n,e):n,i=new Headers(t.headers??{});i.set("X-WP-Nonce",kR(o)),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Fe(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/notes"}),a=await r.text();let l=null;if(a)try{l=JSON.parse(a)}catch{l=null}if(!r.ok){if(r.status===409){const d=l?.data?.current;throw new Dy(d??null)}const c=l;throw new Error(`[openstation] notes REST ${r.status}: ${c?.code??""} ${c?.message??""}`.trim())}if(l===null)throw new Error(`[openstation] notes REST ${r.status}: empty or unparseable body.`);return l}function Ry(){return Vn("",{method:"GET"})}function AR(e){return Vn("",{method:"POST",body:JSON.stringify(e)})}function CR(e,t){return Vn(`/${e}`,{method:"PATCH",body:JSON.stringify(t)})}function IR(e){return Vn(`/${e}`,{method:"DELETE"})}function Oy(e){return Vn(`/${e}/restore`,{method:"POST"})}function xR(e){return Vn(`/${e}/convert`,{method:"POST"})}const LR="openstation_notes_subscribe",TR="openstation_notes";let My=!1,Uc=null;function NR(e){Uc=e,!My&&(My=!0,Le.contribute(LR,()=>Uc?.getHeartbeatSubscription()),Le.subscribe(TR,t=>{Uc?.applyHeartbeatPayload(t)}))}const DR="wpd_note",RR="note-draft",qn="note",OR="os-note-created";function cr(e,t){if(t.length===0)return;window.wp?.os?.broadcast?.(`os.${DR}.changed`,{source:"desktop-mode/notes",action:e,ids:t})}function Py(){const e=window.wp?.os;return e&&typeof e.showToast=="function"?e:null}async function MR(e,t){t.onEvict(e.id);try{await IR(e.id),cr("trashed",[e.id]),Py()?.showToast?.({message:E("Note moved to Trash","desktop-mode"),duration:6e3,action:{label:E("Undo","desktop-mode"),onClick:()=>{Oy(e.id).then(n=>{cr("untrashed",[e.id]),t.onRestore(n)}).catch(n=>{console.error("[openstation] notes: restore failed:",n)})}}})}catch(n){console.error("[openstation] notes: trash failed:",n),t.onRestore(e),Py()?.showToast?.({message:E("Could not move the note to the Trash.","desktop-mode"),duration:5e3})}}function dr(){return window.wp?.os??null}function PR(e){const t=dr();if(!t?.windowManager?.open||!t.deriveWindowId)return window.location.href=e,null;const n=t.deriveWindowId(e);return t.windowManager.open({id:n,baseId:n,url:e,title:E("Edit draft","desktop-mode"),icon:"dashicons-admin-post"}),n}async function WR(e,t){t.onEvict(e.id);try{const n=await xR(e.id);cr("trashed",[e.id]);const o=PR(n.editUrl);dr()?.showToast?.({message:E("Note converted to a draft post","desktop-mode"),duration:6e3,action:{label:E("Undo","desktop-mode"),onClick:()=>{o&&dr()?.windowManager?.getById?.(o)?.close?.(),Oy(e.id).then(s=>{cr("untrashed",[e.id]),t.onRestore(s)}).catch(s=>{console.error("[openstation] notes: convert undo failed:",s)})}}})}catch(n){console.error("[openstation] notes: convert failed:",n),t.onRestore(e),dr()?.showToast?.({message:E("Could not convert the note to a post.","desktop-mode"),duration:5e3})}}const $R=208,UR=1e3,FR=800,BR=10,HR=1;function zR(){return window.wp?.os?.dragManager??null}function ur(e){return e.seed||Math.abs(e.id)||1}const GR='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="currentColor" aria-hidden="true" focusable="false"><path d="m7.3 9.7 1.4 1.4c.2-.2.3-.3.4-.5 0 0 0-.1.1-.1.3-.5.4-1.1.3-1.6L12 7 9 4 7.2 6.5c-.6-.1-1.1 0-1.6.3 0 0-.1 0-.1.1-.3.1-.4.2-.6.4l1.4 1.4L4 11v1h1l2.3-2.3zM4 20h9v-1.5H4V20zm0-5.5V16h16v-1.5H4z" /></svg>',jR=rn("trash",{size:20});class VR{constructor(t){this.root=null,this.liveRegion=null,this.controllers=new Map,this.zCounter=1,this.highWaterMs=0,this.tempIdCounter=0,this.host=t.host,this.pluginUrl=t.pluginUrl,this.canCreatePosts=t.canCreatePosts??!1,this.onError=t.onError}async boot(){try{const{notes:t}=await Ry();t.forEach(n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"none"})}),NR(this)}catch(t){t instanceof Error&&console.debug("[openstation] Pinned notes unavailable:",t.message)}}upsertNote(t,n={animate:"none"}){this.ensureRoot(),this.zCounter=Math.max(this.zCounter,t.z);const o=this.controllers.get(t.id);if(o)return o.replace(t),o;const s=new qR({layer:this,note:t});return this.controllers.set(t.id,s),this.root?.appendChild(s.element),n.animate!=="none"&&s.playInsertion(n.animate==="thunk"?1:.7),s}removeNote(t){const n=this.controllers.get(t);n&&(this.controllers.delete(t),n.dispose(),n.element.remove())}rekeyNote(t,n){this.controllers.delete(t),this.controllers.set(n.note.id,n)}has(t){return this.controllers.has(t)}get(t){return this.controllers.get(t)}nextTempId(){return this.tempIdCounter-=1,this.tempIdCounter}bringToFront(t){this.zCounter+=1,t.setZ(this.zCounter)}bumpHighWater(t){Number.isFinite(t)&&t>this.highWaterMs&&(this.highWaterMs=t)}hostSize(){return{width:Math.max(1,this.host.clientWidth),height:Math.max(1,this.host.clientHeight)}}clampPosition(t,n){const{width:o,height:s}=this.hostSize(),i=Math.max(0,1-$R/o),r=Math.max(0,1-120/s);return{x:Math.min(i,Math.max(0,t)),y:Math.min(r,Math.max(0,n))}}normalizedFromClient(t,n){const o=this.host.getBoundingClientRect(),{width:s,height:i}=this.hostSize();return this.clampPosition((t-o.left)/s,(n-o.top)/i)}createNoteAt(t){const n=t.text??"",o=Wc(t.color??Jt[0]),s=t.isPublic===!0,{x:i,y:r}=this.clampPosition(t.x,t.y),a=hR(n||`${i},${r}`),l=this.nextTempId(),c=this.upsertNote({id:l,text:n,color:o,x:i,y:r,z:1,public:s,seed:a,ownerId:0,ownerName:"",ownerAvatar:"",canEdit:!0,updatedAtMs:0},{animate:"thunk"});return this.bringToFront(c),t.focus&&c.focusEditor(),AR({text:n,color:o,x:i,y:r,public:s,seed:a}).then(d=>{this.bumpHighWater(d.updatedAtMs),c.replace(d),this.rekeyNote(l,c),c.flushPendingEdits()}).catch(d=>{this.removeNote(l),this.notifyError(E("Could not pin the note. Please try again.","desktop-mode")),console.error("[openstation] notes: create failed:",d)}),c}announce(t){this.ensureRoot(),this.liveRegion&&(this.liveRegion.textContent=t)}notifyError(t){this.onError?.(t)}trashNote(t){MR(t,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}convertNote(t){!this.canCreatePosts||!t.canEdit||WR(t,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}getHeartbeatSubscription(){return{knownIds:Array.from(this.controllers.keys()).filter(t=>t>0),sinceMs:this.highWaterMs}}applyHeartbeatPayload(t){for(const n of t.notes??[]){this.bumpHighWater(n.updatedAtMs);const o=this.controllers.get(n.id);o?o.shouldReplaceFromRemote(n)&&o.replace(n):this.upsertNote(n,{animate:"move"})}for(const n of t.removed??[])this.removeNote(n);typeof t.serverTimeMs=="number"&&Number.isFinite(t.serverTimeMs)&&this.bumpHighWater(t.serverTimeMs),t.truncated&&this.reloadFromServer()}async reloadFromServer(){try{const{notes:t}=await Ry(),n=new Set;for(const o of t){n.add(o.id),this.bumpHighWater(o.updatedAtMs);const s=this.controllers.get(o.id);s?s.shouldReplaceFromRemote(o)&&s.replace(o):this.upsertNote(o,{animate:"move"})}for(const o of Array.from(this.controllers.keys()))o>0&&!n.has(o)&&this.removeNote(o)}catch{}}ensureRoot(){if(this.root)return this.root;const t=document.createElement("section");t.className="os-notes",t.setAttribute("aria-label",E("Pinned notes","desktop-mode"));const n=document.createElement("div");return n.className="os-notes__live screen-reader-text",n.setAttribute("aria-live","polite"),t.appendChild(n),this.host.appendChild(t),this.root=t,this.liveRegion=n,t}}class qR{constructor(t){this.editor=null,this.statusEl=null,this.colorDot=null,this.visibilityBtn=null,this.saveTimer=null,this.zTimer=null,this.patchChain=Promise.resolve(),this.pendingText=null,this.disposed=!1,this.moveMode=!1,this.moveOrigin=null,this.dragCleanup=null,this.lastPointer=null,this.layer=t.layer,this.note=t.note,this.jitter=Ny(ur(t.note)),this.element=document.createElement("article"),this.paperEl=document.createElement("div"),this.pinEl=document.createElement(this.note.canEdit?"button":"span"),this.paint(),this.applyPosition(),this.setZ(this.note.z),this.element.addEventListener("pointerdown",()=>this.layer.bringToFront(this),{capture:!0})}paint(){const t=this.note;this.element.className="os-pinned-note",this.element.dataset.noteId=String(t.id),this.element.dataset.noteColor=Wc(t.color),this.element.dataset.owner=t.canEdit?"me":"other",this.element.setAttribute("role",t.canEdit?"group":"note"),this.element.setAttribute("aria-label",t.canEdit?E("Pinned note","desktop-mode"):de(E("Note by %s","desktop-mode"),t.ownerName)),this.element.style.setProperty("--dm-note-rot",`${this.jitter.rotation}deg`),this.element.style.setProperty("--dm-pin-dx",`${this.jitter.pinOffsetX}px`),this.element.style.setProperty("--dm-pin-rot",`${this.jitter.pinRotation}deg`),this.pinEl.className="os-pinned-note__pin",this.pinEl.appendChild(vR(this.layer.pluginUrl)),t.canEdit?(this.pinEl.setAttribute("type","button"),this.pinEl.setAttribute("aria-pressed","false"),this.pinEl.setAttribute("aria-label",E("Move note. Drag the pin, or press Enter then use the arrow keys.","desktop-mode")),this.pinEl.addEventListener("pointerdown",n=>this.startDrag(n)),this.pinEl.addEventListener("click",n=>{n.detail===0&&!this.moveMode&&this.toggleMoveMode()}),this.pinEl.addEventListener("keydown",n=>this.onPinKeydown(n)),this.pinEl.addEventListener("blur",()=>this.exitMoveMode(!1))):this.pinEl.setAttribute("aria-hidden","true"),this.paperEl.className="os-pinned-note__paper",t.canEdit?this.paintOwnerPaper():this.paintViewerPaper(),this.element.append(this.pinEl,this.paperEl)}paintOwnerPaper(){const t=document.createElement("div");t.className="os-pinned-note__meta";const n=document.createElement("os-save-status");n.setAttribute("mode","icon"),n.setAttribute("phase","idle"),n.className="os-pinned-note__status",this.statusEl=n;const o=document.createElement("button");o.type="button",o.className="os-pinned-note__color-dot",this.colorDot=o,this.refreshColorDot(),o.addEventListener("click",()=>this.cycleColor()),t.append(n,o);const s=document.createElement("div");s.className="os-pinned-note__actions";const i=document.createElement("os-window-button");if(i.className="os-pinned-note__visibility",this.visibilityBtn=i,this.refreshVisibility(),i.addEventListener("os-button-activate",()=>this.togglePublic()),s.appendChild(i),this.layer.canCreatePosts){const d=document.createElement("os-window-button");d.className="os-pinned-note__convert",d.innerHTML=GR;const u=E("Convert to a draft post","desktop-mode");d.setAttribute("title",u),d.setAttribute("aria-label",u),d.addEventListener("os-button-activate",()=>this.layer.convertNote(this.note)),s.appendChild(d)}const r=document.createElement("os-window-button");r.className="os-pinned-note__trash",r.innerHTML=jR;const a=E("Move to Trash","desktop-mode");r.setAttribute("title",a),r.setAttribute("aria-label",a),r.addEventListener("os-button-activate",()=>this.confirmTrash()),s.appendChild(r);const l=document.createElement("os-textarea");l.className="os-pinned-note__editor",l.setAttribute("aria-label",E("Note text","desktop-mode")),l.setAttribute("rows","5"),l.setAttribute("auto-grow",""),l.setAttribute("max-rows","10"),l.setAttribute("value",this.note.text),["keydown","keypress","keyup"].forEach(d=>{l.addEventListener(d,u=>u.stopPropagation())}),l.addEventListener("os-input-change",d=>{const u=d.detail;this.pendingText=u.value,this.setPhase("pending"),this.scheduleSave()}),l.addEventListener("os-input-commit",()=>this.flushSave()),this.editor=l;const c=document.createElement("div");c.className="os-pinned-note__footer",c.appendChild(s),this.paperEl.append(t,l,c)}paintViewerPaper(){const t=document.createElement("div");t.className="os-pinned-note__body",t.textContent=this.note.text;const n=document.createElement("div");n.className="os-pinned-note__attribution",n.title=de(E("Pinned by %s","desktop-mode"),this.note.ownerName);const o=document.createElement("os-avatar");o.setAttribute("size","20"),o.setAttribute("name",this.note.ownerName),this.note.ownerAvatar&&o.setAttribute("src",this.note.ownerAvatar);const s=document.createElement("span");s.className="os-pinned-note__attribution-name",s.textContent=this.note.ownerName,n.append(o,s),this.paperEl.append(t,n)}refreshColorDot(){if(!this.colorDot)return;const t=Iy(this.note.color);this.colorDot.style.setProperty("--dm-note-next-paper",`var(--dm-note-${t})`),this.colorDot.setAttribute("aria-label",de(E("Change paper color (next: %s)","desktop-mode"),t))}refreshVisibility(){if(!this.visibilityBtn)return;const t=this.note.public;this.visibilityBtn.innerHTML="";const n=document.createElement("span");n.className=`dashicons ${t?"dashicons-admin-site-alt3":"dashicons-lock"}`,n.setAttribute("aria-hidden","true"),this.visibilityBtn.appendChild(n),this.visibilityBtn.setAttribute("title",E(t?"Public note — everyone can see it. Click to make private.":"Private note. Click to share with every desktop user.","desktop-mode")),this.visibilityBtn.classList.toggle("is-public",t)}replace(t){const n=t.id!==this.note.id,o=ur(t)!==ur(this.note),s=t.color!==this.note.color,i=t.x!==this.note.x||t.y!==this.note.y,r=t.z!==this.note.z;if(this.note=t,r&&(this.element.style.zIndex=String(t.z)),n&&(this.element.dataset.noteId=String(t.id)),o&&(this.jitter=Ny(ur(t)),this.element.style.setProperty("--dm-note-rot",`${this.jitter.rotation}deg`),this.element.style.setProperty("--dm-pin-dx",`${this.jitter.pinOffsetX}px`),this.element.style.setProperty("--dm-pin-rot",`${this.jitter.pinRotation}deg`)),s&&(this.element.dataset.noteColor=Wc(t.color),this.refreshColorDot()),i&&this.applyPosition(),this.note.canEdit)this.pendingText===null&&this.editor?.setAttribute("value",t.text),this.refreshVisibility();else{const a=this.paperEl.querySelector(".os-pinned-note__body");a&&(a.textContent=t.text)}}shouldReplaceFromRemote(t){return this.pendingText!==null||this.saveTimer!==null?!1:t.updatedAtMs>=this.note.updatedAtMs}setZ(t){this.element.style.zIndex=String(t),!(t===this.note.z||!this.note.canEdit)&&(this.note={...this.note,z:t},!(this.note.id<=0)&&(this.zTimer!==null&&window.clearTimeout(this.zTimer),this.zTimer=window.setTimeout(()=>{this.zTimer=null,this.queuePatch({z:this.note.z})},FR)))}applyPosition(){this.element.style.left=`${(this.note.x*100).toFixed(3)}%`,this.element.style.top=`${(this.note.y*100).toFixed(3)}%`}moveTo(t,n){const o=this.layer.clampPosition(t,n);this.note={...this.note,x:o.x,y:o.y},this.applyPosition(),this.note.id>0&&this.queuePatch({x:o.x,y:o.y})}playInsertion(t=1){return dR({pin:this.pinEl,paper:this.paperEl,rippleHost:this.element,restRotation:this.jitter.pinRotation,fallDistance:t>=1?30:12,tempo:t})}focusEditor(){window.setTimeout(()=>this.editor?.focusInput?.(),0)}dispose(){this.disposed=!0,this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.zTimer!==null&&(window.clearTimeout(this.zTimer),this.zTimer=null),this.dragCleanup?.(),this.dragCleanup=null}setPhase(t){this.statusEl?.setAttribute("phase",t)}scheduleSave(){this.saveTimer!==null&&window.clearTimeout(this.saveTimer),this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.flushSave()},UR)}flushPendingEdits(){this.flushSave()}flushSave(){if(this.saveTimer!==null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.pendingText===null||this.note.id<=0)return;const t=this.pendingText;this.pendingText=null,this.note={...this.note,text:t},this.setPhase("saving"),this.queuePatch({text:t})}cycleColor(){const t=Iy(this.note.color);this.note={...this.note,color:t},this.element.dataset.noteColor=t,this.refreshColorDot(),this.note.id>0&&this.queuePatch({color:t})}togglePublic(){const t=!this.note.public;this.note={...this.note,public:t},this.refreshVisibility(),t&&!jn()&&this.visibilityBtn&&this.visibilityBtn.animate?.([{transform:"scale(1)"},{transform:"scale(1.25)"},{transform:"scale(1)"}],{duration:300,easing:"ease-out"}),this.layer.announce(E(t?"Note is now public.":"Note is now private.","desktop-mode")),this.note.id>0&&this.queuePatch({public:t})}confirmTrash(){Pn({title:E("Move note to the Trash?","desktop-mode"),message:E("You can restore it from the Trash later.","desktop-mode"),confirmLabel:E("Move to Trash","desktop-mode"),danger:!0}).then(t=>{t&&this.layer.trashNote(this.note)})}queuePatch(t){this.patchChain=this.patchChain.then(async()=>{if(!(this.disposed||this.note.id<=0))try{const n=await CR(this.note.id,{...t,updatedAtMs:this.note.updatedAtMs});if(this.disposed)return;const o=n.public!==this.note.public;this.note={...this.note,updatedAtMs:n.updatedAtMs,public:n.public},o&&this.refreshVisibility(),this.setPhase("saved")}catch(n){if(this.disposed)return;if(SR(n)&&n.current){this.pendingText=null,this.replace(n.current),this.setPhase("idle"),this.layer.notifyError(E("This note was changed in another session — showing the latest version.","desktop-mode"));return}this.setPhase("failed"),console.error("[openstation] notes: save failed:",n)}})}startDrag(t){if(!this.note.canEdit||this.note.id<=0)return;const n=zR();if(!n)return;t.preventDefault(),this.element.ownerDocument.defaultView?.getSelection()?.removeAllRanges();const o=this.buildGhost(),s=this.element.getBoundingClientRect(),i={noteId:this.note.id,canEdit:this.note.canEdit,updatedAtMs:this.note.updatedAtMs};n.start({payload:{type:qn,source:this.element,data:i,ghost:{element:o.root,offsetX:o.tipX,offsetY:o.tipY,hint:{neutral:E("Drop on the desktop to pin","desktop-mode"),accept:E("Pin here","desktop-mode"),reject:E("Can’t pin here","desktop-mode")}}},origin:t,onClickOnly:()=>{this.teardownDragListeners(),this.toggleMoveMode()},onCancel:()=>{this.teardownDragListeners(),this.snapBack(s)},onCommit:()=>{this.teardownDragListeners(),this.layer.has(this.note.id)&&this.playInsertion(.7)}})&&this.installDragListeners(o)}buildGhost(){const t=this.element.getBoundingClientRect(),o=(this.pinEl.querySelector("img")??this.pinEl).getBoundingClientRect(),s=o.left-t.left+o.width*mR,i=o.top-t.top+o.height*gR,r=document.createElement("div");r.className="os-pinned-note-ghost",r.style.width=`${t.width}px`,r.style.height=`${t.height}px`;const a=document.createElement("div");a.className="os-pinned-note-ghost__swing",a.style.transformOrigin=`${s}px ${i}px`;const l=this.pinEl.cloneNode(!0);l.removeAttribute("aria-pressed"),l.setAttribute("aria-hidden","true");const c=this.paperEl.cloneNode(!0);return c.classList.add("os-pinned-note-ghost__paper"),a.dataset.noteColor=this.element.dataset.noteColor??"",a.append(l,c),r.appendChild(a),{root:r,swing:a,pin:l,paper:c,tipX:s,tipY:i}}installDragListeners(t){this.teardownDragListeners();let n=null;const o=a=>{a.detail?.payload?.data?.noteId===this.note.id&&(n=uR(t.swing))},s=a=>{const l=a.detail;this.lastPointer={x:l.clientX,y:l.clientY},n?.onPointerMove(l.clientX)},i=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.add("os-pinned-note-ghost--doom"),n?.setBias(6))},r=a=>{a.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.remove("os-pinned-note-ghost--doom"),n?.setBias(0))};document.addEventListener(be.START,o),document.addEventListener(be.MOVE,s),document.addEventListener(be.ENTER,i),document.addEventListener(be.LEAVE,r),this.dragCleanup=()=>{n?.stop(),n=null,document.removeEventListener(be.START,o),document.removeEventListener(be.MOVE,s),document.removeEventListener(be.ENTER,i),document.removeEventListener(be.LEAVE,r)}}teardownDragListeners(){this.dragCleanup?.(),this.dragCleanup=null}async snapBack(t){if(!this.lastPointer||jn()){this.playInsertion(.63);return}const n=this.buildGhost();n.root.classList.add("os-pinned-note-ghost--flyback"),n.root.style.position="fixed",n.root.style.left=`${this.lastPointer.x-n.tipX}px`,n.root.style.top=`${this.lastPointer.y-n.tipY}px`,n.root.style.zIndex="2147483647",n.root.style.pointerEvents="none",document.body.appendChild(n.root);try{await fR({flyback:n.root,swing:n.swing,homeX:t.left,homeY:t.top})}finally{n.root.remove()}this.playInsertion(.63)}async playCrumpleAt(t,n){const o=this.buildGhost();o.root.classList.add("os-pinned-note-ghost--flyback"),o.root.style.position="fixed",o.root.style.left=`${t-o.tipX}px`,o.root.style.top=`${n-o.tipY}px`,o.root.style.zIndex="2147483647",o.root.style.pointerEvents="none",document.body.appendChild(o.root);try{await pR({clone:o.root,pin:o.pin,paper:o.paper,binX:t,binY:n+24})}finally{o.root.remove()}}toggleMoveMode(){this.moveMode?this.exitMoveMode(!0):this.enterMoveMode()}enterMoveMode(){this.note.canEdit&&(this.moveMode=!0,this.moveOrigin={x:this.note.x,y:this.note.y},this.element.classList.add("os-pinned-note--move-mode"),this.pinEl.setAttribute("aria-pressed","true"),this.layer.announce(E("Moving note. Arrow keys to move, Enter to place, Escape to cancel, Delete to move to the Trash.","desktop-mode")))}exitMoveMode(t){this.moveMode&&(this.moveMode=!1,this.element.classList.remove("os-pinned-note--move-mode"),this.pinEl.setAttribute("aria-pressed","false"),t?(this.moveTo(this.note.x,this.note.y),this.layer.announce(E("Note placed.","desktop-mode")),this.playInsertion(.7)):this.moveOrigin&&(this.note={...this.note,...this.moveOrigin},this.applyPosition()),this.moveOrigin=null)}onPinKeydown(t){if(!this.moveMode)return;const{width:n,height:o}=this.layer.hostSize(),s=t.shiftKey?HR:BR,i=s/n,r=s/o;switch(t.key){case"ArrowLeft":this.nudge(-i,0);break;case"ArrowRight":this.nudge(i,0);break;case"ArrowUp":this.nudge(0,-r);break;case"ArrowDown":this.nudge(0,r);break;case"Enter":case" ":this.exitMoveMode(!0);break;case"Escape":this.exitMoveMode(!1),this.layer.announce(E("Move cancelled.","desktop-mode"));break;case"Delete":case"Backspace":this.exitMoveMode(!1),this.confirmTrash();break;default:return}t.preventDefault(),t.stopPropagation()}nudge(t,n){const o=this.layer.clampPosition(this.note.x+t,this.note.y+n);this.note={...this.note,...o},this.applyPosition()}}const os=new Map;function KR(e,t){return os.set(e,t),()=>{os.get(e)===t&&os.delete(e)}}function YR(e){const t=os.get(e.type);return t?t.accept(e.data):!1}function XR(e,t){const n=os.get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}function Wy(e,t,n){const o=e.host.getBoundingClientRect(),s=t.payload.ghost?.offsetX??0,i=t.payload.ghost?.offsetY??0,{width:r,height:a}=e.hostSize();return e.clampPosition((n.clientX-s-o.left)/r,(n.clientY-i-o.top)/a)}function ZR(e,t,n){const o=t.payload.data,s=String(o.text??"");if(!s.trim())return;const{x:i,y:r}=Wy(e,t,n);e.createNoteAt({x:i,y:r,text:s,color:String(o.color??""),isPublic:o.isPublic===!0})}function JR(e,t,n){const o=t.payload.data,s=e.get(o.noteId);if(!s)return;const{x:i,y:r}=Wy(e,t,n);s.moveTo(i,r)}function QR(e){const t=[],n=o=>o.folderId===0;return t.push(Hw(RR,{accept:(o,s)=>n(s)&&!!String(o.text??"").trim(),onDrop:(o,s)=>ZR(e,o,s)})),t.push(Hw(qn,{accept:(o,s)=>n(s)&&o.canEdit===!0,onDrop:(o,s)=>JR(e,o,s)})),t.push(KR(qn,{accept:o=>o.canEdit===!0,onDrop:(o,s)=>{const i=o.payload.data,r=e.get(i.noteId);if(!r)return;const a=r.note;r.playCrumpleAt(s.clientX,s.clientY),e.trashNote(a)}})),()=>{t.forEach(o=>o())}}const Fc="data-os-posts-drop-active",$y="desktop-mode-posts",eO='.os-dock__item[data-menu-slug="menu-posts"],.os-dock__item[data-menu-slug="editphp"]',tO="[data-os-posts-root]";function nO(){return window.wp?.os?.dragManager??null}function oO(e){return e.type!==qn?!1:e.data.canEdit===!0}function sO(e){if(!e)return!1;let t=e,n="";try{const i=new URL(e,window.location.origin);t=i.pathname,n=i.search}catch{}if(!(/(?:^|\/)(?:edit\.php|post-new\.php)$/.test(t)||!t.includes("/")&&(t==="edit.php"||t==="post-new.php")))return!1;const s=new URLSearchParams(n).get("post_type");return!s||s==="post"}function iO(e){const t=e.placement.file;if(!t||t.type!=="shortcut")return!1;const n=typeof t.shortcutUrl=="string"?t.shortcutUrl:"";return sO(n)}function Uy(e,t){if(t.payload.type!==qn)return;const n=t.payload.data;if(typeof n.noteId!="number")return;const o=e.get(n.noteId);o&&e.convertNote(o.note)}let Fy=!1,ss=null,is=null,By=null;function Hy(e,t,n,o){return e.registerDropTarget({id:n,element:o,acceptLabel:E("Convert to post","desktop-mode"),accept:s=>oO(s),onEnter:()=>{o.setAttribute(Fc,"")},onLeave:()=>{o.removeAttribute(Fc)},onDrop:s=>{o.removeAttribute(Fc),Uy(t,s)}})}function rO(e,t){const n=e.debug().listTargets().find(o=>o.id===t);return n?n.element:null}function aO(e){if(Fy||!e.canCreatePosts)return;const t=nO();if(!t)return;Fy=!0,Ki(qn,{appliesTo:o=>iO(o),acceptLabel:E("Convert to post","desktop-mode"),accept:o=>o.canEdit===!0,onDrop:o=>Uy(e,o)});const n=()=>{const o=document.querySelector(eO);if(!(o instanceof HTMLElement)){ss?.(),ss=null;return}ss&&rO(t,"notes-convert-dock")===o||(ss?.(),ss=Hy(t,e,"notes-convert-dock",o))};n(),Y(v.DOCK_AFTER_RENDER,"desktop-mode/notes/convert-dock-target",n),typeof MutationObserver<"u"&&(By=new MutationObserver(()=>{n()}),By.observe(document.body,{childList:!0,subtree:!0})),Y(v.WINDOW_OPENED,"desktop-mode/notes/convert-window-target",o=>{if(o.windowId!==$y)return;is?.(),is=null;const s=document.querySelector(tO);s instanceof HTMLElement&&(is=Hy(t,e,"notes-convert-window",s))}),Y(v.WINDOW_CLOSED,"desktop-mode/notes/convert-window-cleanup",o=>{o.windowId===$y&&(is?.(),is=null)})}const zy="new-note";function lO(e){Xn("os.wallpaper-context-menu","desktop-mode/notes",(t,n)=>{if(!Array.isArray(t)||t.some(i=>i.id===zy))return t;const{x:o,y:s}=n??{x:0,y:0};return[...t,{id:zy,label:E("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{const i=e.normalizedFromClient(o,s);e.createNoteAt({...i,focus:!0})}}]})}function cO(e){const t=e.config.notesUrl;if(typeof t!="string"||!t)return null;_R({baseUrl:t,nonce:e.config.restNonce??""});const n=new VR({host:e.host,pluginUrl:e.config.pluginUrl??"",canCreatePosts:e.config.canCreatePosts??!1,onError:e.onError});return QR(n),aO(n),lO(n),document.addEventListener(OR,o=>{const s=o.detail?.note;if(s&&typeof s.id=="number"){n.bumpHighWater(s.updatedAtMs);const i=n.upsertNote(s,{animate:"thunk"});n.bringToFront(i),i.focusEditor()}}),n.boot(),n}const dO={id:"clock",get label(){return E("Clock")},get description(){return E("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 uO(){dl(dO)}async function fO(){const e=window;if(e.openStationReleaseCard)return e.openStationReleaseCard;const t=e.openStationConfig?.releaseCardBundleUrl??"";if(!t)return null;try{await ke(t)}catch{return null}return e.openStationReleaseCard??null}function Gy(e,t){if(t){const o=E('WordPress %1$s "%2$s" is available.');return de(o,e,t)}const n=E("WordPress %s is available.");return de(n,e)}async function pO(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(Ci(a))return;const l=`${a}:no-art`,c=()=>n({url:t.url,title:E("WordPress Updates")}),u=e.resolveArt&&e.loadImage&&e.showCard?null:await fO(),f=e.resolveArt??u?.resolveReleaseArt,p=e.loadImage??u?.preloadImage,g=e.showCard??u?.showReleaseCard,m=f?await f(s,i):null;if(m&&m.artUrl&&p&&g&&await p(m.artUrl)){g({message:Gy(o,i?m.name:""),artUrl:m.artUrl,dismissKey:a,onUpdate:c});return}Ci(l)||Q({message:Gy(o,""),persistent:!0,dismissible:!0,onDismiss:()=>Ii(l),action:{label:E("Update now"),onClick:c}})}function jy(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(Ci(i))continue;const r=s.actionLabel,a=s.actionUrl,l=s.title||r||"";let c;r&&a&&(c={label:r,onClick:()=>n({url:a,title:l})}),Q({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>Ii(i),action:c})}}const Bc="desktop-mode/starter",hO="desktop-mode/dev-mode-gate";let Vy=!1;function mO({osSettings:e,layer:t}){if(Vy)return;Vy=!0,Xn(v.WIDGETS,hO,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==Bc));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(Bc):t.unmount(Bc),xi())})}function gO(e){const{layer:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await ke(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter})}catch(d){T(v.SHELL_ERROR,{scope:"widget-script-load",id:c.id,error:d});return}o.add(c.scriptUrl)}},i=c=>(window.openStationWidgets||{})[c]??null,r=c=>({id:c.id,label:c.label,description:c.description,icon:c.icon,movable:c.movable,resizable:c.resizable,minWidth:c.minWidth||void 0,minHeight:c.minHeight||void 0,maxWidth:c.maxWidth||void 0,maxHeight:c.maxHeight||void 0,defaultWidth:c.defaultWidth||void 0,defaultHeight:c.defaultHeight||void 0,mount:async(d,u)=>{await s(c);const f=i(c.id);if(!f){const p=new Error(`[openstation] No mount callback on window.openStationWidgets["${c.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`);throw T(v.SHELL_ERROR,{scope:"widget-missing-mount",id:c.id,error:p}),p}return f(d,u)}}),a=async c=>{if(n.has(c.id))return;const d=r(c);try{dl(d)}catch(u){T(v.SHELL_ERROR,{scope:"widget-register",id:c.id,error:u});return}n.add(c.id),xi(),t&&t.mountIfEnabled(c.id)},l=c=>{n.has(c)&&(t?.unmount(c),PC(c),n.delete(c),xi())};return async c=>{const d=new Set;for(const u of c)d.add(u.id);for(const u of Array.from(n))d.has(u)||l(u);for(const u of c)n.has(u.id)||await a(u)}}const qy=new Set(Hi),wO=2e3,Hc=new Set,Ky=new WeakSet;let Yy=!1;function yO(e,t){const n=e.length,o=t.length;if(n===0)return o;if(o===0)return n;const s=new Array(o+1);for(let i=0;i<=o;i++)s[i]=i;for(let i=1;i<=n;i++){let r=s[0];s[0]=i;for(let a=1;a<=o;a++){const l=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=l}}return s[o]}function bO(e){let t=null,n=1/0;for(const o of qy){const s=yO(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function vO(e){return e.startsWith("os-")?e.slice(4):e}function _O(e,t){if(Hc.has(e))return;if(Hc.add(e),qy.has(e)){const s=vO(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. | |
| 33 | + `}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};Js.props=["tone","notDismissible","icon","noticeId"],Js.styles=[pN],Js.help=void 0;let il=Js;Jo("os-notice",il);const fs=ae("desktop-mode/window-notices",()=>({entries:new Map})),hN=/^[a-z0-9_/-]+$/;function Og(e){return`os-notice/${e.toLowerCase()}`}function mN(e){const t=document.createElement("os-notice");return t.setAttribute("tone",e.tone??"info"),t.setAttribute("notice-id",e.id),e.dismissible===!1&&t.setAttribute("not-dismissible",""),e.icon&&t.setAttribute("icon",e.icon),t.innerHTML=e.message,t}function Dg(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!hN.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};fs.state.entries.set(t,n);const o=Og(t);return Ag({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=fs.state.entries.get(t);if(!i)return!1;if(typeof i.match!="function")return!0;try{return i.match(s)===!0}catch{return!1}},render:s=>{const i=fs.state.entries.get(t);i&&s.appendChild(mN(i))}}),()=>rl(t)}function rl(e){const t=String(e??"").trim().toLowerCase();t&&fs.state.entries.delete(t)&&nl(Og(t))}function Rg(){return Array.from(fs.state.entries.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function gN(e){const t=String(e??"").trim().toLowerCase();t&&nr(t)}function wN(e){const t=String(e??"").trim().toLowerCase();t&&Ng(t)}function yN(e){if(!e)return;const t=new Set;if(typeof e.window=="string"&&e.window!==""&&t.add(e.window),Array.isArray(e.windows))for(const o of e.windows)typeof o=="string"&&o!==""&&t.add(o);const n=typeof e.urlContains=="string"&&e.urlContains!==""?e.urlContains.toLowerCase():null;if(!(t.size===0&&n===null))return o=>!(t.size>0&&!t.has(o.id)||n!==null&&!(typeof o.config.url=="string"?o.config.url.toLowerCase():"").includes(n))}function xg(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),Dg({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:yN(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of Rg())n.owner==="__server__"&&(t.has(n.id)||rl(n.id))}const Mg=ae("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),ps=Mg.state.registry,vN=Mg.state.listeners,Wg=/^[a-z0-9_/-]+$/;function bN(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Wg.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Wg} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Oe("WindowChrome",t,e);const n=e.id.trim().toLowerCase();ps.set(n,{...e,id:n}),al()}function Pg(e){ps.delete(e.toLowerCase())&&al()}function EN(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(ps.entries()))o.owner===e&&(ps.delete(n),t++);return t>0&&al(),t}function $g(){return Array.from(ps.values()).sort((e,t)=>e.id.localeCompare(t.id))}function al(){const e=Array.from(vN);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function _N(){const e=new Set,t=new Set;let n=new Map;const o=async r=>{if(!r.scriptUrl||t.has(r.scriptUrl)){e.add(r.handle);return}try{await pe(r.scriptUrl,{translations:r.scriptTranslations,deps:r.scriptDeps,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(a){A(v.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:a});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const a=new Map;if(!r)return a;for(const l of r){if(!l.scriptHandle||!l.id)continue;let c=a.get(l.scriptHandle);c||(c=new Set,a.set(l.scriptHandle,c)),c.add(l.id)}return a},i=r=>{const a=new Set;for(const c of $g())c.owner===r&&a.add(c.id);const l=n.get(r);if(l)for(const c of l)a.add(c);return a};return async(r,a)=>{const l=new Set;for(const c of r)c.handle&&l.add(c.handle);for(const c of Array.from(e))if(!l.has(c)){for(const d of i(c))Pg(d);EN(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(a)}}const cl=window.location.origin,Te=ae("desktop-mode/connection",()=>({connSeq:0,connections:new Map,connectionsByTarget:new Map,syntheticIframes:new Map}));function SN(e,t){const{syntheticIframes:n}=Te.state;return n.set(e,t),()=>{n.get(e)===t&&n.delete(e)}}function kN(){return`os-conn-${++Te.state.connSeq}`}function IN(e){const t=(l,c)=>{try{l.contentWindow?.postMessage(c,cl)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(l,c={})=>{const d=kN(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let g=!1,h=!1;const m=()=>{const W=Te.state.syntheticIframes.get(l);return W||(e.getById(l)?.iframe??null)},_=()=>{if(m())return!1;const W=e.getById(l);return!!W&&W.config?.native===!0},I=[],O=()=>{const W=m();if(W)for(;p.length;){const U=p.shift();t(W,{type:"os-bridge-publish",connectionId:d,topic:U.topic,payload:U.payload})}},$={id:d,target:l,isOpen:()=>g,subscribe(W,U){const F=U;if(_()){const Q=_S(l,W,(Z,C)=>{A(v.CONNECTION_MESSAGE,{connectionId:d,topic:C.channel,direction:"in"});try{F(Z,{topic:C.channel})}catch(D){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",D)}});return I.push(Q),Q}let K=f.get(W);return K||(K=new Set,f.set(W,K)),K.add(F),()=>{K?.delete(F)}},send(W,U){if(h)return;if(A(v.CONNECTION_MESSAGE,{connectionId:d,topic:W,direction:"out"}),_()){kS(l,W,U);return}if(!g){p.push({topic:W,payload:U});return}const F=m();F&&t(F,{type:"os-bridge-publish",connectionId:d,topic:W,payload:U})},disconnect(){$._destroy("disconnect")},_targetWindow:m,_handleIframeMessage(W){if(!W||typeof W!="object")return;const U=W;if(U.type==="os-bridge-handshake-ack"){if(g)return;g=!0,A(v.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u,connection:$});try{c.onOpen?.()}catch(F){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",F)}O();return}if(U.type==="os-bridge-publish"){const F=W,K=typeof F.topic=="string"?F.topic:"";if(!K)return;A(v.CONNECTION_MESSAGE,{connectionId:d,topic:K,direction:"in"});const Q=f.get(K);if(Q)for(const C of Array.from(Q))try{C(F.payload,{topic:K})}catch(D){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",D)}const Z=f.get("*");if(Z)for(const C of Array.from(Z))try{C(F.payload,{topic:K})}catch(D){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",D)}return}U.type==="os-bridge-disconnect"&&$._destroy("disconnect")},_destroy(W){if(h)return;h=!0;const U=g;g=!1,Te.state.connections.delete(d);const F=Te.state.connectionsByTarget.get(l);F&&(F.delete(d),F.size===0&&Te.state.connectionsByTarget.delete(l));for(const K of I.splice(0))try{K()}catch{}if(U){const K=m();K&&t(K,{type:"os-bridge-disconnect",connectionId:d})}A(v.CONNECTION_CLOSED,{connectionId:d,reason:W});try{c.onClose?.(W)}catch(K){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",K)}}};Te.state.connections.set(d,$);let S=Te.state.connectionsByTarget.get(l);if(S||(S=new Set,Te.state.connectionsByTarget.set(l,S)),S.add(d),_())return Promise.resolve().then(()=>{if(!(h||g)){g=!0,A(v.CONNECTION_OPENED,{connectionId:d,targetWindowId:l,topics:u});try{c.onOpen?.()}catch(W){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",W)}}}),$;const R=m();return R&&t(R,{type:"os-bridge-handshake",connectionId:d,targetWindowId:l,topics:u}),$},o=(l,c)=>{if(!l||typeof l!="object")return;const d=l;if(typeof d.type!="string"||!d.type.startsWith("os-bridge-"))return;if(d.type==="os-bridge-connection-request"&&typeof d.requestId=="string"&&typeof c=="string"&&c!==""){s(c,d.requestId,Array.isArray(d.topics)?d.topics:[]);return}if(typeof d.connectionId!="string")return;Te.state.connections.get(d.connectionId)?._handleIframeMessage(l)},s=(l,c,d)=>{const f=Te.state.syntheticIframes.get(l)??e.getById(l)?.iframe??null;if(!f)return;const p=J(v.IFRAME_CONNECTION_REQUEST,!0,{windowId:l,requestId:c,topics:d.slice()});if(p===!1){try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!1,reason:"rejected"},cl)}catch{}return}const g=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,h=n(l,{topics:g});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:h.id},cl)}catch{}};return{connect:n,getConnection:l=>Te.state.connections.get(l)??null,routeIncomingFromIframe:o,onIframeReady:l=>{const c=Te.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c)){const u=Te.state.connections.get(d);if(!u||u.isOpen())continue;const f=u._targetWindow();f&&t(f,{type:"os-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:l=>{const c=Te.state.connectionsByTarget.get(l);if(c)for(const d of Array.from(c))Te.state.connections.get(d)?._destroy("window-closed")}}}const AN={};function CN(...e){(typeof{url:sa&&sa.tagName.toUpperCase()==="SCRIPT"&&sa.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&AN?"production":void 0)!=="production"&&console.log(...e)}const LN="iframe:";function ll(e){return LN+e}function Ug(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function TN(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}const NN=250;class ON{constructor(t){this.streamingWindowId=null,this.focusedWindowId=null,this.paletteOpen=!1,this.closeGraceTimer=null,this.manager=t.manager,this.adminUrl=t.adminUrl}install(){document.addEventListener("os-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&this.onFocused(o.windowId)}),document.addEventListener("os-window-closed",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&(Xi(ll(o.windowId)),this.streamingWindowId===o.windowId&&(this.streamingWindowId=null),this.focusedWindowId===o.windowId&&(this.focusedWindowId=null))}),document.addEventListener("os-palette-opened",()=>{this.onPaletteOpened()}),document.addEventListener("os-palette-closed",()=>{this.onPaletteClosed()}),document.addEventListener("os-window-changed",n=>{const o=n.detail;!o||typeof o.windowId!="string"||o.reason==="state"&&o.state==="minimized"&&(this.streamingWindowId===o.windowId&&this.stopStreaming(),this.focusedWindowId===o.windowId&&(this.focusedWindowId=null))}),window.addEventListener("message",n=>{if(n.origin!==window.location.origin)return;const o=n.data;if(!o||typeof o.type!="string")return;if(o.type==="os-bridge-ready"){const i=this.manager.findByIframeSource(n.source);i&&i.id===this.streamingWindowId&&this.sendSubscribe(i.id);return}if(o.type!=="os-commands-list"||!Array.isArray(o.commands))return;const s=this.manager.findByIframeSource(n.source);s&&s.id===this.streamingWindowId&&this.applyList(s.id,o.commands)});const t=this.manager.getFocused();t&&(this.focusedWindowId=t.id)}onFocused(t){const n=!this.paletteOpen||this.streamingWindowId===t;this.focusedWindowId===t&&n||(this.focusedWindowId&&this.focusedWindowId!==t&&Xi(ll(this.focusedWindowId)),this.streamingWindowId&&this.streamingWindowId!==t&&this.stopStreaming(),this.focusedWindowId=t,this.paletteOpen&&this.startStreaming(t))}onPaletteOpened(){this.paletteOpen=!0,this.closeGraceTimer!==null&&(window.clearTimeout(this.closeGraceTimer),this.closeGraceTimer=null),this.focusedWindowId&&this.startStreaming(this.focusedWindowId)}onPaletteClosed(){this.paletteOpen=!1,this.closeGraceTimer!==null&&window.clearTimeout(this.closeGraceTimer),this.closeGraceTimer=window.setTimeout(()=>{this.closeGraceTimer=null,this.stopStreaming()},NN)}startStreaming(t){this.streamingWindowId!==t&&(this.stopStreaming(),this.streamingWindowId=t,this.sendSubscribe(t))}stopStreaming(){if(!this.streamingWindowId)return;const t=this.manager.getById(this.streamingWindowId);if(this.streamingWindowId=null,t&&t.iframe&&t.iframe.contentWindow)try{t.iframe.contentWindow.postMessage({type:"os-commands-unsubscribe"},window.location.origin)}catch{}}sendSubscribe(t){const n=this.manager.getById(t);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"os-commands-subscribe"},window.location.origin)}catch(o){CN("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=ll(t);Xi(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=TN(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?lu(s.iconSvg):"",a={slug:i,label:s.label,icon:Ug(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,Ug(s)):this.runProxy(t,s.name)};try{Xn(a)}catch(l){console.error("[openstation] iframe-bridge: dropping bad command",a,l)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Me(t))return;const r=fe(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runProxy(t,n){return(o,s)=>{s.close();const i=this.manager.getById(t);if(!(!i||!i.iframe||!i.iframe.contentWindow)){try{i.iframe.contentWindow.postMessage({type:"os-commands-invoke",name:n},window.location.origin)}catch{}this.manager.focus(i)}}}}function DN(e){const t=(n,o)=>{const s=e.getById(n);if(!(!s||!s.iframe||!s.iframe.contentWindow))try{s.iframe.contentWindow.postMessage({type:"os-window-active",active:o},window.location.origin)}catch{}};document.addEventListener("os-window-focused",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&t(o.windowId,!0)}),document.addEventListener("os-window-blurred",n=>{const o=n.detail;o&&typeof o.windowId=="string"&&t(o.windowId,!1)}),window.addEventListener("message",n=>{if(n.origin!==window.location.origin)return;const o=n.data;if(!o||o.type!=="os-bridge-ready")return;const s=e.findByIframeSource(n.source);s&&t(s.id,e.getFocused()?.id===s.id)})}const Bg="global",RN=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,xN=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,MN=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,WN=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,PN=/getSiteEditorPage\s*\(|site-editor\.php/,Fg=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function $N(e){const t=e.match(Fg)?.[1];return{wp_template:b("Edit template"),wp_template_part:b("Edit template part"),wp_navigation:b("Edit navigation menu"),wp_block:b("Edit pattern")}[t??""]}function UN(e){const t=window.__openStationMenuCommands;if(!Array.isArray(t))return null;for(const n of t)if(n&&typeof n=="object"&&n.name===e&&typeof n.url=="string"&&n.url!=="")return{label:typeof n.label=="string"?n.label:"",url:n.url};return null}class BN{constructor(t){this.mounted=!1,this.host=null,this.root=null,this.kindCache=Object.create(null),this.callbackCache=Object.create(null),this.lastFingerprint="",this.manager=t.manager,this.adminUrl=t.adminUrl}install(){this.tryMount(0)}tryMount(t){if(this.mounted)return;const n=window.wp;if(!n||!n.data||!n.element||typeof n.data.subscribe!="function"){t<40&&window.setTimeout(()=>this.tryMount(t+1),150);return}this.mount()}mount(){const t=window.wp,n=t.element,o=t.data,s=n.createElement,i=n.useEffect,r=n.useRef,a=n.useMemo,l=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof a!="function"||typeof l!="function"||typeof n.createRoot!="function")return;this.mounted=!0;const c=document.createElement("div");c.setAttribute("aria-hidden","true"),c.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;left:-9999px;top:-9999px;",(document.body||document.documentElement).appendChild(c),this.host=c;const d={perLoader:{},statics:[],loadersList:[]},u=h=>{if(!Array.isArray(h)||h.length===0)return"";const m=new Array(h.length);for(let _=0;_<h.length;_++){const I=h[_];m[_]=I&&I.name?I.name:""}return m.join("|")},f=()=>{let h=[];for(const m of d.loadersList){const _=d.perLoader[m];Array.isArray(_)&&(h=h.concat(_))}Array.isArray(d.statics)&&(h=h.concat(d.statics)),this.callbackCache=Object.create(null);for(const m of h)m&&m.name&&typeof m.callback=="function"&&(this.callbackCache[m.name]=m.callback);this.publish(h)},p=h=>{const m=h.loader;let _=null;try{_=m.hook({search:""})}catch{}const I=_&&Array.isArray(_.commands)?_.commands:[],O=a(()=>u(I),[I]);return i(()=>{d.perLoader[m.name]=I,f()},[O]),i(()=>()=>{delete d.perLoader[m.name],f()},[]),null},g=()=>{const h=l(S=>{const R=S("core/commands");return!R||typeof R.getCommandLoaders!="function"?[]:[...R.getCommandLoaders(!1)||[],...R.getCommandLoaders(!0)||[]]},[]),m=l(S=>{const R=S("core/commands");return!R||typeof R.getCommands!="function"?[]:[...R.getCommands(!1)||[],...R.getCommands(!0)||[]]},[]),_=a(()=>Array.isArray(h)?h.map(S=>S&&S.name||""):[],[h]),I=_.join("|");i(()=>{d.loadersList=_,f()},[I]);const O=a(()=>u(Array.isArray(m)?m:[]),[m]);if(i(()=>{d.statics=Array.isArray(m)?m:[],f()},[O]),!Array.isArray(h)||h.length===0)return null;const $=[];for(const S of h)!S||typeof S.hook!="function"||$.push(s(p,{key:S.name,loader:S}));return s(n.Fragment||"div",null,$)};try{this.root=n.createRoot(c),this.root.render(s(g))}catch{this.mounted=!1,this.root=null,this.host&&this.host.parentNode&&this.host.parentNode.removeChild(this.host),this.host=null}}publish(t){const n=Object.create(null),o=[];for(const i of t)!i||!i.name||!i.label||i.disabled||n[i.name]||(n[i.name]=!0,o.push(this.classify(i)));let s="";for(const i of o)s+=`${i.name}|${i.kind}|${i.url||""} | |
| 34 | +`;if(s!==this.lastFingerprint){this.lastFingerprint=s,Xi(Bg);for(const i of o){if(i.kind==="skip")continue;const r=`global-${i.name.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}`,a=this.iconFor(i),l={slug:r,label:i.label,description:i.kind==="navigate"?$N(i.name):void 0,icon:a,iconSvg:i.iconSvg&&i.iconSvg!==""?lu(i.iconSvg):void 0,owner:Bg,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,a):this.runInvoke(i.name)};try{Xn(l)}catch(c){console.error("[openstation] shell-harvester: dropping bad command",l,c)}}}}classify(t){const n={name:String(t.name),label:String(t.label),icon:typeof t.icon=="string"?t.icon:void 0,iconSvg:void 0,kind:"action",url:void 0,callback:typeof t.callback=="function"?t.callback:void 0},o=this.kindCache[n.name];if(o)return n.kind=o.kind,n.url=o.url,n.iconSvg=o.iconSvg,n;t.icon&&typeof t.icon!="string"&&(n.iconSvg=this.renderIcon(t.icon));const s=UN(n.name);if(s){try{n.url=new URL(s.url,this.adminUrl).toString(),n.kind="navigate",s.label!==""&&(n.windowTitle=s.label)}catch{n.kind="skip"}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}if(typeof t.callback=="function"){let i="";try{i=Function.prototype.toString.call(t.callback)}catch{i=""}const r=i.match(RN)||i.match(xN)||i.match(MN);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(WN.test(i)){const l=PN.test(i)?n.name.match(Fg):null;if(l){const c=l[1],d=l[2],u=`/${c}/${d}`;try{const f=new URL("site-editor.php",this.adminUrl);f.searchParams.set("p",u),f.searchParams.set("canvas","edit"),n.url=f.toString(),n.kind="navigate"}catch{n.kind="skip"}}else n.kind="skip"}}return this.kindCache[n.name]={kind:n.kind,url:n.url,iconSvg:n.iconSvg},n}renderIcon(t){const n=window.wp;if(!n||!n.element||typeof n.element.renderToString!="function")return"";try{const o=n.element.renderToString(t);if(typeof o=="string"&&o.toLowerCase().startsWith("<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(),Me(t))return;const r=fe(t,this.adminUrl);this.manager.open({id:r,baseId:r,url:t,title:n,icon:o})}}runInvoke(t){return(n,o)=>{const s=this.callbackCache[t];if(typeof s!="function")throw new Error(le(b("No live callback for command “%s” — the palette and the command registry are out of step. Reload the page."),t));s({close:()=>o.close()})}}}const Hg="os-command-palette-ready";let hs=null;function FN(){const t=window.openStationConfig?.commandPalette;return!t||!Array.isArray(t.scripts)?null:t}function HN(){const e=window.wp;try{return!!e?.data?.select?.("core/commands")}catch{return!1}}function GN(e){if(!e.url)return;const t=e.url.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(document.head.querySelector(`link[rel="stylesheet"][href="${t}"]`))return;const n=document.createElement("link");n.rel="stylesheet",n.href=e.url,n.dataset.osPaletteStyle=e.handle,document.head.appendChild(n);for(const o of e.inline??[]){if(typeof o!="string"||o==="")continue;const s=document.createElement("style");s.dataset.osPaletteStyle=e.handle,s.textContent=o,document.head.appendChild(s)}}function zN(e){const t=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(document.head.querySelector(`link[rel="preload"][href="${t}"]`))return;const n=document.createElement("link");n.rel="preload",n.as="script",n.href=e,document.head.appendChild(n)}async function jN(){const e=FN();if(!e||e.scripts.length===0)return HN();for(const s of e.styles??[])GN(s);const t=new Set,o=e.scripts.filter(s=>{const i=s.handle||s.url;return!i||t.has(i)?!1:(t.add(i),!0)}).filter(s=>!s.url||!yc(s));for(const s of o)s.url&&zN(s.url);for(const s of o)if(s.url)await pe(s.url,{handle:s.handle,translations:s.translations,l10n:s.l10n,before:s.before,after:s.after});else for(const i of[s.translations??"",...s.l10n??[],...s.before??[],...s.after??[]])typeof i=="string"&&i!==""&&Nh(i);return document.dispatchEvent(new CustomEvent(Hg)),!0}function VN(){return hs||(hs=jN().catch(e=>{throw hs=null,e}),hs)}const Jn=[];function dl(e){Oe("Widget",Yt(e,Gg),e);const t=Jn.findIndex(n=>n.id===e.id);t>=0?Jn[t]=e:Jn.push(e)}function KN(e){const t=Jn.findIndex(n=>n.id===e);t>=0&&Jn.splice(t,1)}function ul(){const e=Jn.slice(),t=J(v.WIDGETS,e);return Array.isArray(t)?t.filter(qN):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function Qn(e){return ul().find(t=>t.id===e)}const Gg=[{field:"id",message:"missing or not a non-empty string",valid:e=>typeof e.id=="string"&&e.id!==""},{field:"label",message:"missing or not a non-empty string",valid:e=>typeof e.label=="string"&&e.label!==""},{field:"description",message:"not a string",valid:e=>typeof e.description=="string"},{field:"icon",message:"missing or not a non-empty string",valid:e=>typeof e.icon=="string"&&e.icon!==""},{field:"mount",message:"not a function",valid:e=>typeof e.mount=="function"}];function qN(e){return Yt(e,Gg).length===0}let Qe=null;function YN(e){if(Qe)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",b("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=b("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),zg(o,e),document.body.appendChild(t),XN(t,e.anchor);const s=a=>{const l=a.target;l&&(t.contains(l)||e.anchor.contains(l)||fl())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=a=>{a.key==="Escape"&&fl()};document.addEventListener("keydown",i),Qe={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function ms(){if(!Qe)return;const e=Qe.panel.querySelector(".os-widget-picker__list");e&&zg(e,Qe.options)}function fl(){if(!Qe)return;document.removeEventListener("pointerdown",Qe.onOutsidePointerDown,!0),document.removeEventListener("keydown",Qe.onKeyDown),Qe.panel.remove();const{onClose:e}=Qe.options;Qe=null,e?.()}function zg(e,t){e.innerHTML="";const n=new Set(t.enabledIds()),o=t.registry();if(o.length===0){const s=document.createElement("div");s.className="os-widget-picker__empty",s.textContent=b("No widgets available. Activate a plugin that registers one, or see the docs for the registerWidget API."),e.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="os-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("os-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let a;r?a=le(b("%s (already added)"),s.label):a=le(b("Add %s"),s.label),i.setAttribute("aria-label",a);const l=document.createElement("span");l.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,l.setAttribute("aria-hidden","true"),i.appendChild(l);const c=document.createElement("span");c.className="os-widget-picker__entry-text";const d=document.createElement("span");if(d.className="os-widget-picker__entry-label",d.textContent=s.label,c.appendChild(d),s.description){const u=document.createElement("span");u.className="os-widget-picker__entry-description",u.textContent=s.description,c.appendChild(u)}if(i.appendChild(c),r){const u=document.createElement("span");u.className="os-widget-picker__entry-status",u.textContent=b("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function XN(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px",e.style.visibility="hidden";const o=e.getBoundingClientRect(),s=o.width||320,i=o.height||200,r=6;let a=n.right-s,l=n.top-i-r;a<8&&(a=8),l<8&&(l=n.bottom+r),e.style.left=`${Math.round(a)}px`,e.style.top=`${Math.round(l)}px`,e.style.visibility=""}const or="os-widgets__card--floating",ZN="os-widgets__card--movable",JN="os-widgets__card--resizable",jg="os-widgets__card--dragging",Vg="os-widgets__card--resizing",QN=160,Kg=80,eO=280,tO=180,eo=20,cn=20,qg=5,nO=qg*qg,oO='input, textarea, select, button, a, [contenteditable="true"]';function sO(e,t,n){const o=document.createElement("div");o.className="os-widgets__card",o.dataset.widgetId=e.id;const s=e.movable===!0,i=e.resizable===!0;s&&o.classList.add(ZN),i&&o.classList.add(JN),s?o.appendChild(iO(e,n.onRemove,n.onRedock)):o.appendChild(aO(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(sr(o,Zg(t.geometry,t.floatingParent)),o.classList.add(or)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${fO(t.dockedHeight,e)}px`);const a=()=>o.classList.contains(or),l=[];if(i)for(const d of dO()){const u=document.createElement("div");u.className=`os-widgets__resize os-widgets__resize--${d}`,u.setAttribute("aria-hidden","true"),u.dataset.dir=d,o.appendChild(u),l.push(lO(o,u,d,e,t,n,a))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=cO(o,d,e,t,n))}return{card:o,body:r,dispose:()=>{for(const d of l)try{d()}catch{}if(c)try{c()}catch{}o.remove()}}}function iO(e,t,n){const o=document.createElement("header");o.className="os-widgets__chrome";const s=document.createElement("span");s.className="os-widgets__grip",s.setAttribute("aria-hidden","true"),o.appendChild(s);const i=document.createElement("span");i.className="os-widgets__title",i.textContent=e.label,o.appendChild(i),o.appendChild(rO(e,n));const r=Yg(e,t);return o.appendChild(r),o}function rO(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",le(b("Dock %s back to widget column"),e.label)),n.innerHTML='<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 aO(e,t){const n=Yg(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function Yg(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",le(b("Remove %s"),e.label)),n.innerHTML=qt("close",{size:16}),n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function cO(e,t,n,o,s){let i=null,r=0,a=0,l=0,c=0,d=!1;const u=h=>{if(h.button!==0)return;const m=h.target;m&&m.closest(oO)||(h.preventDefault(),i=h.pointerId,r=h.clientX,a=h.clientY,d=!1,l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0,t.setPointerCapture(i))},f=()=>{if(!e.classList.contains(or)){const h=o.floatingParent.getBoundingClientRect(),m=e.getBoundingClientRect(),_={x:m.left-h.left,y:m.top-h.top,width:m.width||n.defaultWidth||eO,height:m.height||n.defaultHeight||tO};sr(e,_),e.classList.add(or),s.onLiberate(_),l=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(jg)},p=h=>{if(i===null||h.pointerId!==i)return;const m=h.clientX-r,_=h.clientY-a;if(!d){if(m*m+_*_<nO)return;d=!0,f()}const I=Qg(to(l+m),to(c+_),e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${Jg(I.x)}px`,e.style.top=`${Jg(I.y)}px`},g=h=>{if(!(i===null||h.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(jg),s.onGeometryChanged(Xg(e)))}};return t.addEventListener("pointerdown",u),t.addEventListener("pointermove",p),t.addEventListener("pointerup",g),t.addEventListener("pointercancel",g),()=>{t.removeEventListener("pointerdown",u),t.removeEventListener("pointermove",p),t.removeEventListener("pointerup",g),t.removeEventListener("pointercancel",g)}}function lO(e,t,n,o,s,i,r){let a=null,l=0,c=0,d=0,u=0,f=0,p=0;const g=_=>{if(_.button!==0||!r()&&!uO(n))return;_.preventDefault(),_.stopPropagation(),a=_.pointerId,l=_.clientX,c=_.clientY;const I=e.getBoundingClientRect(),O=s.floatingParent.getBoundingClientRect();d=I.left-O.left,u=I.top-O.top,f=I.width,p=I.height,t.setPointerCapture(a),e.classList.add(Vg)},h=_=>{if(a===null||_.pointerId!==a)return;const I=_.clientX-l,O=_.clientY-c,$=pO(n,I,O,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${$.x}px`,e.style.top=`${$.y}px`,e.style.width=`${$.width}px`),e.style.height=`${$.height}px`},m=_=>{if(!(a===null||_.pointerId!==a)){try{t.releasePointerCapture(a)}catch{}a=null,e.classList.remove(Vg),r()?i.onGeometryChanged(Xg(e)):i.onDockedHeightChanged(e.offsetHeight)}};return t.addEventListener("pointerdown",g),t.addEventListener("pointermove",h),t.addEventListener("pointerup",m),t.addEventListener("pointercancel",m),()=>{t.removeEventListener("pointerdown",g),t.removeEventListener("pointermove",h),t.removeEventListener("pointerup",m),t.removeEventListener("pointercancel",m)}}function dO(){return["n","e","s","w","ne","nw","se","sw"]}function uO(e){return e==="s"}function sr(e,t){e.style.left=`${t.x}px`,e.style.top=`${t.y}px`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`}function Xg(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function fO(e,t){return no(e,t.minHeight??Kg,t.maxHeight??1/0)}function Zg(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Qg(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function to(e){return Math.round(e/cn)*cn}function Jg(e){const t=Math.floor(e/cn)*cn;return t>=eo?t:Math.min(e,eo)}function Qg(e,t,n,o,s){const i=ge(s),r=i.x+eo,a=i.y+eo,l=Math.max(i.x,i.x+i.width-n-eo),c=Math.max(i.y,i.y+i.height-o-eo);return{x:Math.min(Math.max(r,e),l),y:Math.min(Math.max(a,t),c)}}function pO(e,t,n,o,s,i,r,a,l,c){const d=a.minWidth??QN,u=a.minHeight??Kg,f=a.maxWidth??1/0,p=a.maxHeight??1/0,g=ge(l),h=g.x+g.width,m=g.y+g.height;let _=o,I=s,O=i,$=r;if((e==="e"||e==="ne"||e==="se")&&(c?O=ir(to(o+i+t),o+d,Math.min(o+f,h))-o:O=no(i+t,d,Math.min(f,h-o))),e==="w"||e==="nw"||e==="sw"){const S=o+i;if(c)_=ir(to(o+t),Math.max(0,S-Math.min(f,S)),S-d),O=S-_;else{const R=no(i-t,d,Math.min(f,S));_=o+(i-R),O=R}}if((e==="s"||e==="se"||e==="sw")&&(c?$=ir(to(s+r+n),s+u,Math.min(s+p,m))-s:$=no(r+n,u,Math.min(p,m-s))),e==="n"||e==="ne"||e==="nw"){const S=s+r;if(c)I=ir(to(s+n),Math.max(0,S-Math.min(p,S)),S-u),$=S-I;else{const R=no(r-n,u,Math.min(p,S));I=s+(r-R),$=R}}return c||(O=i,_=o),{x:_,y:I,width:O,height:$}}function ir(e,t,n){const o=no(e,t,n),s=Math.floor(o/cn)*cn;if(s>=t)return s;const i=s+cn;return i<=n?i:o}function no(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const ew="desktop-mode-widgets",tw="desktop-mode-widgets-geometry",nw="desktop-mode-widgets-docked-heights";function ow(){try{return window.localStorage.getItem(ew)}catch{return null}}function hO(){const e=ow();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function pl(e){try{window.localStorage.setItem(ew,JSON.stringify(e))}catch{}}function mO(){try{const e=window.localStorage.getItem(tw);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t)){const i=wO(s);i&&(n[o]=i)}return n}catch{return{}}}function hl(e){try{window.localStorage.setItem(tw,JSON.stringify(e))}catch{}}function gO(){try{const e=window.localStorage.getItem(nw);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[o,s]of Object.entries(t))typeof s=="number"&&Number.isFinite(s)&&s>0&&(n[o]=s);return n}catch{return{}}}function sw(e){try{window.localStorage.setItem(nw,JSON.stringify(e))}catch{}}function wO(e){if(!e||typeof e!="object")return null;const{x:t,y:n,width:o,height:s}=e;return typeof t!="number"||!Number.isFinite(t)||typeof n!="number"||!Number.isFinite(n)||typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||s<=0?null:{x:t,y:n,width:o,height:s}}const yO=120,vO="os-inline-loader",iw="os-inline-loader-keyframes";function bO(){return typeof customElements<"u"&&!!customElements.get("os-spinner")}function EO(){if(document.getElementById(iw))return;const e=document.createElement("style");e.id=iw,e.textContent="@keyframes os-inline-loader-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function _O(){if(bO()){const n=document.createElement("os-spinner");return n.setAttribute("preset","inline"),n.setAttribute("size","20"),n.setAttribute("aria-hidden","true"),n}const e=document.createElement("span");return e.setAttribute("aria-hidden","true"),e.style.cssText=["flex:0 0 auto","width:16px","height:16px","border-radius:50%","border:2px solid currentColor","border-top-color:transparent","opacity:0.7"].join(";"),typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches||(EO(),e.style.animation="os-inline-loader-spin 0.7s linear infinite"),e}function SO(e,t={}){const n=t.label??b("Loading…");let o=null,s=!1;const i=()=>{if(s||o||!e.isConnected)return;o=document.createElement("div"),o.className=vO,o.setAttribute("role","status"),o.setAttribute("aria-live","polite"),o.style.cssText=["display:flex","align-items:center","justify-content:center","gap:10px","padding:20px 16px","font-size:13px","color:var(--os-ui-fg-muted,#646970)"].join(";");const l=document.createElement("span");l.textContent=n,o.appendChild(_O()),o.appendChild(l),e.appendChild(o)},r=t.immediate?null:window.setTimeout(i,yO);t.immediate&&i();const a=()=>{r!==null&&window.clearTimeout(r)};return{done:()=>{s||(s=!0,a(),o?.remove(),o=null)},fail:(l,c)=>{if(s||(s=!0,a(),o||(s=!1,i(),s=!0),!o))return;o.textContent="",o.setAttribute("aria-live","assertive"),o.style.flexDirection="column",o.style.color="var(--os-ui-fg-muted,#646970)";const d=document.createElement("span");if(d.textContent=l,o.appendChild(d),c){const u=document.createElement("button");u.type="button",u.textContent=b("Retry"),u.className="button button-small",u.addEventListener("click",()=>{o?.remove(),o=null,s=!1,c()}),o.appendChild(u)}}}}function kO(e){const t=`os.widget.${e}.`,n=o=>{try{return localStorage.getItem(t+o)}catch{return null}};return{get(o){const s=n(o);if(s===null)return null;try{return JSON.parse(s)}catch{return null}},set(o,s){try{localStorage.setItem(t+o,JSON.stringify(s))}catch{}},remove(o){try{localStorage.removeItem(t+o)}catch{}},clear(){try{for(let o=localStorage.length-1;o>=0;o--){const s=localStorage.key(o);s&&s.startsWith(t)&&localStorage.removeItem(s)}}catch{}}}}const IO=["clock"],rr=40,AO=12;class CO{constructor(t,n,o){this.override=null,this.mounted=new Map,this.generation=0,this.unwatchPointer=null,this.stackObserver=null,this.root=t,this.pluginUrl=n,this.enabledIds=hO(),this.geometry=mO(),this.dockedHeights=gO(),this.floatingHost=o??t.parentElement??t,this.listEl=document.createElement("div"),this.listEl.className="os-widgets__list",this.root.appendChild(this.listEl),this.addTile=this.buildAddTile(),this.root.appendChild(this.addTile),typeof ResizeObserver=="function"&&(this.stackObserver=new ResizeObserver(()=>this.positionAddTile())),this.paintEmptyState(),this.watchPointerProximity()}visibleIds(){return this.override??this.enabledIds}hydrate(){ow()===null&&(this.enabledIds=IO.filter(t=>!!Qn(t)),pl(this.enabledIds));for(const t of this.visibleIds())this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){if(Qn(t)){if(this.override){if(this.override.includes(t))return;this.override=[...this.override,t],this.mountById(t),this.paintEmptyState(),A(v.WIDGET_ADDED,{id:t});return}this.enabledIds.includes(t)||(this.enabledIds.push(t),pl(this.enabledIds),this.mountById(t),this.paintEmptyState(),A(v.WIDGET_ADDED,{id:t}))}}remove(t){if(this.override){if(!this.override.includes(t))return;this.override=this.override.filter(o=>o!==t),this.unmountById(t),this.paintEmptyState(),A(v.WIDGET_REMOVED,{id:t}),ms();return}const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(pl(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],hl(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],sw(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),A(v.WIDGET_REMOVED,{id:t}),ms())}getEnabledIds(){return[...this.enabledIds]}getMountedIds(){return Array.from(this.mounted.keys())}openPicker(){this.positionAddTile(),this.root.classList.add("os-widgets--picking"),YN({anchor:this.addTile,registry:()=>ul(),enabledIds:()=>[...this.enabledIds],onAdd:t=>{this.add(t),fl(),this.addTile.focus()},onClose:()=>this.root.classList.remove("os-widgets--picking")})}mountIfEnabled(t){Qn(t)&&this.visibleIds().includes(t)&&(this.mounted.has(t)||(this.mountById(t),this.paintEmptyState()))}unmount(t){this.mounted.has(t)&&(this.unmountById(t),this.paintEmptyState())}ensureMounted(t){return Qn(t)?(this.enabledIds.includes(t)||this.add(t),!0):!1}setVisibleIds(t){this.override=t?[...t]:null;const n=new Set(this.visibleIds());for(const o of Array.from(this.mounted.keys()))n.has(o)||this.unmountById(o);for(const o of n)this.mounted.has(o)||!Qn(o)||this.mountById(o);this.paintEmptyState()}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t);this.unwatchPointer?.(),this.unwatchPointer=null,this.stackObserver?.disconnect()}mountById(t){const n=Qn(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=sO(n,{floatingParent:this.floatingHost,geometry:s,dockedHeight:this.dockedHeights[t]},{onRemove:()=>this.remove(t),onGeometryChanged:u=>this.persistGeometry(t,u),onDockedHeightChanged:u=>this.persistDockedHeight(t,u),onLiberate:u=>this.liberate(t,u),onRedock:()=>this.redock(t)}),r=!!s,a={id:t,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(t,a),this.placeCard(i.card,r),this.stackObserver?.observe(i.card);const l={id:t,pluginUrl:this.pluginUrl,storage:kO(t)};A(v.WIDGET_MOUNTING,{id:t,container:i.body,ctx:l});const c=u=>{const f=this.mounted.get(t);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,this.positionAddTile(),A(v.WIDGET_MOUNTED,{id:t,container:i.body,ctx:l})};let d;try{d=n.mount(i.body,l)}catch(u){this.handleMountFailure(t,u);return}if(LO(d)){const u=SO(i.body,{label:b("Loading…")});d.then(f=>{u.done(),c(f)},f=>{u.done(),this.mounted.get(t)?.generation===o&&this.handleMountFailure(t,f)});return}c(d)}unmountById(t){const n=this.mounted.get(t);if(n){A(v.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){A(v.SHELL_ERROR,{scope:"widget-teardown",id:t,error:o}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" teardown threw:`,o)}this.generation++,this.stackObserver?.unobserve(n.frame.card),n.frame.dispose(),this.mounted.delete(t)}}handleMountFailure(t,n){const o=this.mounted.get(t);o&&(o.frame.dispose(),this.mounted.delete(t)),A(v.WIDGET_MOUNT_FAILED,{id:t,error:n}),A(v.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="os-widgets__add",t.setAttribute("aria-label",b("Add widget"));const n=document.createElement("span");n.className="os-widgets__add-plus",n.setAttribute("aria-hidden","true"),n.textContent="+";const o=document.createElement("span");return o.className="os-widgets__add-label",o.textContent=b("Add widget"),t.appendChild(n),t.appendChild(o),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.openPicker()}),t}watchPointerProximity(){let t=null,n=0;const o=()=>{t=null,this.positionAddTile()},s=()=>{n||(n=requestAnimationFrame(()=>{n=0,this.positionAddTile()}))},i=c=>{t||(t=this.root.getBoundingClientRect());const d=c.clientX>=t.left-rr&&c.clientX<=t.right+rr&&c.clientY>=t.top-rr&&c.clientY<=t.bottom+rr;this.root.classList.toggle("os-widgets--hovered",d),d&&s()},r=()=>{this.root.classList.remove("os-widgets--hovered")};document.addEventListener("pointermove",i,{passive:!0}),document.documentElement.addEventListener("pointerleave",r),window.addEventListener("resize",o);let a=null;typeof ResizeObserver=="function"&&(a=new ResizeObserver(o),a.observe(this.root),this.root.parentElement&&a.observe(this.root.parentElement));const l=Fo(()=>this.reclampFloating());this.unwatchPointer=()=>{n&&(cancelAnimationFrame(n),n=0),l(),a?.disconnect(),document.removeEventListener("pointermove",i),document.documentElement.removeEventListener("pointerleave",r),window.removeEventListener("resize",o)}}placeCard(t,n){n?this.floatingHost.appendChild(t):this.listEl.appendChild(t)}liberate(t,n){const o=this.mounted.get(t);!o||o.floating||(o.floating=!0,this.floatingHost.appendChild(o.frame.card),sr(o.frame.card,n),this.persistGeometry(t,n),this.paintEmptyState())}redock(t){const n=this.mounted.get(t);if(!n||!n.floating)return;n.floating=!1,this.geometry[t]&&(delete this.geometry[t],hl(this.geometry));const o=n.frame.card;o.classList.remove("os-widgets__card--floating"),o.style.left="",o.style.top="",o.style.width="";const s=this.dockedHeights[t];o.style.height=s!==void 0?`${s}px`:"",this.listEl.appendChild(o),this.paintEmptyState()}reclampFloating(){for(const[t,n]of this.mounted){if(!n.floating)continue;const o=this.geometry[t];if(!o)continue;const s=Zg(o,this.floatingHost);s.x===o.x&&s.y===o.y||(sr(n.frame.card,s),this.persistGeometry(t,s))}}persistGeometry(t,n){this.geometry[t]=n,hl(this.geometry),this.positionAddTile()}positionAddTile(){const t=this.root.getBoundingClientRect();if(!t.height)return;let n=this.listEl.offsetTop+this.listEl.offsetHeight;for(const i of this.mounted.values()){if(!i.floating)continue;const r=i.frame.card.getBoundingClientRect();Math.min(r.right,t.right)-Math.max(r.left,t.left)<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+AO,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,sw(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 LO(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const TO=280,NO=220,OO=520,DO=400;function rw(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function aw(e,t,n){return o=>{const s=rw(o,n),i=document.createElement("iframe");i.style.width="100%",i.style.height="100%",i.style.border="0",i.setAttribute("src",e.url),typeof e.sandbox=="string"&&e.sandbox!==""&&i.setAttribute("sandbox",e.sandbox),o.style.padding="0",o.appendChild(i);const r=SN(s,i);t.push(r);let a;try{a=new URL(e.url,window.location.origin).origin}catch{a=window.location.origin}let l=null;const c=new Promise(f=>{l=f}),d=()=>{if(e.bridge)try{const f=i.contentDocument;if(f&&!f.querySelector("script[data-os-iframe-bridge]")){const p=window.openStationConfig?.iframeBridgeUrl;if(p){const g=f.createElement("script");g.src=p,g.setAttribute("data-os-iframe-bridge","1"),f.head?.appendChild(g)}}}catch{}IS(s),l?.()};i.addEventListener("load",d);const u=f=>{if(!i.contentWindow||f.source!==i.contentWindow||f.origin!==a&&f.origin!==window.location.origin)return;const p=f.data;p&&typeof p=="object"&&typeof p.type=="string"&&p.type.startsWith("os-bridge-")&&window.__openStationConnectionBridge?.routeIncomingFromIframe(p,s),p&&typeof p=="object"&&p.type==="os-window-publish"&&typeof p.channel=="string"&&p.channel!==""&&SS(s,p.channel,p.payload);try{e.onMessage?.(f.data)}catch(g){typeof console<"u"&&console.error("[openstation] iframeContent.onMessage threw:",g)}};return window.addEventListener("message",u),t.push(()=>{window.removeEventListener("message",u),i.removeEventListener("load",d)}),c}}function RO(e,t,n={}){let o;try{const c=new URL(t,window.location.origin);if(c.origin!==window.location.origin)return()=>{};if(Ln(c))return()=>{};c.searchParams.set("openstation_chromeless","1"),o=c.toString()}catch{return()=>{}}e.replaceChildren();const s=[],i=rw(e,n.windowId??""),r=aw({url:o},s,i)(e);getComputedStyle(e).position==="static"&&(e.style.position="relative");const a=document.createElement("div");a.style.position="absolute",a.style.inset="0",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center";const l=document.createElement("os-spinner");return l.setAttribute("preset","comet"),a.appendChild(l),e.appendChild(a),r.then(()=>a.remove()),()=>{for(const c of s)try{c()}catch{}e.replaceChildren()}}function xO(e){return async t=>{const n=t.render;let o=n;const s=[];t.iframeContent&&(n&&typeof console<"u"&&console.warn("[openstation] registerWindow: both `render` and `iframeContent` provided — ignoring `render` and using the iframe shorthand. Drop one."),o=aw(t.iframeContent,s,t.id));const i=t.onClose,r=t.iframeContent?()=>{for(const l of s)try{l()}catch{}i?.()}:i;return await e.open({id:t.id,baseId:t.baseId||t.id,native:!0,url:t.url||`#${t.id}`,title:t.title,icon:t.icon,x:t.x??0,y:t.y??0,width:t.width??OO,height:t.height??DO,minWidth:t.minWidth??TO,minHeight:t.minHeight??NO,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let MO=0;function WO(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++MO}`,s=n.persistent===!0,i=[["opened",v.WINDOW_OPENED],["reopened",v.WINDOW_REOPENED],["focused",v.WINDOW_FOCUSED],["blurred",v.WINDOW_BLURRED],["closing",v.WINDOW_CLOSING],["closed",v.WINDOW_CLOSED],["minimized",v.WINDOW_MINIMIZED],["restored",v.WINDOW_RESTORED],["maximized",v.WINDOW_MAXIMIZED],["unmaximized",v.WINDOW_UNMAXIMIZED],["fullscreenEntered",v.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",v.WINDOW_FULLSCREEN_EXITED],["resized",v.WINDOW_RESIZED],["bodyResized",v.WINDOW_BODY_RESIZED],["boundsChanged",v.WINDOW_BOUNDS_CHANGED]],r=[];let a=!1;const l=()=>{if(!a){a=!0;for(const c of r)jt(c,o)}};for(const[c,d]of i){const u=t[c];u&&(r.push(d),ee(d,o,f=>{const p=f;if(p.windowId!==e)return;const{windowId:g,...h}=p;u(h),c==="closed"&&!s&&l()}))}return l}function PO(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function $O(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&Ik(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function cw(e,t){const n=t??{},o=s=>{const i=s?n[s]:void 0;if(!i?.deps||i.deps.length===0)return;const r=[];for(const a of i.deps){const l=n[a];l&&r.push({handle:a,url:l.url??"",before:l.before,after:l.after,l10n:l.l10n,translations:l.translations})}return r.length>0?r:void 0};return e.map(s=>{const i=s.scriptHandle?n[s.scriptHandle]:void 0,r=[];for(const l of s.companionScripts??[]){if(typeof l!="string"){r.push(l);continue}const c=n[l];c?.url&&r.push({scriptUrl:c.url,scriptHandle:l,scriptBefore:c.before,scriptAfter:c.after,scriptL10n:c.l10n,scriptTranslations:c.translations,scriptDeps:o(l)})}const a=(s.tabs??[]).map(l=>{if(typeof l.scriptUrl=="string")return l;const c=l.scriptHandle?n[l.scriptHandle]:void 0;return{...l,scriptUrl:c?.url??"",scriptBefore:c?.before,scriptAfter:c?.after,scriptL10n:c?.l10n,scriptTranslations:c?.translations,scriptDeps:o(l.scriptHandle)}});return{...s,scriptUrl:s.scriptUrl??i?.url??"",scriptBefore:s.scriptBefore??i?.before,scriptAfter:s.scriptAfter??i?.after,scriptL10n:s.scriptL10n??i?.l10n,scriptTranslations:s.scriptTranslations??i?.translations,scriptDeps:s.scriptDeps??o(s.scriptHandle),companionScripts:r,tabs:a}})}function UO(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,a=new Map,l=new Set,c=new Map,d=y=>{const E=Li(y.id);return E?{width:Math.max(E.width,y.minWidth),height:Math.max(E.height,y.minHeight)}:{width:y.width,height:y.height}},u=y=>{if(i.has(y.templateId))return;if(document.getElementById(y.templateId)){i.add(y.templateId);return}if(!y.templateHtml)return;const E=document.createElement("template");E.id=y.templateId,E.innerHTML=y.templateHtml,document.body.appendChild(E),i.add(y.templateId)},f=y=>{const E=y.styleUrl;if(!E||l.has(E))return;const T=E.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${T}"]`)){const X=document.createElement("link");X.rel="stylesheet",X.href=E,y.styleHandle&&(X.dataset.osStyleHandle=y.styleHandle),document.head.appendChild(X)}if(Array.isArray(y.styleInline))for(const X of y.styleInline){if(typeof X!="string"||X==="")continue;const Y=document.createElement("style");y.styleHandle&&(Y.dataset.osStyleHandle=y.styleHandle),Y.textContent=X,document.head.appendChild(Y)}l.add(E)},p=y=>{f(y)},g=y=>{for(const E of y.companionStyles??[])f(E)},h=new Set,m=(y,E)=>{if(h.has(y))return;h.add(y);const T=[E.scriptTranslations??"",...E.scriptL10n??[],...E.scriptBefore??[],...E.scriptAfter??[]];for(const x of T)typeof x=="string"&&x!==""&&Nh(x)},_=(y,E)=>{const T=E.scriptUrl,x=`${y}|${T}`;if(r.has(T))return m(x,E),Promise.resolve();const X=a.get(T);if(X)return X.then(()=>m(x,E));h.add(x);const Y=pe(T,{translations:E.scriptTranslations,l10n:E.scriptL10n,before:E.scriptBefore,after:E.scriptAfter,deps:E.scriptDeps}).catch(ce=>{A(v.SHELL_ERROR,{scope:"native-window-script-load",id:y,error:ce})}).then(()=>{r.add(T),a.delete(T)});return a.set(T,Y),Y},I=async y=>{g(y);for(const E of y.companionScripts??[])E.scriptUrl&&await _(y.id,E);y.scriptUrl&&await _(y.id,y)},O=async y=>{y.preloadScript&&await I(y)},$=new Set,S=(y,E)=>{if(!y||$.has(y)||r.has(y)||l.has(y))return;$.add(y);const T=document.createElement("link");T.rel="prefetch",T.as=E,T.href=y,document.head.appendChild(T)},R=()=>{const y=navigator.connection;if(!(y?.saveData||/2g$/.test(y?.effectiveType??""))){for(const E of c.values())if(!E.preloadScript){for(const T of E.companionScripts??[])S(T.scriptUrl,"script");S(E.scriptUrl,"script");for(const T of E.companionStyles??[])S(T.styleUrl,"style")}}};let W=!1;const U=()=>{if(W)return;W=!0;const y=()=>{W=!1,R()};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(y,{timeout:4e3}):window.setTimeout(y,1500)},F=y=>async(E,T)=>{E.appendChild(lw(y.templateId)),$O(E,y),await I(y),window.wp?.os?.apps?.refresh?.();const X=PO()[y.id];return X?.(E,T)},K=(y,E)=>{const T=F(y),x=d(y);t.open({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:x.width,height:x.height,minWidth:y.minWidth,minHeight:y.minHeight,render:T,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle,...E?{params:E}:{}})},Q=(y,E)=>{const T=F(y),x=d(y);t.openNew({id:y.id,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:x.width,height:x.height,minWidth:y.minWidth,minHeight:y.minHeight,render:T,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle,...E?{params:E}:{}})},Z=(y,E,T)=>{const x=F(y),X=d(y);t.openNew({id:E,baseId:y.id,native:!0,url:`#${y.id}`,title:y.title,icon:y.icon,width:X.width,height:X.height,minWidth:y.minWidth,minHeight:y.minHeight,render:x,autofocus:y.autofocus,ownerHandle:y.ownerHandle||y.scriptHandle,...T})},C=async y=>{if(!s.has(y.id)){if(y.placement==="none"){u(y),p(y),await O(y),s.add(y.id);return}u(y),p(y),await O(y),n({id:y.id,title:y.title,icon:y.icon,windowId:y.id,navKind:y.navKind==="control"?"control":"app",defaultPlacement:"rail",order:y.dockOrder,placeable:y.placeable===!0,isOpen:()=>!!t.getById(y.id),onOpen:()=>K(y)}),A(v.DOCK_ITEM_APPENDED,{id:y.id}),s.add(y.id)}},D=y=>{s.has(y)&&(o(y),s.delete(y),c.delete(y))},V=y=>{try{const E=new URL(y,window.location.origin),T=[E.pathname.split("/").pop()??""];for(const x of["post_type","taxonomy","page"]){const X=E.searchParams.get(x);X&&T.push(`${x}=${X}`)}return T.join("&")}catch{return y}},j=y=>`desktop-mode/menu-pages/${y}`,te=y=>{const E=j(y.id),T=y.menuPages??[];if(T.length===0){pa(E);return}const x=T.map(Y=>({tab:Y.id,key:V(Y.page)})),X=Y=>x.find(ce=>ce.key===V(Y.href))?.tab??null;ht({id:E,nativeWindowId:y.id,matches:(Y,ce)=>X(ce)!==null,params:(Y,ce)=>{const q=X(ce);return q?{tab:q}:void 0}})},N=async y=>{const E=new Set;for(const T of y)E.add(T.id),te(T),c.set(T.id,T);for(const T of Array.from(s))E.has(T)||(D(T),pa(j(T)));for(const T of y)s.has(T.id)||await C(T);U()},L=(y,E={})=>{const T=c.get(y);return T?(_e.publish("os/open-requested",{windowId:y,source:E.source??"api"}),K(T,E.params),!0):!1},M=(y,E={})=>{const T=c.get(y);return T?(_e.publish("os/open-requested",{windowId:y,source:E.source??"api"}),Q(T,E.params),!0):!1},P=(y,E,T)=>{const x=c.get(E);return x?(Z(x,y,T),!0):!1};return ee(v.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",y=>{const E=y,T=E?.windowId,x=E?.width,X=E?.height;if(!T||typeof x!="number"||typeof X!="number")return;const Y=t.getById(T);if(!Y||Y.state!=="normal")return;const ce=Y.config.baseId||Y.id;xp(ce,{width:x,height:X}),Y.element&&Mp(ce,{x:Y.element.offsetLeft,y:Y.element.offsetTop})}),ee(v.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E)return;const T=t.getById(E);if(!T||T.state!=="normal"||!T.element)return;const x=T.config.baseId||T.id;xp(x,{width:T.element.offsetWidth,height:T.element.offsetHeight}),Mp(x,{x:T.element.offsetLeft,y:T.element.offsetTop})}),ee(v.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E||Vt())return;const T=t.getById(E);if(!T)return;const x=T.config.baseId||T.id,X=c.get(x),Y=X?{width:X.width,height:X.height}:{width:T.config.width,height:T.config.height};Wp(x,"maximized",Y)}),ee(v.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",y=>{const E=y?.windowId;if(!E)return;const T=t.getById(E);if(!T)return;const x=T.config.baseId||T.id;Wp(x,null)}),{sync:N,openById:L,openNewById:M,restoreById:P,loadScriptById:async y=>{const E=c.get(y);return E?(await I(E),!0):!1},prewarmById:async y=>{const E=c.get(y);return!E||t.getById(y)?!1:(await I(E),window.wp?.os?.apps?.prewarm?.(y)===!0)}}}function lw(e){let t=null;if(typeof e=="string"){const n=document.getElementById(e);n instanceof HTMLTemplateElement&&(t=n)}else t=e;if(!t)throw new Error(`[openstation] cloneTemplate: no <template> found for ${typeof e=="string"?`#${e}`:"<reference>"}`);return t.content.cloneNode(!0)}function ar(e){const t=window.wp?.os,n=window.openStationConfig,o=t?.config?.adminUrl??n?.adminUrl;if(!o)return null;const s=t?.getMenuItems?.()??n?.dockItems??[],i=fe(e,o);return s.find(r=>fe(r.url,o)===i||(r.submenu??[]).some(a=>fe(a.url,o)===i))??null}const dw="data:image/svg+xml;base64,",cr=new Map;function BO(e){const t=cr.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(dw.length)).includes("currentColor")}catch{}return cr.size>=256&&cr.clear(),cr.set(e,n),n}function oo(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const l=fi(t.slot);l!==null&&(e=l),s=Na(t.slot)}if(typeof e=="string"&&e.startsWith("dashicons-")){const l=document.createElement("span");return l.className=`dashicons ${e} ${n}`.trim(),l.setAttribute("aria-hidden","true"),s!==null&&(l.style.color=s),l}if(s!==null&&typeof e=="string"){const l=document.createElement("span");if(l.className=n,l.setAttribute("aria-hidden","true"),l.style.display="inline-block",$i(l,e,s))return l}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const l=e.slice(dw.length);if(/^[A-Za-z0-9+/=]+$/.test(l)){const c=document.createElement("span");return c.className=n,c.setAttribute("aria-hidden","true"),c.style.display="inline-block",BO(e)&&$i(c,e,"currentColor")||(c.style.backgroundImage=`url("${e}")`,c.style.backgroundRepeat="no-repeat",c.style.backgroundPosition="center",c.style.backgroundSize="contain"),c}}if(typeof e=="string"&&/^data:image\/(png|jpeg|jpg|gif|webp|x-icon|vnd\.microsoft\.icon);base64,/i.test(e)){const l=e.indexOf(","),c=l>=0?e.slice(l+1):"";if(/^[A-Za-z0-9+/=]+$/.test(c))return uw(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return uw(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=FO(o);i.textContent=r;const a=wc(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 uw(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 FO(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 fw="os-icon__badge",gs=new Map,ws=new Map;function HO(e){return Math.max(0,Math.floor(Number(e)||0))}function pw(e,t){if(!e)return;const n=ww(e);if(!n)return;const o=HO(t),s=gs.get(e)??0;o!==s&&(o===0?gs.delete(e):gs.set(e,o),yw(n,o),_e.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),A(v.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function GO(e){pw(e,0)}function zO(e){return gs.get(e)??0}function jO(e,t){if(e){if(!t){ws.delete(e);return}ws.get(e)!==t&&(ws.set(e,t),KO(e,t),_e.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function hw(e){return ws.get(e)??""}function VO(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function KO(e,t){const o=ww(e)?.querySelector(".os-icon__image");if(o){const s=oo(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${VO(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const ml={setBadge:pw,clearBadge:GO,getBadge:zO,setArt:jO,getArt:hw};function qO(e){return!e||e.length===0?"":`${Ta()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let mw="";function gw(e,t,n){const o=qO(t);if(o===mw&&e.querySelector(":scope > .os-icons"))return;mw=o;const s=e.querySelector(":scope > .os-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="os-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",b("Desktop icons"));const r=[...t].sort((l,c)=>{const d=l.pinned?0:1,u=c.pinned?0:1;return d-u}),a=new Map;for(const l of r){const c=XO(l,n),d=gs.get(l.id)??0;d>0&&yw(c,d);const u=ws.get(l.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(oo(u,{className:"os-icon__image",title:""}))}i.appendChild(c),a.set(l.id,c)}e.appendChild(i),A(v.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(l=>l.id),container:i,tiles:a})}function ww(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${YO(e)}"]`):null}function yw(e,t){const n=e.querySelector(`:scope > .${fw}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=le(Kt("%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=fw,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function YO(e){const t=window.CSS;return t?.escape?t.escape(e):e}function XO(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=oo(e.icon,{title:e.title,className:"os-icon__image",slot:pi(e.id)});n.appendChild(o);const s=document.createElement("span");return s.className="os-icon__label",s.textContent=e.title,n.appendChild(s),n.addEventListener("click",i=>{i.stopPropagation(),A(v.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),ZO(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),Rh({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function ZO(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(zn(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=ar(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 JO(e){const t=[],n=new Map,o=s=>{t.push(s),n.set(s.id,s)};for(const s of e.menuItems)n.has(s.id)||o({id:s.id,kind:s.isCore?"core":"plugin",title:s.title,icon:s.icon,windowId:e.resolveMenuWindowId?.(s)||void 0,menu:s});for(const s of e.systemTiles){const i=n.get(s.item.id);if(i){i.tile=s.item;continue}const a=(s.item.submenu??[]).map(l=>l.windowId).filter(l=>!!l);o({id:s.item.id,kind:s.kind,title:s.item.title,icon:s.item.icon,locked:s.locked,defaultPlacement:s.item.defaultPlacement,windowId:s.item.windowId,answersFor:a.length>0?a:void 0,order:s.item.order,tile:s.item})}for(const s of e.icons){const i=s.window?n.get(s.id)??n.get(s.window):n.get(s.id);if(i){i.entry=s,s.window&&(i.windowId=s.window);continue}o({id:s.id,kind:"app",title:s.title,icon:s.icon,windowId:s.window||void 0,entry:s})}return t}const vw="os-side-dock";function QO(e,t,n,o,s="bottom"){let i=t,r=s,a=n,l=o??[],c=null,d=null,u=null,f=null,p=null;const g=new Map;let h=[],m=Uh({items:[],config:{placement:{},order:[]},layout:i,openWindows:[]});const _=()=>e.getSettings?.()??{navPlacement:{},navOrder:[]},I=()=>{const E=e.windowManager.getActiveDesktopId(),T=[],x=new Set;for(const X of e.windowManager.getAll()){if((X.config.desktopId||E)!==E)continue;const Y=X.config.baseId||X.id;x.has(Y)||(x.add(Y),T.push({id:Y,title:X.config.title||Y,icon:X.config.icon||"dashicons-admin-generic",fromAdminUrl:X.config.native!==!0}))}return T},O=E=>E.windowId?E.windowId:Tn(E.url)??fe(E.url,e.adminUrl),$=()=>{const E=[];for(const x of g.values())E.push({item:x,kind:x.navKind??"app",locked:x.locked});h=JO({menuItems:a,systemTiles:E,icons:l,resolveMenuWindowId:O});const T=_();m=Uh({items:h,config:{placement:LI(T.navPlacement,h,e.getWorkspaceProfile?.()??null),order:T.navOrder},layout:i,openWindows:I()})},S=E=>E.tile?{type:"system",item:E.tile}:E.menu?{type:"menu",item:E.windowId?{...E.menu,windowId:E.windowId}:E.menu}:{type:"menu",item:{id:E.id,title:E.title,icon:E.icon,url:E.entry?.url||"",windowId:E.windowId,badge:0,submenu:[],isCore:!1}},R=E=>!!E.entry||!!E.windowId||!!E.menu?.url,W=(E,T)=>E.entry?E.entry:{id:E.id,title:E.title,icon:E.icon,window:E.windowId??"",url:E.menu?.url||"",position:2e3+T},U=E=>({core:(E.core??[]).map(S),apps:(E.apps??[]).map(S),controls:(E.controls??[]).map(S)}),F=(E,T,x)=>{if(!E)return;if(E.setZones){E.setZones(T),x.clear();for(const ce of ct)for(const q of T[ce])q.type==="system"&&x.add(q.item.id);return}const X=[],Y=new Set;for(const ce of ct)for(const q of T[ce])q.type==="menu"?X.push(q.item):Y.add(q.item.id);E.replaceItems(X);for(const ce of Array.from(x))Y.has(ce)||(E.removeSystemItem(ce),x.delete(ce));for(const ce of ct)for(const q of T[ce])q.type==="system"&&!x.has(q.item.id)&&(E.appendSystemItem(q.item),x.add(q.item.id))},K=new Set,Q=new Set,Z=()=>{$(),F(c,U(m.dock),K),F(d,{core:m.sidebar.map(S),apps:[],controls:[]},Q),e.renderIcons(m.desktop.filter(R).map(W))},C=()=>Array.from(m.ephemeral).sort().join(","),D=()=>{const E=document.getElementById(vw);if(E)return E;const T=document.createElement("nav");return T.id=vw,T.className="os-dock",T.setAttribute("role","toolbar"),T.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(T,e.shellBody.firstChild),T},V=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},j=()=>{if(c){try{c.destroy()}catch(E){A(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:E})}c=null,u=null}if(d){try{d.destroy()}catch(E){A(v.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:E})}d=null,f=null}K.clear(),Q.clear()},te=E=>{const T=ma();if(!T)return A(v.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return T.mount(E)}catch(x){if(A(v.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:T.id,error:x}),T===vc)return null;try{return vc.mount(E)}catch{return null}}},N=(E,T)=>({container:E,items:[],fullMenu:a.slice(),fullSystemTiles:h.filter(x=>!!x.tile).filter(x=>L(x.id)).map(x=>x.tile),orientation:T,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:x=>{if(zn(x.url)||Me(x.url))return;const X=fe(x.url,e.adminUrl);e.windowManager.open({id:X,baseId:X,url:x.url,parentUrl:x.url,title:x.title,icon:x.icon.startsWith("dashicons-")?x.icon:"dashicons-admin-generic",submenu:x.submenu,selfLabel:x.selfLabel,multi:!!x.multi})},openSubmenuPick:(x,X)=>{zn(X.url)||Me(X.url,{newInstance:!0})||e.windowManager.openNew({id:fe(X.url,e.adminUrl),baseId:fe(x.url,e.adminUrl),url:X.url,parentUrl:x.url,title:x.title,icon:x.icon.startsWith("dashicons-")?x.icon:"dashicons-admin-generic",submenu:x.submenu,selfLabel:x.selfLabel,multi:!!x.multi})},openSystemItem:x=>x.onOpen()}),L=E=>{for(const T of ct)if(m.dock[T].some(x=>x.id===E))return!0;return m.sidebar.some(T=>T.id===E)},M=()=>i==="classic"?"bottom":r,P=()=>{j(),$(),i==="classic"?(p=D(),d=te(N(p,"left")),f=Gh(d)):V(),c=te(N(e.bottomDockEl,M())),u=Gh(c),Z()},H=()=>{document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:M(),primary:u,side:f}}))},z={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:E=>{E!==i&&(i=E,e.shellRoot.setAttribute("data-os-layout",E),P(),H())},getDockPlacement:()=>r,setDockPlacement:E=>{if(E===r)return;const T=M();r=E,M()!==T&&(P(),H())},applyDockItems:E=>{a=E,Z()},applyDesktopIcons:E=>{l=E??[],Z()},appendSystemTile:E=>{g.set(E.id,E),Z()},removeSystemTile:E=>{g.delete(E)&&Z()},listSystemTiles:()=>Array.from(g.values()).map(E=>({id:E.id,title:E.title,icon:E.icon,navKind:E.navKind??"app",placeable:E.placeable===!0,locked:E.locked===!0})),getSystemTile:E=>g.get(E)??null,getMenuItems:()=>a.slice(),getNavItems:()=>h.slice(),getNav:()=>m,refresh:Z,destroy:()=>{j(),V()}};for(const E of["os-window-opened","os-window-closed"])document.addEventListener(E,()=>{const T=C();$(),C()!==T&&Z()});e.shellRoot.setAttribute("data-os-layout",i),P();let y=ma()?.id??null;return N_(()=>{const E=ma()?.id??null;E!==y&&(y=E,P(),H())}),z}const bw="os-ai-loading",Ew="os-ai-loading-keyframes";let so=null,ys=null;function eD(){if(document.getElementById(Ew))return;const e=document.createElement("style");e.id=Ew,e.textContent="@keyframes os-ai-loading-spin{to{transform:rotate(360deg)}}",document.head.appendChild(e)}function tD(e){if(so&&so.isConnected)return;ys=r=>{r.key==="Escape"&&(lr(),e?.())},document.addEventListener("keydown",ys);const t=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=document.createElement("div");n.id=bw,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||(eD(),s.style.animation="os-ai-loading-spin 0.7s linear infinite");const i=document.createElement("span");i.textContent=b("Starting the command palette…"),o.appendChild(s),o.appendChild(i),n.appendChild(o),document.body.appendChild(n),so=n}function lr(){ys&&(document.removeEventListener("keydown",ys),ys=null),so&&(so.remove(),so=null),document.getElementById(bw)?.remove()}function nD(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 oD{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 VN().catch(t=>{console.warn("[openstation] command-palette runtime failed to load",t)}),this._loadPromise?this._loadPromise:(Vi("desktop-mode-ai-assistant"),this._loadPromise=nD(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||tD(()=>this.close()),this._ensure().then(t=>{lr(),this._intendOpen&&t.open()}).catch(t=>{lr(),console.warn("[openstation] command palette failed to load",t)})}close(){this._intendOpen=!1,lr(),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 _w=e=>!e||typeof e!="object"?!1:e.name==="AbortError",sD=e=>{if(!e)return[];const t=eT();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}}):[]},iD=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 rD(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 aD(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function cD(e){const t=async(s,i)=>{const r=e.config(),a=r.aiSearchUrl??"",l=r.restNonce??"";if(!a||!l)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Ae(a,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":l},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw _w(c)?c:new Error(`[openstation] wp.os.ai.ask: network error — ${String(c?.message??c)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",a=s.tool?.args??"",l=tT(r);if(!l)return{ok:!1,response:{answer_type:"tool_call",message:`Command /${r} was not registered on this page.`,entity:null,admin_links:null,toolCall:{slug:r,args:a,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??e.fallbackContext();let d;try{d=await Promise.resolve(l.run(a,c))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:a,result:d}},o=async(s,i,r,a,l,c)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:aD(a)}};l&&(d.system_prompt_text=l.text,d.system_prompt_mode=l.mode);let u;try{u=await t(d,c)}catch(g){if(_w(g))throw g;return null}if(!u.ok)return null;const f=await u.json().catch(()=>({}));return(typeof f.message=="string"?f.message.trim():"")!==""?f.message??null:null};return async function(i,r={}){const a=(i??"").trim();if(a===""){if(r.tools!==void 0||r.systemPrompt!==void 0||r.followUp===!0||r.resumeTool!==void 0||r.commandContext!==void 0)throw new Error("[openstation] wp.os.ai.ask: empty query passed with non-default options — likely a caller bug. Provide a query or call without options.");return{answer_type:"chat",message:"",entity:null,admin_links:null}}const l=sD(r.tools),c=iD(r.systemPrompt),d={query:a};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),l.length>0&&(d.command_tools=l),c&&(d.system_prompt_text=c.text,d.system_prompt_mode=c.mode);const u=await t(d,r.signal);if(!u.ok){const I=await u.json().catch(()=>({message:u.statusText}));throw new Error(`[openstation] wp.os.ai.ask: HTTP ${u.status} — ${I.message??u.statusText}`)}const f=await u.json();if(f.answer_type!=="tool_call"||!f.tool)return{answer_type:f.answer_type,message:f.message??"",entity:f.entity??null,admin_links:f.admin_links??null,request_id:f.request_id,continue:f.continue??null};const p=await n(f,r);if(!p.ok)return p.response;const{slug:g,args:h,result:m}=p;let _=rD(f.message,m);if(r.followUp===!0){const I=await o(a,g,h,m,c,r.signal);I!==null&&(_=I)}return{answer_type:"tool_call",message:_,entity:null,admin_links:null,toolCall:{slug:g,args:h,result:m},request_id:f.request_id}}}const et=ae("openstation/trash-optimistic",()=>({changes:new Map,reconcile:new Set})),lD=e=>`${e.type}:${e.id}`;function Sw(e){return{subtitle:"",mime:"",preview:"",icon:"",deleted_at:new Date().toISOString(),deleted_by:"",deleted_by_id:0,can_restore:!1,can_purge:!1,edit_link:"",...e}}function io(e){const t=e.file,n=t.type==="shortcut"?"shortcut":"placement";return Sw({id:t.type==="folder"?Number(t.ref):e.id,type:t.type==="folder"?"folder":n,title:t.title,icon:t.icon,preview:t.previewUrl})}function dD(){return Array.from(et.state.changes.values())}function uD(e,t){const n=et.subscribe(e);return()=>{n()}}function ln(e,t="in"){const n=lD(e);if(et.state.changes.get(n)?.pending)return null;const o={item:e,direction:t,pending:!0};return et.state.changes.set(n,o),et.notify(),{async finish(s){et.state.changes.get(n)!==o||!o.pending||(o.pending=!1,s&&(et.notify(),await Promise.allSettled(Array.from(et.state.reconcile,async i=>i()))),et.state.changes.get(n)===o&&(et.state.changes.delete(n),et.notify()))}}}const kw="[os-bin badge]";function lt(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(kw,...e)}catch{}}function dr(...e){console.warn(kw,...e)}const vs="desktop-mode-recycle-bin",fD="openstation_recycle_bin_seen_ts";function pD(){return window.wp?.os}const we=ae("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function bs(e){const t=Math.max(0,Math.floor(e)),n=we.state.current;we.state.current=t,lt("setRecycleBinCount",{prev:n,next:t}),ur(t)}function Iw(e){bs(we.state.current+e)}function hD(){return we.state.current}function ur(e){const t=dD().filter(i=>i.pending),o=e+t.reduce((i,r)=>i+(r.direction==="in"?1:-1),0)>0?we.state.fullArt:we.state.emptyArt;if(lt("paintIconState",{count:e,full:e>0,hasArt:!!o}),!o)return;const s=pD();s?.dock?.setArt?.(vs,o),s?.taskbar?.setArt?.(vs,o),s?.icons?.setArt?.(vs,o)}function mD(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;we.state.emptyArt=String(o?.recycleBinIconEmpty??""),we.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;lt("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:we.state.started,cfgCount:s,cfgUrl:i,cfgDebug:r,readyState:document.readyState});const a=Number(s);if((typeof s=="number"||typeof s=="string")&&Number.isFinite(a)||dr("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),we.state.started){bs(n);return}we.state.started=!0,we.state.countUrl=t,we.state.seenTs=Date.now(),bs(n),gD(),wD(),uD(()=>ur(we.state.current)),yD(),vD(),bD()}function gD(){ee(v.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===vs&&ur(we.state.current)})}function wD(){ee(v.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(vs)&&ur(we.state.current)})}function yD(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":Iw(+r);break;case"untrashed":case"deleted":Iw(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])Zn(`os.${s}.changed`,e)}function vD(){const e=window.location.origin;window.addEventListener("message",t=>{if(t.origin!==e)return;const n=t.data;if(!n||n.type!=="os-recycle-bin-changed")return;const o=typeof n.ts=="number"?n.ts:Date.now();if(o<=we.state.seenTs){lt("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:we.state.seenTs});return}lt("postMessage triggers refetch",{ts:o,prevSeenTs:we.state.seenTs}),we.state.seenTs=o,ED()})}function bD(){const e=window.jQuery;if(!e){dr("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}lt("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[fD]=we.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;lt("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>we.state.seenTs&&(we.state.seenTs=o.ts),typeof o.count=="number"&&bs(o.count))})}async function ED(){if(!we.state.countUrl){lt("refetchCount: no countUrl, skip");return}lt("refetchCount: hitting",we.state.countUrl);try{const e=await Ae(we.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}},{silent:!0,source:"desktop-mode/recycle-bin"});if(!e.ok){dr("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();lt("refetchCount: response",t),typeof t.count=="number"&&bs(t.count)}catch(e){dr("refetchCount: fetch failed",e)}}const _D="desktop-mode-os-settings",SD="desktop-mode-recycle-bin";function kD(e){const t=CD();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===_D?ID():i===SD?AD(s,e.getRecycleBinCount):n})}function ID(e){const t=document.createElement("span");t.className="os-dock-peek__card-body os-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="os-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="os-dock-peek__os-subtitle",o.textContent=b("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="os-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`os-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function AD(e,t){const n=document.createElement("span");n.className="os-dock-peek__card-body os-dock-peek__card-body--recycle-bin",n.setAttribute("aria-hidden","true");const o=Math.max(0,Math.floor(t()||0));n.dataset.empty=o===0?"true":"false";const s=document.createElement("span");s.className="os-dock-peek__bin-stage";const i=document.createElement("span");i.className="os-dock-peek__bin-stack";for(let l=0;l<3;l++){const c=document.createElement("span");c.className="os-dock-peek__bin-slip",i.appendChild(c)}s.appendChild(i);const r=document.createElement("span");r.className="os-dock-peek__bin-icon dashicons dashicons-trash",s.appendChild(r),n.appendChild(s);const a=document.createElement("span");return a.className="os-dock-peek__bin-label",o===0?a.textContent=b("Trash — empty"):o===1?a.textContent=b("1 item"):o>99?a.textContent="99+ items":a.textContent=`${o} items`,n.appendChild(a),n}function CD(){return window.wp?.hooks??null}const Es="desktop-mode-bug-report",LD="WordPress",TD="openstation",Aw=6e3;function ND(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="os-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="os-bug-report__intro",n.textContent=b("Found a bug or have a feature idea? Fill this in and we will open a pre-filled GitHub issue for you to review and submit."),t.appendChild(n),t.appendChild(OD()),t.appendChild(DD("title",b("Title"),{placeholder:b("A short summary"),required:!0})),t.appendChild(Cw("description",b("What happened? What did you expect?"),{placeholder:b("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(Cw("steps",b("Steps to reproduce (bug only)"),{placeholder:b("One step per line"),rows:4}));const o=RD();t.appendChild(o);const s=document.createElement("div");s.className="os-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="os-bug-report__submit",i.textContent=b("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=b("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",a=>{a.preventDefault();const l=MD(t);if(!l.title.trim()||!l.description.trim()){xD(t,b("Title and description are both required."));return}const c=WD(l);window.open(c,"_blank","noopener")}),e.appendChild(t)}function OD(){const e=document.createElement("div");e.className="os-bug-report__field os-bug-report__field--type";const t=document.createElement("span");t.className="os-bug-report__label",t.textContent=b("Type"),e.appendChild(t);const n=document.createElement("div");n.className="os-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:b("Bug"),checked:!0},{value:"feature",label:b("Feature request")},{value:"question",label:b("Question")}];for(const s of o){const i=document.createElement("label");i.className="os-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const a=document.createElement("span");a.textContent=s.label,i.appendChild(a),n.appendChild(i)}return e.appendChild(n),e}function DD(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 Cw(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 RD(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=b("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=Tw(Lw()),e.appendChild(n),e}function xD(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 MD(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 WD(e){const t=PD(e.type),n=$D(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/${LD}/${TD}/issues/new?${o.toString()}`}function PD(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function $D(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(Tw(Lw())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(` | |
| 35 | +`);return n.length>Aw&&(n=n.slice(0,Aw)+` | |
| 244 | 36 | |
| 37 | +…(truncated to fit GitHub URL length limit)`),n}function Lw(){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 Tw(e){return[`Plugin version: ${e.pluginVersion}`,`WordPress version: ${e.wordpressVersion}`,`User agent: ${e.userAgent}`,`Viewport: ${e.viewport}`,`Platform: ${e.platform}`,`Current URL: ${e.currentUrl}`].join(` | |
| 38 | +`)}let dn=null,Nw=!1,Ow=!1,Dw=!1,gl=null,_s=!1,wl=[],un="pending";const UD=5e3,BD=3e3;function FD(e,t,n){if(Ow)return;Ow=!0;const o=typeof t.shellBuild=="string"?t.shellBuild:"",s=(r,a)=>{GD(r).then(l=>{if(!(o!==""&&l!==""&&l!==o)){a&&Rw(r);return}a&&(gl=r),!(Dw||!n)&&(Dw=!0,n({current:o,served:l}))})},i=r=>{!r||typeof r.addEventListener!="function"||r.addEventListener("statechange",()=>{r.state==="installed"&&navigator.serviceWorker.controller&&s(r,!0)})};e.waiting&&navigator.serviceWorker.controller&&s(e.waiting,!0),i(e.installing??null),typeof e.addEventListener=="function"&&e.addEventListener("updatefound",()=>{i(e.installing??null)}),navigator.serviceWorker.addEventListener("controllerchange",()=>{if(gl=null,_s){_s=!1;const a=wl;wl=[];for(const l of a)l();return}const r=navigator.serviceWorker.controller;r&&s(r,!1)})}function Rw(e){_s=!0;try{e.postMessage({type:"os-sw-skip-waiting"})}catch{_s=!1}}function HD(){const e=gl;return e?new Promise(t=>{let n=!1;const o=()=>{n||(n=!0,window.clearTimeout(s),t())},s=window.setTimeout(o,BD);wl.push(o),Rw(e),_s||o()}):Promise.resolve()}function GD(e){return new Promise(t=>{let n=!1,o=0;const s=r=>{const a=r.data;a&&a.type==="os-sw-build"&&i(typeof a.shellBuild=="string"?a.shellBuild:"")},i=r=>{n||(n=!0,window.clearTimeout(o),navigator.serviceWorker.removeEventListener("message",s),t(r))};o=window.setTimeout(()=>i(""),UD),navigator.serviceWorker.addEventListener("message",s);try{e.postMessage({type:"os-sw-get-build"})}catch{i("")}})}const zD=5*6e4;let xw=null,yl=0;function jD(e){if(xw)return;yl=Date.now();const t=()=>{if(typeof document<"u"&&document.visibilityState==="hidden")return;const n=Date.now();if(!(n-yl<zD)){yl=n;try{e.update().catch(()=>{})}catch{}}};document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),xw=()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t)}}const VD=["/desktop-mode/sw.js"];function KD(e,t){if(e===t.swUrl||e===t.swFallbackUrl)return!0;try{const n=new URL(e);return n.pathname.endsWith("/openstation/sw.js")||n.searchParams.has("openstation_sw")?!0:VD.some(o=>n.pathname.endsWith(o))}catch{return!1}}function Mw(){const e=window.openStationConfig?.pwa?.swConfig;YD({adminAssetCache:e?.adminAssetCache===!0,windowPrewarm:e?.windowPrewarm===!0})}async function qD(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return un="unsupported",null;if(dn||Nw)return dn;if(!t.forceReplace){const s=(await navigator.serviceWorker.getRegistrations().catch(()=>[])).find(i=>{const r=i.active?.scriptURL??i.installing?.scriptURL??"";return r!==""&&!KD(r,e)});if(s)return un="foreign-sw",typeof console<"u"&&console.warn("[openstation] another service worker is already registered ("+s.scope+"); skipping openstation SW. Set openstation_pwa_force_replace_sw=true to override."),null}const n=async o=>navigator.serviceWorker.register(o,{scope:e.swScope||"/",updateViaCache:"none"});try{try{dn=await n(e.swUrl)}catch(o){if(!e.swFallbackUrl||e.swFallbackUrl===e.swUrl)throw o;dn=await n(e.swFallbackUrl)}return un="registered",FD(dn,e,t.onShellUpdated),jD(dn),Mw(),navigator.serviceWorker.addEventListener("controllerchange",Mw),dn}catch(o){return Nw=!0,un="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",o),null}}function YD(e){try{navigator.serviceWorker?.controller?.postMessage({type:"os-sw-config",...e})}catch{}}function XD(){return un}const ZD="os-pwa-install";function Ww(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function Pw(){if(Ww())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 Mt=null;function JD(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(),Mt=s}function o(){Mt=null,t({message:le(b("Installed %s as an app."),e)})}}function QD(e,t){return{id:ZD,title:b("Install web app"),icon:"dashicons-download",onOpen:()=>{eR(e,t)}}}async function eR(e,t){if(Mt){const n=Mt;Mt=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:b("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await Pw()){t({message:le(b("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(XD()==="foreign-sw"){t({message:b("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the openstation_pwa_force_replace_sw filter to true.")});return}t({message:b("Install isn't available right now. Keep using the page; if it still doesn't appear, the app may already be installed in this browser.")})}async function tR(){if(!Mt)return"unavailable";const e=Mt;Mt=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function nR(){Promise.resolve().then(()=>jL).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function oR(e,t,n){if(!e.pwa)return;Am(e.pwa),JD(e.pwa.appName||"WordPress",t);const o=n?()=>{t({message:b("A new version of OpenStation is available."),action:{label:b("Reload"),onClick:()=>{HD().then(()=>n())}},persistent:!0,dismissible:!0})}:void 0;qD(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw,onShellUpdated:o})}const Ss=ae("desktop-mode/drag-bridge-resolvers",()=>({byKind:new Map}));function sR(e,t){return Ss.state.byKind.set(e,t),()=>{Ss.state.byKind.get(e)===t&&Ss.state.byKind.delete(e)}}function iR(e){return Ss.state.byKind.has(e.kind)}async function rR(e){const t=Ss.state.byKind.get(e.kind);if(!t)return e;try{return await t(e)}catch(n){return console.error("[openstation] bridge payload resolver threw:",n),null}}const ro={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function aR(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function cR(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function lR(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function dR(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 uR{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(aR(n)){this._startDrag(n.payload);return}if(cR(n)){this._endDrag();return}if(lR(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=dR(t);this._payload=n,document.dispatchEvent(new CustomEvent(ro.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(ro.END,{detail:{payload:t}}))}}class fR{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 pR="os-drag-ghost",$w="os-drag-ghost--accept",Uw="os-drag-ghost--reject",hR="os-drag-hint",Bw="os-drag-hint--accept",Fw="os-drag-hint--reject",Hw="os-drag-hint--neutral",mR=16,gR=18;function wR(e,t,n){const o=SR(e),s=e.ghost?.offsetX??kR(e.source),i=e.ghost?.offsetY??IR(e.source);o.classList.add(pR),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=vR(e),a=r?yR():null;a&&document.body.appendChild(a);const l={get element(){return o},moveTo(c,d){o.style.transform=`translate3d(${c-s}px, ${d-i}px, 0)`,a&&(a.style.transform=`translate3d(${c+mR}px, ${d+gR}px, 0)`)},setMode(c,d){o.classList.remove($w,Uw),c==="accept"?o.classList.add($w):c==="reject"&&o.classList.add(Uw),a&&r&&(a.classList.remove(Bw,Fw,Hw),c==="accept"?(a.classList.add(Bw),a.textContent=d?.acceptLabel??r.accept):c==="reject"?(a.classList.add(Fw),a.textContent=r.reject):(a.classList.add(Hw),a.textContent=r.neutral),a.hidden=!a.textContent)},withHidden(c){const d=o.style.visibility,u=a?.style.visibility??"";o.style.visibility="hidden",a&&(a.style.visibility="hidden");try{return c()}finally{o.style.visibility=d,a&&(a.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),a?.isConnected&&a.remove()}};return l.moveTo(t,n),l.setMode("neutral"),l}function yR(){const e=document.createElement("div");return e.className=hR,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 vR(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??bR(e),reject:t?.reject??ER(),neutral:t?.neutral??_R(e)}}function bR(e){return e.type==="shortcut"?b("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?b("Drop here to move","desktop-mode"):b("Drop here","desktop-mode")}function ER(e){return b("Can’t drop here","desktop-mode")}function _R(e){return e.type==="shortcut"?b("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?b("Drop in a folder","desktop-mode"):""}function SR(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 kR(e){return e.offsetWidth/2}function IR(e){return e.offsetHeight/2}let Gw=!1;function AR(e){Gw||(Gw=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const zw=4,ke={START:"os.drag.start",MOVE:"os.drag.move",ENTER:"os.drag.enter",LEAVE:"os.drag.leave",REJECTED:"os.drag.rejected",COMMIT:"os.drag.commit",CANCEL:"os.drag.cancel",END:"os.drag.end"},fr="os-file-tile--dragging",jw="os-file-tile--drop-target",Vw="data-os-trash-drop-active",Kw="data-files-drop-active",qw="data-os-dragging",Yw="data-os-drag-type",vl="data-os-drag-mode";class CR{constructor(){this._registry=new fR,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)<zw&&Math.abs(s)<zw)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),vt(ke.MOVE,{payload:n.payload,clientX:t.clientX,clientY:t.clientY}))},this._onPointerUp=t=>{const n=this._active;if(!n||n._pointerId!==t.pointerId)return;if(!n._lifted){n._finished=!0,this._active=null;try{n._callbacks.onClickOnly?.()}catch(s){console.error("[openstation] drag onClickOnly threw:",s)}return}const o=this._hitTestNow(n,t.clientX,t.clientY);if(o&&o.accepted&&o.target){this._commit(n,o.target,t.clientX,t.clientY);return}this._cancel(n,o&&o.target?"rejected":"no-target")},this._onPointerCancel=t=>{const n=this._active;!n||n._pointerId!==t.pointerId||this._cancel(n,"pointercancel")}}start(t){if(this._active||t.origin.button!==0||Vt())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(),AR(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:()=>Xw(),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(fr),t._ghost=wR(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(qw,""),document.body.setAttribute(Yw,String(t.payload.type)),document.body.setAttribute(vl,"neutral")),vt(ke.START,{payload:t.payload})}_hitTestNow(t,n,o){const s=()=>{const i=document.elementFromPoint(n,o),r=this._registry.hitTest(i);if(!r)return{target:null,accepted:!1};let a=!1;try{a=r.accept(t.payload)}catch(l){console.error("[openstation] drop target accept() threw:",r.id,l)}return{target:r,accepted:a}};return t._ghost?t._ghost.withHidden(s):s()}_updateHover(t,n,o){const s=this._hitTestNow(t,n,o),i=t._currentTarget;if(s.target===i&&s.accepted===t._currentAccepted)return;i&&bl(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(LR(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),vt(ke.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(vl,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),bl(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)}vt(ke.COMMIT,{payload:t.payload,targetId:n.id}),vt(ke.END,{payload:t.payload,reason:"commit"}),this._active===i&&(this._active=null)}_cancel(t,n){if(!t._finished){t._finished=!0,t._lifted&&(this._lastLiftedEndAt=Date.now()),t._currentTarget&&bl(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}vt(ke.CANCEL,{payload:t.payload,reason:n}),vt(ke.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(fr)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(qw),document.body.removeAttribute(Yw),document.body.removeAttribute(vl)),TR()}}function vt(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function LR(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}vt(ke.ENTER,{payload:t.payload,targetId:e.id})}function bl(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}vt(ke.LEAVE,{payload:t.payload,targetId:e.id})}function Xw(){if(typeof document>"u")return[];const e=[];for(const t of[`.${fr}`,`.${jw}`,`[${Vw}]`,`[${Kw}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function TR(){for(const e of Xw())e.classList.remove(fr,jw),e.removeAttribute(Vw),e.removeAttribute(Kw)}const NR=".os-window",Zw="wp-window-";function Jw(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(NR);return o instanceof HTMLElement?o:null}function OR(e){if(!e.id.startsWith(Zw))return null;const t=e.id.slice(Zw.length);return t.length>0?t:null}const DR="desktop-mode-iframe-drop-",pr="iframe.os-window__iframe",El="data-os-iframe-drop-active";let _l=!1,Qw=null;const Ke=new Map,fn=new Map;let bt=null,pn=null;function RR(){document.querySelectorAll(pr).forEach(t=>{Ke.has(t)||(Ke.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function xR(){Ke.forEach((e,t)=>{t.style.pointerEvents=e}),Ke.clear()}function ey(e,t){const n=Jw(e,t);if(!n)return null;const o=n.querySelector(pr);return o instanceof HTMLIFrameElement?o:null}const ty=e=>{if(!bt)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=ey(e.clientX,e.clientY);if(t===pn){t&&Sl(t,e.clientX,e.clientY);return}pn&&(kl(),dt(pn,{type:"os-drag-leave"})),pn=t,t&&(dt(t,{type:"os-drag-over",payload:bt}),Sl(t,e.clientX,e.clientY))},ny=e=>{if(!bt)return;const t=ey(e.clientX,e.clientY);if(!t){e.preventDefault(),hr();return}e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const n=bt;hr();const o=t.getBoundingClientRect();dt(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},oy=()=>{hr()};function MR(e){if(bt){bt=e;return}bt=e,RR(),document.addEventListener("dragover",ty,!0),document.addEventListener("drop",ny,!0),document.addEventListener("dragend",oy,!0)}function hr(){bt&&(bt=null,kl(),pn&&(dt(pn,{type:"os-drag-leave"}),pn=null),document.removeEventListener("dragover",ty,!0),document.removeEventListener("drop",ny,!0),document.removeEventListener("dragend",oy,!0),xR())}function mr(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}let ao=null,gr=null,co=0;function Sl(e,t,n){gr={iframe:e,clientX:t,clientY:n},!co&&(co=requestAnimationFrame(()=>{co=0;const o=gr;if(gr=null,!o||!o.iframe.isConnected)return;const s=o.iframe.getBoundingClientRect();dt(o.iframe,{type:"os-drag-move",position:{x:o.clientX-s.left,y:o.clientY-s.top}})}))}function kl(){gr=null,co&&(cancelAnimationFrame(co),co=0)}function dt(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function WR(e,t){let n;try{n=new URL(e.src)}catch{return}if(!/\/post(-new)?\.php$/.test(n.pathname))return;const o=ze(t)?.type??n.searchParams.get("post_type");return b(o==="page"?"Add to page":"Add to post","desktop-mode")}function PR(e,t,n,o){return e.registerDropTarget({id:`${DR}${o}`,element:n,accept:s=>!!mr(s),acceptLabel:WR(t,o),onEnter:s=>{const i=mr(s.payload);i&&(n.setAttribute(El,""),ao=t,dt(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(El),ao===t&&(ao=null),dt(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(El),ao=null;const r=mr(s.payload);if(!r)return;const a=t.getBoundingClientRect(),l={x:i.clientX-a.left,y:i.clientY-a.top};if(!iR(r)){dt(t,{type:"os-drop",payload:r,position:l});return}$R(t,r,l)}})}async function $R(e,t,n){const o=await rR(t);if(!o){dt(e,{type:"os-drag-leave"});return}dt(e,{type:"os-drop",payload:o,position:n})}function sy(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 UR(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 BR(e){const t=Qw;if(!t)return;const n=document.querySelectorAll(pr),o=!!mr(e);UR(n.length,o,e),n.forEach(s=>{if(Ke.has(s)||(Ke.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||fn.has(s))return;const i=s.parentElement;if(!i)return;const r=sy(s),a=PR(t,s,i,r);fn.set(s,a)})}function FR(){kl(),ao=null,Ke.forEach((e,t)=>{t.style.pointerEvents=e}),Ke.clear(),fn.forEach(e=>{try{e()}catch{}}),fn.clear()}function HR(e){_l||(_l=!0,Qw=e,document.addEventListener(ke.START,t=>{const n=t.detail;BR(n?.payload)}),document.addEventListener(ke.END,()=>{FR()}),document.addEventListener(ke.MOVE,t=>{const n=ao;if(!n)return;const o=t.detail;typeof o?.clientX!="number"||typeof o?.clientY!="number"||Sl(n,o.clientX,o.clientY)}),document.addEventListener(ro.START,t=>{const n=t.detail;n?.payload&&MR(n.payload)}),document.addEventListener(ro.END,()=>{hr()}),ee(v.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(Ke))t.isConnected||Ke.delete(t);for(const[t,n]of Array.from(fn))if(!t.isConnected){try{n()}catch{}fn.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:_l,iframesInDom:document.querySelectorAll(pr).length,suppressedCount:Ke.size,registeredCount:fn.size,suppressedIframeIds:Array.from(Ke.keys()).map(sy)}))}const GR=250,zR=1e3,jR="os-drag-hover";let iy=!1,Il=null,Al=null,ks=null,Is=null,Cl=null;function ry(){ks!==null&&(clearTimeout(ks),ks=null)}function ay(){Is!==null&&(clearTimeout(Is),Is=null)}function As(){ry(),ay(),Al=null}function cy(){ay(),Is=setTimeout(()=>{Is=null,As()},zR)}function VR(e,t){const n=Il?.getById(e);if(!(!n||n.isFocused()||!J(v.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{Il?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function ly(e,t){e!==Al&&(ry(),Al=e,e!==null&&(ks=setTimeout(()=>{ks=null,VR(e,t)},GR)))}function dy(e,t,n){const o=Jw(e,t);ly(o?OR(o):null,n)}const KR=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||dy(t.clientX,t.clientY,t.payload?.type??"")},qR=()=>{As()};function YR(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 XR=e=>{cy();const t=Cl??(YR(e)?"os-file":"external");dy(e.clientX,e.clientY,t)},uy=()=>{As()},ZR=e=>{e.relatedTarget===null&&As()};function JR(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 QR=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==jR)return;const n=JR(e.source);n&&(cy(),ly(n,typeof t.payloadType=="string"?t.payloadType:"external"))},ex=e=>{const t=e.detail;t?.payload&&(Cl=t.payload.kind??"")},tx=()=>{Cl=null,As()};function nx(e){iy||(iy=!0,Il=e,document.addEventListener(ke.MOVE,KR),document.addEventListener(ke.END,qR),document.addEventListener(ro.START,ex),document.addEventListener(ro.END,tx),document.addEventListener("dragover",XR,!0),document.addEventListener("drop",uy,!0),document.addEventListener("dragend",uy,!0),document.addEventListener("dragleave",ZR,!0),window.addEventListener("message",QR))}function fy(){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=J("os.open-command.items",o);return Array.isArray(i)?i:o}const ox={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=fy();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=fy(),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 sx(){Xn(ox)}const Ie=[],ix=new Set;function py(e){if(!e||typeof e.id!="string"||e.id==="")return()=>{};if(typeof e.open!="function"||typeof e.close!="function"||typeof e.isOpen!="function")return()=>{};const t=Ie.findIndex(n=>n.id===e.id);return t>=0?Ie[t]=e:Ie.push(e),Ll(),()=>{const n=Ie.findIndex(o=>o.id===e.id);n>=0&&(Ie.splice(n,1),Ll())}}function rx(e){const t=Ie.findIndex(n=>n.id===e);t>=0&&(Ie.splice(t,1),Ll())}function hy(){return Ie.slice()}function Ll(){for(const e of Array.from(ix))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",t)}}function lo(e,t){try{document.dispatchEvent(new CustomEvent(t?"os-palette-opened":"os-palette-closed",{detail:{id:e}}))}catch{}}function my(){if(Ie.length===0)return;const e=Ie.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{Ie[0].open(),lo(Ie[0].id,!0)}catch{}return}try{Ie[e].close(),lo(Ie[e].id,!1)}catch{}const t=e+1;if(t<Ie.length)try{Ie[t].open(),lo(Ie[t].id,!0)}catch{}}function wr(e){const t=Ie.find(n=>n.id===e);if(t){for(const n of Ie)if(n.id!==e)try{n.isOpen()&&(n.close(),lo(n.id,!1))}catch{}try{t.open(),lo(t.id,!0)}catch{}}}let gy=!1;function ax(){if(gy)return;gy=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),my())},!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"&&my()})}const tt=ae("os/presence",()=>({byUser:new Map,serverTimeMs:0})),cx=5*60*1e3;let wy=Date.now(),yy=!1;function yr(){wy=Date.now()}function lx(e){if(!e||!e.snapshot)return;const t=tt.state.byUser,n=new Map(t),o=[];for(const[s,i]of Object.entries(e.snapshot)){const r=Number(s);if(!Number.isFinite(r)||r<=0)continue;const l={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=t.get(r);n.set(r,l),(!c||c.status!==l.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:l.status,entry:l})}tt.state.byUser=n,typeof e.serverTimeMs=="number"&&(tt.state.serverTimeMs=e.serverTimeMs),tt.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),_e.publish("os/presence-changed",i)}_e.publish("os/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function dx(){yy||(yy=!0,document.addEventListener("pointerdown",yr,{capture:!0,passive:!0}),window.addEventListener("keydown",yr,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||yr()}),Re.contribute("openstation_presence_active",()=>!0),Re.contribute("openstation_user_active",()=>Date.now()-wy<cx),Re.subscribe("openstation_presence",e=>{lx(e)}))}function ux(e){const t=tt.state.byUser.get(e);return t?t.status:"offline"}function fx(){return new Map(tt.state.byUser)}function px(e){return tt.state.byUser.get(e)??null}function hx(e){return tt.subscribe(t=>e(t))}function mx(){yr()}function gx(e){if(!Array.isArray(e)||e.length===0)return;const t=tt.state.byUser,n=new Map(t),o=[];for(const s of e){const i=Number(s.userId);if(!Number.isFinite(i)||i<=0)continue;const r=t.get(i),a={status:s.status,lastSeenMs:typeof s.lastSeenMs=="number"?s.lastSeenMs:r?.lastSeenMs??0,lastActiveMs:typeof s.lastActiveMs=="number"?s.lastActiveMs:r?.lastActiveMs??0};n.set(i,a),(!r||r.status!==a.status)&&o.push({userId:i,oldStatus:r?r.status:null,newStatus:a.status,entry:a})}if(!(o.length===0&&n.size===t.size)){tt.state.byUser=n,tt.notify();for(const s of o){const i={userId:s.userId,oldStatus:s.oldStatus,newStatus:s.newStatus,lastSeenMs:s.entry.lastSeenMs,lastActiveMs:s.entry.lastActiveMs};document.dispatchEvent(new CustomEvent("os-presence-changed",{detail:i})),_e.publish("os/presence-changed",i)}_e.publish("os/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const wx=Object.freeze({getStatus:ux,getAll:fx,getEntry:px,subscribe:hx,markActive:mx,applyBatch:gx});function vy(e){const t=new Set;let n=null;const o=new Set;e.onChange&&o.add(e.onChange);const s=()=>e.order().filter(a=>t.has(a)),i=()=>{const a=s();for(const l of o)try{l(a)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=a=>{const l=t.size,c=Array.from(t);a(),!(t.size===l&&c.every(d=>t.has(d)))&&i()};return{keys:s,has:a=>t.has(a),size:()=>t.size,anchor:()=>n,set(a){r(()=>{t.clear();for(const l of a)t.add(l)}),n=a.length>0?a[a.length-1]:null},add(a){r(()=>{t.add(a)}),n=a},remove(a){r(()=>{t.delete(a)}),n===a&&(n=null)},toggle(a){r(()=>{t.has(a)?t.delete(a):t.add(a)}),n=a},selectRange(a,l=!1){const c=e.order(),d=c.indexOf(a),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{l||t.clear(),t.add(a)}),n=a;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{l||t.clear();for(let g=f;g<=p;g+=1)t.add(c[g])})},selectAll(){const a=e.order();r(()=>{for(const l of a)t.add(l)}),n===null&&a.length>0&&(n=a[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const a=new Set(e.order());let l=!1;return r(()=>{for(const c of Array.from(t))a.has(c)||(t.delete(c),l=!0)}),n!==null&&!a.has(n)&&(n=null),l},subscribe(a){return o.add(a),()=>{o.delete(a)}}}}const yx=".os-file-tile",vx="os-file-tile--selected",bx="os-selection-marquee",by=4,Ey=36,_y=12,Sy="data-os-marquee";function Ex(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function _x(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(Sy,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(Sy)}}const Sx=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note, .os-mobile-home, .os-mobile-edge",kx="os-area--overview";function Ix(e,t){const n=t.itemSelector??yx,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??Sx,r=()=>Array.from(e.querySelectorAll(n)).filter(L=>t.keyOf(L)!==null),a=()=>{const L=[],M=new Map;r().forEach((H,z)=>{const y=H.parentElement??e;let E=M.get(y);E||(E=[],M.set(y,E),L.push(y)),E.push({key:t.keyOf(H),top:parseFloat(H.style.top)||0,left:parseFloat(H.style.left)||0,index:z})});const P=[];for(const H of L){const z=M.get(H)??[];z.sort((y,E)=>y.top!==E.top?y.top-E.top:y.left!==E.left?y.left-E.left:y.index-E.index);for(const y of z)P.push(y.key)}return P},l=t.order??a,c=vy({order:l,onChange:L=>{p(),t.onChange?.(L),u(L)}}),d={},u=L=>{typeof document>"u"||(uo={surface:t.surface??"",scope:t.scope??"",keys:L.slice(),count:L.length},Nl=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:uo})))},f=L=>r().find(M=>t.keyOf(M)===L)??null,p=()=>{for(const L of r()){const M=t.keyOf(L),P=c.has(M);P!==L.hasAttribute("selected")&&(P?L.setAttribute("selected",""):L.removeAttribute("selected")),L.classList.toggle(vx,P),L.hasAttribute("selectable")||L.setAttribute("selectable","");const H=P?"true":"false";L.getAttribute("aria-selected")!==H&&L.setAttribute("aria-selected",H)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let g=null;const h=L=>{if(!(L.target instanceof Element))return;const M=L.target.closest(n);if(M&&e.contains(M)){const P=t.keyOf(M);if(P===null)return;if(g=P,L.stopPropagation(),L.shiftKey){c.selectRange(P,L.ctrlKey||L.metaKey);return}if(L.ctrlKey||L.metaKey){c.toggle(P);return}c.set([P]);return}if($){$=!1;return}c.clear()};o.addEventListener("click",h);let m=null,_=null,I=null,O=[],$=!1,S=0,R=null,W=null;const U=L=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(L),W=L}catch{}},F=()=>{if(W===null||typeof o.releasePointerCapture!="function"){W=null;return}try{o.hasPointerCapture?.(W)&&o.releasePointerCapture(W)}catch{}W=null},K=(L,M)=>{const P=o.getBoundingClientRect();return{x:L-P.left+o.scrollLeft,y:M-P.top+o.scrollTop}},Q=()=>{m?.remove(),m=null,_=null,I=null,R?.(),R=null,F(),S&&(cancelAnimationFrame(S),S=0),document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",V),document.removeEventListener("pointercancel",j),o.removeEventListener("lostpointercapture",j),o.removeEventListener("scroll",Z),window.removeEventListener("blur",j)};function Z(){if(!_||!I)return;const L=K(I.x,I.y),M=L.x-_.x,P=L.y-_.y;if(!m&&Math.abs(M)<by&&Math.abs(P)<by)return;m||(m=document.createElement("div"),m.className=bx,m.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(m),$=!0,R=_x(o),C());const H=Math.min(_.x,L.x),z=Math.min(_.y,L.y),y=Math.abs(M),E=Math.abs(P);m.style.left=`${H}px`,m.style.top=`${z}px`,m.style.width=`${y}px`,m.style.height=`${E}px`;const T=o.getBoundingClientRect(),x=T.left-o.scrollLeft,X=T.top-o.scrollTop,Y={left:H+x,top:z+X,right:H+y+x,bottom:z+E+X},ce=[];for(const q of r()){const se=q.getBoundingClientRect();se.left<Y.right&&se.right>Y.left&&se.top<Y.bottom&&se.bottom>Y.top&&ce.push(t.keyOf(q))}c.set(Array.from(new Set([...O,...ce])))}function C(){if(S||typeof requestAnimationFrame!="function")return;const L=()=>{if(S=0,!m||!I)return;const M=o.getBoundingClientRect();if(Ex(o)){let H=0;if(I.y<M.top+Ey?H=-_y:I.y>M.bottom-Ey&&(H=_y),H!==0){const z=o.scrollTop;o.scrollTop+=H,o.scrollTop!==z&&Z()}}S=requestAnimationFrame(L)};S=requestAnimationFrame(L)}const D=L=>{_&&(I={x:L.clientX,y:L.clientY},Z())},V=()=>{m&&(Tl=Date.now()),Q()},j=()=>{Q()},te=L=>{if(!s||L.button!==0||!(L.target instanceof Element)||o.classList.contains(kx)||L.target.closest(n))return;const M=L.target.closest(i);M&&M!==o&&o.contains(M)||(_=K(L.clientX,L.clientY),I={x:L.clientX,y:L.clientY},typeof L.pointerId=="number"&&U(L.pointerId),O=L.ctrlKey||L.metaKey||L.shiftKey?c.keys():[],O.length===0&&c.clear(),document.addEventListener("pointermove",D),document.addEventListener("pointerup",V),document.addEventListener("pointercancel",j),o.addEventListener("lostpointercapture",j),window.addEventListener("blur",j),o.addEventListener("scroll",Z,{passive:!0}))};o.addEventListener("pointerdown",te);const N=L=>{if(L.key==="a"&&(L.ctrlKey||L.metaKey)){L.preventDefault(),c.selectAll();return}if(L.key==="Escape"){if(m||_){Q();return}c.size()>0&&c.clear();return}const M=L.key==="ArrowRight"||L.key==="ArrowDown",P=L.key==="ArrowLeft"||L.key==="ArrowUp";if(!M&&!P)return;const H=M?1:-1,z=l();if(z.length===0)return;const y=g??c.anchor(),E=y===null?-1:z.indexOf(y),T=Math.min(z.length-1,Math.max(0,E<0?0:E+H));L.preventDefault();const x=z[T];g=x,L.shiftKey?c.selectRange(x):c.set([x]),f(x)?.focus()};return e.addEventListener("keydown",N),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){Q(),o.removeEventListener("click",h),o.removeEventListener("pointerdown",te),e.removeEventListener("keydown",N),Nl===d&&(uo=null,Nl=null)}}}let Tl=0;function Ax(){return Tl>0&&Date.now()-Tl<500}let uo=null,Nl=null;function Cx(){return uo?{...uo,keys:uo.keys.slice()}:null}function Ol(e){return typeof e.sort=="number"?e.sort:100}function Lx(e,t){return le(b("%1$s (%2$d items)","desktop-mode"),e,t)}function ky(e,t){if(e.length===0)return[];const n=e.map(a=>{const l=t(a);return Array.isArray(l)?l:[]});if(e.length===1)return n[0];const o=e.length,s=[],i=a=>a.multiId??a.id;for(const a of n[0]){const l=i(a),c=[];let d=!1;for(const p of n){const g=p.find(h=>i(h)===l);if(!g||g.multi!==!0){d=!0;break}c.push(g)}if(d||s.some(p=>p.id===l))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):Lx(u.label,o);s.push({id:l,label:f,icon:u.icon,disabled:c.some(p=>p.disabled===!0),danger:c.some(p=>p.danger===!0),sort:Math.min(...c.map(Ol)),multi:!0,onClick:async p=>{const g=new Map,h=[];c.forEach((m,_)=>{const I=m.bulk;if(typeof I!="function"){h.push(m);return}const O=g.get(I);O?O.push(e[_]):g.set(I,[e[_]])});for(const[m,_]of g)try{await m(_)}catch(I){console.error(`[openstation] selection action '${l}' failed for a batch:`,I)}for(const m of h)try{await m.onClick(p)}catch(_){console.error(`[openstation] selection action '${l}' failed for one item:`,_)}}})}s.sort((a,l)=>{const c=Ol(a),d=Ol(l);return c!==d?c-d:a.label.localeCompare(l.label)});const r=J("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function Iy(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 Dl=8;function Ay(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function Rl(e){Ay(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-Dl)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-Dl)}px`)})}function Cy(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,Ay(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-Dl)}px`)})}const Tx="os-wallpaper-menu";let fo=null,xl=null,Ly=0;function Ml(){if(!fo)return;const e=fo.dataset.menuScope??"selection",t=xl;fo.dispatchEvent(new CustomEvent("tile-menu-closed")),fo.remove(),fo=null,xl=null,t?.(),A(`os.${e}.menu.closed`,{})}function Nx(e,t){Ml();const n=++Ly;si(()=>n===Ly,()=>Ox(e,t))}function Ox(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(Tx),o&&a.classList.add(o),a.dataset.menuScope=s;for(const[u,f]of Object.entries(n??{}))a.dataset[u]=f;a.style.left=`${e.x}px`,a.style.top=`${e.y}px`;const l=new Map;for(const u of t){l.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.danger&&f.setAttribute("danger",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",Dx(u.icon)),f.textContent=u.label,a.appendChild(f)}a.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=l.get(f.id);p&&(Ml(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(g=>{console.error(`[openstation] menu action '${p.id}' threw:`,g)}))}),document.body.appendChild(a),fo=a,xl=r??null,Rl(a);const c=Iy(a,{close:()=>Ml()});a.addEventListener("tile-menu-closed",c);const d=t.map(u=>u.id);i?.(d),A(`os.${s}.menu.opened`,{items:d,count:t.length})}function Dx(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const Rx={active:Cx,resolveCommonActions:ky,createModel:vy};let Cs=null;function xx(){Re.contribute("openstation_content_changes_seen_ts",()=>Cs===null?0:Cs),Re.subscribe("openstation_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=Cs===null,n=Cs??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===""||(Ji(`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));Cs=o})}const Mx="desktop_mode_nonces",Wl=new Map;let Ty=!1;function Pl(e,t){if(typeof e!="string"||e==="")return()=>{};let n=Wl.get(e);return n||(n=new Set,Wl.set(e,n)),n.add(t),()=>{n.delete(t)}}function Wx(){Ty||(Ty=!0,Re.subscribe(Mx,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=Wl.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)}}}),Px())}function Px(){Pl("wp_rest",$x),Pl("desktop-mode-plugins",e=>{Ny("desktop-mode-plugins","ajaxNonce",e)}),Pl("updates",e=>{Ny("desktop-mode-plugins","updatesNonce",e)})}function $x(e){const t=Ux();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=Oy();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function Ny(e,t,n){const s=Oy()?.[e];if(!s||typeof s!="object")return;const i=s,r=i.extra;let a=!1;r&&typeof r=="object"&&t in r&&(r[t]=n,a=!0),(t in i||!a)&&(i[t]=n)}function Ux(){if(!(typeof window>"u"))return window.openStationConfig}function Oy(){if(!(typeof window>"u"))return window.openStationWindowConfig}const Bx="desktop_mode_auth",Fx=5e3,Dy=1e3,Hx=1e4;let Ry=!1,vr=!1,$l=!1,br=0,xy=0,Ls=0,po=null,My=0,Wy=null,Py=null,$y=()=>{try{window.location.reload()}catch{}};function Ul(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function Bl(e=Dy){const t=Date.now();if(t<Ls){po===null&&(po=window.setTimeout(()=>{po=null,Ls=Date.now()+Dy,Ul()},Ls-t));return}Ls=t+e,Ul()}function Gx(){vr=!0,!$l&&($l=!0,A(v.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function zx(){for(const e of jx())try{e.contentWindow?.location.reload()}catch{}}function jx(){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 Fl(){const e=Date.now();e-My<Hx||(My=e,vr=!1,$l=!1,po!==null&&(window.clearTimeout(po),po=null),Ls=0,Bl(),zx(),A(v.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function Vx(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(br<=0){br=t;return}t!==br&&$y()}}function Kx(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<xy||(xy=o+Fx,Ul())}function qx(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");Py=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&Bl(),t=n}),Py.observe(e,{attributes:!0,attributeFilter:["class"]})}function Yx(e={}){Ry||(Ry=!0,br=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&($y=e.reloadShell),Re.subscribe("wp-auth-check",t=>{if(t===!1){Gx();return}t===!0&&vr&&Fl()}),Re.subscribe("nonces_expired",()=>{if(vr){Fl();return}Bl()}),Re.subscribe(Bx,Vx),Wy=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&Fl()},window.addEventListener("message",Wy),qx())}const ho=12;function Hl(e,t){return Uy(fe(e,t.adminUrl),t)}function Uy(e,t){if(e)return(t.dockItems||[]).find(n=>fe(n.url,t.adminUrl)===e||(n.submenu||[]).some(o=>fe(o.url,t.adminUrl)===e))}function Xx(e,t){const n=fe(e,t.adminUrl);if(!n)return;const o=t.dockItems||[],s=o.find(i=>fe(i.url,t.adminUrl)===n);if(s?.title)return s.title;for(const i of o){const r=(i.submenu||[]).find(a=>fe(a.url,t.adminUrl)===n);if(r?.title)return r.title}}function By(e,t){const n=t.x??0,o=t.y??0,s=Math.max(200,t.width-ho*2),i=Math.max(200,t.height-ho*2),r=Math.min(e.width,s),a=Math.min(e.height,i),l=n+Math.max(0,t.width-r-ho),c=o+Math.max(0,t.height-a-ho),d=Math.max(n+ho,Math.min(e.x,l)),u=Math.max(o+ho,Math.min(e.y,c));return{x:d,y:u,width:r,height:a}}const Fy=window.location.origin;function Zx(e,t){document.addEventListener("click",n=>{if(n.defaultPrevented||n.button!==0||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey)return;const o=n.target,s=o&&o.closest?o.closest("a[href]"):null;if(!s)return;const i=s,r=i.getAttribute("target");if(r&&r!==""&&r!=="_self"||i.hasAttribute("download"))return;const a=i.getAttribute("href");if(!a||a.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(a))return;let l;try{l=new URL(a,window.location.href)}catch(m){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",a,m);return}if(l.origin!==Fy)return;let c;try{c=new URL(t.adminUrl).pathname}catch(m){typeof console<"u"&&console.error("[openstation] config.adminUrl is not a valid URL; falling back to /wp-admin/:",t.adminUrl,m),c="/wp-admin/"}if(!l.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(l.pathname)||l.searchParams.has("action")&&l.searchParams.get("action")==="logout"||l.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Me(l.href)))return;const d=fe(l.href,t.adminUrl),u=Hl(l.href,t),f=(i.dataset.osWindowTitle||"").trim(),p=(i.textContent||"").trim()||u?.title||"",g=!!i.closest("#wp-admin-bar-new-content"),h={id:d,baseId:d,multi:!!u?.multi||g,url:l.href,parentUrl:u?.url??l.href,title:f||u?.title||p,icon:u?.icon||"dashicons-admin-generic",submenu:u?.submenu,selfLabel:u?.selfLabel};if(g){e.openNew(h);return}e.open(h)},!0)}function Hy(e){const t=e?.scriptDepPayloads;if(!t||typeof t!="object")return e;const n=e;for(const o of Object.keys(n)){if(o==="scriptDepPayloads")continue;const s=n[o];if(!(!s||typeof s!="object"))for(const i of Object.values(s)){if(!i||typeof i!="object")continue;const r=i.scriptDeps;Array.isArray(r)&&(i.scriptDeps=Jx(r,t,o))}}return e}function Jx(e,t,n){const o=[];for(const s of e){if(typeof s!="string"){o.push(s);continue}const i=t[s];if(i){o.push({...i,handle:s});continue}console.warn(`[openstation] ${n}: script dependency "${s}" is not in scriptDepPayloads and was dropped.`)}return o}function Qx(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 eM(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 tM(e){const t=Qx(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=eM(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 nM="os-registry-changed";function oM(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 Gl(e,t,n){const{added:o,removed:s}=oM(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(nM,{detail:i}))}function sM(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:a,syncServerTitleBarButtons:l,syncServerWindowActions:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:g,renderIcons:h,applyDesktopIcons:m,refreshRootPlacements:_,syncShortcuts:I,applyMultisite:O}=e,$=S=>(S??[]).map(R=>String(R?.id??"")).sort().join(` | |
| 39 | +`);return function(R){Hy(R),R.scriptDepPayloads&&typeof R.scriptDepPayloads=="object"&&(n.scriptDepPayloads={...n.scriptDepPayloads,...R.scriptDepPayloads});const W=R.dockItems,U=R.nativeWindows,F=R.serverWidgets,K=R.serverWallpapers,Q=R.serverCommandScripts,Z=R.serverCommands,C=R.serverSettingsTabScripts,D=R.serverSettingsTabs,V=R.serverDockRailRendererScripts,j=R.serverTitleBarButtonScripts,te=R.serverWindowActionScripts,N=R.serverUnfocusEffectScripts,L=R.serverWindowLinkRendererScripts,M=R.serverWindowNotices,P=R.serverGames,H=R.serverDesktopThemes,z=R.desktopIcons;if(!Array.isArray(W)||W.length===0)return;const y=n.dockItems;if(t(W),n.dockItems=W,Gl("dock-items",y,W),I?.(),Array.isArray(U)){const E=n.nativeWindows;o(cw(U,R.nativeWindowScriptData)),n.nativeWindows=U,R.nativeWindowScriptData&&(n.nativeWindowScriptData=R.nativeWindowScriptData),Gl("native-windows",E,U)}if(Array.isArray(F)&&(s(F),n.serverWidgets=F),Array.isArray(K)&&(i(K),n.serverWallpapers=K),Array.isArray(P)&&(p(P),n.serverGames=P),Array.isArray(H)&&(g?.(H),n.serverDesktopThemes=H),Array.isArray(Q)&&(r(Q,Array.isArray(Z)?Z:void 0),n.serverCommandScripts=Q,Array.isArray(Z)&&(n.serverCommands=Z)),Array.isArray(C)&&(a(C,Array.isArray(D)?D:void 0),n.serverSettingsTabScripts=C,Array.isArray(D)&&(n.serverSettingsTabs=D)),Array.isArray(j)&&(l(j),n.serverTitleBarButtonScripts=j),Array.isArray(te)&&(c(te),n.serverWindowActionScripts=te),Array.isArray(N)&&(d(N),n.serverUnfocusEffectScripts=N),Array.isArray(L)&&(u(L),n.serverWindowLinkRendererScripts=L),Array.isArray(V)&&(f(V),n.serverDockRailRendererScripts=V),Array.isArray(M)&&(xg(M),n.serverWindowNotices=M),Array.isArray(z)){const E=n.desktopIcons;h(z),m?.(z),I?.(),$(E)!==$(z)&&_?.(),n.desktopIcons=z,Gl("desktop-icons",E,z)}tM(R.updateCounts),"multisite"in R&&O?.(R.multisite??null)}}const iM=8e3,rM=600;function aM(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:h,applyMultisite:m,renderIcons:_,refreshRootPlacements:I,syncShortcuts:O}=e,$=sM({applyDockItems:C=>t?.applyDockItems(C),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:a,syncServerSettingsTabs:l,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:h,applyMultisite:m,renderIcons:_,applyDesktopIcons:C=>t?.applyDesktopIcons(C),refreshRootPlacements:I,syncShortcuts:O});let S=typeof o.menuSig=="string"?o.menuSig:"",R=!1,W=null,U=!1,F=!1;const K=()=>{if(!o.adminUrl)return Promise.resolve();const C=(()=>{try{const D=new URL("admin.php",o.adminUrl);return D.searchParams.set("openstation_chromeless","1"),D.searchParams.set("openstation_menu_refresh","1"),D.toString()}catch{return null}})();return C?new Promise(D=>{const V=document.createElement("iframe");V.setAttribute("aria-hidden","true"),V.tabIndex=-1,V.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",V.src=C;let j=!1;const te=()=>{j||(j=!0,window.clearTimeout(L),window.removeEventListener("message",N),V.parentNode&&V.parentNode.removeChild(V),D())},N=M=>{if(M.source!==V.contentWindow)return;const P=M.data;!P||P.type!=="os-plugins-changed"||te()},L=window.setTimeout(()=>{A(v.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),te()},iM);window.addEventListener("message",N),document.body.appendChild(V)}):Promise.resolve()},Q=()=>{if(U){F=!0;return}U=!0,K().finally(()=>{U=!1,F&&(F=!1,Q())})},Z=()=>{W!==null&&window.clearTimeout(W),W=window.setTimeout(()=>{W=null,Q()},rM)};return window.addEventListener("message",C=>{if(C.origin!==Fy)return;const D=C.data;if(D){if(D.type==="os-plugins-changed"){D.payload&&($(D.payload),typeof D.payload.menuSig=="string"&&(S=D.payload.menuSig));return}if(D.type==="os-updates-changed"){Z();return}if(D.type==="os-menu-signature"){const V=D.sig;typeof V=="string"&&V!==""&&V!==S&&!R&&(R=!0,K().finally(()=>{R=!1}))}}}),K}function Gy(e,t){const n=By(e,t);return{x:n.x,y:n.y,width:n.width,height:n.height,initialState:e.state}}function cM(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 lM(e,t,n=5e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=l=>{window.clearTimeout(a),document.removeEventListener("os-window-opened",r),s(l)},r=l=>{l.detail?.windowId===t&&i(e.getById(t)??null)},a=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function dM(e,t,n,o){const s=ge(n);Array.isArray(t.session.desktops)&&t.session.desktops.length>0&&e.seedDesktops(t.session.desktops,t.session.activeDesktop||t.session.desktops[0].id);const i={};for(const r of t.session.windows)r.native&&(i[r.id]={desktopId:r.desktopId,...r.unplaced?{}:Gy(r,s),...r.params?{params:r.params}:{},...r.gridSpan?{gridSpan:r.gridSpan}:{}});Object.keys(i).length>0&&e.seedWindowRestoreState(i,{reserveIds:!0});for(const r of t.session.windows){if(r.native){if(e.discardWindowRestoreState(r.id),!o?.(r.id,r.baseId||r.id,i[r.id]))continue;await lM(e,r.id);continue}if(Ln(r.url,t.adminUrl))continue;const a=Hl(r.url,t)??Uy(r.baseId||r.id,t),l=await e.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!a?.multi,url:r.url,parentUrl:a?.url??r.url,title:Xx(r.url,t)??r.title,icon:r.icon||"dashicons-admin-generic",...r.unplaced?{}:Gy(r,s),submenu:a?.submenu,selfLabel:a?.selfLabel,...r.gridSpan?{gridSpan:r.gridSpan}:{}});if(Array.isArray(r.externalTabs))for(const c of r.externalTabs)c&&typeof c.url=="string"&&c.url!==""&&l.addExternalTab(c.url,typeof c.label=="string"&&c.label!==""?c.label:c.url)}if(e.discardWindowRestoreState(),t.session.focused){const r=e.getById(t.session.focused);r&&e.focus(r)}}async function uM(e,t){if(Ln(t.currentPage,t.adminUrl)||Me(t.currentPage))return;const n=fe(t.currentPage,t.adminUrl),o=Hl(t.currentPage,t);await e.open({id:n,baseId:n,multi:!!o?.multi,url:t.currentPage,parentUrl:o?.url??t.currentPage,title:t.currentTitle||o?.title||"",icon:t.currentIcon,submenu:o?.submenu,selfLabel:o?.selfLabel})}function fM(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function zl(e,t,n,o){const s=_u(t,n),i=window.fetch(t,s);i.then(c=>{if(c.status===401||c.status===403){let d;typeof t=="string"?d=t:t instanceof URL?d=t.href:d=t.url,Kx(c.status,d)}},()=>{});let r=o?.window??null;!r&&o?.windowId&&(r=e.getById(o.windowId)??null);const a=r??e.getFocused()??null,l=r??(o?.silent?null:a);return i.then(c=>zy(t,s,o,l,{res:c}),c=>zy(t,s,o,l,{err:c})),o?.silent||a&&typeof a.trackActivity=="function"&&a.trackActivity(i.then(c=>{if(!c.ok)throw new Error(mM(c));return c})).catch(()=>{}),i}function zy(e,t,n,o,s){try{let i;typeof e=="string"?i=e:e instanceof URL?i=e.href:i=e.url;const r=t?.method??(typeof e=="object"&&"method"in e?e.method:"GET"),a={url:i,method:String(r||"GET").toUpperCase(),windowId:o?.id??null,silent:n?.silent===!0,...n?.source?{source:n.source}:{}};let l;"res"in s?l={...a,status:s.res.status,ok:s.res.ok}:(l={...a,error:pM(s.err)},hM(e,t,s.err)&&(l.aborted=!0)),_e.publish("os/request-settled",l)}catch{}}function pM(e){const t=e?.message;return typeof t=="string"?t:String(e)}function hM(e,t,n){return t?.signal?.aborted||e instanceof Request&&e.signal?.aborted?!0:n?.name==="AbortError"}function mM(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return le(b("Request failed (HTTP %s)."),t)}const gM="os-remember-session";function wM(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:gM,urls:t})}catch{}}const yM=500,vM=1500;function jy(e){const{updated:t,...n}=e;return JSON.stringify(n)}function Vy(e){try{if(!window.wp?.os?.getOsSettings?.().windowPrewarmEnabled)return;wM(e.windows.filter(n=>!n.native&&n.url).map(n=>Nk(n.url)||"").filter(Boolean))}catch{}}function bM(e,t){let n=null,o=!1,s=!1,i=null,r=0,a=null;const l=()=>{if(o)return s=!0,Promise.resolve();const f=e.snapshot(),p=jy(f);return p===a?Promise.resolve():(o=!0,r=Date.now(),Vy(f),i=(async()=>{try{(await zl(e,t.sessionUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":t.restNonce},body:JSON.stringify({session:f}),keepalive:!0},{silent:!0}))?.ok&&(a=p)}catch(g){A(v.SHELL_ERROR,{scope:"session-save",error:g})}finally{o=!1,i=null,s&&(s=!1,u())}})(),i)},c=async()=>{for(n!==null&&(clearTimeout(n),n=null);i;)await i;s=!1,await l()},d=()=>{n!==null&&(clearTimeout(n),n=null),s=!1;const f=e.snapshot(),p=jy(f);if(p===a)return;Vy(f);const g=new Blob([JSON.stringify({session:f})],{type:"application/json"}),h=t.sessionUrl+(t.sessionUrl.includes("?")?"&":"?")+"_wpnonce="+encodeURIComponent(t.restNonce);if(navigator.sendBeacon&&navigator.sendBeacon(h,g)){a=p;return}l()},u=()=>{n!==null&&clearTimeout(n);let f=yM;if(r!==0){const p=Date.now()-r;f=Math.max(f,vM-p)}n=window.setTimeout(()=>{n=null,l()},f)};return window.addEventListener("pagehide",d),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&d()}),Object.assign(u,{flush:c})}const EM=120;function _M(e){document.addEventListener("os-window-opened",e),document.addEventListener("os-window-closed",e),document.addEventListener("os-window-focused",e),document.addEventListener("os-window-changed",e),ee(v.DESKTOP_CREATED,"desktop-mode/session-save",e),ee(v.DESKTOP_CLOSED,"desktop-mode/session-save",e),ee(v.DESKTOP_SWITCHED,"desktop-mode/session-save",e),ee(v.DESKTOP_RENAMED,"desktop-mode/session-save",e),ee(v.WORKSPACE_UPDATED,"desktop-mode/session-save",e),ee(v.WORKSPACE_PROVISIONED,"desktop-mode/session-save",e)}function SM(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;A(v.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,EM)}),document.addEventListener("visibilitychange",()=>{A(v.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function kM(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 J(v.DOCK_TILE_CLASS,e,o)}function IM(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 J(v.DOCK_TILE_ELEMENT,e,o)}function AM(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 J(v.DOCK_TILE_TOOLTIP,e,o)}function CM(e,t,n){const o={rail:n.rail??"dock",orientation:n.orientation,dockId:n.dockId,container:n.container??document.body,item:t,isSystem:n.isSystem};A(v.DOCK_TILE_RENDERED,{...o,el:e})}const LM=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),jl=new Set;function TM(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(LM))return!0;for(const n of jl)if(t.closest(n))return!0;return!1}function NM(e){return typeof e!="string"||e.trim()===""?()=>{}:(jl.add(e),()=>{jl.delete(e)})}const Et=new Map,OM=window.location.origin;function Ky(e){let t=Et.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},Et.set(e,t)),DM(e,t),t}function DM(e,t){const n=Vl(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(()=>mo(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function RM(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function Vl(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 xM(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 mo(e){const t=Vl(e);if(!t||!t.contentWindow)return;const n=Et.get(e),o=n?xM(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},OM)}catch{}}ee(v.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&Et.has(t.windowId)&&mo(t.windowId)}),ee(v.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=Et.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const Wt=new Map,MM=1e3;function qy(e,t,n){const o=Wt.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,!!Wt.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const a of r.events||[]){const l=o.channels.get(a.channel);if(l)for(const c of l)try{c(a)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=Wt.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>qy(e,t,n),MM))})}function WM(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function PM(e,t){const n=Wt.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let $M=0;const Yy={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=Ky(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),mo(e),()=>{const r=Et.get(e);if(!r)return;const a=r.headers.get(t);if(!a)return;const l=a.indexOf(s);l>=0&&a.splice(l,1),a.length===0&&r.headers.delete(t),mo(e),Xy(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=Ky(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,mo(e)),()=>{const i=Et.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),mo(e)),Xy(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=Vl(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=Yy.addRequestHeader(e,s,t);try{const a=o.getAttribute("src")||o.src||"",l=new URL(a,window.location.origin);l.searchParams.set(i,t),o.src=l.toString()}catch{}return{dispose:()=>{r()}}},debug:{startSession(){const e=window.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():"wpdbg-"+Date.now().toString(36)+"-"+Math.random().toString(36).slice(2,10)},publish(e,t,n){PM(e,{id:++$M,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=Wt.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},Wt.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=WM();r&&qy(e,r.restUrl,r.restNonce)}return()=>{const r=Wt.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),Wt.delete(e))}}}};function Xy(e){const t=Et.get(e);t&&t.headers.size===0&&t.observers.size===0&&(RM(t),Et.delete(e))}function UM(e){const t=[];for(const l of e.getVisibleRects()){if(l.state==="minimized"||l.element.offsetParent===null)continue;const c=l.element.getBoundingClientRect();t.push({id:`window:${l.windowId}`,kind:"window",rect:Zy(c),face:"top",element:l.element})}const n=document.getElementById("os-shell");if(n){const l=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:l.left,y:l.bottom-1,width:l.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const l of Array.from(o)){const c=l.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const d=l.getAttribute("data-os-dock-placement")??"bottom",u=s===0?"dock:edge":`dock:edge:${s}`;s++,d==="bottom"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:c.width,height:1},face:"top",element:l}):d==="right"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:l}):t.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:l})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(l=>{const c=l.getBoundingClientRect();if(c.width===0&&c.height===0)return;const d=l.dataset.widgetId??String(r++);t.push({id:`widget:${d}`,kind:"widget",rect:Zy(c),face:"top",element:l})});const a=J(v.WALLPAPER_SURFACES,t);return Array.isArray(a)?a:t}function Zy(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const BM="__openstationKeyedListKey",FM="__openstationKeyedListData";function HM(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function GM(e,t,n){const o=HM(e),s=o.byKey,i=new Map,r=[],a=new Set;for(const l of t){const c=String(n.keyOf(l));a.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),a.add(c);const d=s.get(c);if(d){const f=d.data;n.updateItem?.(d.el,l,f),d.data=l,i.set(c,d),r.push(d.el);continue}const u=n.buildItem(l);u[BM]=c,u[FM]=l,i.set(c,{el:u,data:l}),r.push(u)}for(const[l,c]of s)i.has(l)||c.el.remove();for(let l=0;l<r.length;l++){const c=r[l],d=e.children[l];d!==c&&e.insertBefore(c,d??null)}o.byKey=i}function zM(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function jM(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:a=()=>{},onError:l=U=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",U)}}=e;let c=e.sentinel??null;c||(c=document.createElement("div"),c.dataset.osInfiniteListSentinel="",c.style.height="1px",t.appendChild(c));const d=new Set;let u=r,f=!0,p=!1,g=null,h=0,m=!1,_=null;const I=U=>{if(p!==U){p=U;try{a(U)}catch(F){l(F)}}},O=()=>{_&&(_.disconnect(),_=null)},$=()=>{_||!c||m||(_=new IntersectionObserver(U=>{for(const F of U)F.isIntersecting&&S()},{rootMargin:i}),_.observe(c))},S=async()=>{if(m||p||!f)return;I(!0),g=new AbortController;const U=g;try{const F=await n(u,U.signal);if(m||U!==g)return;let K=0;const Q=document.createDocumentFragment();for(const Z of F.items??[]){const C=String(o(Z));if(d.has(C))continue;d.add(C);const D=s(Z,h+K);Q.appendChild(D),K++}K>0&&(c&&c.parentNode===t?t.insertBefore(Q,c):t.appendChild(Q),h+=K),u=F.nextCursor??null,u||(f=!1,O())}catch(F){if(F?.name==="AbortError")return;l(F)}finally{U===g&&(I(!1),g=null)}},R=()=>{if(m)return;g?.abort(),g=null,d.clear(),u=r,f=!0,h=0;const U=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);U&&c&&t.appendChild(c),I(!1),$(),S()},W=()=>{m||(m=!0,O(),g?.abort(),g=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,I(!1))};return $(),S(),{reset:R,loadMore:S,hasMore:()=>f,isLoading:()=>p,destroy:W}}const VM=520,KM=720,qM=500;function YM(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=ZM(),o=JM();return Ae(rt(n,"desktop-mode/v1/oauth/start"),{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o??""},body:JSON.stringify({service:e})},{source:"desktop-mode/oauth-start"}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");let r=null;try{r=JSON.parse(i)}catch{r=null}throw mt(s.status,r,`[openstation] OAuth start failed (${s.status}): ${i}`)}return await s.json()}).then(s=>XM(s,e,t))}function XM(e,t,n){return new Promise((o,s)=>{const i=n.width??VM,r=n.height??KM,a=Math.max(0,Math.floor((window.screen.width-i)/2)),l=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${a}`,`top=${l}`,"menubar=no","toolbar=no","location=yes","status=no","resizable=yes","scrollbars=yes"].join(","),d=window.open(e.authorize_url,`os-oauth-${t}`,c);if(!d){s(new Error("[openstation] OAuth popup blocked. Tell users to allow popups for this site."));return}const u=window.location.origin;let f=null,p=!1;const g=()=>{p||(p=!0,window.removeEventListener("message",h),f!==null&&(window.clearInterval(f),f=null))},h=m=>{if(m.origin!==u)return;const _=m.data;if(!_||_.type!=="os-oauth-callback")return;const I=_.payload;if(g(),I&&I.ok)o(I);else{const O=I?.reason??"unknown",$=I?.message??"OAuth flow failed",S=new Error(`[openstation] startOAuth(${t}) failed: ${O} — ${$}`);S.cause=I,s(S)}};window.addEventListener("message",h),f=window.setInterval(()=>{d.closed&&(g(),s(new Error(`[openstation] startOAuth(${t}) cancelled — popup closed before completing.`)))},qM)})}function Jy(){return window.openStationConfig??{}}function ZM(){const e=Jy().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function JM(){const e=Jy().restNonce;return typeof e=="string"&&e!==""?e:null}const Er=["os-section","os-button","os-swatch","os-swatch-grid","os-segmented","os-segment","os-select","os-option","os-multiselect","os-color-field","os-range-field","os-text-field","os-number-field","os-checkbox","os-checkbox-label","os-switch","os-toast","os-toast-container","os-tabs","os-tab","os-tabpanel","os-window-button","os-menu","os-menu-item","os-action-menu","os-context-menu","os-context-menu-option","os-confirm-dialog","os-modal","os-user-search","os-role-picker","os-flyout","os-coachmark","os-tooltip","os-tab-chip","os-stack","os-cluster","os-icon","os-body","os-panel","os-row","os-grid","os-app-frame","os-split","os-display","os-disclosure","os-empty-state","os-key","os-code","os-badge","os-ribbon","os-tile","os-log","os-steps","os-step","os-table","os-spinner","os-relative-time","os-histogram","os-fact","os-facts","os-stat","os-avatar","os-textarea","os-chip","os-tag-input","os-form","os-save-status","os-category-picker","os-crumb-chain","os-card","os-rating-summary","os-notice","os-progress-bar","os-field-row","os-repeater","os-token-field"],Qy=new Set(Er);let _r=null;function Kl(){return!!window.openStationComponents}function QM(){return window.openStationConfig?.componentsBundleUrl??""}function e1(e){return new Promise((t,n)=>{const o=()=>{if(Kl()){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){Kl()?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 t1(e){const t=e.filter(n=>!Qy.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 ${Er.length} tags; see docs/components-reference.md for the list. The others in this call still loaded.`)}async function n1(e){if(e){if(t1(e),e.filter(o=>Qy.has(o)&&!customElements.get(o)).length===0)return}else if(Kl())return;const t=QM();t&&(_r||(_r=e1(t).catch(n=>{throw _r=null,n})),await _r)}const o1=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","dockPlacement","icons","iconSet","files","confirm","saveSession","hooks","HOOKS","isActive","registerWallpaper","registerWidget","widgetLayer","widgets","registerSystemTile","registerWindow","openWindow","openNewWindow","cloneTemplate","onWindow","createInfiniteList","startOAuth","repaintLoadingOverlays","loadVendorScript","getWallpaperSurfaces","wallpaper","games","mode","deactivationFeedback","registerModule","loadModules","whenReady","ready","isReady","setDefaultWindow","refreshMenu","config","ai","dragBridge","dragManager","registerCommand","unregisterCommand","listCommands","registerDestructiveAdminAction","unregisterDestructiveAdminAction","listDestructiveAdminActions","registerSettingsTab","unregisterSettingsTab","listSettingsTabs","registerDockRailRenderer","unregisterDockRailRenderer","listDockRailRenderers","openOsSettings","getOsSettings","subscribeOsSettings","updateOsSettings","resetOsSettings","deriveWindowId","listSystemTiles","getSystemTile","getMenuItems","getNavItems","getNav","renderIcon","applyTileClasses","applyTileElement","applyTileTooltip","dispatchTileRendered","isDockElement","registerDockSelector","registerTitleBarButton","unregisterTitleBarButton","listTitleBarButtons","registerWindowAction","unregisterWindowAction","listWindowActions","registerUnfocusEffect","unregisterUnfocusEffect","listUnfocusEffects","registerWindowReveal","unregisterWindowReveal","listWindowReveals","relations","registerWindowLinkRenderer","unregisterWindowLinkRenderer","listWindowLinkRenderers","registerWindowTheme","unregisterWindowTheme","listWindowThemes","applyWindowTheme","desktopThemes","registerWindowControl","unregisterWindowControl","listWindowControls","applyWindowControls","registerWindowSlot","unregisterWindowSlot","listWindowSlots","applyWindowSlot","registerWindowNotice","unregisterWindowNotice","listWindowNotices","dismissWindowNotice","undismissWindowNotice","registerWindowChrome","unregisterWindowChrome","listWindowChromes","applyWindowChrome","connect","getConnection","broadcast","subscribe","announceContentChange","registerPalette","unregisterPalette","listPalettes","openPalette","devtools","createSharedStore","presence","workArea","selection","activity","heartbeat","showToast","renderKeyedList","clearKeyedList","registerNamespace","notify","pwa","getWindowConfig","getWindowParams","debug","registerNativeUrlRemap","fetch"]);function s1(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:a,widgetLayer:l,registerWindow:c,openWindowById:d,openNewWindowById:u,loadWindowScriptById:f,prewarmWindowById:p,placeSystemTile:g,setDefaultWindow:h,refreshMenu:m,openOsSettings:_,aiAssistant:I,dragBridge:O,dragManager:$,connect:S,getConnection:R,wallpaperSuspend:W,mio:U,mode:F,workspaces:K,config:Q}=e,Z={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,iconSet:u_,files:r,confirm:Qt,saveSession:a,hooks:HE(),HOOKS:v,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:C=>{Fn(C),s.apply()},registerWidget:C=>{dl(C)},widgetLayer:l,widgets:{redock:C=>{l?.redock(C)}},loadVendorScript:pe,getWallpaperSurfaces:()=>UM(t),wallpaper:W,mio:U,mode:F,games:km,registerWindow:c,openWindow:d,openNewWindow:u,embedAdminPage:RO,loadWindowScript:f,prewarmWindow:p,loadComponents:n1,fetch:(C,D,V)=>zl(t,C,D,V),repaintLoadingOverlays:Jp,cloneTemplate:lw,onWindow:WO,createInfiniteList:jM,startOAuth:YM,registerSystemTile:C=>{g(C),A(v.DOCK_ITEM_APPENDED,{id:C.id})},registerModule:dm,loadModules:Dc,whenReady:su,ready:su,isReady:zE,setDefaultWindow:h,refreshMenu:m,config:Q,ai:I,dragBridge:O,dragManager:$,registerCommand:Xn,unregisterCommand:xm,listCommands:Mm,registerDestructiveAdminAction:TA,unregisterDestructiveAdminAction:Qp,listDestructiveAdminActions:NA,registerSettingsTab:Pm,unregisterSettingsTab:$m,listSettingsTabs:Um,registerDockRailRenderer:Au,unregisterDockRailRenderer:A_,listDockRailRenderers:T_,openOsSettings:_,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:C=>s.subscribeOsSettings(C),updateOsSettings:(C,D={})=>{s.update(C,D),(C.navPlacement||C.navOrder)&&o?.refresh()},resetOsSettings:(C={})=>{s.reset(C),o?.refresh()},deriveWindowId:(C,D)=>fe(C,D??Q.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:C=>o?.getSystemTile(C)??null,getMenuItems:()=>o?.getMenuItems()??[],getNavItems:()=>o?.getNavItems()??[],getNav:()=>o?.getNav()??null,renderIcon:oo,applyTileClasses:kM,applyTileElement:IM,applyTileTooltip:AM,dispatchTileRendered:CM,isDockElement:TM,registerDockSelector:NM,registerTitleBarButton:os,unregisterTitleBarButton:Hm,listTitleBarButtons:cT,registerWindowAction:jm,unregisterWindowAction:uT,listWindowActions:pT,registerUnfocusEffect:er,unregisterUnfocusEffect:BT,listUnfocusEffects:Kc,registerWindowReveal:Be,unregisterWindowReveal:rS,listWindowReveals:Zu,relations:BA,registerWindowLinkRenderer:ug,unregisterWindowLinkRenderer:VT,listWindowLinkRenderers:Yc,registerWindowTheme:gg,unregisterWindowTheme:wg,listWindowThemes:yg,desktopThemes:{list:mS,getActive:Ta,setActive:_c,ensureFull:df,subscribe:yS,resolveIcon:fi,resolveIconColor:Na,applyRecommendedOsSettings:C=>{const D=C!==void 0?C:Ta()??"";return s.applyThemeRecommendations(D)}},applyWindowTheme:(C,D)=>{const V=t.getById(C);V&&V.setAppearanceTheme(D)},registerWindowControl:ds,unregisterWindowControl:Eg,listWindowControls:_g,applyWindowControls:(C,D)=>{const V=t.getById(C);V&&V.setAppearanceControls(D)},registerWindowSlot:Ag,unregisterWindowSlot:nl,listWindowSlots:Cg,applyWindowSlot:(C,D,V)=>{const j=t.getById(C);j&&j.setAppearanceSlot(D,V)},registerWindowNotice:Dg,unregisterWindowNotice:rl,listWindowNotices:Rg,dismissWindowNotice:gN,undismissWindowNotice:wN,registerWindowChrome:bN,unregisterWindowChrome:Pg,listWindowChromes:$g,applyWindowChrome:(C,D)=>{const V=t.getById(C);V&&V.setAppearanceChrome(D)},connect:S,getConnection:R,broadcast:Ji,subscribe:Zn,announceContentChange:Zm,registerPalette:py,unregisterPalette:rx,listPalettes:hy,openPalette:wr,devtools:Yy,createSharedStore:ae,presence:wx,workArea:Yk,workspaces:K,selection:Rx,activity:_e,heartbeat:Re,showToast:ue,notify:$c,pwa:{promptInstall:tR,undismissInstallHint:nR,getState:es,subscribe:Cm,requestNotificationPermission:VL,getNotificationPermission:KL},renderKeyedList:GM,clearKeyedList:zM,registerNamespace:(C,D)=>{if(typeof C!="string"||C===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!D||typeof D!="object"){console.warn(`[openstation] registerNamespace("${C}"): api must be an object`);return}if(o1.has(C)){console.warn(`[openstation] registerNamespace("${C}"): name is reserved by the shell — pick a plugin-specific key`);return}Z[C]=D;const V=window.wp?.os;V&&V!==Z&&(V[C]=D)},getWindowConfig:C=>{const D=window.openStationWindowConfig;if(!D||typeof D!="object")return;const V=D[C];return V===void 0?void 0:V},getWindowParams:C=>{const D=t.getById(C);if(D)return{...D.config.params??{}}},registerNativeUrlRemap:ht,debug:{window:C=>{const D=(Q.nativeWindows??[]).find(M=>M.id===C);if(!D)return null;const V=D.scriptUrl||(D.scriptHandle?Q.nativeWindowScriptData?.[D.scriptHandle]?.url??"":"");let j="unknown",te=!1;V&&(document.querySelector(`script[data-os-vendor="${V.replace(/"/g,'\\"')}"]`)?(j="lazy",te=!0):Array.from(document.querySelectorAll("script[src]")).find(H=>H.src===V)&&(j="eager",te=!0));const N=window.openStationWindowConfig,L=!!(N&&typeof N=="object"&&Object.prototype.hasOwnProperty.call(N,C));return{id:C,scriptHandle:D.scriptHandle||"",scriptUrl:V,loadPath:j,tagInDom:te,configPresent:L,extras:{hasTranslations:!!D.scriptTranslations,l10nCount:(D.scriptL10n??[]).length,beforeCount:(D.scriptBefore??[]).length,afterCount:(D.scriptAfter??[]).length}}}}};return Z}function i1(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const ql=ae("desktop-mode/layout",()=>({layout:"classic"}));function ev(e){ql.state.layout!==e&&(ql.state.layout=e,ql.notify())}class tv{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 r1 extends tv{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const Ts=new Map,Yl=new Set;function qe(e){if(!e.type)throw new Error("[openstation] registerType: `type` is required.");if(!e.label)throw new Error("[openstation] registerType: `label` is required.");Ts.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),A("os.files.type-registered",e.type,e),ov()}function a1(e){Ts.delete(e)&&(A("os.files.type-unregistered",e),ov())}function c1(e){const t=Ts.get(e);return t||null}function nv(){const e=Array.from(Ts.values()).slice(),t=J("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 Pt(e){const t=Ts.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new r1(e,e.type)}function l1(e){return Yl.add(e),()=>Yl.delete(e)}function ov(){for(const e of Yl)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const Sr=new Map,Xl=new Set;let Zl={};function sv(e){Zl={...e},td()}function Jl(){return{...Zl}}function Fe(e){if(!e.id)throw new Error("[openstation] registerOpener: `id` is required.");if(!e.label)throw new Error("[openstation] registerOpener: `label` is required.");if(!Array.isArray(e.types)||e.types.length===0)throw new Error("[openstation] registerOpener: `types` must be a non-empty array.");if(!e.handler||typeof e.handler!="object")throw new Error("[openstation] registerOpener: `handler` is required.");Sr.set(e.id,{id:e.id,label:e.label,types:e.types.slice(),isDefault:!!e.isDefault,sort:typeof e.sort=="number"?e.sort:100,appliesTo:typeof e.appliesTo=="function"?e.appliesTo:void 0,handler:e.handler}),A("os.files.opener-registered",e.id,e),td()}function d1(e){Sr.delete(e)&&(A("os.files.opener-unregistered",e),td())}function u1(e){return Sr.get(e)??null}function iv(){const e=Array.from(Sr.values()).slice(),t=J("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 Ql(e,t){return iv().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function ed(e,t){const n=Ql(e,t);if(n.length===0)return null;const o=Zl[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]),J("os.files.resolve-opener",s,e)??null}function rv(e){return Xl.add(e),()=>Xl.delete(e)}function td(){for(const e of Xl)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let $t=null;function f1(e){$t=e}function nd(e){return!$t||!e.url?!1:$t.openUrl({id:$t.deriveWindowId(e.url),...e})}async function Ns(e,t){if(!$t)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=ed(e.type(),e);if(!n)return A("os.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;A("os.files.opening",{file:e,openerId:n.id});try{const o=n.handler;if(o.kind==="url"){const s=await o.url(e);if(!s)return!1;const i=o.windowId?o.windowId(e):$t.deriveWindowId(s),r=o.title?o.title(e):e.title(),a=e.icon(),l=$t.openUrl({id:i,url:s,title:r,icon:a});return A("os.files.opened",{file:e,openerId:n.id,kind:"url"}),l}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=$t.openNativeWindow(o.windowId,s);return A("os.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),A("os.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return A("os.files.open-failed",{reason:"handler-threw",type:e.type(),ref:e.ref(),openerId:n.id,error:o}),console.error("[openstation] file opener threw:",o),!1}}const p1="dashicons-portfolio";function h1(){qe({type:"shortcut",label:"Plugin shortcut",sort:1}),qe({type:"folder",label:"Folder",sort:5}),qe({type:"post",label:"Post",sort:10}),qe({type:"attachment",label:"Media",sort:20}),qe({type:"upload",label:"Uploaded file",sort:25}),qe({type:"user",label:"User",sort:30}),qe({type:"term",label:"Taxonomy term",sort:40}),qe({type:"comment",label:"Comment",sort:50}),qe({type:"bookmark",label:"Bookmark",sort:60}),qe({type:"link",label:"Web link",sort:70}),qe({type:"embed",label:"Embedded web window",sort:80})}function m1(){const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]%16+64,e[8]=e[8]%64+128;const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}class go extends No{constructor(t,n,o=new No("",{status:0})){super(t,{status:o.status,code:o.code,data:o.data,serverMessage:o.serverMessage}),this.name="JobRequestError",this.retryable=n}}async function g1(e,t,n){const o=new AbortController,s=window.setTimeout(()=>o.abort(),15e3);try{const i=await Ae(rt(e.restRoot,t),{method:n?"POST":"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:n?JSON.stringify(n):void 0,signal:o.signal,cache:"no-store"},{source:"desktop-mode/agents",silent:!n}),r=await i.json().catch(()=>null);if(!i.ok)throw new go(r?.message||`HTTP ${i.status}`,i.status>=500&&!r?.code||i.status===408,mt(i.status,r));if(!r||!r.jobId&&typeof r.text!="string")throw new go(b("The job status could not be read.","desktop-mode"),!0,mt(i.status,null));return r}finally{window.clearTimeout(s)}}function w1(e){return new Promise(t=>window.setTimeout(t,e))}async function y1(e,t,n,o,s=()=>{}){const i=`desktop-mode/v1/agents/${e}`,r=Date.now()+2*60*60*1e3;let a=!1,l=2e3;for(;Date.now()<r;){try{const c=await g1(n,a?`${i}/jobs/${o}`:`${i}/invoke`,a?void 0:{...t,async:!0,requestId:o});if(!("jobId"in c))return c;if(c.jobId!==o)throw new go(b("The server returned a different job.","desktop-mode"),!1);if(a=!0,c.status==="completed"&&c.result)return c.result;if(c.status==="failed")throw new go(c.error?.message||b("The agent job failed.","desktop-mode"),!1);if(c.status!=="queued"&&c.status!=="running")throw new go(b("The server returned an invalid job state.","desktop-mode"),!1);s(c.status),l=Math.min(1e4,Math.max(l*1.25,(c.pollAfter||3)*1e3))}catch(c){if(c instanceof go&&!c.retryable)throw c;s("reconnecting"),l=Math.min(l*2,3e4)}await w1(document.hidden?Math.max(l,15e3):l)}throw new Error(b("The background job has not returned a result. Some work may already have been applied. Check the site before submitting again.","desktop-mode"))}const He=ae("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function av(e){He.state.activeAgent=e,He.state.transcripts[e.id]||(He.state.transcripts[e.id]=[]),He.state.conversationIds||(He.state.conversationIds={},He.state.conversationsRev=0),He.notify()}const cv="desktop-mode/v1/agents/conversations";async function lv(e,t,n={}){const o=await Ae(rt(e.restRoot,t),{...n,headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce,...n.headers??{}}},{source:"desktop-mode/agents",silent:!0}),s=await o.json().catch(()=>null);if(!o.ok)throw mt(o.status,s);return s}function v1(e){return e.filter(t=>!t.pending)}async function b1(e,t){const n=He.state,o=v1(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await lv(t,`${cv}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await lv(t,cv,{method:"POST",body:JSON.stringify({agentId:e.id,messages:o})});n.conversationIds[e.id]=i.id}n.conversationsRev=(n.conversationsRev??0)+1,He.notify()}catch(s){console.warn("[desktop-mode/agents] conversation save failed:",s)}}}const dv={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function uv(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function fv(e){if(e.type==="shortcut"){const t=e.data;let n=dv[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=uv(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=dv[String(n.type??"")],s=uv(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function E1(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function _1(e){return le(b('The user dropped the %1$s "%2$s" (id %3$s) onto you. Handle it according to your instructions, using your tools as needed.',"desktop-mode"),e.kind,e.title,String(e.id))}function S1(e){return{kind:e.kind,id:e.id,title:e.title}}function pv(e,t="agents"){av(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function k1(e,t,n,o,s){av(e);const i=He.state.transcripts[e.id],r=b("The agent finished without a text answer.","desktop-mode"),a=i.filter(c=>!c.pending&&c.role!=="error"&&!(c.role==="agent"&&c.text===r)).map(c=>({role:c.role,text:c.text}));i.push({role:"user",text:t,at:Date.now(),attachment:s});const l={role:"agent",text:b("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(l),He.notify();try{const c=await y1(e.id,{message:t,source:o,history:a},n,m1(),d=>{const u={queued:b("Queued — waiting for a WordPress worker…","desktop-mode"),reconnecting:b("Reconnecting to the background job…","desktop-mode"),running:b("Working in the background…","desktop-mode")};l.text=u[d],He.notify()});c.text?.trim()?l.text=c.text:(l.role="error",l.text=r),l.toolCalls=c.toolCalls,Array.isArray(c.callToActions)&&c.callToActions.length>0&&(l.callToActions=c.callToActions)}catch(c){l.role="error",l.text=c instanceof Error?c.message:String(c)}l.pending=!1,He.notify(),b1(e,n)}function I1(e,t,n){return pv(e,"agents-drop"),k1(e,_1(t),n,"drag",S1(t))}let od=null;function hv(e){od=e}function wo(){if(!od)throw new Error("[openstation] files REST client called before installRestDeps().");return od}function A1(){return wo()}class sd extends Error{constructor(t){super(`Row was changed by ${t.actor.name||"another session"} (parent="${t.current.parentName}")`),this.name="FilesConflictError",this.status=409,this.detail=t}}const he=k_({prefix:"[openstation] files REST",source:"desktop-mode/files",url:e=>rt(wo().baseUrl,e),nonce:()=>wo().nonce,conflict:e=>{const t=e?.data?.data??e?.data;return t&&typeof t=="object"?new sd(t):null}});function xe(e=0){return he(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function Os(e){return he("/placements",{method:"POST",body:JSON.stringify(e)})}function yo(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 id(e){return he(`/placements/${e}`,{method:"DELETE"})}async function kr(e,t){const{baseUrl:n,nonce:o}=wo(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Ae(i,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o},credentials:"same-origin",body:JSON.stringify({items:[{id:e,type:t}]})},{source:"desktop-mode/files"});if(!r.ok)throw await Nn(r);return await r.json()}function mv(){return he("/folders",{method:"GET"})}function rd(e){return he("/folders",{method:"POST",body:JSON.stringify(e)})}function gv(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 ad(e){return he(`/folders/${e}`,{method:"DELETE"})}function wv(e){return he("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function C1(e){return he(`/folders/${e}/shares`,{method:"GET"})}function L1(e,t){return he(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function T1(e,t,n){return he(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function N1(e,t){return he(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function O1(e,t){return he(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function D1(e,t){return he(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function yv(e){return he(`/folders/${e}/leave`,{method:"POST"})}function R1(){return he("/folder-sharing-tables/purge",{method:"POST"})}function x1(e){return he(`/uploads/${e}/shares`,{method:"GET"})}function M1(e,t){return he(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function W1(e,t){return he(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function P1(e,t){return he(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function $1(e,t){return he(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function vv(e){return he(`/uploads/${e}/leave`,{method:"POST"})}function U1(e,t){return he(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function Ir(e){return he(`/uploads/${e}/media`,{method:"POST"})}function bv(e,t){return he(`/uploads/${e}/post`,{method:"POST",body:JSON.stringify({postType:t})})}function Ev(e,t){return he(`/posts/${e}/uploads`,{method:"POST",body:JSON.stringify({fileIds:t})})}function B1(e,t){return he("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function hn(e){const{baseUrl:t,nonce:n}=wo(),o=rt(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function _v(e){const{baseUrl:t,nonce:n}=wo(),o=rt(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const F1=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:sd,acceptFileShare:P1,acceptShare:O1,addUploadToMediaLibrary:Ir,attachUploadsToPost:Ev,createFolder:rd,createPlacement:Os,deleteFolder:ad,deletePlacement:id,denyFileShare:$1,denyShare:D1,ensureUploadPath:B1,getFilesRestDeps:A1,getFolderZipUrl:_v,getUploadDownloadUrl:hn,installRestDeps:hv,inviteFileShare:M1,inviteShare:L1,leaveFileShare:vv,leaveShare:yv,listFileShares:x1,listFolders:mv,listPlacements:xe,listShares:C1,purgeFolderSharingTables:R1,renameUpload:U1,restoreTrashedItem:kr,revokeFileShare:W1,revokeShare:N1,saveAssociations:wv,startPostFromUpload:bv,updateFolder:gv,updatePlacement:yo,updateShareCapability:T1},Symbol.toStringTag,{value:"Module"})),H1="desktop-mode/files";function nt(){return ae(H1,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function vo(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function Ut(e,t){const n=nt(),o=new Map(n.state.placementsByFolder);o.set(e,t.slice());const s=new Set(n.state.hydratedFolders);s.add(e),n.state={...n.state,placementsByFolder:o,hydratedFolders:s},n.notify(),vo({kind:"placements-set",folderId:e})}function cd(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=nt(),o=new Map(n.state.placementsByFolder);for(const[a,l]of o)if(l.findIndex(d=>d&&d.id===e.id)>=0&&a!==e.parentId){const d=l.filter(Boolean),u=d.findIndex(f=>f.id===e.id);u>=0&&d.splice(u,1),o.set(a,d)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(a=>a.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),vo({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function Ds(e,t="local"){const n=nt(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(l=>l&&l.id===e)>=0){const l=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,l),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),vo({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function ld(e){const t=nt(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),vo({kind:"folders-set"})}function dd(e,t="local"){const n=nt(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),vo({kind:"folder-upserted",folderRowId:e.id,source:t})}function ud(e,t="local"){const n=nt(),o=new Map(n.state.folders);o.delete(e);const s=new Map(n.state.placementsByFolder);s.delete(e),n.state={...n.state,folders:o,placementsByFolder:s},n.notify(),vo({kind:"folder-removed",folderRowId:e,source:t})}function fd(e){return nt().subscribe(e)}function Bt(){return nt().getState()}function Sv(e){const t=Bt(),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 oe={getState:Bt,subscribe:fd,setFolderPlacements:Ut,upsertPlacement:cd,upsertFolder:dd,removePlacement:Ds,removeFolder:ud,currentPlacement:Sv},G1=Le`:host{display:inline-block}`,z1=Le`: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 ) )}`,Qs=class Qs extends sn{render(){return jn`<span class="banner" part="banner"><slot></slot></span>`}};Qs.props=["placement","tone"],Qs.styles=[z1],Qs.help=void 0;let pd=Qs;Jo("os-ribbon",pd);const de="os-file-tile",kv={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function j1(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function V1(){return window.wp?.os?.dragManager??null}const K1=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],Ao=class Ao extends sn{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null,this._onSettingsSave=t=>{t.detail?.phase==="saved"&&this._paint()}}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this.click())},this.addEventListener("keydown",this._keydownHandler)),document.addEventListener("os-settings-save-lifecycle",this._onSettingsSave),this._paint()}disconnectedCallback(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null),this._keydownHandler&&(this.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null),document.removeEventListener("os-settings-save-lifecycle",this._onSettingsSave)}requestUpdate(){this.isConnected&&this._paint()}attributeChangedCallback(t,n,o){if(n!==o){if(t==="selected"||t==="selectable"||t==="aria-selected"){this._paintSelection();return}super.attributeChangedCallback(t,n,o)}}_paintSelection(){const t=this.hasAttribute("selected"),n=this.hasAttribute("selectable");if(this.classList.toggle(`${de}--selected`,t),this.setAttribute("role",n?"option":"listitem"),n){const o=t?"true":"false";this.getAttribute("aria-selected")!==o&&this.setAttribute("aria-selected",o)}else this.removeAttribute("aria-selected")}render(){return jn``}_paint(){const t=this.getAttribute("type")??"",n=this.getAttribute("ref")??"",o=this.getAttribute("label")??"",s=this.getAttribute("icon")??"",i=this.getAttribute("thumbnail")??"",r=this.getAttribute("kind")??"entry",a=this.getAttribute("status")??"",l=this.hasAttribute("selected"),c=this.hasAttribute("selectable"),d=this.hasAttribute("missing"),u=this.hasAttribute("access-gated"),f=[de,`${de}--folder`,`${de}--missing`,`${de}--access-gated`,`${de}--selected`];for(const _ of f)this.classList.remove(_);this.classList.add(de),r==="folder"&&this.classList.add(`${de}--folder`),d&&this.classList.add(`${de}--missing`),u&&this.classList.add(`${de}--access-gated`),l&&this.classList.add(`${de}--selected`),this.dataset.fileType=t,this.dataset.fileRef=n,r&&(this.dataset.role=r),this.setAttribute("role",c?"option":"listitem"),c?this.setAttribute("aria-selected",l?"true":"false"):this.removeAttribute("aria-selected"),this.setAttribute("aria-label",o),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");const p="You don’t have permission to open this — ask the folder owner for access.";u?(this.title=p,this.setAttribute("aria-disabled","true")):(this.removeAttribute("aria-disabled"),this.title===p&&this.removeAttribute("title"));const g=[`${de}__visual`,`${de}__label`,`${de}__lock`];for(const _ of g)this.querySelectorAll(`:scope > .${_}`).forEach(I=>I.remove());this.querySelectorAll(":scope > os-ribbon").forEach(_=>_.remove());const h=document.createElement("span");if(h.className=`${de}__visual`,i){const _=document.createElement("img");_.src=i,_.alt="",_.loading="lazy",_.decoding="async",_.className=`${de}__preview`,_.draggable=!1,h.appendChild(_)}else if(s){const _=oo(s,{title:o,className:`${de}__icon`});h.appendChild(_)}this.appendChild(h);const m=document.createElement("span");if(m.className=`${de}__label`,m.textContent=o,this.appendChild(m),u){const _=document.createElement("span");_.className=`${de}__lock dashicons dashicons-lock`,_.setAttribute("aria-hidden","true"),this.appendChild(_)}if(a&&a!=="publish"&&kv[a]&&j1()){const _=document.createElement("os-ribbon");_.setAttribute("placement","top-end"),_.setAttribute("tone",q1(a)),_.textContent=kv[a],this.appendChild(_)}YE(this),A("os.tile.rendered",{tile:this}),this._wireDragOut()}_wireDragOut(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null);const t=this.getAttribute("drag-kind");if(!t)return;const n=o=>{if(o.button!==0)return;const s=V1();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,a=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,l=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:a},ghost:{offsetX:o.clientX-l.left,offsetY:o.clientY-l.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};Ao.shadow=!1,Ao.props=K1,Ao.styles=[G1],Ao.help=void 0;let hd=Ao;function q1(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}Jo("os-tile",hd);function Y1(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=J("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 X1(e,t){const n=document.createElement("div");n.className="os-drag-stack";const o=e.getBoundingClientRect();n.style.width=`${o.width}px`,n.style.height=`${o.height}px`;const s=e.cloneNode(!0);s.removeAttribute("id"),s.removeAttribute("selected"),s.removeAttribute("aria-selected"),s.classList.remove(`${de}--selected`),s.style.left="0px",s.style.top="0px",s.style.position="relative",n.appendChild(s);const i=document.createElement("span");return i.className="os-drag-stack__count",i.textContent=String(t),n.appendChild(i),n}function Iv(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:Pt(e.file).title()}function Z1(e,t){const n=Pt(e.file),o=n.previewUrl(),s=Iv(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:hw(e.file.ref)||i||fi(ES(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 J1(e,t){const n=Y1(Z1(e,t)),o=J("os.files.tile-class",de,e);o&&o!==de&&(n.className=o);const s=J("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=Sv(e),a=Pt(r.file);if(r.accessGated){ue({message:`You don’t have permission to open "${r.file.title||a.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}Ns(a,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),A("os.files.tile-rendered",{tile:n,placement:e}),n}function mn(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const Q1=ae("desktop-mode/tile-payload-handlers",()=>({handlers:new Map}));function Rs(){return Q1.state.handlers}function xs(e,t){const n=Rs().get(e);return n?n.push(t):Rs().set(e,[t]),()=>{const o=Rs().get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&Rs().delete(e)}}function md(e,t){const n=Rs().get(e);if(n)return n.find(o=>o.appliesTo(t))}function eW(e,t){return md(e,t)?.acceptLabel}function tW(e,t){const n=md(e.type,t);return n?n.accept(e.data,t):!1}function nW(e,t,n){const o=md(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function oW(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&&Nx(e,{actions:o,scope:"files.tile",dataset:{placementId:String(n.placementIds[0]??""),placementIds:n.placementIds.join(",")},onOpened:s=>{A("os.files.tile-menu.opened",{placementId:n.placementIds[0],placementIds:n.placementIds.slice(),items:s})},onClosed:()=>{A("os.files.tile-menu.closed",{})}})}const sW="my-wordpress",bo=ae("desktop-mode/my-wordpress/open-target",()=>({kind:null,entityId:"",id:0,title:"",requestedAt:0}));function iW(e){bo.state.kind=e.kind,bo.state.entityId=e.entityId,bo.state.id=e.id,bo.state.title=e.title,bo.state.requestedAt=Date.now(),bo.notify()}function rW(e){const t=window.wp?.os?.openWindow;t?.(sW,{source:e})}function Av(e){const t=Number(e.postId);!Number.isFinite(t)||t<=0||(iW({kind:"detail",entityId:e.entityId||"posts",id:t,title:e.postTitle??""}),rW("my-wordpress/open-detail"))}function aW(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function gd(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function wd(e){const t=()=>{const n=e.shadowRoot?.querySelector("input");return n?(n.focus(),n.select(),!0):!1};t()||queueMicrotask(()=>void t())}const Pe="os-create-folder-dialog";let Ms=null;function yd(){Ms&&(Ms.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),Ms.remove(),Ms=null,A("os.files.create-folder.closed",{}))}function vd(e){if(yd(),J("os.files.create-folder.dialog",null,e)===!1)return;const n=(e.initialName??"Untitled folder").trim(),o=document.createElement("div");o.className=`${Pe}__overlay`,o.setAttribute("role","presentation");const s=document.createElement("div");s.className=Pe,s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-labelledby",`${Pe}-title`);const i=document.createElement("h2");i.id=`${Pe}-title`,i.className=`${Pe}__title`,i.textContent=e.title??"New folder",s.appendChild(i);const r=document.createElement("os-text-field");r.className=`${Pe}__field`,r.id=`${Pe}-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=`${Pe}__error`,a.hidden=!0,a.setAttribute("role","alert"),s.appendChild(a);const l=document.createElement("div");l.className=`${Pe}__actions`;const c=document.createElement("os-button");c.className=`${Pe}__btn ${Pe}__btn--secondary`,c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className=`${Pe}__btn ${Pe}__btn--primary`,d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(d),s.appendChild(l),o.appendChild(s),document.body.appendChild(o),Ms=o,wd(r),A("os.files.create-folder.opened",{});const u=m=>{gd(r,m),gd(c,m),gd(d,m),s.classList.toggle(`${Pe}--busy`,m)},f=m=>{a.textContent=m,a.hidden=!1},p=()=>{yd(),e.onCancel?.()},g=async()=>{const m=aW(r).trim();if(!m){f("Please enter a name."),wd(r);return}a.hidden=!0,u(!0);try{await e.onSubmit(m),yd()}catch(_){u(!1),f(_ instanceof Error?_.message:"Could not create the folder."),wd(r)}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void g()),o.addEventListener("click",m=>{m.target===o&&p()});const h=m=>{m.key==="Escape"?(m.preventDefault(),p()):m.key==="Enter"&&!m.isComposing&&(m.preventDefault(),g())};s.addEventListener("keydown",h),o.addEventListener("create-folder-dialog-closed",()=>{s.removeEventListener("keydown",h)})}function Ar(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function cW(e){return e.id<=0||Ar(e)!==null}function Cv(e){e.length!==0&&Z0(e)}const lW="rest_cookie_invalid_nonce",Lv=()=>b("Could not reach the site. Check your connection and try again.","desktop-mode");function Tv(e){return typeof navigator<"u"&&navigator.onLine===!1?!0:e instanceof TypeError}function dW(e){return Su(e)?e.code===lW||e.status===401?"session":e.status>=200&&e.status<300?"unreadable":e.status===404?"gone":e.status>=500?"server":e.status>=400?"refused":"unknown":Tv(e)?"offline":"unknown"}function Nv(e){return Su(e)?e.serverMessage:Tv(e)?Lv():e instanceof Error?e.message:""}function uW(e,t){const{fallback:n,lead:o}=t,s=dW(e),i=s==="offline"||s==="unreadable"?"warning":"error";let r="",a=!0;switch(s){case"offline":r=Lv();break;case"session":r=b("Your session has expired. Reload the page and try again.","desktop-mode");break;case"unreadable":r=b("The site sent an unreadable reply. Reload the page to check whether the change went through.","desktop-mode");break;case"gone":case"refused":case"server":{const c=e;c.serverMessage?r=c.serverMessage:s==="gone"?(r=b("It no longer exists. Reload the page to catch up.","desktop-mode"),a=!1):s==="server"?(r=le(b("The server answered with error %d.","desktop-mode"),c.status),a=!1):(r=le(b("The server refused the request (HTTP %d).","desktop-mode"),c.status),a=!1);break}case"unknown":default:r=Nv(e);break}let l;return o?l=r?`${o}: ${r}`:n:r?a?l=r:l=`${n} ${r}`:l=n,{message:l,reason:r,kind:s,type:i}}function gn(e,t,n){if(!e)return;const{duration:o,...s}=n,i=uW(t,s),r={message:i.message,type:i.type};o&&(r.duration=o),e(r)}function Ov(e){const t=window.wp?.os;return typeof t?.showToast!="function"?()=>{}:t.showToast(e)??(()=>{})}function Eo(e,t,n){Zm(e,t,n,"desktop-files")}function Cr(e){gn(Ov,e,{fallback:"Could not move this item to the recycle bin.",duration:5e3})}function bd(e,t){Ov({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function Dv(e){const t=ln(io(e));if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Item",i=e.file?.type==="shortcut"?"shortcut":"placement";oe.removePlacement(n);try{await id(n),Eo(i,"trashed",[n]),t.finish(!0),bd(`"${s}" moved to Trash`,async()=>{const r=ln(io(e),"out");try{await kr(n,"placement");const a=await xe(o);oe.setFolderPlacements(o,a.placements),Eo(i,"untrashed",[n]),r?.finish(!0)}catch(a){r?.finish(!1),console.error("[openstation] restore failed:",a)}})}catch(r){console.error("[openstation] deletePlacement failed:",r),t.finish(!1),oe.upsertPlacement(e),Cr(r),xe(o).then(a=>{oe.setFolderPlacements(o,a.placements)}).catch(()=>{})}}async function Rv(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=ln(io(e));if(!n)return;const o=e.id,s=e.parentId,i=e.file?.title??"Folder";oe.removePlacement(o);const r=oe.getState().folders.get(t);oe.removeFolder(t);try{await ad(t),Eo("folder","trashed",[t]),n.finish(!0),bd(`"${i}" moved to Trash`,async()=>{const a=ln(io(e),"out");try{await kr(t,"folder");const l=await xe(s);oe.setFolderPlacements(s,l.placements),Eo("folder","untrashed",[t]),a?.finish(!0)}catch(l){a?.finish(!1),console.error("[openstation] restore folder failed:",l)}})}catch(a){console.error("[openstation] deleteFolder failed:",a),r&&oe.upsertFolder(r),n.finish(!1),oe.upsertPlacement(e),Cr(a),xe(s).then(l=>{oe.setFolderPlacements(s,l.placements)}).catch(()=>{})}}async function xv(e){if(e.length===0)return;if(e.length===1)return fW(e[0]);const t=new Map(e.map(d=>[d.id,ln(io(d))]));e=e.filter(d=>t.get(d.id));const n=new Map(oe.getState().folders),o=new Set;for(const d of e)if(o.add(d.parentId),oe.removePlacement(d.id),d.file?.type==="folder"){const u=parseInt(d.file.ref,10);u&&oe.removeFolder(u)}const s=async()=>{for(const d of o)try{const u=await xe(d);oe.setFolderPlacements(d,u.placements)}catch(u){console.error("[openstation] files: re-hydrate failed:",u)}},i=await Promise.allSettled(e.map(async d=>{if(d.file?.type==="folder"){const u=parseInt(d.file.ref,10);if(!u)throw new Error("folder placement without a folder id");return await ad(u),{id:u,kind:"folder",restoreId:u,restoreKind:"folder"}}return await id(d.id),{id:d.id,kind:d.file?.type==="shortcut"?"shortcut":"placement",restoreId:d.id,restoreKind:"placement"}}));i.forEach((d,u)=>{if(d.status==="rejected"){const f=e[u];oe.upsertPlacement(f);const p=f.file.type==="folder"&&n.get(Number(f.file.ref));p&&oe.upsertFolder(p),t.get(e[u].id)?.finish(!1)}});const r=[];let a=0;for(const d of i)d.status==="fulfilled"?r.push(d.value):(a+=1,console.error("[openstation] trash (bulk) failed for one item:",d.reason));if(a>0&&s(),r.length===0){Cr(i.find(d=>d.status==="rejected")?.reason);return}for(const d of["placement","shortcut","folder"]){const u=r.filter(f=>f.kind===d).map(f=>f.id);u.length>0&&Eo(d,"trashed",u)}i.forEach((d,u)=>{d.status==="fulfilled"&&t.get(e[u].id)?.finish(!0)});const l=r.length===1?"item":"items",c=a>0?`${r.length} ${l} moved to Trash · ${a} could not be moved`:`${r.length} ${l} moved to Trash`;bd(c,async()=>{const d=r.map(g=>{const h=e.find(m=>m.file.type==="folder"?Number(m.file.ref)===g.id&&g.kind==="folder":m.id===g.id&&g.kind!=="folder");return h?ln(io(h),"out"):null}),u=await Promise.allSettled(r.map(g=>kr(g.restoreId,g.restoreKind)));await s();const f=r.filter((g,h)=>u[h].status==="fulfilled"),p=r.length-f.length;for(const g of u)g.status==="rejected"&&console.error("[openstation] restore (bulk) failed for one item:",g.reason);for(const g of["placement","shortcut","folder"]){const h=f.filter(m=>m.kind===g).map(m=>m.id);h.length>0&&Eo(g,"untrashed",h)}u.forEach((g,h)=>{d[h]?.finish(g.status==="fulfilled")}),p>0&&Cr(new Error(`${p} of ${r.length} items could not be restored.`))})}function fW(e){return e.file?.type==="folder"?Rv(e):Dv(e)}const pW=5,Mv=e=>xv(e);async function hW(e){if(!(e.length>pW&&!await Qt({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await Ns(Pt(t.file))}function mW(e){const t=parseInt(e.file.ref,10);t&&vd({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}};oe.upsertPlacement(i);try{const r=oe.getState().folders.get(t)?.updatedAtMs??0,a=await gv(t,{name:o},r);oe.upsertFolder(a);const l=await xe(e.parentId);oe.setFolderPlacements(e.parentId,l.placements)}catch(r){console.error("[openstation] rename folder failed:",r),oe.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function gW(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=typeof e.file.postType=="string"?e.file.postType:"post";Av({entityId:n==="page"?"pages":"posts",postId:t,postTitle:e.file.title||`#${t}`})}function wW(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>hW(i),onClick:()=>{Ns(Pt(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>gW(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>mW(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:Mv,onClick:()=>Rv(e)});else{const i=Ar(e),r=e.file.type==="shortcut";if(i||r){const a=i??e.file.ref;t.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,multi:!0,bulkLabel:l=>`Hide ${l} items from desktop`,bulk:l=>{Cv(l.map(c=>Ar(c)??c.file.ref).filter(c=>!!c))},onClick:()=>Cv([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:Mv,onClick:()=>Dv(e)})}const o=J("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const Ft=16,Wv=88,Pv=104,yW=20,vW=16,Ed=Wv+yW,_d=Pv+vW;function Ws(e,t){const n=Math.max(0,Math.round((e-Ft)/Ed)),o=Math.max(0,Math.round((t-Ft)/_d));return wn(n,o)}function wn(e,t){return{col:e,row:t,x:Ft+e*Ed,y:Ft+t*_d}}const bW=5,EW=4;function Ps(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 _W(e){const t=Ps(e).height;return t<=0?bW:Math.max(1,Math.floor((t-Ft)/_d))}function SW(e){const t=Ps(e).width;return t<=0?EW:Math.max(1,Math.floor((t-Ft)/Ed))}const $v=999;function Lr(e,t="column",n){if(t==="row"){const s=SW(n);for(let i=0;i<$v;i++)for(let r=0;r<s;r++)if(!e.has(Ce(r,i)))return wn(r,i);return wn(0,0)}const o=_W(n);for(let s=0;s<$v;s++)for(let i=0;i<o;i++)if(!e.has(Ce(s,i)))return wn(s,i);return wn(0,0)}function Uv(e,t,n="column",o){const s=new Set(t),i=[];for(let r=0;r<e;r++){const a=Lr(s,n,o);s.add(Ce(a.col,a.row)),i.push(a)}return i}function Ht(e,t,n,o,s="column"){const i=Ws(e,t);return n.has(Ce(i.col,i.row))?Lr(n,s,o):i}function Bv(e,t){const n=new Set;for(const o of e){const s=Ws(o.x,o.y);n.add(Ce(s.col,s.row))}return n}function Ce(e,t){return`${e},${t}`}function kW(e){const t=String(e),{placementsByFolder:n}=nt().state;for(const o of n.values())for(const s of o)if(s.file?.type==="folder"&&s.file.ref===t)return s.file}function IW(e,t){const n=kW(e);if(n)return Pt(n);const o=nt().state.folders.get(e);return Pt({type:"folder",ref:String(e),title:o?.name||t||"Folder",icon:p1,previewUrl:"",exists:!0})}function Fv(e){return e instanceof sd}function AW(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 Hv(e){const t=AW(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{Ns(IW(n,e.detail.current.parentName))}}),ue({message:t,action:o,duration:7e3})}const CW=ae("desktop-mode/canvas-payload-handlers",()=>({handlers:new Map}));function Gv(){return CW.state.handlers}function LW(e,t){const n=Gv().get(e.type);return n?n.accept(e.data,t):!1}function TW(e,t,n){const o=Gv().get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function yn(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function Tr(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}const zv="application/x-wp-media-attachment",jv="data-files-drop-active";function Vv(){const e=window.wp?.os?.dragBridge;if(!e)return null;try{return e.getPayload()}catch{return null}}function Kv(e){if(!e)return null;switch(e.kind){case"attachment":case"post":case"user":return typeof e.id!="number"?null:{kind:e.kind,ref:String(e.id),title:e.title};default:return null}}function NW(e){if(!e)return null;let t="";try{t=e.getData(zv)}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 qv(e){const t=e.dataTransfer?.types,n=t?Array.from(t):[];return n.includes("Files")?!1:n.includes(zv)?!0:Kv(Vv())!==null}function Yv(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 Xv(e,t){if(!(e instanceof Element))return null;const n=e.closest(`.${de}`);return!(n instanceof HTMLElement)||!t.contains(n)?null:n.dataset.fileType==="folder"?n:null}function OW(e){const{host:t,container:n,folderId:o}=e;let s=null;const i=()=>{t.removeAttribute(jv),s&&(s.classList.remove(`${de}--drop-target`),s=null)},r=c=>{if(!qv(c))return;if(!Yv(c.target,t,n)){i();return}c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"),t.setAttribute(jv,"");const d=Xv(c.target,n);d!==s&&(s?.classList.remove(`${de}--drop-target`),d?.classList.add(`${de}--drop-target`),s=d)},a=c=>{const d=c.relatedTarget;d instanceof Node&&t.contains(d)||i()},l=c=>{if(!qv(c))return;if(!Yv(c.target,t,n)){i();return}i(),c.preventDefault(),c.stopPropagation();const d=Kv(Vv())??NW(c.dataTransfer);if(!d)return;const u=Xv(c.target,n);let f=o;if(u){const p=parseInt(u.getAttribute("ref")??"",10);!Number.isNaN(p)&&p>0&&(f=p)}e.fileEntities([d],f)};return t.addEventListener("dragover",r),t.addEventListener("dragleave",a),t.addEventListener("drop",l),()=>{i(),t.removeEventListener("dragover",r),t.removeEventListener("dragleave",a),t.removeEventListener("drop",l)}}function DW(){return window.openStationConfig?.desktopStorage?.canAddToMedia===!0}function RW(e){if(e.type!=="upload"||e.isMedia!==!0||!DW())return;const t=parseInt(String(e.ref??""),10);if(!(!Number.isFinite(t)||t<=0))return{kind:"upload",fileId:t,title:String(e.title??""),mime:String(e.mime??""),thumbnailUrl:e.previewUrl?String(e.previewUrl):void 0}}async function xW(e){if(e.kind!=="upload")return null;try{const t=await Ir(e.fileId);return{kind:"attachment",id:t.attachmentId,url:t.url,title:t.title||e.title,alt:"",mime:e.mime,thumbnailUrl:e.thumbnailUrl}}catch(t){return gn(ue,t,{lead:"Could not add to the Media Library",fallback:"Could not add to the Media Library."}),null}}function MW(){return sR("upload",xW)}function WW(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o};if(t.type==="upload")return RW(t)}function $s(){return window.wp?.os?.dragManager??null}const PW="os-files-layer";function Nr(e){return e===0?"column":"row"}function $W(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function Zv(e,t){return t!==0||!e?e:{get width(){return ge(e).width},get height(){return ge(e).height}}}function Jv(e,t=0){const n=Nr(t),o=Zv(e,t),s=document.createElement("div");s.className=PW,s.setAttribute("role","list"),s.dataset.folderId=String(t),e.appendChild(s);let i="";const r=N=>{const L=oe.getState().placementsByFolder.get(t)??[],M=new Map;for(const P of L)P&&M.set(String(P.id),P);return N.map(P=>M.get(P)).filter(P=>!!P)},a=new Set,l=new Set,c=Ix(s,{itemSelector:`.${de}`,background:e,surface:"files",scope:String(t),keyOf:N=>N.dataset.placementId??null,onChange:N=>{const L=r(N),M=L.length===1?L[0]:null;for(const P of a)try{P(M)}catch(H){console.error("[openstation] files: selection listener threw:",H)}for(const P of l)try{P(L)}catch(H){console.error("[openstation] files: selection listener threw:",H)}}}),d=()=>r(c.keys()),u=N=>{const L=new Map,M=new Set;let P=0;for(const z of N){if(!$e(z))continue;const y=wn(0,P);L.set(z.id,{x:y.x,y:y.y}),M.add(Ce(y.col,y.row)),P+=1}const H=new Map;for(const z of N){if(L.has(z.id))continue;const y=Ws(z.x,z.y),E=Ce(y.col,y.row);if(!M.has(E)){M.add(E);continue}const T=Ht(z.x,z.y,M,o,n);M.add(Ce(T.col,T.row)),H.set(z.id,{x:T.x,y:T.y})}return{pinnedSlots:L,displaced:H}},f=(N,L,M,P)=>{const H=M.get(L.id),z=P.get(L.id);H?mn(N,H.x,H.y):z?mn(N,z.x,z.y):mn(N,L.x,L.y)},p=(N,L,M)=>{const P=J1(N,t),H=L.get(N.id);if(H){if(mn(P,H.x,H.y),P.classList.add(`${de}--pinned`),ob(P,N,c,d),Qv(N)){const y=$s();y&&I.set(N.id,nb(y,P,N))}return P}const z=M.get(N.id);if(z&&mn(P,z.x,z.y),zW(P,N,t,c,d),ob(P,N,c,d),N.file.type==="folder"){const y=parseInt(N.file.ref,10);if(y>0){const E=$s();if(E){const T=GW(E,P,y);_.set(N.id,T)}}}else if(Qv(N)){const y=$s();y&&I.set(N.id,nb(y,P,N))}return P},g=N=>{const L=new Map;for(const z of s.querySelectorAll("[data-placement-id]")){const y=z.dataset.placementId??"",E=parseInt(y,10);if(y===""||Number.isNaN(E)&&y!=="-0")return!1;L.set(E,z)}const M=new Set;for(const z of N)M.add(z.id);for(const z of N){const y=L.get(z.id);if(!y)continue;if(y.dataset.fileType!==z.file.type||y.dataset.fileRef!==z.file.ref||y.classList.contains(`${de}--pinned`)!==$e(z))return!1}for(const[z,y]of L){if(M.has(z))continue;const E=_.get(z);if(E){try{E()}catch{}_.delete(z)}const T=I.get(z);if(T){try{T()}catch{}I.delete(z)}y.remove()}const{pinnedSlots:P,displaced:H}=u(N);for(const z of N){const y=L.get(z.id);if(y){f(y,z,P,H),tb(y,z);continue}s.appendChild(p(z,P,H))}return c.refresh(),A("os.files.grid-rendered",{folderId:t,count:N.length}),!0},h=N=>{const M=(N.placementsByFolder.get(t)??[]).slice().sort((y,E)=>{const T=$e(y)?0:1,x=$e(E)?0:1;return T-x}),P=UW(M);if(P===i||(i=P,HW(M,s,o,n))||g(M))return;s.replaceChildren();for(const[,y]of _)try{y()}catch{}_.clear();for(const[,y]of I)try{y()}catch{}I.clear();const{pinnedSlots:H,displaced:z}=u(M);for(const y of M)s.appendChild(p(y,H,z));c.refresh(),A("os.files.grid-rendered",{folderId:t,count:M.length})},m=[],_=new Map,I=new Map;let O=null,$=null;const S=N=>{if(O||N.payload.type!=="desktop-file")return;const L=document.createElement("div");L.className="os-files-drop-preview",L.setAttribute("aria-hidden","true"),s.appendChild(L),O=L;const M=N.payload.ghost,P=M?.offsetX??0,H=M?.offsetY??0,y=N.payload.data?.placement?.id,E=(X,Y)=>{const ce=s.getBoundingClientRect(),q=Math.max(0,X-ce.left-P),se=Math.max(0,Y-ce.top-H),Ee=oe.getState().placementsByFolder.get(t)??[],zt=Dr(Ee,y),Ne=Ht(q,se,zt,o,n);L.style.transform=`translate3d(${Ne.x}px, ${Ne.y}px, 0)`},T=N.payload.source.getBoundingClientRect();E(T.left+P,T.top+H);const x=X=>{E(X.clientX,X.clientY)};document.addEventListener("pointermove",x),$=x},R=()=>{$&&(document.removeEventListener("pointermove",$),$=null),O&&(O.remove(),O=null)},W={id:`os-files-canvas-${t}`,element:e,accept:N=>{if(N.type!=="desktop-file"&&N.type!=="shortcut")return LW(N,{folderId:t,host:e});if(t>0&&N.type==="desktop-file"){const L=N.data;for(const M of yn(L)){if(M.file?.type!=="folder")continue;const P=parseInt(M.file.ref,10);if(!Number.isNaN(P)&&eb(P,t))return!1}}return!0},onEnter:N=>{e.setAttribute("data-files-drop-active",""),(N.payload.type==="desktop-file"||N.payload.type==="shortcut")&&S(N)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),R()},onDrop:(N,L)=>{if(e.removeAttribute("data-files-drop-active"),R(),N.payload.type!=="desktop-file"&&N.payload.type!=="shortcut"){TW(N,L,{folderId:t,host:e});return}const M=s.getBoundingClientRect(),P=N.payload.ghost,H=P?.offsetX??0,z=P?.offsetY??0,y=Math.max(0,L.clientX-M.left-H),E=Math.max(0,L.clientY-M.top-z),T=oe.getState().placementsByFolder.get(t)??[];if(N.payload.type==="desktop-file"){const x=N.payload.data,X=yn(x),Y=new Set(X.map(se=>se.id)),ce=Dr(T,Y),q=Ht(y,E,ce,o,n);ce.add(Ce(q.col,q.row));for(const se of X){let Ee=q;if(se.id!==x.placement.id){const Ne=se.x-x.placement.x,ta=se.y-x.placement.y;Ee=Ht(Math.max(0,q.x+Ne),Math.max(0,q.y+ta),ce,o,n),ce.add(Ce(Ee.col,Ee.row))}const zt={...se,x:Ee.x,y:Ee.y,parentId:t};if(oe.upsertPlacement(zt),A("os.files.tile-manually-placed",{folderId:t,placementId:se.id}),Or(se)){const Ne=Ar(se);Ne&&FW(Ne,Ee.x,Ee.y);continue}yo(se.id,{x:Ee.x,y:Ee.y,parentId:t},se.updatedAtMs).then(Ne=>{oe.upsertPlacement(Ne,"remote")}).catch(Ne=>{Fv(Ne)?Hv(Ne):console.error("[openstation] files: drag persist failed",Ne),oe.upsertPlacement(se)})}return}if(N.payload.type==="shortcut"){const x=N.payload.data;Sd(Tr(x),t,e)}}},U=$s();if(U&&m.push(U.registerDropTarget(W)),m.push(OW({host:e,container:s,folderId:t,fileEntities:(N,L)=>{Sd(N,L,L===t?e:null)}})),!oe.getState().hydratedFolders.has(t)){const N=$W(t);N&&oe.setFolderPlacements(t,N)}h(oe.getState()),queueMicrotask(()=>V());const F=oe.subscribe(N=>{h(N),V()});let K=()=>{};const Q=new Promise(N=>{K=N});oe.getState().hydratedFolders.has(t)?queueMicrotask(K):xe(t).then(N=>{oe.setFolderPlacements(t,N.placements)}).catch(N=>{console.error("[openstation] files: failed to hydrate folder",t,N)}).finally(()=>{K()});const Z=N=>{const L=new Set;for(let M=0;M<N;M+=1)L.add(Ce(0,M));return L},C=(N,L)=>{const M=N.slice();switch(L){case"name-asc":M.sort((P,H)=>P.file.title.localeCompare(H.file.title));break;case"name-desc":M.sort((P,H)=>H.file.title.localeCompare(P.file.title));break;case"date-asc":M.sort((P,H)=>P.updatedAtMs-H.updatedAtMs);break;case"date-desc":M.sort((P,H)=>H.updatedAtMs-P.updatedAtMs);break}return M},D=N=>{const L=oe.getState().placementsByFolder.get(t);if(!L||L.length===0)return;const M=L.filter(y=>$e(y)),P=L.filter(y=>!$e(y)),H=C(P,N),z=Uv(H.length,Z(M.length),n,o);H.forEach((y,E)=>{const{x:T,y:x}=z[E],X={...y,x:T,y:x,sortOrder:E};oe.upsertPlacement(X),!Or(y)&&yo(y.id,{x:T,y:x,sortOrder:E}).catch(Y=>{console.error("[openstation] files: sort persist failed",Y)})})},V=()=>{const N=oe.getState().placementsByFolder.get(t);if(!N||N.length===0)return;const L=Ps(o),M=L.width>0?L.width:1/0,P=L.height>0?L.height:1/0;if(!N.some(T=>T.x+Wv>M||T.y+Pv>P))return;const z=N.filter(T=>$e(T)),y=N.filter(T=>!$e(T)),E=Uv(y.length,Z(z.length),n,o);y.forEach((T,x)=>{const X=s.querySelector(`[data-placement-id="${T.id}"]`);X&&mn(X,E[x].x,E[x].y)})};let j=Ps(o),te=null;return typeof ResizeObserver<"u"&&(te=new ResizeObserver(()=>{const N=Ps(o);N.width===j.width&&N.height===j.height||(j=N,V())}),te.observe(e)),{host:e,folderId:t,onSelectionChange(N){return a.add(N),()=>{a.delete(N)}},onSelectionChanged(N){return l.add(N),()=>{l.delete(N)}},getSelection:d,selectAll:()=>c.model.selectAll(),clearSelection:()=>c.model.clear(),sort:D,reflow:V,hydrated:Q,dispose(){F(),te?.disconnect(),te=null;for(const N of m)try{N()}catch{}m.length=0;for(const N of _.values())try{N()}catch{}_.clear();for(const N of I.values())try{N()}catch{}I.clear(),c.destroy(),a.clear(),l.clear(),s.remove()}}}function UW(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}:${$e(n)?1:0}`);return t.join("|")}function $e(e){return!!e.file.pinned}function Or(e){return cW(e)}const BW="desktop-mode-recycle-bin";function Qv(e){return!(e.file?.type==="folder"||e.file?.ref===BW)}function Dr(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,a)=>{const l=$e(r)?0:1,c=$e(a)?0:1;return l-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if($e(r))s.add(Ce(0,i)),i+=1;else{const a=Ws(r.x,r.y);s.add(Ce(a.col,a.row))}return s}function Sd(e,t,n){const o=oe.getState().placementsByFolder.get(t)??[],s=Dr(o),i=Nr(t);for(const r of e){const a=Lr(s,i,Zv(n,t));s.add(Ce(a.col,a.row)),Os({parentId:t,type:r.kind,ref:r.ref,x:a.x,y:a.y}).then(l=>{oe.upsertPlacement(l),A("os.files.shortcut-dropped",{folderId:t,placement:l})}).catch(l=>{console.error("[openstation] shortcut drop failed:",l)})}}function eb(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=oe.getState();for(const a of o.placementsByFolder.values())for(const l of a){if(l.file?.type!=="folder")continue;const c=parseInt(l.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,l.parentId)}const s=new Set;let i=t,r=256;for(;i>0&&r-- >0;){if(i===e||s.has(i))return!0;s.add(i);const a=n.get(i);if(a===void 0)return!1;i=a}return!1}function FW(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 HW(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(`${de}--pinned`)!==$e(d))return!1}const r=new Map,a=new Set;let l=0;for(const d of e){if(!$e(d))continue;const u=wn(0,l);r.set(d.id,{x:u.x,y:u.y}),a.add(Ce(u.col,u.row)),l+=1}const c=new Map;for(const d of e){if(r.has(d.id))continue;const u=Ws(d.x,d.y),f=Ce(u.col,u.row);if(!a.has(f)){a.add(f);continue}const p=Ht(d.x,d.y,a,n,o);a.add(Ce(p.col,p.row)),c.set(d.id,{x:p.x,y:p.y})}for(const d of e){const u=i.get(d.id);if(!u)continue;const f=r.get(d.id)??c.get(d.id)??{x:d.x,y:d.y};mn(u,f.x,f.y),tb(u,d)}return!0}function tb(e,t){const n=Iv(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function nb(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?eW(s,o):void 0},accept:i=>(s=i.type,tW(i,o)),onEnter:()=>{t.classList.add(`${de}--drop-target`)},onLeave:()=>{t.classList.remove(`${de}--drop-target`)},onDrop:(i,r)=>{t.classList.remove(`${de}--drop-target`),nW(i,r,o)}})}function GW(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 yn(r)){if(a.file.type==="folder"&&parseInt(a.file.ref,10)===n||a.parentId===n||Or(a))return!1;if(a.file.type==="folder"){const l=parseInt(a.file.ref,10);if(!Number.isNaN(l)&&eb(l,n))return!1}}}return!0},onEnter:()=>{t.classList.add(`${de}--drop-target`)},onLeave:()=>{t.classList.remove(`${de}--drop-target`)},onDrop:i=>{if(t.classList.remove(`${de}--drop-target`),i.payload.type==="desktop-file"){const r=i.payload.data,a=oe.getState().placementsByFolder.get(n)??[],l=Dr(a),c=Nr(n);for(const d of yn(r)){const u=Lr(l,c);l.add(Ce(u.col,u.row)),oe.upsertPlacement({...d,x:u.x,y:u.y,parentId:n}),yo(d.id,{x:u.x,y:u.y,parentId:n},d.updatedAtMs).then(f=>{oe.upsertPlacement(f,"remote")}).catch(f=>{Fv(f)?Hv(f):console.error("[openstation] files: move-into-folder persist failed",f),oe.upsertPlacement(d)})}return}if(i.payload.type==="shortcut"){const r=i.payload.data;Sd(Tr(r),n)}}};return e.registerDropTarget(s)}function zW(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=$s();if(!r)return;const l=oe.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||l.x,parseFloat(e.style.top)||l.y;const c=o.model.has(String(l.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===l.id)?d:[l];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(l.id)])};document.addEventListener("os.drag.start",f);const p=()=>{document.removeEventListener("os.drag.start",f),document.removeEventListener("pointerup",p)};document.addEventListener("pointerup",p)}if(u.length>1){const f=[],p=()=>{for(const h of f)h.classList.remove(`${de}--dragging`);f.length=0,document.removeEventListener("os.drag.start",g),document.removeEventListener("os.drag.end",p),document.removeEventListener("pointerup",p)},g=()=>{for(const h of u){const m=e.parentElement?.querySelector(`[data-placement-id="${h.id}"]`);m&&m!==e&&(m.classList.add(`${de}--dragging`),f.push(m))}};document.addEventListener("os.drag.start",g),document.addEventListener("os.drag.end",p),document.addEventListener("pointerup",p)}r.start({payload:{type:"desktop-file",source:e,data:{placement:l,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:WW(l)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?X1(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 ob(e,t,n,o){e.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=oe.currentPlacement(t);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),a=r.length>0?r:[i],l=ky(a,wW);oW({x:s.clientX,y:s.clientY},l,{placementIds:a.map(c=>c.id)})})}function sb(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 _o="os-folder-status-bar";function jW(e,t,n={}){const o=document.createElement("div");o.className=_o,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const a=Bt().placementsByFolder.get(t)??[],l=a.filter(p=>p.file.type==="folder").length,c=a.length-l;let d=0;for(const p of a)if(p.file.type==="upload"){const g=Number(p.file.sizeBytes??0);Number.isFinite(g)&&g>0&&(d+=g)}const u={folderId:t,selectedCount:n.selection?.count()??0,totals:{files:c,folders:l,total:a.length,bytes:d}},f=VW(u);KW(o,f)};s();const i=fd(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function VW(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:rb(n,"file","files")+(t>0?`, ${rb(t,"folder","folders")}`:"")+(o>0?` (${sb(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=J("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function KW(e,t){const n=(i,r)=>{const a=typeof i.sort=="number"?i.sort:100,l=typeof r.sort=="number"?r.sort:100;return a!==l?a-l:i.label.localeCompare(r.label)},o=t.filter(i=>(i.align??"start")==="start").sort(n),s=t.filter(i=>i.align==="end").sort(n);e.replaceChildren(),e.appendChild(ib("start",o)),e.appendChild(ib("end",s))}function ib(e,t){const n=document.createElement("div");n.className=`${_o}__cluster ${_o}__cluster--${e}`;for(const o of t)n.appendChild(qW(o));return n}function qW(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${_o}__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=`${_o}__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=`${_o}__label`,o.textContent=e.label,n.appendChild(o),n}function rb(e,t,n){return`${e} ${e===1?t:n}`}const Rr="os-icon-canvas-menu";let Us=null,xr=null,kd=null,Bs=null,Fs=null;function YW(e,t){t.openOnBackgroundClick;const n=i=>{XW(i.target)||ab(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(kd===e&&Us){vn();return}const a=ZW(t),l=J("os.icon-canvas.menu",a,t.scope),c=Array.isArray(l)?l:a,d=++o;si(()=>d===o,()=>JW(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),vn()}}}function XW(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function ab(e){return e instanceof Element?e.closest(`.${Rr}`)!==null:!1}function ZW(e){const n=[{id:"sort-by",label:b("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:b("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:b("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:b("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:b("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function cb(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 JW(e,t,n){if(vn(),e.length===0)return;kd=n;const o=cb(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(Rr),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=lb(s,r);Mr(r)&&a.addEventListener("mouseenter",()=>{db(r,a)})}s.addEventListener("os-context-menu-pick",r=>{const a=r.detail,l=i.get(a.id);if(l){if(Mr(l)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${l.id}"]`);c&&db(l,c);return}vn(),l.onClick?.()}}),document.body.appendChild(s),Us=s,Rl(s),queueMicrotask(()=>{Bs=r=>{ab(r.target)||vn()},Fs=r=>{r.key==="Escape"&&vn()},document.addEventListener("mousedown",Bs),document.addEventListener("keydown",Fs)})}function lb(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",QW(t.icon)),Mr(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function db(e,t){if(ub(),!Mr(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(Rr,`${Rr}--flyout`);const o=new Map;for(const s of cb(e.children??[]))o.set(s.id,s),lb(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),vn(),r.onClick?.())}),document.body.appendChild(n),xr=n,Cy(n,t)}function Mr(e){return Array.isArray(e.children)&&e.children.length>0}function ub(){xr&&(xr.remove(),xr=null)}function vn(){ub(),Us&&(Us.remove(),Us=null),kd=null,Bs&&(document.removeEventListener("mousedown",Bs),Bs=null),Fs&&(document.removeEventListener("keydown",Fs),Fs=null)}function QW(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const bn="os-breadcrumbs";function eP(e,t,n={}){if(e.replaceChildren(),e.classList.add(bn),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${bn}__back`,s.setAttribute("aria-label",b("Back","desktop-mode")),s.title=b("Back","desktop-mode");const i=document.createElement("span");i.className="dashicons dashicons-arrow-left-alt2",i.setAttribute("aria-hidden","true"),s.appendChild(i),n.backDisabled&&(s.disabled=!0);const r=n.onBack;s.addEventListener("click",()=>{s.disabled||r()}),e.appendChild(s)}const o=document.createElement("nav");o.className=`${bn}__crumbs`,o.setAttribute("aria-label",b("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const l=document.createElement("span");l.className=`${bn}__sep`,l.setAttribute("aria-hidden","true"),l.textContent="›",o.appendChild(l)}if(!s.onClick){const l=document.createElement("span");l.className=`${bn}__crumb ${bn}__crumb--current`,l.setAttribute("aria-current","page"),l.textContent=s.label,o.appendChild(l);return}const r=document.createElement("button");r.type="button",r.className=`${bn}__crumb`,r.textContent=s.label;const a=s.onClick;r.addEventListener("click",()=>{a()}),o.appendChild(r)}),e.appendChild(o)}function Wr(e){const t=document.createElement("a");t.href=e,t.setAttribute("download",""),t.style.display="none",document.body.appendChild(t),t.click(),t.remove()}async function Hs(e,t={}){const n=await Ae(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":tP(),...t.headers??{}},...t});if(!n.ok)throw await Nn(n);return await n.json()}function tP(){return window.wp?.os?.config?.restNonce??""}function nP(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function Gs(e){return rt(nP(),e)}function oP(e,t){const n=J("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(sP(e));return}t.replaceChildren(mP()),iP(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(gP(o))})}function sP(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 iP(e){const t=e.file;switch(t.type){case"post":return rP(t.ref,t);case"folder":return fP(t);case"shortcut":return pP(t);case"attachment":return dP(t.ref,t);case"upload":return uP(t);case"user":return aP(t.ref,t);case"term":return cP(t);case"comment":return lP(t.ref,t);case"bookmark":return hP(t);default:return ot(t)}}async function rP(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await Hs(Gs(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return ot(t);const s=ut(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Pr(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(fb(o.date)),o.status&&o.status!=="publish"&&a.push(o.status),r.textContent=a.join(" · "),s.appendChild(r),o.content?.rendered){const u=document.createElement("div");u.className="os-my-wordpress__article-content",u.innerHTML=o.content.rendered,s.appendChild(u)}const l=document.createElement("footer");l.className="os-my-wordpress__article-footer";const c=document.createElement("os-button");c.setAttribute("variant","secondary"),c.textContent=b("Explore details","desktop-mode"),c.title=b("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),c.addEventListener("click",()=>{const u=typeof t.postType=="string"?t.postType:"post";Av({entityId:u==="page"?"pages":"posts",postId:n,postTitle:Pr(o.title.rendered)||`#${n}`})}),l.appendChild(c);const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=b("Open in editor","desktop-mode"),d.addEventListener("click",()=>{const u=window.wp?.os?.config?.adminUrl;if(!u)return;const f=`${u}post.php?post=${n}&action=edit`,p=window.wp?.os?.windowManager,h=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${h}-edit-${n}`,url:f,title:Pr(o.title.rendered),icon:t.icon})}),l.appendChild(d),s.appendChild(l),s}async function aP(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;try{o=await Hs(Gs(`desktop-mode/v1/user-stats/${n}`))}catch{return ot(t)}const s=ut("os-my-wordpress__user"),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.profile.avatarUrl){const c=document.createElement("img");c.className="os-my-wordpress__user-avatar",c.src=o.profile.avatarUrl,c.alt="",i.appendChild(c)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");if(a.className="os-my-wordpress__article-title",a.textContent=o.profile.name||t.title||`#${n}`,r.appendChild(a),o.profile.roleLabels&&o.profile.roleLabels.length>0){const c=document.createElement("div");c.className="os-my-wordpress__user-roles";for(const d of o.profile.roleLabels){const u=document.createElement("span");u.className="os-my-wordpress__user-role",u.textContent=d,c.appendChild(u)}r.appendChild(c)}if(i.appendChild(r),s.appendChild(i),o.profile.description){const c=document.createElement("div");c.className="os-my-wordpress__user-bio",c.textContent=o.profile.description,s.appendChild(c)}const l=document.createElement("div");return l.className="os-my-wordpress__user-stats",l.appendChild(So(o.counts.posts.total.toLocaleString(),b("Posts","desktop-mode"))),l.appendChild(So(o.counts.pages.total.toLocaleString(),b("Pages","desktop-mode"))),l.appendChild(So(o.counts.commentsReceived.toLocaleString(),b("Comments received","desktop-mode"))),s.appendChild(l),s}async function cP(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return ot(e);let o=null;try{o=await Hs(Gs(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return ot(e)}const s=ut(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=o.profile.name||e.title||`#${t}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.profile.taxonomyLabel||o.profile.taxonomy,s.appendChild(r),o.profile.description){const l=document.createElement("div");l.className="os-my-wordpress__article-content",l.innerHTML=o.profile.description,s.appendChild(l)}const a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(So(o.counts.posts.total.toLocaleString(),b("Posts","desktop-mode"))),a.appendChild(So(o.counts.commentsReceived.toLocaleString(),b("Comments","desktop-mode"))),a.appendChild(So(o.counts.distinctAuthors.toLocaleString(),b("Authors","desktop-mode"))),s.appendChild(a),s}async function lP(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;try{o=await Hs(Gs(`desktop-mode/v1/comment-stats/${n}`))}catch{return ot(t)}const s=ut(),i=document.createElement("header");if(i.className="os-my-wordpress__user-header",o.author.avatarUrl){const d=document.createElement("img");d.className="os-my-wordpress__user-avatar",d.src=o.author.avatarUrl,d.alt="",i.appendChild(d)}const r=document.createElement("div");r.className="os-my-wordpress__user-headline";const a=document.createElement("h2");a.className="os-my-wordpress__article-title",a.textContent=o.author.name,r.appendChild(a);const l=document.createElement("p");l.className="os-my-wordpress__article-meta",l.textContent=`${fb(o.comment.date)} · ${o.comment.status}`,r.appendChild(l),i.appendChild(r),s.appendChild(i);const c=document.createElement("div");if(c.className="os-my-wordpress__article-content",c.innerHTML=o.comment.rendered,s.appendChild(c),o.post){const d=document.createElement("div");d.className="os-my-wordpress__comment-post";const u=document.createElement("a");u.className="os-my-wordpress__comment-post-title",u.href=o.post.link,u.target="_blank",u.rel="noopener noreferrer",u.textContent=o.post.title,d.appendChild(u),s.appendChild(d)}return s}async function dP(e,t){const n=parseInt(e,10);if(!n)return ot(t);let o=null;try{o=await Hs(Gs(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return ot(t)}const s=ut(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=Pr(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");if(r.className="os-my-wordpress__article-meta",r.textContent=o.mime_type,s.appendChild(r),o.mime_type.startsWith("image/")){const a=document.createElement("img");a.className="os-my-wordpress__article-hero";const l=o.media_details?.sizes;a.src=l?.large?.source_url??l?.medium?.source_url??o.source_url,a.alt=o.alt_text??"",s.appendChild(a)}else{const a=document.createElement("p"),l=document.createElement("a");l.href=o.source_url,l.textContent=o.source_url,l.target="_blank",l.rel="noopener noreferrer",a.appendChild(l),s.appendChild(a)}return s}function uP(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Uploaded file","desktop-mode"),t.appendChild(n);const o=typeof e.mime=="string"?e.mime:"",s=typeof e.sizeBytes=="number"?e.sizeBytes:0,i=typeof e.kind=="string"?e.kind:"file",r=document.createElement("p");r.className="os-my-wordpress__article-meta",r.textContent=[o,s>0?sb(s):""].filter(Boolean).join(" · "),t.appendChild(r);const a=parseInt(e.ref,10),l=()=>{const c=document.createElement("p");return c.className="os-my-wordpress__article-meta os-files__no-preview",c.textContent=b("No preview available for this file type.","desktop-mode"),c};if(a>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=hn(a),c.alt=e.title||"",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="video"){const c=document.createElement("video");c.className="os-my-wordpress__article-hero",c.controls=!0,c.preload="metadata",c.src=hn(a),c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else if(a>0&&i==="audio"){const c=document.createElement("audio");c.controls=!0,c.preload="metadata",c.src=hn(a),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(l())}),t.appendChild(c)}else t.appendChild(l());if(a>0){const c=document.createElement("footer");c.className="os-my-wordpress__article-footer";const d=document.createElement("os-button");d.setAttribute("variant","primary"),d.textContent=b("Download","desktop-mode"),d.addEventListener("click",()=>{Wr(hn(a))}),c.appendChild(d),t.appendChild(c)}return t}function fP(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=b("Double-click to open.","desktop-mode"),t.appendChild(o),t}function pP(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=b("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function hP(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||b("Bookmark","desktop-mode"),t.appendChild(n);const o=typeof e.url=="string"?e.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",t.appendChild(s)}return t}function ot(e){const t=ut(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||e.type,t.appendChild(n);const o=document.createElement("p");if(o.className="os-my-wordpress__article-meta",o.textContent=le(b("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="os-my-wordpress__article-meta",s.textContent=b("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function ut(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function So(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 mP(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function gP(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:b("Unknown error.","desktop-mode"),t}function Pr(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function fb(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function pb(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=b("Select an item to preview it here.","desktop-mode"),e}function wP(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=le(b("%d items selected","desktop-mode"),e.length),t.appendChild(n);const o=new Map;for(const i of e){const r=i.file?.type||"item";o.set(r,(o.get(r)??0)+1)}const s=Array.from(o.entries()).sort((i,r)=>r[1]-i[1]||i[0].localeCompare(r[0])).map(([i,r])=>`${r} × ${i}`).join(" · ");if(s){const i=document.createElement("div");i.className="os-files-preview__selection-breakdown",i.textContent=s,t.appendChild(i)}return t}const $r="desktop-mode-embed-",yP=800,vP=600,Id=360,Ad=240,Ur=16,Cd=new Map;function bP(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?`${$r}${s.id}`:`${$r}anon-${kP(n)}`,a=i?.name?.trim()??"",l=a!==""?a:e.title(),c={id:r,baseId:r,url:n,title:l,icon:e.icon(),minWidth:Id,minHeight:Ad},d=i?.window,u=document.getElementById("os-area"),f=u?ge(u):{x:0,y:0,width:window.innerWidth,height:window.innerHeight};if(d&&Number.isFinite(d.width)&&Number.isFinite(d.height)){const{x:p,y:g,width:h,height:m}=SP(d,f);c.x=p,c.y=g,c.width=h,c.height=m}else c.width=Math.min(yP,Math.max(Id,f.width-Ur*2)),c.height=Math.min(vP,Math.max(Ad,f.height-Ur*2));s&&d&&Cd.set(r,{...d}),o.open(c)}let hb=!1;function EP(){if(hb)return;hb=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith($r))return;const s=o.slice($r.length),i=parseInt(s,10);if(!i)return;const l=window.wp?.os?.windowManager?.getById?.(o)?.element;if(!l)return;const c={x:l.offsetLeft,y:l.offsetTop,width:l.offsetWidth,height:l.offsetHeight},d=Cd.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(Cd.set(o,c),_P(i,c))};ee(v.WINDOW_DRAG_END,"os-embed-persist",e),ee(v.WINDOW_RESIZE_END,"os-embed-persist",e)}async function _P(e,t){try{const i={...(await xe(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await yo(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function SP(e,t){const n=Math.max(Id,Math.min(e.width,t.width-Ur)),o=Math.max(Ad,Math.min(e.height,t.height-Ur)),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 kP(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 zs(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function mb(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 IP(){Fe({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${zs()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Fe({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${zs()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),Fe({id:"agent-chat",label:b("Agent chat","desktop-mode"),types:["user"],isDefault:!0,sort:5,appliesTo:e=>e.shape.isAgent===!0,handler:{kind:"js",open:e=>{const t=e.shape;pv({id:Number.parseInt(t.ref,10),name:t.title,description:t.agentDescription??"",avatarUrl:t.previewUrl??""},"agents-open")}}}),Fe({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${zs()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),Fe({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`${zs()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),Fe({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${zs()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),Fe({id:"desktop-mode-upload-download",label:"Download",types:["upload"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=parseInt(e.ref(),10);t&&Wr(hn(t))}}}),Fe({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=oe.getState().folders.get(t),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,a=e.title(),l=r?`${a} · Shared`:a;n.open({id:o,baseId:o,url:`#folder-${t}`,title:l,icon:e.icon(),native:!0,render:c=>{c.replaceChildren(),c.classList.add("desktop-mode-folder-window"),Vi("desktop-mode-my-wordpress");const d=[{folderId:t,title:e.title()}];let u=null;const f=document.createElement("header");c.appendChild(f);const p=document.createElement("div");p.style.cssText="flex:1 1 auto;min-height:0;display:flex;flex-direction:column;",c.appendChild(p);const g=()=>{const m=d.map((_,I)=>I===d.length-1?{label:_.title}:{label:_.title,onClick:()=>{d.length=I+1,h()}});eP(f,m,{onBack:()=>{d.length<=1||(d.pop(),h())},backDisabled:d.length<=1})},h=()=>{u?.(),u=null,p.replaceChildren();const m=document.createElement("div");m.className="os-folder-window__split",p.appendChild(m);const _=document.createElement("div");_.className="os-folder-window__layer",m.appendChild(_);const I=document.createElement("div");I.className="os-folder-window__preview",I.appendChild(pb()),m.appendChild(I);const O=d[d.length-1],$=Jv(_,O.folderId),S=$.onSelectionChanged(F=>{if(F.length===0){I.replaceChildren(pb());return}if(F.length>1){I.replaceChildren(wP(F));return}oP(F[0],I)}),R=F=>{if(!(F.target instanceof Element))return;const K=F.target.closest(".os-file-tile");if(!K||K.dataset.fileType!=="folder")return;const Q=parseInt(K.dataset.fileRef??"",10);if(!Q)return;F.preventDefault(),F.stopPropagation();const Z=K.querySelector(".os-file-tile__label")?.textContent??`#${Q}`;d.push({folderId:Q,title:Z}),h()};_.addEventListener("dblclick",R,!0);const W=YW(_,{scope:`os-folder:${O.folderId}`,onSort:F=>$.sort(F),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{vd({onSubmit:async F=>{const K=await rd({name:F}),Q=oe.getState().placementsByFolder.get(O.folderId)??[],Z=Bv(Q),C=Ht(Ft,Ft,Z,_,Nr(O.folderId)),D=await Os({type:"folder",ref:String(K.id),parentId:O.folderId,x:C.x,y:C.y});oe.upsertFolder(K),oe.upsertPlacement(D)}})}}]}),U=jW(p,O.folderId,{selection:{count:()=>$.getSelection().length,subscribe:F=>$.onSelectionChanged(()=>F())}});u=()=>{S(),W.dispose(),U.dispose(),_.removeEventListener("dblclick",R,!0),$.dispose()},g()};h()},width:720,height:480,minWidth:360,minHeight:240})}}}),Fe({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(A(v.DESKTOP_ICON_CLICKED,{id:e.shape.ref,target:t.shortcutWindow?"window":"url"}),t.shortcutWindow&&n.openWindow){n.openWindow(t.shortcutWindow);return}if(t.shortcutUrl&&n.windowManager)try{const o=new URL(t.shortcutUrl,window.location.origin);if(o.origin!==window.location.origin){window.open(o.toString(),"_blank","noopener,noreferrer");return}if(Me(o.toString()))return;const s=n.config?.adminUrl,i=s?fe(o.toString(),s):`desktop-icon-${e.ref()}`,r=ar(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{}}}}}),Fe({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=mb(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Fe({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=mb(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),Fe({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{bP(e,t)}}})}const AP="os-file-associations";let En=null;function CP(){Pm({id:AP,label:"File Associations",order:50,render(e){En&&(En(),En=null),gb(e),En=rv(()=>{if(!e.isConnected){En&&(En(),En=null);return}gb(e)})}})}function gb(e){e.replaceChildren();const t=nv();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=Jl(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(LP(i.type,i.label,o));e.appendChild(s)}function LP(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=Ql(e);if(i.length===0){const c=document.createElement("span");return c.className="os-file-associations__none",c.textContent="No app available",o.appendChild(c),o}const r=ed(e),a=n[e]??r?.id??"",l=document.createElement("os-select");l.setAttribute("value",a),l.setAttribute("aria-label",`Default app for ${t}`),l.className="os-file-associations__select",s.htmlFor=`assoc-${e}`,l.id=`assoc-${e}`;for(const c of i){const d=document.createElement("os-option");d.setAttribute("value",c.id),d.textContent=c.isDefault?`${c.label} (default)`:c.label,l.appendChild(d)}return l.addEventListener("os-pick",c=>{const d=c.detail?.value;if(!d)return;const u={...Jl(),[e]:d};sv(u),wv(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(l),o}function TP(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,ld(t),!0)}function NP(){return window.openStationConfig?.filesOverlaysBundleUrl??""}async function js(){if(window.openStationFilesOverlays)return window.openStationFilesOverlays;const e=NP();if(!e)return null;try{await pe(e)}catch(t){return console.warn("[openstation] files-overlays bundle failed to load",t),null}return window.openStationFilesOverlays??null}async function wb(...e){await(await js())?.openShareSettingsModal(...e)}async function OP(...e){await(await js())?.openFileShareModal(...e)}async function DP(...e){return(await js())?.openPendingFileInviteModal(...e)}async function RP(...e){return(await js())?.openPendingInviteModal(...e)}function xP(...e){js().then(t=>t?.openUrlDialog(...e))}function yb(){return Number(window.openStationConfig?.currentUserId??0)}function MP(e){window.wp?.os?.windowManager?.getById?.(e)?.close?.()}function Ld(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function vb(e){const t=Bt().folders.get(e);return t?Number(t.ownerId):0}function bb(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function WP(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function PP(e){return Number(e.file.ownerId??0)}function $P(){pt("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!Ld())return e;const n=WP(t);if(n===null)return e;const o=vb(n)||PP(t),s=yb();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:()=>{wb({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 Qt({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 yv(n),Ds(t.id);try{const a=await xe(0);Ut(0,a.placements)}catch{}const r=`os-folder-${n}`;MP(r),ue({message:"You left the shared folder."})}catch(r){gn(ue,r,{lead:"Could not leave",fallback:"Could not leave."})}}});return e}),os({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!Ld())return!1;const t=e.config.baseId??e.id,n=bb(t);return n===null?!1:vb(n)===yb()},onClick:e=>{if(!Ld())return;const t=e.config.baseId??e.id,n=bb(t);n!==null&&wb({folderId:n,folderName:e.config.title||`Folder ${n}`})}}),ee("os.files.tile-rendered","desktop-mode/folder-share",e=>{const{tile:t,placement:n}=e;if(n.file.type!=="folder"||!n.file.shareSummary?.shared||t.querySelector(".os-file-tile__share-badge"))return;const s=document.createElement("span");s.className="os-file-tile__share-badge dashicons dashicons-share",s.setAttribute("aria-label","Shared folder"),s.title="Shared folder",s.style.cssText=["position:absolute","top:6px","inset-inline-end:6px","background:rgba(0,0,0,0.55)","color:#fff","border-radius:50%","width:18px","height:18px","font-size:12px","line-height:18px","text-align:center","pointer-events:none"].join(";"),t.appendChild(s)})}let Td=null;function Br(){return Td||(Td=ae("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),Td}function UP(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 Eb(e){const t=Br(),n=new Map(t.state.pending.map(s=>[s.id,s]));let o=!1;for(const s of e){const i=s.targetType==="file"&&typeof s.folderId!="number"?{...s,folderId:0}:s;if(i.targetType==="file"){if(typeof i.fileId=="number"&&t.state.deniedFiles.has(i.fileId))continue}else if(t.state.deniedFolders.has(i.folderId))continue;const r=n.get(i.id);if(r){if(UP(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 Fr(e,t={}){const n=Br();n.state.pending=n.state.pending.filter(o=>o.id!==e),t.denied&&typeof t.folderId=="number"&&n.state.deniedFolders.add(t.folderId),t.denied&&typeof t.fileId=="number"&&n.state.deniedFiles.add(t.fileId),n.notify()}const _b=new Set;function BP(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function FP(){const e=Br(),t=n=>{if(BP()){for(const o of n.pending)if(!_b.has(o.id)){if(_b.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;DP({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?Fr(o.id):i==="denied"&&Fr(o.id,{denied:!0,fileId:s})});continue}RP({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Fr(o.id):s==="denied"&&Fr(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function HP(){return Number(window.openStationConfig?.currentUserId??0)}function Sb(){return window.openStationConfig?.desktopStorage??{}}function GP(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function zP(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function jP(){pt("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&Sb().zipAvailable){const i=Number(t.file.ref);return Number.isFinite(i)&&i>0&&e.push({id:"desktop-mode/folder-zip-download",label:"Download as .zip",icon:"dashicons-download",sort:45,onClick:()=>{Wr(_v(i))}}),e}const n=zP(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{Wr(hn(n))}});const o=Number(t.file.ownerId??0),s=HP();return o===s&&GP()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{OP({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 Qt({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 vv(n),Ds(t.id);try{const r=await xe(0);Ut(0,r.placements)}catch{}ue({message:"You left the shared file."})}catch(r){gn(ue,r,{lead:"Could not leave",fallback:"Could not leave."})}}}),e}),pt("os.wallpaper-context-menu","desktop-mode/uploads",e=>(Sb().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>kb(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>kb(!0)})),e))}function kb(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&&VP(n,e)}),t.click()}async function VP(e,t){const n=window.openStationConfig?.fileDropBundleUrl;if(n){try{await pe(n)}catch{ue({message:"Upload machinery failed to load — try again."});return}await window.openStationFileDrop?.routePickedFiles(e,t)}}function KP(){return window.openStationConfig?.desktopStorage??{}}function Ib(e){if(e.file.type!=="upload"||e.file.isMedia!==!0)return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function qP(e){return e.file.kind==="image"}function YP(e){ue({message:e.created?"Added to the Media Library.":"Already in the Media Library.",action:{label:"Open",onClick:()=>{nd({url:e.editUrl,title:e.title||"Attachment",icon:"dashicons-admin-media"})}}})}async function XP(e){try{YP(await Ir(e))}catch(t){gn(ue,t,{lead:"Could not add to the Media Library",fallback:"Could not add to the Media Library."})}}const ZP=async e=>{let t=0,n=0,o=0;for(const i of e){const r=Ib(i);if(r!==null)try{(await Ir(r)).created?t+=1:n+=1}catch{o+=1}}const s=[];t>0&&s.push(`Added ${t} ${t===1?"file":"files"} to the Media Library.`),n>0&&s.push(`${n} already there.`),o>0&&s.push(`${o} could not be added.`),s.length>0&&ue({message:s.join(" ")})};async function Ab(e,t){try{const n=await bv(e,t);nd({url:n.editUrl,title:t==="page"?"Add New Page":"Add New Post",icon:t==="page"?"dashicons-admin-page":"dashicons-admin-post"})||(window.location.href=n.editUrl)}catch(n){gn(ue,n,{lead:`Could not start a ${t}`,fallback:`Could not start a ${t}.`})}}function JP(){pt("os.files.tile-menu","desktop-mode/media-library",(e,t)=>{const n=Ib(t);if(n===null)return e;const o=KP();return!o.canAddToMedia||(e.push({id:"desktop-mode/upload-add-to-media",label:"Add to Media Library",icon:"dashicons-admin-media",sort:50,multi:!0,bulkLabel:s=>`Add ${s} files to Media Library`,bulk:ZP,onClick:()=>XP(n)}),!qP(t))||(o.canStartPost&&e.push({id:"desktop-mode/upload-start-post",label:"Start a post with this image",icon:"dashicons-admin-post",sort:55,onClick:()=>Ab(n,"post")}),o.canStartPage&&e.push({id:"desktop-mode/upload-start-page",label:"Start a page with this image",icon:"dashicons-admin-page",sort:56,onClick:()=>Ab(n,"page")})),e})}function QP(){return window.openStationConfig?.desktopStorage?.canAddToMedia===!0}function e$(e){const t=e.placement.file;if(t.type!=="post"||t.exists===!1||t.status==="trash"||!QP())return 0;const n=parseInt(String(t.ref??""),10);return Number.isFinite(n)&&n>0?n:0}function Cb(e){const t=yn(e);if(t.length===0)return[];const n=[];for(const o of t){const s=o?.file;if(!s||s.type!=="upload"||s.isMedia!==!0)return[];const i=parseInt(String(s.ref??""),10);if(!Number.isFinite(i)||i<=0)return[];n.push(i)}return n}async function t$(e,t){const n=parseInt(String(e.file.ref??""),10);try{const o=await Ev(n,t),s=o.attachments.length,i=s===1?"file":`${s} files`,r=o.title||e.file.title||`#${n}`;if(nd({url:o.editUrl,title:r,icon:e.file.icon||"dashicons-admin-post"}),ue({message:`Added ${i} to “${r}”.`}),o.featuredImageSet)try{const a=await xe(e.parentId);Ut(e.parentId,a.placements)}catch{}}catch(o){gn(ue,o,{lead:"Could not add to the post",fallback:"Could not add to the post."})}}function Lb(e){return{appliesTo:t=>{if(e$(t)===0)return!1;const n=t.placement.file.postType==="page";return e==="page"?n:!n},accept:t=>Cb(t).length>0,acceptLabel:e==="page"?"Add to page":"Add to post",onDrop:(t,n,o)=>{const s=Cb(t.payload.data);s.length!==0&&t$(o.placement,s)}}}function n$(){const e=xs("desktop-file",Lb("page")),t=xs("desktop-file",Lb("other"));return()=>{e(),t()}}h1(),IP(),EP(),CP(),TP(),$P(),jP(),JP(),MW(),n$();const Nd=window.openStationConfig?.serverPendingShares;Array.isArray(Nd)&&Nd.length>0&&Eb(Nd),FP();const Ge={DesktopFile:tv,registerType:qe,unregisterType:a1,getType:c1,getTypes:nv,resolve:Pt,subscribe:l1,registerOpener:Fe,unregisterOpener:d1,getOpener:u1,getOpeners:iv,getOpenersForType:Ql,resolveOpener:ed,subscribeOpeners:rv,getUserAssociations:Jl,open:Ns,registerTilePayloadHandler:xs,rest:F1,store:{get:nt,getState:Bt,subscribe:fd,setFolderPlacements:Ut,upsertPlacement:cd,removePlacement:Ds,setFolders:ld,upsertFolder:dd,removeFolder:ud}},Tb="__synthFromDockItem";function o$(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function s$(e,t){const n=!!e.tile,o=t[e.id];return{id:o$(e.id),parentId:0,x:o?o.x:0,y:o?o.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Tb]: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 Od=!1;const Dd=new Map;function i$(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(!Od){Od=!0;try{const s=Ge.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[Tb]:null;typeof u=="string"&&r.set(u,d)}const a=new Set;for(const d of t)d.entry&&a.add(d.entry.id);const l=new Map;for(const d of s){const u=d?.file?.ref;typeof u=="string"&&a.has(u)&&l.set(u,d)}for(const d of e)d.entry||r.has(d.id)||Ge.store.upsertPlacement(s$(d,n));const c=[];for(const[d,u]of r)i.has(d)||(Ge.store.removePlacement(u.id),n[d]&&c.push(d));c.length>0&&i$(c);for(const d of t){const u=d.entry;if(!u)continue;const f=l.get(u.id);if(!i.has(d.id)){f&&(Dd.set(u.id,f),Ge.store.removePlacement(f.id));continue}if(!f){const p=Dd.get(u.id);p&&(Ge.store.upsertPlacement(p),Dd.delete(u.id))}}}finally{Od=!1}}}function a$(e){queueMicrotask(e);const t=Ge.store.subscribe(e),n="desktop-mode/shortcuts-sync";return ee(v.DOCK_ITEM_APPENDED,n,e),()=>{t(),jt(v.DOCK_ITEM_APPENDED,n)}}const Hr="os-note-created",c$="openstation_notes";function l$(e){if(!e.bundleUrl)return()=>{};let t=null;const n=[];let o=null;const s=()=>(t||(t=pe(e.bundleUrl).then(()=>{const a=window.openStationNotes;if(!a)return null;const l=a.boot({host:e.host,config:e.config,onError:e.onError});document.removeEventListener(Hr,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(ke.START,r);for(const c of n.splice(0))document.dispatchEvent(c);return l}).catch(a=>(t=null,console.warn("[openstation] notes bundle failed to load",a),null))),t),i=a=>{n.push(new CustomEvent(Hr,{detail:a.detail})),s()};document.addEventListener(Hr,i);const r=()=>{s()};return window.addEventListener("dragstart",r,!0),document.addEventListener(ke.START,r),pt("os.wallpaper-context-menu","desktop-mode/notes-sentinel",(a,l)=>{if(!Array.isArray(a)||a.some(u=>u.id==="new-note"))return a;const{x:c,y:d}=l??{x:0,y:0};return[...a,{id:"new-note",label:b("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{s().then(u=>{if(!u)return;const f=u.normalizedFromClient(c,d);u.createNoteAt({...f,focus:!0})})}}]}),e.hasNotes?(typeof requestIdleCallback=="function"?requestIdleCallback:l=>window.setTimeout(l,200))(()=>void s()):o=Re.subscribe(c$,a=>{a&&(o?.(),o=null,s())}),()=>{document.removeEventListener(Hr,i),window.removeEventListener("dragstart",r,!0),document.removeEventListener(ke.START,r),o?.(),o=null}}const d$={id:"clock",get label(){return b("Clock")},get description(){return b("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("os-widget-clock");const t=document.createElement("div");t.className="os-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="os-widget-clock__date",e.appendChild(n);const o=()=>{const a=new Date;t.textContent=a.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=a.toLocaleDateString(void 0,{weekday:"long",month:"short",day:"numeric"})};o();const s=1e3-Date.now()%1e3;let i=null;const r=window.setTimeout(()=>{o(),i=window.setInterval(o,1e3)},s);return()=>{window.clearTimeout(r),i!==null&&window.clearInterval(i)}}};function u$(){dl(d$)}async function f$(){const e=window;if(e.openStationReleaseCard)return e.openStationReleaseCard;const t=e.openStationConfig?.releaseCardBundleUrl??"";if(!t)return null;try{await pe(t)}catch{return null}return e.openStationReleaseCard??null}function Nb(e,t){if(t){const o=b('WordPress %1$s "%2$s" is available.');return le(o,e,t)}const n=b("WordPress %s is available.");return le(n,e)}async function p$(e){const{update:t,openUrl:n}=e;if(!t||typeof t.version!="string"||!t.version||typeof t.url!="string"||!t.url)return!1;const o=t.version,s=typeof t.branch=="string"&&t.branch?t.branch:o,i=t.crossing===!0,a=`desktop-mode/core-update:${typeof t.available=="string"&&t.available?t.available:o}`;if(tr(a))return!1;const l=`${a}:no-art`,c=()=>n({url:t.url,title:b("WordPress Updates")}),u=e.resolveArt&&e.loadImage&&e.showCard?null:await f$(),f=e.resolveArt??u?.resolveReleaseArt,p=e.loadImage??u?.preloadImage,g=e.showCard??u?.showReleaseCard,h=f?await f(s,i):null;return h&&h.artUrl&&p&&g&&await p(h.artUrl)?(g({message:Nb(o,i?h.name:""),artUrl:h.artUrl,dismissKey:a,onUpdate:c}),!0):tr(l)?!1:(ue({message:Nb(o,""),persistent:!0,dismissible:!0,onDismiss:()=>nr(l),action:{label:b("Update now"),onClick:c}}),!0)}function Ob(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(tr(i))continue;const r=s.actionLabel,a=s.actionUrl,l=s.title||r||"";let c;r&&a&&(c={label:r,onClick:()=>n({url:a,title:l})}),ue({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>nr(i),action:c})}}const Rd="desktop-mode/starter",h$="desktop-mode/dev-mode-gate";let Db=!1;function m$({osSettings:e,layer:t}){if(Db)return;Db=!0,pt(v.WIDGETS,h$,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==Rd));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(Rd):t.unmount(Rd),ms())})}function g$(e){const{layer:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await pe(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter,deps:c.scriptDeps})}catch(d){A(v.SHELL_ERROR,{scope:"widget-script-load",id:c.id,error:d});return}o.add(c.scriptUrl)}},i=c=>(window.openStationWidgets||{})[c]??null,r=c=>({id:c.id,label:c.label,description:c.description,icon:c.icon,movable:c.movable,resizable:c.resizable,minWidth:c.minWidth||void 0,minHeight:c.minHeight||void 0,maxWidth:c.maxWidth||void 0,maxHeight:c.maxHeight||void 0,defaultWidth:c.defaultWidth||void 0,defaultHeight:c.defaultHeight||void 0,mount:async(d,u)=>{await s(c);const f=i(c.id);if(!f){const p=new Error(`[openstation] No mount callback on window.openStationWidgets["${c.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`);throw A(v.SHELL_ERROR,{scope:"widget-missing-mount",id:c.id,error:p}),p}return f(d,u)}}),a=async c=>{if(n.has(c.id))return;const d=r(c);try{dl(d)}catch(u){A(v.SHELL_ERROR,{scope:"widget-register",id:c.id,error:u});return}n.add(c.id),ms(),t&&t.mountIfEnabled(c.id)},l=c=>{n.has(c)&&(t?.unmount(c),KN(c),n.delete(c),ms())};return async c=>{const d=new Set;for(const u of c)d.add(u.id);for(const u of Array.from(n))d.has(u)||l(u);for(const u of c)n.has(u.id)||await a(u)}}const Rb=new Set(Er),w$=2e3,xd=new Set,xb=new WeakSet;let Mb=!1;function y$(e,t){const n=e.length,o=t.length;if(n===0)return o;if(o===0)return n;const s=new Array(o+1);for(let i=0;i<=o;i++)s[i]=i;for(let i=1;i<=n;i++){let r=s[0];s[0]=i;for(let a=1;a<=o;a++){const l=s[a];s[a]=e[i-1]===t[a-1]?r:1+Math.min(r,s[a],s[a-1]),r=l}}return s[o]}function v$(e){let t=null,n=1/0;for(const o of Rb){const s=y$(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function b$(e){return e.startsWith("os-")?e.slice(4):e}function E$(e,t){if(xd.has(e))return;if(xd.add(e),Rb.has(e)){const s=b$(e);console.error(`[wp.os] <${e}> is in the DOM but its module was never imported, so the tag will not upgrade and the component will render as inert HTML. | |
| 40 | + | |
| 245 | 41 | Fix — side-effect-import the component module from wherever you render it: |
| 246 | 42 | |
| 247 | 43 | import '<rel>/ui/components/${s}/${s}'; |
| 248 | 44 | |
| @@ -250,15 +46,15 @@ | ||
| 250 | 46 | |
| 251 | 47 | import '<rel>/ui/components'; |
| 252 | 48 | |
| 253 | 49 | See docs/components-reference.md for the full list.`,` |
| 254 | -First offending element:`,t);return}const o=bO(e);if(o){console.error(`[wp.os] <${e}> is not a registered os-* component. Did you mean <${o}>? | |
| 50 | +First offending element:`,t);return}const o=v$(e);if(o){console.error(`[wp.os] <${e}> is not a registered os-* component. Did you mean <${o}>? | |
| 255 | 51 | |
| 256 | 52 | If the typo is in your template, update it. If you meant to ship a new component, register it via 'src/ui/components/<name>/<name>.ts' and add it to 'src/ui/components/tags.ts' + 'src/ui/components/index.ts'.`,` |
| 257 | 53 | First offending element:`,t);return}console.error(`[wp.os] <${e}> looks like a os-* tag but no component by that name exists. |
| 258 | 54 | |
| 259 | 55 | See 'src/ui/components/index.ts' (or docs/components-reference.md) for the canonical list. If you intended to register a new component, add it to 'tags.ts' and side-effect-import its module.`,` |
| 260 | -First offending element:`,t)}function Xy(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||Hc.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||_O(t,e)},wO)}function Zy(e){e instanceof Element&&(Xy(e),e.shadowRoot&&fr(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];Xy(o),o.shadowRoot&&fr(o.shadowRoot)}}function fr(e){if(Ky.has(e))return;Ky.add(e),Zy(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&&Zy(r)}}}).observe(e,{childList:!0,subtree:!0})}function EO(){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"&&fr(s),s};n.__wpdPatched=!0,e.attachShadow=n}function kO(){Yy||typeof document>"u"||(Yy=!0,EO(),fr(document))}const Jy={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}},te={radius:[16,220],bodyAlpha:[0,1],hueStart:[-720,720],hueSpan:[-360,360],hueDrift:[-180,180],hueAngle:[-360,360],hueSpin:[-180,180],saturation:[0,1],lightness:[.15,1],iridescence:[0,2],outlineWidth:[.5,24],glow:[0,20],eyeScale:[.05,.6],points:[12,128],shapeLobes:[0,8],shapeAmount:[0,1.4],shapeAngle:[-360,360],shapeShuffle:[0,3600],radialStiffness:[0,2e3],edgeStiffness:[0,4e3],bendStiffness:[0,2e3],pressure:[0,8e3],damping:[0,30],airDamping:[0,20],magnetStrength:[0,8e3],magnetRange:[0,2e3],magnetGrip:[0,.6],magnetDamping:[0,40],floatAmplitude:[0,200],floatSpeed:[0,20],idleWobble:[0,.4],idleWobbleSpeed:[0,8],speedStretch:[0,.8],friction:[0,1],restitution:[0,1],dragStiffness:[1,4e3],throwBoost:[0,4],minStretch:[.1,1],maxStretch:[1,4],minAngularGap:[0,.9],limitIterations:[0,8],dragMaxAccel:[100,2e5],subStep:[1/1e3,1/30],maxSubSteps:[1,32]};function ne(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function Qy(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 eb(e,t){return typeof e=="boolean"?e:t}const SO=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function AO(e,t){return SO.includes(e)?e:t}function rs(e,t=Jy){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:ne(o.radius,t.appearance.radius,te.radius),bodyColor:Qy(o.bodyColor,t.appearance.bodyColor),bodyAlpha:ne(o.bodyAlpha,t.appearance.bodyAlpha,te.bodyAlpha),hueStart:ne(o.hueStart,t.appearance.hueStart,te.hueStart),hueSpan:ne(o.hueSpan,t.appearance.hueSpan,te.hueSpan),hueDrift:ne(o.hueDrift,t.appearance.hueDrift,te.hueDrift),hueLoop:eb(o.hueLoop,t.appearance.hueLoop),hueAngle:ne(o.hueAngle,t.appearance.hueAngle,te.hueAngle),hueSpin:ne(o.hueSpin,t.appearance.hueSpin,te.hueSpin),saturation:ne(o.saturation,t.appearance.saturation,te.saturation),lightness:ne(o.lightness,t.appearance.lightness,te.lightness),iridescence:ne(o.iridescence,t.appearance.iridescence,te.iridescence),outlineWidth:ne(o.outlineWidth,t.appearance.outlineWidth,te.outlineWidth),glow:ne(o.glow,t.appearance.glow,te.glow),glowBlur:eb(o.glowBlur,t.appearance.glowBlur),eyeColor:Qy(o.eyeColor,t.appearance.eyeColor),eyeScale:ne(o.eyeScale,t.appearance.eyeScale,te.eyeScale)},r={points:Math.round(ne(s.points,t.physics.points,te.points)),shapePreset:AO(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(ne(s.shapeLobes,t.physics.shapeLobes,te.shapeLobes)),shapeAmount:ne(s.shapeAmount,t.physics.shapeAmount,te.shapeAmount),shapeAngle:ne(s.shapeAngle,t.physics.shapeAngle,te.shapeAngle),shapeShuffle:ne(s.shapeShuffle,t.physics.shapeShuffle,te.shapeShuffle),radialStiffness:ne(s.radialStiffness,t.physics.radialStiffness,te.radialStiffness),edgeStiffness:ne(s.edgeStiffness,t.physics.edgeStiffness,te.edgeStiffness),bendStiffness:ne(s.bendStiffness,t.physics.bendStiffness,te.bendStiffness),pressure:ne(s.pressure,t.physics.pressure,te.pressure),damping:ne(s.damping,t.physics.damping,te.damping),airDamping:ne(s.airDamping,t.physics.airDamping,te.airDamping),magnetStrength:ne(s.magnetStrength,t.physics.magnetStrength,te.magnetStrength),magnetRange:ne(s.magnetRange,t.physics.magnetRange,te.magnetRange),magnetGrip:ne(s.magnetGrip,t.physics.magnetGrip,te.magnetGrip),magnetDamping:ne(s.magnetDamping,t.physics.magnetDamping,te.magnetDamping),floatAmplitude:ne(s.floatAmplitude,t.physics.floatAmplitude,te.floatAmplitude),floatSpeed:ne(s.floatSpeed,t.physics.floatSpeed,te.floatSpeed),idleWobble:ne(s.idleWobble,t.physics.idleWobble,te.idleWobble),idleWobbleSpeed:ne(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,te.idleWobbleSpeed),speedStretch:ne(s.speedStretch,t.physics.speedStretch,te.speedStretch),friction:ne(s.friction,t.physics.friction,te.friction),restitution:ne(s.restitution,t.physics.restitution,te.restitution),dragStiffness:ne(s.dragStiffness,t.physics.dragStiffness,te.dragStiffness),throwBoost:ne(s.throwBoost,t.physics.throwBoost,te.throwBoost),minStretch:ne(s.minStretch,t.physics.minStretch,te.minStretch),maxStretch:ne(s.maxStretch,t.physics.maxStretch,te.maxStretch),minAngularGap:ne(s.minAngularGap,t.physics.minAngularGap,te.minAngularGap),dragMaxAccel:ne(s.dragMaxAccel,t.physics.dragMaxAccel,te.dragMaxAccel),limitIterations:Math.round(ne(s.limitIterations,t.physics.limitIterations,te.limitIterations)),subStep:ne(s.subStep,t.physics.subStep,te.subStep),maxSubSteps:Math.round(ne(s.maxSubSteps,t.physics.maxSubSteps,te.maxSubSteps))};return{appearance:i,physics:r}}const tb="desktop-mode-mio-position",nb="os-mio",CO="os-mio-toggle",IO=`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"> | |
| 56 | +First offending element:`,t)}function Wb(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||xd.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||E$(t,e)},w$)}function Pb(e){e instanceof Element&&(Wb(e),e.shadowRoot&&Gr(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];Wb(o),o.shadowRoot&&Gr(o.shadowRoot)}}function Gr(e){if(xb.has(e))return;xb.add(e),Pb(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&&Pb(r)}}}).observe(e,{childList:!0,subtree:!0})}function _$(){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"&&Gr(s),s};n.__wpdPatched=!0,e.attachShadow=n}function S$(){Mb||typeof document>"u"||(Mb=!0,_$(),Gr(document))}const $b=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"> | |
| 261 | 57 | <defs><linearGradient id="mio" x1="19" y1="19" x2="5" y2="5" gradientUnits="userSpaceOnUse"> |
| 262 | 58 | <stop offset="0" stop-color="#3f6dff"/><stop offset=".5" stop-color="#a855f7"/><stop offset="1" stop-color="#ff4fd8"/> |
| 263 | 59 | </linearGradient></defs> |
| 264 | 60 | <circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/> |
| @@ -263,86 +59,10 @@ | ||
| 263 | 59 | </linearGradient></defs> |
| 264 | 60 | <circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/> |
| 265 | 61 | <rect x="8" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 266 | 62 | <rect x="13.1" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 267 | -</svg>`)}`;class xO{constructor(t){this.layer=null,this.handle=null,this.parked=null,this.generation=0,this.loading=null,this.look=da(),this.options=t,this.enabled=t.enabled,this.look=Hf(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=rs(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=y0(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=rs({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=da(),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(v.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount())}resolveConfig(){const t=rs(this.options.serverConfig,Jy),n=q("os.mio.config",t),o=rs(n,t);return rs({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(nb);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=nb,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:LO(),savePosition:ob});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&&ob(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=ke(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function LO(){try{const e=window.localStorage.getItem(tb);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 ob(e){try{window.localStorage.setItem(tb,JSON.stringify(e))}catch{}}const sb=8,TO=e=>`<rect x="28" y="5" width="8" height="12" rx="2" fill="currentColor" transform="rotate(${360/sb*e} 32 32)"/>`,NO='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'+Array.from({length:sb},(e,t)=>TO(t)).join("")+'<circle cx="32" cy="32" r="15.5" fill="none" stroke="currentColor" stroke-width="9"/></svg>',DO=`data:image/svg+xml;base64,${btoa(NO)}`,RO='<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>',OO=2400,ib="os-notch";function MO(e,t){document.getElementById(ib)?.remove();const n=document.createElement("button");n.type="button",n.id=ib,n.className="os-notch",n.setAttribute("aria-label",E("Open the site assistant"));const o=document.createElement("span");o.className="os-notch__glyph",o.setAttribute("aria-hidden","true"),o.innerHTML=RO,n.appendChild(o);const s=document.createElement("span");s.className="os-notch__label",s.setAttribute("aria-hidden","true"),s.textContent=E("Site assistant"),n.appendChild(s);const i=document.createElement("span");i.className="os-notch__message",i.setAttribute("aria-live","polite"),n.appendChild(i),n.addEventListener("click",t);let r=null;const a=l=>{r!==null&&window.clearTimeout(r),i.textContent=l,n.classList.add("os-notch--speaking"),r=window.setTimeout(()=>{r=null,n.classList.remove("os-notch--speaking"),window.setTimeout(()=>{n.classList.contains("os-notch--speaking")||(i.textContent="")},200)},OO)};return e.appendChild(n),{say:a,destroy:()=>{r!==null&&window.clearTimeout(r),n.remove()}}}function PO(){return document.fullscreenElement!==null}function WO(){if(PO()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function rb(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 $O(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const c=document.createElement("h2");c.className="os-shortcuts__heading",c.textContent=e.heading,t.appendChild(c)}const n=document.createElement("div");n.className="os-shortcuts__scroller";const o=document.createElement("table");o.className="os-shortcuts__table";const s=e.headers??{},i=["key","outside","inside","showDesktop"],r=document.createElement("thead"),a=document.createElement("tr");for(const c of i){const d=document.createElement("th");d.scope="col",d.textContent=s[c]??"",a.appendChild(d)}r.appendChild(a),o.appendChild(r);const l=document.createElement("tbody");for(const c of e.rows??[]){const d=document.createElement("tr"),u=document.createElement("td");if(u.className="os-shortcuts__key-cell",u.appendChild(rb(c.keys??[])),c.note){const f=document.createElement("span");f.className="os-shortcuts__note",f.textContent=c.note,u.appendChild(f)}d.appendChild(u);for(const f of["outside","inside","showDesktop"]){const p=document.createElement("td");p.textContent=c[f]??"",d.appendChild(p)}l.appendChild(d)}return o.appendChild(l),n.appendChild(o),t.appendChild(n),t}function UO(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(rb(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 FO(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($O(n.contextual)),n.general&&t.appendChild(UO(n.general)),e.appendChild(t)}const zc="openstation-shortcuts",BO=`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 HO(e){e({id:zc,baseId:zc,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:BO,native:!0,render:FO,width:760,height:560,minWidth:480,minHeight:360})}const ab="openstation-rebrand",zO=1200,GO="a[href], button:not([disabled])";async function jO(e){const t=e.seenIntrosUrl;if(t)try{await Fe(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:ab})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function VO(){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(E("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=E("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=E("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",t.appendChild(a);const l=document.createElement("p");l.id="os-announce-desc",l.textContent=E("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),a.appendChild(l);const c=document.createElement("p");c.textContent=E("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=E("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=E("Got it"),u.appendChild(f),e}async function qO(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(ab))return;await new Promise(c=>window.setTimeout(c,zO));const n=VO(),o=n.querySelector(".os-announce__card"),i=document.activeElement;let r=!1;const a=()=>{r||(r=!0,document.removeEventListener("keydown",l,!0),n.remove(),i?.focus?.(),jO(t))};function l(c){if(!n.isConnected){document.removeEventListener("keydown",l,!0);return}if(c.key==="Escape"){c.preventDefault(),a();return}if(c.key!=="Tab")return;const d=Array.from(n.querySelectorAll(GO));if(d.length===0)return;const u=d[0],f=d[d.length-1],p=n.ownerDocument.activeElement;c.shiftKey&&(p===u||!n.contains(p))?(c.preventDefault(),f.focus()):!c.shiftKey&&(p===f||!n.contains(p))&&(c.preventDefault(),u.focus())}n.addEventListener("click",c=>{o&&!o.contains(c.target)&&a()});for(const c of n.querySelectorAll("[data-rebrand-dismiss]"))c.addEventListener("click",a);document.addEventListener("keydown",l,!0),document.body.appendChild(n),n.querySelector(".os-announce__btn--primary")?.focus()}const KO=new Set(["post"]);function lb(){const e=window.wp?.os?.myWordpress;return e&&typeof e.trashEntity=="function"?e:null}const Gc="data-os-trash-drop-active",Qt="desktop-mode-recycle-bin",YO=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${Qt}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${Qt}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${Qt}"]`}];let cb=!1;const jc=new Map;let as=null,db=null;function XO(e){return e.payload.type==="desktop-file"}function ZO(e){return e.payload.type==="shortcut"}function JO(e){if(!e.kind||!e.ref||!e.entityId||!KO.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return!Number.isFinite(t)||t<=0?!1:lb()!==null}function ub(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:E("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=Hn(s);return r.length>1?r.every(a=>a.file?.ref!==Qt&&a.canTrash!==!1):i.file?.ref===Qt?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=Ji(s);return i.length>0&&i.every(r=>JO(r))}return YR(o)},onEnter:()=>{n.setAttribute(Gc,"")},onLeave:()=>{n.removeAttribute(Gc)},onDrop:(o,s)=>{if(n.removeAttribute(Gc),XO(o)){Pw(Hn(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&XR(o,s))&&ZO(o)){const i=lb();if(!i?.trashEntity)return;const r=i.trashEntity,l=Ji(o.payload.data).map(c=>({entityId:c.entityId,ref:Number.parseInt(c.ref,10)})).filter(c=>!!c.entityId&&Number.isFinite(c.ref)&&c.ref>0);if(l.length===0)return;Promise.allSettled(l.map(c=>r(c.entityId,c.ref))).then(c=>{const d=c.filter(f=>f.status==="rejected");for(const f of d)console.error("[openstation] recycle-bin: shortcut trash failed:",f.reason);const u=l.length-d.length;(u>1||d.length>0)&&Q({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 QO(e){if(cb)return;cb=!0;const t=()=>{for(const{id:n,selector:o}of YO){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=jc.get(n);if(!i){r?.deregister(),jc.delete(n);continue}r&&r.el===i||(r?.deregister(),jc.set(n,{el:i,deregister:ub(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),Y(v.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),Y(v.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){db=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;db.observe(n,{childList:!0,subtree:!0})}Y(v.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==Qt)return;as?.(),as=null;const o=document.querySelector("[data-os-recycle-bin-root]");o instanceof HTMLElement&&(as=ub(e,"recycle-bin-window",o))}),Y(v.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===Qt&&(as?.(),as=null)})}function Vc(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function eM(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function fb(e){return{appliesTo(t){return Vc(t)!==null},accept(t,n){const o=Vc(n);if(!o)return!1;const s=dw({type:e,data:t});return BT(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:E("Send to agent","desktop-mode"),onDrop(t,n,o){const s=Vc(o);if(!s)return;const i=dw({type:t.payload.type,data:t.payload.data}),r=eM();!i||!r||jT({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let pb=!1;function tM(){pb||(pb=!0,Ki("shortcut",fb("shortcut")),Ki("desktop-file",fb("desktop-file")))}let hb=!1,en=0;function nM(){hb||(hb=!0,Le.contribute("openstation_files_subscribe",()=>{const e=xt(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:en,sharesVersion:Qe().state.sharesVersion}}),Le.subscribe("openstation_files",e=>{oM(e)}))}function oM(e){const t=e.folders??[];for(const i of t)ic(i,"remote"),i.updatedAtMs>en&&(en=i.updatedAtMs);const n=e.placements??[];for(const i of n)Vi(i,"remote"),i.updatedAtMs>en&&(en=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])rc(i,"remote");for(const i of o.placements??[])jo(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>en&&(en=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&py(s),e.truncated){const i=Array.from(xt().hydratedFolders);for(const r of i)Te(r).then(a=>{ht(r,a.placements)}).catch(()=>{})}}let mb=!1;const sM=[];function iM(){if(mb)return;mb=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||rM()};sM.push(En("os.placement.changed",e),En("os.shortcut.changed",e),En("os.folder.changed",e))}function rM(){nc().then(t=>{qi(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from(xt().hydratedFolders);for(const t of e)Te(t).then(n=>{ht(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const ls="os-wallpaper-menu";let Kn=null;function gb(){return Kn!==null}let wb=0;function aM(e,t,n,o={}){cs();const s=++wb;Ps(()=>s===wb,()=>lM(e,t,n,o))}function lM(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,g=typeof f.sort=="number"?f.sort:100;return p!==g?p-g:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(ls),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const l=()=>{r&&(r.remove(),r=null,a=null)};for(const u of n){i.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.heading&&f.setAttribute("heading",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",yb(u.icon));const p=Array.isArray(u.children)&&u.children.length>0;p&&f.setAttribute("has-children",""),f.textContent=u.label,f.addEventListener("mouseenter",()=>{if(p){c(u,f);return}l()}),s.appendChild(f)}s.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=i.get(f.id)??null;if(p){if(Array.isArray(p.children)&&p.children.length>0){if(u.stopPropagation(),a&&a.id===p.id){l();return}const g=s.querySelector(`[data-menu-item-id="${p.id}"]`);g&&c(p,g);return}cs(),p.onClick(new MouseEvent("click"))}});function c(u,f){l();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(ls,`${ls}--flyout`),p.dataset.parentId=u.id;const g=(u.children??[]).slice().sort((m,h)=>{const b=typeof m.sort=="number"?m.sort:100,y=typeof h.sort=="number"?h.sort:100;return b!==y?b-y:m.label.localeCompare(h.label)});for(const m of g){const h=document.createElement("os-context-menu-option");h.dataset.menuItemId=m.id,h.setAttribute("value",m.id),m.icon&&h.setAttribute("icon",yb(m.icon)),m.disabled&&h.setAttribute("disabled",""),m.checked&&h.setAttribute("checked",""),h.textContent=m.label,h.addEventListener("os-context-menu-pick",b=>{b.stopPropagation(),cs(),m.onClick(new MouseEvent("click"))}),p.appendChild(h)}document.body.appendChild(p),r=p,a=u,Rg(p,f)}e.appendChild(s),Kn=s,Ll(s);const d=Ng(s,{close:()=>cs(),siblingSelectors:[`.${ls}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),T("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function cs(){Kn&&(document.querySelectorAll(`.${ls}--flyout`).forEach(e=>e.remove()),Kn.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),Kn.remove(),Kn=null,T("os.wallpaper-menu.closed",{}))}function cM(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=>dM(i,e)),o=[...t,...n],s=q("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function dM(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 yb(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const ds="os-url-dialog";let us=null;function qc(){us&&(us.dispatchEvent(new CustomEvent("url-dialog-closed")),us.remove(),us=null,T("os.files.url-dialog.closed",{}))}function uM(e){if(qc(),q("os.files.url-dialog",null,e)===!1)return;const n=document.createElement("div");n.className=`${ds}__overlay os-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${ds} os-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${ds}-title`);const s=document.createElement("h2");if(s.id=`${ds}-title`,s.className="os-create-folder-dialog__title",s.textContent=e.title,o.appendChild(s),e.description){const h=document.createElement("p");h.className=`${ds}__description`,h.textContent=e.description,o.appendChild(h)}const i=document.createElement("os-text-field");i.className="os-create-folder-dialog__field",i.setAttribute("label",e.nameLabel??"Name"),i.setAttribute("value",e.initialName??""),i.setAttribute("placeholder","My web app"),i.setAttribute("autocomplete","off"),o.appendChild(i);const r=document.createElement("os-text-field");r.className="os-create-folder-dialog__field",r.setAttribute("label",e.urlLabel??"URL"),r.setAttribute("value",e.initialUrl??"https://"),r.setAttribute("placeholder","https://example.com"),r.setAttribute("type","url"),r.setAttribute("autocomplete","off"),o.appendChild(r);const a=document.createElement("p");a.className="os-create-folder-dialog__error",a.hidden=!0,a.setAttribute("role","alert"),o.appendChild(a);const l=document.createElement("div");l.className="os-create-folder-dialog__actions";const c=document.createElement("os-button");c.className="os-create-folder-dialog__btn os-create-folder-dialog__btn--secondary",c.setAttribute("variant","ghost"),c.textContent="Cancel";const d=document.createElement("os-button");d.className="os-create-folder-dialog__btn os-create-folder-dialog__btn--primary",d.setAttribute("variant","primary"),d.textContent=e.submitLabel??"Create",l.appendChild(c),l.appendChild(d),o.appendChild(l),n.appendChild(o),document.body.appendChild(n),us=n,Yi(i),T("os.files.url-dialog.opened",{});const u=h=>{Kt(i,h),Kt(r,h),Kt(c,h),Kt(d,h),o.classList.toggle("os-create-folder-dialog--busy",h)},f=h=>{a.textContent=h,a.hidden=!1},p=()=>{qc(),e.onCancel?.()},g=async()=>{const h=uc(r).trim();if(!h){f("Please enter a URL.");return}const b=/^[a-z][a-z0-9+\-.]*:/i.test(h)?h:`https://${h}`;try{new URL(b)}catch{f("That doesn't look like a valid URL.");return}const y=uc(i).trim();a.hidden=!0,u(!0);try{await e.onSubmit({name:y,url:b}),qc()}catch(I){u(!1),f(I instanceof Error?I.message:"Could not save.")}};c.addEventListener("click",()=>p()),d.addEventListener("click",()=>void g()),n.addEventListener("click",h=>{h.target===n&&p()});const m=h=>{h.key==="Escape"?(h.preventDefault(),p()):h.key==="Enter"&&!h.isComposing&&(h.preventDefault(),g())};o.addEventListener("keydown",m),n.addEventListener("url-dialog-closed",()=>{o.removeEventListener("keydown",m)})}const bb=[];let Kc=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(Kc){Promise.resolve().then(o);return}bb.push(o)}},ready(o){n.whenReady(o)},isReady(){return Kc}};t.wp.os=n})();const pr="desktop-mode-os-settings";let Yc=[],hr=Number.POSITIVE_INFINITY,Xc=!1;function Ke(e,t=1500){if(Yc.push(e),t<hr&&(hr=t),Xc)return;Xc=!0;const n=()=>{const o=Yc;Yc=[],hr=Number.POSITIVE_INFINITY,Xc=!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:hr}):window.setTimeout(n,0)}function vb(){const e=window.openStationConfig;if(!e)return;const t=document.getElementById("os-area");if(!t)return;const n=new WE(t),o=document.getElementById("os-wallpaper"),s=e.pluginUrl||"";let i=null;o&&(i=new Cp(o,s));const r=document.getElementById("os-widgets");let a=null;uO(),uk(),r&&(a=new uI(r,s)),mp({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const l=new Uk({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 Cp(document.createElement("div"),s));l.apply();const c=document.getElementById("os-shell"),d=new xO({shell:c??document.body,bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:l.state.mioEnabled,persist:S=>{l.state.mioEnabled=S,l.save()},savedLook:l.state.mioStyle,persistLook:S=>{l.state.mioStyle=S,l.save()}}),u=d.api();d.boot(),a&&mO({osSettings:l,layer:a});const f=new BI({aiSearchUrl:e.aiSearchUrl??"",restNonce:e.restNonce,adminUrl:e.adminUrl,isAiAvailable:()=>e.aiAssistant?.available===!0&&e.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>l.getOsSettingsSnapshot().ai.enabled!==!1},e.aiAssistantBundleUrl??"");f.attachAsk(VI({config:()=>e,fallbackContext:()=>({close:()=>f.close(),openInWindow:(S,z,K)=>{n.open({url:S,title:z,icon:K??"dashicons-admin-generic"})},confirm:S=>Pn({message:S})})}));const p=new Wx,g=new Qx;document.addEventListener(be.START,S=>{const K=S.detail?.payload;if(!K||K.type!=="shortcut"&&K.type!=="desktop-file")return;const oe=K.data?.bridgePayload;oe&&p.start(oe)}),document.addEventListener(be.END,()=>{p.end()}),Ke(()=>fL(g)),Ke(()=>CL(n)),window.addEventListener("message",S=>{if(S.origin!==window.location.origin)return;const z=S.data;!z||z.type!=="os-drop-failed"||Q({message:"Could not insert into the editor."})}),vg({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>f.open(),close:()=>f.close(),isOpen:()=>f.isOpen}),DL(),UE(n),GE(n),Ke(()=>{new CC({manager:n,adminUrl:e.adminUrl}).install(),IC(n),new MC({manager:n,adminUrl:e.adminUrl}).install()}),document.addEventListener("os-open-ai",()=>{Sl("desktop-mode-ai-assistant")}),document.addEventListener("click",S=>{const z=S.target;!(z instanceof Element)||!z.closest("#wp-admin-bar-command-palette")||(S.preventDefault(),S.stopImmediatePropagation(),Sl("desktop-mode-ai-assistant"))},!0);const m=document.getElementById("os-dock"),h=document.getElementById("os-shell"),b=h?.querySelector(".os-shell__body");let y=null,I=!1;const R=S=>S.some(z=>!!z.windowId&&n.getAllByBaseIdOnActiveDesktop(z.windowId).length>0),k=SI({manager:n,appendSystemTile:S=>y?.appendSystemTile(S),removeSystemTile:S=>y?.removeSystemTile(S)}),M=k.sync;YE({getSnapshot:()=>l.getOsSettingsSnapshot(),openById:(S,z)=>k.openById(S,z),adminUrl:e.adminUrl});const P=S=>{const z=ce(S,e.adminUrl),K=y?y.getMenuItems():e.dockItems??[];for(const oe of K){if(ce(oe.url,e.adminUrl)===z)return{title:oe.title,icon:oe.icon,url:oe.url,submenu:oe.submenu,selfLabel:oe.selfLabel,multi:oe.multi};for(const ye of oe.submenu??[])if(ce(ye.url,e.adminUrl)===z)return{title:ye.title,icon:oe.icon,url:oe.url,multi:oe.multi}}return null};if(f0({adminUrl:e.adminUrl,deriveSlug:S=>ce(S,e.adminUrl),openWindow:S=>{n.open(S)},findDockEntry:P}),kt({id:"desktop-mode-dashboard",nativeWindowId:"desktop-mode-dashboard",matches:(S,z)=>JE(z)}),kt({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(S,z)=>{if(!z.pathname.endsWith("/edit.php"))return!1;const K=z.searchParams.get("post_type");return!K||K==="post"},enabled:S=>S.nativePostsEnabled===!0}),kt({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(S,z)=>z.pathname.endsWith("/edit.php")?z.searchParams.get("post_type")==="page":!1,enabled:S=>S.nativePagesEnabled===!0}),kt({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(S,z)=>z.pathname.endsWith("/users.php"),enabled:S=>S.nativeUsersEnabled===!0}),kt({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(S,z)=>{if(KE(z))return!1;const K=z.pathname;return K.endsWith("/profile.php")?!0:K.endsWith("/user-edit.php")?z.searchParams.has("user_id"):!1},enabled:S=>S.nativeUsersEnabled===!0,onMatch:(S,z)=>{const K=parseInt(z.searchParams.get("user_id")??"0",10);K>0&&Hk(K)}}),kt({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(S,z)=>z.pathname.endsWith("/edit-comments.php"),enabled:S=>S.nativeCommentsEnabled===!0,onMatch:(S,z)=>{const K=parseInt(z.searchParams.get("p")??"0",10);K>0?Sp(K):Gk()}}),kt({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(S,z)=>{const K=z.pathname;return K.endsWith("/plugins.php")||K.endsWith("/plugin-install.php")},enabled:S=>S.nativePluginsEnabled===!0,onMatch:(S,z)=>{const K=z.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>FM).then(oe=>{oe.setPluginsWindowTab(K)})}}),m&&h&&b&&e.dockItems){t.classList.add("os-area--with-dock");const S=l.getOsSettingsSnapshot(),z=S.desktopLayout,K=S.dockPlacement,oe=ve=>{xm(t,ve,{openWindow:k.openById,manager:n,deriveWindowId:Ie=>ce(Ie,e.adminUrl)})};y=UI({shellRoot:h,shellBody:b,bottomDockEl:m,desktopArea:t,windowManager:n,adminUrl:e.adminUrl,renderIcons:oe,getSettings:()=>{const ve=l.getOsSettingsSnapshot();return{navPlacement:ve.navPlacement,navOrder:ve.navOrder}}},z,e.dockItems,e.desktopIcons,K),PA({windowManager:n,adminUrl:e.adminUrl,getMenuItems:()=>y?.getMenuItems()??[],getSystemItem:ve=>y?.getSystemTile(ve)??null}),MO(h,()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))});const ye=xx(e.pwa?.appName||"WordPress",Q),wt={id:S_,title:"System",icon:C_,navKind:"control",placeable:!0,order:Vs.system,onOpen:W,get submenu(){const ve=[{title:"OpenStation Preferences",url:"",windowId:pr,onSelect:()=>W()}];return e.homeUrl&&ve.push({title:"View site",url:e.homeUrl}),ve.push({title:"Fullscreen",url:"",onSelect:WO},{title:"Keyboard shortcuts",url:"",windowId:zc,onSelect:()=>HO(Ie=>{n.open(Ie)})},{title:"Report a bug",url:"",windowId:Ro,onSelect:()=>_()}),!zm()&&!I&&ve.push({title:ye.title,url:"",onSelect:ye.onOpen}),e.logoutUrl&&ve.push({title:"Log out",url:"",onSelect:()=>{window.location.assign(e.logoutUrl)}}),ve},isOpen:()=>R(wt.submenu??[])};y.appendSystemTile(wt),Gm().then(ve=>{I=ve})}function W(S={}){const z={extended:"features",effects:"windows"},K=S.tabId?z[S.tabId]:void 0;K&&(S={...S,tabId:K}),S.tabId&&(l.activeTabId=S.tabId),n.open({id:pr,baseId:pr,url:"#os-settings",title:"OpenStation Preferences",icon:DO,native:!0,render:oe=>l.renderPanel(oe),width:820,height:720,minWidth:560,minHeight:480}),S.tabId&&l.focusTab(S.tabId)}function _(){n.open({id:Ro,baseId:Ro,url:`#${Ro}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:S=>ux(S),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("os-open-bug-report",()=>{_()}),y&&(y.appendSystemTile(x_()),y.appendSystemTile({id:CO,title:"Mio",icon:IO,navKind:"control",placeable:!0,order:Vs.mio,isOpen:()=>u.isEnabled(),onOpen:()=>{u.toggle()}}),y.appendSystemTile({id:k_,title:"Overview",icon:A_,navKind:"control",placeable:!0,order:Vs.overview,isOpen:()=>n._overviewActive,onOpen:()=>{n._overviewActive?n.exitOverview():n.enterOverview()}}));const w=y?.getPrimary()??null;M(Array.isArray(e.nativeWindows)?e.nativeWindows:[]);const L=N1(e.session);function A(S){return S===pr?(W(),!0):S===Ro?(_(),!0):k.openById(S)}const C=typeof e.soloWindow=="string"?e.soloWindow:"";C&&queueMicrotask(()=>{if(A(C))return;const S=C.startsWith("os-game-")?C.slice(8):"";if(S){Op.launch(S).catch(z=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",z)});return}typeof console<"u"&&console.error(`[openstation] solo window "${C}" is not registered; nothing to paint.`)});const $=L&&!C?R1(n,e,t,A).catch(S=>{typeof console<"u"&&console.error("[openstation] session restore failed:",S)}):Promise.resolve(),X=e.defaultWindow?.enabled!==!1,Z=e.defaultWindow?.url??"",x=typeof Z=="string"&&Z.startsWith("native:");!C&&M1({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:L,defaultEnabled:X,isNativeDefault:x})&&$.then(()=>O1(n,e).catch(S=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",S)}));const F=U1(n,e);B1(F);const N=async S=>{try{const z=await Bl(n,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:S})},{source:"desktop-mode/default-window"});if(!z.ok)throw new Error(`HTTP ${z.status}`);const K=await z.json();e.defaultWindow=K,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:K}))}catch(z){T(v.SHELL_ERROR,{scope:"default-window-save",error:z}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",z)}};if(n.onToggleStartupRequested=S=>{const z=e.defaultWindow,K=!!S.config.native,oe=K?`native:${S.id}`:S.getCurrentUrl(),ye=K?z?.url===oe:md(z?.url??"")===md(oe),wt=!!z?.enabled&&ye;N(wt?null:oe)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!L&&x){const S=Z.slice(7);queueMicrotask(()=>{A(S)})}const U=S=>{y?.appendSystemTile(S)},B=gO({layer:a});B(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const H=pS({osSettings:l});H(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),Y(v.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",S=>{const z=S?.wallpapers;Array.isArray(z)&&H(z)});const O=mS();O(Array.isArray(e.serverGames)?e.serverGames:[]);const V=gS();V(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const D=TS();D(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const j=RS();j(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const G=$S();G(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const ae=GS();ae(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const fe=EA();fe(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const pe=kA();pe(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),AA({manager:n,osSettings:l}),j_({osSettings:l}),d0({manager:n}),nA({manager:n,osSettings:l}),rA({manager:n,openUrl:S=>{if(S.windowId&&k.openById(S.windowId,{source:"related-entities",...S.params?{params:S.params}:{}})||!S.url||Ge(S.url))return;const z=ce(S.url,e.adminUrl);n.open({id:z,baseId:z,url:S.url,title:S.label,icon:S.icon||"dashicons-admin-links"})}}),yA({manager:n});const re=CA();re(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),ZA()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),eC(),tC()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),sC()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),Zh(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),gC()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const Ts=vC(n);aA(n),Ke(()=>lA()),jE(),Y("os.shell.toast","desktop-mode/shell-toast",S=>{!S||typeof S.message!="string"||Q({message:S.message,action:S.action,duration:S.duration})});const rd=e,QM=rd.recycleBinCount;XI(Number(QM)||0,typeof rd.recycleBinCountUrl=="string"?rd.recycleBinCountUrl:""),ix({getRecycleBinCount:YI}),window.__openStationConnectionBridge=Ts,Y(v.WINDOW_CLOSED,"desktop-mode/connection-cleanup",S=>{S?.windowId&&Ts.onWindowClosed(S.windowId)}),Y(v.IFRAME_READY,"desktop-mode/connection-rearm",S=>{S?.windowId&&Ts.onIframeReady(S.windowId)});const eP=bI(n),tP=S=>{if(y){y.applyDesktopIcons(S);return}xm(t,S,{openWindow:k.openById,manager:n,deriveWindowId:z=>ce(z,e.adminUrl)})},ad=()=>{y&&XD(y.getNav().desktop,y.getNavItems(),l.getOsSettingsSnapshot().dockPromotedPositions)},nP=T1({layoutDispatcher:y,desktopArea:t,config:e,syncNativeWindows:M,syncServerWidgets:B,syncServerWallpapers:H,syncServerCommands:D,syncServerSettingsTabs:j,syncServerTitleBarButtons:G,syncServerWindowActions:ae,syncServerUnfocusEffects:fe,syncServerWindowLinkRenderers:pe,syncServerDockRailRenderers:re,syncServerGames:O,syncServerDesktopThemes:V,renderIcons:tP,syncShortcuts:ad});document.addEventListener(sp,()=>{y&&y.setLayout(y.getLayout());for(const S of n._stack)try{S.repaintWindowControls(),S.repaintThemedChrome()}catch(z){T(v.SHELL_ERROR,{scope:"desktop-theme-repaint",id:S.id,error:z})}}),l.subscribeOsSettings(S=>{if(!y)return;const z=y.getLayout(),K=y.getDockPlacement();y.setDockPlacement(S.dockPlacement),y.setLayout(S.desktopLayout),Ns.dock=y.getPrimary(),Ns.sideDock=y.getSide(),Ns.desktopLayout=S.desktopLayout,Ns.dockPlacement=y.getDockPlacement(),z===S.desktopLayout&&K===S.dockPlacement&&y.refresh(),ad(),Qg(S.desktopLayout)}),ZD(ad),Qg(l.getOsSettingsSnapshot().desktopLayout);const Ns=IT({manager:n,dock:w,layoutDispatcher:y,osSettings:l,iconsApi:RI,filesApi:ze,saveSession:F,widgetLayer:a,registerWindow:eP,openWindowById:k.openById,openNewWindowById:k.openNewById,loadWindowScriptById:k.loadScriptById,placeSystemTile:U,setDefaultWindow:N,refreshMenu:nP,openOsSettings:W,aiAssistant:f,dragBridge:p,dragManager:g,connect:Ts.connect,getConnection:Ts.getConnection,mio:u,wallpaperSuspend:{suspend:S=>i?.suspend(S),resume:S=>i?.resume(S),isSuspended:()=>i?.isSuspended()??!1},config:e});xT(Ns),Ke(()=>QO(g)),Ke(()=>tM()),wS(),U_(),e.gamesEnabled!==!1&&CS({currentUserId:Number(e.currentUserId)||0}),Ke(()=>i1()),Ke(()=>a1()),Ke(()=>v1({currentUserId:Number(e.currentUserId)||0})),cO({host:t,config:e,onError:S=>{Q({message:S})}}),PT({openUrl:({id:S,url:z,title:K,icon:oe})=>(Ge(z)||n.open({id:S,baseId:S,url:z,title:K,icon:oe}),!0),openNativeWindow:S=>k.openById(S),deriveWindowId:S=>ce(S,e.adminUrl)}),ow(e.userFileAssociations??{}),pO({update:e.coreUpdate,openUrl:({url:S,title:z})=>{Ge(S)||n.open({id:"update-core",baseId:"update-core",url:S,title:z,icon:"dashicons-update"})}});const Rb=({url:S,title:z})=>{if(Ge(S))return;const K=ce(S,e.adminUrl);n.open({id:K,baseId:K,url:S,title:z,icon:"dashicons-info"})};if(jy({notices:e.coreNotices,openUrl:Rb}),jy({notices:e.pluginNotices,openUrl:Rb,keyPrefix:"plugin-notice"}),qO({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){fw({baseUrl:e.filesUrl,nonce:e.restNonce});const S=document.getElementById("os-area");if(S){const z=Xw(S,0),K=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},oe=setTimeout(K,2e3);z.hydrated.then(()=>{clearTimeout(oe),K()})}}Ke(()=>nM()),Ke(()=>iM()),Ke(()=>ML()),T(v.COMPONENTS_REGISTERED,{tags:[...Hi]}),xL(),Dx(e,Q);const Ob=()=>{Xb(e.shellOverlaysBundleUrl??""),Kb(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(Ob,{timeout:1500}):window.setTimeout(Ob,0),T(v.INIT,{config:e}),Kc=!0;const oP=bb.splice(0);for(const S of oP)try{S()}catch(z){T(v.SHELL_ERROR,{scope:"when-ready-cb",error:z}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",z)}l.apply(),a?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),a?.disposeAll()}),H1(),_1(n,e);const Mb=(S,z=!0)=>{const K=ze.store.getState().placementsByFolder.get(0)??[],oe=S(K),ye=Math.max(1,Math.floor((t.clientHeight-16)/110)),wt=new Set;let ve=0;for(const Ie of oe){const Re=Tt(16+Math.floor(ve/ye)*96,16+ve%ye*110,wt,t);wt.add(`${Re.col},${Re.row}`),ve++,!(Ie.x===Re.x&&Ie.y===Re.y)&&(ze.store.upsertPlacement({...Ie,x:Re.x,y:Re.y,sortOrder:ve}),!(!z||Qi(Ie))&&Wn(Ie.id,{x:Re.x,y:Re.y,sortOrder:ve}).catch(yt=>{console.error("[openstation] relayout persist failed",yt)}))}},Pb=S=>z=>{const K=z.slice();switch(S){case"name-asc":K.sort((oe,ye)=>oe.file.title.localeCompare(ye.file.title));break;case"name-desc":K.sort((oe,ye)=>ye.file.title.localeCompare(oe.file.title));break;case"date-asc":K.sort((oe,ye)=>oe.updatedAtMs-ye.updatedAtMs);break;case"date-desc":K.sort((oe,ye)=>ye.updatedAtMs-oe.updatedAtMs);break}return K},ld="desktop-mode:root-sort-mode",sP=S=>S==="name-asc"||S==="name-desc"||S==="date-asc"||S==="date-desc";let vr=(()=>{try{const S=window.localStorage.getItem(ld);return sP(S)?S:null}catch{return null}})();const Wb=S=>{vr=S;try{S?window.localStorage.setItem(ld,S):window.localStorage.removeItem(ld)}catch{}};if(Y("os.files.tile-manually-placed","desktop-mode/root-sort-clear",S=>{S?.folderId===0&&Wb(null)}),typeof ResizeObserver<"u"){let S=t.clientWidth,z=t.clientHeight;new ResizeObserver(()=>{if(!vr)return;const oe=t.clientWidth,ye=t.clientHeight;oe===S&&ye===z||(S=oe,z=ye,Mb(Pb(vr),!1))}).observe(t)}let $b=!1;t.addEventListener("pointerdown",S=>{S.isPrimary&&($b=S.target===t)}),t.addEventListener("click",S=>{l.state.showDesktopOnWallpaperClick&&S.target===t&&$b&&(t.classList.contains("os-area--overview")||gb()||g.recentlyEndedDrag()||ZL()||n.toggleShowDesktop())}),t.addEventListener("contextmenu",S=>{if(S.target!==t)return;S.preventDefault();const z=S.clientX,K=S.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(gb()){cs();return}const oe={x:z,y:K},ye=()=>{const Ie=t.getBoundingClientRect(),Re=Math.max(0,oe.x-Ie.left),yt=Math.max(0,oe.y-Ie.top),Ds=Uw(ze.store.getState().placementsByFolder.get(0)??[]);return Tt(Re,yt,Ds,t)},wt=(Ie,Re)=>{uM({title:Ie,description:Re,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:yt,url:Ds})=>{const Ub=ye(),iP=await Go({type:"link",ref:Ds,parentId:0,x:Ub.x,y:Ub.y,meta:yt?{name:yt}:void 0});ze.store.upsertPlacement(iP)}})},ve=cM({createFolder:()=>{pc({onSubmit:async Ie=>{const Re=await oc({name:Ie}),yt=ye(),Ds=await Go({type:"folder",ref:String(Re.id),parentId:0,x:yt.x,y:yt.y});ze.store.upsertFolder(Re),ze.store.upsertPlacement(Ds)}})},createUrl:()=>wt("New URL","Opens the URL in a new browser tab."),addWidget:()=>a?.openPicker(),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>W(),sortIcons:Ie=>{Wb(Ie),Mb(Pb(Ie))},currentSortMode:vr,includeShowDesktop:!l.state.showDesktopOnWallpaperClick,position:{x:z,y:K},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??[]});aM(document.body,{x:z,y:K},ve)})()}),Promise.resolve().then(()=>JM).then(S=>{S.bootOsFileDrop({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:L}}))}kO(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",vb):vb();const he={FILES_DETECTED:"os.drop.files-detected",FILES_REJECTED:"os.drop.files-rejected",DIALOG_FIELDS:"os.drop.dialog-fields",BEFORE_UPLOAD:"os.drop.before-upload",UPLOAD_STARTED:"os.drop.upload-started",UPLOAD_PROGRESS:"os.drop.upload-progress",AFTER_UPLOAD:"os.drop.after-upload",UPLOAD_FAILED:"os.drop.upload-failed"},fM=32;function pM(e){if(!e)return[];const t=[];for(let n=0;n<e.length;n++){const o=e[n];if(o.kind!=="file")continue;const s=typeof o.webkitGetAsEntry=="function"?o.webkitGetAsEntry():null;s&&t.push(s)}return t}function hM(e){const t=e.createReader();return new Promise((n,o)=>{const s=[],i=()=>{t.readEntries(r=>{if(r.length===0){n(s);return}s.push(...r),i()},o)};i()})}function mM(e){return new Promise((t,n)=>{e.file(t,n)})}async function gM(e){const t={files:[],emptyDirs:[],hadDirectory:!1};for(const n of e)await _b(n,"",t,0);return t}async function _b(e,t,n,o){if(o>fM)return;if(e.isFile){try{const r=await mM(e);n.files.push({file:r,relativePath:t?`${t}${r.name}`:""})}catch{}return}if(!e.isDirectory)return;n.hadDirectory=!0;const s=`${t}${e.name}`;let i=[];try{i=await hM(e)}catch{i=[]}if(i.length===0){n.emptyDirs.push(s);return}for(const r of i)await _b(r,`${s}/`,n,o+1)}const Eb=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function fs(e){const t=e.dataTransfer?.types;if(!t)return!1;const n=t;if(typeof n.includes=="function")return n.includes("Files");if(typeof n.contains=="function")return n.contains("Files");for(let o=0;o<n.length;o++)if(n[o]==="Files")return!0;return!1}function mr(e){const t=e?.closest?.(".os-window");if(!t)return;const n=/^wp-window-(.+)$/.exec(t.id||"");return n?n[1]:void 0}function wM(e){if(!e)return;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e){const o=mr(n);return o||n.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0}}function kb(e){const t=window;if(t.__openStationOsFileDropMounted)return t.__openStationOsFileDropMounted;if(!e.config.enabled)return bM();const n=yM();let o=0,s=null;const i=()=>{o=0,n.classList.remove("is-active"),s!==null&&(clearTimeout(s),s=null)},r=()=>{s!==null&&clearTimeout(s),s=setTimeout(i,250)},a=m=>{fs(m)&&(m.preventDefault(),o++,n.classList.add("is-active"),r())},l=m=>{if(fs(m)){if(m.defaultPrevented){i();return}m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="copy"),r()}},c=()=>{o=Math.max(0,o-1),o===0&&n.classList.remove("is-active")},d=m=>{if(!fs(m))return;if(m.defaultPrevented){i();return}m.preventDefault(),i();const h=pM(m.dataTransfer?.items),b=Sb(m);if(h.some(I=>I.isDirectory)){Ab(h,b,e);return}const y=m.dataTransfer?.files?Array.from(m.dataTransfer.files):[];y.length!==0&&Zc(y,b,e)},u=()=>i(),f=()=>{document.visibilityState==="hidden"&&i()},p=m=>{if(m.origin!==window.location.origin)return;const h=m.data;if(!h||h.type!=="os-file-drop"||!Array.isArray(h.files)||h.files.length===0)return;const b=h.files.filter(R=>R instanceof File);if(b.length===0)return;const y=wM(m.source);if(!y)return;const I={surface:"iframe",windowId:y,x:typeof h.x=="number"?h.x:0,y:typeof h.y=="number"?h.y:0};o=0,n.classList.remove("is-active"),Zc(b,I,e)};window.addEventListener("dragenter",a),window.addEventListener("dragover",l),window.addEventListener("dragleave",c),window.addEventListener("drop",d),window.addEventListener("dragend",u),document.addEventListener("visibilitychange",f),window.addEventListener("blur",u),window.addEventListener("message",p);const g={dispose:()=>{window.removeEventListener("dragenter",a),window.removeEventListener("dragover",l),window.removeEventListener("dragleave",c),window.removeEventListener("drop",d),window.removeEventListener("dragend",u),document.removeEventListener("visibilitychange",f),window.removeEventListener("blur",u),window.removeEventListener("message",p),n.remove(),delete window.__openStationOsFileDropMounted}};return t.__openStationOsFileDropMounted=g,g}function yM(){const e=document.querySelector(".os-drop-overlay");if(e)return e;const t=document.createElement("div");t.className="os-drop-overlay",t.setAttribute("aria-hidden","true"),t.style.cssText=["position:fixed","inset:0","pointer-events:none","z-index:200","opacity:0","transition:opacity 120ms ease","background:radial-gradient(circle at center, rgba(34,113,177,0.18) 0%, rgba(34,113,177,0.06) 60%, transparent 100%)","box-shadow:inset 0 0 0 3px rgba(34,113,177,0.55)"].join(";");const n=document.createElement("div");n.style.cssText=["position:absolute","top:50%","left:50%","transform:translate(-50%,-50%)","padding:14px 22px","border-radius:12px","background:rgba(20,20,24,0.78)","color:#fff","font:600 14px/1.2 -apple-system,BlinkMacSystemFont,sans-serif","letter-spacing:0.02em"].join(";"),n.textContent="Drop to upload",t.appendChild(n),document.body.appendChild(t);const o=document.createElement("style");return o.textContent=".os-drop-overlay.is-active{opacity:1!important;}",document.head.appendChild(o),t}function bM(){const e=o=>{if(!fs(o))return;const s=o.target;s?.closest&&Eb.some(i=>s.closest(i))||o.preventDefault()};window.addEventListener("dragover",e),window.addEventListener("drop",e);const t=window,n={dispose:()=>{window.removeEventListener("dragover",e),window.removeEventListener("drop",e),delete t.__openStationOsFileDropMounted}};return t.__openStationOsFileDropMounted=n,n}function Sb(e){const t=e.clientX,n=e.clientY;let o=e.target;for(;o&&o!==document.body;){if(o.classList.contains("os-file-tile")&&o.dataset.fileType==="folder"){const s=Number(o.dataset.fileRef??0);if(Number.isFinite(s)&&s>0)return{surface:"folder",folderId:s,x:t,y:n}}if(o.tagName==="IFRAME")return{surface:"iframe",windowId:mr(o),x:t,y:n};if(o.classList.contains("os-window")||o.hasAttribute("data-window-id")){const s=mr(o)??(o.getAttribute("data-window-id")||void 0),i=s?/^os-folder-(\d+)/.exec(s):null;return i?{surface:"folder",folderId:Number(i[1]),windowId:s,x:t,y:n}:{surface:"window",windowId:s,x:t,y:n}}if(o.dataset?.folderId!==void 0){const s=Number(o.dataset.folderId);return Number.isFinite(s)&&s>0?{surface:"folder",folderId:s,x:t,y:n}:{surface:"wallpaper",x:t,y:n}}if(o.id==="os-wallpaper"||o.classList.contains("os-wallpaper")||o.classList.contains("os-desktop"))return{surface:"wallpaper",x:t,y:n};o=o.parentElement}return{surface:"unknown",x:t,y:n}}async function Zc(e,t,n){const o=q(he.FILES_DETECTED,e,t);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=Jc(o,n.config);if(i.length>0&&(T(he.FILES_REJECTED,{rejections:i,context:t}),Q({message:i.length===1?i[0].message:`${i.length} files couldn't be uploaded.`})),s.length===0)return;const r=s.map(({file:a,mime:l})=>{const c={file:a,mime:l,fields:Qc(a,l)},d=q(he.DIALOG_FIELDS,c,t);return!d||typeof d!="object"||!("fields"in d)||typeof d.fields!="object"?c:d});await n.openDialog(r,t)}async function Ab(e,t,n){if(!n.storage?.canUpload||!n.filesUrl){Q({message:"Folder uploads need desktop storage, which is not available for your account."});return}const o=await gM(e),s=q(he.FILES_DETECTED,o.files.map(u=>u.file),t);if(!Array.isArray(s))return;const i=new Set(s),r=o.files.filter(u=>i.has(u.file));if(r.length===0&&o.emptyDirs.length===0)return;const{accepted:a,rejected:l}=Jc(r.map(u=>u.file),n.config);l.length>0&&(T(he.FILES_REJECTED,{rejections:l,context:t}),Q({message:l.length===1?l[0].message:`${l.length} files couldn't be uploaded.`}));const c=new Map(r.map(u=>[u.file,u.relativePath])),d=a.map(({file:u,mime:f})=>({file:u,mime:f,fields:Qc(u,f),relativePath:c.get(u)??""}));d.length===0&&o.emptyDirs.length===0||await n.openDialog(d,t,{forceDesktop:!0,emptyDirs:o.emptyDirs})}function Jc(e,t){const n=[],o=[];for(const s of e){if(s.size===0){o.push({file:s,reason:"empty",message:`“${s.name}” is empty.`});continue}if(t.maxSize>0&&s.size>t.maxSize){o.push({file:s,reason:"size",message:`“${s.name}” exceeds the ${_M(t.maxSize)} upload limit.`});continue}const i=Cb(s,t.allowedMimes,t.extToMime);if(!i){o.push({file:s,reason:"mime",message:`“${s.name}” is not an allowed file type.`});continue}n.push({file:s,mime:i})}return{accepted:n,rejected:o}}function Cb(e,t,n){if(t.length===0)return null;const o=e.type.toLowerCase();if(o&&t.includes(o))return o;const s=Ib(e.name);if(!s)return null;if(n){for(const[r,a]of Object.entries(n))if(r.split("|").includes(s)&&t.includes(a))return a;return null}const i=vM[s];return i&&t.includes(i)?i:null}const vM={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",avif:"image/avif",heic:"image/heic",heif:"image/heif",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",pdf:"application/pdf"};function Ib(e){const t=e.lastIndexOf(".");return t<0?"":e.slice(t+1).toLowerCase()}function Qc(e,t){const n=xb(e.name),o=Ib(n),s=o?n.slice(0,n.length-o.length-1):n,i=Lb(s);return{title:i,altText:t.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function xb(e){return e.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function Lb(e){const t=e.replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Upload"}function _M(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}const EM=Object.freeze(Object.defineProperty({__proto__:null,IFRAME_PASSTHROUGH_SELECTORS:Eb,classifyDropTarget:Sb,defaultFields:Qc,dragHasFiles:fs,handleFiles:Zc,handleTreeDrop:Ab,humanize:Lb,mountOsFileDropManager:kb,partitionByPolicy:Jc,resolveAllowedMime:Cb,sanitizeFilename:xb,windowIdFromElement:mr},Symbol.toStringTag,{value:"Module"})),kM=ue` ${dt} ${Aa}:host{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var( --os-ui-fg,#1d2327 );min-width:0}:host( [ hidden ] ){display:none}.os-text-field__label{font-size:12px;color:var( --os-ui-fg-muted,#646970 )}.os-text-field__row{position:relative;display:flex;align-items:center;width:100%}input{appearance:none;-webkit-appearance:none;display:block;width:100%;min-width:0;box-sizing:border-box;padding:7px 10px;background:var( --os-window-bg,#fff );border:1px solid var( --os-ui-border,#dcdcde );border-radius:6px;font:inherit;font-size:13px;color:var( --os-ui-fg,#1d2327 )}.os-text-field__suffix{position:absolute;inset-inline-end:10px;top:50%;transform:translateY( -50% );pointer-events:none;font-size:12px;color:var( --os-ui-fg-muted,#646970 )}.os-text-field__row--has-reveal input{padding-inline-end:36px}.os-text-field__reveal{position:absolute;inset-inline-end:0;top:0;bottom:0;width:34px;display:flex;align-items:center;justify-content:center;padding:0;border:none;background:transparent;color:var( --os-ui-fg-muted,#646970 );cursor:pointer;border-radius:0 6px 6px 0;transition:color 0.12s ease}.os-text-field__reveal:hover{color:var( --os-ui-accent,#2271b1 )}.os-text-field__reveal:focus-visible{outline:none;color:var( --os-ui-accent,#2271b1 );box-shadow:inset 0 0 0 2px var( --os-ui-accent,#2271b1 );border-radius:0 6px 6px 0}.os-text-field__reveal:disabled{opacity:0.45;cursor:not-allowed}.os-text-field__input--masked{-webkit-text-security:disc;text-security:disc}@supports not ( ( -webkit-text-security:disc ) or ( text-security:disc ) ){.os-text-field__input--masked{font-family:text-security-disc,"password",monospace;letter-spacing:0.2em}}input:disabled{opacity:0.55;cursor:not-allowed;background:var( --os-ui-hover,rgba( 0,0,0,0.03 ) )}input[ aria-invalid='true' ],input[ aria-invalid='true' ]:hover:not(:disabled ){border-color:var( --os-ui-danger,#d63638 )}input[ aria-invalid='true' ]:focus,input[ aria-invalid='true' ]:focus-visible{border-color:var( --os-ui-danger,#d63638 );box-shadow:0 0 0 1px var( --os-ui-danger,#d63638 ),0 0 0 4px rgba( 214,54,56,0.18 )}input[ type='number' ]::-webkit-inner-spin-button,input[ type='number' ]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}input[ type='number' ]{-moz-appearance:textfield}`,Is=class Is extends Se{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),hp(this)}render(){const t=this.label||"",n=this.value??"",o=this.placeholder||"",s=this.disabled!==null,i=this.readonly!==null,r=this.autocomplete,a=this.type||"text",l=a==="password";let c=r||"off";l&&(!r||c==="off")&&(c="new-password");const d=this.maxlength,u=this.minlength,f=this.pattern||"",p=this.name||"",g=this.suffix||"",m=this.invalid!==null,h=this.reveal!==null,b=a==="password",y=b&&!(h&&this._revealed);let I;b||h&&this._revealed?I="text":I=a;const R=h?"os-text-field__row os-text-field__row--has-reveal":"os-text-field__row",k=y?"os-text-field__input os-text-field__input--masked":"os-text-field__input",P=`${this.id||"os-unnamed"}__input`;return J` | |
| 268 | - ${t?J`<label | |
| 269 | - class="os-text-field__label" | |
| 270 | - for=${P} | |
| 271 | - >${t}</label>`:J``} | |
| 272 | - <span class=${R}> | |
| 273 | - <input | |
| 274 | - id=${P} | |
| 275 | - class=${k} | |
| 276 | - type=${I} | |
| 277 | - .value=${n} | |
| 278 | - placeholder=${o} | |
| 279 | - ?disabled=${s} | |
| 280 | - ?readonly=${i} | |
| 281 | - autocomplete=${c} | |
| 282 | - maxlength=${d??""} | |
| 283 | - minlength=${u??""} | |
| 284 | - pattern=${f} | |
| 285 | - name=${p} | |
| 286 | - aria-invalid=${m?"true":"false"} | |
| 287 | - aria-label=${t||""} | |
| 288 | - @input=${W=>this._onInput(W)} | |
| 289 | - @change=${W=>this._onChange(W)} | |
| 290 | - @keydown=${W=>this._onKeyDown(W)} | |
| 291 | - /> | |
| 292 | - ${g?J`<span class="os-text-field__suffix">${g}</span>`:J``} | |
| 293 | - ${h?this._renderRevealButton(s):J``} | |
| 294 | - </span> | |
| 295 | - `}_renderRevealButton(t){const n=this._revealed?"Hide":"Show";return J` | |
| 296 | - <button | |
| 297 | - type="button" | |
| 298 | - class="os-text-field__reveal" | |
| 299 | - aria-label=${n} | |
| 300 | - aria-pressed=${this._revealed?"true":"false"} | |
| 301 | - ?disabled=${t} | |
| 302 | - tabindex="0" | |
| 303 | - @click=${()=>this._onToggleReveal()} | |
| 304 | - > | |
| 305 | - ${this._revealed?AM():SM()} | |
| 306 | - </button> | |
| 307 | - `}_onToggleReveal(){this._revealed=!this._revealed,this.requestUpdate()}_onInput(t){const n=t.target;this.value=n.value,this.emit("os-input-change",{value:n.value})}_onChange(t){const n=t.target;this.emit("os-input-commit",{value:n.value})}_onKeyDown(t){if(t.key==="Enter"&&!t.shiftKey&&!t.altKey&&!t.metaKey){const n=t.target;this.emit("os-submit",{value:n.value})}}};Is.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],Is.styles=[kM],Is.help=void 0;let ed=Is;xe("os-text-field",ed);function SM(){return J` | |
| 308 | - <svg | |
| 309 | - viewBox="0 0 16 16" | |
| 310 | - width="14" | |
| 311 | - height="14" | |
| 312 | - fill="none" | |
| 313 | - stroke="currentColor" | |
| 314 | - stroke-width="1.5" | |
| 315 | - stroke-linecap="round" | |
| 316 | - stroke-linejoin="round" | |
| 317 | - aria-hidden="true" | |
| 318 | - focusable="false" | |
| 319 | - > | |
| 320 | - <path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> | |
| 321 | - <circle cx="8" cy="8" r="2" /> | |
| 322 | - </svg> | |
| 323 | - `}function AM(){return J` | |
| 324 | - <svg | |
| 325 | - viewBox="0 0 16 16" | |
| 326 | - width="14" | |
| 327 | - height="14" | |
| 328 | - fill="none" | |
| 329 | - stroke="currentColor" | |
| 330 | - stroke-width="1.5" | |
| 331 | - stroke-linecap="round" | |
| 332 | - stroke-linejoin="round" | |
| 333 | - aria-hidden="true" | |
| 334 | - focusable="false" | |
| 335 | - > | |
| 336 | - <path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> | |
| 337 | - <circle cx="8" cy="8" r="2" /> | |
| 338 | - <line x1="2" y1="2" x2="14" y2="14" /> | |
| 339 | - </svg> | |
| 340 | - `}async function CM(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=q(he.BEFORE_UPLOAD,t,e.context);if(!n)throw new td;const o=new FormData,s=n.fields.filename!==n.file.name?new File([n.file],n.fields.filename,{type:n.mime||n.file.type}):n.file;return o.append("file",s),o.append("title",n.fields.title),o.append("alt_text",n.fields.altText),o.append("caption",n.fields.caption),o.append("description",n.fields.description),new Promise((i,r)=>{const a=new XMLHttpRequest;a.open("POST",e.mediaUrl,!0),a.withCredentials=!0,a.setRequestHeader("X-WP-Nonce",e.restNonce),a.responseType="text";let l=!1,c=!1,d=!1;const u=()=>{if(d=!0,!c){l=!0;try{a.abort()}catch{}}};T(he.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:u}),a.upload.addEventListener("progress",f=>{T(he.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:f.loaded,total:f.lengthComputable?f.total:0,indeterminate:!f.lengthComputable})}),a.upload.addEventListener("load",()=>{c=!0,T(he.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:n.file.size,total:n.file.size,indeterminate:!1})}),a.addEventListener("error",()=>{if(l)return;const f=new Error("Network error during upload.");T(he.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),r(f)}),a.addEventListener("abort",()=>{const f=new gr;T(he.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),r(f)}),a.addEventListener("load",()=>{if(l)return;if(a.status<200||a.status>=300){const g=xM(a),m=new Error(g);T(he.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}let f;try{f=JSON.parse(a.responseText)}catch(g){const m=g instanceof Error?g:new Error("Could not parse server response.");T(he.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}if(d&&f.id){IM(e.mediaUrl,e.restNonce,f.id);const g=new gr;T(he.UPLOAD_FAILED,{file:n.file,error:g,context:e.context}),r(g);return}const p={id:f.id,url:f.source_url,mime:f.mime_type||n.mime,title:f.title?.rendered||n.fields.title,filename:f.media_details?.file||n.fields.filename};T(he.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:e.context}),i(p)}),a.send(o)})}class td extends Error{constructor(){super("Upload cancelled by os.drop.before-upload filter."),this.name="UploadCancelledError"}}class gr extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function IM(e,t,n){const o=`${e.replace(/\/$/,"")}/${n}?force=true`,s=new XMLHttpRequest;return s.open("DELETE",o,!0),s.withCredentials=!0,s.setRequestHeader("X-WP-Nonce",t),new Promise(i=>{s.addEventListener("loadend",()=>{(s.status<200||s.status>=300)&&console.warn(`[os-file-drop] late-cancel cleanup failed for attachment ${n} (HTTP ${s.status}). The attachment remains in the Media Library; delete it manually.`),i()}),s.addEventListener("error",()=>{console.warn(`[os-file-drop] late-cancel cleanup network error for attachment ${n}. The attachment remains in the Media Library; delete it manually.`),i()});try{s.send()}catch(r){console.warn(`[os-file-drop] late-cancel cleanup could not be dispatched for attachment ${n}:`,r),i()}})}function xM(e){const t=`Upload failed (HTTP ${e.status}).`,n=e.responseText;if(!n)return t;try{const o=JSON.parse(n);if(o&&typeof o.message=="string")return o.message}catch{}return t}async function LM(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=q(he.BEFORE_UPLOAD,t,e.context);if(!n)throw new td;const o=new FormData,s=n.fields.filename!==n.file.name?new File([n.file],n.fields.filename,{type:n.mime||n.file.type}):n.file;o.append("file",s),o.append("parentId",String(e.parentId)),e.relativePath&&o.append("relativePath",e.relativePath),e.coords&&(o.append("x",String(e.coords.x)),o.append("y",String(e.coords.y)));const i=`${e.filesUrl.replace(/\/$/,"")}/uploads`;return new Promise((r,a)=>{const l=new XMLHttpRequest;l.open("POST",i,!0),l.withCredentials=!0,l.setRequestHeader("X-WP-Nonce",e.restNonce),l.responseType="text";let c=!1;const d=()=>{c=!0;try{l.abort()}catch{}};T(he.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:d}),l.upload.addEventListener("progress",f=>{T(he.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:f.loaded,total:f.lengthComputable?f.total:0,indeterminate:!f.lengthComputable})});const u=f=>{T(he.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),a(f)};l.addEventListener("error",()=>{c||u(new Error("Network error during upload."))}),l.addEventListener("abort",()=>u(new gr)),l.addEventListener("load",()=>{if(c)return;if(l.status<200||l.status>=300){u(new Error(TM(l,n.file.name)));return}let f;try{f=JSON.parse(l.responseText)}catch{u(new Error("Could not parse server response."));return}if(!f.placement||typeof f.storedFileId!="number"){u(new Error("Unexpected server response."));return}Vi(f.placement,"local");const p={placement:f.placement,storedFileId:f.storedFileId};T(he.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:e.context}),r(p)}),l.send(o)})}function TM(e,t){if(e.status===413)return`“${t}” is larger than this server accepts.`;const n=`Upload failed (HTTP ${e.status}).`,o=e.responseText;if(!o)return n;try{const s=JSON.parse(o);if(s&&typeof s.message=="string"&&s.message)return s.message}catch{}return n}function NM(e,t){const n=Math.max(0,Math.round((e-16)/96)),o=Math.max(0,Math.round((t-16)/110));return{x:16+n*96,y:16+o*110}}const DM=/^(image|video|audio)\//;function nd(e){return e.desktopAllowed?e.forceDesktop||e.preferDesktop?"desktop":e.surface==="window"||e.surface==="iframe"?"media":(e.folderId??0)>0?"desktop":e.mimes.length>0&&e.mimes.every(n=>DM.test(n))?"media":"desktop":"media"}let tn=null;async function RM(e){if(e.entries.length===0&&!e.emptyDirs?.length)return;if(tn){tn.replace(e);return}const t=!!(e.storage?.canUpload&&e.filesUrl);let n=nd({desktopAllowed:t,surface:e.context.surface,folderId:e.context.folderId,forceDesktop:e.forceDesktop,preferDesktop:e.preferDesktop,mimes:e.entries.map(d=>d.mime)});const o=document.createElement("os-modal");o.setAttribute("open",""),o.setAttribute("size","md"),document.body.appendChild(o);const s=()=>{const d=e.entries.length;let u="Media Library";n==="desktop"&&(u=(e.context.folderId??0)>0?"this folder":"Desktop");let f=`Upload ${d} files to ${u}`;d===0?f=(e.context.folderId??0)>0?"Create folders in this folder":"Create folders on Desktop":d===1&&(f=`Upload to ${u}`),o.setAttribute("title",f)};s();const i=e.entries.map(d=>({...d.fields})),r=()=>{if(o.innerHTML="",t&&!e.forceDesktop){const m=document.createElement("div");m.style.cssText="display:flex;align-items:center;gap:10px;margin-bottom:14px;";const h=document.createElement("span");h.textContent="Upload to",h.style.cssText="font-weight:600;",m.appendChild(h);const b=document.createElement("os-segmented");b.setAttribute("value",n),b.setAttribute("label","Destination"),b.style.setProperty("--os-ui-segmented-bg","rgba(255,255,255,0.06)");const y=document.createElement("os-segment");y.setAttribute("value","desktop"),y.textContent="Desktop",b.appendChild(y);const I=document.createElement("os-segment");I.setAttribute("value","media"),I.textContent="Media Library",b.appendChild(I),b.addEventListener("os-pick",R=>{n=R.detail.value,s(),r()}),m.appendChild(b),o.appendChild(m)}else if(e.forceDesktop){const m=document.createElement("div");m.style.cssText="opacity:0.7;font-size:12px;margin-bottom:14px;",m.textContent="Folder uploads land in your desktop storage, preserving the folder structure.",o.appendChild(m)}const d=n==="desktop"?e.storage?.maxBytes??0:e.mediaMaxBytes??0;if(d>0){const m=document.createElement("div");m.className="os-upload-dialog__max-size",m.style.cssText="opacity:0.6;font-size:12px;margin-bottom:14px;",m.textContent=`Maximum file size: ${Yt(d)}`,o.appendChild(m)}const u=document.createElement("div");u.style.cssText="display:flex;flex-direction:column;gap:18px;max-height:60vh;overflow:auto;padding-right:6px;",e.entries.forEach((m,h)=>{u.appendChild(a(m,i[h],h+1))}),o.appendChild(u);const f=document.createElement("div");f.setAttribute("slot","footer"),f.style.cssText="display:flex;gap:8px;justify-content:flex-end;";const p=document.createElement("os-button");p.setAttribute("variant","secondary"),p.textContent="Cancel",p.addEventListener("click",()=>{o.remove()});const g=document.createElement("os-button");g.setAttribute("variant","primary"),e.entries.length===0?g.textContent="Create folders":g.textContent=e.entries.length===1?"Upload":`Upload ${e.entries.length} files`,g.addEventListener("click",()=>{l(g,p)}),f.appendChild(p),f.appendChild(g),o.appendChild(f)},a=(d,u,f)=>{const p=document.createElement("div");p.style.cssText="display:flex;flex-direction:column;gap:8px;border:1px solid rgba(255,255,255,0.08);border-radius:10px;padding:14px;";const g=document.createElement("div");g.style.cssText="display:flex;gap:10px;align-items:center;font-weight:600;";const m=document.createElement("span");m.textContent=e.entries.length===1?"":`#${f} · `,m.style.opacity="0.6";const h=document.createElement("span");h.textContent=d.file.name,h.style.cssText="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";const b=document.createElement("span");if(b.textContent=`${d.mime||"unknown"} · ${Yt(d.file.size)}`,b.style.cssText="opacity:0.6;font-size:12px;",g.appendChild(m),g.appendChild(h),g.appendChild(b),p.appendChild(g),n==="desktop"){if(d.relativePath){const y=document.createElement("div");y.textContent=d.relativePath,y.style.cssText="opacity:0.55;font-size:12px;",p.appendChild(y)}return p.appendChild(ps("Filename",u.filename,y=>u.filename=y)),p}return p.appendChild(ps("Title",u.title,y=>u.title=y)),p.appendChild(ps("Filename",u.filename,y=>u.filename=y)),d.mime.startsWith("image/")&&p.appendChild(ps("Alt text",u.altText,y=>u.altText=y)),p.appendChild(ps("Caption",u.caption,y=>u.caption=y)),p.appendChild(OM("Description",u.description,y=>u.description=y)),p},l=async(d,u)=>{tn===c&&(tn=null),d.disabled=!0,u.disabled=!0,d.textContent="Uploading…";const f=e.entries.length;let p=0,g=0,m=0;const h=[],b=e.context.folderId??0;let y=!1;for(let R=0;R<f;R++){const k=e.entries[R];try{if(n==="desktop"&&e.filesUrl){const P=!k.relativePath&&!y&&e.context.surface==="wallpaper"?NM(e.context.x,e.context.y):void 0;P&&(y=!0),await LM({file:k.file,mime:k.mime,fields:i[R],context:e.context,filesUrl:e.filesUrl,restNonce:e.restNonce,parentId:b,relativePath:k.relativePath??"",coords:P})}else await CM({file:k.file,mime:k.mime,fields:i[R],context:e.context,mediaUrl:e.mediaUrl,restNonce:e.restNonce});p++}catch(M){if(M instanceof td){m++;continue}if(M instanceof gr){m++;continue}g++;const P=M instanceof Error?M.message:"Upload failed.";h.push(`“${k.file.name}” — ${P}`)}}if(n==="desktop"&&e.emptyDirs?.length)for(const R of e.emptyDirs)try{await xw(b,R)}catch{}const I=e.entries.some(R=>R.relativePath)||!!e.emptyDirs?.length;if(n==="desktop"&&I)try{const[R,k]=await Promise.all([nc(),Te(b)]);qi(R.folders),ht(b,k.placements)}catch{}o.remove(),MM({total:f,successes:p,failures:g,cancelled:m,failureDetails:h,destination:n})},c={replace:d=>{e.entries=d.entries,e.emptyDirs=d.emptyDirs,e.forceDesktop=d.forceDesktop,e.preferDesktop=d.preferDesktop,e.context=d.context,e.mediaMaxBytes=d.mediaMaxBytes??e.mediaMaxBytes,i.length=0;for(const u of d.entries)i.push({...u.fields});n=nd({desktopAllowed:t,surface:d.context.surface,folderId:d.context.folderId,forceDesktop:d.forceDesktop,preferDesktop:d.preferDesktop,mimes:d.entries.map(u=>u.mime)}),s(),r()}};tn=c,r(),await new Promise(d=>{const u=()=>{tn===c&&(tn=null),d()};o.addEventListener("os-modal-cancel",()=>{o.remove(),u()});const f=new MutationObserver(()=>{o.isConnected||(f.disconnect(),u())});f.observe(document.body,{childList:!0,subtree:!0})})}function ps(e,t,n){const o=document.createElement("os-text-field");return o.setAttribute("label",e),o.setAttribute("value",t),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function OM(e,t,n){const o=document.createElement("os-textarea");return o.setAttribute("label",e),o.setAttribute("value",t),o.setAttribute("rows","3"),o.addEventListener("input",()=>{const s=o.value;typeof s=="string"&&n(s)}),o}function MM(e){const{total:t,successes:n,failures:o,cancelled:s,failureDetails:i}=e,r=e.destination==="desktop"?"your desktop":"Media Library";if(t===0){e.destination==="desktop"&&Q({message:"Folder created on your desktop."});return}if(t===1){n===1?Q({message:`Uploaded to ${r}.`}):o===1&&i[0]?Q({message:i[0]}):s===1&&Q({message:"Upload cancelled."});return}if(n===t){Q({message:`Uploaded ${n} files to ${r}.`});return}if(s===t){Q({message:"All uploads cancelled."});return}if(o===t){Q({message:o===1&&i[0]?i[0]:`${o} uploads failed.`});return}const a=[];n>0&&a.push(`Uploaded ${n} file${n===1?"":"s"}.`),s>0&&a.push(`Cancelled ${s}.`),o>0&&a.push(`Failed ${o}.`),Q({message:a.join(" ")})}const Tb=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:RM,resolveDefaultDestination:nd},Symbol.toStringTag,{value:"Module"})),PM={tab:null,requestedAt:0};let wr=null;function od(){if(wr)return wr;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(wr=t("desktop-mode/plugins-window/tab-target",()=>({...PM})),wr)}function WM(e){const t=od();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 $M(){const e=od();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 UM(e){const t=od();return t?t.subscribe(n=>e({...n})):()=>{}}const FM=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:$M,setPluginsWindowTab:WM,subscribePluginsWindowTab:UM},Symbol.toStringTag,{value:"Module"})),BM=ue` ${dt} ${vp}:host{display:block;--_track-bg:var( --os-ui-progress-track-bg,var( --os-ui-surface-sunken,rgba( 0,0,0,0.08 ) ) );--_fill:var( --os-ui-progress-fill,var( --wp-admin-theme-color,#2271b1 ) );--_height:var( --os-ui-progress-height,6px );--_radius:var( --os-ui-progress-radius,999px );--_label-color:var( --os-ui-progress-label-color,inherit );--_label-size:var( --os-ui-progress-label-size,12px );--_label-gap:var( --os-ui-progress-label-gap,4px );width:100%;font:inherit;color:var( --_label-color )}:host( [ hidden ] ){display:none}.header{display:flex;align-items:baseline;justify-content:space-between;gap:8px;margin-bottom:var( --_label-gap );font-size:var( --_label-size );line-height:1.3}.label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.percent{font-variant-numeric:tabular-nums;opacity:0.75;flex-shrink:0}.track{position:relative;width:100%;height:var( --_height );background:var( --_track-bg );border-radius:var( --_radius );overflow:hidden}.fill{position:absolute;inset-block:0;inset-inline-start:0;width:0;background:var( --_fill );border-radius:inherit;transition:width 0.18s ease-out}:host( [ tone='success' ] ){--os-ui-progress-fill:var( --os-ui-success-fg,#3a8a3a )}:host( [ tone='warning' ] ){--os-ui-progress-fill:var( --os-ui-warning-fg,#dba617 )}:host( [ tone='danger' ] ){--os-ui-progress-fill:var( --os-ui-danger,#d63638 )}:host( [ indeterminate ] ) .fill{width:100%;transition:none;background-image:var( --_fill );background-size:300% 300%;background-repeat:no-repeat;animation:os-holo-shimmer 2.4s var( --_holo-loop ) infinite}:host( [ indeterminate ][ tone ] ) .fill{width:33%;background-image:none;animation:os-progress-sweep 1.1s linear infinite}@keyframes os-progress-sweep{0%{transform:translateX( -120% )}100%{transform:translateX( 320% )}}@media ( prefers-reduced-motion:reduce ){.fill{transition:none}:host( [ indeterminate ] ) .fill,:host( [ indeterminate ][ tone ] ) .fill{animation:none;width:100%;opacity:0.6}}`,xs=class xs extends Se{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return J`<div class="root" part="root"> | |
| 341 | - <div class="header" part="header" hidden> | |
| 342 | - <span class="label" part="label"></span> | |
| 343 | - <span class="percent" part="percent"></span> | |
| 344 | - </div> | |
| 345 | - <div class="track" part="track"> | |
| 346 | - <div class="fill" part="fill"></div> | |
| 347 | - </div> | |
| 348 | - </div>`}requestUpdate(){super.requestUpdate(),queueMicrotask(()=>this._paint())}connectedCallback(){super.connectedCallback(),queueMicrotask(()=>this._paint())}_paint(){const t=this.shadowRoot;if(!t)return;const n=this._readMax(),o=this.hasAttribute("indeterminate")||n<=0,s=o?0:this._readValue(n),i=o?0:s/n,r=Math.round(i*100),a=this.getAttribute("label")??"",l=this.hasAttribute("show-percent"),c=t.querySelector(".fill");c&&!o?c.style.width=`${(i*100).toFixed(2)}%`:c&&o&&c.style.removeProperty("width");const d=t.querySelector(".header"),u=t.querySelector(".label"),f=t.querySelector(".percent");if(d&&u&&f){const g=a||l&&!o;d.hidden=!g,u.textContent=a,f.hidden=!(l&&!o),f.textContent=`${r}%`}this._syncAria(n,s,o,a);const p=t.querySelector(".track");p&&(p.setAttribute("role","progressbar"),p.setAttribute("aria-valuemin","0"),o?(p.removeAttribute("aria-valuenow"),p.removeAttribute("aria-valuemax")):(p.setAttribute("aria-valuemax",String(n)),p.setAttribute("aria-valuenow",String(s))),a?p.setAttribute("aria-label",a):p.removeAttribute("aria-label"))}_syncAria(t,n,o,s){this.setAttribute("role","progressbar"),this.setAttribute("aria-valuemin","0"),o?(this.removeAttribute("aria-valuenow"),this.removeAttribute("aria-valuemax")):(this.setAttribute("aria-valuemax",String(t)),this.setAttribute("aria-valuenow",String(n)));const i=this.getAttribute("aria-label");s?(i===null||i===this._ownedAriaLabel)&&(this.setAttribute("aria-label",s),this._ownedAriaLabel=s):i!==null&&i===this._ownedAriaLabel&&(this.removeAttribute("aria-label"),this._ownedAriaLabel=null)}_readMax(){const t=this.getAttribute("max");if(t===null)return 100;const n=parseFloat(t);return Number.isFinite(n)?n:100}_readValue(t){const n=parseFloat(this.getAttribute("value")??"0");return!Number.isFinite(n)||n<0?0:n>t?t:n}};xs.props=["value","max","indeterminate","tone","label","showPercent"],xs.styles=[BM],xs.help=void 0;let sd=xs;xe("os-progress-bar",sd);const et=new Map;let gt=null;function HM(){if(document.body.hasAttribute("data-os-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const e="desktop-mode/os-file-drop-hud";Y(he.UPLOAD_STARTED,e,t=>zM(t.file,t.fields,t.abort)),Y(he.UPLOAD_PROGRESS,e,t=>GM(t.file,t.loaded,t.total,t.indeterminate)),Y(he.AFTER_UPLOAD,e,t=>jM(t.file,t.fields,t.result)),Y(he.UPLOAD_FAILED,e,t=>VM(t.file,t.error))}function zM(e,t,n){const o=qM(),s=document.createElement("div");s.className="os-upload-hud__row";const i=document.createElement("div");i.className="os-upload-hud__meta";const r=document.createElement("div");r.className="os-upload-hud__name",r.textContent=t.filename||e.name,r.title=t.filename||e.name;const a=document.createElement("div");a.className="os-upload-hud__status",a.textContent="Uploading…",i.append(r,a);const l=document.createElement("os-progress-bar");l.setAttribute("indeterminate",""),l.setAttribute("show-percent","");const c=document.createElement("div");c.className="os-upload-hud__actions";const d=document.createElement("os-button");d.setAttribute("variant","tertiary"),d.setAttribute("size","small"),d.textContent="Cancel",d.addEventListener("click",()=>{const u=et.get(e);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):id(u))}),c.appendChild(d),s.append(i,l,c),o.querySelector(".os-upload-hud__list").appendChild(s),et.set(e,{file:e,abort:n,root:s,bar:l,statusEl:a,cancelBtn:d,state:"running",lingerTimer:null}),yr()}function GM(e,t,n,o){const s=et.get(e);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${Yt(t)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(t)),s.statusEl.textContent=`${Yt(t)} / ${Yt(n)}`))}function jM(e,t,n){const o=et.get(e);o&&(o.state="success",o.bar.removeAttribute("indeterminate"),o.bar.setAttribute("value","100"),o.bar.setAttribute("max","100"),o.bar.setAttribute("tone","success"),o.statusEl.textContent="Uploaded",o.cancelBtn.textContent="Dismiss",o.lingerTimer=setTimeout(()=>id(o),2500),yr(),Ee.publish("os/upload-hud-complete",{filename:t.filename||n.filename,attachmentId:n.id}))}function VM(e,t){const n=et.get(e);n&&(n.bar.removeAttribute("indeterminate"),n.bar.setAttribute("tone","danger"),n.cancelBtn.textContent="Dismiss",n.cancelBtn.disabled=!1,t.name==="UploadAbortedError"?(n.state="aborted",n.statusEl.textContent="Cancelled"):(n.state="failed",n.statusEl.textContent=t.message||"Upload failed"),yr())}function id(e){e.lingerTimer&&clearTimeout(e.lingerTimer),et.delete(e.file),e.root.remove(),yr(),et.size===0&>&&(gt.hidden=!0)}function qM(){if(gt&>.isConnected)return gt.hidden=!1,gt;const e=document.createElement("div");e.className="os-upload-hud",e.setAttribute("role","region"),e.setAttribute("aria-label","Uploads");const t=document.createElement("div");t.className="os-upload-hud__header";const n=document.createElement("div");n.className="os-upload-hud__title",n.textContent="Uploads";const o=document.createElement("button");o.type="button",o.className="os-upload-hud__close",o.setAttribute("aria-label","Hide upload panel"),o.textContent="×",o.addEventListener("click",()=>{for(const i of[...et.values()])i.state!=="running"&&id(i);et.size===0&&(e.hidden=!0)}),t.append(n,o);const s=document.createElement("div");return s.className="os-upload-hud__list",e.append(t,s),document.body.appendChild(e),gt=e,e}function yr(){if(!gt)return;const e=gt.querySelector(".os-upload-hud__title");if(!e)return;const t=et.size,n=[...et.values()].filter(o=>o.state==="running").length;n>0?e.textContent=n===t?`Uploading ${n} file${n===1?"":"s"}…`:`${n} of ${t} uploading…`:t>0?e.textContent=`Uploads (${t})`:e.textContent="Uploads"}function KM(){if(document.body.hasAttribute("data-os-suppress-media-library-refresh"))return;const e=window;e.__wpdMediaLibraryRefresher||(e.__wpdMediaLibraryRefresher=!0,Y(he.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>YM()))}function YM(){const e=document.querySelectorAll("iframe");for(const t of Array.from(e))if(XM(Nb(t)))try{t.contentWindow?.location.reload()}catch{const n=Nb(t);n&&t.setAttribute("src",n)}}function Nb(e){try{return e.contentWindow?.location.href??e.src??""}catch{return e.src??""}}function XM(e){return e?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(e):!1}function ZM(e){const t=e.config||{enabled:!1,allowedMimes:[],maxSize:0};HM(),KM(),kb({config:t,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.storage,openDialog:async(n,o,s)=>{const{openUploadDialog:i}=await Promise.resolve().then(()=>Tb);await i({entries:n,context:o,mediaUrl:e.mediaUrl,restNonce:e.restNonce,filesUrl:e.filesUrl,storage:e.storage,forceDesktop:s?.forceDesktop,emptyDirs:s?.emptyDirs,mediaMaxBytes:t.maxSize})}})}const JM=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:he,bootOsFileDrop:ZM},Symbol.toStringTag,{value:"Module"}));return _r.clampGeometryToViewport=Ul,Object.defineProperty(_r,Symbol.toStringTag,{value:"Module"}),_r}({}); | |
| 63 | +</svg>`,k$=`data:image/svg+xml;base64,${btoa($b)}`;let Md=0;function I$(e,t,n){const o=`openstation/mio-window-${++Md}`,s=new Set,i=r=>{const a=t(),l=a.available&&a.enabled;let c=b(l?"Disable MIO in this window":"Enable MIO in this window");a.available||(c=b("Enable MIO in the dock first")),r.setAttribute("aria-label",c),r.setAttribute("title",c),r.setAttribute("aria-pressed",String(l)),r.toggleAttribute("disabled",!a.available),r.inert=!a.available,r.setAttribute("aria-hidden",String(!a.available)),r.dataset.mioAvailable=String(a.available),r.toggleAttribute("active",l),r.dataset.mioDisabled=String(!l),r.dataset.mioThinking=String(l&&a.thinking)};return os({id:o,label:b("MIO in this window"),icon:$b.replace('id="mio"',`id="mio-${Md}"`).replace("url(#mio)",`url(#mio-${Md})`),placement:"right",order:20,match:r=>r.id===e,render:r=>{r.classList.add("os-mio-window-toggle");const a=r.querySelector("svg");if(a){const l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M3 3L21 21"),l.setAttribute("class","os-mio-window-toggle__slash"),a.appendChild(l)}s.add(r),i(r),r.addEventListener("os-button-activate",()=>{t().available&&n()})}}),{update:()=>{for(const r of s)r.isConnected?i(r):s.delete(r)},dispose:()=>{Hm(o),s.clear()}}}class A${constructor(t,n,o,s){this.host=t,this.frame=n,this.handle=o,this.visibility=s,this.request=null,this.dismissed=new Set,this.active=!1,this.visible=!1,this.raf=0,this.bubble=document.createElement("aside"),this.bubble.className="os-mio-callout",this.bubble.hidden=!0,this.bubble.setAttribute("aria-label",b("MIO tip")),this.message=document.createElement("span"),this.message.setAttribute("role","status");const i=document.createElement("os-button");i.setAttribute("variant","ghost"),i.setAttribute("aria-label",b("Dismiss MIO tip"));const r=document.createElement("span");r.textContent="×",r.setAttribute("aria-hidden","true");const a=document.createElement("span");a.className="screen-reader-text",a.textContent=b("Dismiss MIO tip"),i.append(r,a),i.addEventListener("click",()=>{this.request&&(this.dismissed.add(this.request.id),this.update(),this.request.onDismiss?.())}),this.bubble.append(this.message,i),n.append(this.bubble),this.observer=new MutationObserver(()=>this.update()),this.observer.observe(t,{childList:!0,subtree:!0,attributes:!0})}show(t){if(!t.id.trim()||!t.message.trim()||typeof t.target!="function")throw new Error("MIO callouts require an id, message and a live target resolver.");this.request=t,this.message.textContent=t.message,this.update()}clear(){this.request=null,this.update()}setActive(t){this.active=t,this.update()}update(){cancelAnimationFrame(this.raf),this.raf=0;const t=this.request,n=this.active&&t&&!this.dismissed.has(t.id)?t.target():null,o=this.frame.getBoundingClientRect(),s=n?.getBoundingClientRect(),i=!!(n?.isConnected&&this.host.contains(n)&&s&&s.width>0&&s.height>0&&s.bottom>o.top&&s.top<o.bottom&&s.right>o.left&&s.left<o.right);if(this.bubble.hidden=!i,i&&s){const r=(f,p,g)=>Math.max(p,Math.min(f,g)),a=getComputedStyle(this.frame).direction==="rtl",l={x:r(a?s.left+60:s.right-60,o.left+60,o.right-60),y:r(s.bottom+65,o.top+65,o.bottom-65)};this.handle()?.setAnchor?.(l,!0);const c=this.handle()?.getPosition()??l,d=this.bubble.offsetWidth,u=this.bubble.offsetHeight;this.bubble.style.left=`${r(c.x-o.left+(a?45:-d-45),8,o.width-d-8)}px`,this.bubble.style.top=`${r(c.y-o.top-u-24,8,o.height-u-8)}px`}i!==this.visible&&(this.visible=i,i||this.handle()?.setAnchor?.(null),this.visibility(i)),this.active&&t&&!this.dismissed.has(t.id)&&(this.raf=requestAnimationFrame(()=>this.update()))}dispose(){this.setActive(!1),this.observer.disconnect(),this.bubble.remove()}}function C$(e,t,n){const o=e.getBoundingClientRect(),s=n()?.getPosition(),i=s?{x:s.x-o.left,y:s.y-o.top}:null,r=new ResizeObserver(a);function a(){if(!e.isConnected||e.hidden)return;const l=e.getBoundingClientRect(),c=t.getBoundingClientRect();let d=i?{x:l.left+i.x,y:l.top+i.y}:null;c.left-l.left>=140&&(d={x:c.left-70,y:Math.min(c.top+70,l.bottom-70)}),n()?.setAnchor?.(d,!0)}return r.observe(t),r.observe(e),a(),{close:l=>{r.disconnect();const c=e.getBoundingClientRect();n()?.setAnchor?.(l&&i?{x:c.left+i.x,y:c.top+i.y}:null,!1)}}}const ft=Object.freeze({rounds:8,calls:16,validationFailures:3,repeatedReads:4});class zr extends Error{constructor(t,n=!0){super(t.map(o=>`${o.path}: ${o.message}`).join("; ")),this.errors=t,this.retryable=n,this.name="MioValidationError"}}function ko(e,t){try{e?.(t)}catch{}}function Ub(e){if(!e||typeof e!="object")return null;const t=e;return t.effect==="none"&&t.status==="completed"||t.effect==="none"&&t.status==="rejected"&&Array.isArray(t.errors)||t.effect==="write"&&t.status==="confirmed"&&typeof t.receipt=="string"&&t.receipt.length>0&&t.receipt.length<=500||t.effect==="write"&&t.status==="unknown"?t:null}class L${constructor(t){this.records=new Map,this.inspectors=new Map,this.receipts=new Map,this.context=t}list(){return Array.from(this.records.values(),t=>structuredClone(t))}record(t,n,o,s){const i=this.records.get(t.callId);if(i?.status==="confirmed"&&o!=="confirmed")return structuredClone(i);if(i?.receipt&&s&&i.receipt!==s)throw new Error("MIO operation receipt changed unexpectedly.");const r=s&&this.receipts.has(s)&&this.receipts.get(s)!==t.callId,a={turnId:t.turnId,callId:t.callId,idempotencyKey:t.idempotencyKey,windowId:t.windowId,revision:t.revision,ability:n,effect:t.effect,status:r?"unknown":o,...s?{receipt:s}:{}};for(s&&!r&&this.receipts.set(s,t.callId),this.records.set(t.callId,a),this.context.operationStatus&&this.inspectors.set(t.callId,this.context.operationStatus);this.records.size>64;){const l=this.records.keys().next().value,c=this.records.get(l);c?.receipt&&this.receipts.get(c.receipt)===l&&this.receipts.delete(c.receipt),this.records.delete(l),this.inspectors.delete(l)}if(ko(this.context.onOperation,structuredClone(a)),r)throw new Error("MIO received a duplicate write receipt; inspect the operation status before continuing.");return structuredClone(a)}async inspect(t,n){const o=this.records.get(t),s=this.inspectors.get(t);if(!o)throw new Error("Unknown MIO operation.");if(o.effect!=="write"||o.status==="confirmed"||!s)return structuredClone(o);n.throwIfAborted();const i=Ub(await s(structuredClone(o),n));return n.throwIfAborted(),i?.effect==="write"&&i.status==="confirmed"?this.record({...o,signal:n,limits:ft,validationFailures:0,validationRemaining:0},o.ability,"confirmed",i.receipt):i?.effect==="none"&&i.status==="rejected"?this.record({...o,signal:n,limits:ft,validationFailures:0,validationRemaining:0},o.ability,"rejected"):structuredClone(o)}}function T$(e){return`Reads: ${e.reads}; rejected candidates: ${e.rejected}; confirmed writes: ${e.confirmedWrites}; unknown write outcomes: ${e.unknownWrites}. Completed writes are not rolled back.`}const Wd=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t;class N${constructor(t,n,o){this.entries=new Map,this.listeners=new Set,this.disposed=!1,this.context=t,this.active=n,this.messages=o}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notify(){for(const t of this.listeners)ko(t,void 0)}create(t){const n=[];if(this.disposed)return n;try{const o=this.context.responseActions?.(t);if(!Array.isArray(o)||this.disposed)return n;const s=new Set;let i=!1;for(const r of o.slice(0,100))try{if(!r||typeof r!="object")continue;const a={...r};if(!Wd(a.id,80)||s.has(a.id)||!Wd(a.label,40)||typeof a.run!="function"||!["read","navigate"].includes(a.effect)||a.emphasis!==void 0&&!["primary","secondary"].includes(a.emphasis)||a.allowed!==void 0&&typeof a.allowed!="function"||a.ariaLabel!==void 0&&!Wd(a.ariaLabel,160))continue;s.add(a.id),a.icon!==void 0&&(typeof a.icon!="string"||!/^(?:dashicons-)?[a-z][a-z0-9-]{0,63}$/.test(a.icon))&&delete a.icon,a.emphasis==="primary"&&!i?i=!0:a.emphasis="secondary";const l=crypto.randomUUID();if(this.entries.set(l,{messageId:t.messageId,turnId:t.summary.turnId,action:a,pending:null,status:""}),n.push(l),n.length===3)break}catch{}}catch{}return n}prune(){const t=new Set(this.messages().slice(-40).flatMap(n=>n.role==="assistant"?(n.actionIds??[]).map(o=>`${n.id}/${o}`):[]));for(const[n,o]of this.entries)t.has(`${o.messageId}/${n}`)||(o.pending?.abort(),this.entries.delete(n))}allowed(t){try{return!this.disposed&&this.active()&&(t.action.allowed?.()??!0)}catch{return!1}}list(t){return this.prune(),t.role!=="assistant"?[]:(t.actionIds??[]).flatMap(n=>{const o=this.entries.get(n);if(!o||o.messageId!==t.id)return[];const s=this.allowed(o);if(!s&&!o.status)return[];const{label:i,ariaLabel:r,icon:a,emphasis:l}=o.action;return[{id:n,label:i,ariaLabel:r,icon:a,emphasis:l??"secondary",pending:o.pending!==null,available:s,status:o.status}]})}async run(t,n){this.prune();const o=this.entries.get(n);if(!o||o.messageId!==t||o.pending)return;if(!this.allowed(o)){o.status=b("This action is no longer available."),this.notify();return}const s=new AbortController;o.pending=s,o.status=b("Working…"),this.notify();try{if(s.signal.throwIfAborted(),!this.allowed(o))throw new Error(b("This action is no longer available."));await o.action.run({signal:s.signal,messageId:t,turnId:o.turnId}),o.status=b("Done.")}catch(i){o.status=i instanceof Error?i.message.slice(0,500):b("Could not complete this action. Try again."),s.signal.aborted&&(o.status="")}finally{o.pending=null,this.notify()}}cancel(){for(const t of this.entries.values())t.pending?.abort()}dispose(){this.disposed=!0,this.cancel(),this.entries.clear(),this.listeners.clear()}}const O$=new Set("a an and are as at be by can do for from how i in is it me of on or please that the this to use we what with you your".split(" ")),Pd=e=>(e.toLocaleLowerCase().match(/[\p{L}\p{N}_-]+/gu)??[]).filter(t=>!O$.has(t)),Bb=e=>({id:e.id,title:e.title,version:e.version,topics:e.topics??[],componentIds:e.componentIds??[]});function Fb(e){const t=[],n=new Map;let o={id:"intro",title:"Introduction",markdown:""},s="";for(const i of e.split(` | |
| 64 | +`)){const r=i.match(/^\s*(`{3,}|~{3,})/)?.[1];r&&(s?r[0]===s[0]&&r.length>=s.length&&(s=""):s=r);const a=!s&&i.match(/^#{1,6}\s+(.+?)\s*#*$/);if(a){o.markdown&&t.push(o);const l=a[1].toLowerCase().replace(/[^\p{L}\p{N}_-]+/gu,"-").replace(/^-|-$/g,"")||"section",c=n.get(l)??0;n.set(l,c+1),o={id:c?`${l}-${c}`:l,title:a[1],markdown:""}}o.markdown+=`${o.markdown?` | |
| 65 | +`:""}${i}`}return o.markdown&&t.push(o),t}function D$(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%4294967291;return t.toString(36)}function Hb(e,t){const n=[...new Set(Pd(t))],o=t.trim().toLowerCase();return e.map(s=>{const i=[s.id,s.id.replace(/\.md$/,""),s.title,...s.componentIds??[],...s.topics??[]].map(f=>f.toLowerCase()),r=i.includes(o)?1e3:0,a=Fb(s.markdown).map(f=>{const p=new Set(Pd(f.markdown)),g=new Set(Pd(`${s.title} ${s.id} ${f.title} ${i.join(" ")}`));return{section:f,score:r+n.reduce((h,m)=>h+(p.has(m)?1:0)+(g.has(m)?10:0),0)}}).sort((f,p)=>p.score-f.score),l=a[0],c=l?.section.markdown??"";let d=Math.min(c.length,3200);d<c.length&&/[\uD800-\uDBFF]/.test(c[d-1])&&d--;const u=c.slice(0,d);return{...Bb(s),score:l?.score??0,section:l?.section.id,excerpt:u,truncated:(l?.section.markdown.length??0)>u.length,sections:a.slice(0,2).map(f=>({id:f.section.id,title:f.section.title}))}}).filter(s=>s.score>0).sort((s,i)=>i.score-s.score).slice(0,4)}function Gb(e,t,n,o){const s=e.find(p=>p.id===t);if(!s)throw new Error("Unknown help document.");const i=Fb(s.markdown),r=n?i.find(p=>p.id===n):null;if(n&&!r)throw new Error("Unknown help section.");const a=r?.markdown??s.markdown,l=D$(`${t} | |
| 66 | +${s.version??""} | |
| 67 | +${n??""} | |
| 68 | +${a}`);let c=0;if(o){const p=o.match(/^([a-z0-9]+):(\d+)$/);if(!p||p[1]!==l||Number(p[2])>=a.length)throw new Error("Invalid or stale help cursor; read the document again.");c=Number(p[2])}let d=Math.min(a.length,c+12e3);d<a.length&&/[\uD800-\uDBFF]/.test(a[d-1])&&d--;const u=new URL(t,"https://mio.invalid/"),f=[...s.markdown.matchAll(/\]\(([^)\s]+)(?:\s+[^)]*)?\)/g)].map(p=>{try{const g=new URL(p[1],u);return g.origin===u.origin?decodeURIComponent(g.pathname.slice(1)):""}catch{return""}}).filter(p=>e.some(g=>g.id===p));return{...Bb(s),section:n,markdown:a.slice(c,d),truncated:d<a.length,cursor:d<a.length?`${l}:${d}`:null,sections:i.map(p=>({id:p.id,title:p.title})),links:[...new Set(f)]}}function R$(e){return["search_help","read_help"].map(t=>{const n=t==="search_help"?"query":"id";return{name:t,effect:"read",description:t==="search_help"?"Search local help by document, topic or exact component ID. Returns section IDs and explicit truncation.":"Read a document or section. Follow cursor with the same id and section until truncated is false.",parameters:{type:"object",properties:{[n]:{type:"string"},...t==="read_help"?{section:{type:"string"},cursor:{type:"string"}}:{}},required:[n],additionalProperties:!1},validate:o=>{if(!(Object.keys(o).every(i=>(t==="read_help"?["id","section","cursor"]:["query"]).includes(i)&&typeof o[i]=="string"&&o[i].length<=500)&&typeof o[n]=="string"))return!1;if(t==="read_help")try{Gb(e,o.id,o.section,o.cursor)}catch(i){return{ok:!1,retryable:!0,errors:[{code:"help_location",path:"$",message:i.message,suggestion:"Use search_help to find a current document and section."}]}}return!0},run:o=>t==="search_help"?Hb(e,o.query):Gb(e,o.id,o.section,o.cursor)}})}const zb=Object.freeze({prompt:16e3,transcript:96e3,tools:96e3,request:22e4}),jb=e=>new TextEncoder().encode(e).byteLength;class x$ extends Error{constructor(t,n,o){super(`MIO ${t} budget exceeded (${n}/${o} UTF-8 bytes). Use a compact draft reference or smaller edit; no document was truncated.`),this.scope=t,this.usedBytes=n,this.limitBytes=o,this.code="mio_request_budget",this.name="MioBudgetError",this.remainingBytes=Math.max(0,o-n)}}const M$=e=>JSON.stringify(e).replace(/\//g,"\\/").replace(/[^\x00-\x7f]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`);function Vb(e){const t={prompt:e.prompt,transcript:e.transcript,tools:M$(e.tools),request:JSON.stringify(e)};for(const n of Object.keys(t)){const o=jb(t[n]);if(o>zb[n])throw new x$(n,o,zb[n])}}function jr(e,t){return new zr([{code:e,path:"$",message:t}])}function Kb(e){if(!Array.isArray(e)||!e.length||e.length>20)throw new Error("Invalid MIO validation feedback.");return e.map(t=>{if(!t||typeof t.code!="string"||typeof t.path!="string"||typeof t.message!="string")throw new Error("Invalid MIO validation feedback.");return{code:t.code.slice(0,80),path:t.path.slice(0,300),message:t.message.slice(0,1e3),...typeof t.suggestion=="string"?{suggestion:t.suggestion.slice(0,1e3)}:{}}})}function W$(e,t,n){if(typeof e!="string"||jb(e)>96e3)throw jr("argument_budget","Provide JSON arguments within 96,000 UTF-8 bytes; use a draft reference or a smaller patch for larger documents.");let o;try{o=JSON.parse(e)}catch{throw jr("invalid_json","Provide a valid JSON object for the tool arguments.")}if(!o||typeof o!="object"||Array.isArray(o))throw jr("invalid_envelope","Expected an object containing the advertised argument properties.");const s=t.validate(o,n);if(s===!1)throw jr("invalid_arguments",`Arguments do not satisfy ${t.name}; check its schema and live options.`);if(s!==!0&&s?.ok!==!0)throw!s||s.ok!==!1||typeof s.retryable!="boolean"?new Error("Invalid MIO validator result."):new zr(Kb(s.errors),s.retryable);return o}function $d(e){return Array.isArray(e)?`[${e.map($d).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${$d(e[t])}`).join(",")}}`:JSON.stringify(e)}function P$(){let e=[];return{read:()=>e.map(t=>({...t,...t.actionIds?{actionIds:[...t.actionIds]}:{}})),write:t=>{e=t.slice(-40).map(n=>({...n,...n.actionIds?{actionIds:[...n.actionIds]}:{}}))},clear:()=>{e=[]}}}class $${constructor(t,n,o,s=P$()){this.context=t,this.transport=n,this.active=o,this.conversation=s,this.disposed=!1,this.pending=null,this.abortTurn=null,this.thinkingListeners=new Set,this.operations=new L$(t),this.responseActions=new N$(t,()=>!this.disposed&&o(),()=>s.read())}subscribeThinking(t){return this.thinkingListeners.add(t),t(this.pending!==null),()=>{this.thinkingListeners.delete(t)}}notifyThinking(){for(const t of this.thinkingListeners)ko(t,this.pending!==null)}cancel(){this.responseActions.cancel(),this.pending?.abort(),this.abortTurn?.(),this.abortTurn=null,this.pending=null,this.notifyThinking()}dispose(){this.disposed=!0,this.responseActions.dispose(),this.cancel(),this.conversation.clear(),this.thinkingListeners.clear()}async ask(t){if(this.disposed)throw new Error("This MIO window session is disposed.");if(this.pending)throw new Error("MIO is already answering.");if(!t.trim()||t.length>4e3)throw new Error("Write a message of 1–4000 characters.");const n=new AbortController,{signal:o}=n,s=crypto.randomUUID();let i=0,r=0,a=0,l=!1,c,d="failed",u=null;const f=()=>({turnId:s,windowId:this.context.windowId,revision:c,signal:o,limits:ft,validationFailures:r,validationRemaining:Math.max(0,ft.validationFailures-r)}),p=()=>{const W=this.operations.list().filter(U=>U.turnId===s);return{...f(),status:d,reads:a,rejected:r,calls:i,confirmedWrites:W.filter(U=>U.status==="confirmed").length,unknownWrites:W.filter(U=>U.effect==="write"&&(U.status==="unknown"||U.status==="running")).length}},g=()=>{l||(l=!0,d="aborted",u?.context.effect==="write"&&this.operations.record(u.context,u.name,"unknown"),ko(this.context.onTurnAbort,f()))},h=()=>{if(o.aborted||!this.active())throw n.abort(),g(),new DOMException("The window context changed.","AbortError")};this.pending=n,this.abortTurn=g,this.notifyThinking();const m=[...this.conversation.read().slice(-39),{role:"user",text:t,id:crypto.randomUUID()}];this.conversation.write(m),this.responseActions.prune();const _=W=>{const U={role:"assistant",text:W,id:crypto.randomUUID()},F=this.responseActions.create(Object.freeze({messageId:U.id,summary:Object.freeze(p()),operations:Object.freeze(this.operations.list().filter(K=>K.turnId===s).map(K=>Object.freeze(K)))}));if(F.length&&(U.actionIds=F),this.disposed||this.pending!==n){this.responseActions.prune();return}this.conversation.write([...m,U].slice(-40)),this.responseActions.prune()},I=[],O=new Set,$=new Map,S=()=>[...R$(this.context.documents),...this.context.abilities()].filter(W=>!W.allowed||W.allowed()),R=(W,U,F,K)=>{r++,this.operations.record(U,F,"rejected");const Q=Kb(W.errors);if(I.push(JSON.parse(JSON.stringify({name:F,callId:U.callId,effect:"none",status:"rejected",result:{effect:"none",status:"rejected",errors:Q,data:K,retryable:W.retryable,validationRemaining:Math.max(0,ft.validationFailures-r)}}))),!W.retryable)throw new Error(`MIO validation is terminal: ${W.message}`);if(r>=ft.validationFailures)throw new Error("MIO validation retry budget exhausted; no further candidates will run in this turn.")};try{h(),c=this.context.revision?.(),ko(this.context.onTurnBegin,f());for(let W=0;W<ft.rounds;W++){h();const U=S();if(new Set(U.map(C=>C.name)).size!==U.length)throw new Error("MIO ability names must be unique within a window.");c=this.context.revision?.();const F=await this.context.prompt();h();const K={messages:m.slice(-20).map(({role:C,text:D})=>({role:C,text:D})),help:Hb(this.context.documents,t),outcomes:I},Q={prompt:F,transcript:JSON.stringify(this.context.compactHistory?this.context.compactHistory(structuredClone(K),f()):K),tools:U.map(({name:C,description:D,parameters:V,effect:j})=>({name:C,description:`[Effect: ${j??"write"}] ${D}`,parameters:V}))};Vb(Q),h();const Z=await this.transport(Q,o);if(h(),!Array.isArray(Z.calls)||Z.calls.length>ft.calls)throw new Error("Invalid MIO tool response.");if(!Z.calls.length){if(typeof Z.message!="string"||!Z.message.trim())throw new Error("MIO returned no answer.");return d="completed",_(Z.message),Z.message}for(const C of Z.calls){if(h(),i>=ft.calls)throw new Error("MIO reached its action limit. Review the changes before continuing.");i++;const D=S().find(y=>y.name===C.name);if(!D||!U.some(y=>y.name===C.name))throw new Error("MIO requested an unavailable action.");c=this.context.revision?.();const V=`${s}:${i}`,j={...f(),callId:V,idempotencyKey:V,effect:D.effect??"write"};let te;try{te=W$(C.arguments,D,j)}catch(y){if(y instanceof zr){R(y,j,C.name);break}throw y}const N=$d([C.name,te]);if(j.effect==="write"&&O.has(N))throw new Error("MIO repeated an action; stopped to avoid replaying a write.");if(j.effect!=="write"){const y=($.get(N)??0)+1;if($.set(N,y),y>ft.repeatedReads)throw new Error("MIO repeated-read budget exhausted.")}if(h(),D.allowed&&!D.allowed())throw new Error("MIO requested an unavailable action.");j.effect==="write"&&O.add(N),u={context:j,name:C.name},this.operations.record(j,C.name,"running");try{if(h(),D.allowed&&!D.allowed())throw new Error("MIO requested an unavailable action.")}catch(y){throw u=null,this.operations.record(j,C.name,"rejected"),y}let L;try{L=await D.run(te,o,j)}catch(y){throw this.operations.record(j,C.name,j.effect==="write"?"unknown":"rejected"),u=null,y}const M=Ub(L);if(M?.effect==="none"&&M.status==="rejected"){this.operations.record(j,C.name,"rejected"),u=null,O.delete(N),h();const y=D.history?D.history({name:C.name,callId:V,args:te,result:M},j):M.data;R(new zr(M.errors,M.retryable),j,C.name,y);break}if(M?.effect==="none"&&M.status==="completed")this.operations.record(j,C.name,"completed"),u=null;else if(j.effect==="write"){const y=!M&&!!L&&typeof L=="object"&&L.saved===!0,E=M?.effect==="write"&&M.status==="confirmed"?M.receipt:void 0;if(this.operations.record(j,C.name,E||y?"confirmed":"unknown",E??(y?V:void 0)),u=null,!E&&!y)throw new Error("MIO write outcome is unknown; inspect its status before making another change.")}else this.operations.record(j,C.name,"completed"),j.effect==="read"&&a++,u=null;h();const P={name:C.name,callId:V,args:te,result:L},H=D.history?D.history(P,j):{result:L},z=this.operations.list().find(y=>y.callId===V);I.push(JSON.parse(JSON.stringify({...H,name:C.name,callId:V,effect:M?.effect??j.effect,status:z?.status,receipt:z?.receipt})))}}throw new Error("MIO reached its action limit. Review the changes before continuing.")}catch(W){if(this.pending===n){const U=W instanceof Error?W.message:String(W);_(`${U} ${T$(p())}`)}throw W}finally{ko(this.context.onTurnEnd,p()),this.pending===n&&(this.pending=null,this.abortTurn=null,this.notifyThinking())}}}function U$(e){return async(t,n)=>{Vb(t);const o=window.wp?.os?.config;if(!o?.aiSearchUrl||!o.restNonce)throw new Error("Enable the AI assistant in Preferences → Features and connect a provider.");const s=o.aiSearchUrl.replace(/\/ai\/search(?=\?|$)/,"/mio/turn");if(s===o.aiSearchUrl)throw new Error("MIO transport URL is unavailable.");const i=await Ae(s,{method:"POST",credentials:"same-origin",cache:"no-store",signal:n,headers:{"Content-Type":"application/json","X-WP-Nonce":o.restNonce},body:JSON.stringify(t)},{windowId:e,source:"mio/window"}),r=await i.json();if(!i.ok){const a=mt(i.status,r);throw a.serverMessage?a:mt(i.status,r,"MIO could not reach the AI provider.")}return r}}class B${constructor(t){this.options=t,this.residents=new Map,this.attachmentObserver=new MutationObserver(()=>{for(const n of this.residents.values())(!n.context.host.isConnected||!n.frame.isConnected)&&n.dispose?.()}),this.owner=null,this.chat=null,this.chatPlacement=null,this.thinkingOwner=null,this.revision=0,this.transitioning=!1,this.targetLayer=null,this.moving=Promise.resolve(),this.animation=null,this.deskPosition=null;for(const n of["os-window-focused","os-window-closed"])document.addEventListener(n,()=>this.refresh());for(const n of[v.WINDOW_MINIMIZED,v.WINDOW_RESTORED,v.DESKTOP_SWITCHED,v.WINDOW_DESKTOP_CHANGED])ee(n,"openstation/mio-residency",()=>this.refresh())}canChat(){return this.options.enabled()&&(this.options.chatAvailable?.()??!0)}getWindowId(){return this.owner?.id??null}register(t,n){const o=document.getElementById(`wp-window-${t}`),s=o?.querySelector(".os-window__body");if(!o||!s||!n.host.isConnected||!s.contains(n.host)||!n.title.trim()||typeof n.prompt!="function")throw new Error("MIO requires an explicit context belonging to a live window body.");if(this.residents.has(t))throw new Error("This window already registered MIO. Dispose its lease before replacing it.");const i=document.createElement("div");i.className="os-mio-residence",i.hidden=!0,o.appendChild(i);const r=()=>{i.style.top=`${s.offsetTop}px`,i.style.left=`${s.offsetLeft}px`,i.style.width=`${s.clientWidth}px`,i.style.height=`${s.clientHeight}px`},a=new ResizeObserver(r);a.observe(s),r();const l=document.createElement("os-button");l.className="os-mio-chat-launcher",l.hidden=!this.canChat(),l.setAttribute("variant","ghost"),l.textContent=b("Ask MIO"),l.setAttribute("aria-haspopup","dialog"),i.appendChild(l);const c={enabled:n.enabled!==!1,thinking:!1,calloutVisible:!1,id:t,context:n,frame:i,button:l,observer:a,session:new $$({...n,windowId:t},U$(t),()=>this.canChat()&&c.enabled&&this.owner===c&&this.options.focused()===t&&n.host.isConnected)};c.callout=new A$(n.host,i,this.options.handle,p=>{c.calloutVisible=p,this.syncVisibility()}),this.residents.set(t,c),this.attachmentObserver.observe(document.body,{childList:!0,subtree:!0});const d=p=>{this.residents.get(t)!==c||c.enabled===p||(c.enabled=p,p||c.session.cancel(),this.refresh(),A("os.mio.window-enabled-changed",{windowId:t,enabled:p}))};c.toggle=I$(t,()=>({enabled:c.enabled,available:this.options.enabled(),thinking:c.thinking}),()=>d(!c.enabled)),c.session.subscribeThinking(p=>{c.thinking=p,c.toggle?.update(),this.syncThinking()});const u=async()=>{if(!n.host.isConnected||!this.canChat()||!c.enabled||this.options.focused()!==t||this.residents.get(t)!==c||(await this.options.ready(),await window.wp?.os?.loadComponents(["os-button","os-textarea"]),await this.moving,!n.host.isConnected||!this.canChat()||!c.enabled||this.owner!==c||this.options.focused()!==t))return;this.closeChat(),this.chat=window.openStationMountMioChat?.(i,n.title,c.session,()=>this.closeChat(!0))??null,l.hidden=this.chat!==null,c.callout?.setActive(!1),this.syncVisibility();const p=i.querySelector(".os-mio-chat");p&&(this.chatPlacement=C$(i,p,this.options.handle))};l.addEventListener("click",()=>{u().catch(p=>{l.textContent=p instanceof Error?p.message:b("MIO could not open.")})});const f=()=>{if(this.residents.get(t)!==c)return;this.residents.delete(t),c.session.dispose(),c.callout?.dispose(),c.toggle?.dispose(),a.disconnect(),this.refresh();const p=this.options.layer();p&&i.contains(p)&&(this.options.shell.appendChild(p),delete p.dataset.mioWindow,delete p.dataset.mioThinking),i.remove(),this.residents.size||this.attachmentObserver.disconnect()};return c.dispose=f,this.refresh(),{showCallout:p=>c.callout?.show(p),clearCallout:()=>c.callout?.clear(),isEnabled:()=>c.enabled,setEnabled:d,openChat:u,getOperations:()=>c.session.operations.list(),inspectOperation:(p,g=new AbortController().signal)=>c.session.operations.inspect(p,g),dispose:f}}closeChat(t=!1){this.chatPlacement?.close(t),this.chatPlacement=null,this.chat?.destroy(),this.chat=null,this.owner&&(this.owner.button.hidden=!this.canChat(),t&&(this.owner.button.shadowRoot?.querySelector("button")??this.owner.button).focus()),this.syncCallouts()}syncVisibility(){const t=this.options.layer();t&&(t.dataset.mioVisible=String(this.owner?!!this.chat||this.owner.calloutVisible:(this.options.held?.()??!1)||(this.options.wallpaperVisible?.()??!0)))}syncCallouts(){for(const t of this.residents.values())t.callout?.setActive(this.options.enabled()&&t.enabled&&this.owner===t&&!this.chat&&!this.transitioning);this.syncVisibility()}syncThinking(){const t=this.owner?.thinking&&this.options.enabled()&&this.owner.enabled?this.owner.id:null,n=this.options.layer();n&&(n.dataset.mioThinking=String(t!==null)),this.thinkingOwner!==t&&(this.thinkingOwner&&A("os.mio.thinking-changed",{windowId:this.thinkingOwner,thinking:!1}),this.thinkingOwner=t,t&&A("os.mio.thinking-changed",{windowId:t,thinking:!0}))}refresh(){const t=this.options.enabled();!this.canChat()&&this.chat&&this.closeChat();for(const c of this.residents.values())c.toggle?.update(),c.button.hidden=!this.canChat()||c===this.owner&&this.chat!==null,this.canChat()||c.session.cancel();if(!t)for(const c of this.residents.values())c.frame.hidden=!0;const n=t&&!this.options.held?.()?this.options.focused():null,o=n?this.residents.get(n)??null:null,s=o?.enabled&&o.context.host.isConnected?o:null,i=this.options.layer();if(this.owner===s&&i===this.targetLayer){this.syncVisibility();return}this.targetLayer=i;const r=this.owner;this.transitioning=!0,this.closeChat(),r?.session.cancel(),this.owner=s,this.syncCallouts(),this.syncThinking();const a=++this.revision;this.animation?.cancel(),this.animation=null,this.options.handle()?.setAnimating(!1),s&&i&&!i.dataset.mioWindow&&(this.deskPosition=this.options.handle()?.getPosition()??null),s&&(s.frame.hidden=!1,s.button.hidden=!this.canChat());const l=async()=>{const c=async(d,u)=>{if(!i?.animate||window.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;const f=this.options.handle()?.getPosition(),p=i.getBoundingClientRect();i.style.transformOrigin=f?`${f.x-p.left}px ${f.y-p.top}px`:"50% 50%",this.animation=i.animate([{transform:`scale(${d})`,opacity:d},{transform:`scale(${u})`,opacity:u}],{duration:150,easing:"ease-in-out",fill:"forwards"}),await this.animation.finished};try{if(await c(1,0),a!==this.revision)return;for(const d of this.residents.values())d.frame.hidden=d!==s;if(i){i.style.opacity="0",this.animation?.cancel(),this.animation=null,(s?.frame??this.options.shell).appendChild(i),s?(i.dataset.mioWindow=s.id,i.dataset.mioThinking=String(s.thinking)):(delete i.dataset.mioWindow,delete i.dataset.mioThinking);const d=i.getBoundingClientRect(),u=s?{x:d.right-82,y:d.bottom-95}:this.deskPosition;u&&this.options.handle()?.setPosition(u.x,u.y)}A("os.mio.owner-changed",{windowId:s?.id??null,previousWindowId:r?.id??null}),this.options.handle()?.setAnimating(!document.hidden),await c(0,1)}catch{}finally{a===this.revision&&(this.animation?.cancel(),this.animation=null,i?.style.removeProperty("opacity"),this.transitioning=!1,this.syncCallouts(),this.options.handle()?.setAnimating(!document.hidden))}};this.moving=l()}}const qb={appearance:{radius:56,bodyColor:789263,bodyAlpha:1,hueStart:296.5,hueSpan:-52.5,hueAngle:225,hueDrift:0,hueSpin:0,hueLoop:!0,saturation:1,lightness:.75,iridescence:0,outlineWidth:4,linerWidth:2,linerColor:16776191,glow:10,glowBlur:!0,eyeColor:16776191,eyeScale:.3},physics:{points:12,shapePreset:"blob",shapeLobes:3,shapeAmount:1,shapeAngle:0,shapeShuffle:60,radialStiffness:460,edgeStiffness:540,bendStiffness:170,pressure:2400,damping:9,airDamping:.5,magnetStrength:2200,magnetRange:260,magnetGrip:.24,magnetDamping:7,floatAmplitude:10,floatSpeed:1.1,idleWobble:.085,idleWobbleSpeed:.55,speedStretch:.3,friction:.86,restitution:.2,dragStiffness:480,throwBoost:1,minStretch:.55,maxStretch:1.7,minAngularGap:.25,limitIterations:3,dragMaxAccel:9e3,subStep:1/240,maxSubSteps:8}},ie={radius:[16,220],bodyAlpha:[0,1],hueStart:[-720,720],hueSpan:[-360,360],hueDrift:[-180,180],hueAngle:[-360,360],hueSpin:[-180,180],saturation:[0,1],lightness:[.15,1],iridescence:[0,2],outlineWidth:[.5,24],linerWidth:[0,12],glow:[0,20],eyeScale:[.05,.6],points:[12,128],shapeLobes:[0,8],shapeAmount:[0,1.4],shapeAngle:[-360,360],shapeShuffle:[0,3600],radialStiffness:[0,2e3],edgeStiffness:[0,4e3],bendStiffness:[0,2e3],pressure:[0,8e3],damping:[0,30],airDamping:[0,20],magnetStrength:[0,8e3],magnetRange:[0,2e3],magnetGrip:[0,.6],magnetDamping:[0,40],floatAmplitude:[0,200],floatSpeed:[0,20],idleWobble:[0,.4],idleWobbleSpeed:[0,8],speedStretch:[0,.8],friction:[0,1],restitution:[0,1],dragStiffness:[1,4e3],throwBoost:[0,4],minStretch:[.1,1],maxStretch:[1,4],minAngularGap:[0,.9],limitIterations:[0,8],dragMaxAccel:[100,2e5],subStep:[1/1e3,1/30],maxSubSteps:[1,32]};function re(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function Ud(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 Yb(e,t){return typeof e=="boolean"?e:t}const F$=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function H$(e,t){return F$.includes(e)?e:t}function Vs(e,t=qb){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:re(o.radius,t.appearance.radius,ie.radius),bodyColor:Ud(o.bodyColor,t.appearance.bodyColor),bodyAlpha:re(o.bodyAlpha,t.appearance.bodyAlpha,ie.bodyAlpha),hueStart:re(o.hueStart,t.appearance.hueStart,ie.hueStart),hueSpan:re(o.hueSpan,t.appearance.hueSpan,ie.hueSpan),hueDrift:re(o.hueDrift,t.appearance.hueDrift,ie.hueDrift),hueLoop:Yb(o.hueLoop,t.appearance.hueLoop),hueAngle:re(o.hueAngle,t.appearance.hueAngle,ie.hueAngle),hueSpin:re(o.hueSpin,t.appearance.hueSpin,ie.hueSpin),saturation:re(o.saturation,t.appearance.saturation,ie.saturation),lightness:re(o.lightness,t.appearance.lightness,ie.lightness),iridescence:re(o.iridescence,t.appearance.iridescence,ie.iridescence),outlineWidth:re(o.outlineWidth,t.appearance.outlineWidth,ie.outlineWidth),linerWidth:re(o.linerWidth,t.appearance.linerWidth,ie.linerWidth),linerColor:Ud(o.linerColor,t.appearance.linerColor),glow:re(o.glow,t.appearance.glow,ie.glow),glowBlur:Yb(o.glowBlur,t.appearance.glowBlur),eyeColor:Ud(o.eyeColor,t.appearance.eyeColor),eyeScale:re(o.eyeScale,t.appearance.eyeScale,ie.eyeScale)},r={points:Math.round(re(s.points,t.physics.points,ie.points)),shapePreset:H$(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(re(s.shapeLobes,t.physics.shapeLobes,ie.shapeLobes)),shapeAmount:re(s.shapeAmount,t.physics.shapeAmount,ie.shapeAmount),shapeAngle:re(s.shapeAngle,t.physics.shapeAngle,ie.shapeAngle),shapeShuffle:re(s.shapeShuffle,t.physics.shapeShuffle,ie.shapeShuffle),radialStiffness:re(s.radialStiffness,t.physics.radialStiffness,ie.radialStiffness),edgeStiffness:re(s.edgeStiffness,t.physics.edgeStiffness,ie.edgeStiffness),bendStiffness:re(s.bendStiffness,t.physics.bendStiffness,ie.bendStiffness),pressure:re(s.pressure,t.physics.pressure,ie.pressure),damping:re(s.damping,t.physics.damping,ie.damping),airDamping:re(s.airDamping,t.physics.airDamping,ie.airDamping),magnetStrength:re(s.magnetStrength,t.physics.magnetStrength,ie.magnetStrength),magnetRange:re(s.magnetRange,t.physics.magnetRange,ie.magnetRange),magnetGrip:re(s.magnetGrip,t.physics.magnetGrip,ie.magnetGrip),magnetDamping:re(s.magnetDamping,t.physics.magnetDamping,ie.magnetDamping),floatAmplitude:re(s.floatAmplitude,t.physics.floatAmplitude,ie.floatAmplitude),floatSpeed:re(s.floatSpeed,t.physics.floatSpeed,ie.floatSpeed),idleWobble:re(s.idleWobble,t.physics.idleWobble,ie.idleWobble),idleWobbleSpeed:re(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,ie.idleWobbleSpeed),speedStretch:re(s.speedStretch,t.physics.speedStretch,ie.speedStretch),friction:re(s.friction,t.physics.friction,ie.friction),restitution:re(s.restitution,t.physics.restitution,ie.restitution),dragStiffness:re(s.dragStiffness,t.physics.dragStiffness,ie.dragStiffness),throwBoost:re(s.throwBoost,t.physics.throwBoost,ie.throwBoost),minStretch:re(s.minStretch,t.physics.minStretch,ie.minStretch),maxStretch:re(s.maxStretch,t.physics.maxStretch,ie.maxStretch),minAngularGap:re(s.minAngularGap,t.physics.minAngularGap,ie.minAngularGap),dragMaxAccel:re(s.dragMaxAccel,t.physics.dragMaxAccel,ie.dragMaxAccel),limitIterations:Math.round(re(s.limitIterations,t.physics.limitIterations,ie.limitIterations)),subStep:re(s.subStep,t.physics.subStep,ie.subStep),maxSubSteps:Math.round(re(s.maxSubSteps,t.physics.maxSubSteps,ie.maxSubSteps))};return{appearance:i,physics:r}}const Xb="desktop-mode-mio-position",Zb="os-mio",G$="os-mio-toggle";class z${constructor(t){this.layer=null,this.handle=null,this.mounting=null,this.parked=null,this.summoned=!1,this.heldSpot=null,this.generation=0,this.loading=null,this.look=dc(),this.options=t,this.residency=new B$({shell:t.shell,focused:t.focusedWindow??(()=>null),layer:()=>this.layer,handle:()=>this.handle,enabled:()=>this.enabled,chatAvailable:t.chatAvailable,wallpaperVisible:t.wallpaperVisible,held:()=>this.summoned,ready:()=>this.mount()}),ee("os.mio.owner-changed","openstation/mio-held-spot",()=>this.applyHeldSpot()),this.enabled=t.enabled,this.saved=t.enabled,this.look=gh(t.savedLook),this.config=this.resolveConfig()}boot(){this.enabled&&this.mount()}setAnchor(t){this.heldSpot=t,this.handle?.setAnchor?.(t,!0)}syncEnabled(t){this.saved=t,this.setEnabled(t||this.summoned,!1),this.residency.refresh()}async summon(){this.summoned=!0,this.handle?.setFloating?.(!0),await this.setEnabled(!0,!1),this.residency.refresh()}dismiss(){this.summoned&&(this.summoned=!1,this.heldSpot=null,this.handle?.setFloating?.(!1),this.setEnabled(this.saved,!1),this.residency.refresh())}refreshWindowAvailability(){this.residency.refresh()}api(){return{registerWindow:(t,n)=>this.residency.register(t,n),getWindowId:()=>this.residency.getWindowId(),isEnabled:()=>this.enabled,enable:()=>this.setEnabled(!0),disable:()=>{this.setEnabled(!1)},toggle:()=>this.setEnabled(!this.enabled),getPosition:()=>this.handle?.getPosition()??null,setPosition:(t,n)=>this.handle?.setPosition(t,n),getConfig:()=>this.config,setConfig:t=>{this.config=Vs(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=s0(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=Vs({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=dc(),this.config=this.resolveConfig(),this.handle?.applyConfig(this.config),this.commitLook()}}}async setEnabled(t,n=!0){if(t===this.enabled){n&&this.summoned&&(this.summoned=!1,this.handle?.setFloating?.(!1),this.saved=t,this.options.persist(t));return}this.enabled=t,this.generation++,n&&(this.saved=t,this.summoned=!1,this.handle?.setFloating?.(!1),this.options.persist(t)),A(t?"os.mio.enabled":"os.mio.disabled",{}),A(v.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount()}resolveConfig(){const t=Vs(this.options.serverConfig,qb),n=J("os.mio.config",t),o=Vs(n,t);return Vs({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(Zb);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=Zb,n.className="os-mio",n.dataset.mioVisible=String(this.options.wallpaperVisible?.()??!0),n.setAttribute("aria-hidden","true"),this.options.shell.appendChild(n),this.layer=n,n}mount(){if(this.mounting?.generation===this.generation)return this.mounting.promise;const t=this.mountInstance().finally(()=>{this.mounting?.promise===t&&(this.mounting=null)});return this.mounting={generation:this.generation,promise:t},t}async mountInstance(){const t=this.generation;if(this.handle)return;const n=this.parked;if(n){this.parked=null,n.layer.style.removeProperty("display"),n.handle.applyConfig(this.config),n.handle.setAnimating(!0),this.handle=n.handle,this.layer=n.layer,this.residency.refresh(),this.applyHeldSpot();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:j$(),savePosition:i=>{this.residency.getWindowId()||Jb(i)}});if(!s){this.layer?.remove(),this.layer=null;return}if(t!==this.generation||!this.enabled){const i=this.layer;this.layer=null,s.setAnimating(!1),i?(i.style.display="none",this.parked={handle:s,layer:i}):s.destroy();return}this.handle=s,this.residency.refresh(),this.applyHeldSpot()}applyHeldSpot(){this.handle?.setFloating?.(this.summoned),this.summoned&&this.heldSpot&&this.handle?.setAnchor?.(this.heldSpot,!0)}unmount(){const t=this.residency.getWindowId()!==null;this.residency.closeChat();const n=this.handle,o=this.layer;if(this.handle=null,this.layer=null,this.residency.refresh(),!n||!o){o?.remove();return}const s=n.getPosition();s&&!t&&Jb(s),n.setAnimating(!1),o.style.display="none",this.parked={handle:n,layer:o}}loadBundle(){if(typeof window.openStationMountMio=="function")return Promise.resolve();if(!this.loading){if(!this.options.bundleUrl)return Promise.reject(new Error("No Mio bundle URL in the shell config."));this.loading=pe(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function j$(){try{const e=window.localStorage.getItem(Xb);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 Jb(e){try{window.localStorage.setItem(Xb,JSON.stringify(e))}catch{}}const Bd="--os-admin-bar-height",V$="wpadminbar";function K$(e){const t=e.getBoundingClientRect();return t.height<=0||t.top<0?null:Math.round(t.bottom*100)/100}function q$(e={}){const t=e.bar===void 0?document.getElementById(V$):e.bar,n=e.root??document.documentElement,o={refresh:()=>{},destroy:()=>{}};if(!t)return o;let s,i=!1;const r=()=>{if(i)return;const c=K$(t);c!==s&&(s=c,c===null?n.style.removeProperty(Bd):n.style.setProperty(Bd,`${c}px`))};let a=null;typeof ResizeObserver<"u"&&(a=new ResizeObserver(r),a.observe(t,{box:"border-box"}));let l=null;return typeof MutationObserver<"u"&&document.body&&(l=new MutationObserver(r),l.observe(document.body,{attributes:!0,attributeFilter:["class"]})),window.addEventListener("resize",r),r(),{refresh:r,destroy:()=>{i=!0,a?.disconnect(),l?.disconnect(),window.removeEventListener("resize",r),n.style.removeProperty(Bd)}}}const Y$="New: ",X$=b("Edit this workspace…"),Z$=b("New workspace…"),Qb=b("Keep this desk"),eE=b("Make this workspace open the way the desk is now — these windows where they are, these widgets, these apps.");function J$(e,t,n=()=>{},o=()=>!1){const s=()=>{const i=e.manager.getActiveDesktopId(),r=c=>e.manager.getAll().filter(d=>(d.config.desktopId||i)===c).length,a=c=>c===i?b("You are here"):le(b("%d open"),r(c)),l=e.manager.getDesktops().map(c=>({label:c.label,description:a(c.id),icon:c.profile?.icon||"dashicons-desktop",run:()=>e.manager.switchDesktop(c.id)}));for(const c of Go())l.push({label:`${Y$}${c.label}`,description:c.description,icon:c.icon,run:()=>{_i(e,{preset:c.id})}});return l.push({label:Z$,description:b("Blank, or set up for a job — the wizard asks."),icon:"dashicons-plus-alt2",run:n}),l.push({label:X$,description:b("Name, apps, widgets, look and windows."),icon:"dashicons-admin-generic",run:()=>t(e.manager.getActiveDesktopId())}),l.push({label:Qb,description:eE,icon:"dashicons-saved",run:()=>{o(e.manager.getActiveDesktopId())}}),l};Xn({slug:"keep-desk",label:Qb,description:eE,icon:"dashicons-saved",run(i,r){if(!o(e.manager.getActiveDesktopId()))return b("There is no desk to keep.");r.close()}}),Xn({slug:"workspace",label:b("Workspace"),description:b("Switch, create or edit a workspace."),hint:"[name]",icon:"dashicons-desktop",suggest(i){const r=i.trim().toLowerCase();return s().filter(c=>!r||c.label.toLowerCase().includes(r)).slice(0,12).map(c=>({value:c.label,label:c.label,description:c.description,icon:c.icon}))},run(i,r){const a=i.trim();if(!a)return b("Type a workspace name to switch to it, or pick a template to create one.");const l=a.toLowerCase(),c=s(),d=c.find(u=>u.label.toLowerCase()===l)??c.find(u=>u.label.toLowerCase().includes(l));if(!d)return le(b("No workspace matching **%s** — try `/workspace` alone to see them all."),a);d.run(),r.close()}})}let tE=0;function nE(){return window.openStationWorkspaceWizard??null}function Q$(){return window.openStationConfig?.workspaceWizardBundleUrl??""}function oE(e){const t=nE();if(t){t.openWorkspaceWizard(e);return}const n=Q$();if(!n)return;const o=++tE;pe(n).then(()=>{o===tE&&nE()?.openWorkspaceWizard(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] workspace-wizard bundle failed to load; wizard suppressed:",s)})}function e2(e,t,n=()=>({}),o=()=>{},s=()=>!1){return{list:()=>e.manager.getDesktops(),active:()=>{const i=e.manager.getActiveDesktopId();return e.manager.getDesktops().find(r=>r.id===i)??null},getProfile:i=>Jt(e.manager,i),setProfile:(i,r)=>Un(e,i,r),create:i=>_i(e,i),switchTo:i=>e.manager.switchDesktop(i),arrange:i=>ip(e.manager,i),provision:(i,r)=>Ya(e,i,r),capture:i=>Xa(e.manager,i),captureAppearance:n,edit:t,openCreator:o,saveDesk:s,presets:Go,registerPreset:ep,unregisterPreset:Ka}}const sE="desktop-mode/workspace-presets";let Vr=null;const _n=new Set;function t2(e){const t=AI.includes(e.layout)?e.layout:"free";return{id:e.id,label:e.label||e.id,description:e.description||"",icon:e.icon||"dashicons-desktop",color:e.color||"",apps:Array.isArray(e.apps)?e.apps.slice():[],widgets:Array.isArray(e.widgets)?e.widgets.slice():[],appearance:sp(e.appearance??{}),windows:Array.isArray(e.windows)?e.windows.map(n=>({...n})):[],layout:t,order:typeof e.order=="number"?e.order:0}}function n2(e){if(!Array.isArray(e))return;const t=new Set(e.map(o=>o.id).filter(Boolean)),n=new Set(Go().filter(o=>!_n.has(o.id)).map(o=>o.id));for(const o of e)!o?.id||n.has(o.id)||(ep(t2(o)),_n.add(o.id));for(const o of[..._n])t.has(o)||(Ka(o),_n.delete(o));Vr=t}function o2(){return pt(v.WORKSPACE_PRESETS,sE,e=>Vr?e.filter(t=>_n.has(t.id)||Vr?.has(t.id)):e),()=>{FE(v.WORKSPACE_PRESETS,sE),Vr=null;for(const e of _n)Ka(e);_n.clear()}}function s2(){return document.fullscreenElement!==null}function i2(){if(s2()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function iE(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 r2(e){const t=document.createElement("section");if(t.className="os-shortcuts__section",e.heading){const c=document.createElement("h2");c.className="os-shortcuts__heading",c.textContent=e.heading,t.appendChild(c)}const n=document.createElement("div");n.className="os-shortcuts__scroller";const o=document.createElement("table");o.className="os-shortcuts__table";const s=e.headers??{},i=["key","outside","inside","showDesktop"],r=document.createElement("thead"),a=document.createElement("tr");for(const c of i){const d=document.createElement("th");d.scope="col",d.textContent=s[c]??"",a.appendChild(d)}r.appendChild(a),o.appendChild(r);const l=document.createElement("tbody");for(const c of e.rows??[]){const d=document.createElement("tr"),u=document.createElement("td");if(u.className="os-shortcuts__key-cell",u.appendChild(iE(c.keys??[])),c.note){const f=document.createElement("span");f.className="os-shortcuts__note",f.textContent=c.note,u.appendChild(f)}d.appendChild(u);for(const f of["outside","inside","showDesktop"]){const p=document.createElement("td");p.textContent=c[f]??"",d.appendChild(p)}l.appendChild(d)}return o.appendChild(l),n.appendChild(o),t.appendChild(n),t}function a2(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(iE(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 c2(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(r2(n.contextual)),n.general&&t.appendChild(a2(n.general)),e.appendChild(t)}const Fd="openstation-shortcuts",l2=`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 d2(e){e({id:Fd,baseId:Fd,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:l2,native:!0,render:c2,width:760,height:560,minWidth:480,minHeight:360})}const rE="openstation-rebrand",u2=1200,f2="a[href], button:not([disabled])";async function p2(e){const t=e.seenIntrosUrl;if(t)try{await Ae(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:rE})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function h2(){const e=document.createElement("div");e.className="os-announce",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","os-announce-title"),e.setAttribute("aria-describedby","os-announce-desc");const t=document.createElement("div");t.className="os-announce__card",e.appendChild(t);const n=document.createElement("div");n.className="os-announce__hero",t.appendChild(n);const o=document.createElement("span");o.className="os-announce__eyebrow";const s=document.createElement("span");s.className="os-announce__eyebrow-dot",s.setAttribute("aria-hidden","true"),o.appendChild(s),o.appendChild(document.createTextNode(b("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=b("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=b("The beginning of a new identity."),n.appendChild(r);const a=document.createElement("div");a.className="os-announce__body",t.appendChild(a);const l=document.createElement("p");l.id="os-announce-desc",l.textContent=b("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),a.appendChild(l);const c=document.createElement("p");c.textContent=b("This update also comes with a new default theme that we hope you enjoy."),a.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=b("Everything is already set up. You don't need to install any new plugins, so you can keep using the same features as before."),a.appendChild(d);const u=document.createElement("div");u.className="os-announce__actions",t.appendChild(u);const f=document.createElement("button");return f.type="button",f.className="os-announce__btn os-announce__btn--primary",f.dataset.rebrandDismiss="",f.textContent=b("Got it"),u.appendChild(f),e}async function m2(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(rE))return;await new Promise(c=>window.setTimeout(c,u2));const n=h2(),o=n.querySelector(".os-announce__card"),i=document.activeElement;let r=!1;const a=()=>{r||(r=!0,document.removeEventListener("keydown",l,!0),n.remove(),i?.focus?.(),p2(t))};function l(c){if(!n.isConnected){document.removeEventListener("keydown",l,!0);return}if(c.key==="Escape"){c.preventDefault(),a();return}if(c.key!=="Tab")return;const d=Array.from(n.querySelectorAll(f2));if(d.length===0)return;const u=d[0],f=d[d.length-1],p=n.ownerDocument.activeElement;c.shiftKey&&(p===u||!n.contains(p))?(c.preventDefault(),f.focus()):!c.shiftKey&&(p===f||!n.contains(p))&&(c.preventDefault(),u.focus())}n.addEventListener("click",c=>{o&&!o.contains(c.target)&&a()});for(const c of n.querySelectorAll("[data-rebrand-dismiss]"))c.addEventListener("click",a);document.addEventListener("keydown",l,!0),document.body.appendChild(n),n.querySelector(".os-announce__btn--primary")?.focus()}const g2="shell-tour",w2="os-shell-tour-start",y2="openstation-shell-tour";function aE(){return window.openStationUsageFeedback??null}function v2(){return window.openStationConfig?.usageFeedbackBundleUrl??""}async function b2(e){let t=aE();if(!t){const n=v2();if(!n)return!1;try{await pe(n)}catch(o){return typeof console<"u"&&console.warn("[openstation] usage-feedback bundle failed to load; prompt suppressed:",o),!1}t=aE()}return t?(t.showUsageFeedbackPrompt(e),!0):!1}const Kr="usage-feedback",E2=4e3;async function _2(e){const t=e.seenIntrosUrl;if(t)try{await Ae(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:Kr})},{source:"desktop-mode/usage-feedback",silent:!0})}catch{}}async function S2(e){const{config:t}=e,n=t.usageFeedback;if(!n||t.seenIntros?.includes(Kr))return;const o=e.showPrompt??b2;await new Promise(i=>window.setTimeout(i,E2)),!await o({restUrl:n.restUrl,restNonce:t.restNonce??"",onAnswered:i=>{if(t.seenIntros=[...t.seenIntros??[],Kr],i==="sent"){ue({message:b("Thank you! That really helps.")});return}_2(t)}})&&typeof console<"u"&&console.warn("[openstation] usage feedback prompt could not be shown.")}const qr="openstation/shell-tour-loader",k2=1200;let Hd=0;function Yr(){return window.openStationShellTour??null}function I2(e,t){return!(e.shellTour===!1||e.soloWindow||e.seenIntros?.includes(g2)||e.rebrandNotice||e.usageFeedback&&!e.seenIntros?.includes(Kr)||t())}function Xr(e){if(e.isMobile())return;const t=Yr();if(t){t.startShellTour(e);return}const n=e.config.shellTourBundleUrl??"";if(!n)return;const o=++Hd;pe(n).then(()=>{o!==Hd||e.isMobile()||Yr()?.startShellTour(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] shell-tour bundle failed to load; tour suppressed:",s)})}function A2(e){const t=new AbortController,{signal:n}=t;let o=0;const s=()=>{t.abort(),window.clearTimeout(o),jt(v.DESKTOP_ICON_CLICKED,qr),jt(v.MODE_CHANGED,qr)};return document.addEventListener(w2,()=>Xr(e),{signal:n}),document.addEventListener("os-intros-reset",()=>Xr(e),{signal:n}),ee(v.DESKTOP_ICON_CLICKED,qr,i=>{i?.id===y2&&Xr(e)}),ee(v.MODE_CHANGED,qr,i=>{i?.mode==="mobile"&&(Hd++,Yr()?.endShellTour())}),I2(e.config,e.isMobile)&&(o=window.setTimeout(()=>{(e.updateNoticeShown??Promise.resolve(!1)).catch(()=>!1).then(i=>{i||n.aborted||Yr()?.isShellTourRunning()||Xr(e)})},k2)),s}function C2(){const e=window.wp?.os?.refreshMenu;if(typeof e=="function")try{e()}catch{}}const L2="(display-mode: standalone)";function cE(e,t){return e||t?.standalone===!0?"standalone":"browser"}const T2=["auto","desktop","mobile"],Zr={mobile:767,tablet:1024};function Jr(e){return T2.includes(e)?e:"auto"}function N2(e){const t=e&&typeof e=="object"?e:{},n=(i,r)=>{const a=typeof i=="number"?i:Number(i);return Number.isFinite(a)&&a>0?Math.floor(a):r},o=n(t.mobile,Zr.mobile),s=Math.max(o+1,n(t.tablet,Zr.tablet));return{mobile:o,tablet:s}}function lE(e,t="auto",n=Zr){return t==="mobile"?"mobile":t==="desktop"?"desktop":e<=n.mobile?"mobile":e<=n.tablet?"tablet":"desktop"}function O2(e={}){const t=e.root??document.documentElement,n=e.win??window,o=N2({...Zr,...e.breakpoints??{}});let s=Jr(e.preference);const i=new Set,r=()=>typeof n.innerWidth=="number"&&n.innerWidth>0?n.innerWidth:Number.POSITIVE_INFINITY;let a=lE(r(),s,o);iu(t,a);const l=e.nav??(typeof navigator<"u"?navigator:void 0),c=typeof n.matchMedia=="function"?n.matchMedia(L2):null;let d=cE(!!c?.matches,l);ru(t,d);const u=()=>{d=cE(!!c?.matches,l),ru(t,d)},f=()=>{const h=lE(r(),s,o);if(h===a)return;const m={mode:h,previous:a,preference:s};a=h,iu(t,a),A(v.MODE_CHANGED,m),document.dispatchEvent(new CustomEvent("os-mode-changed",{detail:m}));for(const _ of i)try{_(m)}catch(I){console.error("[openstation] mode listener threw:",I)}},p=[];if(typeof n.matchMedia=="function")for(const h of[o.mobile,o.tablet]){const m=n.matchMedia(`(max-width: ${h}px)`);typeof m.addEventListener=="function"?m.addEventListener("change",f):typeof m.addListener=="function"&&m.addListener(f),p.push(m)}return c&&(typeof c.addEventListener=="function"?c.addEventListener("change",u):typeof c.addListener=="function"&&c.addListener(u)),{api:{get:()=>a,getPreference:()=>s,getBreakpoints:()=>({...o}),isMobile:()=>a==="mobile",getDisplay:()=>d,isStandalone:()=>d==="standalone",subscribe(h,m){return i.add(h),m?.immediate&&h({mode:a,previous:a,preference:s}),()=>{i.delete(h)}}},setPreference(h){const m=Jr(h);m!==s&&(s=m,f())},dispose(){for(const h of p)typeof h.removeEventListener=="function"?h.removeEventListener("change",f):typeof h.removeListener=="function"&&h.removeListener(f);c&&(typeof c.removeEventListener=="function"?c.removeEventListener("change",u):typeof c.removeListener=="function"&&c.removeListener(u)),i.clear()}}}function D2(e){return Vt(e)||jE(e)}function R2(e={}){const t=e.root??document.documentElement,n=e.doc??document,o=a=>{D2(t)&&a.cancelable&&a.preventDefault()},s=a=>{a.touches?.length>1&&o(a)},i=a=>{a.ctrlKey&&o(a)},r={passive:!1};return n.addEventListener("gesturestart",o,r),n.addEventListener("gesturechange",o,r),n.addEventListener("gestureend",o,r),n.addEventListener("touchmove",s,r),n.addEventListener("wheel",i,r),()=>{n.removeEventListener("gesturestart",o),n.removeEventListener("gesturechange",o),n.removeEventListener("gestureend",o),n.removeEventListener("touchmove",s),n.removeEventListener("wheel",i)}}const Sn="openstation/mobile";function x2(e){const t=Array.isArray(e?.windows)?e.windows:[],n=e?.focused??"",o=t.find(s=>s.id===n);return{restore:o?[o]:[],recents:t.filter(s=>s!==o)}}function M2(e){const{manager:t,mode:n}=e,o=new Map,s=new Map;let i=[];const r=new Set,a=()=>{for(const h of r)h()},l=h=>{if(!n.isMobile())return;const m=t.getById(h);if(!(!m||m.isMinimized()||m.isMaximized()||m.isFullscreen())){if(!o.has(m.id)){const _=m.getSnapshot();o.set(m.id,{x:_.x,y:_.y,width:_.width,height:_.height,state:_.state,unplaced:!1})}m.maximize()}},c=h=>{if(!n.isMobile())return;const m=t.getById(h);if(!m)return;const _=t.getActiveDesktopId(),I=m.config.desktopId||_;I!==_&&(s.has(h)||s.set(h,I),t.moveWindowToDesktop(h,_))},d=()=>{if(s.size===0)return;const h=new Set(t.getDesktops().map(I=>I.id));for(const[I,O]of s)h.has(O)&&t.moveWindowToDesktop(I,O);s.clear();const m=t.getActiveDesktopId(),_=t.getFocused();if(_&&(_.config.desktopId||m)!==m){const I=[...t.getAll()].reverse().find(O=>(O.config.desktopId||m)===m&&!O.isMinimized());I&&t.focus(I)}},u=h=>{const m=ge();if(m.width<=0||m.height<=0)return null;const _=12,I=Math.min(Math.round(m.width*.8),1200),O=Math.min(Math.round(m.height*.8),800),$=40+h%8*30;return{x:Math.max(m.x+_,Math.min(m.x+$,m.x+m.width-I-_)),y:Math.max(m.y+_,Math.min(m.y+$,m.y+m.height-O-_)),width:I,height:O}};pt(v.WINDOW_GEOMETRY,Sn,(h,m)=>!n.isMobile()||h.state==="minimized"?h:(o.set(m.windowId,{x:h.x,y:h.y,width:h.width,height:h.height,state:h.state??"normal",unplaced:!m.hasSavedGeometry&&!m.callerPinned}),{...h,state:"maximized"}));const f=h=>{const m=h?.windowId;m&&l(m)};ee(v.WINDOW_RESTORED,Sn,f),ee(v.WINDOW_UNMAXIMIZED,Sn,f),ee(v.WINDOW_OPENED,Sn,h=>{const m=h?.windowId;m&&(c(m),l(m))}),ee(v.WINDOW_CLOSED,Sn,h=>{const m=h?.windowId;m&&(o.delete(m),s.delete(m))});const p=n.subscribe(h=>{if(h.mode==="mobile"){for(const _ of t.getAll())c(_.id),l(_.id);return}if(h.previous!=="mobile")return;d();let m=0;for(const _ of t.getAll()){const I=o.get(_.id);if(!(!I||!_.isMaximized())){if(I.unplaced){const O=u(m++);O&&(_._savedGeometry=O)}_.toggleMaximize()}}o.clear()});pt(v.SESSION_SNAPSHOT,Sn,h=>{const m=new Set(h.windows.map(O=>O.id)),_=h.windows.map(O=>{const $=o.get(O.id),S=s.get(O.id);return!n.isMobile()||!$&&!S?O:{...O,...$?{x:$.x,y:$.y,width:$.width,height:$.height,state:$.state,...$.unplaced?{unplaced:!0}:{}}:{},...S?{desktopId:S}:{}}}),I=i.filter(O=>!m.has(O.id));return I.length?{...h,windows:[..._,...I]}:{...h,windows:_}});const g={list:()=>i.slice(),forget(h){const m=i.filter(_=>_.id!==h);m.length!==i.length&&(i=m,a())},open(h){if(g.forget(h.id),h.native)return e.openNative(h.id,h.baseId||h.id,{desktopId:h.desktopId,...h.params?{params:h.params}:{}}),void 0;const m=ar(h.url);t.openNew({id:h.id,baseId:h.baseId||h.id,url:h.url,parentUrl:m?.url??h.url,title:h.title,icon:h.icon||"dashicons-admin-generic",desktopId:h.desktopId,x:h.x,y:h.y,width:h.width,height:h.height,submenu:m?.submenu,selfLabel:m?.selfLabel,multi:!!m?.multi}).then(_=>{for(const I of h.externalTabs??[])_.addExternalTab(I.url,I.label)}).catch(_=>{console.error("[openstation] could not reopen a recent window:",_)})},subscribe(h){return r.add(h),()=>{r.delete(h)}}};return ee(v.WINDOW_OPENED,Sn,h=>{const m=h?.windowId;m&&g.forget(m)}),{recents:g,trimSessionForMobile(h){const{restore:m,recents:_}=x2(h.session);return i=_,a(),{...h,session:{...h.session,windows:m}}},forcedIds:()=>Array.from(o.keys()),foldedIds:()=>Array.from(s.keys()),dispose(){p(),r.clear()}}}let Qr=null;function Gd(){return window.openStationMobile}function W2(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-mobile="1"]'),s=()=>{const a=Gd();if(a){t(a);return}n(new Error("[openstation] mobile bundle loaded but did not set `window.openStationMobile`."))},i=()=>n(new Error("failed to load the mobile bundle"));if(o){Gd()?s():(o.addEventListener("load",s),o.addEventListener("error",i));return}const r=document.createElement("script");r.src=e,r.async=!0,r.dataset.osMobile="1",r.addEventListener("load",s),r.addEventListener("error",i),document.head.appendChild(r)})}function P2(e){const t=Gd();return t?Promise.resolve(t):e?(Qr||(Qr=W2(e).catch(n=>{throw Qr=null,n})),Qr):Promise.reject(new Error("[openstation] no `mobileBundleUrl` in the shell config — is `mobile[.min].js` built and the config key wired?"))}function $2(e){const{manager:t,adminUrl:n,openNative:o}=e;return s=>{if(s.windowId){const u=t.getById(s.windowId);if(u)return u.isMinimized()&&u.restore(),t.focus(u),!0;if(o(s.windowId))return!0}if(s.tile)return s.tile.onOpen(),!0;const i=s.menu?.url||s.entry?.url||"";if(!i)return!1;if(zn(i)||Me(i))return!0;let r;try{r=new URL(i,window.location.origin)}catch{return!1}const a=r.toString(),l=fe(a,n),c=s.menu??ar(a)??null,d=s.icon||c?.icon||"dashicons-admin-generic";return t.open({id:l,baseId:l,url:a,parentUrl:c?.url??a,title:s.title,icon:d.startsWith("dashicons-")||d.startsWith("data:")||/^https?:/.test(d)?d:"dashicons-admin-generic",submenu:c?.submenu,selfLabel:c?.selfLabel,multi:!!c?.multi}),!0}}function U2(){return window.wp?.os?.config??{}}async function B2(e,t){const{restUrl:n,restNonce:o}=U2();if(!n||!e||!(t>0))throw new Error("[openstation] trashByRestPath: missing REST config or target.");const s=await Ae(rt(n,`${e.replace(/\/+$/,"")}/${t}`),{method:"DELETE",credentials:"same-origin",headers:{"X-WP-Nonce":String(o??""),Accept:"application/json"}},{source:"my-wordpress/trash"});if(!s.ok)throw await Nn(s)}const F2=ae("desktop-mode/recycle-bin-payload-handlers",()=>({handlers:new Map}));function dE(){return F2.state.handlers}function H2(e){const t=dE().get(e.type);return t?t.accept(e.data):!1}function G2(e,t){const n=dE().get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}const z2=new Set(["user","attachment"]),zd="data-os-trash-drop-active",Ks="desktop-mode-recycle-bin",j2=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${Ks}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${Ks}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${Ks}"]`},{id:"recycle-bin-window",selector:"[data-os-recycle-bin-root]"}];let uE=!1;const jd=new Map;let fE=null;function V2(e){return e.payload.type==="desktop-file"}function K2(e){return e.payload.type==="shortcut"}function q2(e){if(!e.kind||!e.ref||!e.restPath||z2.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return Number.isFinite(t)&&t>0}function Y2(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:b("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const s=o.data,i=s?.placement;if(!i)return!1;const r=yn(s);return r.length>1?r.every(a=>a.file?.ref!==Ks&&a.canTrash!==!1):i.file?.ref===Ks?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=Tr(s);return i.length>0&&i.every(r=>q2(r))}return H2(o)},onEnter:()=>{n.setAttribute(zd,"")},onLeave:()=>{n.removeAttribute(zd)},onDrop:(o,s)=>{if(n.removeAttribute(zd),V2(o)){xv(yn(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&G2(o,s))&&K2(o)){const r=Tr(o.payload.data).map(l=>({title:l.title??"",icon:l.icon??"",restPath:l.restPath,kind:l.kind,ref:Number.parseInt(l.ref,10)})).filter(l=>!!l.restPath&&Number.isFinite(l.ref)&&l.ref>0);if(r.length===0)return;const a=r.map(l=>ln(Sw({id:l.ref,type:l.kind,title:l.title,icon:l.icon})));Promise.allSettled(r.map((l,c)=>a[c]?B2(l.restPath,l.ref):Promise.reject(new Error("Item is already moving to Trash.")))).then(l=>{const c=l.filter(p=>p.status==="rejected");for(const p of c)console.error("[openstation] recycle-bin: shortcut trash failed:",p.reason);const d=r.filter((p,g)=>l[g]?.status==="fulfilled").reduce((p,g)=>{var h;return(p[h=g.kind]??(p[h]=[])).push(g.ref),p},{}),u=window.wp?.os?.announceContentChange;for(const[p,g]of Object.entries(d))u?.(p,"trashed",g,"recycle-bin");l.forEach((p,g)=>{a[g]?.finish(p.status==="fulfilled")});const f=r.length-c.length;if(f>1||c.length>0){const p=c.length>0?Nv(c[0].reason):"",g={message:c.length>0?`${f} moved to Trash · ${c.length} could not be moved${p?`: ${p}`:""}`:`${f} items moved to Trash`,duration:c.length>0?6e3:4e3};c.length>0&&(g.type=f>0?"warning":"error"),ue(g)}})}}})}function X2(e){if(uE)return;uE=!0;const t=()=>{for(const{id:n,selector:o}of j2){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=jd.get(n);if(!i){r?.deregister(),jd.delete(n);continue}r&&r.el===i||(r?.deregister(),jd.set(n,{el:i,deregister:Y2(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),ee(v.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),ee(v.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){fE=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;fE.observe(n,{childList:!0,subtree:!0})}}function Vd(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function Z2(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function pE(e){return{appliesTo(t){return Vd(t)!==null},accept(t,n){const o=Vd(n);if(!o)return!1;const s=fv({type:e,data:t});return E1(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:b("Send to agent","desktop-mode"),onDrop(t,n,o){const s=Vd(o);if(!s)return;const i=fv({type:t.payload.type,data:t.payload.data}),r=Z2();!i||!r||I1({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let hE=!1;function J2(){hE||(hE=!0,xs("shortcut",pE("shortcut")),xs("desktop-file",pE("desktop-file")))}let mE=!1,kn=0;function Q2(){mE||(mE=!0,Re.contribute("openstation_files_subscribe",()=>{const e=Bt(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:kn,sharesVersion:Br().state.sharesVersion}}),Re.subscribe("openstation_files",e=>{eU(e)}))}function eU(e){const t=e.folders??[];for(const i of t)dd(i,"remote"),i.updatedAtMs>kn&&(kn=i.updatedAtMs);const n=e.placements??[];for(const i of n)cd(i,"remote"),i.updatedAtMs>kn&&(kn=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])ud(i,"remote");for(const i of o.placements??[])Ds(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>kn&&(kn=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&Eb(s),e.truncated){const i=Array.from(Bt().hydratedFolders);for(const r of i)xe(r).then(a=>{Ut(r,a.placements)}).catch(()=>{})}}let gE=!1;const tU=[];function nU(){if(gE)return;gE=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||oU()};tU.push(Zn("os.placement.changed",e),Zn("os.shortcut.changed",e),Zn("os.folder.changed",e))}function oU(){mv().then(t=>{ld(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from(Bt().hydratedFolders);for(const t of e)xe(t).then(n=>{Ut(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const qs="os-wallpaper-menu";let Io=null;function wE(){return Io!==null}let yE=0;function sU(e,t,n,o={}){Ys();const s=++yE;si(()=>s===yE,()=>iU(e,t,n,o))}function iU(e,t,n,o={}){if(n.length===0)return;n=n.slice().sort((u,f)=>{const p=typeof u.sort=="number"?u.sort:100,g=typeof f.sort=="number"?f.sort:100;return p!==g?p-g:u.label.localeCompare(f.label)});const s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(qs),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,a=null;const l=()=>{r&&(r.remove(),r=null,a=null)};for(const u of n){i.set(u.id,u);const f=document.createElement("os-context-menu-option");f.dataset.menuItemId=u.id,f.setAttribute("value",u.id),u.heading&&f.setAttribute("heading",""),u.disabled&&f.setAttribute("disabled",""),u.icon&&f.setAttribute("icon",vE(u.icon));const p=Array.isArray(u.children)&&u.children.length>0;p&&f.setAttribute("has-children",""),f.textContent=u.label,f.addEventListener("mouseenter",()=>{if(p){c(u,f);return}l()}),s.appendChild(f)}s.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=i.get(f.id)??null;if(p){if(Array.isArray(p.children)&&p.children.length>0){if(u.stopPropagation(),a&&a.id===p.id){l();return}const g=s.querySelector(`[data-menu-item-id="${p.id}"]`);g&&c(p,g);return}Ys(),p.onClick(new MouseEvent("click"))}});function c(u,f){l();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(qs,`${qs}--flyout`),p.dataset.parentId=u.id;const g=(u.children??[]).slice().sort((h,m)=>{const _=typeof h.sort=="number"?h.sort:100,I=typeof m.sort=="number"?m.sort:100;return _!==I?_-I:h.label.localeCompare(m.label)});for(const h of g){const m=document.createElement("os-context-menu-option");m.dataset.menuItemId=h.id,m.setAttribute("value",h.id),h.icon&&m.setAttribute("icon",vE(h.icon)),h.disabled&&m.setAttribute("disabled",""),h.checked&&m.setAttribute("checked",""),m.textContent=h.label,m.addEventListener("os-context-menu-pick",_=>{_.stopPropagation(),Ys(),h.onClick(new MouseEvent("click"))}),p.appendChild(m)}document.body.appendChild(p),r=p,a=u,Cy(p,f)}e.appendChild(s),Io=s,Rl(s);const d=Iy(s,{close:()=>Ys(),siblingSelectors:[`.${qs}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),A("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function Ys(){Io&&(document.querySelectorAll(`.${qs}--flyout`).forEach(e=>e.remove()),Io.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),Io.remove(),Io=null,A("os.wallpaper-menu.closed",{}))}function rU(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=>aU(i,e)),o=[...t,...n],s=J("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function aU(e,t){return{id:e.id,label:e.label,icon:e.icon,sort:e.sort,disabled:e.disabled,onClick:()=>{if(e.callbackId){const n=t.serverCallbacks?.[e.callbackId];if(typeof n=="function")return n()}A("os.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function vE(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}function Kd(e){const t=e.dataTransfer?.types;return t?Array.from(t).includes("Files"):!1}function cU(e){if(!e.bundleUrl||Vt())return()=>{};let t=null,n=!1;const o=[],s=()=>{window.removeEventListener("dragenter",r,!0),window.removeEventListener("dragover",a),window.removeEventListener("drop",l)},i=()=>(t||(t=pe(e.bundleUrl).then(()=>{const c=window.openStationFileDrop;if(c){c.boot(e.boot),n=!0,s();for(const d of o.splice(0))c.replayCapturedDrop(d)}}).catch(c=>{t=null,console.warn("[openstation] file-drop bundle failed to load",c),o.length>0&&(o.length=0,ue({message:b("That drop could not be processed — please try again.","desktop-mode")}))})),t),r=c=>{Kd(c)&&i()},a=c=>{!n&&Kd(c)&&(c.preventDefault(),c.dataTransfer&&(c.dataTransfer.dropEffect="copy"))},l=c=>{if(n||!Kd(c))return;const d=c.defaultPrevented;c.preventDefault(),o.push({files:c.dataTransfer?Array.from(c.dataTransfer.files):[],clientX:c.clientX,clientY:c.clientY,target:c.target,alreadyClaimed:d}),i()};return window.addEventListener("dragenter",r,!0),window.addEventListener("dragover",a),window.addEventListener("drop",l),s}const bE=[];let qd=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(qd){Promise.resolve().then(o);return}bE.push(o)}},ready(o){n.whenReady(o)},isReady(){return qd}};t.wp.os=n})();let Yd=[],ea=Number.POSITIVE_INFINITY,Xd=!1;function Ye(e,t=1500){if(Yd.push(e),t<ea&&(ea=t),Xd)return;Xd=!0;const n=()=>{const o=Yd;Yd=[],ea=Number.POSITIVE_INFINITY,Xd=!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:ea}):window.setTimeout(n,0)}function EE(){const e=window.openStationConfig;if(!e)return;Hy(e);const t=document.getElementById("os-area");if(!t)return;const n=m_(window.location.href);if(n)try{window.history.replaceState(window.history.state,"",n)}catch{}kC(e.arrivalDirection==="next"||e.arrivalDirection==="prev"?e.arrivalDirection:null);const o=new cA(t),s=document.getElementById("os-wallpaper"),i=e.pluginUrl||"";let r=null;s&&(r=new mm(s,i));const a=document.getElementById("os-widgets");let l=null;u$(),oC(),a&&(l=new CO(a,i)),dm({id:"pixijs",url:`${i}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const c=new mC(r??new mm(document.createElement("div"),i));c.apply();const d=O2({preference:Jr(c.getOsSettingsSnapshot().mobileLayout??e.mode?.preference),breakpoints:e.mode?.breakpoints});c.subscribeOsSettings(w=>{d.setPreference(Jr(w.mobileLayout))}),R2();const u=M2({manager:o,mode:d.api,openNative:(w,k,B)=>Y(w,k,B)}),f=document.getElementById("os-shell"),p=new z$({shell:f??document.body,focusedWindow:()=>{const w=o.getFocused();return w&&o.isActive(w.id)?w.id:null},bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:c.state.mioEnabled,wallpaperVisible:()=>c.state.mioShowOnWallpaper,chatAvailable:()=>!!(c.state.ai.enabled&&e.aiAssistant?.available&&e.aiAssistant.assistantProviderConfigured),persist:w=>{c.state.mioEnabled=w,c.state.mioApiEnabled=w,c.save()},savedLook:c.state.mioStyle,persistLook:w=>{c.state.mioStyle=w,c.save()}}),g=p.api();if(c.subscribeOsSettings(w=>p.syncEnabled(w.mioEnabled)),document.addEventListener("os-ai-status-changed",()=>p.refreshWindowAvailability()),!d.api.isMobile())p.boot();else{const w=d.api.subscribe(k=>{k.mode!=="mobile"&&(w(),p.boot())})}l&&m$({osSettings:c,layer:l});const h=new oD({aiSearchUrl:e.aiSearchUrl??"",restNonce:e.restNonce,adminUrl:e.adminUrl,isAiSupported:()=>e.aiAssistant?.available===!0,canConnectProvider:()=>!!e.currentUserIsAdmin,isAiAvailable:()=>e.aiAssistant?.available===!0&&e.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>c.getOsSettingsSnapshot().ai.enabled!==!1},e.aiAssistantBundleUrl??"");h.attachAsk(cD({config:()=>e,fallbackContext:()=>({close:()=>h.close(),openInWindow:(w,k,B)=>{o.open({url:w,title:k,icon:B??"dashicons-admin-generic"})},confirm:w=>Qt({message:w})})}));const m=new uR,_=new CR;document.addEventListener(ke.START,w=>{const B=w.detail?.payload;if(!B||B.type!=="shortcut"&&B.type!=="desktop-file")return;const G=B.data?.bridgePayload;G&&m.start(G)}),document.addEventListener(ke.END,()=>{m.end()}),Ye(()=>HR(_)),Ye(()=>nx(o)),window.addEventListener("message",w=>{if(w.origin!==window.location.origin)return;const k=w.data;!k||k.type!=="os-drop-failed"||ue({message:"Could not insert into the editor."})}),py({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>h.open(),close:()=>h.close(),isOpen:()=>h.isOpen}),fA(),ax(),dA(o),yA(o),kA(o,{shouldAsk:()=>c.state.confirmCloseAllWindows,setAsk:w=>{c.state.confirmCloseAllWindows=w,c.save()}}),Ye(()=>{new ON({manager:o,adminUrl:e.adminUrl}).install(),DN(o);const w=new BN({manager:o,adminUrl:e.adminUrl});w.install(),document.addEventListener(Hg,()=>w.install(),{once:!0})}),document.addEventListener("os-open-ai",()=>{wr("desktop-mode-ai-assistant")}),document.addEventListener("click",w=>{const k=w.target;!(k instanceof Element)||!k.closest("#wp-admin-bar-command-palette")||(w.preventDefault(),w.stopImmediatePropagation(),wr("desktop-mode-ai-assistant"))},!0);const I=document.getElementById("os-dock"),O=document.getElementById("os-shell"),$=O?.querySelector(".os-shell__body");let S=null,R=null;const W=(w,k)=>{if(d.api.isMobile()){w.setAppearance?.(null),w.setVisibleWidgets?.(null);return}qa(w,k)},U=(w,k)=>{d.api.isMobile()||Ya(w,k)};let F=!1;const K=()=>sp(c.getOsSettingsSnapshot()),Q=w=>({presets:Go(),apps:w.getNavItems().map(k=>({id:k.id,title:k.title,kind:k.kind,locked:k.locked,url:k.menu?.url||k.entry?.url||void 0,windowId:k.windowId})),widgets:ul().map(k=>({id:k.id,label:k.label||k.id,description:k.description})),enabledWidgetIds:l?.getEnabledIds()??[],wallpapers:cc().map(k=>({id:k.id,label:k.label,preview:k.preview})),accents:li().map(k=>({id:k.id,label:k.label,value:k.value})),resolvePreset:k=>tp(k,w.getNavItems()),captureAppearance:K}),Z=w=>{if(!R)return;const k=R,B=w??_i(k).id;oE({mode:"create",...Q(k),onCreate:G=>{_i(k,{desktopId:B,label:G.label||void 0,...G.preset?{preset:G.preset}:{profile:G.profile??void 0}}),W(k,B),U(k,B)}})},C=(w=o.getActiveDesktopId())=>{if(!R)return!1;const k=S?.getNav();let B;k&&(B=[...k.dock.core,...k.dock.apps,...k.dock.controls,...k.sidebar,...k.desktop].filter(be=>!k.ephemeral.has(be.id)).map(be=>be.id));const G=PI(R,w,{visibleAppIds:B,mountedWidgetIds:l?.getMountedIds()});if(!G)return!1;const me=o.getDesktops().find(ve=>ve.id===w)?.label??"",Xe=o.getAll().filter(ve=>(ve.config.desktopId||w)===w).length,st=G.windows.length;let ne;return Xe>st?ne=le(b("%1$s will open like this — the top %2$d of %3$d windows, where they are."),me,st,Xe):ne=le(b("%1$s will open like this — %2$d windows, where they are."),me,st),ue({message:ne}),!0},D=w=>{if(!R)return;const k=o.getDesktops().find(G=>G.id===w);if(!k)return;const B=R;oE({mode:"edit",desktopId:w,label:k.label,profile:k.profile??op(),...Q(B),onSave:G=>{G.label&&o.renameDesktop(w,G.label),Un(B,w,G.profile)},captureWindows:()=>Xa(o,w),onDelete:o.getDesktops().length>1?()=>o.closeDesktop(w):void 0})},V=w=>w.some(k=>!!k.windowId&&o.getAllByBaseIdOnActiveDesktop(k.windowId).length>0),j=UO({manager:o,appendSystemTile:w=>S?.appendSystemTile(w),removeSystemTile:w=>S?.removeSystemTile(w)}),te=j.sync;b_({getSnapshot:()=>c.getOsSettingsSnapshot(),openById:(w,k)=>j.openById(w,k),openNewById:(w,k)=>j.openNewById(w,k),adminUrl:e.adminUrl});const N=w=>{const k=fe(w,e.adminUrl),B=S?S.getMenuItems():e.dockItems??[];for(const G of B){if(fe(G.url,e.adminUrl)===k)return{title:G.title,icon:G.icon,url:G.url,submenu:G.submenu,selfLabel:G.selfLabel,multi:G.multi};for(const me of G.submenu??[])if(fe(me.url,e.adminUrl)===k)return{title:me.title,icon:G.icon,url:G.url,multi:G.multi}}return null},L=Sc,M=(w,k)=>{const B=e.multisite?.hopUrl;return B?yC({hopUrl:B,restNonce:e.restNonce})(w,k):Promise.resolve(null)};if(VI(()=>e.multisite?QC(e.multisite,{mint:M}):null),document.addEventListener("os-app-effect",w=>{const k=w.detail?.effect;k?.type==="hop"&&e.multisite&&typeof k.site=="string"&&Oc(e.multisite,k.site,{mint:M})}),JC({multisite:()=>e.multisite,isShown:()=>!!document.querySelector(".os-area--overview .os-site-switcher"),mint:M}),e.hopLinkOffer&&tL(e.hopLinkOffer,{confirm:w=>Qt(w),post:eL(e.restNonce)}),GA({adminUrl:e.adminUrl,deriveSlug:w=>fe(w,e.adminUrl),openWindow:w=>{o.open(w)},findDockEntry:N,openOtherAdmin:L}),ht({id:"desktop-mode-dashboard",nativeWindowId:"desktop-mode-dashboard",matches:(w,k)=>LA(k),enabled:w=>w.stationHomeEnabled===!0}),ht({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(w,k)=>{if(!k.pathname.endsWith("/edit.php"))return!1;const B=k.searchParams.get("post_type");return!B||B==="post"},enabled:w=>w.nativePostsEnabled===!0}),ht({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(w,k)=>k.pathname.endsWith("/edit.php")?k.searchParams.get("post_type")==="page":!1,enabled:w=>w.nativePagesEnabled===!0}),ht({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(w,k)=>k.pathname.endsWith("/users.php"),enabled:w=>w.nativeUsersEnabled===!0}),ht({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(w,k)=>{if(v_(k))return!1;const B=k.pathname;return B.endsWith("/profile.php")?!0:B.endsWith("/user-edit.php")?k.searchParams.has("user_id"):!1},enabled:w=>w.nativeUsersEnabled===!0,params:(w,k)=>{const B=parseInt(k.searchParams.get("user_id")??"0",10);return{userId:B>0?B:0}}}),ht({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(w,k)=>k.pathname.endsWith("/edit-comments.php"),enabled:w=>w.nativeCommentsEnabled===!0,params:(w,k)=>{const B=parseInt(k.searchParams.get("p")??"0",10);return{post:B>0?B:0}}}),ht({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(w,k)=>{const B=k.pathname;return B.endsWith("/plugins.php")||B.endsWith("/plugin-install.php")},enabled:w=>w.nativePluginsEnabled===!0,params:(w,k)=>({tab:k.pathname.endsWith("/plugin-install.php")?"browse":"installed"})}),I&&O&&$&&e.dockItems){t.classList.add("os-area--with-dock");const w=c.getOsSettingsSnapshot(),k=w.desktopLayout,B=w.dockPlacement,G=ne=>{gw(t,ne,{openWindow:j.openById,manager:o,deriveWindowId:ve=>fe(ve,e.adminUrl)})};S=QO({shellRoot:O,shellBody:$,bottomDockEl:I,desktopArea:t,windowManager:o,adminUrl:e.adminUrl,renderIcons:G,getSettings:()=>{const ne=c.getOsSettingsSnapshot();return{navPlacement:ne.navPlacement,navOrder:ne.navOrder}},getWorkspaceProfile:()=>d.api.isMobile()?null:DI(o)},k,e.dockItems,e.desktopIcons,B),q$(),Kk({shell:O,shellBody:$,area:t}),vI(o),t0({shellBody:$,getBehaviors:()=>({dock:c.state.dockBehavior,sidebar:c.state.sideDockBehavior})}),eN({bundleUrl:e.dockConstellationBundleUrl??"",deps:{windowManager:o,adminUrl:e.adminUrl,getMenuItems:()=>S?.getMenuItems()??[],getSystemItem:ne=>S?.getSystemTile(ne)??null}}),R={manager:o,getNavItems:()=>S?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:ne=>fe(ne,e.adminUrl),openNative:j.openById,refreshLayout:()=>S?.refresh(),setVisibleWidgets:ne=>l?.setVisibleIds(ne),setAppearance:ne=>c.setWorkspaceAppearance(ne)},o2(),n2(e.workspacePresets),J$(R,D,Z,C),$I({...R,openCreator:Z,openEditor:D}),ee(v.DESKTOP_SWITCHED,"desktop-mode/workspace-provision",ne=>{!R||!ne?.to||(W(R,ne.to),U(R,ne.to))});const me=(ne,ve)=>{if(!R||!ve)return;const be=o.getActiveDesktopId(),Ze=Jt(o,be);if(!Ze||Ze.widgets?.mode!=="only")return;const ni=OI(Ze,ne,ve);ni!==Ze&&Un(R,be,ni)};if(ee(v.WIDGET_ADDED,"desktop-mode/workspace-widgets",ne=>me(ne.id,!0)),R){const ne=o.getActiveDesktopId();W(R,ne),U(R,ne)}const Xe=QD(e.pwa?.appName||"WordPress",ue),st={id:pf,title:"System",icon:HS,navKind:"control",placeable:!0,order:Po.system,onOpen:()=>E(),get submenu(){const ne=[{title:"OpenStation Preferences",url:"",windowId:Ct,onSelect:()=>E()}];return e.homeUrl&&ne.push({title:"View site",url:e.homeUrl}),ne.push({title:"Fullscreen",url:"",onSelect:i2},{title:"Keyboard shortcuts",url:"",windowId:Fd,onSelect:()=>d2(ve=>{o.open(ve)})},{title:"Report a bug",url:"",windowId:Es,onSelect:()=>T()}),!Ww()&&!F&&ne.push({title:Xe.title,url:"",onSelect:Xe.onOpen}),e.logoutUrl&&ne.push({title:"Log out",url:"",onSelect:()=>{window.location.assign(e.logoutUrl)}}),ne},isOpen:()=>V(st.submenu??[])};S.appendSystemTile(st),Pw().then(ne=>{F=ne})}const P="os-settings-layout",H=8e3;function z(w){const k=document.getElementById(w);return k&&!k.closest("[hidden]")?k:null}function y(w,k=performance.now()+H){const B=z(w);if(B){B.scrollIntoView({block:"start",behavior:"instant"});return}performance.now()<k&&requestAnimationFrame(()=>y(w,k))}function E(w={}){const k={extended:"features",effects:"windows"},B=w.tabId?k[w.tabId]:void 0;B&&(w={...w,tabId:B});const G=!!o.getById(Ct);j.openById(Ct,{source:"os-settings",...w.tabId?{params:{tab:w.tabId}}:{}}),w.tabId&&G&&window.wp?.os?.apps?.local(Ct,"tab",{value:w.tabId})}function T(w=Es,k){Vi("desktop-mode-bug-report");const B={id:w,baseId:Es,url:`#${Es}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:G=>ND(G),width:560,height:620,minWidth:420,minHeight:480,...k};k?o.openNew(B):o.open(B)}if(S){if(S.appendSystemTile(jS()),e.multisite){const w=wC(e.multisite,L);w&&S.appendSystemTile(w)}S.appendSystemTile({id:US,title:b("Site assistant"),icon:GS,navKind:"control",placeable:!0,order:Po.assistant,onOpen:()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))}}),S.appendSystemTile({id:G$,title:"Mio",icon:k$,navKind:"control",placeable:!0,order:Po.mio,isOpen:()=>g.isEnabled(),onOpen:()=>{g.toggle()}}),S.appendSystemTile({id:BS,title:"Workspaces",icon:FS,navKind:"control",placeable:!0,order:Po.overview,isOpen:()=>o._overviewActive,onOpen:()=>{o._overviewActive?o.exitOverview():o.enterOverview()}})}const x=S?.getPrimary()??null;te(cw(Array.isArray(e.nativeWindows)?e.nativeWindows:[],e.nativeWindowScriptData));const X=cM(e.session);function Y(w,k,B){const G=k||w;return G==="desktop-mode-dashboard"&&c.getOsSettingsSnapshot().stationHomeEnabled!==!0?!1:G===Es?(T(w,B),!0):B?j.restoreById(w,G,B):j.openById(w)}const ce=typeof e.soloWindow=="string"?e.soloWindow:"";ce&&queueMicrotask(()=>{if(Y(ce))return;const w=ce.startsWith("os-game-")?ce.slice(8):"";if(w){km.launch(w).catch(k=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",k)});return}typeof console<"u"&&console.error(`[openstation] solo window "${ce}" is not registered; nothing to paint.`)});const q=d.api.isMobile()?u.trimSessionForMobile(e):e,se=X&&!ce?dM(o,q,t,Y).catch(w=>{typeof console<"u"&&console.error("[openstation] session restore failed:",w)}):Promise.resolve(),Ee=e.defaultWindow?.enabled!==!1,zt=e.defaultWindow?.url??"",Ne=typeof zt=="string"&&zt.startsWith("native:");let ta=se;if(!ce&&fM({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:X,defaultEnabled:Ee,isNativeDefault:Ne})&&(ta=se.then(()=>uM(o,e).catch(w=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",w)}))),e.landInOverview&&!ce&&ta.then(()=>{o.enterOverview(),tm()}),!ce&&R){const w=R;se.then(()=>{const k=o.getActiveDesktopId();d.api.isMobile()||MI(w,k),W(w,k)})}const Zd=bM(o,e);_M(Zd);const _E=async w=>{try{const k=await zl(o,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:w})},{source:"desktop-mode/default-window"});if(!k.ok)throw await Nn(k);const B=await k.json();e.defaultWindow=B,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:B}))}catch(k){A(v.SHELL_ERROR,{scope:"default-window-save",error:k}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",k)}};if(o.onToggleStartupRequested=w=>{const k=e.defaultWindow,B=!!w.config.native,G=B?`native:${w.id}`:w.getCurrentUrl(),me=B?k?.url===G:cu(k?.url??"")===cu(G),Xe=!!k?.enabled&&me;_E(Xe?null:G)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!X&&Ne){const w=zt.slice(7);queueMicrotask(()=>{Y(w)})}const lU=w=>{S?.appendSystemTile(w)},SE=g$({layer:l});SE(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const Jd=BL({osSettings:c});Jd(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),ee(v.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",w=>{const k=w?.wallpapers;Array.isArray(k)&&Jd(k)});const kE=HL();kE(Array.isArray(e.serverGames)?e.serverGames:[]);const IE=rC();IE(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const AE=nT();AE(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const CE=iT();CE(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const LE=lT();LE(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const TE=hT();TE(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const NE=GT();NE(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const OE=qT();OE(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),JT({manager:o,osSettings:c}),ck({osSettings:c}),FA({manager:o}),YT();{let w=!1;ee(v.WINDOW_LINK_GROUPS_CHANGED,"desktop-mode/window-link-visuals-sentinel",()=>{w||(w=!0,fg().then(k=>{k&&window.openStationWindowLinkVisuals?.start({manager:o,osSettings:c})}).catch(()=>{w=!1}))})}yT({manager:o,openUrl:w=>{if(w.windowId&&j.openById(w.windowId,{source:"related-entities",...w.params?{params:w.params}:{}})||!w.url||Me(w.url))return;const k=fe(w.url,e.adminUrl);o.open({id:k,baseId:k,url:w.url,title:w.label,icon:w.icon||"dashicons-admin-links"})}}),NT({manager:o}),UT({manager:o});const DE=QT();DE(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),oN()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),rN(),aN()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),dN()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),xg(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),_N()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const ei=IN(o);vT(o),Ye(()=>bT()),IA(),ee("os.shell.toast","desktop-mode/shell-toast",w=>{!w||typeof w.message!="string"||ue({message:w.message,type:typeof w.type=="string"?w.type:void 0,action:w.action,duration:w.duration})});const Qd=e,dU=Qd.recycleBinCount;mD(Number(dU)||0,typeof Qd.recycleBinCountUrl=="string"?Qd.recycleBinCountUrl:""),kD({getRecycleBinCount:hD}),window.__openStationConnectionBridge=ei,ee(v.WINDOW_CLOSED,"desktop-mode/connection-cleanup",w=>{w?.windowId&&ei.onWindowClosed(w.windowId)}),ee(v.IFRAME_READY,"desktop-mode/connection-rearm",w=>{w?.windowId&&ei.onIframeReady(w.windowId)});const uU=xO(o),fU=w=>{if(S){S.applyDesktopIcons(w);return}gw(t,w,{openWindow:j.openById,manager:o,deriveWindowId:k=>fe(k,e.adminUrl)})},eu=()=>{S&&r$(S.getNav().desktop,S.getNavItems(),c.getOsSettingsSnapshot().dockPromotedPositions)},pU=aM({layoutDispatcher:S,desktopArea:t,config:e,applyMultisite:w=>{const k=e.multisite;e.multisite=w&&k?{...w,current:k.current,isNetworkAdmin:k.isNetworkAdmin}:w,jo(o)},syncNativeWindows:te,syncServerWidgets:SE,syncServerWallpapers:Jd,syncServerCommands:AE,syncServerSettingsTabs:CE,syncServerTitleBarButtons:LE,syncServerWindowActions:TE,syncServerUnfocusEffects:NE,syncServerWindowLinkRenderers:OE,syncServerDockRailRenderers:DE,syncServerGames:kE,syncServerDesktopThemes:IE,renderIcons:fU,refreshRootPlacements:()=>{xe(0).then(w=>{Ut(0,w.placements)}).catch(()=>{})},syncShortcuts:eu});document.addEventListener(jh,()=>{S&&S.setLayout(S.getLayout());for(const w of o._stack)try{w.repaintWindowControls(),w.repaintThemedChrome()}catch(k){A(v.SHELL_ERROR,{scope:"desktop-theme-repaint",id:w.id,error:k})}}),c.subscribeOsSettings(w=>{if(!S)return;const k=S.getLayout(),B=S.getDockPlacement();S.setDockPlacement(w.dockPlacement),S.setLayout(w.desktopLayout),ti.dock=S.getPrimary(),ti.sideDock=S.getSide(),ti.desktopLayout=w.desktopLayout,ti.dockPlacement=S.getDockPlacement(),k===w.desktopLayout&&B===w.dockPlacement&&S.refresh(),eu(),ev(w.desktopLayout)}),a$(eu),ev(c.getOsSettingsSnapshot().desktopLayout);const ti=s1({manager:o,dock:x,layoutDispatcher:S,osSettings:c,iconsApi:ml,filesApi:Ge,saveSession:Zd,widgetLayer:l,registerWindow:uU,openWindowById:j.openById,openNewWindowById:j.openNewById,loadWindowScriptById:j.loadScriptById,prewarmWindowById:j.prewarmById,placeSystemTile:lU,setDefaultWindow:_E,refreshMenu:pU,openOsSettings:E,aiAssistant:h,dragBridge:m,dragManager:_,connect:ei.connect,getConnection:ei.getConnection,mio:g,mode:d.api,workspaces:e2(R??{manager:o,getNavItems:()=>S?.getNavItems()??[],adminUrl:e.adminUrl,deriveWindowId:w=>fe(w,e.adminUrl),openNative:j.openById,refreshLayout:()=>S?.refresh()},D,K,Z,C),wallpaperSuspend:{suspend:w=>r?.suspend(w),resume:w=>r?.resume(w),isSuspended:()=>r?.isSuspended()??!1},config:e});i1(ti);let Co=null,RE=0;const hU=$2({manager:o,adminUrl:e.adminUrl,openNative:Y}),xE=()=>{const w=++RE;if(!d.api.isMobile()){Co&&(Co.unmount(),Co=null);return}if(Co||!O)return;const k=O;P2(e.mobileBundleUrl??"").then(B=>{w!==RE||!d.api.isMobile()||Co||(Co=B.mount({manager:o,shell:k,area:t,mode:d.api,getNav:()=>S?.getNav()??null,openNavItem:hU,getBadge:G=>Math.max(G.menu?.badge??0,ml.getBadge(G.id)),getPinnedTabIds:()=>{const G=c.getOsSettingsSnapshot().mobileTabs;return Array.isArray(G)&&G.length>0?G:e.mode?.tabBar??[]},subscribeNav:G=>{const me=c.subscribeOsSettings(G);return document.addEventListener("os-layout-changed",G),document.addEventListener("os-registry-changed",G),()=>{me(),document.removeEventListener("os-layout-changed",G),document.removeEventListener("os-registry-changed",G)}},wallpaper:{suspend:G=>r?.suspend(G),resume:G=>r?.resume(G)},openExternal:G=>{window.open(G,"_blank","noopener")},adminUrl:e.adminUrl,renderIcon:(G,me)=>oo(G,me),getArt:G=>ml.getArt(G.id)||x?.getArt(G.id)||"",subscribeArt:G=>_e.subscribe("os/art-changed",()=>G())}))}).catch(B=>{typeof console<"u"&&console.error("[openstation] the phone layer failed to load:",B)})};xE(),d.api.subscribe(xE),d.api.subscribe(w=>{if(w.mode!=="mobile"&&w.previous!=="mobile"||(S?.refresh(),!R))return;const k=o.getActiveDesktopId();W(R,k),U(R,k)}),Ye(()=>X2(_)),Ye(()=>J2()),GL(),nk(),e.gamesEnabled!==!1&&JL({currentUserId:Number(e.currentUserId)||0}),Ye(()=>xx()),Ye(()=>Wx()),Ye(()=>Yx({currentUserId:Number(e.currentUserId)||0})),l$({bundleUrl:e.notesBundleUrl??"",hasNotes:!!e.hasNotes,host:t,config:e,onError:w=>{ue(w)}}),f1({openUrl:({id:w,url:k,title:B,icon:G})=>(Me(k)||o.open({id:w,baseId:w,url:k,title:B,icon:G}),!0),openNativeWindow:w=>j.openById(w),deriveWindowId:w=>fe(w,e.adminUrl)}),sv(e.userFileAssociations??{});const mU=p$({update:e.coreUpdate,openUrl:({url:w,title:k})=>{Me(w)||o.open({id:"update-core",baseId:"update-core",url:w,title:k,icon:"dashicons-update"})}}),ME=({url:w,title:k})=>{if(Me(w))return;const B=fe(w,e.adminUrl);o.open({id:B,baseId:B,url:w,title:k,icon:"dashicons-info"})};Ob({notices:e.coreNotices,openUrl:ME}),Ob({notices:e.pluginNotices,openUrl:ME,keyPrefix:"plugin-notice"}),m2({config:e});let tu=null;if(A2({config:e,windowManager:o,isMobile:()=>d.api.isMobile(),updateNoticeShown:mU,openPalette:()=>wr("desktop-mode-ai-assistant"),openLayoutSettings:()=>{const w=!!o.getById(Ct);return E({tabId:"appearance"}),y(P),{windowId:Ct,wasAlreadyOpen:w}},findLayoutTarget:()=>z(P)??document.querySelector(`.os-dock__item[data-system-id="${pf}"]`),closeWindow:w=>o.getById(w)?.close(),closePalette:()=>{const w=hy().find(k=>k.id==="desktop-mode-ai-assistant");w?.isOpen()&&(w.close(),lo(w.id,!1))},mio:{size:()=>d.api.isMobile()?0:g.getConfig().appearance.radius*2,summon:()=>{p.summon().then(()=>p.setAnchor(tu))},follow:w=>{tu=w,p.setAnchor(w)},release:()=>{tu=null,p.setAnchor(null),p.dismiss()}},refreshDesktopIcons:C2,findAssistant:()=>document.querySelector("#desktop-mode-ai-assistant:not([hidden]) .os-ai__panel"),openFallbackWindow:()=>{const w=`${e.adminUrl}edit.php`,k=fe(w,e.adminUrl);o.open({id:k,baseId:k,url:w,title:b("Posts"),icon:"dashicons-admin-post"})}}),S2({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){hv({baseUrl:e.filesUrl,nonce:e.restNonce});const w=document.getElementById("os-area");if(w){const k=Jv(w,0),B=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},G=setTimeout(B,2e3);k.hydrated.then(()=>{clearTimeout(G),B()})}}Ye(()=>Q2()),Ye(()=>nU()),Ye(()=>dx()),A(v.COMPONENTS_REGISTERED,{tags:[...Er]}),sx(),oR(e,ue,async()=>{await Zd.flush(),window.location.reload()});const WE=()=>{QE(e.shellOverlaysBundleUrl??""),ZE(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(WE,{timeout:1500}):window.setTimeout(WE,0),A(v.INIT,{config:e}),qd=!0;const gU=bE.splice(0);for(const w of gU)try{w()}catch(k){A(v.SHELL_ERROR,{scope:"when-ready-cb",error:k}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",k)}if(c.apply(),!d.api.isMobile())l?.hydrate();else{const w=d.api.subscribe(k=>{k.mode!=="mobile"&&(w(),l?.hydrate())})}window.addEventListener("pagehide",()=>{r?.teardownActive(),l?.disposeAll()}),SM(),Zx(o,e);const PE=(w,k=!0)=>{const B=Ge.store.getState().placementsByFolder.get(0)??[],G=w(B),me=ge(t),Xe=Math.max(1,Math.floor((me.height-16)/110)),st=new Set;let ne=0;for(const ve of G){const be=Ht(16+Math.floor(ne/Xe)*96,16+ne%Xe*110,st,me);st.add(`${be.col},${be.row}`),ne++,!(ve.x===be.x&&ve.y===be.y)&&(Ge.store.upsertPlacement({...ve,x:be.x,y:be.y,sortOrder:ne}),!(!k||Or(ve))&&yo(ve.id,{x:be.x,y:be.y,sortOrder:ne}).catch(Ze=>{console.error("[openstation] relayout persist failed",Ze)}))}},$E=w=>k=>{const B=k.slice();switch(w){case"name-asc":B.sort((G,me)=>G.file.title.localeCompare(me.file.title));break;case"name-desc":B.sort((G,me)=>me.file.title.localeCompare(G.file.title));break;case"date-asc":B.sort((G,me)=>G.updatedAtMs-me.updatedAtMs);break;case"date-desc":B.sort((G,me)=>me.updatedAtMs-G.updatedAtMs);break}return B},nu="desktop-mode:root-sort-mode",wU=w=>w==="name-asc"||w==="name-desc"||w==="date-asc"||w==="date-desc";let na=(()=>{try{const w=window.localStorage.getItem(nu);return wU(w)?w:null}catch{return null}})();const UE=w=>{na=w;try{w?window.localStorage.setItem(nu,w):window.localStorage.removeItem(nu)}catch{}};ee("os.files.tile-manually-placed","desktop-mode/root-sort-clear",w=>{w?.folderId===0&&UE(null)});{let w=ge(t);const k=()=>{if(!na)return;const B=ge(t);B.width===w.width&&B.height===w.height||(w=B,PE($E(na),!1))};typeof ResizeObserver<"u"&&new ResizeObserver(k).observe(t),Fo(k)}let BE=!1;t.addEventListener("pointerdown",w=>{w.isPrimary&&(BE=w.target===t)}),t.addEventListener("click",w=>{c.state.showDesktopOnWallpaperClick&&w.target===t&&BE&&(t.classList.contains("os-area--overview")||wE()||_.recentlyEndedDrag()||Ax()||o.toggleShowDesktop())}),t.addEventListener("contextmenu",w=>{if(w.target!==t)return;w.preventDefault();const k=w.clientX,B=w.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(wE()){Ys();return}const G={x:k,y:B},me=()=>{const ne=t.getBoundingClientRect(),ve=Math.max(0,G.x-ne.left),be=Math.max(0,G.y-ne.top),Ze=Bv(Ge.store.getState().placementsByFolder.get(0)??[]);return Ht(ve,be,Ze,ge(t))},Xe=(ne,ve)=>{xP({title:ne,description:ve,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:be,url:Ze})=>{const ni=me(),yU=await Os({type:"link",ref:Ze,parentId:0,x:ni.x,y:ni.y,meta:be?{name:be}:void 0});Ge.store.upsertPlacement(yU)}})},st=rU({createFolder:()=>{vd({onSubmit:async ne=>{const ve=await rd({name:ne}),be=me(),Ze=await Os({type:"folder",ref:String(ve.id),parentId:0,x:be.x,y:be.y});Ge.store.upsertFolder(ve),Ge.store.upsertPlacement(Ze)}})},createUrl:()=>Xe("New URL","Opens the URL in a new browser tab."),addWidget:()=>l?.openPicker(),toggleShowDesktop:()=>o.toggleShowDesktop(),openOsSettings:()=>E(),sortIcons:ne=>{UE(ne),PE($E(ne))},currentSortMode:na,includeShowDesktop:!c.state.showDesktopOnWallpaperClick,position:{x:k,y:B},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??[]});sU(document.body,{x:k,y:B},st)})()}),cU({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:X}}))}return S$(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",EE):EE(),oa.clampGeometryToViewport=By,Object.defineProperty(oa,Symbol.toStringTag,{value:"Module"}),oa}({}); | |