| 1 |
var openStation=function(cr){"use strict";var dr=typeof document<"u"?document.currentScript:null;function mb(){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={registerEntityKind:(i,r)=>{const l={unregister:null},a={kind:i,renderer:r,slot:l};return o.push(a),()=>{if(l.unregister){l.unregister(),l.unregister=null;return}const c=o.indexOf(a);c!==-1&&o.splice(c,1)}},__pendingKinds:o};n.myWordpress=s}mb();function Lt(){const e=window.wp?.hooks;if(!e)throw new Error("[openstation] `window.wp.hooks` is not available. The plugin declares `wp-hooks` as a script dependency; if you are seeing this error, verify the enqueue order.");return e}function zn(e,t,n,o){Lt().addFilter(e,t,n,o)}function Y(e,t,n,o){Lt().addAction(e,t,n,o)}function ur(e,t){return Lt().removeAction(e,t)}function G(e,t,...n){return Lt().applyFilters(e,t,...n)}function L(e,...t){Lt().doAction(e,...t)}function Kc(e){return Lt().didAction(e)}function gb(){return Lt()}const _={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_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 wb=0;function Yc(e){if(Kc(_.INIT)>0){Promise.resolve().then(e);return}const t=`desktop-mode/when-ready-${++wb}`;Y(_.INIT,t,e)}function yb(){return Kc(_.INIT)>0}const bb=["post_type","page","taxonomy","path","post","c","tag_ID","item","p"];function Xc(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 ae(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 a of bb){const c=n.searchParams.get(a);c&&r.set(a,c)}const l=r.toString();return Xc(l?`${i}?${l}`:i)}let o=e.replace(t,"");return o.startsWith("/")&&(o=o.substring(1)),Xc(o)}function Zc(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 Jc(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 Ls(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 Qc(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 l of r){if(o.has(l.nodeName.toLowerCase())){l.remove();continue}for(const a of Array.from(l.attributes)){const c=a.name.toLowerCase(),d=a.value.trim().toLowerCase();if(c.startsWith("on")){l.removeAttribute(a.name);continue}d.startsWith("javascript:")&&l.removeAttribute(a.name)}s(l)}};s(n);for(const i of Array.from(n.attributes)){const r=i.name.toLowerCase(),l=i.value.trim().toLowerCase();(r.startsWith("on")||l.startsWith("javascript:"))&&n.removeAttribute(i.name)}return n.outerHTML}let Jt=null;function Ts(){return!!window.openStationWindowSystem}function ed(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-window-system="1"]'),s=()=>{if(Ts()){t();return}n(new Error("[openstation] window-system bundle loaded but did not register `window.openStationWindowSystem`."))};if(o){Ts()?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 _b(){return window.openStationConfig?.windowSystemBundleUrl??""}function Eb(e){!e||Ts()||Jt||(Jt=ed(e).catch(t=>{Jt=null,typeof console<"u"&&console.warn("[openstation] window-system preload failed; will retry on first open():",t)}))}async function kb(e){if(Ts())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 Jt||(Jt=ed(e)),await Jt,window.openStationWindowSystem}const Sb="os-confirm-dialog";let Qt=null;function Gn(){return typeof window.customElements<"u"&&!!window.customElements.get(Sb)}function td(e){return new Promise((t,n)=>{const o=document.querySelector('script[data-os-shell-overlays="1"]'),s=()=>{if(Gn()){t();return}n(new Error("[openstation] shell-overlays bundle loaded but did not register the overlay components."))};if(o){Gn()?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 Ab(e){!e||Gn()||Qt||(Qt=td(e).catch(t=>{Qt=null,typeof console<"u"&&console.warn("[openstation] shell-overlays preload failed; will retry on first overlay use:",t)}))}function fr(e){return Gn()||!e?Promise.resolve():(Qt||(Qt=td(e)),Qt)}function pr(){return window.openStationConfig?.shellOverlaysBundleUrl??""}function Ns(e,t){const n=pr();if(Gn()||!n){t();return}fr(n).then(()=>{e()&&t()}).catch(o=>{typeof console<"u"&&console.warn("[openstation] shell-overlays failed to load; menu/dialog suppressed:",o)})}const nd="desktop-mode";function hr(){return window.wp?.i18n}function k(e,t=nd){return hr()?.__(e,t)??e}function en(e,t,n,o=nd){return hr()?._n(e,t,n,o)??(n===1?e:t)}function le(e,...t){const n=hr()?.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 Cb(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 Ib(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 xb(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 l=Math.min(s,Math.ceil(e/r));if(r*l<e)continue;const a=t/r/Math.max(1,n/l),c=Math.abs(a-o),d=r*l-e,u=c+d*.05;u<i.score&&(i={cols:r,rows:l,score:u})}return{cols:i.cols,rows:i.rows}}function mr(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,l=24,a=34,c=(t.width-r*2-l*(s-1))/s,d=(t.height-r*2-n-l*(i-1))/i,u=Math.max(40,d-a);return e.map((f,p)=>{const g=p%s,m=Math.floor(p/s),h=t.left+r+g*(c+l),b=t.top+n+r+m*(d+l)+a,y=f.element.offsetWidth,C=f.element.offsetHeight,w=Math.min(c/y,u/C),E=y*w,T=C*w;return{win:f,x:h+(c-E)/2,y:b+(u-T)/2,scale:w}})}const od=120,sd="__openStationSharedStores";function Lb(){const e=window;let t=e[sd];return t||(t=new Map,e[sd]=t),t}function re(e,t){const n=Lb();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 l=r;for(const a of Object.keys(l))delete l[a];Object.assign(l,i)}else o.state=i;o.listeners.clear()}};return s}const jn=re("desktop-mode/dock-rail-registry",()=>({registry:new Map,listeners:new Set,activeId:"default"})),at=jn.state.registry,gr=jn.state.listeners,Tb=/^[a-z0-9_-]+$/;function id(e){if(!e||typeof e!="object")throw new TypeError("[openstation] registerDockRailRenderer: renderer must be an object.");if(typeof e.id!="string"||!Tb.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).`);at.set(e.id,e),Ds()}function Nb(e){at.delete(e)&&Ds()}function Db(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(at.entries()))o.owner===e&&(at.delete(n),t++);return t>0&&Ds(),t}function Rb(e){return at.get(e)}function Ob(){return Array.from(at.values())}function Mb(e){return gr.add(e),()=>{gr.delete(e)}}function Pb(e){jn.state.activeId!==e&&(jn.state.activeId=e,Ds())}function wr(){return at.get(jn.state.activeId)??at.get("default")??at.values().next().value}function Ds(){const e=Array.from(gr);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] dock-rail-renderer listener threw:",n)}}function Tt(e,t){if(!e||typeof e!="object")return["def (not an object)"];const n=e,o=[];for(const s of t)s.valid(n)||o.push(`${s.field} (${s.message})`);return o}class Wb 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 Wb(e,t,n)}function rd(e,t,n){typeof console>"u"||console.warn(`[openstation] ${e} registration rejected — fields: `+t.join(", ")+".",n)}const yt=[[0,0],[100,0],[100,100],[0,100]],$b=48,Ub=80,yr=6,br=8,ad=4,ld=3,cd=64,vr=105,bt=2;function dd(e){return`${Math.round(e*1e3)/1e3}%`}function vt(e){return e.slice().reverse()}function Vn(e,t,n,o){return[[e,t],[n,t],[n,o],[e,o]]}function Fb(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 Qe(e,t=[]){const n=[],o=s=>{n.push(`${dd(s[0])} ${dd(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 ud(e){return Qe(yt,[vt(Fb(50,50,e,$b))])}function fd(e){return Qe(yt,[vt(Vn(50-e,-bt,50+e,100+bt))])}function pd(e){const t=100/yr,n=[];for(let o=0;o<yr;o++){const s=o*t;n.push(vt(Vn(-bt,s,100+bt,s+e)))}return Qe(yt,n)}function hd(e){return Qe(yt,[vt(Vn(-bt,50-e,100+bt,50+e))])}function md(e){const t=100/br,n=[];for(let o=0;o<br;o++){const s=o*t;n.push(vt(Vn(s,-bt,s+e,100+bt)))}return Qe(yt,n)}function gd(e){return Qe(yt,[vt([[50,50-e],[50+e,50],[50,50+e],[50-e,50]])])}function wd(e){const t=100/ad,n=100/ld,o=[];for(let s=0;s<ld;s++)for(let i=0;i<ad;i++){const r=i*t+t/2,l=s*n+n/2,a=t/2*e,c=n/2*e;o.push(vt(Vn(r-a,l-c,r+a,l+c)))}return Qe(yt,o)}function yd(e){const t=-Math.PI/2,n=e/180*Math.PI,o=[[50,50]];for(let s=0;s<cd;s++){const i=t+s/(cd-1)*n;o.push([50+Math.cos(i)*vr,50+Math.sin(i)*vr])}return Qe(yt,[vt(o)])}function Bb(){return{from:ud(0),to:ud(Ub)}}function Hb(){return{from:fd(0),to:fd(52)}}function zb(){return{from:pd(0),to:pd(100/yr+.5)}}function Gb(){return{from:hd(0),to:hd(52)}}function jb(){return{from:md(0),to:md(100/br+.5)}}function Vb(){return{from:gd(0),to:gd(vr)}}function qb(){return{from:wd(0),to:wd(1.04)}}function Kb(){return{from:yd(0),to:yd(360)}}function Yb(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 100% 0% )"}}function Xb(){return{from:"inset( 0% 0% 0% 0% )",to:"inset( 0% 0% 0% 100% )"}}function Zb(){return{from:Qe([[-60,0],[100,0],[100,100],[0,100]]),to:Qe([[100,0],[260,0],[260,100],[160,100]])}}const _r=6,Er=100,tn=Er/2,Rs=200,bd=90,vd=["#5c5c6d","#525261","#484855","#3e3e49","#34343d","#2a2a31"],Jb="#101014",Qb=1.25,nn="http://www.w3.org/2000/svg";let ev=0;function Os(e){return Math.round(e*1e3)/1e3}function kr(e){return e/_r*Math.PI*2-Math.PI/2}function tv(e){const n=kr(e)+Math.PI/_r+Math.PI/2;return{x:Math.cos(n),y:Math.sin(n)}}function nv(e){const t=kr(e),n=kr(e+1);return[[tn,tn],[tn+Math.cos(t)*Rs,tn+Math.sin(t)*Rs],[tn+Math.cos(n)*Rs,tn+Math.sin(n)*Rs]]}function _d(e,t){const n=nv(e),o=document.createElementNS(nn,"path");return o.setAttribute("d",`M ${n.map(([s,i])=>`${Os(s)} ${Os(i)}`).join(" L ")} Z`),t?o.setAttribute("fill","#fff"):(o.setAttribute("fill",vd[e%vd.length]),o.setAttribute("stroke",Jb),o.setAttribute("stroke-width",String(Qb)),o.setAttribute("vector-effect","non-scaling-stroke"),o.setAttribute("stroke-linejoin","round")),o}function ov(){const e=`os-iris-${++ev}`,t=document.createElementNS(nn,"svg");t.setAttribute("viewBox",`0 0 ${Er} ${Er}`),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(nn,"defs"),o=document.createElementNS(nn,"mask");o.setAttribute("id",e);const s=document.createElementNS(nn,"g"),i=document.createElementNS(nn,"g");i.setAttribute("mask",`url(#${e})`);const r=[];for(let a=0;a<_r;a++){const c=_d(a,!0),d=_d(a,!1);s.appendChild(c),i.appendChild(d),r.push({el:c,index:a},{el:d,index:a})}o.appendChild(s),n.appendChild(o),t.appendChild(n),t.appendChild(i);const l=document.createElement("div");return l.appendChild(t),{element:l,play:a=>r.map(({el:c,index:d})=>{const u=tv(d),f=Os(u.x*bd),p=Os(u.y*bd);return c.animate([{transform:"translate( 0px, 0px )"},{transform:`translate( ${f}px, ${p}px )`}],{duration:a.duration,easing:a.easing,delay:a.delay,fill:"both"})})}}const qn="none",sv=460,iv="cubic-bezier( 0.33, 0, 0.2, 1 )",Ed=80,kd=4e3,rv=70,av=600,Sd=re("desktop-mode/window-reveal-registry",()=>({registry:new Map,listeners:new Set})),Ms=Sd.state.registry,lv=Sd.state.listeners,Ad=/^[a-z0-9_/-]+$/;function Cd(e){const t=/^\s*([a-zA-Z-]+)\s*\(/.exec(e);return t?t[1].toLowerCase():""}function cv(e){return typeof e!="number"||!Number.isFinite(e)?sv:Math.min(kd,Math.max(Ed,e))}const Sr=0;function Id(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?Sr:Math.min(kd,Math.max(Ed,e))}function on(e){return typeof e!="number"||!Number.isFinite(e)?rv:Math.min(av,Math.max(0,e))}function xd(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 Ld(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=Cd(e.from),r=Cd(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 dv(e){if(typeof KeyframeEffect!="function")return!0;try{return new KeyframeEffect(null,null,{easing:e}),!0}catch{return!1}}function Fe(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)"):Ad.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===qn&&t.push('id ("none" is reserved)'):t.push(`id (must match ${Ad} — 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,l)=>{if(!r||typeof r!="object"){t.push(`layers[ ${l} ] (not an object)`);return}t.push(...Ld(r,`layers[ ${l} ]`))})):t.push(...Ld(e,"").map(r=>r.replace(/^\./,"")))),e.easing!==void 0&&(typeof e.easing!="string"||e.easing.trim()===""?t.push("easing (not a non-empty string)"):dv(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();Ms.set(n,{...e,id:n}),Dd()}function uv(e){Ms.delete(e.toLowerCase())&&Dd()}function Td(){const e=Array.from(Ms.values()),t=G(_.WINDOW_REVEALS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-reveals` filter returned a non-array; falling back to registry list."),e)}function Nd(e){return Td().find(t=>t.id===e)}function fv(e){return Ms.has(e)}function Dd(){const e=Array.from(lv);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-reveal registry listener threw:",n)}}Fe({id:"sweep",label:k("Sweep"),description:k("A straight edge travels across the window, uncovering the page behind it."),...Xb(),duration:420}),Fe({id:"iris",label:k("Iris"),description:k("The page opens out from the centre of the window, like a camera shutter."),...Bb(),duration:520}),Fe({id:"curtain",label:k("Curtain"),description:k("Two panels part from the middle of the window and slide off the sides."),...Hb(),duration:480}),Fe({id:"blinds",label:k("Blinds"),description:k("Six horizontal slats retract at once, letting the page through between them."),...zb(),duration:560}),Fe({id:"diagonal",label:k("Diagonal"),description:k("A slanted edge sweeps off the trailing corner of the window."),...Zb(),duration:460}),Fe({id:"rise",label:k("Rise"),description:k("The page rises into the window from the bottom edge upward."),...Yb(),duration:440}),Fe({id:"shutter",label:k("Shutter"),description:k("Two panels part from the middle of the window and slide off the top and bottom."),...Gb(),duration:480}),Fe({id:"slats",label:k("Slats"),description:k("Eight vertical slats retract at once, letting the page through between them."),...jb(),duration:560}),Fe({id:"diamond",label:k("Diamond"),description:k("The page opens out from the centre of the window through a growing rhombus."),...Vb(),duration:520}),Fe({id:"mosaic",label:k("Mosaic"),description:k("The page arrives as a grid of tiles, each opening out from its own centre."),...qb(),duration:600}),Fe({id:"obturator",label:k("Camera shutter"),description:k("Six wedges slide aside in unison, opening a hexagonal aperture from the centre like the iris of a camera lens."),render:ov,duration:720,edgeLag:0}),Fe({id:"radar",label:k("Radar"),description:k("A spoke sweeps a full turn around the centre of the window, uncovering the page behind it."),...Kb(),duration:760});const Rd="desktop-mode-os-settings",pv="custom-gradient",Od="custom-image",Ar="galaxy",Md="custom",Pd=[{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 Cr(){const t=window.wp?.os?.config?.accentColors;if(!Array.isArray(t)||t.length===0)return Pd;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:Pd}function Wd(){const t=window.wp?.os?.config?.defaultWallpaper;return typeof t=="string"&&t!==""?t:Ar}const Ir=[{id:"compact",label:"Compact",width:48,icon:18},{id:"default",label:"Default",width:56,icon:20},{id:"large",label:"Large",width:72,icon:26}],xr=[{id:"sharp",label:"Sharp",value:0},{id:"default",label:"Default",value:8},{id:"round",label:"Round",value:16}],Ps=[{id:"static",label:"Static"},{id:"dynamic",label:"Dynamic"},{id:"hidden",label:"Hidden"}],hv=[{id:"bottom",label:"Bottom"},{id:"left",label:"Left"},{id:"right",label:"Right"}],mv=[{id:"unified",label:"Unified"},{id:"classic",label:"Split"}],J={wallpaper:Ar,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,itemVisibility:{},dockOrder:[],dockPromotedPositions:{}},$d={dockSize:["compact","default","large"],desktopLayout:["classic","unified"],dockPlacement:["bottom","left","right"],windowRadius:["sharp","default","round"],adminBarMode:["static","dynamic","hidden"]},Ud=["dockRailRenderer","windowReveal","accent"],Fd={windowRevealDuration:{min:80,max:4e3}},gv=/^[a-z0-9_-]+$/;[...Object.keys($d),...Ud,...Object.keys(Fd)];function Bd(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},o={};for(const[s,i]of Object.entries($d)){const r=t[s];typeof r=="string"&&i.includes(r)&&(n[s]=r)}for(const s of Ud){const i=t[s];typeof i=="string"&&gv.test(i)&&(n[s]=i)}for(const[s,i]of Object.entries(Fd)){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 wv(e){const t=Bd(e);return typeof t.dockRailRenderer=="string"&&Rb(t.dockRailRenderer)===void 0&&delete t.dockRailRenderer,typeof t.windowReveal=="string"&&t.windowReveal!==qn&&!fv(t.windowReveal)&&delete t.windowReveal,typeof t.accent=="string"&&!Cr().some(n=>n.id===t.accent)&&delete t.accent,t}const yv=/^[a-z0-9_-]+$/,Hd=128;function bv(e){return typeof e!="string"||e===""||e.length>2048?!1:e.startsWith("dashicons-")||e.startsWith("https://")||e.startsWith("http://")||e.startsWith("data:image/")}function zd(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.slug=="string"?t.slug:"";if(!yv.test(n))return null;const o={};if(t.icons&&typeof t.icons=="object"){let a=0;for(const[c,d]of Object.entries(t.icons)){if(a>=Hd)break;c===""||!bv(d)||(o[c]=d,a+=1)}}const s={};if(t.tokens&&typeof t.tokens=="object")for(const[a,c]of Object.entries(t.tokens))typeof c=="string"&&(s[a]=c);const i=[];if(Array.isArray(t.fonts))for(const a of t.fonts)typeof a=="string"&&a!==""&&i.push(a);const r={};if(t.iconColors&&typeof t.iconColors=="object"){let a=0;for(const[c,d]of Object.entries(t.iconColors)){if(a>=Hd)break;c===""||typeof d!="string"||d===""||(r[c]=d,a+=1)}}const l=a=>typeof t[a]=="string"?t[a]:"";return{id:l("id")||n,slug:n,name:l("name")||n,version:l("version"),author:l("author"),description:l("description"),previewUrl:l("previewUrl"),cssUrl:l("cssUrl"),cssText:l("cssText"),tokens:s,fonts:i,icons:o,iconColors:r,recommendedOsSettings:Bd(t.recommendedOsSettings),installedAt:typeof t.installedAt=="number"?t.installedAt:0,source:t.source==="code"?"code":"upload"}}function vv(){const t=window.openStationConfig?.serverDesktopThemes,n=[];if(Array.isArray(t))for(const o of t){const s=zd(o);s&&n.push(s)}return{themes:n,activeId:null,activeIcons:null,activeIconColors:null}}const sn=re("desktop-mode/desktop-themes",vv);function Ws(){return sn}function _v(){return sn.getState().themes.slice()}function Gd(e){if(typeof e!="string"||e==="")return null;const t=e.replace(/\//g,"-");return sn.getState().themes.find(n=>n.slug===t||n.id===e)??null}function Lr(){return sn.getState().activeId}function Ev(e){const t=[];for(const n of e){const o=zd(n);o&&t.push(o)}sn.setState({themes:t})}function kv(e){return sn.subscribe(e)}function $s(e){const t=Ws().state;if(t.activeIcons===null||!e)return null;const n=t.activeIcons[e];if(typeof n!="string"||n==="")return null;const o=G(_.DESKTOP_THEME_ICON,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?o:null}function Tr(e){const t=Ws().state;if(t.activeIconColors===null||!e)return null;const n=t.activeIconColors[e];if(typeof n!="string"||n==="")return null;const o=G(_.DESKTOP_THEME_ICON_COLOR,n,{slot:e,themeId:t.activeId??""});return typeof o=="string"&&o!==""?Sv(o):null}function Sv(e){const t=e.trim();if(t===""||t.length>64||/[;{}<>"'\\]/.test(t))return null;let n=0;for(const o of t)if(o==="(")n+=1;else if(o===")"&&(n-=1,n<0))return null;return n===0?t:null}const Nt={WINDOW_CONTROL_MINIMIZE:"WINDOW_CONTROL_MINIMIZE",WINDOW_CONTROL_MAXIMIZE:"WINDOW_CONTROL_MAXIMIZE",WINDOW_CONTROL_FULLSCREEN:"WINDOW_CONTROL_FULLSCREEN",WINDOW_CONTROL_FULLSCREEN_EXIT:"WINDOW_CONTROL_FULLSCREEN_EXIT",WINDOW_CONTROL_CLOSE:"WINDOW_CONTROL_CLOSE",WINDOW_CONTROL_MENU:"WINDOW_CONTROL_MENU",WINDOW_CONTROL_RELOAD:"WINDOW_CONTROL_RELOAD",WINDOW_CONTROL_DETACH:"WINDOW_CONTROL_DETACH",OS_SETTINGS:"OS_SETTINGS",RECYCLE_BIN:"RECYCLE_BIN",BUG_REPORT:"BUG_REPORT",EXIT_OPENSTATION:"EXIT_OPENSTATION",PWA_INSTALL:"PWA_INSTALL",DEFAULT_APP_ICON:"DEFAULT_APP_ICON",FOLDER:"FOLDER",FILE_SHORTCUT:"FILE_SHORTCUT",FILE_POST:"FILE_POST",FILE_ATTACHMENT:"FILE_ATTACHMENT",FILE_UPLOAD:"FILE_UPLOAD",FILE_USER:"FILE_USER",FILE_TERM:"FILE_TERM",FILE_COMMENT:"FILE_COMMENT",FILE_BOOKMARK:"FILE_BOOKMARK",FILE_LINK:"FILE_LINK",FILE_EMBED:"FILE_EMBED",RECYCLE_RESTORE:"RECYCLE_RESTORE",RECYCLE_DELETE:"RECYCLE_DELETE"},Av={"desktop-mode-os-settings":Nt.OS_SETTINGS,"desktop-mode-recycle-bin":Nt.RECYCLE_BIN,"desktop-mode-bug-report":Nt.BUG_REPORT,"os-exit":Nt.EXIT_OPENSTATION,"os-pwa-install":Nt.PWA_INSTALL};function Us(e){if(typeof e!="string"||e==="")return"";const t=Av[e];if(t)return t;const n=e.toLowerCase().replace(/[^a-z0-9_-]/g,"");return n===""?"":`APP:${n}`}function Cv(e){if(typeof e!="string"||e==="")return"";if(e==="folder")return Nt.FOLDER;const n=`FILE_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`;return n in Nt?n:""}const jd=new Map,Iv=new Map;function Nr(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 Vd(e,t,n,o){const s={channel:n,windowId:t},i=Nr(e,t,n,!1);if(i)for(const l of Array.from(i))try{l(o,s)}catch(a){typeof console<"u"&&console.error(`[openstation] window-channel subscriber for "${n}" threw:`,a)}const r=Nr(e,t,"*",!1);if(r)for(const l of Array.from(r))try{l(o,s)}catch(a){typeof console<"u"&&console.error(`[openstation] window-channel wildcard subscriber for "${t}" threw:`,a)}}function xv(e,t,n){const o=Nr(jd,e,t,!0);o.add(n);let s=!1;return()=>{s||(s=!0,o.delete(n))}}function Lv(e,t,n){Vd(jd,e,t,n)}function Tv(e,t,n){Vd(Iv,e,t,n)}const qd=new Set,Nv=new Set,Kd=new Map;function Dv(e){if(!qd.has(e)){qd.add(e);const t=Kd.get(e);if(t){Kd.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)}}}Nv.delete(e)&&(L(_.WINDOW_CONTENT_LOADED,{windowId:e}),typeof document<"u"&&document.dispatchEvent(new CustomEvent("os-window-content-loaded",{detail:{windowId:e}})))}const Rv="os.activity.";function Dr(e){return Rv+String(e).replace(/[^a-zA-Z0-9_.-]/g,".")}let Ov=0;const ke={publish(e,t){L(Dr(e),t)},subscribe(e,t){const n=`os/activity-sub/${++Ov}`,o=Dr(e);Y(o,n,i=>t(i));let s=!1;return()=>{s||(s=!0,ur(o,n))}},filter(e,t,...n){return G(Dr(e),t,...n)}},Mv=4e3,Pv=200,Wv=1200;function X(e){const t=ke.filter("os/toast-requested",{...e});if(!t||t.cancel===!0)return()=>{};let n=!1,o=null;return Ns(()=>!n,()=>{o=$v(t)}),()=>{n=!0,o&&o()}}function $v(e){const t=Hv(),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(),a()})),e.dismissible&&(n.setAttribute("dismissible",""),n.addEventListener("os-toast-dismiss",()=>{e.onDismiss?.(),a()})),t.appendChild(n);let o=!1,s=null,i=e.duration??Mv,r=0;const l=()=>{s!==null&&(window.clearTimeout(s),s=null)},a=()=>{o||(o=!0,l(),Bv(n),n.setAttribute("state","out"),window.setTimeout(()=>{n.remove(),Fv()},Pv))},c=()=>{o||e.persistent||s!==null||(r=Date.now(),s=window.setTimeout(a,i))},d=()=>{s!==null&&(i=Math.max(0,i-(Date.now()-r)),l())};return requestAnimationFrame(()=>{n.setAttribute("state","in")}),n.addEventListener("os-toast-hold",u=>{if(u.detail?.held){d();return}i=Math.max(i,Wv),c()}),Uv(n),c(),ke.publish("os/toast-shown",{...e}),a}let Fs=null,Kn=0;function Yd(e){const t=e.target;t instanceof HTMLElement&&(t.closest("os-toast-container")||(Fs=t))}function Uv(e){Kn===0&&document.addEventListener("focusin",Yd,!0),Kn+=1;const t=e.ownerDocument,n=t.activeElement;n instanceof HTMLElement&&n!==t.body&&!n.closest("os-toast-container")&&(Fs=n)}function Fv(){Kn=Math.max(0,Kn-1),Kn===0&&document.removeEventListener("focusin",Yd,!0)}function Bv(e){const t=e.ownerDocument.activeElement;t!==e&&!e.contains(t)||Fs?.isConnected===!0&&Fs.focus()}function Hv(){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 Xd="X-WP-Nonce";function Zd(e,t){const n=zv();if(!n)return t;const o=Gv(e);if(!o||!jv(o))return t;const s=t?.headers??(typeof Request<"u"&&e instanceof Request?e.headers:void 0),i=new Headers(s??{});return i.has(Xd)?t:(i.set(Xd,n),{...t??{},headers:i})}function zv(){if(typeof window>"u")return;const t=window.openStationConfig?.restNonce;return typeof t=="string"&&t.length>0?t:void 0}function Gv(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 jv(e){return typeof window>"u"||!window.location||e.origin!==window.location.origin?!1:!!(e.pathname.includes("/wp-json/")||e.searchParams.has("rest_route"))}function Be(e,t,n={}){const o=window.wp?.os?.fetch;if(typeof o=="function")return o(e,t,n);const s=Zd(e,t);return fetch(e,s)}const Vv="http://localhost/";function et(e,t){const n=typeof window<"u"&&window.location?window.location.href:Vv,o=new URL(e,n),s=t.replace(/^\/+/,""),i=s.indexOf("?"),r=i===-1?s:s.slice(0,i),l=i===-1?"":s.slice(i+1);if(o.searchParams.has("rest_route")){const a=o.searchParams.get("rest_route")??"/",c=a.endsWith("/")?a:a+"/";o.searchParams.set("rest_route",c+r)}else{const a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";o.pathname=a+r}return l&&new URLSearchParams(l).forEach((c,d)=>{o.searchParams.append(d,c)}),o.toString()}const qv="os-overview",Kv="os-system",Bs={mio:10,overview:20,system:30,exit:35},Yv=`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>')}`,Xv=`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>')}`,Zv="os-exit";function Jv(){return{id:Zv,title:k("Exit OpenStation"),order:Bs.exit,icon:"dashicons-exit",onOpen:()=>{Qv()}}}async function Qv(){const e=window.openStationAdminBar,t=e?.classicUrl||"/wp-admin/";if(!e?.ajaxUrl||!e?.nonce){Rr(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{}Rr(o)}function Rr(e){try{(window.top??window).location.assign(e)}catch{window.location.assign(e)}}const Jd=800;function e_(e,t=Jd){window.setTimeout(()=>{if(e){Rr(e);return}try{(window.top??window).location.reload()}catch{window.location.reload()}},t)}const t_="desktop_mode_nonces",n_="desktop-mode/v1",o_=3e4,s_=3,rn=re("desktop-mode/plugin-presence",()=>({confirmInFlight:!1,lastConfirmAt:null,exiting:!1,booted:!1,negativeConfirms:0}));function Qd(){return window.wp?.os?.config??{}}function i_(){const e=Qd().restUrl;return e?et(e,n_):null}function r_(){rn.state.negativeConfirms=0}async function a_(){const e=rn.state;if(e.exiting||e.confirmInFlight||e.negativeConfirms>=s_)return;const t=i_();if(!t)return;const n=Date.now();if(!(e.lastConfirmAt!==null&&n-e.lastConfirmAt<o_)){e.lastConfirmAt=n,e.confirmInFlight=!0;try{const o=await Be(t,{credentials:"same-origin"},{silent:!0,source:"desktop-mode/plugin-presence"});if(o.status!==404){e.negativeConfirms+=1;return}if((await o.json())?.code!=="rest_no_route"){e.negativeConfirms+=1;return}l_()}catch{}finally{e.confirmInFlight=!1}}}function l_(){if(!rn.state.exiting){rn.state.exiting=!0,e_(Qd().adminUrl||"");try{X({message:k("OpenStation is no longer active. Returning to the WordPress dashboard…"),duration:Jd})}catch{}}}function c_(){if(rn.state.booted)return;rn.state.booted=!0;const e=window.jQuery;e&&e(document).on("heartbeat-tick",(...t)=>{const n=t[1];if(n){if(n[t_]!==void 0){r_();return}a_()}})}const d_=0,Or=40,eu=250,u_=120,f_=250,Yn="os-window__loading",Hs="os-window__loading--visible",zs=re("desktop-mode/window-reveal-active",()=>({id:qn,duration:Sr}));function tu(e){zs.state.id=typeof e=="string"&&e!==""?e:qn}function p_(){const e=zs.state.id;return!e||e===qn?null:Nd(e)??null}function nu(e){zs.state.duration=Id(e)}function h_(){return zs.state.duration}function m_({osSettings:e}){const t=e.getOsSettingsSnapshot();tu(t.windowReveal),nu(t.windowRevealDuration),e.subscribeOsSettings(n=>{tu(n.windowReveal),nu(n.windowRevealDuration)})}const an="os-window__reveal",Xn="os-window__reveal--edge",g_="os-window__reveal--custom",Dt="os-window__body--revealing",Mr="data-os-reveal",Pr="data-os-reveal-layer",_t=new WeakMap,ou=re("desktop-mode/window-reveal-rendered",()=>({plays:new WeakMap})).state.plays;function su(){if(typeof window>"u"||typeof window.matchMedia!="function")return!1;try{return window.matchMedia("( prefers-reduced-motion: reduce )").matches}catch{return!1}}const w_="--os-window-reveal-duration",y_="--os-window-reveal-edge-thickness";function iu(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 b_(e){if(typeof window>"u"||typeof window.getComputedStyle!="function")return 0;try{return Id(iu(window.getComputedStyle(e).getPropertyValue(w_)))}catch{return 0}}function v_(e,t){if(typeof window>"u"||typeof window.getComputedStyle!="function")return"";try{return window.getComputedStyle(e).getPropertyValue(t).trim()}catch{return""}}function __(e,t){const n=v_(e,y_);if(n==="")return null;const o=/^(-?\d*\.?\d+)%$/.exec(n);if(o)return on(t*Number(o[1])/100);const s=/^(-?\d*\.?\d+)$/.exec(n);if(s)return on(t*Number(s[1]));const i=iu(n);return/^-?\d*\.?\d+\s*(ms|s)$/i.test(n)?on(i):null}function ru(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 E_(e,t){const n=cv(t.duration),o=h_(),s=o!==Sr?o:b_(e)||n,i=__(e,s);if(i!==null)return{duration:s,edgeLag:i};const r=on(t.edgeLag);return s===n?{duration:n,edgeLag:r}:{duration:s,edgeLag:on(r*s/n)}}function au(e){return e.querySelector(":scope .os-window__body")}function k_(e){return e.querySelector(`:scope .${an}:not( .${Xn} )`)}function S_(e){return e.querySelector(`:scope .${Xn}`)}function lu(e){return Array.from(e.querySelectorAll(`:scope .${an}:not( .${Xn} )`))}function cu(e){return Array.from(e.querySelectorAll(`:scope .${Xn}`))}function Wr(e){return Array.from(e.querySelectorAll(`:scope .${an}`))}function du(e,t,n,o){const s=document.createElement("div");s.className=o?`${an} ${Xn}`:an;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(Mr,e.id),s.setAttribute(Pr,String(n)),s.style.clipPath=t.from,s}function A_(){const e=p_();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(an),s.classList.add(g_),s.setAttribute("aria-hidden","true"),s.setAttribute(Mr,e.id),s.setAttribute(Pr,"0"),ou.set(s,o.play),[s]}const t=xd(e);if(t.length===0)return[];const n=[];return on(e.edgeLag)>0&&t.forEach((o,s)=>n.push(du(e,o,s,!0))),t.forEach((o,s)=>n.push(du(e,o,s,!1))),n}function C_(e){const t=au(e);if(t){t.classList.remove(Dt);for(const n of Wr(t))_t.get(n)?.cancel(),_t.delete(n),n.remove();for(const n of A_())t.appendChild(n)}}function uu(e){const t=au(e);if(!t)return;const n=k_(t);if(!n)return;let o;try{o=Nd(n.getAttribute(Mr)??"")}catch(E){typeof console<"u"&&console.error("[openstation] window-reveal lookup threw; uncovering without a reveal:",E)}if(!o){Wr(t).forEach(E=>E.remove());return}const i=!!t.querySelector(`:scope .${Yn}`)?.classList.contains(Hs)?eu:0,{duration:r,edgeLag:l}=E_(t,o),a=o.easing??iv,c=ou.get(n);if(c){t.classList.add(Dt);const E=()=>{_t.delete(n),n.remove(),t.classList.remove(Dt)};if(su()||typeof n.animate!="function"){window.setTimeout(E,i);return}let T=[];try{T=c({duration:r,easing:a,delay:i})}catch(M){typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" play threw:`,M)}if(T.length===0){E();return}T[0].addEventListener("finish",E),T[0].addEventListener("cancel",()=>{_t.delete(n),t.classList.remove(Dt)}),_t.set(n,T[0]);return}const d=S_(t);d&&(l<=0||ru(d))&&cu(t).forEach(E=>E.remove()),ru(n)&&lu(t).forEach(E=>E.remove());const u=Wr(t);if(u.length===0)return;t.classList.add(Dt);const f=()=>{for(const E of u)_t.delete(E),E.remove();t.classList.remove(Dt)};if(su()||typeof n.animate!="function"){window.setTimeout(f,i);return}const p=a,g=xd(o),m=(E,T)=>{const M=g[Number(E.getAttribute(Pr))];if(!M)return E.remove(),null;E.style.willChange="clip-path";let P;try{P=E.animate([{clipPath:M.from},{clipPath:M.to}],{duration:T,easing:p,delay:i,fill:"both"})}catch(v){return typeof console<"u"&&console.error(`[openstation] window reveal "${o.id}" failed to animate; uncovering:`,v),E.remove(),null}return _t.set(E,P),P},h=lu(t).map(E=>m(E,r)).filter(E=>E!==null),b=cu(t).map(E=>m(E,r+l)).filter(E=>E!==null),y=h[0]??null,C=b[0]??null;if(!y&&!C){f();return}(C??y)?.addEventListener("finish",f);const w=()=>{for(const E of u)_t.delete(E);t.classList.remove(Dt)};y?.addEventListener("cancel",w),C?.addEventListener("cancel",w)}const I_="os-window-tab-change";function fu(e){return Array.from(e.querySelectorAll(".os-window__tab"))}function pu(e){return e.replace(/[^a-zA-Z0-9_-]/g,"-")}function hu(e,t){return`${e.id||"os-window"}-tab-${pu(t)}`}function mu(e,t){return`${e.id||"os-window"}-panel-${pu(t)}`}function x_(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 L_(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 T_(e){const t=fu(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 gu(e){const t=new Map;for(const n of fu(e))n.dataset.kind==="panel"&&n.dataset.panel&&t.set(n.dataset.panel,n);return t}function wu(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 N_(e,t){const n=e.querySelector(".os-window__tabs");if(!n)return;let o=!1;for(const[s,i]of gu(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 wu(e)){const i=s.getAttribute("for")===t;s.toggleAttribute("hidden",!i),s.setAttribute("aria-hidden",i?"false":"true")}T_(n),x_(n),e.dispatchEvent(new CustomEvent(I_,{bubbles:!0,detail:{value:t}}))}}function D_(e,t,n){const o=e.querySelector(".os-window__tabs");if(!o)return;const s=gu(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=hu(e,d.value),u.setAttribute("aria-controls",mu(e,d.value)),u.previousElementSibling!==r&&o.insertBefore(u,r?r.nextSibling:o.firstChild),r=u}for(const d of s.values())d.remove();L_(o);const l=o.querySelector(":scope > .os-window__tab")!==null;for(const d of wu(e)){const u=d.getAttribute("for");u&&(d.id=mu(e,u),l?d.setAttribute("aria-labelledby",hu(e,u)):d.removeAttribute("aria-labelledby"))}const a=d=>d!==void 0&&t.some(u=>u.value===d),c=[n,i,t[0]?.value].find(a);c!==void 0&&N_(e,c)}const Zn="os-window__body--loading",$r="os-window__body--loading-out",Ur="data-os-loading-at",yu="data-os-loading-cycle";function Gs(e){return e.getAttribute(yu)??"0"}function R_(e){e.setAttribute(Ur,String(Date.now())),e.setAttribute(yu,String(Number(Gs(e))+1))}function O_(e,t){const n=Number(e.getAttribute(Ur)),o=Number.isFinite(n)&&n>0?Date.now()-n:0,s=u_-o;if(s<=0){t.classList.add(Hs);return}window.setTimeout(()=>{t.isConnected&&e.classList.contains(Zn)&&t.classList.add(Hs)},s)}const M_=Symbol.for("desktop-mode/window-config");function P_(e){return e[M_]}function Fr(){const e=document.querySelectorAll(".os-window--fullscreen:not(.os-window--minimized)").length>0;document.body.classList.toggle("os-has-fullscreen-window",e)}function bu(){const e=document.createElement("div");e.className=Yn,e.setAttribute("role","status"),e.setAttribute("aria-live","polite");const t=document.createElement("os-spinner");return t.setAttribute("preset","classic"),t.setAttribute("size","clamp(96px, 14vw, 192px)"),t.setAttribute("label",k("Loading window content")),e.appendChild(t),e}function W_(e){let t=bu();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=G(_.WINDOW_LOADING_OVERLAY,t,n);o instanceof HTMLElement&&(t=o)}catch(o){typeof console<"u"&&console.error(`[openstation] WINDOW_LOADING_OVERLAY filter threw for "${e.id}":`,o)}return t&&!t.classList.contains(Yn)&&t.classList.add(Yn),t}function vu(e){e.querySelector(":scope .os-window__loading")?.remove()}function _u(e){const t=e.querySelector(":scope .os-window__body");if(!t||t.querySelector(":scope .os-window__loading"))return;const o=P_(e),s=o?W_(o):bu();t.appendChild(s),O_(t,s)}const Eu=["adminmenumain","adminmenuback","os-dock","os-side-dock","os-widgets"],js="osHadFullscreenBeforeOverview";function ku(e){(e.state==="fullscreen"||e.element.classList.contains("os-window--fullscreen"))&&(e.element.classList.remove("os-window--fullscreen"),e.element.dataset[js]="true",Fr()),e.state==="minimized"&&(e.element.style.removeProperty("content-visibility"),e.iframe&&(e.iframe.style.visibility=""))}function Su(e){if(e.element.dataset[js]==="true"){if(e.state!=="fullscreen"&&e.state!=="minimized"){delete e.element.dataset[js],Fr();return}e.element.classList.add("os-window--fullscreen"),delete e.element.dataset[js],Fr()}}function Br(e,t=!0){t&&Su(e),e.state==="minimized"&&(e.element.style.setProperty("content-visibility","hidden"),e.iframe&&(e.iframe.style.visibility="hidden"))}function Au(e){const t=document.getElementById("wpbody-content");if(t)for(const n of Array.from(t.children))n.inert=e}function Cu(e,t){for(const n of e._stack)for(const o of Array.from(n.element.children))o.inert=t}function $_(e){if(e._overviewActive)return;Iu(e);const t=e._stack.filter(c=>c.config.desktopId===e._activeDesktopId);e._overviewActive=!0,L(_.OVERVIEW_ENTERING,{});for(const c of Eu){const d=document.getElementById(c);d&&(d.inert=!0)}Au(!0),Cu(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)ku(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=xu(e),e._desktop.appendChild(e._overviewTopBar);const l=mr(t,i,od);e._overviewLabels.clear();for(const c of l){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=zr(c);d.insertAdjacentElement("afterend",p),e._overviewLabels.set(c.win.id,p)}const a=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=a(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"){Rt(e);return}const p=e.getById(d.id);L(_.OVERVIEW_WINDOW_CLICK,{windowId:d.id}),Rt(e,p)},e._overviewKeyHandler=c=>{if(c.key==="Escape"){Rt(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){Lu(e);return}Rt(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&&L(_.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),f&&L(_.OVERVIEW_WINDOW_HOVER,{windowId:f}),e._lastOverviewHoverId=f)},e._desktop.addEventListener("mouseover",e._overviewMouseHandler),e._overviewEnterTimeoutId=window.setTimeout(()=>{e._overviewEnterTimeoutId=null,e._overviewActive&&L(_.OVERVIEW_ENTERED,{})},300)}function Iu(e){e._overviewExitTimeoutId!==null&&(window.clearTimeout(e._overviewExitTimeoutId),e._overviewExitTimeoutId=null);const t=e._overviewExitFinalizer;e._overviewExitFinalizer=null,t?.()}function U_(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 xu(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(F_(e,s));const o=document.createElement("button");return o.type="button",o.className="os-overview-top-bar__tile os-overview-top-bar__tile--add",e._overviewAddTileFocused&&o.classList.add("os-overview-top-bar__tile--cursor"),o.setAttribute("aria-label",k("Add new desktop")),o.innerHTML='<span class="os-overview-top-bar__tile-plus" aria-hidden="true">+</span>',o.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),Lu(e)}),n.appendChild(o),t}function Lu(e){const t=Ru(e);e._overviewAddTileFocused=!1,Tu(e,t.id)}function F_(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(k("Switch to %s"),t.label));const s=document.createElement("span");s.className="os-overview-top-bar__tile-preview";const i=e._stack.filter(a=>a.config.desktopId===t.id).length;if(i>0){const a=document.createElement("span");a.className="os-overview-top-bar__tile-count",a.textContent=String(i),s.appendChild(a)}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",a=>{a.preventDefault(),a.stopPropagation(),Tu(e,t.id)});const l=document.createElement("button");return l.type="button",l.className="os-overview-top-bar__tile-close",l.setAttribute("aria-label",le(k("Close %s"),t.label)),l.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2.5 2.5l7 7M9.5 2.5l-7 7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',l.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),Mu(e,t.id),Hr(e)}),n.appendChild(o),n.appendChild(l),n}function Hr(e){if(!e._overviewTopBar)return;const t=xu(e);e._overviewTopBar.replaceWith(t),e._overviewTopBar=t}function Tu(e,t){Ou(e,t),Rt(e)}function zr(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 l=document.createElement("span");l.className="os-overview-label__meta",l.textContent=le(en("· %d open tab","· %d open tabs",r),r),t.appendChild(l)}return t}function Rt(e,t,n=!1){if(!e._overviewActive)return;e._overviewActive=!1,e._overviewAddTileFocused=!1,L(_.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 Eu){const r=document.getElementById(i);r&&(r.inert=!1)}Au(!1),Cu(e,!1);for(const[i,r]of e._overviewSnapshot){const l=e.getById(i);l&&(l.element.style.transform=r.transform)}t&&(t.state==="minimized"&&(Su(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"),Br(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),L(_.OVERVIEW_EXITED,{windowId:t?t.id:void 0,reason:t?"select":"cancel"})},e._overviewExitTimeoutId=window.setTimeout(()=>Iu(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&&(L(_.OVERVIEW_WINDOW_UNHOVER,{windowId:e._lastOverviewHoverId}),e._lastOverviewHoverId=null)}function B_(e){return[...e._desktops]}function Nu(e){return e._desktops.find(n=>n.id===e._activeDesktopId)??e._desktops[0]}function H_(e){return Nu(e).id}function Du(e,t){const n=t.config.desktopId===e._activeDesktopId;t.element.style.display=n?"":"none",n&&!e._overviewActive&&Br(t)}function Gr(e){for(const t of e._stack)Du(e,t)}function Ru(e){e._desktopSeq++;const t={id:`desktop-${e._desktopSeq}`,label:le(k("Desktop %d"),e._desktopSeq)};return e._desktops.push(t),L(_.DESKTOP_CREATED,{desktopId:t.id}),t}function Ou(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)Pu(e),Hr(e);else{Gr(e),n?.direction&&z_(e,n.direction);const s=[...e._stack].reverse().find(i=>i.config.desktopId===t&&i.state!=="minimized");s&&e.focus(s)}L(_.DESKTOP_SWITCHED,{from:o,to:t})}function z_(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 Mu(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?Pu(e):Gr(e),L(_.DESKTOP_CLOSED,{desktopId:t,migratedTo:s.id})}function Pu(e){for(const[i,r]of e._overviewSnapshot){const l=e.getById(i);l&&(l.element.style.transform=r.transform,l.element.style.transition=r.transition,l.element.classList.remove("os-window--overview"),Br(l,l.config.desktopId===e._activeDesktopId))}for(const i of e._overviewLabels.values())i.remove();e._overviewLabels.clear(),e._overviewSnapshot.clear(),Gr(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||""}),ku(i);const n=e._desktop.getBoundingClientRect(),o=new DOMRect(0,0,n.width,n.height),s=mr(t,o,od);for(const i of s){const r=i.win.element;r.classList.add("os-window--overview");const l=i.x-r.offsetLeft,a=i.y-r.offsetTop;r.style.transform=`translate(${l}px, ${a}px) scale(${i.scale})`;const c=zr(i);r.insertAdjacentElement("afterend",c),e._overviewLabels.set(i.win.id,c)}}function G_(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 j_(e){const t=e._stack.filter(u=>u.config.desktopId===e._activeDesktopId);if(t.length===0)return;L(_.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),l=Math.max(1,Math.floor((n.width-i-o)/s)),a=Math.max(1,Math.floor((n.height-r-o)/s)),c=Math.min(l,a);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"}})),L(_.ARRANGE_CASCADE_APPLIED,{windowCount:t.length})}function V_(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=xb(t.length,n.width,n.height),s=G(_.ARRANGE_TILE_DIMENSIONS,o,{windowCount:t.length,areaWidth:n.width,areaHeight:n.height}),{cols:i,rows:r}=Cb(s,t.length)?{cols:Math.floor(s.cols),rows:Math.floor(s.rows)}:o;L(_.ARRANGE_TILE_STARTING,{windowCount:t.length,cols:i,rows:r});const l=16,a=12,c=Math.floor((n.width-l*2-a*(i-1))/i),d=Math.floor((n.height-l*2-a*(r-1))/r);t.forEach((f,p)=>{const g=p%i,m=Math.floor(p/i);f.element.style.left=`${l+g*(c+a)}px`,f.element.style.top=`${l+m*(d+a)}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"}})),L(_.ARRANGE_TILE_APPLIED,{windowCount:t.length,cols:i,rows:r})}const Wu="desktop-mode-snap-to-grid";function q_(){try{return window.localStorage.getItem(Wu)==="1"}catch{return!1}}function K_(e,t){if(e._snapEnabled!==t){e._snapEnabled=t;try{window.localStorage.setItem(Wu,t?"1":"0")}catch{}L(_.ARRANGE_SNAP_CHANGED,{enabled:t})}}function Y_(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=G(_.ARRANGE_SNAP_CELL_SIZE,o,{areaWidth:t.width,areaHeight:t.height}),{cellWidth:i,cellHeight:r}=Ib(s)?s:o;return{enabled:!0,cellWidth:i,cellHeight:r}}function X_(e,t,n){if(e._splitOverviewActive)return;e._splitOverviewActive=!0,e._splitOverviewAnchor=t,e._splitOverviewZone=n;const o=e._stack.filter(l=>l!==t&&l.state!=="minimized"&&l.config.desktopId===e._activeDesktopId);if(o.length===0){$u(e);return}e._splitOverviewSnapshot.clear();for(const l of o)e._splitOverviewSnapshot.set(l.id,{transform:l.element.style.transform||"",transition:l.element.style.transition||""});e._desktop.classList.add("os-area--split-overview");const s=tE(e,n),i=mr(o,s,0);e._splitOverviewLabels.clear();for(const l of i){const a=l.win.element;a.classList.add("os-window--overview");const c=l.x-a.offsetLeft,d=l.y-a.offsetTop;a.style.transform=`translate(${c}px, ${d}px) scale(${l.scale})`;const u=zr(l);a.insertAdjacentElement("afterend",u),e._splitOverviewLabels.set(l.win.id,u)}const r=l=>{const a=l.target,c=a?.closest(".os-window--overview");return c?{id:c.id.replace(/^wp-window-/,""),element:c}:a?{id:"dismiss",element:e._desktop}:null};e._splitOverviewPointerDown=l=>{if(l.button!==0){e._splitOverviewPressTarget=null;return}e._splitOverviewPressTarget=r(l),e._splitOverviewPressTarget&&(l.preventDefault(),l.stopPropagation())},e._splitOverviewPointerUp=l=>{if(l.button!==0)return;const a=e._splitOverviewPressTarget;if(e._splitOverviewPressTarget=null,!a)return;const c=a.element.getBoundingClientRect();if(!(l.clientX>=c.left&&l.clientX<=c.right&&l.clientY>=c.top&&l.clientY<=c.bottom))return;if(l.preventDefault(),l.stopPropagation(),a.id==="dismiss"){Jn(e);return}const u=e.getById(a.id);if(!u){Jn(e);return}Z_(e,u)},e._splitOverviewKey=l=>{l.key==="Escape"&&Jn(e)},e._splitOverviewClickBlocker=l=>{l.stopPropagation(),l.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 Z_(e,t){const n=e._splitOverviewZone;if(!n){Jn(e);return}const o=n==="left"?"right":"left";t.element.style.transform="",t.element.classList.remove("os-window--overview"),t.applySnap(o),e._splitOverviewSnapshot.delete(t.id),e.focus(t),L(_.SNAP_SPLIT_FILLED,{windowId:t.id,zone:o}),Jn(e)}function Jn(e){if(!e._splitOverviewActive)return;e._splitOverviewActive=!1;for(const[n,o]of e._splitOverviewSnapshot){const s=e.getById(n);s&&(s.element.style.transform=o.transform)}for(const n of e._splitOverviewLabels.values())n.classList.add("os-overview-label--out");e._desktop.classList.remove("os-area--split-overview"),window.setTimeout(()=>{for(const n of e._stack)e._splitOverviewSnapshot.has(n.id)&&n.element.classList.remove("os-window--overview");for(const n of e._splitOverviewLabels.values())n.remove();$u(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 $u(e){e._splitOverviewSnapshot.clear(),e._splitOverviewLabels.clear(),e._splitOverviewAnchor=null,e._splitOverviewZone=null,e._splitOverviewActive=!1}const Uu=30,J_=260;function Q_(e,t){return e<=t.left+Uu?"left":e>=t.right-Uu?"right":null}function eE(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 tE(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 nE(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=eE(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 jr(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()},J_)}function oE(e,t,n){if(e._splitOverviewActive)return;const o=e._desktop.getBoundingClientRect(),s=Q_(n,o),i=e._snapPendingZone;s?(nE(e,s),i!==s&&L(_.SNAP_ZONE_PENDING,{windowId:t.id,zone:s})):i&&(jr(e),L(_.SNAP_ZONE_CANCELED,{windowId:t.id}))}function sE(e,t){const n=e._snapPendingZone;return n?(jr(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),L(_.SNAP_ZONE_COMMITTED,{windowId:t.id,zone:n}),window.requestAnimationFrame(()=>{X_(e,t,n)}),!0):!1}function iE(e){e._snapPendingZone&&jr(e)}const Fu="desktop-mode-native-window-geometry",Bu=64,tt=8192;function Vs(){try{const e=window.localStorage.getItem(Fu);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:t}catch{return{}}}function Hu(e){try{window.localStorage.setItem(Fu,JSON.stringify(e))}catch{}}function zu(e){if(!e)return null;const n=Vs()[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>tt||s>tt)return null;const i=n.state==="maximized"?"maximized":void 0,r=Number(n.x),l=Number(n.y),a=Number.isFinite(r)&&Number.isFinite(l)&&r>=0&&l>=0&&r<=tt&&l<=tt;return{width:Math.round(o),height:Math.round(s),...a?{x:Math.round(r),y:Math.round(l)}:{},...i?{state:i}:{}}}function Gu(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>tt||o>tt)return;const s=Vs(),i=s[e],r=i&&i.state==="maximized"?"maximized":void 0,l=typeof i?.x=="number"?i.x:void 0,a=typeof i?.y=="number"?i.y:void 0;i&&i.width===n&&i.height===o&&i.state===r&&i.x===l&&i.y===a||(Qn(s,e,{width:n,height:o,...typeof l=="number"&&typeof a=="number"?{x:l,y:a}:{},...r?{state:r}:{}}),eo(s))}function ju(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>tt||o>tt)return;const s=Vs(),i=s[e];i&&(i.x===n&&i.y===o||(Qn(s,e,{...i,x:n,y:o}),eo(s)))}function Vu(e,t,n){if(!e)return;const o=Vs(),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>tt||r>tt)return;Qn(o,e,{width:i,height:r,state:t}),eo(o);return}if(t===null){if(!s.state)return;const{state:i,...r}=s;Qn(o,e,r),eo(o);return}s.state!==t&&(Qn(o,e,{...s,state:t}),eo(o))}function Qn(e,t,n){delete e[t],e[t]=n}function eo(e){const t=Object.keys(e);if(t.length>Bu){const n={};for(const o of t.slice(-Bu))n[o]=e[o];Hu(n);return}Hu(e)}function rE(e,t,n,o,s){const i=Or-n,r=o-Or,l=Math.max(i,Math.min(e,r)),a=d_,c=s-Or,d=Math.max(a,Math.min(t,c));return{x:l,y:d}}const qu=100,qs=30;class aE{constructor(t){this._stack=[],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=q_(),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=rE(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 a=Ls(t.url);a===Ls(o.getCurrentUrl())||a===Ls(o.config.url||"")||a===Ls(o.config.parentUrl??o.config.url??"")||(r=o.navigateTo(t.url))}t.params&&(o.config.params={...t.params});const l={windowId:o.id,baseId:n,wasMinimized:i,navigated:r,params:o.config.params??{}};return document.dispatchEvent(new CustomEvent("os-window-reopened",{detail:l})),L(_.WINDOW_REOPENED,l),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*qs,i=40+this.cascadeIndex%8*qs;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*qs,l=40+this.cascadeIndex%8*qs,a=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?zu(a):null,b=t.width??(h?Math.max(h.width,c):s),y=t.height??(h?Math.max(h.height,d):i),C=t.initialState??(h?.state==="maximized"?"maximized":void 0);let w,E;if(h&&typeof h.x=="number"&&typeof h.y=="number"){const H=Math.max(0,o.width-b-12),Z=Math.max(0,o.height-y-12);w=Math.max(12,Math.min(h.x,H)),E=Math.max(12,Math.min(h.y,Z))}const T=t.x??w??r,M=t.y??E??l,P=u||f||p||g||m,v=!!h,$={x:T,y:M,width:b,height:y,state:C};let D;try{D=G(_.WINDOW_GEOMETRY,$,{windowId:t.id,baseId:a,hasSavedGeometry:v,callerPinned:P,desktopRect:{width:o.width,height:o.height}})}catch(N){L(_.SHELL_ERROR,{scope:"window-geometry-filter",windowId:t.id,error:N}),typeof console<"u"&&console.error(`[openstation] WINDOW_GEOMETRY filter threw for "${t.id}":`,N),D=$}const I=(N,H)=>typeof N=="number"&&Number.isFinite(N)?N:H,W=D&&typeof D=="object"?D:$,z=Math.max(I(W.width,b),c),q=Math.max(I(W.height,y),d),K=I(W.x,T),x=I(W.y,M),F=W.state??C,R={icon:t.icon||"dashicons-admin-generic",...t,x:K,y:x,width:z,height:q,minWidth:c,minHeight:d,...F?{initialState:F}:{},baseId:a,desktopId:t.desktopId||this._activeDesktopId};this.cascadeIndex++;const[S]=await Promise.all([kb(_b()),fr(pr())]),O=S.createWindow(R);O.onFocusRequest=N=>this.focus(N),O.onClose=N=>this.remove(N),O.onMinimize=()=>{const N=this._stack.filter(H=>H.state!=="minimized");N.length>0&&this.focus(N[N.length-1])},O.onOpenAnother=N=>{const H=N.config.baseId||N.id;N.config.native&&window.wp?.os?.openNewWindow?.(H,{source:"open-another"})||this.openNew({id:H,baseId:H,url:N.config.url||"",title:N.config.title,icon:N.config.icon,submenu:N.config.submenu,multi:!0})},O.onOpenInNewWindow=N=>{const H=N.config.baseId||N.id;if(N.config.native&&window.wp?.os?.openNewWindow?.(H,{source:"open-in-new-window"}))return;const Z=N.getCurrentUrl();this.openNew({id:H,baseId:H,url:Z||N.config.url||"",title:N.config.title,icon:N.config.icon,submenu:N.config.submenu,multi:!0})},O.onToggleStartup=N=>{this.onToggleStartupRequested?.(N)},O.snapConfigProvider=()=>this.getSnapConfig(),O.onDragMove=(N,H)=>{oE(this,N,H)},O.onDragEnd=N=>this._snapPendingZone?sE(this,N):(iE(this),!1),this._stack.push(O),this._desktop.appendChild(O.element),Du(this,O),O.hydrateNative(),this.focus(O);const U={windowId:O.id,page:t.url,title:t.title,url:t.url};return document.dispatchEvent(new CustomEvent("os-window-opened",{detail:U})),L(_.WINDOW_OPENED,U),O}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=this._stack.length>0?this._stack[this._stack.length-1]:null,o=this._stack.find(r=>r!==t&&r.isFocused()&&r.isFullscreen());o&&G(_.WINDOW_AUTO_EXIT_FULLSCREEN,!0,{windowId:o.id,focusedTo:t.id})&&o.toggleFullscreen();const s=this._stack.indexOf(t);if(s>-1&&this._stack.splice(s,1),this._stack.push(t),this._stack.forEach((r,l)=>{r.setZIndex(qu+l),r.setFocused(l===this._stack.length-1)}),n&&n!==t&&n.id!==t.id){const r={windowId:n.id,focusedTo:t.id};document.dispatchEvent(new CustomEvent("os-window-blurred",{detail:r})),L(_.WINDOW_BLURRED,r)}const i={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-focused",{detail:i})),L(_.WINDOW_FOCUSED,i)}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._stack.forEach((s,i)=>{s.setZIndex(qu+i)}))}remove(t){const n=this._stack.indexOf(t);n>-1&&this._stack.splice(n,1);for(let i=this._stack.length-1;i>=0;i--){const r=this._stack[i];if(!(r.state==="minimized"||(r.config.desktopId||this._activeDesktopId)!==this._activeDesktopId)){this.focus(r);break}}const o={windowId:t.id,element:t.element};document.dispatchEvent(new CustomEvent("os-window-closing",{detail:o})),L(_.WINDOW_CLOSING,o);const s={windowId:t.id};document.dispatchEvent(new CustomEvent("os-window-closed",{detail:s})),L(_.WINDOW_CLOSED,s)}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 B_(this)}getActiveDesktop(){return Nu(this)}getActiveDesktopId(){return H_(this)}createDesktop(){return Ru(this)}switchDesktop(t,n){Ou(this,t,n)}closeDesktop(t){Mu(this,t)}getPrimaryDesktopId(){const t=this.getDesktops(),n=t.length>0?t[0].id:"desktop-1",o=G(_.PRIMARY_DESKTOP_ID,n,t);return typeof o!="string"||o===""?n:t.some(i=>i.id===o)?o:n}closeAll(t){const n=new Set(t?.exceptIds??[]),o=this._stack.filter(a=>!n.has(a.id));L(_.WINDOWS_BEFORE_CLOSE_ALL,{candidates:o});const s=G(_.WINDOWS_CLOSE_ALL,o),i=Array.isArray(s)?s:o,r=o.filter(a=>!i.includes(a));let l=0;for(const a of i.slice())try{a.close(),l++}catch(c){typeof console<"u"&&console.error("[openstation] closeAll: window.close() threw for",a.id,c)}return L(_.WINDOWS_AFTER_CLOSE_ALL,{closed:l,skipped:r}),l}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(){j_(this)}tile(){V_(this)}isSnapEnabled(){return this._snapEnabled}setSnapEnabled(t){K_(this,t)}getSnapConfig(){return Y_(this)}enterOverview(){$_(this)}exitOverview(t,n=!1){Rt(this,t,n)}destroy(){this._overviewActive&&Rt(this),U_(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).map(i=>{const r=i.getSnapshot(),l=i.getExternalTabsSnapshot(),a=!!i.config.native,c=i.config.params,d=a&&c?this.sanitizeParams(c):null;return{id:i.id,baseId:i.config.baseId||i.id,desktopId:i.config.desktopId||this._activeDesktopId,...a?{native:!0}:{},...d?{params:d}:{},url:a?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,...l.length>0?{externalTabs:l}:{}}}),s=t&&!t.config.ephemeral?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){G_(this,t,n)}}function lE(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 Ku(e,t){if(e._overviewActive)return;const n=lE(e);if(n.length<2)return;const o=e.getFocused(),r=((o?n.indexOf(o):-1)+(t==="next"?1:-1)+n.length)%n.length,l=n[r];l.state==="minimized"?l.restore():e.focus(l)}let Yu=!1;function Xu(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;if(!t)return!1;if(t instanceof HTMLIFrameElement||t instanceof HTMLTextAreaElement)return!0;if(t instanceof HTMLInputElement)return new Set(["text","search","url","email","password","tel","number","date","datetime-local","month","week","time"]).has(t.type);if(t instanceof HTMLElement&&t.isContentEditable===!0)return!0;const n=t.getAttribute("contenteditable");return n!==null&&n!=="false"}function cE(e){if(Yu)return;Yu=!0,document.addEventListener("keydown",n=>{n.ctrlKey||n.metaKey||n.altKey||n.code==="Backquote"&&(Xu(document)||(n.preventDefault(),Ku(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"||Ku(e,o.direction==="prev"?"prev":"next")})}function Zu(e,t){const n=e.getDesktops();if(n.length<2)return!1;const o=e.getActiveDesktopId(),s=n.findIndex(l=>l.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 Ju(e,t){if(!e._overviewActive)return!1;const n=e.getDesktops(),o=n.length+1,s=n.length,i=e._overviewAddTileFocused?s:n.findIndex(a=>a.id===e.getActiveDesktopId());if(i===-1)return!1;const l=(i+(t==="next"?1:-1)+o)%o;return l===i?!1:l===s?(e._overviewAddTileFocused=!0,Hr(e),!0):(e._overviewAddTileFocused=!1,e.switchDesktop(n[l].id,{direction:t}),!0)}function dE(e){return e._overviewActive?e.exitOverview():e.enterOverview(),!0}function uE(e){return e._overviewActive||e.getAll().length===0?!1:(e.toggleShowDesktop(),!0)}function Qu(e){return e._overviewActive?(e.exitOverview(),!0):!1}function fE(e){const t=e.getAll();return t.length===0?!1:t.every(n=>n.state==="minimized")}function pE(e){return fE(e)?(e.toggleShowDesktop(),!0):!1}let ef=!1;function hE(e){ef||(ef=!0,document.addEventListener("keydown",t=>{if(t.ctrlKey||t.metaKey||t.altKey||t.shiftKey||t.code!=="ArrowLeft"&&t.code!=="ArrowRight"&&t.code!=="ArrowUp"&&t.code!=="ArrowDown"||Xu(document))return;let n=!1;switch(t.code){case"ArrowLeft":n=e._overviewActive?Ju(e,"prev"):Zu(e,"prev");break;case"ArrowRight":n=e._overviewActive?Ju(e,"next"):Zu(e,"next");break;case"ArrowUp":n=Qu(e)||pE(e)||dE(e);break;case"ArrowDown":n=Qu(e)||uE(e);break}n&&t.preventDefault()},!0))}const tf=eu;let nf=!1;function of(e){return e?document.getElementById(`wp-window-${e}`):null}function mE(){nf||(nf=!0,gE())}function gE(){Y(_.WINDOW_CONTENT_LOADING,"desktop-mode/window-loading-enter",e=>{const t=of(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");n&&(t.setAttribute("aria-busy","true"),n.classList.remove($r),n.classList.add(Zn),R_(n),_u(t),C_(t))}),Y(_.WINDOW_CONTENT_LOADED,"desktop-mode/window-loading-exit",e=>{const t=of(e?.windowId??"");if(!t)return;const n=t.querySelector(":scope .os-window__body");if(!n)return;t.removeAttribute("aria-busy");const o=!!n.querySelector(`:scope .${Yn}`)?.classList.contains(Hs);if(n.classList.remove(Zn),n.removeAttribute(Ur),!o){vu(t),uu(t);return}n.classList.add($r);const s=Gs(n);uu(t),window.setTimeout(()=>{Gs(n)===s&&(n.classList.contains(Zn)||vu(t))},tf),window.setTimeout(()=>{Gs(n)===s&&(n.classList.contains(Zn)||n.classList.remove($r))},tf+f_)}),Y(_.INIT,"desktop-mode/loading-overlay-init-sweep",()=>{queueMicrotask(()=>sf())})}function sf(){document.querySelectorAll(".os-window__body--loading").forEach(t=>{const n=t.closest(".os-window");n&&(t.querySelector(":scope .os-window__loading")?.remove(),_u(n))})}const wE="os_person_view";function yE(e){return e.searchParams.has(wE)}const to=re("desktop-mode/native-url-remap",()=>({remaps:[],deps:null}));function bE(e){to.state.deps=e}function ln(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),()=>vE(e.id)}function vE(e){const t=to.state.remaps,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function Vr(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 Ge(e){const{deps:t,remaps:n}=to.state;if(!t||!e)return!1;let o;try{o=new URL(e,t.adminUrl)}catch{return!1}const s=t.getSnapshot();for(const i of n){if(!i.matches(e,o)||i.enabled&&!i.enabled(s))continue;if(i.onMatch)try{i.onMatch(e,o)}catch(a){console.warn(`[openstation] URL remap onMatch hook threw for "${i.id}":`,a)}let r;if(i.params)try{r=i.params(e,o)??void 0}catch(a){console.warn(`[openstation] URL remap params hook threw for "${i.id}":`,a)}if(r?t.openById(i.nativeWindowId,{params:r}):t.openById(i.nativeWindowId))return!0}return!1}const qr=re("desktop-mode/destructive-admin-actions",()=>({entries:[]}));function _E(e){if(!e||typeof e.id!="string"||e.id.trim()==="")return()=>{};if(typeof e.matches!="function")return()=>{};const t=qr.state.entries,n=t.findIndex(o=>o.id===e.id);return n>=0&&t.splice(n,1),t.push(e),()=>rf(e.id)}function rf(e){const t=qr.state.entries,n=t.findIndex(o=>o.id===e);n>=0&&t.splice(n,1)}function EE(){return qr.state.entries.slice()}const kE=32,SE=64,AE=/^[a-z0-9_/-]+$/,me=re("desktop-mode/window-links",()=>({contentByWindow:new Map,focusSeq:new Map,seq:0,listeners:new Set,lastGroupsSignature:"",manager:null,started:!1}));function Ot(e){return`${e.type}:${e.id}`}function af(e){return e.root?Ot(e.root):Ot(e)}function lf(e){const t=o=>typeof o=="number"&&Number.isFinite(o)||typeof o=="string"&&o.trim()!=="",n=o=>typeof o=="string"&&AE.test(o.trim().toLowerCase());return Tt(e,[{field:"type",valid:o=>n(o.type),message:"must match /^[a-z0-9_/-]+$/ — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-type"},{field:"id",valid:o=>t(o.id),message:"must be a finite number or non-empty string"},{field:"root",valid:o=>o.root===void 0||!!o.root&&typeof o.root=="object"&&n(o.root.type)&&t(o.root.id),message:"when present, must be { type, id } with the same shapes as the ref itself"},{field:"related",valid:o=>o.related===void 0||Array.isArray(o.related)&&o.related.every(s=>!!s&&typeof s=="object"&&typeof s.id=="string"&&s.id.trim()!==""&&typeof s.group=="string"&&s.group.trim()!==""&&typeof s.label=="string"&&s.label.trim()!==""&&typeof s.url=="string"&&s.url.trim()!==""&&(s.groupLabel===void 0||typeof s.groupLabel=="string")&&(s.icon===void 0||typeof s.icon=="string")&&(s.count===void 0||typeof s.count=="number"&&Number.isFinite(s.count))),message:"when present, must be an array of { id, group, label, url, groupLabel?, icon?, count? } entries with non-empty strings"},{field:"links",valid:o=>o.links===void 0||Array.isArray(o.links)&&o.links.every(s=>!!s&&typeof s=="object"&&n(s.type)&&t(s.id)&&(s.rel===void 0||s.rel==="references"||s.rel==="child")),message:"when present, must be an array of { type, id, rel?: 'references'|'child' } entries"}])}function CE(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,kE).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,SE).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 cf(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 Kr(e){return e?[Ot(e),af(e),...(e.links??[]).map(t=>Ot(t)+(t.rel==="child"?"!child":""))].join("|"):""}function Ks(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 l=lf(t);if(l.length>0){o==="api"&&Ne("WindowContentRef",l,t),rd("WindowContentRef",l,t);return}s=CE(t,o)}if(s=G(_.WINDOW_LINKS_CONTENT,s,{windowId:e,source:o}),s!==null&&(!s||lf(s).length>0)){rd("WindowContentRef",["filter (os.window-links.content returned an invalid ref)"],s);return}const i=me.state.contentByWindow.get(e)??null;if(s===null&&i===null||s!==null&&i!==null&&Kr(s)===Kr(i)&&s.label===i.label&&s.previewUrl===i.previewUrl&&cf(s)===cf(i))return;s===null?me.state.contentByWindow.delete(e):me.state.contentByWindow.set(e,s);const r={windowId:e,content:s,previous:i,source:o};document.dispatchEvent(new CustomEvent("os-window-content-changed",{detail:r})),L(_.WINDOW_CONTENT_CHANGED,r),TE(),xE()}function lt(e){return me.state.contentByWindow.get(e)}function Ys(){const e=new Map;for(const[s,i]of me.state.contentByWindow){const r=af(i);let l=e.get(r);l||(l={key:r,root:i.root?{...i.root}:{type:i.type,id:i.id},rootWindowIds:[],children:[]},e.set(r,l)),i.root?l.children.push({windowId:s,content:i}):l.rootWindowIds.push(s)}const t=me.state.focusSeq;for(const s of e.values())s.rootWindowIds.sort((i,r)=>(t.get(r)??0)-(t.get(i)??0));const n=Array.from(e.values()),o=G(_.WINDOW_LINK_GROUPS,n);return Array.isArray(o)?o:(typeof console<"u"&&console.warn("[openstation] `os.window-links.groups` filter returned a non-array; falling back to computed groups."),n)}function df(e){return Ys().find(t=>t.rootWindowIds.includes(e)||t.children.some(n=>n.windowId===e))}function uf(e){const t=new Set,n=df(e);if(n)for(const o of[...n.rootWindowIds,...n.children.map(s=>s.windowId)])t.add(o);for(const o of no())o.fromWindowId===e?t.add(o.toWindowId):o.toWindowId===e&&t.add(o.fromWindowId);return t.delete(e),Array.from(t)}function IE(e){const t=new Set;for(const n of no())n.fromWindowId===e?t.add(n.toWindowId):n.toWindowId===e&&t.add(n.fromWindowId);return t.delete(e),Array.from(t)}function no(){const e=me.state.focusSeq,t=new Map;for(const[l,a]of me.state.contentByWindow){const c=Ot(a),d=t.get(c);(!d||(e.get(l)??0)>(e.get(d)??0))&&t.set(c,l)}const n=new Map,o=(l,a)=>`${l}→${a}`;for(const[l,a]of me.state.contentByWindow){if(a.root){const c=t.get(Ot(a.root));c&&c!==l&&n.set(o(l,c),{fromWindowId:l,toWindowId:c,kind:"child-root",bidirectional:!1})}for(const c of a.links??[]){const d=t.get(Ot(c));if(!d||d===l)continue;if(c.rel==="child"){const f=o(d,l),p=n.get(f);(!p||p.kind!=="child-root")&&n.set(f,{fromWindowId:d,toWindowId:l,kind:"child-root",bidirectional:!1});continue}const u=o(l,d);n.has(u)||n.set(u,{fromWindowId:l,toWindowId:d,kind:"reference",bidirectional:!1})}}const s=[],i=new Set;for(const[l,a]of n){if(i.has(l))continue;const c=o(a.toWindowId,a.fromWindowId),d=n.get(c);if(d&&a.kind==="reference"){if(d.kind==="reference"){i.add(c),s.push({...a,bidirectional:!0});continue}continue}s.push(a)}const r=G(_.WINDOW_LINK_EDGES,s);return Array.isArray(r)?r:(typeof console<"u"&&console.warn("[openstation] `os.window-links.edges` filter returned a non-array; falling back to derived edges."),s)}function ff(e){return me.state.listeners.add(e),()=>{me.state.listeners.delete(e)}}function xE(){for(const e of Array.from(me.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] window-links listener threw:",t)}}function LE(){return Array.from(me.state.contentByWindow).map(([e,t])=>`${e}=${Kr(t)}`).sort().join(";")}function TE(){const e=LE();if(e===me.state.lastGroupsSignature)return;me.state.lastGroupsSignature=e;const n={groups:Ys()};document.dispatchEvent(new CustomEvent("os-window-link-groups-changed",{detail:n})),L(_.WINDOW_LINK_GROUPS_CHANGED,n)}const NE={get:lt,set:(e,t)=>Ks(e,t,{source:"api"}),groups:Ys,edges:no,groupOf:df,related:uf,subscribe:ff};function DE({manager:e}){me.state.manager=e,!me.state.started&&(me.state.started=!0,Y(_.WINDOW_OPENED,"desktop-mode/window-links-seed",t=>{if(!t?.windowId)return;const o=me.state.manager?.getById(t.windowId)?.config?.content;o&&Ks(t.windowId,o,{source:"config"})}),Y(_.WINDOW_CLOSED,"desktop-mode/window-links-clear",t=>{t?.windowId&&(me.state.focusSeq.delete(t.windowId),Ks(t.windowId,null,{source:"config"}))}),Y(_.WINDOW_FOCUSED,"desktop-mode/window-links-recency",t=>{t?.windowId&&(me.state.seq+=1,me.state.focusSeq.set(t.windowId,me.state.seq))}),window.addEventListener("message",t=>{if(t.origin!==window.location.origin)return;const n=t.data;if(!n||n.type!=="os-content-identity")return;const o=me.state.manager?.findByIframeSource?.(t.source);o&&Ks(o.id,n.identity??null,{source:"bridge"})}))}const RE=re("desktop-mode/admin-link-deps",()=>({deps:null}));function OE(e){RE.state.deps=e}const pf=re("desktop-mode/wallpaper-registry",()=>({seed:[],listeners:new Set})),cn=pf.state.seed,ME=pf.state.listeners;function oo(e){Ne("Wallpaper",Tt(e,wf),e);const t=cn.findIndex(n=>n.id===e.id);t>=0?cn[t]=e:cn.push(e),mf()}function hf(e){const t=cn.findIndex(n=>n.id===e);t>=0&&(cn.splice(t,1),mf())}function mf(){const e=Array.from(ME);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] wallpaper registry listener threw:",n)}}function gf(){const e=cn.slice(),t=G(_.WALLPAPERS,e);return Array.isArray(t)?t.filter(PE):(typeof console<"u"&&console.warn("[openstation] `os.wallpapers` filter returned a non-array; falling back to seed list."),e)}function Yr(e){return gf().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 PE(e){return Tt(e,wf).length===0}const yf=re("desktop-mode/wallpaper-settings",()=>({values:{}}));function WE(e){return{...yf.state.values[e]??{}}}function $E(e){const t=yf.state.values;for(const n of Object.keys(t))delete t[n];for(const[n,o]of Object.entries(e))t[n]={...o}}function bf(e){return typeof e=="string"&&/^#[0-9a-f]{3,8}$/i.test(e)}const vf=["radius","bodyColor","bodyAlpha","hueStart","hueSpan","hueDrift","hueLoop","hueAngle","hueSpin","saturation","lightness","iridescence","outlineWidth","glow","glowBlur","eyeColor","eyeScale"],_f=["shapePreset","shapeLobes","shapeAmount","shapeAngle","shapeShuffle","idleWobble","idleWobbleSpeed"];function Xr(){return{appearance:{},physics:{}}}function UE(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"&&Number.isFinite(e)}function Xs(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&&UE(i)&&Object.assign(n,{[s]:i})}return n}function Ef(e){if(!e||typeof e!="object"||Array.isArray(e))return Xr();const t=e;return{appearance:Xs(t.appearance,vf),physics:Xs(t.physics,_f)}}function FE(e){return{appearance:Xs(e,vf),physics:Xs(e,_f)}}function BE(){const e=HE();if(e){const t=kf(e);return Jr(t),KE(t),t}try{const t=window.localStorage.getItem(Rd);if(t)return kf(JSON.parse(t))}catch{}return QE()}function HE(){const t=window.openStationConfig?.osSettings;return!t||typeof t!="object"||Array.isArray(t)?null:t}function kf(e){const t=Cr();return{wallpaper:typeof e.wallpaper=="string"&&e.wallpaper!==""?e.wallpaper:Wd(),accent:e.accent===Md||t.some(n=>n.id===e.accent)?e.accent:J.accent,customAccent:typeof e.customAccent=="string"&&/^#[0-9a-fA-F]{6}$/.test(e.customAccent)?e.customAccent:J.customAccent,dockSize:Ir.some(n=>n.id===e.dockSize)?e.dockSize:J.dockSize,windowRadius:xr.some(n=>n.id===e.windowRadius)?e.windowRadius:J.windowRadius,adminBarMode:Ps.some(n=>n.id===e.adminBarMode)?e.adminBarMode:J.adminBarMode,desktopLayout:mv.some(n=>n.id===e.desktopLayout)?e.desktopLayout:J.desktopLayout,dockPlacement:hv.some(n=>n.id===e.dockPlacement)?e.dockPlacement:J.dockPlacement,dockRailRenderer:typeof e.dockRailRenderer=="string"&&/^[a-z0-9_-]+$/.test(e.dockRailRenderer)?e.dockRailRenderer:J.dockRailRenderer,desktopTheme:typeof e.desktopTheme=="string"&&/^[a-z0-9_-]*$/.test(e.desktopTheme)?e.desktopTheme:J.desktopTheme,appliedThemeRecommendations:Array.isArray(e.appliedThemeRecommendations)?Array.from(new Set(e.appliedThemeRecommendations.filter(n=>typeof n=="string"&&/^[a-z0-9_-]+$/.test(n)))).slice(-64):J.appliedThemeRecommendations.slice(),unfocusEffect:typeof e.unfocusEffect=="string"&&/^[a-z0-9_/-]+$/.test(e.unfocusEffect)?e.unfocusEffect:J.unfocusEffect,windowReveal:typeof e.windowReveal=="string"&&/^[a-z0-9_/-]+$/.test(e.windowReveal)?e.windowReveal:J.windowReveal,windowRevealDuration:typeof e.windowRevealDuration=="number"&&Number.isFinite(e.windowRevealDuration)&&e.windowRevealDuration>0?Math.min(4e3,Math.max(80,Math.round(e.windowRevealDuration))):J.windowRevealDuration,windowLinkRenderer:typeof e.windowLinkRenderer=="string"&&/^[a-z0-9_/-]+$/.test(e.windowLinkRenderer)?e.windowLinkRenderer:J.windowLinkRenderer,windowLinkVisibility:e.windowLinkVisibility==="focus"||e.windowLinkVisibility==="always"||e.windowLinkVisibility==="off"?e.windowLinkVisibility:J.windowLinkVisibility,windowLinksEnabled:typeof e.windowLinksEnabled=="boolean"?e.windowLinksEnabled:J.windowLinksEnabled,windowLinkRaiseOnFocus:typeof e.windowLinkRaiseOnFocus=="boolean"?e.windowLinkRaiseOnFocus:J.windowLinkRaiseOnFocus,windowLinkHighlight:typeof e.windowLinkHighlight=="boolean"?e.windowLinkHighlight:J.windowLinkHighlight,customGradient:t0(e.customGradient),customImage:n0(e.customImage),wallpaperSettings:zE(e.wallpaperSettings),libraryHdOnly:typeof e.libraryHdOnly=="boolean"?e.libraryHdOnly:J.libraryHdOnly,ai:e0(e.ai),heartbeatRate:e.heartbeatRate===15||e.heartbeatRate===30||e.heartbeatRate===45||e.heartbeatRate===60?e.heartbeatRate:J.heartbeatRate,nativePostsEnabled:typeof e.nativePostsEnabled=="boolean"?e.nativePostsEnabled:J.nativePostsEnabled,nativePostsHiddenColumns:Array.isArray(e.nativePostsHiddenColumns)?e.nativePostsHiddenColumns.filter(n=>typeof n=="string"&&n!=="").slice(0,32):J.nativePostsHiddenColumns.slice(),nativePagesEnabled:typeof e.nativePagesEnabled=="boolean"?e.nativePagesEnabled:J.nativePagesEnabled,nativeUsersEnabled:typeof e.nativeUsersEnabled=="boolean"?e.nativeUsersEnabled:J.nativeUsersEnabled,nativePluginsEnabled:typeof e.nativePluginsEnabled=="boolean"?e.nativePluginsEnabled:J.nativePluginsEnabled,nativeCommentsEnabled:typeof e.nativeCommentsEnabled=="boolean"?e.nativeCommentsEnabled:J.nativeCommentsEnabled,showDesktopOnWallpaperClick:typeof e.showDesktopOnWallpaperClick=="boolean"?e.showDesktopOnWallpaperClick:J.showDesktopOnWallpaperClick,mioEnabled:typeof e.mioEnabled=="boolean"?e.mioEnabled:J.mioEnabled,mioStyle:Ef(e.mioStyle),showPostStatusRibbons:typeof e.showPostStatusRibbons=="boolean"?e.showPostStatusRibbons:J.showPostStatusRibbons,developerModeEnabled:typeof e.developerModeEnabled=="boolean"?e.developerModeEnabled:J.developerModeEnabled,foldersSharingEnabled:typeof e.foldersSharingEnabled=="boolean"?e.foldersSharingEnabled:J.foldersSharingEnabled,itemVisibility:GE(e.itemVisibility),dockOrder:jE(e.dockOrder),dockPromotedPositions:VE(e.dockPromotedPositions)}}function zE(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[l,a]of Object.entries(s)){if(r>=32)break;if(!(typeof l!="string"||l===""||!/^[a-zA-Z0-9_-]+$/.test(l))){if(typeof a=="boolean")i[l]=a;else if(typeof a=="number"&&Number.isFinite(a))i[l]=a;else if(typeof a=="string")i[l]=a.slice(0,256);else continue;r++}}r!==0&&(t[o]=i,n++)}return t}function GE(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=["both","dock","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 jE(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 VE(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 Zs=null;const qE=250;let Mt=null;function KE(e){Mt=Zr(e)}function Zr(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(),itemVisibility:{...e.itemVisibility},dockOrder:e.dockOrder.slice(),dockPromotedPositions:Object.fromEntries(Object.entries(e.dockPromotedPositions).map(([t,n])=>[t,{...n}]))}}function YE(e,t={}){Jr(e),XE(e,t.windowId)}function Jr(e){try{window.localStorage.setItem(Rd,JSON.stringify(e))}catch{}}function XE(e,t){Zs!==null&&clearTimeout(Zs),t&&(Qr=t),Pt("pending"),Zs=setTimeout(()=>{Zs=null;const n=Qr;Qr=null,JE(e,n)},qE)}let Qr=null;function ZE(e){if(!Mt)return{...e};const t=Mt,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 JE(e,t){const n=window.openStationConfig,o=n?.osSettingsUrl,s=n?.restNonce;if(!o||!s){Pt("saved");return}const i=ZE(e);if(!i){Pt("saved");return}Pt("saving");const r=t||"desktop-mode-os-settings";Be(o,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":s},body:JSON.stringify({settings:i})},{windowId:r}).then(l=>{if(!l.ok)throw new Error(`${l.status} ${l.statusText}`);Mt=Zr(e),Pt("saved")}).catch(l=>{Mt?(Jr(Mt),Pt("failed",l instanceof Error?l.message:String(l),Zr(Mt))):Pt("failed",l instanceof Error?l.message:String(l))})}function Pt(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 QE(){return{...J,customGradient:{...J.customGradient},customImage:null,wallpaperSettings:{...J.wallpaperSettings},ai:{...J.ai},appliedThemeRecommendations:[...J.appliedThemeRecommendations],itemVisibility:{...J.itemVisibility},dockOrder:[...J.dockOrder],dockPromotedPositions:{...J.dockPromotedPositions}}}function e0(e){if(!e||typeof e!="object")return{...J.ai};const{enabled:t}=e;return{enabled:typeof t=="boolean"?t:J.ai.enabled}}function t0(e){if(!e||typeof e!="object")return{...J.customGradient};const{from:t,to:n,angle:o}=e;return{from:bf(t)?t:J.customGradient.from,to:bf(n)?n:J.customGradient.to,angle:typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=360?o:J.customGradient.angle}}function n0(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 dn(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 o0(e){return typeof e!="string"||e===""||e.length>4096||!/^(https?:\/\/|data:image\/)/i.test(e)?!1:!/['"()\\<>\s]/.test(e)}function so(e,t,n){if(!o0(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 ea="data-os-constellation";function s0(){return document.body.hasAttribute(ea)}function i0(e){return`desktop:${e}`}function r0(e){return`dock:${e}`}function un(e,t,n){const o=n[e];return o||t}function Sf(e){return e==="dock"||e==="both"}function Af(e){return e==="desktop"||e==="both"}function a0(e,t,n,o,s){const i=n.itemVisibility,r=n.dockOrder,l=[];for(const a of e){const c=un(a.id,"dock",i);Sf(c)&&l.push(a)}for(const a of t){const c=un(a.id,"desktop",i),d=c!=="hidden"&&!!a.window&&!!s?.has(a.window);!Sf(c)&&!d||a.window&&o&&o.has(a.window)||l.push({id:r0(a.id),title:a.title,icon:a.icon,url:a.url||"",windowId:a.window||void 0,badge:0,submenu:[],isCore:!1})}return c0(l,r)}function l0(e,t,n){const o=[];for(const i of e){const r=un(i.id,"desktop",n);Af(r)&&o.push(i)}let s=0;for(const i of t){const r=un(i.id,"dock",n);Af(r)&&o.push({id:i0(i.id),title:i.title,icon:i.icon,window:"",url:i.url||"",position:2e3+s++})}return o}function c0(e,t){if(t.length===0||e.length<=1)return e;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&&(o.push(r),s.add(i))}for(const i of e)s.has(i.id)||o.push(i);return o}function j(e,...t){return{__wpdHtml:!0,strings:e,values:t}}function d0(e){return!!e&&e.__wpdHtml===!0}const u0="$$wpd$$",De=/\$\$wpd\$\$(\d+)\$\$/g;function f0(e){let t=e[0];for(let n=1;n<e.length;n++)t+=`${u0}${n-1}$$`+e[n];return t}const Cf=new WeakMap;function If(e){const t=Cf.get(e);if(t)return t;const n=document.createElement("template");n.innerHTML=f0(e);const o=[],s=(l,a)=>{if(l.nodeType===Node.ELEMENT_NODE){const u=l;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:a,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:a,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:a,kind:"bool",name:p.slice(1),valueIndex:h?Number(h[1]):0}),u.removeAttribute(p)}else{const h=[],b=[];let y=0,C;for(De.lastIndex=0;(C=De.exec(g))!==null;)h.push(g.slice(y,C.index)),b.push(Number(C[1])),y=C.index+C[0].length;h.push(g.slice(y)),o.push({path:a,kind:"attr",name:p,template:h,valueIndices:b}),u.setAttribute(p,"")}}}const c=Array.from(l.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=[],C=[];for(De.lastIndex=0;(b=De.exec(g))!==null;){b.index>h&&y.push(document.createTextNode(g.slice(h,b.index)));const w=document.createTextNode("");y.push(w),C.push({path:[...a,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 w of y)m.insertBefore(w,f);m.removeChild(f),d+=y.length-1,o.push(...C)}else s(f,[...a,p])}};s(n.content,[]);const r={template:n,buildParts:l=>{const a=[];for(const c of o){let d=l;for(const u of c.path)d=d.childNodes[u];c.kind==="node"?a.push({kind:"node",valueIndex:c.valueIndex,child:{anchor:d,state:null}}):c.kind==="attr"?a.push({kind:"attr",element:d,name:c.name,template:c.template,valueIndices:c.valueIndices}):c.kind==="event"?a.push({kind:"event",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="prop"?a.push({kind:"prop",valueIndex:c.valueIndex,element:d,name:c.name}):c.kind==="bool"&&a.push({kind:"bool",valueIndex:c.valueIndex,element:d,name:c.name})}return a}};return Cf.set(e,r),r}const xf=new WeakMap;function p0(e,t){for(const n of e.nodes)if(n.parentNode!==t)return!1;return!0}function h0(e,t){const n=xf.get(t);if(n&&n.strings===e.strings&&p0(n,t)){Js(n.parts,e.values);return}const o=If(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),Js(i,e.values),xf.set(t,{strings:e.strings,parts:i,nodes:r})}function Js(e,t){for(const n of e)if(n.kind==="node")ta(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+=Lf(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 ta(e,t){if(t==null||t===!1){e.state&&(Wt(e.state),e.state=null);return}if(Array.isArray(t)){y0(e,t);return}if(d0(t)){w0(e,t);return}if(t instanceof Node){m0(e,t);return}g0(e,Lf(t))}function m0(e,t){const n=e.state;n?.shape==="node"&&n.node===t||(n&&Wt(n),Qs(e,[t]),e.state={shape:"node",node:t})}function g0(e,t){const n=e.state;if(n?.shape==="text"){n.text!==t&&(n.node.textContent=t,n.text=t);return}n&&Wt(n);const o=document.createTextNode(t);Qs(e,[o]),e.state={shape:"text",node:o,text:t}}function w0(e,t){const n=e.state;if(n?.shape==="template"&&n.strings===t.strings){Js(n.parts,t.values);return}n&&Wt(n);const o=If(t.strings),s=o.template.content.cloneNode(!0),i=o.buildParts(s),r=Array.from(s.childNodes);Qs(e,[s]),Js(i,t.values),e.state={shape:"template",strings:t.strings,parts:i,nodes:r}}function y0(e,t){const n=e.state;if(n?.shape==="array"&&n.entries.length===t.length){for(let s=0;s<t.length;s++)ta(n.entries[s],t[s]);return}n&&Wt(n);const o=[];for(const s of t){const i=document.createTextNode("");Qs(e,[i]);const r={anchor:i,state:null};ta(r,s),o.push(r)}e.state={shape:"array",entries:o}}function Qs(e,t){const n=e.anchor.parentNode;if(n)for(const o of t)n.insertBefore(o,e.anchor)}function Wt(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&&(Wt(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&&Wt(t.state),t.anchor.remove()}function Lf(e){return e==null||e===!1?"":String(e)}const xt=class xt 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(Tf)}connectedCallback(){this._adoptStyles(),this.requestUpdate()}attributeChangedCallback(t,n,o){if(n===o)return;const s=b0(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=Tf(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&&h0(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(!xt._lightStylesAdopted.has(t)){xt._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)}}}};xt.props=[],xt.styles=[],xt.shadow=!0,xt._lightStylesAdopted=new WeakSet;let Ee=xt;function Ie(e,t){customElements.get(e)||customElements.define(e,t)}function Tf(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function b0(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}const v0=(()=>{try{return typeof new CSSStyleSheet().replaceSync=="function"}catch{return!1}})();function ce(e,...t){let n=e[0];for(let o=1;o<e.length;o++){const s=t[o-1];if(typeof s=="string"||typeof s=="number")n+=String(s);else if(s&&s.__wpdCss)n+=s.cssText;else throw new TypeError("[os-ui] css`` interpolations must be strings, numbers, or other css`` results. Got: "+typeof s);n+=e[o]}if(v0){const o=new CSSStyleSheet;return o.replaceSync(n),{__wpdCss:!0,sheet:o,cssText:n}}return{__wpdCss:!0,sheet:null,cssText:n}}function _0(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 l=s.getAttribute("for");l&&n.unshift(l)}s=s.parentElement}o&&t.push(na(o));for(const r of n)t.push("tab-"+na(r));const i=e.getAttribute("label");return i&&t.push(na(i)),t.length===0?"os-unnamed":"os-"+t.filter(r=>r!=="").join("-")}function na(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Nf(e){if(e.id)return e.id;const t=_0(e);return e.id=t,t}const nt=ce`:host{--_holo-fill:var( --os-ui-holo-fill,${"linear-gradient( 124deg, #afa2e8 0%, #f5a8ea 46%, #8ee9f7 100% )"} );--_holo-ink:var( --os-ui-holo-ink,#0c0b0f );--_holo-sheen:var( --os-ui-holo-sheen,linear-gradient( 124deg,rgba( 159,214,255,0.1 ) 0%,rgba( 236,155,255,0.12 ) 34%,rgba( 242,82,252,0.1 ) 58%,rgba( 147,240,198,0.09 ) 100% ) );--_holo-edge:var( --os-ui-holo-edge,linear-gradient( 124deg,rgba( 154,242,255,0.7 ) 0%,rgba( 236,155,255,0.85 ) 38%,rgba( 242,82,252,0.7 ) 62%,rgba( 159,152,255,0.6 ) 100% ) );--_holo-edge-quiet:var( --os-ui-holo-edge-quiet,linear-gradient( 124deg,rgba( 154,242,255,0.22 ) 0%,rgba( 236,155,255,0.28 ) 38%,rgba( 242,82,252,0.22 ) 62%,rgba( 159,152,255,0.2 ) 100% ) );--_holo-glow:var( --os-ui-holo-glow,0 0 0 1px rgba( 242,82,252,0.28 ),0 2px 10px rgba( 242,82,252,0.22 ) );--_holo-glow-strong:var( --os-ui-holo-glow-strong,0 0 0 1px rgba( 242,82,252,0.42 ),0 4px 18px rgba( 242,82,252,0.38 ),0 1px 3px rgba( 12,11,15,0.6 ) );--_holo-track:var( --os-ui-holo-track,rgba( 255,251,255,0.16 ) );--_holo-track-edge:var( --os-ui-holo-track-edge,#8c8f94 );--_holo-ring-color:var( --os-ui-accent-dim,#2271b1 );--_holo-focus:var( --os-ui-focus-ring,0 0 0 2px rgba( 12,11,15,0.9 ),0 0 0 4px #f252fc,0 0 12px 2px rgba( 242,82,252,0.45 ) );--_holo-focus-field:var( --os-ui-focus-ring-field,0 0 0 1px #f252fc,0 0 0 4px rgba( 242,82,252,0.18 ) );--_holo-t:var( --os-ui-holo-transition,220ms );--_holo-t-fast:var( --os-ui-motion-fast,140ms );--_holo-t-slow:var( --os-ui-motion-slow,340ms );--_holo-t-ambient:var( --os-ui-motion-ambient,12s );--_holo-spring:var( --os-ui-ease-spring,cubic-bezier( 0.32,1.5,0.55,1 ) );--_holo-ease:var( --os-ui-ease-out,cubic-bezier( 0.22,0.9,0.28,1 ) );--_holo-loop:var( --os-ui-ease-loop,cubic-bezier( 0.45,0,0.55,1 ) )}`,E0=ce` .os-holo-fill{background-color:transparent;background-image:var( --_holo-fill );background-size:220% 220%;background-position:22% 28%;background-repeat:no-repeat;color:var( --_holo-ink );transition:background-position var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease,filter var( --_holo-t ) ease}.os-holo-fill:hover{background-position:74% 66%}.os-holo-fill:active{background-position:88% 82%;filter:brightness( 0.94 )}@media ( prefers-reduced-motion:reduce ){.os-holo-fill{transition-duration:1ms}.os-holo-fill:hover,.os-holo-fill:active{background-position:22% 28%}}`,oa=ce` .os-holo-sheen{position:relative;isolation:isolate}.os-holo-sheen::before{content:'';position:absolute;inset:0;z-index:-1;border-radius:inherit;background-image:var( --_holo-sheen );background-size:200% 200%;background-position:20% 30%;opacity:0;pointer-events:none;transition:opacity var( --_holo-t ) ease,background-position var( --_holo-t ) ease}.os-holo-sheen:hover::before,.os-holo-sheen:focus-visible::before{opacity:1;background-position:76% 68%}@media ( prefers-reduced-motion:reduce ){.os-holo-sheen::before{transition-duration:1ms}.os-holo-sheen:hover::before,.os-holo-sheen:focus-visible::before{background-position:20% 30%}}`,Df=ce` .os-holo-edge{position:relative}.os-holo-edge::after{content:'';position:absolute;inset:0;border-radius:inherit;padding:1px;background-image:var( --_holo-edge-quiet );opacity:0;pointer-events:none;-webkit-mask:linear-gradient( #000 0 0 ) content-box,linear-gradient( #000 0 0 );-webkit-mask-composite:xor;mask:linear-gradient( #000 0 0 ) content-box,linear-gradient( #000 0 0 );mask-composite:exclude;transition:opacity var( --_holo-t ) ease}.os-holo-edge:hover::after,.os-holo-edge:focus-visible::after{background-image:var( --_holo-edge );opacity:1}.os-holo-edge.is-lit::after{background-image:var( --_holo-edge );opacity:1}@media ( prefers-reduced-motion:reduce ){.os-holo-edge::after{transition-duration:1ms}}`,Rf=ce` .os-holo-glint{position:absolute;inset:0;border-radius:inherit;overflow:hidden;pointer-events:none}.os-holo-glint::before{content:'';position:absolute;top:-60%;bottom:-60%;width:45%;inset-inline-start:-60%;background:linear-gradient( 90deg,transparent 0%,rgba( 255,251,255,0.14 ) 45%,rgba( 255,251,255,0.22 ) 50%,rgba( 255,251,255,0.14 ) 55%,transparent 100% );transform:rotate( 18deg ) translateX( 0 );opacity:0}:hover>.os-holo-glint::before,:focus-visible>.os-holo-glint::before,:host(:hover )>.os-holo-glint::before,:host(:focus-visible )>.os-holo-glint::before{animation:os-holo-glint var( --_holo-t-slow ) var( --_holo-ease )}@keyframes os-holo-glint{0%{opacity:0;transform:rotate( 18deg ) translateX( 0 )}15%{opacity:1}85%{opacity:1}100%{opacity:0;transform:rotate( 18deg ) translateX( 240vw )}}@media ( prefers-reduced-motion:reduce ){:hover>.os-holo-glint::before,:focus-visible>.os-holo-glint::before,:host(:hover )>.os-holo-glint::before,:host(:focus-visible )>.os-holo-glint::before{animation:none}}`,Of=ce` .os-holo-ring{position:absolute;inset:0;border-radius:inherit;box-shadow:0 0 0 0 var( --_holo-ring-color );opacity:0;pointer-events:none}:active:not(:disabled )>.os-holo-ring,:host(:active:not( [ disabled ] ) )>.os-holo-ring{animation:os-holo-ring var( --_holo-t-slow ) var( --_holo-ease )}@keyframes os-holo-ring{0%{opacity:0.45;box-shadow:0 0 0 0 var( --_holo-ring-color )}100%{opacity:0;box-shadow:0 0 0 10px transparent}}@media ( prefers-reduced-motion:reduce ){:active:not(:disabled )>.os-holo-ring,:host(:active:not( [ disabled ] ) )>.os-holo-ring{animation:none}}`,Mf=ce` .os-holo-shimmer{background-image:var( --_holo-fill );background-size:300% 300%;background-repeat:no-repeat;animation:os-holo-shimmer 2.4s var( --_holo-loop ) infinite}@keyframes os-holo-shimmer{0%{background-position:0% 50%}100%{background-position:100% 50%}}@media ( prefers-reduced-motion:reduce ){.os-holo-shimmer{animation:none;background-position:30% 50%}}`,k0=ce` .os-holo-enter{animation:os-holo-enter var( --_holo-t ) var( --_holo-spring )}@keyframes os-holo-enter{from{opacity:0;transform:scale( 0.96 )}}@media ( prefers-reduced-motion:reduce ){.os-holo-enter{animation:none}}`,sa=ce` input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ),select,textarea{transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):hover:not(:disabled ),select:hover:not(:disabled ),textarea:hover:not(:disabled ){border-color:var( --os-ui-border-strong,#8c8f94 )}input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):focus,input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ):focus-visible,select:focus,select:focus-visible,textarea:focus,textarea:focus-visible{outline:none;border-color:var( --os-ui-accent,#2271b1 );box-shadow:var( --_holo-focus-field )}input::placeholder,textarea::placeholder{color:var( --os-ui-fg-faint,#8c8f94 );opacity:1}input::selection,textarea::selection{background:var( --os-ui-selection-bg,rgba( 159,152,255,0.6 ) );color:var( --os-ui-selection-fg,#fffbff )}@media ( prefers-reduced-motion:reduce ){input:where(:not( [ type='checkbox' ] ):not( [ type='radio' ] ) ),select,textarea{transition-duration:1ms}}`,S0=ce` input[ type='checkbox' ],input[ type='radio' ]{appearance:none;-webkit-appearance:none;position:relative;flex:0 0 auto;box-sizing:border-box;width:16px;height:16px;margin:0;padding:0;border:1px solid var( --_holo-track-edge );border-radius:4px;background-color:var( --_holo-track );background-image:none;background-repeat:no-repeat;cursor:inherit;transition:background-color var( --_holo-t ) ease,border-color var( --_holo-t ) ease,box-shadow var( --_holo-t ) ease}input[ type='radio' ]{border-radius:50%}input[ type='checkbox' ]:hover:not(:disabled ),input[ type='radio' ]:hover:not(:disabled ){border-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:focus-visible,input[ type='radio' ]:focus-visible{outline:none;box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked,input[ type='checkbox' ]:indeterminate,input[ type='radio' ]:checked{border-color:transparent;background-color:var( --os-ui-accent,#2271b1 )}input[ type='checkbox' ]:checked:focus-visible,input[ type='radio' ]:checked:focus-visible{box-shadow:var( --_holo-focus )}input[ type='checkbox' ]:checked::after{content:'';position:absolute;inset-inline-start:50%;top:46%;width:3.5px;height:7.5px;border:solid var( --os-ui-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}}`,Pf=ce` @keyframes os-holo-drift{0%{background-position:16% 26%}50%{background-position:84% 74%}100%{background-position:16% 26%}}.os-holo-alive{animation:os-holo-drift var( --_holo-t-ambient ) var( --_holo-loop ) infinite}@media ( prefers-reduced-motion:reduce ){.os-holo-alive{animation:none}}`;ce` ${nt} ${E0} ${oa} ${Df} ${Rf} ${Of} ${Mf} ${k0} ${sa} ${S0} ${Pf} `;const A0=ce` ${nt}: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}:host( [ open ] ){display:flex;animation:os-confirm-scrim var( --_holo-t ) var( --_holo-ease )}:host( [ open ] ) .dialog{animation:os-confirm-dialog var( --_holo-t ) var( --_holo-spring )}@keyframes os-confirm-scrim{from{opacity:0}}@keyframes os-confirm-dialog{from{opacity:0;transform:scale( 0.96 ) translateY( 8px )}}@media ( prefers-reduced-motion:reduce ){:host( [ open ] ),:host( [ open ] ) .dialog{animation:none}}.dialog{width:min( 420px,92vw );background-color:var( --os-ui-confirm-dialog-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-confirm-dialog-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 );padding:20px 22px 18px;display:flex;flex-direction:column;gap:10px;position:relative}.close{position:absolute;top:8px;right:10px;width:28px;height:28px;display:inline-flex;align-items:center;justify-content:center;background:transparent;border:0;border-radius:6px;color:var( --os-ui-confirm-dialog-fg-muted,var( --os-ui-fg-muted,rgba( 255,255,255,0.7 ) ) );cursor:pointer;font-size:22px;line-height:1;padding:0}.close:hover{background:var( --os-ui-hover,rgba( 255,255,255,0.08 ) );color:inherit}.btn:focus,.close:focus{outline:none;box-shadow:var( --_holo-focus )}.dialog:focus,.dialog:focus-visible{outline:none}.title{margin:0 0 4px;font-size:16px;font-weight:600}.message{margin:0;color:var( --os-ui-confirm-dialog-fg-muted,var( --os-ui-fg-muted,rgba( 255,255,255,0.7 ) ) );line-height:1.45;white-space:pre-line}.actions{display:flex;justify-content:flex-end;gap:8px;margin-top:6px}.btn{border:0;border-radius:6px;padding:8px 14px;font-size:13px;cursor:pointer;font-weight:500}.btn--secondary{background:var( --os-ui-hover,rgba( 255,255,255,0.08 ) );color:inherit}.btn--secondary:hover{background:var( --os-ui-hover,rgba( 255,255,255,0.14 ) )}.btn--primary{background:var( --wp-admin-theme-color,#2271b1 );color:var( --os-ui-fg-on-accent,#fff )}.btn--primary:hover{filter:brightness( 1.08 )}.btn--danger{background:var( --os-ui-danger,#d63638 );color:var( --os-ui-fg-on-accent,#fff )}.btn--danger:hover{filter:brightness( 1.08 )}`,Wf='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function C0(e){let t=e?.activeElement??null;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t&&t!==e?.body?t:null}function $f(e){const t=e.composedPath(),n=t.length>0?t[0]:e.target;return n instanceof HTMLElement?n:null}function Uf(e){return e!==null&&e.matches(Wf)}const cs=class cs extends Ee{constructor(){super(...arguments),this._prevFocus=null,this._focusTries=0,this._onKey=t=>{if(t.key==="Escape"){t.preventDefault(),this._cancel();return}if(t.key==="Tab"){this._trapTab(t);return}if(t.key==="Enter"&&!t.isComposing){if(Uf($f(t))||this.hasAttribute("danger"))return;t.preventDefault(),this._confirm()}},this._focusInitial=()=>{if(!this.hasAttribute("open"))return;const t=this.isConnected?this._initialFocusTarget():null;if(t){t.focus();return}if(this._focusTries++<5){queueMicrotask(this._focusInitial);return}this.isConnected&&this.focus()},this._onBackdrop=t=>{const n=t.composedPath();(n.length>0?n[0]:t.target)===this&&this._cancel()},this._confirm=()=>{this.emit("os-confirm",{confirmed:!0}),this.removeAttribute("open")},this._cancel=()=>{this.emit("os-cancel",{confirmed:!1}),this.removeAttribute("open")}}connectedCallback(){super.connectedCallback(),this.setAttribute("role","dialog"),this.setAttribute("aria-modal","true"),this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),this.addEventListener("keydown",this._onKey),this.addEventListener("click",this._onBackdrop)}disconnectedCallback(){this.removeEventListener("keydown",this._onKey),this.removeEventListener("click",this._onBackdrop),this._restoreFocus()}attributeChangedCallback(t,n,o){super.attributeChangedCallback(t,n,o),t==="open"&&(o!==null?(this._prevFocus=C0(this.ownerDocument),this._focusTries=0,queueMicrotask(this._focusInitial)):this._restoreFocus())}_focusables(){const t=this.shadowRoot;return t?Array.from(t.querySelectorAll(Wf)):[]}_trapTab(t){const n=this._focusables();if(n.length===0)return;const o=n[0],s=n[n.length-1],i=$f(t),r=!Uf(i);t.shiftKey&&(r||i===o)?(t.preventDefault(),s.focus()):!t.shiftKey&&(r||i===s)&&(t.preventDefault(),o.focus())}_initialFocusTarget(){const t=this.shadowRoot;if(!t)return null;const n=t.querySelector(".btn--secondary"),o=t.querySelector(".dialog");return this.hasAttribute("danger")?n??t.querySelector(".close")??o:t.querySelector(".btn--primary, .btn--danger")??n??o}_restoreFocus(){const t=this._prevFocus;this._prevFocus=null,!(!t||!t.isConnected)&&t.focus()}render(){const t=this.title??"",n=this.message??"",o=this["confirm-label"]||"Confirm",s=this["cancel-label"]||"Cancel",i=this.hasAttribute("danger"),r=this.hasAttribute("hide-cancel"),l=this.hasAttribute("dismissable");return j` |
| 2 |
<div class="dialog" tabindex="-1"> |
| 3 |
${l?j`<button |
| 4 |
type="button" |
| 5 |
class="close" |
| 6 |
aria-label="Close" |
| 7 |
@click=${()=>this._cancel()} |
| 8 |
>×</button>`:j``} |
| 9 |
${t?j`<h2 class="title">${t}</h2>`:j``} |
| 10 |
${n?j`<p class="message">${n}</p>`:j``} |
| 11 |
<div class="actions"> |
| 12 |
${r?j``:j`<button |
| 13 |
type="button" |
| 14 |
class="btn btn--secondary" |
| 15 |
@click=${()=>this._cancel()} |
| 16 |
> |
| 17 |
${s} |
| 18 |
</button>`} |
| 19 |
<button |
| 20 |
type="button" |
| 21 |
class="btn ${i?"btn--danger":"btn--primary"}" |
| 22 |
@click=${()=>this._confirm()} |
| 23 |
> |
| 24 |
${o} |
| 25 |
</button> |
| 26 |
</div> |
| 27 |
</div> |
| 28 |
`}};cs.props=["open","title","message","confirm-label","cancel-label","danger","hide-cancel","dismissable"],cs.styles=[A0],cs.help=void 0;let ia=cs;Ie("os-confirm-dialog",ia);function Ff(e){return 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)})}const ra=8;function Bf(e,t){e.style.visibility="hidden";const n=()=>{e.isConnected&&(t(e.getBoundingClientRect()),e.style.visibility="")};typeof requestAnimationFrame=="function"?requestAnimationFrame(n):n()}function aa(e){Bf(e,t=>{t.right>window.innerWidth&&(e.style.left=`${Math.max(0,window.innerWidth-t.width-ra)}px`),t.bottom>window.innerHeight&&(e.style.top=`${Math.max(0,window.innerHeight-t.height-ra)}px`)})}function Hf(e,t){const n=t.getBoundingClientRect();e.style.position="fixed",e.style.left=`${n.right}px`,e.style.top=`${n.top}px`,Bf(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-ra)}px`)})}const ei="os-item-menu-opening",I0=180,x0=220,zf=32;function Gf(e){const{tile:t}=e;let n=null,o=null,s=null,i=!1,r=null;const l=()=>{o!==null&&(window.clearTimeout(o),o=null)},a=()=>{s!==null&&(window.clearTimeout(s),s=null)},c=()=>{l(),a(),t.removeAttribute("data-peek-active"),n&&(n.remove(),n=null),r?.clear(),r=null,e.suppressTooltip(!1)},d=m=>{m.pointerType==="mouse"&&(s0()&&(t.dataset.menuSlug||t.dataset.constellationId)||L0(e)&&(i=!0,a(),!n&&(o=window.setTimeout(()=>{o=null,i&&p()},I0))))},u=m=>{n&&m.relatedTarget instanceof Node&&n.contains(m.relatedTarget)||(i=!1,l(),f())},f=()=>{a(),s=window.setTimeout(()=>{s=null,!i&&c()},x0)},p=()=>{e.suppressTooltip(!0),t.setAttribute("data-peek-active",""),r=new Map,n=T0(e,()=>c(),r),document.body.appendChild(n),W0(n),$0(n,t,e.getOrientation()),requestAnimationFrame(()=>{n?.classList.add("os-dock-peek--open")}),n.addEventListener("pointerenter",()=>{i=!0,a()}),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(ei,g),()=>{t.removeEventListener("pointerenter",d),t.removeEventListener("pointerleave",u),document.removeEventListener(ei,g),c()}}function L0(e){return e.getInstances().length>=1}function T0(e,t,n){const o=document.createElement("div");o.className="os-dock-peek",o.setAttribute("role","menu"),o.setAttribute("aria-label",le(k("%s — open windows"),e.item.title));const s=document.createElement("div");s.className="os-dock-peek__cards",o.appendChild(s);const i=e.getInstances();let r=0;for(const l of i){const a=N0(l,e,r++,t,n);s.appendChild(a)}if(e.enableGhost!==!1){const l=R0(e,r,t);s.appendChild(l)}return o}function jf(e,t){e.state==="minimized"&&(e.restore(),t&&delete t.dataset.state)}function N0(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*zf}ms`);const r=e.config.title||t.item.title;i.style.setProperty("--peek-card-hue",`${dn(e.id||r)}`),i.style.setProperty("--peek-card-vt-name",`os-peek-card-${e.id}`);const l=document.createElement("span");l.className="os-dock-peek__card-titlebar";const a=document.createElement("span");a.className="os-dock-peek__card-dots",a.setAttribute("aria-hidden","true");for(let y=0;y<3;y++)a.appendChild(document.createElement("i"));l.appendChild(a);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",Zc(d)):c.classList.add("dashicons","dashicons-admin-generic"),l.appendChild(c);const u=document.createElement("span");u.className="os-dock-peek__card-label",u.textContent=r,l.appendChild(u),i.appendChild(l);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 C=document.createElement("span");C.className="os-dock-peek__card-line",f.appendChild(C)}const p={window:e,item:t.item},g=G(_.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 C=t.windowManager.getById(y.previouslyFocusedId);C&&t.windowManager.focus(C)}};return i.addEventListener("click",()=>{m(),D0(t,e,i,o)}),i.addEventListener("pointerenter",()=>{if(s.has(e.id))return;const y=e.state==="minimized",C=t.windowManager.getFocused(),w=C&&C!==e?C.id:null;(y||w!==null)&&(s.set(e.id,{wasMinimized:y,previouslyFocusedId:w}),i.dataset.preview=""),y?jf(e,i):C&&C!==e&&t.windowManager.focus(e)}),i.addEventListener("pointerleave",()=>{const y=s.get(e.id);y&&h(y)}),G(_.DOCK_PEEK_CARD_ELEMENT,i,p)}function D0(e,t,n,o){const s=document,i=`os-peek-card-${t.id}`,r=()=>{o(),jf(t,n),e.windowManager.focus(t)};if(typeof s.startViewTransition!="function"){r();return}const l=t.element;n.style.setProperty("view-transition-name",i),l.style.setProperty("view-transition-name",i);const a=s.startViewTransition(r),c=()=>{n.style.removeProperty("view-transition-name"),l.style.removeProperty("view-transition-name")},d=a;d.finished&&typeof d.finished.then=="function"?d.finished.then(c,c):Promise.resolve().then(c)}function R0(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*zf}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(k("New %s"),e.item.title),o.appendChild(i),o.addEventListener("click",()=>{O0(e,n)}),o}function O0(e,t){const n=document,o=()=>{t(),e.openNew()};if(typeof n.startViewTransition=="function"){n.startViewTransition(o);return}o()}const M0=12,P0=["--wp-admin-theme-color","--os-titlebar-bg","--os-titlebar-bg-focused","--os-titlebar-color","--os-titlebar-color-focused"];function W0(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of P0){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function $0(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(()=>U0(e))}function U0(e,t){const n=e.getBoundingClientRect(),o=window.innerHeight,s=window.innerWidth,i=M0;let r=0,l=0;n.top<i?r=i-n.top:n.bottom>o-i&&(r=o-i-n.bottom),n.left<i?l=i-n.left:n.right>s-i&&(l=s-i-n.right),!(l===0&&r===0)&&(e.style.setProperty("--peek-clamp-x",`${l}px`),e.style.setProperty("--peek-clamp-y",`${r}px`),e.classList.add("os-dock-peek--clamped"))}function fn(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 la=new Map;function F0(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 Se(e,t){const n=la.get(e);if(n)return n;const o=new Promise((s,i)=>{const r=`script[data-os-vendor="${B0(e)}"]`,l=document.querySelector(r);if(l){if(l.dataset.loaded==="1"){s();return}l.addEventListener("load",()=>s(),{once:!0}),l.addEventListener("error",()=>i(new Error(`Failed to load ${e}`)),{once:!0});return}const a=F0(e);if(a){a.dataset.osVendor=e,a.dataset.loaded="1",s();return}t?.translations&&ti(t.translations);for(const d of t?.l10n??[])ti(d);for(const d of t?.before??[])ti(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??[])ti(d);s()},{once:!0}),c.addEventListener("error",()=>{la.delete(e),c.remove(),i(new Error(`Failed to load ${e}`))},{once:!0}),document.head.appendChild(c)});return la.set(e,o),o}function ti(e){if(!e)return;const t=document.createElement("script");t.textContent=e,t.dataset.osVendorInline="1",document.head.appendChild(t)}function B0(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}let Vf=0;function qf(){return window.openStationItemVisibilityMenu??null}function H0(){return window.openStationConfig?.itemVisibilityMenuBundleUrl??""}function Kf(e){const t=qf();if(t){t.openItemVisibilityMenu(e);return}const n=H0();if(!n)return;const o=++Vf;Se(n).then(()=>{o===Vf&&qf()?.openItemVisibilityMenu(e)}).catch(s=>{typeof console<"u"&&console.warn("[openstation] item-visibility-menu bundle failed to load; menu suppressed:",s)})}const $e=class $e{constructor(t,n,o,s,i="left"){this.itemElements=new Map,this.systemItems=[],this.systemItemElements=new Map,this.systemSeparator=null,this.badgeOverrides=new Map,this.artOverrides=new Map,this.attentionTimers=new Map,this.peekTeardowns=new Map,this.boundRefresh=()=>{},this.container=t,this.windowManager=n,this.items=o,this.adminUrl=s,this.orientation=i,this.rail=i==="bottom"?"taskbar":"dock",this.hooksNamespace=`desktop-mode/dock/${++$e.instanceCounter}`,this.container.classList.add("os-dock--no-transition"),this.container.setAttribute("data-os-dock-placement",i),this.container.offsetWidth,this.container.classList.remove("os-dock--no-transition");const r=document.createElement("div");r.className="os-dock__scroll";const l=document.createElement("div");l.className="os-dock__pinned",t.appendChild(r),t.appendChild(l),this.itemHost=r,this.systemHost=l,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.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){for(const i of this.itemElements.keys()){const r=this.peekTeardowns.get(i);r&&(r(),this.peekTeardowns.delete(i))}for(const i of this.itemElements.values())i.remove();this.itemHost.querySelectorAll(".os-dock__separator--group").forEach(i=>i.remove()),this.itemElements.clear(),this.items=t;const n=this.buildHookContextBase();L(_.DOCK_BEFORE_RENDER,{...n,items:t,tileElements:this.itemElements});let o=!1,s=0;for(const i of t){if(!o&&i.isCore===!1){if(s>0){const c=document.createElement("div");c.className="os-dock__separator os-dock__separator--group",c.setAttribute("aria-hidden","true"),this.itemHost.appendChild(c)}o=!0}const r=this.createItemButton(i);this.itemElements.set(i.id,r),this.itemHost.appendChild(r),s++;const l=this.badgeOverrides.get(i.id);if(l!==void 0){const c=r.querySelector(".os-dock__item-primary");Yf(c??r,l)}const a=this.artOverrides.get(i.id);a&&this._paintArt(r,i.id,a),L(_.DOCK_TILE_RENDERED,{...n,item:i,isSystem:!1,el:r})}this.updateActiveStates(),L(_.DOCK_AFTER_RENDER,{...n,items:t,tileElements:this.itemElements})}hasItems(){return this.itemElements.size>0||this.systemItemElements.size>0}removeSystemItem(t){const n=this.systemItemElements.get(t);n&&(n.remove(),this.systemItemElements.delete(t),this.systemItems=this.systemItems.filter(o=>o.id!==t),this.badgeOverrides.delete(t),this.artOverrides.delete(t),this.systemSeparator&&!this.systemHost.querySelector(".os-dock__item")&&(this.systemSeparator.remove(),this.systemSeparator=null),L(_.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");Yf(i??o,s),ke.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),ke.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),ke.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,Us(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 l=o.durationMs??4e3;if(l>0){const a=window.setTimeout(()=>{this.attentionTimers.delete(t),this.setAttention(t,null)},l);this.attentionTimers.set(t,a)}}_resolveTileElement(t){return this.itemElements.get(t)??this.systemItemElements.get(t)??null}_systemSlotFor(t,n){const o=t.order??0;for(const s of Array.from(n.children))if(s instanceof HTMLElement&&s.dataset.systemOrder!==void 0&&Number(s.dataset.systemOrder)>o)return s;return null}appendSystemItem(t){this.systemItems.push(t);const n=this.systemHost;this.systemSeparator||(this.systemSeparator=document.createElement("div"),this.systemSeparator.className="os-dock__separator",this.systemSeparator.setAttribute("aria-hidden","true"),this.systemHost.appendChild(this.systemSeparator));const o=this.createSystemItemButton(t);this.systemItemElements.set(t.id,o);const s=this.artOverrides.get(t.id);s&&this._paintArt(o,t.id,s),o.dataset.systemOrder=String(t.order??0),n.insertBefore(o,this._systemSlotFor(t,n)),this.updateActiveStates(),L(_.DOCK_TILE_RENDERED,{...this.buildHookContextBase(),item:t,isSystem:!0,el:o})}render(){if($e.activeDragReset){const o=$e.activeDragReset;$e.activeDragReset=null,o()}for(const o of this.peekTeardowns.values())o();this.peekTeardowns.clear(),this.itemHost.innerHTML="";const t=this.buildHookContextBase();L(_.DOCK_BEFORE_RENDER,{...t,items:this.items,tileElements:this.itemElements});let n=!1;for(const o of this.items){if(!n&&o.isCore===!1){if(this.itemHost.childElementCount>0){const i=document.createElement("div");i.className="os-dock__separator os-dock__separator--group",i.setAttribute("aria-hidden","true"),this.itemHost.appendChild(i)}n=!0}const s=this.createItemButton(o);this.itemElements.set(o.id,s),this.itemHost.appendChild(s),L(_.DOCK_TILE_RENDERED,{...t,item:o,isSystem:!1,el:s})}L(_.DOCK_AFTER_RENDER,{...t,items:this.items,tileElements:this.itemElements})}createSystemItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!0},o=document.createElement("div"),s=["os-dock__item","os-dock__item--system"],i=G(_.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.systemId=t.id,t.submenu&&t.submenu.length>0&&(o.dataset.constellationId=t.id);const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title),r.appendChild(this.resolveIcon(t.icon,t.title,void 0,Us(t.id))),r.addEventListener("click",()=>t.onOpen()),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const l=Gf({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:a=>{a&&this.tooltip.classList.remove("os-dock__tooltip--visible")}});return this.peekTeardowns.set(`system:${t.id}`,l),G(_.DOCK_TILE_ELEMENT,o,n)}createItemButton(t){const n={...this.buildHookContextBase(),item:t,isSystem:!1},o=document.createElement("div"),s=["os-dock__item"];t.multi&&s.push("os-dock__item--multi");const i=G(_.DOCK_TILE_CLASS,s,n);o.className=i.join(" "),o.dataset.menuSlug=t.id;const r=document.createElement("button");r.className="os-dock__item-primary",r.setAttribute("type","button"),r.setAttribute("aria-label",t.title);const l=this.resolveIcon(t.icon,t.title,t.url,Us(t.id));if(r.appendChild(l),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(en("%d update","%d updates",t.badge),t.badge)),r.appendChild(u)}r.addEventListener("click",()=>{this.openPage(t)}),o.addEventListener("contextmenu",d=>{d.preventDefault(),Kf({x:d.clientX,y:d.clientY,id:t.id,title:t.title,surface:"dock",pluginFile:t.pluginFile??null,pluginName:t.pluginName??null})}),o.appendChild(r),this.bindTooltipFiltered(o,t.title,n);const a=this.resolveItemBaseId(t),c=Gf({tile:o,item:{id:t.id,title:t.title,icon:t.icon,url:t.url},getInstances:()=>this.windowManager.getAllByBaseIdOnActiveDesktop(a),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.attachDragReorder(o,t.id),G(_.DOCK_TILE_ELEMENT,o,n)}attachDragReorder(t,n){let i=!1,r=0,l=0,a=[],c=null,d=-1,u=null,f=!1;const p=()=>{i=!1,t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",y),document.removeEventListener("pointerup",T),document.removeEventListener("pointercancel",M),document.removeEventListener("keydown",P,!0),window.removeEventListener("blur",v),document.removeEventListener("visibilitychange",$),d=-1,u=null},g=D=>!!D&&D instanceof HTMLElement&&D.classList.contains("os-dock__item")&&!D.classList.contains("os-dock__item--system")&&!!D.dataset.menuSlug,m=D=>{for(const I of Array.from(this.itemHost.children))I instanceof HTMLElement&&I!==t&&g(I)&&D(I)},h=()=>{const D=[];for(const I of Array.from(this.itemHost.children))g(I)&&D.push(I.dataset.menuSlug);return D},b=D=>{m(I=>{const W=D.get(I);if(!W)return;const z=I.getBoundingClientRect(),q=W.left-z.left,K=W.top-z.top;if(Math.abs(q)<.5&&Math.abs(K)<.5)return;I.style.transition="none",I.style.transform=`translate(${q}px, ${K}px)`,I.offsetHeight,I.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",I.style.transform="";const x=()=>{I.style.transition="",I.style.transform="",I.removeEventListener("transitionend",x)};I.addEventListener("transitionend",x)})},y=D=>{if(d!==-1&&D.pointerId!==d)return;if(!i){const S=D.clientX-r,O=D.clientY-l;if(S*S+O*O<5*5)return;i=!0,a=h(),c=t.nextSibling,u=t.getBoundingClientRect(),t.classList.add("os-dock__item--dragging"),this.tooltip.classList.remove("os-dock__tooltip--visible")}if(!u)return;const I=D.clientX-r,W=D.clientY-l;t.style.transform=`translate(${I}px, ${W}px)`;const q=document.elementFromPoint(D.clientX,D.clientY)?.closest(".os-dock__item");if(!q||q===t||!g(q))return;const K=q.getBoundingClientRect();let x;this.orientation==="bottom"?x=D.clientX<K.left+K.width/2:x=D.clientY<K.top+K.height/2;const F=new Map;m(S=>{F.set(S,S.getBoundingClientRect())});let R=!1;if(x?q!==t.nextSibling&&(this.itemHost.insertBefore(t,q),R=!0):q.nextSibling!==t&&(this.itemHost.insertBefore(t,q.nextSibling),R=!0),R){t.style.transform="";const S=t.getBoundingClientRect();r=S.left+S.width/2,l=S.top+S.height/2,t.style.transform=`translate(${D.clientX-r}px, ${D.clientY-l}px)`,b(F)}},C=()=>{t.classList.remove("os-dock__item--dragging"),t.style.transform="",t.style.transition="",document.removeEventListener("pointermove",y),document.removeEventListener("pointerup",T),document.removeEventListener("pointercancel",M),document.removeEventListener("keydown",P,!0),window.removeEventListener("blur",v),document.removeEventListener("visibilitychange",$),d=-1,u=null,i=!1,$e.activeDragReset===p&&($e.activeDragReset=null)},w=()=>{t.style.transition="transform 200ms cubic-bezier(0.2, 0.7, 0.3, 1)",t.style.transform="";const D=()=>{t.style.transition="",t.removeEventListener("transitionend",D)};t.addEventListener("transitionend",D)},E=D=>{const I=window.wp?.os;if(!I?.getOsSettings||!I?.updateOsSettings)return;const W=I.getOsSettings().dockOrder,z=new Set(D),q=[];let K=!1;for(const x of W){if(z.has(x)){K||(q.push(...D),K=!0);continue}q.push(x)}K||q.push(...D),I.updateOsSettings({dockOrder:q})},T=D=>{if(d!==-1&&D.pointerId!==d)return;if(!i){C();return}f=!0;const I=h();w(),C(),I.length===a.length&&I.every((z,q)=>z===a[q])||E(I),setTimeout(()=>{f=!1},200)},M=D=>{if(!(D&&d!==-1&&D.pointerId!==d)){if(i&&c!==void 0){const I=new Map;m(W=>{I.set(W,W.getBoundingClientRect())}),this.itemHost.insertBefore(t,c),b(I)}w(),C()}},P=D=>{D.key==="Escape"&&M()},v=()=>M(),$=()=>{document.visibilityState!=="visible"&&M()};t.addEventListener("pointerdown",D=>{if(D.button===0){if($e.activeDragReset){const I=$e.activeDragReset;$e.activeDragReset=null,I()}(i||d!==-1)&&p(),r=D.clientX,l=D.clientY,d=D.pointerId,i=!1,$e.activeDragReset=p,document.addEventListener("pointermove",y),document.addEventListener("pointerup",T),document.addEventListener("pointercancel",M),document.addEventListener("keydown",P,!0),window.addEventListener("blur",v),document.addEventListener("visibilitychange",$)}}),t.addEventListener("click",D=>{f&&(D.preventDefault(),D.stopImmediatePropagation())},!0)}resolveIcon(t,n,o,s){let i=!1,r=null;if(s){const l=$s(s);l!==null&&(t=l,i=!0),r=Tr(s)}if(r!==null&&!t.startsWith("dashicons-")){const l=this._makeMaskSpan();if(so(l,t,r))return l}if(t.startsWith("dashicons-")&&(i||t!=="dashicons-admin-generic")){const l=document.createElement("span");return l.className=`dashicons ${t}`,l.setAttribute("aria-hidden","true"),r!==null&&(l.style.color=r),l}if(t.startsWith("data:image/svg+xml;base64,")){const l=t.slice(26);if(/^[A-Za-z0-9+/=]+$/.test(l))return this._makeSvgIcon(t)}if(t.startsWith("url("))return this._makeSvgIcon(t);if(t.startsWith("http://")||t.startsWith("https://")){const l=document.createElement("img");return l.className="os-dock__item-img",l.src=t,l.alt="",l.setAttribute("aria-hidden","true"),l}if(o&&!i){const l=this._extractNativeMenuIcon(o);if(l)return l}if(t==="dashicons-admin-generic"){const l=document.createElement("span");return l.className="dashicons dashicons-admin-generic",l.setAttribute("aria-hidden","true"),l}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(so(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 l=r.querySelector("img");if(l&&l.src){const f=document.createElement("img");return f.className="os-dock__item-img",f.src=l.src,f.alt="",f.setAttribute("aria-hidden","true"),f}const a=r.className.match(/\bdashicons-[\w-]+\b/);if(a&&a[0]!=="dashicons-before"){const f=document.createElement("span");return f.className=`dashicons ${a[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=dn(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=G(_.DOCK_TILE_TOOLTIP,n,o);t.dataset.dockTooltip=s,s!==""&&(t.addEventListener("pointerenter",()=>{this.positionTooltip(t,s),this.tooltip.classList.add("os-dock__tooltip--visible")}),t.addEventListener("pointerleave",()=>{this.tooltip.classList.remove("os-dock__tooltip--visible")}))}positionTooltip(t,n){const o=t.getBoundingClientRect();this.tooltip.textContent=n,this.orientation==="bottom"?(this.tooltip.style.left=`${o.left+o.width/2}px`,this.tooltip.style.top=`${o.top-14}px`):this.orientation==="right"?(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.left}px`):(this.tooltip.style.top=`${o.top+o.height/2-14}px`,this.tooltip.style.left=`${o.right+8}px`)}openPage(t){if(t.id.startsWith("dock:")){const o=t.id.slice(5),i=window.openStationConfig?.desktopIcons?.find(r=>r.id===o);if(i?.window){window.wp?.os?.openWindow?.(i.window);return}if(i?.url){if(fn(i.url))return;const r=this.deriveWindowId(i.url);this.windowManager.open({id:r,baseId:r,url:i.url,parentUrl:i.url,title:i.title,icon:i.icon.startsWith("dashicons-")?i.icon:"dashicons-admin-generic",submenu:[],multi:!1});return}return}if(fn(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(fn(t.url))return;const n=window.wp?.os?.openNewWindow;if(t.windowId&&!t.url&&n?.(t.windowId,{source:"dock-peek"}))return;const o=Vr(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 ae(t,this.adminUrl)}resolveItemBaseId(t){if(t.windowId)return t.windowId;if(t.id.startsWith("dock:")){const o=t.id.slice(5),i=window.openStationConfig?.desktopIcons?.find(r=>r.id===o);if(i?.window)return i.window;if(i?.url)return Vr(i.url)??this.deriveWindowId(i.url)}return Vr(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?.(_.WINDOW_MINIMIZED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(_.WINDOW_RESTORED,this.hooksNamespace,t),window.wp?.hooks?.addAction?.(_.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?.(_.WINDOW_MINIMIZED,this.hooksNamespace),window.wp?.hooks?.removeAction?.(_.DOCK_REFRESH_ACTIVE,this.hooksNamespace),window.wp?.hooks?.removeAction?.(_.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.systemSeparator=null,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 l=this.resolveItemBaseId(i);let a=this.windowManager.getAllByBaseId(l).filter(o);if(a.length===0&&i.url){const f=this.deriveWindowId(i.url);a=this.windowManager.getAll().filter(p=>{const g=p.config.baseId||p.id;if(g===l||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===l||m===f}return!1}).filter(o)}const c=a.length>0,d=c&&a.every(s),u=!!t&&o(t)&&!s(t)&&a.some(f=>f.id===t.id||(t.config.baseId||t.id)===l);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&&a.length>1)}for(const i of this.systemItems){const r=this.systemItemElements.get(i.id);if(!r)continue;const l=this.windowManager.getById(i.id),a=i.isOpen?i.isOpen():!!l,c=!!l&&s(l),d=!!t&&t.id===i.id&&!s(t);r.classList.toggle("os-dock__item--active",a),r.classList.toggle("os-dock__item--focused",d),r.classList.toggle("os-dock__item--all-minimized",c)}this.updateShowDesktopBodyClass()}updateShowDesktopBodyClass(){const t=this.windowManager.getActiveDesktopId(),n=this.windowManager.getAll().filter(s=>(s.config.desktopId||t)===t),o=n.length>0&&n.every(s=>s.state==="minimized");document.body.classList.toggle("os-show-desktop-active",o)}};$e.instanceCounter=0,$e.activeDragReset=null;let ni=$e;function Yf(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(en("%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(en("%d notification","%d notifications",t),t)),e.appendChild(s)}const Xf=Symbol.for("desktop-mode/default-dock-rail-renderer/dock"),ca={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 ni(e.container,e.windowManager,e.items,e.adminUrl,e.orientation);return{[Xf]:t,replaceItems:o=>t.replaceItems(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 da(e){if(!e)return null;const n=e[Xf];return n instanceof ni?n:null}function z0(){id(ca)}const Zf="os-desktop-theme-css",G0="os-desktop-theme-inline-css",ua="data-os-desktop-theme-css",Jf="os-desktop-theme-changed";function Qf(){return document.getElementById("os-shell")}function ep(){const e=[];for(const t of[Zf,G0]){const n=document.getElementById(t);n&&e.push(n)}return document.querySelectorAll(`[${ua}]`).forEach(t=>{e.includes(t)||e.push(t)}),e}function tp(){for(const e of ep())e.remove()}function j0(e){const t=Qf();return!t||t.getAttribute("data-os-desktop-theme")!==e?!1:ep().length>0}function np(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 fa(e){const t=Ws(),n=t.state.activeId,o=typeof e=="string"?e.trim():"",s=o===""?null:Gd(o),i=s?s.slug:null;if(i===n)return;const r=Qf();if(!s)r?.removeAttribute("data-os-desktop-theme"),np(null),tp(),t.setState({activeId:null,activeIcons:null,activeIconColors:null});else{if(!j0(s.slug)){if(tp(),s.cssUrl!==""){const a=document.createElement("link");a.id=Zf,a.rel="stylesheet",a.href=s.cssUrl,a.setAttribute(ua,s.slug),document.head.appendChild(a)}else if(s.cssText!==""){const a=document.createElement("style");a.setAttribute(ua,s.slug),a.textContent=s.cssText,document.head.appendChild(a)}}r?.setAttribute("data-os-desktop-theme",s.slug),np(s.slug),t.setState({activeId:s.slug,activeIcons:s.icons,activeIconColors:s.iconColors})}const l={themeId:i,previous:n};L(_.DESKTOP_THEME_CHANGED,l),typeof document<"u"&&document.dispatchEvent(new CustomEvent(Jf,{detail:l}))}const V0=ce` ${nt}: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 ) )}: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}`,op='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',ds=class ds extends Ee{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,l=t.composedPath()[0]||r;t.shiftKey&&l===o?(t.preventDefault(),s.focus()):!t.shiftKey&&l===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(op)),o=Array.from(t.querySelectorAll(op));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` |
| 29 |
<div part="dialog" class="dialog" tabindex="-1"> |
| 30 |
${t?j` |
| 31 |
<div class="header"> |
| 32 |
<h2 class="title">${t}</h2> |
| 33 |
<div class="header-actions"> |
| 34 |
<slot name="header-actions"></slot> |
| 35 |
${n?j``:j`<button |
| 36 |
type="button" |
| 37 |
class="close" |
| 38 |
aria-label="Close" |
| 39 |
@click=${()=>this._cancel()} |
| 40 |
>×</button>`} |
| 41 |
</div> |
| 42 |
</div> |
| 43 |
`:j``} |
| 44 |
<div class="body"> |
| 45 |
<slot></slot> |
| 46 |
</div> |
| 47 |
<div class="footer"> |
| 48 |
<slot name="footer"></slot> |
| 49 |
</div> |
| 50 |
</div> |
| 51 |
`}};ds.props=["open","title","size","mandatory"],ds.styles=[V0],ds.help=void 0;let pa=ds;Ie("os-modal",pa);const q0=ce` ${nt} ${oa} ${Df} ${Rf} ${Of} ${Pf}: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 )}}`,us=class us extends Ee{render(){const t=this.disabled!==null,n=this.busy!==null,o=this.type||"button";return j` |
| 52 |
<button |
| 53 |
part="button" |
| 54 |
class="os-holo-edge os-holo-sheen" |
| 55 |
type=${o} |
| 56 |
?disabled=${t||n} |
| 57 |
aria-busy=${n?"true":"false"} |
| 58 |
> |
| 59 |
${n?j`<span class="os-button__spinner" aria-hidden="true"></span>`:""} |
| 60 |
<slot></slot> |
| 61 |
<!-- |
| 62 |
The two motion layers. Elements rather than |
| 63 |
pseudo-elements because the sheen and the hairline |
| 64 |
have already taken this button's ::before and |
| 65 |
::after — see the pseudo-element budget note in |
| 66 |
src/ui/holo.ts. Both are inert and aria-hidden. |
| 67 |
--> |
| 68 |
<span class="os-holo-glint" aria-hidden="true"></span> |
| 69 |
<span class="os-holo-ring" aria-hidden="true"></span> |
| 70 |
</button> |
| 71 |
`}};us.props=["variant","disabled","type","busy","fill-cell"],us.styles=[q0],us.help=void 0;let ha=us;Ie("os-button",ha);function sp(e){const{from:t,to:n,angle:o}=e.customGradient;return`linear-gradient(${o}deg, ${t}, ${n})`}const K0=()=>k("Mix your own two-colour gradient and set the angle — your desk, your palette.");function Y0(e){oo({id:pv,label:k("Custom gradient"),type:"css",preview:sp(e.state),description:K0(),resolveValue:()=>sp(e.state)})}function X0(e){if(!e.customImage){hf(Od);return}const n=`url("${encodeURI(e.customImage.url)}") center/cover no-repeat, #1d2327`;oo({id:Od,label:k("Custom image"),type:"css",value:n,preview:n,description:k("Any image from your media library or an upload, sized to cover the whole desk.")})}let oi=null;function Z0(e){return window.openStationRenderOsSettingsPanel?Promise.resolve(window.openStationRenderOsSettingsPanel):oi||(oi=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)}),oi)}class J0{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=BE(),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))}),Y0(this),X0(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,itemVisibility:{...this.state.itemVisibility},dockOrder:this.state.dockOrder.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;$E(this.state.wallpaperSettings);const n=Yr(this.state.wallpaper)||Yr(Wd())||Yr(Ar)||gf()[0];n&&this.layer.apply(n);const o=Cr(),s=o.find(f=>f.id===this.state.accent)??o[0],i=this.state.accent===Md?this.state.customAccent:s.value,r=Ir.find(f=>f.id===this.state.dockSize)??Ir[1],l=xr.find(f=>f.id===this.state.windowRadius)??xr[1],a=document.body;a.style.setProperty("--wp-admin-theme-color",i),a.style.setProperty("--os-ui-accent",i);const d=i.toLowerCase()==="#f252fc"?null:`color-mix( in srgb, ${i} 88%, #000 )`;d===null?a.style.removeProperty("--os-ui-accent-dim"):a.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),a.style.setProperty("--os-dock-width",`${r.width}px`),a.style.setProperty("--os-dock-icon-size",`${r.icon}px`),a.style.setProperty("--os-window-radius",`${l.value}px`),t.style.setProperty("--os-window-radius",`${l.value}px`);const u=Ps.find(f=>f.id===this.state.adminBarMode)??Ps[0];for(const f of Ps)document.body.classList.toggle(`os-admin-bar-${f.id}`,f.id===u.id);t.setAttribute("data-os-layout",this.state.desktopLayout),Pb(this.state.dockRailRenderer),fa(this.state.desktopTheme)}save(t={}){if(YE(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}Z0(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 Q0={userId:null,requestedAt:0,tabRequested:!1};let si=null;function ek(){if(si)return si;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(si=t("desktop-mode/user-edit/target",()=>({...Q0})),si)}function tk(e){const t=ek();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 ii=null;function nk(){if(ii)return ii;const e=window.wp?.os?.createSharedStore;return typeof e!="function"?null:(ii=e("desktop-mode/comments/post-filter",()=>({postId:0})),ii)}function ip(e){const t=nk();t&&(t.state.postId=e,t.notify())}function ok(){ip(0)}const ri=new Map;function rp(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}ri.set(e.id,e)}function sk(){return Array.from(ri.keys())}async function ap(e){if(!e||e.length===0)return;const t=e.filter(n=>!ri.has(n));if(t.length>0)throw new Error(`[openstation] Unknown module(s) in needs: ${t.map(n=>`"${n}"`).join(", ")}. Known modules: ${sk().join(", ")||"(none)"}.`);await Promise.all(e.map(n=>{const o=ri.get(n);return!o||o.isReady&&o.isReady()?Promise.resolve():Se(o.url)}))}function lp(e,t){return{id:e,pluginUrl:t,prefersReducedMotion:ik(),visible:!document.hidden,settings:WE(e)}}function ik(){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,L(_.WALLPAPER_UNMOUNTING,{id:t});try{n()}catch(o){L(_.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(lp(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=lp(t.id,this.pluginUrl);L(_.WALLPAPER_MOUNTING,{id:t.id,container:this.element,ctx:o});const s=t.needs&&t.needs.length>0?ap(t.needs):Promise.resolve(),i=r=>{if(n!==this.generation){try{r()}catch{}return}this.active={id:t.id,teardown:r},L(_.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(l){this.handleMountFailure(t.id,l);return}if(rk(r)){r.then(i,l=>{n===this.generation&&this.handleMountFailure(t.id,l)});return}i(r)},r=>{n===this.generation&&this.handleMountFailure(t.id,r)})}isEffectivelyHidden(){return document.hidden||this.isSuspended()}emitEffectiveVisibility(){this.active&&L(_.WALLPAPER_VISIBILITY,{id:this.active.id,state:this.isEffectivelyHidden()?"hidden":"visible"})}emitSuspendAction(){L(_.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="",L(_.WALLPAPER_MOUNT_FAILED,{id:t,error:n}),L(_.SHELL_ERROR,{scope:"wallpaper-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Wallpaper "${t}" failed to mount:`,n)}}function rk(e){return!!e&&typeof e=="object"&&typeof e.then=="function"}const dp=re("desktop-mode/games-registry",()=>({seed:[],listeners:new Set})),pn=dp.state.seed,ma=dp.state.listeners;function ga(e){Ne("Game",Tt(e,hp),e);const t=pn.findIndex(n=>n.id===e.id);t>=0?pn[t]=e:pn.push(e),fp()}function up(e){const t=pn.findIndex(n=>n.id===e);t>=0&&(pn.splice(t,1),fp())}function ak(e){return ma.add(e),()=>{ma.delete(e)}}function fp(){const e=Array.from(ma);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] games registry listener threw:",n)}}function pp(){const e=pn.slice(),t=G(_.GAMES,e);return Array.isArray(t)?t.filter(lk):(typeof console<"u"&&console.warn("[openstation] `os.games` filter returned a non-array; falling back to seed list."),e)}function ai(e){return pp().find(t=>t.id===e)}const hp=[{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 lk(e){return Tt(e,hp).length===0}const ck="desktop-mode/games";function dk(){const t=window.wp?.os?.config;return{restUrl:t?.restUrl||"/wp-json/",restNonce:t?.restNonce||""}}async function io(e,t={},n={}){const{restUrl:o,restNonce:s}=dk(),i=new Headers(t.headers??{});i.set("X-WP-Nonce",s),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Be(et(o,e),{...t,headers:i,credentials:"same-origin"},{source:ck,windowId:n.windowId,silent:n.silent}),l=await r.json().catch(()=>null);if(!r.ok){const a=l?.message||`Games request failed (${r.status})`,c=new Error(a);throw c.status=r.status,c}return l}function uk(e,t,n={}){return io(`desktop-mode/v1/games/${e}/scores`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}function fk(){return io("desktop-mode/v1/games/playtime")}function pk(e,t,n={}){return io(`desktop-mode/v1/games/${e}/playtime`,{method:"POST",body:JSON.stringify({seconds:t})},n)}function hk(e){return io(`desktop-mode/v1/games/challenges/${e}/accept`,{method:"POST"})}function mk(e,t,n={}){return io(`desktop-mode/v1/games/challenges/${e}/complete`,{method:"POST",body:JSON.stringify({score:t.score,meta:t.meta??{}})},n)}const gk=6e4;function wk(e,t={}){let n=Date.now(),o=0,s=!1;const i=()=>{if(n===null)return;const a=Date.now();o+=Math.max(0,a-n),n=a},r=()=>{i();const a=Math.floor(o/1e3);a<1||(o-=a*1e3,pk(e,a,{windowId:t.windowId,silent:!0}).catch(()=>{o+=a*1e3}))},l=setInterval(r,gk);return{pause:()=>{i(),n=null},resume:()=>{s||n!==null||(n=Date.now())},stop:()=>{s||(s=!0,clearInterval(l),i(),n=null,r())}}}const hn=re("desktop-mode/games-challenges",()=>({rows:new Map,version:0,listeners:new Set}));function yk(){return hn.state}function wa(e){const t=hn.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&&vk()}function bk(e){return hn.state.listeners.add(e),()=>{hn.state.listeners.delete(e)}}function vk(){for(const e of Array.from(hn.state.listeners))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] challenges store listener threw:",t)}}function _k(){return Array.from(hn.state.rows.values()).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}function mp(){return window.wp?.os??{}}const Ek=760,kk=560,Sk=480,Ak=380;async function Ck(e){if(typeof e.render=="function")return e;const t=mp().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 ga(s),s}async function gp(e,t={}){const n=mp();let o=ai(e);if(!o)throw new Error(`[openstation] Unknown game "${e}".`);o=await Ck(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}`,l=n.windowManager,a=l?.getByBaseId?.(i)??l?.getById(i);if(a){const m=a.config?.desktopId;m&&l?.switchDesktop&&m!==l?.getActiveDesktopId?.()&&l.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 mk(h,m,{windowId:i}).then(({challenge:b})=>{wa([b]),p(m,h)})}return uk(e,m,{windowId:i}).then(()=>p(m))};try{await n.registerWindow({id:i,title:o.title,icon:o.icon,width:o.window?.width??Ek,height:o.window?.height??kk,minWidth:o.window?.minWidth??Sk,minHeight:o.window?.minHeight??Ak,render:m=>{const h={windowId:i,container:m,config:o.config??{},challenge:t.challenge,submitScore:g,close:()=>{n.windowManager?.getById(i)?.close()}};u=wk(e,{windowId:i});const b=s(h);return()=>{try{b?.()}finally{f(),d()}}}})}catch(m){throw f(),d(),m}}const wp={register:ga,unregister:up,list:pp,get:ai,subscribe:ak,launch:gp,getPlaytime:()=>fk().then(e=>e.playtime)};function Ik(e){const{osSettings:t}=e,n=new Set,o=new Set,s=async c=>{if(!(!c.scriptUrl||o.has(c.scriptUrl))){try{await Se(c.scriptUrl,{translations:c.scriptTranslations,l10n:c.scriptL10n,before:c.scriptBefore,after:c.scriptAfter})}catch(d){L(_.SHELL_ERROR,{scope:"wallpaper-script-load",id:c.id,error:d});return}o.add(c.scriptUrl)}},i=c=>(window.openStationWallpapers||{})[c]??null,r=c=>c.type!=="css"||c.value===""?null:{id:c.id,label:c.label,type:"css",value:c.value,preview:c.preview!==""?c.preview:c.value,description:c.description||void 0},l=async c=>{if(n.has(c.id))return;const d=r(c);if(d){oo(d),n.add(c.id),t.apply();return}await s(c);let u=i(c.id);if(u&&!u.description&&c.description&&(u={...u,description:c.description}),!u){L(_.SHELL_ERROR,{scope:"wallpaper-missing-def",id:c.id,error:new Error(`[openstation] No wallpaper def on window.openStationWallpapers["${c.id}"]. Script loaded but didn't publish a def — check the plugin's enqueue + global assignment.`)});return}try{oo(u)}catch(f){L(_.SHELL_ERROR,{scope:"wallpaper-register",id:c.id,error:f});return}n.add(c.id),t.apply()},a=c=>{n.has(c)&&(hf(c),n.delete(c),t.apply())};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)||a(u);for(const u of c)n.has(u.id)||await l(u)}}function xk(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 Lk(){const e=new Set,t=o=>{try{const s=ai(o.id),i=xk(o);ga(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)&&(up(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 Tk(e={}){const t=e.deactivate??(()=>fa(""));return function(o){Ev(Array.isArray(o)?o:[]);const{activeId:s,themes:i}=Ws().getState();s!==null&&(i.some(r=>r.slug===s)||t())}}const li=new Map,ya=new Map;let yp=!1;const xe={contribute(e,t){return li.set(e,t),()=>{li.get(e)===t&&li.delete(e)}},subscribe(e,t){let n=ya.get(e);return n||(n=new Set,ya.set(e,n)),n.add(t),()=>{n.delete(t)}}};function Nk(){if(yp)return;yp=!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 li)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 ya){const i=n[o];if(i!==void 0)for(const r of s)try{r(i)}catch(l){console.error(`[desktop-mode/heartbeat] subscriber for "${o}" threw:`,l)}}})}let ci=null,di={installHintDismissed:!1,notificationsEnabled:!1};const ba=new Set;function bp(e){if(!e){ci=null;return}ci=e,di={...e.state},_p()}function ro(){return{...di}}function va(e){if(di={...di,...e},_p(),!ci)return ro();const t=JSON.stringify(e),n=Dk();return fetch(ci.stateUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",...n?{"X-WP-Nonce":n}:{}},body:t}).catch(o=>{typeof console<"u"&&console.warn("[openstation] pwa-state write failed:",o)}),ro()}function vp(e){return ba.add(e),()=>{ba.delete(e)}}function _p(){const e=ro();for(const t of Array.from(ba))try{t(e)}catch(n){typeof console<"u"&&console.error("[openstation] pwa-state listener threw:",n)}}function Dk(){return window.openStationConfig?.restNonce??""}const Rk=Object.freeze(Object.defineProperty({__proto__:null,getPwaState:ro,initPwaState:bp,subscribePwaState:vp,updatePwaState:va},Symbol.toStringTag,{value:"Module"}));function _a(e){const t=ke.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=X({message:t.body?t.title+" — "+t.body:t.title}),ke.publish("os/notification-shown",{...t,fallback:"toast"})};if(typeof window>"u"||typeof Notification>"u")return r(),i;const l=Notification.permission;return l==="granted"?(o=Ep(t),o||r(),i):l==="denied"?(r(),i):(Notification.requestPermission().then(a=>{if(!n){if(a==="granted"){va({notificationsEnabled:!0}),o=Ep(t),o||r();return}r()}}),i)}function Ep(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 ke.publish("os/notification-shown",{...e,fallback:null}),()=>{t&&t.close()}}async function Ok(){if(typeof Notification>"u")return"unsupported";if(Notification.permission!=="default")return Notification.permission;const e=await Notification.requestPermission();return e==="granted"&&va({notificationsEnabled:!0}),e}function Mk(){return typeof Notification>"u"?"unsupported":Notification.permission}function Pk(e){return ai(e)?.title||e}const kp=new Set,Sp=new Set;async function Wk(e){const{challenge:t}=await hk(e.id);wa([t]),await gp(e.game,{challenge:{id:e.id,scoreToBeat:e.scoreToBeat,scoreMeta:e.scoreMeta,challengerName:e.challengerName}})}function $k(e){const t=le(k("%1$s challenged you to %2$s — beat %3$s!"),e.challengerName,Pk(e.game),String(e.scoreToBeat));_a({title:k("Game challenge"),body:t,tag:`os-game-challenge-${e.id}`}),X({message:t,persistent:!0,dismissible:!0,action:{label:k("Accept & Play"),onClick:()=>{Wk(e).catch(n=>{X({message:n instanceof Error?n.message:k("Could not accept the challenge.")})})}}})}function Uk(e){let t;e.result==="beaten"?t=k("%1$s beat your score: %2$s vs your %3$s."):t=k("%1$s did not beat your score: %2$s vs your %3$s.");const n=le(t,e.recipientName,String(e.resultScore??0),String(e.scoreToBeat));_a({title:k("Challenge finished"),body:n,tag:`os-game-challenge-${e.id}`}),X({message:n})}function Fk(e){const{currentUserId:t}=e;if(!t)return;xe.contribute("openstation_games_subscribe",()=>({challengesVersion:yk().version})),xe.subscribe("openstation_games",o=>{Array.isArray(o?.challenges)&&wa(o.challenges)});const n=()=>{for(const o of _k())o.state==="pending"&&o.recipientId===t&&!kp.has(o.id)&&(kp.add(o.id),$k(o)),o.state==="completed"&&o.challengerId===t&&!Sp.has(o.id)&&(Sp.add(o.id),Uk(o))};bk(n),n()}const Ap=/^[a-z0-9_/-]+$/,Cp=re("desktop-mode/commands-registry",()=>({registry:new Map,listeners:new Set})),$t=Cp.state.registry,Bk=Cp.state.listeners;function ui(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)"):Ap.test(n)||t.push(`slug (must match ${Ap} — 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),$t.set(n,{...e,slug:n}),Ea()}function Ip(e){$t.delete(e.toLowerCase())&&Ea()}function fi(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from($t.entries()))o.owner===e&&($t.delete(n),t++);return t>0&&Ea(),t}function xp(){return Array.from($t.values())}function Hk(){const e=[];for(const t of $t.values())t.aiCallable===!0&&e.push({slug:t.slug,label:t.label,description:t.description??"",hint:t.hint??""});return e}function zk(e){return $t.get(e.toLowerCase())??null}function Ea(){const e=Array.from(Bk);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] command-registry listener threw:",n)}}function Gk(){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 Se(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(l){L(_.SHELL_ERROR,{scope:"command-script-load",handle:r.handle,url:r.scriptUrl,error:l});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const l=new Map;if(!r)return l;for(const a of r){if(!a.scriptHandle||!a.slug)continue;let c=l.get(a.scriptHandle);c||(c=new Set,l.set(a.scriptHandle,c)),c.add(a.slug)}return l},i=r=>{const l=new Set;for(const c of xp())c.owner===r&&l.add(c.slug);const a=n.get(r);if(a)for(const c of a)l.add(c);return l};return async(r,l)=>{const a=new Set;for(const c of r)c.handle&&a.add(c.handle);for(const c of Array.from(e))if(!a.has(c)){for(const d of i(c))Ip(d);e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(l)}}const Lp=re("desktop-mode/settings-tab-registry",()=>({registry:new Map,listeners:new Set})),ao=Lp.state.registry,jk=Lp.state.listeners;function Tp(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}ao.set(t,{...e,id:t}),ka()}function Np(e){ao.delete(e.toLowerCase())&&ka()}function Vk(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&&ka(),t}function Dp(){return Array.from(ao.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function ka(){const e=Array.from(jk);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] settings-tab-registry listener threw:",n)}}function qk(){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 Se(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(l){L(_.SHELL_ERROR,{scope:"settings-tab-script-load",handle:r.handle,url:r.scriptUrl,error:l});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const l=new Map;if(!r)return l;for(const a of r){if(!a.scriptHandle||!a.id)continue;let c=l.get(a.scriptHandle);c||(c=new Set,l.set(a.scriptHandle,c)),c.add(a.id)}return l},i=r=>{Vk(r);const l=n.get(r);if(l){const a=new Set(Dp().map(c=>c.id));for(const c of l)a.has(c)&&Np(c)}};return async(r,l)=>{const a=new Set;for(const c of r)c.handle&&a.add(c.handle);for(const c of Array.from(e))a.has(c)||(i(c),e.delete(c));for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(l)}}const Rp=re("desktop-mode/title-bar-buttons-registry",()=>({registry:new Map,listeners:new Set})),lo=Rp.state.registry,Kk=Rp.state.listeners,Op=/^[a-z0-9_/-]+$/;function pi(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Op.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Op} — 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();lo.set(n,{...e,id:n}),hi()}function Yk(e){lo.delete(e.toLowerCase())&&hi()}function Xk(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(lo.entries()))o.owner===e&&(lo.delete(n),t++);return t>0&&hi(),t}function Zk(){return Array.from(lo.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function hi(){const e=Array.from(Kk);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"&&hi()});function Jk(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Se(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(_.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)||(Xk(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Mp=re("desktop-mode/window-actions-registry",()=>({registry:new Map,listeners:new Set})),co=Mp.state.registry,Qk=Mp.state.listeners,Pp=/^[a-z0-9_/-]+$/;function Sa(){for(const e of Array.from(Qk))try{e()}catch{}}function eS(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Pp.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Pp} — 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();co.set(n,{...e,id:n}),Sa()}function tS(e){co.delete(String(e||"").toLowerCase())&&Sa()}function nS(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(co.entries()))o.owner===e&&(co.delete(n),t++);return t>0&&Sa(),t}function oS(){return Array.from(co.values()).sort((e,t)=>(e.order??100)-(t.order??100))}function sS(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Se(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(_.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)||(nS(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const mn="none",Aa="svg-splines",Wp=re("desktop-mode/window-link-renderer-registry",()=>({registry:new Map,listeners:new Set})),uo=Wp.state.registry,Ca=Wp.state.listeners,$p=/^[a-z0-9_/-]+$/;function Up(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):$p.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===mn&&t.push('id ("none" is reserved)'):t.push(`id (must match ${$p} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),(typeof e.label!="string"||e.label.trim()==="")&&t.push("label (missing)"),typeof e.mount!="function"&&t.push("mount (not a function)")),Ne("WindowLinkRenderer",t,e);const n=e.id.trim().toLowerCase();uo.set(n,{...e,id:n}),xa()}function iS(e){uo.delete(e.toLowerCase())&&xa()}function rS(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(uo.entries()))o.owner===e&&(uo.delete(n),t++);return t>0&&xa(),t}function Fp(){const e=Array.from(uo.values()),t=G(_.WINDOW_LINK_RENDERERS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.window-links.renderers` filter returned a non-array; falling back to registry list."),e)}function Ia(e){return Fp().find(t=>t.id===e)}function aS(e){return Ca.add(e),()=>{Ca.delete(e)}}function xa(){const e=Array.from(Ca);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-link-renderer registry listener threw:",n)}}const lS=16;function cS(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 dS(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,l=i!==0?e.height/2/Math.abs(i):1/0,a=Math.min(r,l),c=n+s*a,d=o+i*a;let u;return r<=l?u=s>0?"right":"left":u=i>0?"bottom":"top",{x:c,y:d,side:u}}function Bp(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 uS(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 l=null,a=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 cS(d,p)){if(g.end-g.start<lS)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<a&&(a=y,l={x:h,y:b,side:c})}}return l}function fS(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),l=Math.min(e.y+e.height,t.y+t.height);let a,c;i>=s?a=c=(s+i)/2:t.x>e.x?(a=e.x+e.width,c=t.x):(a=e.x,c=t.x+t.width);let d,u;l>=r?d=u=(r+l)/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:a,y:d,side:p(e,a,d)},to:{x:c,y:u,side:p(t,c,u)}}}function Hp(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 pS(e){return{x:e.x+e.width/2,y:e.y+e.height/2}}const gn="http://www.w3.org/2000/svg";let hS=0;function zp(e,t,n,o,s){const i=dS(e,s);return t===null||Bp(i,t,o,n)?i:uS(e,t,o,n,s)??i}function mS(e,t){const n=document.createElementNS(gn,"defs"),o=(l,a,c)=>{const d=`${t}-${l}`,u=document.createElementNS(gn,"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(gn,"circle");return f.setAttribute("cx","5"),f.setAttribute("cy","5"),f.setAttribute("r","4"),f.classList.add(a),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}Up({id:"svg-splines",label:k("Splines"),description:k("Curved connectors between related windows, ending in circular dots — the larger dot sits on the window the content belongs to; windows that reference each other get large dots on both ends."),mount:e=>{const t=++hS,n=(l,a)=>{const c=document.createElementNS(gn,"svg");return c.classList.add("os-window-links__svg"),l.appendChild(c),{svg:c,markers:mS(c,`os-window-link-${t}${a}`)}},o={base:n(e.container,""),elevated:n(e.elevatedContainer,"-elevated")},s=new Map,i=l=>{for(const{svg:c}of[o.base,o.elevated])c.setAttribute("width",String(l.container.width)),c.setAttribute("height",String(l.container.height)),c.setAttribute("viewBox",`0 0 ${l.container.width} ${l.container.height}`);const a=new Set;for(const c of l.edges){if(!c.from||!c.to)continue;const d=`${c.fromWindowId}→${c.toWindowId}:${c.kind}`;a.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 M=document.createElementNS(gn,"g");M.classList.add("os-window-link");const P=document.createElementNS(gn,"path");P.classList.add("os-window-link__path"),M.appendChild(P),o[u].svg.appendChild(M),f={group:M,path:P,surface:u},s.set(d,f)}const p=l.obstacles??[],g=fS(c.from,c.to),m=(M,P,v)=>P===null||Bp(M,P,p,v);let h=null;g&&m(g.from,c.fromZIndex,c.fromWindowId)&&(h=g.from),h||(h=zp(c.from,c.fromZIndex,c.fromWindowId,p,g?{x:g.to.x,y:g.to.y}:pS(c.to)));let b=null;g&&m(g.to,c.toZIndex,c.toWindowId)&&(b=g.to),b||(b=zp(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),C=Hp(h,y),w=Hp(b,y);f.path.setAttribute("d",`M ${h.x} ${h.y} C ${C.x} ${C.y}, ${w.x} ${w.y}, ${b.x} ${b.y}`);const E=o[f.surface].markers,T=c.focused?"active":"normal";f.path.setAttribute("marker-end",`url(#${E.dot[T]})`),f.path.setAttribute("marker-start",`url(#${c.bidirectional?E.dot[T]:E.port[T]})`),f.group.classList.toggle("os-window-link--active",c.focused)}for(const[c,d]of Array.from(s))a.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 Gp="os-window-links",jp="os-window--linked",Vp="os-window-links--visible";let qp=!1;function gS({manager:e,osSettings:t}){if(qp)return;qp=!0;let n=t.getOsSettingsSnapshot(),o=null,s=null,i=null,r=null,l=0;const a=new Set;let c=!1;const d=new Set;let u=!1;const f=I=>{const W=I.element;return!W||!W.isConnected||I.state==="minimized"||W.offsetParent===null?null:{x:W.offsetLeft,y:W.offsetTop,width:W.offsetWidth,height:W.offsetHeight}},p=I=>I.state==="snapped-left"||I.state==="snapped-right"?null:f(I),g=()=>{const I=[];for(const x of Ys()){if(x.rootWindowIds.length===0||x.children.length===0)continue;const F=[],R=(S,O,U)=>{const N=e.getById(S);!N||!U||F.push({windowId:S,role:O,content:U,rect:p(N),focused:N.isFocused(),state:N.state})};for(const S of x.rootWindowIds)R(S,"root",lt(S));for(const S of x.children)R(S.windowId,"child",S.content);F.length>0&&I.push({key:x.key,root:x.root,members:F})}const W=x=>{const F=Number.parseInt(x.element?.style.zIndex||"",10);return Number.isFinite(F)?F:null},z=e.getFocused()?.id??null,q=[];for(const x of no()){const F=e.getById(x.fromWindowId),R=e.getById(x.toWindowId);if(!F||!R)continue;const S=F.isFocused()||R.isFocused();q.push({fromWindowId:x.fromWindowId,toWindowId:x.toWindowId,kind:x.kind,bidirectional:x.bidirectional,focused:S,from:p(F),to:p(R),fromZIndex:W(F),toZIndex:W(R),elevated:z!==null&&(x.fromWindowId===z||x.toWindowId===z)})}const K=[];for(const x of e.getAll()){const F=f(x);F&&K.push({windowId:x.id,rect:F,zIndex:W(x)??0})}return{groups:I,edges:q,obstacles:K,container:{width:o?.offsetWidth??0,height:o?.offsetHeight??0}}},m=()=>{c||a.size===0||(c=!0,requestAnimationFrame(()=>{if(c=!1,!i)return;const I=g();for(const W of Array.from(a))try{W(I)}catch(z){typeof console<"u"&&console.error("[openstation] window-link frame subscriber threw:",z)}}))},h=()=>{if(o&&o.isConnected&&s?.isConnected)return o;const I=document.getElementById("os-area");if(!I)return null;o=document.createElement("div"),o.id=Gp,o.className="os-window-links",o.setAttribute("aria-hidden","true"),s=document.createElement("div"),s.id=`${Gp}-elevated`,s.className="os-window-links os-window-links--elevated",s.setAttribute("aria-hidden","true");const W=document.getElementById("os-widgets");return W&&W.parentElement===I?(W.insertAdjacentElement("afterend",s),W.insertAdjacentElement("afterend",o)):I.prepend(o,s),o},b=()=>no().length>0,y=()=>{let I=n.windowLinkRenderer||Aa;return I=G(_.WINDOW_LINK_RENDERER,I),I===mn?mn:Ia(I)?I:Ia(Aa)?Aa:mn},C=()=>{if(l++,a.clear(),c=!1,r){try{r()}catch(I){L(_.SHELL_ERROR,{scope:"window-link-renderer-teardown",error:I})}r=null}i=null,o?.replaceChildren(),s?.replaceChildren()},w=I=>{const W=Ia(I),z=h();if(!W||!z||!s)return;i=I;const q=++l,K={container:z,elevatedContainer:s,getFrame:g,onFrame:x=>(a.add(x),()=>{a.delete(x)})};try{const x=W.mount(K);x instanceof Promise?x.then(F=>{if(q!==l){typeof F=="function"&&F();return}typeof F=="function"&&(r=F)}).catch(F=>{L(_.SHELL_ERROR,{scope:"window-link-renderer-mount",error:F}),q===l&&(i=null)}):typeof x=="function"&&(r=x)}catch(x){L(_.SHELL_ERROR,{scope:"window-link-renderer-mount",error:x}),i=null}m()},E=()=>{const I=e.getFocused();return I?new Set(uf(I.id)):new Set},T=()=>n.windowLinksEnabled!==!1,M=()=>{if(!o)return;const I=!u&&T()&&(n.windowLinkVisibility==="always"||n.windowLinkVisibility==="focus"&&E().size>0);o.classList.toggle(Vp,I),s?.classList.toggle(Vp,I)},P=()=>{if(!T()||n.windowLinkRaiseOnFocus===!1||n.windowLinkVisibility==="off")return;const I=e.getFocused();if(I)for(const W of IE(I.id)){const z=e.getById(W);z&&z.state!=="minimized"&&e.raise(W)}},v=()=>{if(!s)return;const I=e.getFocused(),W=E();if(!I||W.size===0||!T()||n.windowLinkVisibility==="off"){s.style.zIndex="";return}let z=-1/0;for(const q of[I.id,...W]){const K=e.getById(q),x=K?.element;if(!x||K.state==="minimized")continue;const F=Number.parseInt(x.style.zIndex||"",10);Number.isFinite(F)&&(z=Math.max(z,F))}s.style.zIndex=Number.isFinite(z)?String(z):""},$=()=>{const I=T()&&n.windowLinkHighlight!==!1&&n.windowLinkVisibility!=="off"?E():new Set;for(const W of d)I.has(W)||e.getById(W)?.element?.classList.remove(jp);for(const W of I)e.getById(W)?.element?.classList.add(jp);d.clear();for(const W of I)d.add(W)},D=()=>{const I=T()&&n.windowLinkVisibility!=="off"&&b()?y():mn;I===mn?i&&C():I!==i&&(C(),w(I)),M(),$(),v(),m()};Y(_.WINDOW_BOUNDS_CHANGED,"desktop-mode/window-links-frame",()=>m());for(const I of[_.WINDOW_MOVED,_.WINDOW_RESIZED,_.WINDOW_MINIMIZED,_.WINDOW_RESTORED,_.WINDOW_MAXIMIZED,_.WINDOW_UNMAXIMIZED,_.WINDOW_FULLSCREEN_ENTERED,_.WINDOW_FULLSCREEN_EXITED,_.SNAP_ZONE_COMMITTED,_.SNAP_SPLIT_FILLED,_.DESKTOP_SWITCHED,_.SHELL_RESIZED])Y(I,"desktop-mode/window-links-frame",()=>m());Y(_.WINDOW_FOCUSED,"desktop-mode/window-links-focus",()=>{P(),M(),$(),v(),m()}),Y(_.WINDOW_BLURRED,"desktop-mode/window-links-blur",()=>{M(),$(),v(),m()}),Y(_.OVERVIEW_ENTERING,"desktop-mode/window-links-overview",()=>{u=!0,M()}),Y(_.OVERVIEW_EXITED,"desktop-mode/window-links-overview",()=>{u=!1,M(),m()}),ff(D),aS(D),t.subscribeOsSettings(I=>{const W=I.windowLinkRenderer!==n.windowLinkRenderer,z=W||I.windowLinkVisibility!==n.windowLinkVisibility||I.windowLinksEnabled!==n.windowLinksEnabled||I.windowLinkRaiseOnFocus!==n.windowLinkRaiseOnFocus||I.windowLinkHighlight!==n.windowLinkHighlight;n=I,z&&(W&&i&&C(),D())}),D()}function Kp(e){return e==="comments"?0:e.startsWith("terms/")?1:e==="media"?2:e==="links"?3:4}function wS({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 l=o.get(r.group);l?l.push(r):o.set(r.group,[r])}const s=Array.from(o.entries()).sort((r,l)=>Kp(r[0])-Kp(l[0])),i=[];for(const[,r]of s){const l=r.find(a=>typeof a.groupLabel=="string"&&a.groupLabel!=="")?.groupLabel;if(l){const a=document.createElement("div");a.className="os-window__related-group",a.setAttribute("role","presentation"),a.textContent=l,n.appendChild(a)}for(const a of r){const c=document.createElement("os-menu-item");c.setAttribute("role","menuitem"),c.setAttribute("value",a.id),c.tabIndex=-1,a.icon&&c.setAttribute("icon",a.icon),c.classList.add("os-window__related-item"),c.textContent=typeof a.count=="number"?`${a.label} (${a.count})`:a.label,c.addEventListener("os-menu-item-click",d=>{d.stopPropagation(),t(a)}),i.push(c),n.appendChild(c)}}return n.addEventListener("keydown",r=>{const l=r,a=i.indexOf(n.ownerDocument.activeElement);if(l.key==="ArrowDown"||l.key==="ArrowUp"){l.preventDefault(),l.stopPropagation();const c=l.key==="ArrowDown";let d=i[c?0:i.length-1];a!==-1&&(d=i[(a+(c?1:-1)+i.length)%i.length]),d?.focus()}else if(l.key==="Home"||l.key==="End")l.preventDefault(),l.stopPropagation(),i[l.key==="Home"?0:i.length-1]?.focus();else if(l.key==="Enter"||l.key===" "){const c=i[a];c&&(l.preventDefault(),l.stopPropagation(),c.dispatchEvent(new CustomEvent("os-menu-item-click",{bubbles:!0})))}}),n}function Yp(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)&&(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 Xp(e){const t=lt(e)??null,n=t&&Array.isArray(t.related)?t.related.map(s=>({...s})):[],o=G(_.RELATED_ENTITIES_ITEMS,n,{windowId:e,content:t});return Array.isArray(o)?o.filter(Yp):(typeof console<"u"&&console.warn("[openstation] `os.related-entities.items` filter returned a non-array; falling back to the identity list."),n.filter(Yp))}function La(e){e?.querySelectorAll(".os-window__related-panel").forEach(t=>{t._wpdRelatedClose?t._wpdRelatedClose():t.remove()})}function yS(e){const t=n=>{n.stopImmediatePropagation()};e.addEventListener("dblclick",t,!0),setTimeout(()=>{e.removeEventListener("dblclick",t,!0)},500)}function bS(e,t,n){const o=e.closest(".os-window__titlebar");if(!o)return;const s=Xp(t.id);if(s.length===0)return;let i=null;const r=()=>{i&&(document.removeEventListener("pointerdown",i,!0),i=null),o.removeEventListener("keydown",l),a.remove(),e.setAttribute("aria-expanded","false")},l=c=>{c.key==="Escape"&&(c.stopPropagation(),r(),e.focus())},a=wS({items:s,onPick:c=>{r(),yS(o),n(c)}});a._wpdRelatedClose=r,o.appendChild(a),o.addEventListener("keydown",l),e.setAttribute("aria-expanded","true"),i=c=>{const d=c.target;!d||a.contains(d)||e.contains(d)||r()},setTimeout(()=>{i&&document.addEventListener("pointerdown",i,!0)},0),a.querySelector('[role="menuitem"]')?.focus()}function vS({manager:e,openUrl:t}){pi({id:"desktop-mode/related-entities",label:k("Related"),icon:"dashicons-networking",placement:"right",order:60,match:n=>Xp(n.id).length>0,render:(n,o)=>{La(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")){La(o.element);return}bS(n,o,t)})}}),Y(_.WINDOW_CONTENT_CHANGED,"desktop-mode/related-entities",n=>{if(!n?.windowId)return;const o=e.getById(n.windowId);o&&(La(o.element),o.renderCustomTitleBarButtons?.())})}const Ta="os-broadcast",Zp="os-broadcast",Jp=window.location.origin;let Na=null;function _S(e){Na=e}function Da(e,t){const n=String(G("os.broadcast.topic",e,{payload:t})??e),o=G("os.broadcast.payload",t,{topic:n}),s={topic:n,payload:o};if(document.dispatchEvent(new CustomEvent(Ta,{detail:s})),L(_.BROADCAST,s),ke.publish(n,o),!Na)return;const i={type:Zp,topic:n,payload:o};for(const r of Na._stack){const l=r.iframe?.contentWindow;if(l)try{l.postMessage(i,Jp)}catch{}}}function wn(e,t){const n=o=>{const s=o.detail;if(s&&!(e!=="*"&&s.topic!==e))try{t(s.payload,{topic:s.topic})}catch(i){L(_.SHELL_ERROR,{scope:"broadcast-subscriber",topic:s.topic,error:i})}};return document.addEventListener(Ta,n),()=>document.removeEventListener(Ta,n)}function ES(){window.addEventListener("message",e=>{if(e.origin!==Jp)return;const t=e.data;!t||t.type!==Zp||t._fromParent||typeof t.topic=="string"&&Da(t.topic,t.payload)})}const kS=new Set(["saved","no-editor","not-dirty","error"]);let Qp=0;function eh(e){if(!(typeof e!="string"||e===""))try{return new URL(e,window.location.origin).origin===window.location.origin?e:void 0}catch{return}}function SS(e,{timeoutMs:t=1e4}={}){const n=e.iframe?.contentWindow;if(!n)return Promise.resolve({status:"no-editor"});Qp+=1;const o=`os-editor-preview-${Date.now()}-${Qp}`;return new Promise(s=>{let i=null,r=!1;const l=c=>{r||(r=!0,window.removeEventListener("message",a),i!==null&&window.clearTimeout(i),s(c))},a=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"&&kS.has(d.status)?d.status:"error",f=eh(d.previewUrl);l(f?{status:u,previewUrl:f}:{status:u})};window.addEventListener("message",a),i=window.setTimeout(()=>l({status:"timeout"}),t);try{n.postMessage({type:"os-editor-autosave-request",requestId:o},window.location.origin)}catch{l({status:"no-editor"})}})}const Oe=re("desktop-mode/editor-preview",()=>({pairings:new Map,busyEditors:new Set})),AS=400,th=1500;function fo(e){return e?`${e.type}:${e.id}`:""}function CS(e){for(const t of Oe.state.pairings.values())if(t.previewWindowId===e)return t}function IS(){return typeof window.matchMedia=="function"&&window.matchMedia("(max-width: 767px)").matches}function xS(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 mi(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(oh(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})),L(_.EDITOR_PREVIEW_CLOSED,s),e.getById(t.editorWindowId)?.renderCustomTitleBarButtons?.()}function Ra(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||lt(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?.()},AS)}function LS(e,t,n){const o=`os.${n.type}.changed`,s=String(n.id);t.unsubscribe=wn(o,i=>{const r=i?.ids;!Array.isArray(r)||!r.some(l=>String(l)===s)||Ra(e,t)})}let nh=0;function oh(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 sh(e,t,n){oh(e,t);const o=G(_.EDITOR_PREVIEW_LIVE,{enabled:!0,debounceMs:th},{editorWindowId:t.editorWindowId,content:n});if(!o||o.enabled===!1)return;const s=e.getById(t.editorWindowId)?.iframe?.contentWindow;if(!s)return;nh+=1;const i=`${t.previewWindowId}-watch-${nh}`;try{s.postMessage({type:"os-editor-live-watch",watchId:i,debounceMs:typeof o.debounceMs=="number"?o.debounceMs:th},window.location.origin),t.watchId=i}catch{}}let TS=SS;async function NS(e,t){const n=Oe.state.pairings.get(t.id);if(n){mi(e,n,"toggled","close");return}if(Oe.state.busyEditors.has(t.id)||!e.getById(t.id))return;const o=lt(t.id);if(!o?.previewUrl){X({message:k("No preview is available for this content.")});return}Oe.state.busyEditors.add(t.id),t.renderCustomTitleBarButtons?.();const s=IS();s||t.applySnap?.("left");const i=TS(t);i.then(f=>{f.status==="error"&&X({message:k("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 l=k("Preview");o.label&&(l=le(k("Preview: %s"),o.label));let a={id:r,baseId:r,url:o.previewUrl,title:l,icon:"dashicons-visibility",ephemeral:!0,...s?{}:{initialState:"snapped-right"}};const c=G(_.EDITOR_PREVIEW_WINDOW_CONFIG,a,{editorWindowId:t.id,content:o});if(c&&typeof c=="object"&&typeof c.id=="string"&&c.id!==""&&typeof c.url=="string"&&c.url!==""?a=c:typeof console<"u"&&console.warn("[openstation] `os.editor-preview.window-config` filter returned an invalid config; using the default."),await e.open(a),!e.getById(t.id)||fo(lt(t.id))!==fo(o)){e.getById(a.id)?.destroy?.();return}const d={editorWindowId:t.id,previewWindowId:a.id,postKey:fo(o),openUrl:a.url,unsubscribe:()=>{},reloadTimer:null,watchId:""};LS(e,d,o),sh(e,d,o),Oe.state.pairings.set(t.id,d);const u={editorWindowId:t.id,previewWindowId:a.id,content:o};document.dispatchEvent(new CustomEvent("os-editor-preview-opened",{detail:u})),L(_.EDITOR_PREVIEW_OPENED,u),i.then(f=>{Oe.state.pairings.get(t.id)===d&&f.status==="saved"&&Ra(e,d,f.previewUrl)})}function DS({manager:e}){pi({id:"desktop-mode/editor-preview",label:k("Preview"),icon:"dashicons-visibility",placement:"right",order:55,match:t=>!t.config.native&&(!!lt(t.id)?.previewUrl||xS(t)),render:(t,n)=>{if(!lt(n.id)?.previewUrl){const i=k("Save the post to enable its preview");t.setAttribute("aria-disabled","true"),t.setAttribute("aria-label",i),t.setAttribute("title",i),t.classList.add("os-window__btn--disabled"),t.addEventListener("click",r=>{r.stopPropagation(),X({message:k("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(),NS(e,n)})}}),Y(_.WINDOW_CONTENT_CHANGED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);n&&fo(t.content)!==n.postKey&&mi(e,n,"content-changed","close"),e.getById(t.windowId)?.renderCustomTitleBarButtons?.()}),Y(_.WINDOW_CLOSED,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);if(n){mi(e,n,"editor-closed","destroy");return}const o=CS(t.windowId);o&&mi(e,o,"preview-closed","none")}),Y(_.IFRAME_READY,"desktop-mode/editor-preview",t=>{if(!t?.windowId)return;const n=Oe.state.pairings.get(t.windowId);if(n){const o=lt(t.windowId);o&&fo(o)===n.postKey&&sh(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){Ra(e,o,eh(n.previewUrl));return}}})}const ih="none",rh=re("desktop-mode/unfocus-effect-registry",()=>({registry:new Map,listeners:new Set})),po=rh.state.registry,Oa=rh.state.listeners,ah=/^[a-z0-9_/-]+$/;function gi(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):ah.test(e.id.trim().toLowerCase())?e.id.trim().toLowerCase()===ih&&t.push('id ("none" is reserved)'):t.push(`id (must match ${ah} — 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();po.set(n,{...e,id:n}),Pa()}function RS(e){po.delete(e.toLowerCase())&&Pa()}function OS(e){if(!e)return 0;let t=0;for(const[n,o]of Array.from(po.entries()))o.owner===e&&(po.delete(n),t++);return t>0&&Pa(),t}function Ma(){const e=Array.from(po.values()),t=G(_.UNFOCUS_EFFECTS,e);return Array.isArray(t)?t:(typeof console<"u"&&console.warn("[openstation] `os.unfocus-effects` filter returned a non-array; falling back to registry list."),e)}function lh(e){return Ma().find(t=>t.id===e)}function MS(e){return Oa.add(e),()=>{Oa.delete(e)}}function Pa(){const e=Array.from(Oa);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] unfocus-effect registry listener threw:",n)}}gi({id:"darken",label:k("Darken"),description:k("Dim unfocused windows so the focused one stands out."),className:"os-window--fx-darken"}),gi({id:"frost",label:k("Frost"),description:k("Throw unfocused windows out of focus — a soft, frosted-glass blur, as if you were looking at them through an iced-over pane."),className:"os-window--fx-frost"}),gi({id:"grayscale",label:k("Grayscale"),description:k("Drain the colour from unfocused windows so the focused one is the only thing still in colour — your eye snaps right to it."),className:"os-window--fx-grayscale"});function PS(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Se(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(_.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)||(OS(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function WS(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Se(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(_.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)||(rS(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}const Wa="data-desktop-unfocus-effect",$a="data-desktop-unfocus-effect-class";let ch=!1;function $S(e){return e.querySelector("canvas")!==null}function US({manager:e,osSettings:t}){if(ch)return;ch=!0;let n=t.getOsSettingsSnapshot().unfocusEffect;const o=(r,l)=>{const a=r.getAttribute($a);a&&(r.classList.remove(a),r.removeAttribute($a));const c=r.getAttribute(Wa);c&&lh(c)?.clear?.(r);for(const d of l)d.className&&r.classList.remove(d.className);r.removeAttribute(Wa)},s=(r,l)=>{l.className&&(r.classList.add(l.className),r.setAttribute($a,l.className)),r.setAttribute(Wa,l.id),l.apply?.(r)},i=()=>{const r=n===ih?void 0:lh(n),l=Ma();for(const a of e.getAll()){const c=a.element;c&&(o(c,l),!(!r||a.isFocused()||a.state==="minimized")&&($S(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()}),MS(()=>i()),i()}function FS(){const e=new Set,t=new Set,n=async o=>{if(!o.scriptUrl||t.has(o.scriptUrl)){e.add(o.handle);return}try{await Se(o.scriptUrl,{translations:o.scriptTranslations,l10n:o.scriptL10n,before:o.scriptBefore,after:o.scriptAfter})}catch(s){L(_.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)||(Db(i),e.delete(i));for(const i of o)!i.handle||e.has(i.handle)||await n(i)}}function dh(e){return e.startsWith("dashicons-")?e:"dashicons-admin-generic"}function BS(e,t){if(t.url&&fn(t.url)||t.url&&Ge(t.url))return;const n=ae(t.url,e.adminUrl);e.windowManager.open({id:n,baseId:n,url:t.url,parentUrl:t.url,title:t.title,icon:dh(t.icon),submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}function HS(e,t,n){fn(n.url)||Ge(n.url)||e.windowManager.open({id:ae(n.url,e.adminUrl),baseId:ae(t.url,e.adminUrl),url:n.url,parentUrl:t.url,title:t.title,icon:dh(t.icon),submenu:t.submenu,selfLabel:t.selfLabel,multi:!!t.multi})}const zS=130,GS=240,jS=160,wi=14,uh=18,Et=12,VS=160,qS="os-constellation-open",yi=e=>e.dataset.menuSlug??e.dataset.constellationId??"",Ua=e=>{const t=e.closest(".os-dock")?.getAttribute("data-os-dock-placement");return t==="left"?"right":t==="right"?"left":"top"},KS={top:"ArrowUp",right:"ArrowRight",left:"ArrowLeft"};function YS(){return typeof window.matchMedia=="function"&&window.matchMedia("( prefers-reduced-motion: reduce )").matches}function XS(e){let t=null,n=null,o="",s=null,i=null;const r=()=>{s!==null&&(window.clearTimeout(s),s=null)},l=()=>{i!==null&&(window.clearTimeout(i),i=null)},a=C=>{if(!(C instanceof Element))return null;const w=C.closest(".os-dock__item");return!w||!yi(w)||!w.closest(".os-dock")?null:w},c=new Set,d=()=>{document.body.classList.toggle(qS,t!==null||c.size>0)},u=(C,w={})=>{if(!t)return;const E=n,T=t;t=null,n=null,o="",E?.removeAttribute("data-constellation-open"),C==="cut"||YS()?T.remove():(T.classList.remove("os-constellation--open"),T.classList.add("os-constellation--closing"),c.add(T),window.setTimeout(()=>{T.remove(),c.delete(T),d()},jS)),d(),w.restoreFocus&&E&&E.querySelector(".os-dock__item-primary")?.focus(),L(_.CONSTELLATION_CLOSED,{menuSlug:E?yi(E):"",handoff:w.handoff===!0})},f=(C=!1,w=!1)=>{r(),l(),u(w?"cut":"exit",{restoreFocus:C})},p=(C,w=!1)=>{r(),l();const E=yi(C);if(t&&o===E){w&&yn(t,0);return}const T=ZS(e,C);if(!T){f();return}const M=t!==null;u("exit",{handoff:M});const P=JS(e,T);t=eA(e,T,P,C,f);for(const v of Fa(t))v.tabIndex=-1;n=C,o=E,t.dataset.osCnSide=Ua(C),document.body.appendChild(t),d(),C.setAttribute("data-constellation-open",""),aA(t),lA(t,C),requestAnimationFrame(()=>{t?.classList.add("os-constellation--open"),w&&t&&yn(t,0)}),L(_.CONSTELLATION_OPENED,{menuSlug:E,item:T,instances:P,handoff:M})},g=C=>{if(C.pointerType&&C.pointerType!=="mouse")return;if(t&&C.target instanceof Node&&t.contains(C.target)){l();return}const w=a(C.target);w&&(l(),!(t&&o===yi(w))&&(r(),s=window.setTimeout(()=>{s=null,p(w)},t?0:zS)))},m=C=>{const w=C.relatedTarget;w instanceof Node&&(t&&t.contains(w)||n&&n.contains(w)||a(w))||(r(),l(),i=window.setTimeout(()=>{i=null,f()},GS))},h=C=>{if(t&&C.target instanceof Node&&t.contains(C.target)){const E=Fa(t),T=E.indexOf(C.target);C.key==="Escape"?(C.preventDefault(),f(!0)):C.key==="ArrowDown"?(C.preventDefault(),yn(t,T+1)):C.key==="ArrowUp"?(C.preventDefault(),T<=0?f(!0):yn(t,T-1)):C.key==="Home"?(C.preventDefault(),yn(t,0)):C.key==="End"?(C.preventDefault(),yn(t,E.length-1)):C.key==="Tab"&&f(!0);return}const w=a(C.target);w&&(C.key===KS[Ua(w)]?(C.preventDefault(),p(w,!0)):C.key==="Escape"&&f())},b=()=>f(!1,!0),y=C=>{!t||!(C.target instanceof Element)||t.contains(C.target)||C.target.closest(".os-dock__item")&&f()};return document.body.setAttribute(ea,""),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(ei,b),document.addEventListener("scroll",b,!0),()=>{f(!1,!0);for(const C of c)C.remove();c.clear(),d(),document.body.removeAttribute(ea),document.removeEventListener(ei,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 ZS(e,t){const n=t.dataset.menuSlug;if(n){const i=e.getMenuItems().find(l=>l.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 JS(e,t){const n=new Set;if(t.menuItem){const o=QS(e,t.menuItem);for(const i of e.windowManager.getAllByBaseIdOnActiveDesktop(o))n.add(i);const s=ae(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&&ae(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 QS(e,t){return t.windowId?t.windowId:ae(t.url,e.adminUrl)}function eA(e,t,n,o,s){const i=document.createElement("div");i.className="os-constellation",i.setAttribute("role","menu"),i.setAttribute("aria-label",le(k("%s menu"),t.title)),i.style.setProperty("--os-cn-hue",String(dn(t.title)));const r=document.createElement("div");r.className="os-constellation__surface",i.appendChild(r),r.appendChild(tA(e,t,s));let l=0;const a=()=>l++;n.length>0&&r.appendChild(nA(e,t,n,s,a)),t.submenu.length>0&&r.appendChild(oA(e,t,s,a)),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 G(_.CONSTELLATION_PANEL,i,u)}function tA(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(iA(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){BS(e,t.menuItem);return}fh(e,t,t.submenu[0])}),o}function fh(e,t,n){if(n){if(n.onSelect){n.onSelect();return}if(t.menuItem){HS(e,t.menuItem,n);return}n.url&&window.open(n.url,"_blank","noopener,noreferrer")}}function nA(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",k("Open windows")),i.appendChild(ph(le(en("%d open window","%d open windows",n.length),n.length)));for(const r of n){const l=document.createElement("button");l.type="button",l.className="os-constellation__row os-constellation__row--live",l.setAttribute("role","menuitem"),l.style.setProperty("--os-cn-row",String(s())),r.state==="minimized"&&(l.dataset.state="minimized");const a=document.createElement("span");a.className="os-constellation__pip",a.setAttribute("aria-hidden","true"),l.appendChild(a);const c=document.createElement("span");c.className="os-constellation__row-label",c.textContent=r.config.title||t.title,l.appendChild(c);const d=document.createElement("span");d.className="os-constellation__row-meta",d.textContent=r.state==="minimized"?k("Minimized"):k("Open"),l.appendChild(d),l.addEventListener("click",()=>{o(),r.state==="minimized"&&r.restore(),e.windowManager.focus(r)}),i.appendChild(l)}return i}function oA(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(ph(k("Open")));for(const i of t.submenu)s.appendChild(sA(e,t,i,n,o()));return s}function sA(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(dn(n.title)));const r=document.createElement("span");r.className="os-constellation__orbit",r.setAttribute("aria-hidden","true"),i.appendChild(r);const l=document.createElement("span");return l.className="os-constellation__row-label",l.textContent=n.title,i.appendChild(l),i.addEventListener("click",()=>{o(),fh(e,t,n)}),i}function ph(e){const t=document.createElement("span");return t.className="os-constellation__legend",t.textContent=e,t}function iA(e){if(!e.startsWith("dashicons-")){const n=document.createElement("span");if(n.className="os-constellation__head-art",so(n,e,"currentColor"))return n}const t=document.createElement("span");return t.className="dashicons",t.classList.add(e.startsWith("dashicons-")?Zc(e):"dashicons-admin-generic"),t}function Fa(e){return Array.from(e.querySelectorAll(".os-constellation__row"))}function yn(e,t){const n=Fa(e);if(n.length===0)return;const o=Math.max(0,Math.min(n.length-1,t));n[o].focus()}const rA=["--wp-admin-theme-color","--os-titlebar-bg-focused","--os-titlebar-color-focused"];function aA(e){const t=document.querySelector(".os-shell");if(!t)return;const n=window.getComputedStyle(t);for(const o of rA){const s=n.getPropertyValue(o).trim();s&&e.style.setProperty(o,s)}}function lA(e,t){const n=t.getBoundingClientRect(),o=Ua(t),s=o==="top"?n.top-wi-Et:window.innerHeight-Et*2;if(e.style.setProperty("--os-cn-max-h",`${Math.max(VS,s)}px`),o!=="top"){e.style.left=o==="right"?`${n.right+wi}px`:`${n.left-wi}px`;const i=e.offsetHeight,r=window.innerHeight,l=Math.max(Et,Math.min(n.top,r-Et-i));e.style.top=`${l}px`;const a=Math.max(uh,Math.min(n.top+n.height/2-l,i-uh));e.style.setProperty("--os-cn-beam-y",`${a}px`);return}e.style.left=`${n.left+n.width/2}px`,e.style.top=`${n.top-wi}px`,requestAnimationFrame(()=>{const i=e.getBoundingClientRect(),r=window.innerWidth;let l=0;i.left<Et?l=Et-i.left:i.right>r-Et&&(l=r-Et-i.right),l!==0&&(e.style.setProperty("--os-cn-shift",`${l}px`),e.style.setProperty("--os-cn-beam-x",`${-l}px`))})}const hh=re("desktop-mode/window-themes-registry",()=>({registry:new Map,listeners:new Set})),ho=hh.state.registry,cA=hh.state.listeners,mh=/^[a-z0-9_/-]+$/;function gh(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)"):mh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${mh} — 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();ho.set(n,{...e,id:n}),Ba()}function wh(e){ho.delete(e.toLowerCase())&&Ba()}function dA(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&&Ba(),t}function yh(){return Array.from(ho.values()).sort((e,t)=>(e.priority??100)-(t.priority??100))}function Ba(){const e=Array.from(cA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-theme registry listener threw:",n)}}function uA(){const e=new Set,t=new Set;let n=new Map;const o=new Set,s=async a=>{if(!a.scriptUrl||t.has(a.scriptUrl)){e.add(a.handle);return}try{await Se(a.scriptUrl,{translations:a.scriptTranslations,l10n:a.scriptL10n,before:a.scriptBefore,after:a.scriptAfter})}catch(c){L(_.SHELL_ERROR,{scope:"window-theme-script-load",handle:a.handle,url:a.scriptUrl,error:c});return}t.add(a.scriptUrl),e.add(a.handle)},i=a=>{const c=new Map;if(!a)return c;for(const d of a){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=a=>{const c=new Set;for(const u of yh())u.owner===a&&c.add(u.id);const d=n.get(a);if(d)for(const u of d)c.add(u);return c},l=a=>{if(a){for(const c of a)if(!(!c.id||!c.tokens))try{gh({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){L(_.SHELL_ERROR,{scope:"window-theme-shell-register",id:c.id,error:d})}}};return async(a,c)=>{const d=new Set;for(const u of a)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)wh(p),o.delete(p);dA(u),e.delete(u)}l(c);for(const u of a)!u.handle||e.has(u.handle)||await s(u);n=i(c)}}const bh=re("desktop-mode/window-controls-registry",()=>({registry:new Map,listeners:new Set})),mo=bh.state.registry,fA=bh.state.listeners,vh=/^[a-z0-9_/-]+$/;function go(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):vh.test(e.id.trim().toLowerCase())||t.push(`id (must match ${vh} — 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();mo.set(n,{...e,id:n}),Ha()}function _h(e){mo.delete(e.toLowerCase())&&Ha()}function pA(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&&Ha(),t}function Eh(){return Array.from(mo.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Ha(){const e=Array.from(fA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-control registry listener threw:",n)}}function hA(){go({id:"core/minimize",label:k("Minimize"),icon:"minimize",placement:"controls",order:10,core:!0,match:()=>!0,onClick:e=>{e.minimize()}}),go({id:"core/maximize",label:k("Maximize"),icon:"maximize",placement:"controls",order:20,core:!0,match:()=>!0,onClick:e=>{e.toggleMaximize()}}),go({id:"core/focus-tab",label:k("Enter fullscreen"),icon:"fullscreen",placement:"controls",order:30,core:!0,match:()=>!0,onClick:e=>{e.toggleFullscreen()}}),go({id:"core/close",label:k("Close"),icon:"close",placement:"controls",order:50,core:!0,match:()=>!0,onClick:e=>{e.close()}})}function mA(){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 Se(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(l){L(_.SHELL_ERROR,{scope:"window-control-script-load",handle:r.handle,url:r.scriptUrl,error:l});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const l=new Map;if(!r)return l;for(const a of r){if(!a.scriptHandle||!a.id)continue;let c=l.get(a.scriptHandle);c||(c=new Set,l.set(a.scriptHandle,c)),c.add(a.id)}return l},i=r=>{const l=new Set;for(const c of Eh())c.owner===r&&l.add(c.id);const a=n.get(r);if(a)for(const c of a)l.add(c);return l};return async(r,l)=>{const a=new Set;for(const c of r)c.handle&&a.add(c.handle);for(const c of Array.from(e))if(!a.has(c)){for(const d of i(c))_h(d);pA(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(l)}}const kh=re("desktop-mode/window-slots-registry",()=>({registry:new Map,listeners:new Set})),wo=kh.state.registry,gA=kh.state.listeners,Sh=/^[a-z0-9_/-]+$/,Ah=new Set(["before-titlebar","before-icon","icon","title","after-title","before-controls","controls","after-controls","after-titlebar"]);function Ch(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())||t.push(`id (must match ${Sh} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.slot!="string"||e.slot.trim()===""?t.push("slot (missing)"):Ah.has(e.slot)||t.push(`slot (must be one of ${Array.from(Ah).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();wo.set(n,{...e,id:n}),Ga()}function za(e){wo.delete(e.toLowerCase())&&Ga()}function wA(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&&Ga(),t}function Ih(){return Array.from(wo.values()).sort((e,t)=>{const n=e.order??100,o=t.order??100;return n!==o?n-o:e.id.localeCompare(t.id)})}function Ga(){const e=Array.from(gA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-slot registry listener threw:",n)}}function yA(){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 Se(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(l){L(_.SHELL_ERROR,{scope:"window-slot-script-load",handle:r.handle,url:r.scriptUrl,error:l});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const l=new Map;if(!r)return l;for(const a of r){if(!a.scriptHandle||!a.id)continue;let c=l.get(a.scriptHandle);c||(c=new Set,l.set(a.scriptHandle,c)),c.add(a.id)}return l},i=r=>{const l=new Set;for(const c of Ih())c.owner===r&&l.add(c.id);const a=n.get(r);if(a)for(const c of a)l.add(c);return l};return async(r,l)=>{const a=new Set;for(const c of r)c.handle&&a.add(c.handle);for(const c of Array.from(e))if(!a.has(c)){for(const d of i(c))za(d);wA(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(l)}}const bA="desktop-mode-notice-dismissed";function vA(){const t=window.wp?.os?.config?.currentUserId;return typeof t=="number"&&t>0?String(t):"anon"}function xh(){return`${bA}:${vA()}`}function ja(){try{const e=window.localStorage.getItem(xh());if(!e)return{};const t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return{}}function Lh(e){try{window.localStorage.setItem(xh(),JSON.stringify(e))}catch{}}function Va(e){return e?ja()[e]===!0:!1}function bi(e){if(!e)return;const t=ja();t[e]=!0,Lh(t)}function Th(e){if(!e)return;const t=ja();t[e]&&(delete t[e],Lh(t))}const _A=ce`:host{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:10px 14px;font:var( --os-ui-notice-font,13px/1.5 var( --os-font,system-ui ) );color:var( --os-ui-notice-color,var( --os-ui-fg,#1d2327 ) );background:var( --os-ui-notice-bg,var( --os-ui-hover,rgba( 0,0,0,0.04 ) ) );border-block-end:1px solid var( --os-ui-notice-border,var( --os-ui-border,rgba( 0,0,0,0.08 ) ) );border-inline-start:4px solid var( --os-ui-notice-accent,var( --os-ui-border,#646970 ) )}:host( [ hidden ] ){display:none}.os-notice__icon{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;color:var( --os-ui-notice-accent,var( --os-ui-accent,#646970 ) )}.os-notice__icon[ hidden ]{display:none}.os-notice__label{flex:1;min-width:0;word-wrap:break-word}::slotted( a ){color:var( --os-ui-notice-link,var( --wp-admin-theme-color,#2271b1 ) );border-radius:2px}::slotted( a:hover ),::slotted( a:focus-visible ){color:var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) )}::slotted( a:focus-visible ){outline:2px solid var( --os-ui-notice-link-hover,var( --os-ui-accent-strong,#135e96 ) );outline-offset:2px}::slotted( p:first-child ){margin-block-start:0}::slotted( p:last-child ){margin-block-end:0}.os-notice__close{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:none;background:transparent;color:inherit;opacity:0.6;cursor:pointer;border-radius:4px;transition:opacity 0.12s ease,background-color 0.12s ease}.os-notice__close:hover{opacity:1;background:var( --os-ui-hover,rgba( 0,0,0,0.06 ) )}.os-notice__close:focus-visible{opacity:1;outline:2px solid var( --wp-admin-theme-color,#2271b1 );outline-offset:1px}.os-notice__close[ hidden ]{display:none}.os-notice__close svg{width:14px;height:14px}:host( [ tone='info' ] ){--os-ui-notice-accent:var( --os-ui-notice-info,var( --os-ui-info-fg,#0969da ) );--os-ui-notice-bg:var( --os-ui-notice-info-bg,rgba( 9,105,218,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-info-border,rgba( 9,105,218,0.16 ) )}:host( [ tone='success' ] ){--os-ui-notice-accent:var( --os-ui-notice-success,var( --os-ui-success-fg,#1a7f37 ) );--os-ui-notice-bg:var( --os-ui-notice-success-bg,rgba( 26,127,55,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-success-border,rgba( 26,127,55,0.16 ) )}:host( [ tone='warning' ] ){--os-ui-notice-accent:var( --os-ui-notice-warning,var( --os-ui-warning-fg,#9a6700 ) );--os-ui-notice-bg:var( --os-ui-notice-warning-bg,rgba( 154,103,0,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-warning-border,rgba( 154,103,0,0.16 ) )}:host( [ tone='error' ] ),:host( [ tone='danger' ] ){--os-ui-notice-accent:var( --os-ui-notice-error,var( --os-ui-danger,#cf222e ) );--os-ui-notice-bg:var( --os-ui-notice-error-bg,rgba( 207,34,46,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-error-border,rgba( 207,34,46,0.16 ) )}:host( [ tone='neutral' ] ){--os-ui-notice-accent:var( --os-ui-notice-neutral,var( --os-ui-fg-muted,#57606a ) );--os-ui-notice-bg:var( --os-ui-notice-neutral-bg,rgba( 87,96,106,0.08 ) );--os-ui-notice-border:var( --os-ui-notice-neutral-border,rgba( 87,96,106,0.16 ) )}`,fs=class fs extends Ee{connectedCallback(){super.connectedCallback(),this.hasAttribute("role")||this.setAttribute("role","status"),this.hasAttribute("tone")||this.setAttribute("tone","info");const t=this.getAttribute("notice-id");t&&Va(t)&&(this.hidden=!0)}dismiss(){this.hidden=!0;const t=this.getAttribute("notice-id");t&&bi(t),this.emit("os-notice-dismiss",{noticeId:t??void 0})}undismiss(){const t=this.getAttribute("notice-id");t&&Th(t),this.hidden=!1}render(){const t=this.getAttribute("icon"),n=!this.hasAttribute("not-dismissible");return j` |
| 72 |
<span |
| 73 |
class="os-notice__icon dashicons ${t??""}" |
| 74 |
?hidden=${!t} |
| 75 |
aria-hidden="true" |
| 76 |
></span> |
| 77 |
<span class="os-notice__label"><slot></slot></span> |
| 78 |
<button |
| 79 |
type="button" |
| 80 |
class="os-notice__close" |
| 81 |
?hidden=${!n} |
| 82 |
aria-label=${k("Dismiss notice")} |
| 83 |
@click=${o=>this._onDismiss(o)} |
| 84 |
> |
| 85 |
<svg viewBox="0 0 14 14" aria-hidden="true"> |
| 86 |
<path |
| 87 |
d="M3 3 L11 11 M11 3 L3 11" |
| 88 |
stroke="currentColor" |
| 89 |
stroke-width="1.6" |
| 90 |
stroke-linecap="round" |
| 91 |
fill="none" |
| 92 |
></path> |
| 93 |
</svg> |
| 94 |
</button> |
| 95 |
`}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.dismiss()}};fs.props=["tone","notDismissible","icon","noticeId"],fs.styles=[_A],fs.help=void 0;let qa=fs;Ie("os-notice",qa);const yo=re("desktop-mode/window-notices",()=>({entries:new Map})),EA=/^[a-z0-9_/-]+$/;function Nh(e){return`os-notice/${e.toLowerCase()}`}function kA(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 Dh(e){if(!e||typeof e!="object")return()=>{};const t=String(e.id??"").trim().toLowerCase();if(!t||!EA.test(t))return()=>{};if(typeof e.message!="string"||e.message==="")return()=>{};const n={...e,id:t};yo.state.entries.set(t,n);const o=Nh(t);return Ch({id:o,slot:"after-titlebar",order:n.order??100,replace:!1,owner:n.owner,match:s=>{const i=yo.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=yo.state.entries.get(t);i&&s.appendChild(kA(i))}}),()=>Ka(t)}function Ka(e){const t=String(e??"").trim().toLowerCase();t&&yo.state.entries.delete(t)&&za(Nh(t))}function Rh(){return Array.from(yo.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 SA(e){const t=String(e??"").trim().toLowerCase();t&&bi(t)}function AA(e){const t=String(e??"").trim().toLowerCase();t&&Th(t)}function CA(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 Oh(e){const t=new Set;for(const n of e)!n||typeof n.id!="string"||!n.id||(t.add(n.id.toLowerCase()),Dh({id:n.id,message:n.message,tone:n.tone,dismissible:n.dismissible!==!1,icon:n.icon,match:CA(n.match),order:typeof n.order=="number"?n.order:void 0,owner:"__server__"}));for(const n of Rh())n.owner==="__server__"&&(t.has(n.id)||Ka(n.id))}const Mh=re("desktop-mode/window-chrome-registry",()=>({registry:new Map,listeners:new Set})),bo=Mh.state.registry,IA=Mh.state.listeners,Ph=/^[a-z0-9_/-]+$/;function xA(e){const t=[];!e||typeof e!="object"?t.push("def (not an object)"):(typeof e.id!="string"||e.id.trim()===""?t.push("id (missing)"):Ph.test(e.id.trim().toLowerCase())||t.push(`id (must match ${Ph} — lowercase alphanum, hyphens, underscores, slashes for vendor/sub-id)`),typeof e.match!="function"&&t.push("match (must be a function)"),typeof e.render!="function"&&t.push("render (must be a function)")),Ne("WindowChrome",t,e);const n=e.id.trim().toLowerCase();bo.set(n,{...e,id:n}),Ya()}function Wh(e){bo.delete(e.toLowerCase())&&Ya()}function LA(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 $h(){return Array.from(bo.values()).sort((e,t)=>e.id.localeCompare(t.id))}function Ya(){const e=Array.from(IA);for(const t of e)try{t()}catch(n){typeof console<"u"&&console.error("[openstation] window-chrome registry listener threw:",n)}}function TA(){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 Se(r.scriptUrl,{translations:r.scriptTranslations,l10n:r.scriptL10n,before:r.scriptBefore,after:r.scriptAfter})}catch(l){L(_.SHELL_ERROR,{scope:"window-chrome-script-load",handle:r.handle,url:r.scriptUrl,error:l});return}t.add(r.scriptUrl),e.add(r.handle)},s=r=>{const l=new Map;if(!r)return l;for(const a of r){if(!a.scriptHandle||!a.id)continue;let c=l.get(a.scriptHandle);c||(c=new Set,l.set(a.scriptHandle,c)),c.add(a.id)}return l},i=r=>{const l=new Set;for(const c of $h())c.owner===r&&l.add(c.id);const a=n.get(r);if(a)for(const c of a)l.add(c);return l};return async(r,l)=>{const a=new Set;for(const c of r)c.handle&&a.add(c.handle);for(const c of Array.from(e))if(!a.has(c)){for(const d of i(c))Wh(d);LA(c),e.delete(c)}for(const c of r)!c.handle||e.has(c.handle)||await o(c);n=s(l)}}const Xa=window.location.origin;let NA=0;const bn=new Map,vn=new Map,vo=new Map;function DA(e,t){return vo.set(e,t),()=>{vo.get(e)===t&&vo.delete(e)}}function RA(){return`os-conn-${++NA}`}function OA(e){const t=(a,c)=>{try{a.contentWindow?.postMessage(c,Xa)}catch(d){typeof console<"u"&&console.error("[openstation] connection: postMessage failed",d)}},n=(a,c={})=>{const d=RA(),u=Array.isArray(c.topics)?[...c.topics]:[],f=new Map,p=[];let g=!1,m=!1;const h=()=>{const M=vo.get(a);return M||(e.getById(a)?.iframe??null)},b=()=>{if(h())return!1;const M=e.getById(a);return!!M&&M.config?.native===!0},y=[],C=()=>{const M=h();if(M)for(;p.length;){const P=p.shift();t(M,{type:"os-bridge-publish",connectionId:d,topic:P.topic,payload:P.payload})}},w={id:d,target:a,isOpen:()=>g,subscribe(M,P){const v=P;if(b()){const D=xv(a,M,(I,W)=>{L(_.CONNECTION_MESSAGE,{connectionId:d,topic:W.channel,direction:"in"});try{v(I,{topic:W.channel})}catch(z){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",z)}});return y.push(D),D}let $=f.get(M);return $||($=new Set,f.set(M,$)),$.add(v),()=>{$?.delete(v)}},send(M,P){if(m)return;if(L(_.CONNECTION_MESSAGE,{connectionId:d,topic:M,direction:"out"}),b()){Tv(a,M,P);return}if(!g){p.push({topic:M,payload:P});return}const v=h();v&&t(v,{type:"os-bridge-publish",connectionId:d,topic:M,payload:P})},disconnect(){w._destroy("disconnect")},_targetWindow:h,_handleIframeMessage(M){if(!M||typeof M!="object")return;const P=M;if(P.type==="os-bridge-handshake-ack"){if(g)return;g=!0,L(_.CONNECTION_OPENED,{connectionId:d,targetWindowId:a,topics:u,connection:w});try{c.onOpen?.()}catch(v){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",v)}C();return}if(P.type==="os-bridge-publish"){const v=M,$=typeof v.topic=="string"?v.topic:"";if(!$)return;L(_.CONNECTION_MESSAGE,{connectionId:d,topic:$,direction:"in"});const D=f.get($);if(D)for(const W of Array.from(D))try{W(v.payload,{topic:$})}catch(z){typeof console<"u"&&console.error("[openstation] connection subscriber threw:",z)}const I=f.get("*");if(I)for(const W of Array.from(I))try{W(v.payload,{topic:$})}catch(z){typeof console<"u"&&console.error("[openstation] connection wildcard subscriber threw:",z)}return}P.type==="os-bridge-disconnect"&&w._destroy("disconnect")},_destroy(M){if(m)return;m=!0;const P=g;g=!1,bn.delete(d);const v=vn.get(a);v&&(v.delete(d),v.size===0&&vn.delete(a));for(const $ of y.splice(0))try{$()}catch{}if(P){const $=h();$&&t($,{type:"os-bridge-disconnect",connectionId:d})}L(_.CONNECTION_CLOSED,{connectionId:d,reason:M});try{c.onClose?.(M)}catch($){typeof console<"u"&&console.error("[openstation] connection.onClose threw:",$)}}};bn.set(d,w);let E=vn.get(a);if(E||(E=new Set,vn.set(a,E)),E.add(d),b())return Promise.resolve().then(()=>{if(!(m||g)){g=!0,L(_.CONNECTION_OPENED,{connectionId:d,targetWindowId:a,topics:u});try{c.onOpen?.()}catch(M){typeof console<"u"&&console.error("[openstation] connection.onOpen threw:",M)}}}),w;const T=h();return T&&t(T,{type:"os-bridge-handshake",connectionId:d,targetWindowId:a,topics:u}),w},o=(a,c)=>{if(!a||typeof a!="object")return;const d=a;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;bn.get(d.connectionId)?._handleIframeMessage(a)},s=(a,c,d)=>{const f=vo.get(a)??e.getById(a)?.iframe??null;if(!f)return;const p=G(_.IFRAME_CONNECTION_REQUEST,!0,{windowId:a,requestId:c,topics:d.slice()});if(p===!1){try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!1,reason:"rejected"},Xa)}catch{}return}const g=p&&typeof p=="object"&&Array.isArray(p.topics)?p.topics:d,m=n(a,{topics:g});try{f.contentWindow?.postMessage({type:"os-bridge-connection-ack",requestId:c,accepted:!0,connectionId:m.id},Xa)}catch{}};return{connect:n,getConnection:a=>bn.get(a)??null,routeIncomingFromIframe:o,onIframeReady:a=>{const c=vn.get(a);if(c)for(const d of Array.from(c)){const u=bn.get(d);if(!u||u.isOpen())continue;const f=u._targetWindow();f&&t(f,{type:"os-bridge-handshake",connectionId:u.id,targetWindowId:u.target,topics:[]})}},onWindowClosed:a=>{const c=vn.get(a);if(c)for(const d of Array.from(c))bn.get(d)?._destroy("window-closed")}}}const MA={};function PA(...e){(typeof{url:dr&&dr.tagName.toUpperCase()==="SCRIPT"&&dr.src||new URL("desktop.min.js",document.baseURI).href}<"u"&&MA?"production":void 0)!=="production"&&console.log(...e)}const WA="iframe:";function Za(e){return WA+e}function Uh(e){return e.icon&&typeof e.icon=="string"&&e.icon.startsWith("dashicons-")?e.icon:e.kind==="navigate"?"dashicons-external":"dashicons-arrow-right-alt"}function $A(e,t){const n=t.toLowerCase().replace(/[^a-z0-9_-]+/g,"-");return`win-${e.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}-${n}`}class UA{constructor(t){this.subscribedWindowId=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"&&(fi(Za(o.windowId)),this.subscribedWindowId===o.windowId&&(this.subscribedWindowId=null))}),document.addEventListener("os-window-changed",n=>{const o=n.detail;!o||typeof o.windowId!="string"||o.reason==="state"&&o.state==="minimized"&&this.subscribedWindowId===o.windowId&&(this.subscribedWindowId=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.subscribedWindowId&&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.subscribedWindowId&&this.applyList(s.id,o.commands)});const t=this.manager.getFocused();t&&this.onFocused(t.id)}onFocused(t){if(this.subscribedWindowId!==t){if(this.subscribedWindowId){const n=this.manager.getById(this.subscribedWindowId);if(n&&n.iframe&&n.iframe.contentWindow)try{n.iframe.contentWindow.postMessage({type:"os-commands-unsubscribe"},window.location.origin)}catch{}fi(Za(this.subscribedWindowId))}this.subscribedWindowId=t,this.sendSubscribe(t)}}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){PA("[os-cmd:parent] sendSubscribe: postMessage threw",o)}}applyList(t,n){const o=Za(t);fi(o);for(const s of n){if(!s||!s.name||!s.label)continue;const i=$A(t,s.name),r=typeof s.iconSvg=="string"&&s.iconSvg!==""?Qc(s.iconSvg):"",l={slug:i,label:s.label,icon:Uh(s),iconSvg:r!==""?r:void 0,owner:o,eager:!0,run:s.kind==="navigate"&&s.url?this.runNavigate(s.url,s.label,Uh(s)):this.runProxy(t,s.name)};try{ui(l)}catch(a){console.error("[openstation] iframe-bridge: dropping bad command",l,a)}}}runNavigate(t,n,o){return(s,i)=>{if(i.close(),Ge(t))return;const r=ae(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)}}}}const Fh="global",FA=/(?:document\.location\.href|window\.location\.href|location\.href)\s*=\s*['"]([^'"$]+?)['"]/,BA=/(?:document\.location|window\.location|location)\s*=\s*['"]([^'"$]+?)['"]/,HA=/location\.(?:assign|replace)\s*\(\s*['"]([^'"$]+?)['"]\s*\)/,zA=/(?:document\.location|window\.location|location)\s*(?:\.href\s*)?=|location\.(?:assign|replace)\s*\(/,GA=/getSiteEditorPage\s*\(|site-editor\.php/,jA=/^(wp_template_part|wp_template|wp_navigation|wp_block)-(.+)$/;function VA(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 qA{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,l=n.useMemo,a=o.useSelect;if(typeof s!="function"||typeof i!="function"||typeof r!="function"||typeof l!="function"||typeof a!="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:[],C=l(()=>u(y),[y]);return i(()=>{d.perLoader[h.name]=y,f()},[C]),i(()=>()=>{delete d.perLoader[h.name],f()},[]),null},g=()=>{const m=a(E=>{const T=E("core/commands");return!T||typeof T.getCommandLoaders!="function"?[]:[...T.getCommandLoaders(!1)||[],...T.getCommandLoaders(!0)||[]]},[]),h=a(E=>{const T=E("core/commands");return!T||typeof T.getCommands!="function"?[]:[...T.getCommands(!1)||[],...T.getCommands(!0)||[]]},[]),b=l(()=>Array.isArray(m)?m.map(E=>E&&E.name||""):[],[m]),y=b.join("|");i(()=>{d.loadersList=b,f()},[y]);const C=l(()=>u(Array.isArray(h)?h:[]),[h]);if(i(()=>{d.statics=Array.isArray(h)?h:[],f()},[C]),!Array.isArray(m)||m.length===0)return null;const w=[];for(const E of m)!E||typeof E.hook!="function"||w.push(s(p,{key:E.name,loader:E}));return s(n.Fragment||"div",null,w)};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||""} |
| 96 |
`;if(s!==this.lastFingerprint){this.lastFingerprint=s,fi(Fh);for(const i of o){if(i.kind==="skip")continue;const r=`global-${i.name.toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}`,l=this.iconFor(i),a={slug:r,label:i.label,icon:l,iconSvg:i.iconSvg&&i.iconSvg!==""?Qc(i.iconSvg):void 0,owner:Fh,run:i.kind==="navigate"&&i.url?this.runNavigate(i.url,i.windowTitle||i.label,l):this.runInvoke(i.name,i.label,l)};try{ui(a)}catch(c){console.error("[openstation] shell-harvester: dropping bad command",a,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=VA(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(FA)||i.match(BA)||i.match(HA);if(r&&r[1])try{n.url=new URL(r[1],window.location.href).toString(),n.kind="navigate"}catch{n.kind="action"}else if(zA.test(i)){const a=GA.test(i)?n.name.match(jA):null;if(a){const c=a[1],d=a[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=ae(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 l=this.runWithNavCapture(r);if(l){i.close();const a=ae(l,this.adminUrl);this.manager.open({id:a,baseId:a,url:l,title:n,icon:o})}}}runWithNavCapture(t){let n=null;const o=a=>{n===null&&typeof a=="string"&&a!==""&&(n=a)},s=window.location,i=new Proxy(s,{get(a,c){const d=a[c];return c==="assign"||c==="replace"?u=>o(u):typeof d=="function"?d.bind(a):d},set(a,c,d){return c==="href"&&o(d),!0}}),r=[],l=a=>{try{Object.defineProperty(a,"location",{configurable:!0,get:()=>i,set:c=>o(c)}),r.push({obj:a,key:"location"})}catch{}};l(document),l(window);try{t({close:()=>{}})}catch{}finally{for(const a of r)try{delete a.obj[a.key]}catch{}}return n}}const _n=[];function Ja(e){Ne("Widget",Tt(e,Hh),e);const t=_n.findIndex(n=>n.id===e.id);t>=0?_n[t]=e:_n.push(e)}function KA(e){const t=_n.findIndex(n=>n.id===e);t>=0&&_n.splice(t,1)}function Bh(){const e=_n.slice(),t=G(_.WIDGETS,e);return Array.isArray(t)?t.filter(YA):(typeof console<"u"&&console.warn("[openstation] `os.widgets` filter returned a non-array; falling back to seed list."),e)}function _o(e){return Bh().find(t=>t.id===e)}const Hh=[{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 YA(e){return Tt(e,Hh).length===0}let ot=null;function XA(e){if(ot)return;const t=document.createElement("div");t.className="os-widget-picker",t.setAttribute("role","menu"),t.setAttribute("aria-label",k("Add widget"));const n=document.createElement("div");n.className="os-widget-picker__title",n.textContent=k("Add widget"),t.appendChild(n);const o=document.createElement("div");o.className="os-widget-picker__list",t.appendChild(o),Gh(o,e),document.body.appendChild(t),ZA(t,e.anchor);const s=l=>{const a=l.target;a&&(t.contains(a)||e.anchor.contains(a)||zh())};window.setTimeout(()=>{document.addEventListener("pointerdown",s,!0)},0);const i=l=>{l.key==="Escape"&&zh()};document.addEventListener("keydown",i),ot={panel:t,options:e,onOutsidePointerDown:s,onKeyDown:i},o.querySelector("button:not([disabled])")?.focus()}function Eo(){if(!ot)return;const e=ot.panel.querySelector(".os-widget-picker__list");e&&Gh(e,ot.options)}function zh(){ot&&(document.removeEventListener("pointerdown",ot.onOutsidePointerDown,!0),document.removeEventListener("keydown",ot.onKeyDown),ot.panel.remove(),ot=null)}function Gh(e,t){e.innerHTML="";const n=new Set(t.enabledIds()),o=t.registry();if(o.length===0){const s=document.createElement("div");s.className="os-widget-picker__empty",s.textContent=k("No widgets available. Activate a plugin that registers one, or see the docs for the registerWidget API."),e.appendChild(s);return}for(const s of o){const i=document.createElement("button");i.type="button",i.className="os-widget-picker__entry";const r=n.has(s.id);r&&(i.classList.add("os-widget-picker__entry--added"),i.disabled=!0,i.setAttribute("aria-disabled","true")),i.setAttribute("role","menuitem");let l;r?l=le(k("%s (already added)"),s.label):l=le(k("Add %s"),s.label),i.setAttribute("aria-label",l);const a=document.createElement("span");a.className=`os-widget-picker__entry-icon dashicons ${s.icon}`,a.setAttribute("aria-hidden","true"),i.appendChild(a);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=k("Added"),i.appendChild(u)}r||i.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t.onAdd(s.id)}),e.appendChild(i)}}function ZA(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 l=n.right-s,a=n.top-i-r;l<8&&(l=8),a<8&&(a=n.bottom+r),e.style.left=`${Math.round(l)}px`,e.style.top=`${Math.round(a)}px`,e.style.visibility=""}const vi="os-widgets__card--floating",JA="os-widgets__card--movable",QA="os-widgets__card--resizable",jh="os-widgets__card--dragging",Vh="os-widgets__card--resizing",eC=160,qh=80,tC=280,nC=180,_i=20,Kh=5,oC=Kh*Kh,sC='input, textarea, select, button, a, [contenteditable="true"]';function iC(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(JA),i&&o.classList.add(QA),s?o.appendChild(rC(e,n.onRemove,n.onRedock)):o.appendChild(lC(e,n.onRemove));const r=document.createElement("div");r.className="os-widgets__card-body",o.appendChild(r),t.geometry?(Qa(o,hC(t.geometry,t.floatingParent)),o.classList.add(vi)):i&&typeof t.dockedHeight=="number"&&(o.style.height=`${pC(t.dockedHeight,e)}px`);const l=()=>o.classList.contains(vi),a=[];if(i)for(const d of uC()){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),a.push(dC(o,u,d,e,t,n,l))}let c=null;if(s){const d=o.querySelector(".os-widgets__chrome");d&&(c=cC(o,d,e,t,n))}return{card:o,body:r,dispose:()=>{for(const d of a)try{d()}catch{}if(c)try{c()}catch{}o.remove()}}}function rC(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(aC(e,n));const r=Yh(e,t);return o.appendChild(r),o}function aC(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-redock",n.setAttribute("aria-label",le(k("Dock %s back to widget column"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2 6h6M5.5 3.5L8 6l-2.5 2.5M10 2.5v7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n.dataset.noDrag="true",n}function lC(e,t){const n=Yh(e,t);return n.classList.add("os-widgets__card-close--corner"),n}function Yh(e,t){const n=document.createElement("button");return n.type="button",n.className="os-widgets__card-close",n.setAttribute("aria-label",le(k("Remove %s"),e.label)),n.innerHTML='<svg viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M2.5 2.5l7 7M9.5 2.5l-7 7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',n.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t()}),n}function cC(e,t,n,o,s){let i=null,r=0,l=0,a=0,c=0,d=!1;const u=m=>{if(m.button!==0)return;const h=m.target;h&&h.closest(sC)||(m.preventDefault(),i=m.pointerId,r=m.clientX,l=m.clientY,d=!1,a=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0,t.setPointerCapture(i))},f=()=>{if(!e.classList.contains(vi)){const m=o.floatingParent.getBoundingClientRect(),h=e.getBoundingClientRect(),b={x:h.left-m.left,y:h.top-m.top,width:h.width||n.defaultWidth||tC,height:h.height||n.defaultHeight||nC};Qa(e,b),e.classList.add(vi),s.onLiberate(b),a=parseFloat(e.style.left)||0,c=parseFloat(e.style.top)||0}e.classList.add(jh)},p=m=>{if(i===null||m.pointerId!==i)return;const h=m.clientX-r,b=m.clientY-l;if(!d){if(h*h+b*b<oC)return;d=!0,f()}const y=Zh(a+h,c+b,e.offsetWidth,e.offsetHeight,o.floatingParent);e.style.left=`${y.x}px`,e.style.top=`${y.y}px`},g=m=>{if(!(i===null||m.pointerId!==i)){try{t.releasePointerCapture(i)}catch{}i=null,d&&(d=!1,e.classList.remove(jh),s.onGeometryChanged(Xh(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 dC(e,t,n,o,s,i,r){let l=null,a=0,c=0,d=0,u=0,f=0,p=0;const g=b=>{if(b.button!==0||!r()&&!fC(n))return;b.preventDefault(),b.stopPropagation(),l=b.pointerId,a=b.clientX,c=b.clientY;const y=e.getBoundingClientRect(),C=s.floatingParent.getBoundingClientRect();d=y.left-C.left,u=y.top-C.top,f=y.width,p=y.height,t.setPointerCapture(l),e.classList.add(Vh)},m=b=>{if(l===null||b.pointerId!==l)return;const y=b.clientX-a,C=b.clientY-c,w=mC(n,y,C,d,u,f,p,o,s.floatingParent,r());r()&&(e.style.left=`${w.x}px`,e.style.top=`${w.y}px`,e.style.width=`${w.width}px`),e.style.height=`${w.height}px`},h=b=>{if(!(l===null||b.pointerId!==l)){try{t.releasePointerCapture(l)}catch{}l=null,e.classList.remove(Vh),r()?i.onGeometryChanged(Xh(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 uC(){return["n","e","s","w","ne","nw","se","sw"]}function fC(e){return e==="s"}function Qa(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 Xh(e){return{x:parseFloat(e.style.left)||0,y:parseFloat(e.style.top)||0,width:e.offsetWidth,height:e.offsetHeight}}function pC(e,t){return ko(e,t.minHeight??qh,t.maxHeight??1/0)}function hC(e,t){if(!t.clientWidth||!t.clientHeight)return e;const n=Zh(e.x,e.y,e.width,e.height,t);return{...e,x:n.x,y:n.y}}function Zh(e,t,n,o,s){const i=s.clientWidth||s.getBoundingClientRect().width,r=s.clientHeight||s.getBoundingClientRect().height,l=Math.max(0,i-n-_i),a=Math.max(0,r-o-_i);return{x:Math.min(Math.max(_i,e),l),y:Math.min(Math.max(_i,t),a)}}function mC(e,t,n,o,s,i,r,l,a,c){const d=l.minWidth??eC,u=l.minHeight??qh,f=l.maxWidth??1/0,p=l.maxHeight??1/0,g=a.clientWidth||a.getBoundingClientRect().width,m=a.clientHeight||a.getBoundingClientRect().height;let h=o,b=s,y=i,C=r;if((e==="e"||e==="ne"||e==="se")&&(y=ko(i+t,d,Math.min(f,g-o))),e==="w"||e==="nw"||e==="sw"){const w=ko(i-t,d,Math.min(f,o+i));h=o+(i-w),y=w}if((e==="s"||e==="se"||e==="sw")&&(C=ko(r+n,u,Math.min(p,m-s))),e==="n"||e==="ne"||e==="nw"){const w=ko(r-n,u,Math.min(p,s+r));b=s+(r-w),C=w}return c||(y=i,h=o),{x:h,y:b,width:y,height:C}}function ko(e,t,n){return n<t?t:Math.min(Math.max(e,t),n)}const Jh="desktop-mode-widgets",Qh="desktop-mode-widgets-geometry",em="desktop-mode-widgets-docked-heights";function tm(){try{return window.localStorage.getItem(Jh)}catch{return null}}function gC(){const e=tm();if(e===null)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function el(e){try{window.localStorage.setItem(Jh,JSON.stringify(e))}catch{}}function wC(){try{const e=window.localStorage.getItem(Qh);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=bC(s);i&&(n[o]=i)}return n}catch{return{}}}function tl(e){try{window.localStorage.setItem(Qh,JSON.stringify(e))}catch{}}function yC(){try{const e=window.localStorage.getItem(em);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 nm(e){try{window.localStorage.setItem(em,JSON.stringify(e))}catch{}}function bC(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 vC(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 _C=["clock"];class EC{constructor(t,n,o){this.mounted=new Map,this.generation=0,this.root=t,this.pluginUrl=n,this.enabledIds=gC(),this.geometry=wC(),this.dockedHeights=yC(),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()}hydrate(){tm()===null&&(this.enabledIds=_C.filter(t=>!!_o(t)),el(this.enabledIds));for(const t of this.enabledIds)this.mounted.has(t)||this.mountById(t);this.paintEmptyState()}add(t){this.enabledIds.includes(t)||_o(t)&&(this.enabledIds.push(t),el(this.enabledIds),this.mountById(t),this.paintEmptyState(),L(_.WIDGET_ADDED,{id:t}),Eo())}remove(t){const n=this.enabledIds.length;this.enabledIds=this.enabledIds.filter(o=>o!==t),this.enabledIds.length!==n&&(el(this.enabledIds),this.geometry[t]&&(delete this.geometry[t],tl(this.geometry)),this.dockedHeights[t]!==void 0&&(delete this.dockedHeights[t],nm(this.dockedHeights)),this.unmountById(t),this.paintEmptyState(),L(_.WIDGET_REMOVED,{id:t}),Eo())}getEnabledIds(){return[...this.enabledIds]}mountIfEnabled(t){_o(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 _o(t)?(this.enabledIds.includes(t)||this.add(t),!0):!1}disposeAll(){for(const t of Array.from(this.mounted.keys()))this.unmountById(t)}mountById(t){const n=_o(t);if(!n)return;const o=++this.generation,s=n.movable===!0?this.geometry[t]:void 0,i=iC(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,l={id:t,frame:i,generation:o,teardown:null,floating:r};this.mounted.set(t,l),this.placeCard(i.card,r);const a={id:t,pluginUrl:this.pluginUrl,storage:vC(t)};L(_.WIDGET_MOUNTING,{id:t,container:i.body,ctx:a});const c=u=>{const f=this.mounted.get(t);if(!f||f.generation!==o){try{u()}catch{}return}f.teardown=u,L(_.WIDGET_MOUNTED,{id:t,container:i.body,ctx:a})};let d;try{d=n.mount(i.body,a)}catch(u){this.handleMountFailure(t,u);return}if(kC(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){L(_.WIDGET_UNMOUNTING,{id:t});try{n.teardown?.()}catch(o){L(_.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)),L(_.WIDGET_MOUNT_FAILED,{id:t,error:n}),L(_.SHELL_ERROR,{scope:"widget-mount",id:t,error:n}),typeof console<"u"&&console.error(`[openstation] Widget "${t}" failed to mount:`,n)}buildAddTile(){const t=document.createElement("button");t.type="button",t.className="os-widgets__add",t.setAttribute("aria-label",k("Add widget"));const n=document.createElement("span");n.className="os-widgets__add-plus",n.setAttribute("aria-hidden","true"),n.textContent="+";const o=document.createElement("span");return o.className="os-widgets__add-label",o.textContent=k("Add widget"),t.appendChild(n),t.appendChild(o),t.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),XA({anchor:t,registry:()=>Bh(),enabledIds:()=>[...this.enabledIds],onAdd:i=>this.add(i)})}),t}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),Qa(o.frame.card,n),this.persistGeometry(t,n),this.paintEmptyState())}redock(t){const n=this.mounted.get(t);if(!n||!n.floating)return;n.floating=!1,this.geometry[t]&&(delete this.geometry[t],tl(this.geometry));const o=n.frame.card;o.classList.remove("os-widgets__card--floating"),o.style.left="",o.style.top="",o.style.width="";const s=this.dockedHeights[t];o.style.height=s!==void 0?`${s}px`:"",this.listEl.appendChild(o),this.paintEmptyState()}persistGeometry(t,n){this.geometry[t]=n,tl(this.geometry)}persistDockedHeight(t,n){!Number.isFinite(n)||n<=0||(this.dockedHeights[t]=n,nm(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)}}function kC(e){return!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function"}const SC=280,AC=220,CC=520,IC=400;function xC(e,t){const o=e.closest('[id^="wp-window-"]')?.id.slice(10);return o||t}function LC(e,t,n){return o=>{const s=xC(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=DA(s,i);t.push(r);let l;try{l=new URL(e.url,window.location.origin).origin}catch{l=window.location.origin}let a=null;const c=new Promise(f=>{a=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{}Dv(s),a?.()};i.addEventListener("load",d);const u=f=>{if(!i.contentWindow||f.source!==i.contentWindow||f.origin!==l&&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!==""&&Lv(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 TC(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=LC(t.iframeContent,s,t.id));const i=t.onClose,r=t.iframeContent?()=>{for(const a of s)try{a()}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??CC,height:t.height??IC,minWidth:t.minWidth??SC,minHeight:t.minHeight??AC,render:o,onClose:r,onResize:t.onResize,autofocus:t.autofocus,initialState:t.initialState,ownerHandle:t.ownerHandle,multi:t.multi,desktopId:t.desktopId})}}let NC=0;function DC(e,t,n={}){const o=`desktop-mode/on-window/${e}/${++NC}`,s=n.persistent===!0,i=[["opened",_.WINDOW_OPENED],["reopened",_.WINDOW_REOPENED],["focused",_.WINDOW_FOCUSED],["blurred",_.WINDOW_BLURRED],["closing",_.WINDOW_CLOSING],["closed",_.WINDOW_CLOSED],["minimized",_.WINDOW_MINIMIZED],["restored",_.WINDOW_RESTORED],["maximized",_.WINDOW_MAXIMIZED],["unmaximized",_.WINDOW_UNMAXIMIZED],["fullscreenEntered",_.WINDOW_FULLSCREEN_ENTERED],["fullscreenExited",_.WINDOW_FULLSCREEN_EXITED],["resized",_.WINDOW_RESIZED],["bodyResized",_.WINDOW_BODY_RESIZED],["boundsChanged",_.WINDOW_BOUNDS_CHANGED]],r=[];let l=!1;const a=()=>{if(!l){l=!0;for(const c of r)ur(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&&a()}))}return a}function om(){const e=window;return{...e.wpDesktopNativeWindows||{},...e.openStationNativeWindows||{}}}function sm(e,t){const n=t.tabs;if(!Array.isArray(n)||n.length<2)return;const o=e.closest(".os-window");o&&D_(o,n.map(s=>({value:s.value,label:s.label})),n.find(s=>s.isMain)?.value)}function RC(e){const{manager:t,appendSystemTile:n,removeSystemTile:o}=e,s=new Set,i=new Set,r=new Set,l=new Set,a=new Map,c=w=>{const E=zu(w.id);return E?{width:Math.max(E.width,w.minWidth),height:Math.max(E.height,w.minHeight)}:{width:w.width,height:w.height}},d=w=>{if(i.has(w.templateId))return;if(document.getElementById(w.templateId)){i.add(w.templateId);return}if(!w.templateHtml)return;const E=document.createElement("template");E.id=w.templateId,E.innerHTML=w.templateHtml,document.body.appendChild(E),i.add(w.templateId)},u=w=>{const E=w.styleUrl;if(!E||l.has(E))return;const T=E.replace(/\\/g,"\\\\").replace(/"/g,'\\"');if(!document.head.querySelector(`link[rel="stylesheet"][href="${T}"]`)){const P=document.createElement("link");P.rel="stylesheet",P.href=E,w.styleHandle&&(P.dataset.osStyleHandle=w.styleHandle),document.head.appendChild(P)}if(Array.isArray(w.styleInline))for(const P of w.styleInline){if(typeof P!="string"||P==="")continue;const v=document.createElement("style");w.styleHandle&&(v.dataset.osStyleHandle=w.styleHandle),v.textContent=P,document.head.appendChild(v)}l.add(E)},f=async w=>{if(!(!w.scriptUrl||r.has(w.scriptUrl))){try{await Se(w.scriptUrl,{translations:w.scriptTranslations,l10n:w.scriptL10n,before:w.scriptBefore,after:w.scriptAfter})}catch(E){L(_.SHELL_ERROR,{scope:"native-window-script-load",id:w.id,error:E})}r.add(w.scriptUrl)}},p=(w,E)=>{const T=om()[w.id],M=(v,$)=>(v.appendChild(nl(w.templateId)),sm(v,w),T?.(v,$)),P=c(w);t.open({id:w.id,baseId:w.id,native:!0,url:`#${w.id}`,title:w.title,icon:w.icon,width:P.width,height:P.height,minWidth:w.minWidth,minHeight:w.minHeight,render:M,autofocus:w.autofocus,ownerHandle:w.ownerHandle||w.scriptHandle,...E?{params:E}:{}})},g=(w,E)=>{const T=om()[w.id],M=(v,$)=>(v.appendChild(nl(w.templateId)),sm(v,w),T?.(v,$)),P=c(w);t.openNew({id:w.id,baseId:w.id,native:!0,url:`#${w.id}`,title:w.title,icon:w.icon,width:P.width,height:P.height,minWidth:w.minWidth,minHeight:w.minHeight,initialState:"normal",render:M,autofocus:w.autofocus,ownerHandle:w.ownerHandle||w.scriptHandle,...E?{params:E}:{}})},m=async w=>{if(!s.has(w.id)){if(w.placement==="none"){d(w),u(w),await f(w),s.add(w.id);return}d(w),u(w),await f(w),n({id:w.id,title:w.title,icon:w.icon,order:w.dockOrder,placeable:w.placeable===!0,isOpen:()=>!!t.getById(w.id),onOpen:()=>p(w)}),L(_.DOCK_ITEM_APPENDED,{id:w.id}),s.add(w.id)}},h=w=>{s.has(w)&&(o(w),s.delete(w),a.delete(w))},b=async w=>{const E=new Set;for(const T of w)E.add(T.id),a.set(T.id,T);for(const T of Array.from(s))E.has(T)||h(T);for(const T of w)s.has(T.id)||await m(T)},y=(w,E={})=>{const T=a.get(w);return T?(ke.publish("os/open-requested",{windowId:w,source:E.source??"api"}),p(T,E.params),!0):!1},C=(w,E={})=>{const T=a.get(w);return T?(ke.publish("os/open-requested",{windowId:w,source:E.source??"api"}),g(T,E.params),!0):!1};return Y(_.WINDOW_RESIZE_END,"desktop-mode-native-window-geometry",w=>{const E=w,T=E?.windowId,M=E?.width,P=E?.height;if(!T||typeof M!="number"||typeof P!="number")return;const v=t.getById(T);if(!v||v.state!=="normal")return;const $=v.config.baseId||v.id;Gu($,{width:M,height:P}),v.element&&ju($,{x:v.element.offsetLeft,y:v.element.offsetTop})}),Y(_.WINDOW_DRAG_END,"desktop-mode-native-window-geometry",w=>{const E=w?.windowId;if(!E)return;const T=t.getById(E);if(!T||T.state!=="normal"||!T.element)return;const M=T.config.baseId||T.id;Gu(M,{width:T.element.offsetWidth,height:T.element.offsetHeight}),ju(M,{x:T.element.offsetLeft,y:T.element.offsetTop})}),Y(_.WINDOW_MAXIMIZED,"desktop-mode-native-window-geometry",w=>{const E=w?.windowId;if(!E)return;const T=t.getById(E);if(!T)return;const M=T.config.baseId||T.id,P=a.get(M),v=P?{width:P.width,height:P.height}:{width:T.config.width,height:T.config.height};Vu(M,"maximized",v)}),Y(_.WINDOW_UNMAXIMIZED,"desktop-mode-native-window-geometry",w=>{const E=w?.windowId;if(!E)return;const T=t.getById(E);if(!T)return;const M=T.config.baseId||T.id;Vu(M,null)}),{sync:b,openById:y,openNewById:C}}function nl(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 im(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=ae(e,o);return s.find(r=>ae(r.url,o)===i||(r.submenu??[]).some(l=>ae(l.url,o)===i))??null}const rm="data:image/svg+xml;base64,",Ei=new Map;function OC(e){const t=Ei.get(e);if(t!==void 0)return t;let n=!1;try{n=atob(e.slice(rm.length)).includes("currentColor")}catch{}return Ei.size>=256&&Ei.clear(),Ei.set(e,n),n}function So(e,t){const n=t.className??"",o=t.title??"";let s=null;if(t.slot){const a=$s(t.slot);a!==null&&(e=a),s=Tr(t.slot)}if(typeof e=="string"&&e.startsWith("dashicons-")){const a=document.createElement("span");return a.className=`dashicons ${e} ${n}`.trim(),a.setAttribute("aria-hidden","true"),s!==null&&(a.style.color=s),a}if(s!==null&&typeof e=="string"){const a=document.createElement("span");if(a.className=n,a.setAttribute("aria-hidden","true"),a.style.display="inline-block",so(a,e,s))return a}if(typeof e=="string"&&e.startsWith("data:image/svg+xml;base64,")){const a=e.slice(rm.length);if(/^[A-Za-z0-9+/=]+$/.test(a)){const c=document.createElement("span");return c.className=n,c.setAttribute("aria-hidden","true"),c.style.display="inline-block",OC(e)&&so(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 a=e.indexOf(","),c=a>=0?e.slice(a+1):"";if(/^[A-Za-z0-9+/=]+$/.test(c))return am(e,n)}if(typeof e=="string"&&(e.startsWith("http://")||e.startsWith("https://")))return am(e,n);const i=document.createElement("span");i.className=`${n} os-icon-letter`.trim(),i.setAttribute("aria-hidden","true");const r=MC(o);i.textContent=r;const l=dn(o);return i.style.backgroundColor=`hsl( ${l}, 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 am(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 MC(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 lm="os-icon__badge",Ao=new Map,Co=new Map;function PC(e){return Math.max(0,Math.floor(Number(e)||0))}function cm(e,t){if(!e)return;const n=pm(e);if(!n)return;const o=PC(t),s=Ao.get(e)??0;o!==s&&(o===0?Ao.delete(e):Ao.set(e,o),hm(n,o),ke.publish("os/badge-changed",{itemId:e,count:o,rail:"icon"}),L(_.ICON_BADGE_CHANGED,{iconId:e,count:o,previousCount:s}))}function WC(e){cm(e,0)}function $C(e){return Ao.get(e)??0}function UC(e,t){if(e){if(!t){Co.delete(e);return}Co.get(e)!==t&&(Co.set(e,t),BC(e,t),ke.publish("os/art-changed",{itemId:e,icon:t,rail:"icon"}))}}function dm(e){return Co.get(e)??""}function FC(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function BC(e,t){const o=pm(e)?.querySelector(".os-icon__image");if(o){const s=So(t,{className:"os-icon__image",title:""});o.replaceWith(s)}document.querySelectorAll(`os-tile[data-file-ref="${FC(e)}"]`).forEach(s=>s.setAttribute("icon",t))}const HC={setBadge:cm,clearBadge:WC,getBadge:$C,setArt:UC,getArt:dm};function zC(e){return!e||e.length===0?"":`${Lr()??""}::`+e.map(n=>`${n.id}|${n.title}|${n.icon}|${n.window??""}|${n.url??""}|${n.position??0}|${n.pinned?1:0}`).join(";")}let um="";function fm(e,t,n){const o=zC(t);if(o===um&&e.querySelector(":scope > .os-icons"))return;um=o;const s=e.querySelector(":scope > .os-icons");if(s&&s.remove(),!t||t.length===0)return;const i=document.createElement("div");i.className="os-icons",i.setAttribute("role","list"),i.setAttribute("aria-label",k("Desktop icons"));const r=[...t].sort((a,c)=>{const d=a.pinned?0:1,u=c.pinned?0:1;return d-u}),l=new Map;for(const a of r){const c=jC(a,n),d=Ao.get(a.id)??0;d>0&&hm(c,d);const u=Co.get(a.id);if(u){const f=c.querySelector(".os-icon__image");f&&f.replaceWith(So(u,{className:"os-icon__image",title:""}))}i.appendChild(c),l.set(a.id,c)}e.appendChild(i),L(_.DESKTOP_ICONS_RENDERED,{ids:(t??[]).map(a=>a.id),container:i,tiles:l})}function pm(e){if(!e)return null;const t=document.querySelector(".os-icons");return t?t.querySelector(`[data-icon-id="${GC(e)}"]`):null}function hm(e,t){const n=e.querySelector(`:scope > .${lm}`);if(t<=0){n?.remove();return}const o=t>99?"99+":String(t),s=le(en("%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=lm,i.textContent=o,i.setAttribute("aria-label",s),e.appendChild(i)}function GC(e){const t=window.CSS;return t?.escape?t.escape(e):e}function jC(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=So(e.icon,{title:e.title,className:"os-icon__image",slot:Us(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(),L(_.DESKTOP_ICON_CLICKED,{id:e.id,target:e.window?"window":"url"}),VC(e,t)}),n.addEventListener("contextmenu",i=>{e.pinned||(i.preventDefault(),i.stopPropagation(),Kf({x:i.clientX,y:i.clientY,id:e.id,title:e.title,surface:"desktop"}))}),n}function VC(e,t){if(e.window)return t.openWindow(e.window),void 0;if(e.url){if(fn(e.url))return;try{const n=new URL(e.url,window.location.origin),o=t.deriveWindowId(n.toString()),s=im(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{}}}const mm="os-side-dock";function qC(e,t,n,o,s="bottom"){let i=t,r=s,l=n,a=o??[],c=null,d=null,u=null,f=null,p=null;const g=new Map,m=new Set,h=S=>c,b=()=>{const S=document.getElementById(mm);if(S)return S;const O=document.createElement("nav");return O.id=mm,O.className="os-dock",O.setAttribute("role","toolbar"),O.setAttribute("aria-label","Core admin navigation"),e.shellBody.insertBefore(O,e.shellBody.firstChild),O},y=()=>{p&&p.parentNode&&p.parentNode.removeChild(p),p=null},C=()=>e.getSettings?.()??{itemVisibility:{},dockOrder:[]},w=S=>{const O=C().itemVisibility;let U=O[S];for(const N of a)if(N.window===S&&O[N.id]){U=O[N.id];break}return!U||U==="dock"||U==="both"?!0:U!=="hidden"&&E().has(S)},E=()=>{const S=e.windowManager.getActiveDesktopId(),O=new Set;for(const U of e.windowManager.getAll())(U.config.desktopId||S)===S&&O.add(U.config.baseId||U.id);return O},T=()=>{for(const[S,O]of g){const U=w(S),N=m.has(S);U&&!N?(h(O.affinity)?.appendSystemItem(O.item),m.add(S)):!U&&N&&(h(O.affinity)?.removeSystemItem(S),m.delete(S))}},M=()=>{const S=E(),O=C().itemVisibility,U=a.filter(H=>!!H.window&&S.has(H.window)&&(O[H.id]??"desktop")==="desktop").map(H=>H.id),N=Array.from(g.keys()).filter(H=>S.has(H)&&O[H]==="desktop");return[...U,...N].sort().join(",")};let P=M();for(const S of["os-window-opened","os-window-closed"])document.addEventListener(S,()=>{const O=M();O!==P&&(P=O,F.refresh())});const v=()=>{const S=new Set;for(const O of g.values())S.add(O.item.id);return a0(l,a,C(),S,E())},$=()=>{const S=v(),O=[],U=[];for(const N of S)N.isCore?O.push(N):U.push(N);return{core:O,plugin:U}},D=()=>{const{core:S,plugin:O}=$();return[...S,...O]},I=()=>{const S=C();e.renderIcons(l0(a,l,S.itemVisibility))},W=()=>{if(c){try{c.destroy()}catch(S){L(_.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:S})}c=null,u=null}if(d){try{d.destroy()}catch(S){L(_.SHELL_ERROR,{scope:"dock-rail-renderer/destroy",error:S})}d=null,f=null}},z=S=>{const O=wr();if(!O)return L(_.SHELL_ERROR,{scope:"dock-rail-renderer",message:"No dock rail renderer is registered."}),null;try{return O.mount(S)}catch(U){if(L(_.SHELL_ERROR,{scope:"dock-rail-renderer/mount",rendererId:O.id,error:U}),O===ca)return null;try{return ca.mount(S)}catch{return null}}},q=(S,O,U)=>({container:S,items:O,fullMenu:l.slice(),fullSystemTiles:Array.from(g.values()).filter(N=>w(N.item.id)).map(N=>N.item),orientation:U,windowManager:e.windowManager,adminUrl:e.adminUrl,openItem:N=>{const H=ae(N.url,e.adminUrl);e.windowManager.open({id:H,baseId:H,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})},openSubmenuPick:(N,H)=>{e.windowManager.open({id:ae(H.url,e.adminUrl),baseId:ae(N.url,e.adminUrl),url:H.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})},openSystemItem:N=>N.onOpen()}),K=()=>i==="classic"?"bottom":r,x=()=>{W();const{core:S,plugin:O}=$();i==="classic"?(p=b(),d=z(q(p,S,"left")),f=da(d),c=z(q(e.bottomDockEl,O,"bottom")),u=da(c)):(y(),c=z(q(e.bottomDockEl,D(),K())),u=da(c)),m.clear();for(const[U,N]of g)w(U)&&(h(N.affinity)?.appendSystemItem(N.item),m.add(U))},F={getLayout:()=>i,getPrimary:()=>u,getSide:()=>f,setLayout:S=>{S!==i&&(i=S,e.shellRoot.setAttribute("data-os-layout",S),x(),I(),document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:S,placement:K(),primary:u,side:f}})))},getDockPlacement:()=>r,setDockPlacement:S=>{if(S===r)return;const O=K();r=S,K()!==O&&(x(),I(),document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,placement:K(),primary:u,side:f}})))},applyDockItems:S=>{l=S;const{core:O,plugin:U}=$();i==="classic"?(d?.replaceItems(O),c?.replaceItems(U)):c?.replaceItems([...O,...U]),I()},applyDesktopIcons:S=>{a=S??[],T(),I()},appendSystemTile:(S,O="plugin")=>{g.set(S.id,{item:S,affinity:O}),w(S.id)&&(h()?.appendSystemItem(S),m.add(S.id))},removeSystemTile:S=>{const O=g.get(S);O&&(g.delete(S),m.delete(S),h(O.affinity)?.removeSystemItem(S))},listSystemTiles:()=>Array.from(g.values()).map(S=>({id:S.item.id,title:S.item.title,icon:S.item.icon,affinity:S.affinity,placeable:S.item.placeable===!0})),getSystemTile:S=>g.get(S)?.item??null,getMenuItems:()=>l.slice(),refresh:()=>{const{core:S,plugin:O}=$();i==="classic"?(d?.replaceItems(S),c?.replaceItems(O)):c?.replaceItems([...S,...O]),T(),I()},destroy:()=>{W(),y()}};e.shellRoot.setAttribute("data-os-layout",i),x(),I();let R=wr()?.id??null;return Mb(()=>{const S=wr()?.id??null;S!==R&&(R=S,x(),I(),document.dispatchEvent(new CustomEvent("os-layout-changed",{detail:{layout:i,primary:u,side:f}})))}),F}function KC(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 YC{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=KC(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 gm=e=>!e||typeof e!="object"?!1:e.name==="AbortError",XC=e=>{if(!e)return[];const t=Hk();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}}):[]},ZC=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 JC(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 QC(e){return e===void 0?{value:null}:typeof e=="object"&&e!==null?e:{value:e}}function eI(e){const t=async(s,i)=>{const r=e.config(),l=r.aiSearchUrl??"",a=r.restNonce??"";if(!l||!a)throw new Error("[openstation] wp.os.ai.ask: aiSearchUrl / restNonce missing from config. AI Copilot may not be enabled.");try{return await Be(l,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":a},body:JSON.stringify(s),signal:i},{source:"desktop-mode/ai-ask"})}catch(c){throw gm(c)?c:new Error(`[openstation] wp.os.ai.ask: network error — ${String(c?.message??c)}`)}},n=async(s,i)=>{const r=s.tool?.slug??"",l=s.tool?.args??"",a=zk(r);if(!a)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:l,result:{error:"command_not_found"}},request_id:s.request_id}};const c=i.commandContext??e.fallbackContext();let d;try{d=await Promise.resolve(a.run(l,c))}catch(u){d={error:String(u?.message??u)}}return{ok:!0,slug:r,args:l,result:d}},o=async(s,i,r,l,a,c)=>{const d={query:s,follow_up:{tool:{slug:i,args:r},result:QC(l)}};a&&(d.system_prompt_text=a.text,d.system_prompt_mode=a.mode);let u;try{u=await t(d,c)}catch(g){if(gm(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 l=(i??"").trim();if(l===""){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 a=XC(r.tools),c=ZC(r.systemPrompt),d={query:l};r.resumeTool&&(d.resume_tool=r.resumeTool),typeof r.startOffset=="number"&&(d.start_offset=r.startOffset),a.length>0&&(d.command_tools=a),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=JC(f.message,h);if(r.followUp===!0){const y=await o(l,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 wm="[os-bin badge]";function st(...e){try{window.localStorage?.getItem("openStationBinDebug")&&console.info(wm,...e)}catch{}}function ki(...e){console.warn(wm,...e)}const Io="desktop-mode-recycle-bin",tI="openstation_recycle_bin_seen_ts";function nI(){return window.wp?.os}const ue=re("desktop-mode/recycle-bin/icon-state",()=>({current:0,emptyArt:"",fullArt:"",seenTs:0,started:!1,countUrl:""}));function xo(e){const t=Math.max(0,Math.floor(e)),n=ue.state.current;ue.state.current=t,st("setRecycleBinCount",{prev:n,next:t}),ol(t)}function ym(e){xo(ue.state.current+e)}function oI(){return ue.state.current}function ol(e){const t=e>0?ue.state.fullArt:ue.state.emptyArt;if(st("paintIconState",{count:e,full:e>0,hasArt:!!t}),!t)return;const n=nI();n?.dock?.setArt?.(Io,t),n?.taskbar?.setArt?.(Io,t),n?.icons?.setArt?.(Io,t)}function sI(e,t=""){const n=Number(e)||0,o=window.openStationConfig,s=o?.recycleBinCount,i=o?.recycleBinCountUrl;ue.state.emptyArt=String(o?.recycleBinIconEmpty??""),ue.state.fullArt=String(o?.recycleBinIconFull??"");const r=o?.openStationBinDebug;st("startRecycleBinIconState entry",{initial:n,countUrl:t,alreadyStarted:ue.state.started,cfgCount:s,cfgUrl:i,cfgDebug:r,readyState:document.readyState});const l=Number(s);if((typeof s=="number"||typeof s=="string")&&Number.isFinite(l)||ki("openStationConfig.recycleBinCount is missing — PHP filter `openstation_shell_config` did not deliver. Check your PHP error log for `[os-bin debug]` lines.",{cfg:o}),ue.state.started){xo(n);return}ue.state.started=!0,ue.state.countUrl=t,ue.state.seenTs=Date.now(),xo(n),iI(),rI(),aI(),lI(),cI()}function iI(){Y(_.DOCK_ITEM_APPENDED,"desktop-mode/recycle-bin/icon-state",e=>{e?.id===Io&&ol(ue.state.current)})}function rI(){Y(_.DESKTOP_ICONS_RENDERED,"desktop-mode/recycle-bin/icon-state",e=>{e?.ids?.includes(Io)&&ol(ue.state.current)})}function aI(){const e=s=>{const i=s;if(!i)return;const r=Array.isArray(i.ids)?i.ids.length:0;switch(i.action){case"trashed":ym(+r);break;case"untrashed":case"deleted":ym(-r);break}},n=window.openStationConfig?.recycleBinPostTypes??["post","page","attachment"],o=["comment","placement","shortcut","folder"];for(const s of[...n,...o])wn(`os.${s}.changed`,e)}function lI(){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<=ue.state.seenTs){st("postMessage skipped (ts <= seenTs)",{ts:o,seenTs:ue.state.seenTs});return}st("postMessage triggers refetch",{ts:o,prevSeenTs:ue.state.seenTs}),ue.state.seenTs=o,dI()})}function cI(){const e=window.jQuery;if(!e){ki("wireHeartbeatProbe: window.jQuery not available — heartbeat path disabled");return}st("wireHeartbeatProbe: jQuery + heartbeat hooks attached"),e(document).on("heartbeat-send",(...t)=>{const n=t[1];n&&(n[tI]=ue.state.seenTs)}),e(document).on("heartbeat-tick",(...t)=>{const o=t[1]?.openstation_recycle_bin;st("heartbeat-tick",{hasBlock:!!o,block:o}),o&&(typeof o.ts=="number"&&o.ts>ue.state.seenTs&&(ue.state.seenTs=o.ts),typeof o.count=="number"&&xo(o.count))})}async function dI(){if(!ue.state.countUrl){st("refetchCount: no countUrl, skip");return}st("refetchCount: hitting",ue.state.countUrl);try{const e=await fetch(ue.state.countUrl,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!e.ok){ki("refetchCount: non-OK",e.status,e.statusText);return}const t=await e.json();st("refetchCount: response",t),typeof t.count=="number"&&xo(t.count)}catch(e){ki("refetchCount: fetch failed",e)}}const uI="desktop-mode-os-settings",fI="desktop-mode-recycle-bin";function pI(e){const t=gI();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===uI?hI():i===fI?mI(s,e.getRecycleBinCount):n})}function hI(e){const t=document.createElement("span");t.className="os-dock-peek__card-body os-dock-peek__card-body--os-settings",t.setAttribute("aria-hidden","true");const n=document.createElement("span");n.className="os-dock-peek__os-hero dashicons dashicons-admin-generic",t.appendChild(n);const o=document.createElement("span");o.className="os-dock-peek__os-subtitle",o.textContent=k("System Preferences"),t.appendChild(o);const s=document.createElement("span");s.className="os-dock-peek__os-tabs";for(const i of["dashicons-art","dashicons-admin-customizer","dashicons-editor-help"]){const r=document.createElement("span");r.className=`os-dock-peek__os-tab dashicons ${i}`,s.appendChild(r)}return t.appendChild(s),t}function mI(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 a=0;a<3;a++){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 l=document.createElement("span");return l.className="os-dock-peek__bin-label",o===0?l.textContent=k("Trash — empty"):o===1?l.textContent=k("1 item"):o>99?l.textContent="99+ items":l.textContent=`${o} items`,n.appendChild(l),n}function gI(){return window.wp?.hooks??null}const Lo="desktop-mode-bug-report",wI="WordPress",yI="openstation",bm=6e3;function bI(e){e.classList.add("desktop-mode-bug-report"),e.replaceChildren();const t=document.createElement("form");t.className="os-bug-report__form",t.setAttribute("novalidate","");const n=document.createElement("p");n.className="os-bug-report__intro",n.textContent=k("Found a bug or have a feature idea? Fill this in and we will open a pre-filled GitHub issue for you to review and submit."),t.appendChild(n),t.appendChild(vI()),t.appendChild(_I("title",k("Title"),{placeholder:k("A short summary"),required:!0})),t.appendChild(vm("description",k("What happened? What did you expect?"),{placeholder:k("Describe the issue or the feature you have in mind."),rows:5,required:!0})),t.appendChild(vm("steps",k("Steps to reproduce (bug only)"),{placeholder:k("One step per line"),rows:4}));const o=EI();t.appendChild(o);const s=document.createElement("div");s.className="os-bug-report__actions";const i=document.createElement("button");i.type="submit",i.className="os-bug-report__submit",i.textContent=k("Open issue on GitHub"),s.appendChild(i);const r=document.createElement("span");r.className="os-bug-report__hint",r.textContent=k("You will review and submit on GitHub."),s.appendChild(r),t.appendChild(s),t.addEventListener("submit",l=>{l.preventDefault();const a=SI(t);if(!a.title.trim()||!a.description.trim()){kI(t,k("Title and description are both required."));return}const c=AI(a);window.open(c,"_blank","noopener")}),e.appendChild(t)}function vI(){const e=document.createElement("div");e.className="os-bug-report__field os-bug-report__field--type";const t=document.createElement("span");t.className="os-bug-report__label",t.textContent=k("Type"),e.appendChild(t);const n=document.createElement("div");n.className="os-bug-report__radio-group",n.setAttribute("role","radiogroup");const o=[{value:"bug",label:k("Bug"),checked:!0},{value:"feature",label:k("Feature request")},{value:"question",label:k("Question")}];for(const s of o){const i=document.createElement("label");i.className="os-bug-report__radio";const r=document.createElement("input");r.type="radio",r.name="type",r.value=s.value,s.checked&&(r.checked=!0),i.appendChild(r);const l=document.createElement("span");l.textContent=s.label,i.appendChild(l),n.appendChild(i)}return e.appendChild(n),e}function _I(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 vm(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 EI(){const e=document.createElement("details");e.className="os-bug-report__metadata";const t=document.createElement("summary");t.textContent=k("Environment included with the report"),e.appendChild(t);const n=document.createElement("pre");return n.className="os-bug-report__metadata-body",n.textContent=Em(_m()),e.appendChild(n),e}function kI(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 SI(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 AI(e){const t=CI(e.type),n=II(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/${wI}/${yI}/issues/new?${o.toString()}`}function CI(e){switch(e){case"bug":return["bug"];case"feature":return["enhancement"];case"question":return["question"];default:return[]}}function II(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(Em(_m())),t.push("```"),t.push(""),t.push("</details>");let n=t.join(` |
| 97 |
`);return n.length>bm&&(n=n.slice(0,bm)+` |
| 98 |
|
| 99 |
…(truncated to fit GitHub URL length limit)`),n}function _m(){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 Em(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(` |
| 100 |
`)}let Si=null,km=!1,Sm=!1,Am=!1,Ut="pending";function xI(){if(Sm)return;Sm=!0;const e=!!navigator.serviceWorker.controller;navigator.serviceWorker.addEventListener("controllerchange",()=>{e&&(Am||TI()||(NI(),Am=!0,setTimeout(()=>window.location.reload(),0)))})}const Cm="os-sw-reload-ts",LI=3e4;function TI(){try{const e=sessionStorage.getItem(Cm),t=e?Number.parseInt(e,10):0;return!Number.isFinite(t)||t<=0?!1:Date.now()-t<LI}catch{return!1}}function NI(){try{sessionStorage.setItem(Cm,String(Date.now()))}catch{}}async function DI(e,t={}){if(typeof navigator>"u"||!("serviceWorker"in navigator)||!e?.swUrl||!window.isSecureContext)return Ut="unsupported",null;if(Si||km)return Si;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 Ut="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 Si=await navigator.serviceWorker.register(e.swUrl,{scope:"/",updateViaCache:"none"}),Ut="registered",xI(),Si}catch(n){return km=!0,Ut="failed",typeof console<"u"&&console.warn("[openstation] SW registration failed:",n),null}}function RI(){return Ut}const OI="os-pwa-install";function Im(){return typeof window>"u"?!1:window.matchMedia?.("(display-mode: standalone)").matches?!0:window.navigator.standalone===!0}async function xm(){if(Im())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 kt=null;function MI(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(),kt=s}function o(){kt=null,t({message:le(k("Installed %s as an app."),e)})}}function PI(e,t){return{id:OI,title:k("Install web app"),icon:"dashicons-download",onOpen:()=>{WI(e,t)}}}async function WI(e,t){if(kt){const n=kt;kt=null;try{await n.prompt(),(await n.userChoice).outcome==="dismissed"&&t({message:k("Install cancelled.")})}catch(o){typeof console<"u"&&console.warn("[openstation] install prompt failed:",o)}return}if(await xm()){t({message:le(k("%s is already installed. Open it from your apps menu or home screen."),e)});return}if(RI()==="foreign-sw"){t({message:k("Install isn't available — another plugin's service worker is active on this site. A site admin can opt in by setting the openstation_pwa_force_replace_sw filter to true.")});return}t({message:k("Install isn't available right now. Keep using the page; if it still doesn't appear, the app may already be installed in this browser.")})}async function $I(){if(!kt)return"unavailable";const e=kt;kt=null;try{return await e.prompt(),(await e.userChoice).outcome}catch{return"unavailable"}}function UI(){Promise.resolve().then(()=>Rk).then(e=>{e.updatePwaState({installHintDismissed:!1})})}function FI(e,t){e.pwa&&(bp(e.pwa),MI(e.pwa.appName||"WordPress",t),DI(e.pwa,{forceReplace:!!e.pwa.forceReplaceSw}))}const En={START:"os-cross-frame-drag-start",END:"os-cross-frame-drag-end"};function BI(e){return!!e&&typeof e=="object"&&e.type==="os-drag-start"&&!!e.payload&&typeof e.payload=="object"}function HI(e){return!!e&&typeof e=="object"&&e.type==="os-drag-end"}function zI(e){return!!e&&typeof e=="object"&&e.type==="os-drag-payload-request"}function GI(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 jI{constructor(){this._payload=null,this._onMessage=t=>{if(t.origin!==this._origin)return;const n=t.data;if(BI(n)){this._startDrag(n.payload);return}if(HI(n)){this._endDrag();return}if(zI(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=GI(t);this._payload=n,document.dispatchEvent(new CustomEvent(En.START,{detail:{payload:n}}))}_endDrag(){if(this._payload===null)return;const t=this._payload;this._payload=null,document.dispatchEvent(new CustomEvent(En.END,{detail:{payload:t}}))}}class VI{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 qI="os-drag-ghost",Lm="os-drag-ghost--accept",Tm="os-drag-ghost--reject",KI="os-drag-hint",Nm="os-drag-hint--accept",Dm="os-drag-hint--reject",Rm="os-drag-hint--neutral",YI=16,XI=18;function ZI(e,t,n){const o=ox(e),s=e.ghost?.offsetX??sx(e.source),i=e.ghost?.offsetY??ix(e.source);o.classList.add(qI),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=QI(e),l=r?JI():null;l&&document.body.appendChild(l);const a={get element(){return o},moveTo(c,d){o.style.transform=`translate3d(${c-s}px, ${d-i}px, 0)`,l&&(l.style.transform=`translate3d(${c+YI}px, ${d+XI}px, 0)`)},setMode(c,d){o.classList.remove(Lm,Tm),c==="accept"?o.classList.add(Lm):c==="reject"&&o.classList.add(Tm),l&&r&&(l.classList.remove(Nm,Dm,Rm),c==="accept"?(l.classList.add(Nm),l.textContent=d?.acceptLabel??r.accept):c==="reject"?(l.classList.add(Dm),l.textContent=r.reject):(l.classList.add(Rm),l.textContent=r.neutral),l.hidden=!l.textContent)},withHidden(c){const d=o.style.visibility,u=l?.style.visibility??"";o.style.visibility="hidden",l&&(l.style.visibility="hidden");try{return c()}finally{o.style.visibility=d,l&&(l.style.visibility=u)}},dispose(){o.isConnected&&o.remove(),l?.isConnected&&l.remove()}};return a.moveTo(t,n),a.setMode("neutral"),a}function JI(){const e=document.createElement("div");return e.className=KI,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 QI(e){const t=e.ghost?.hint;return t?.hidden?null:{accept:t?.accept??ex(e),reject:t?.reject??tx(),neutral:t?.neutral??nx(e)}}function ex(e){return e.type==="shortcut"?k("Drop here to create shortcut","desktop-mode"):e.type==="desktop-file"?k("Drop here to move","desktop-mode"):k("Drop here","desktop-mode")}function tx(e){return k("Can’t drop here","desktop-mode")}function nx(e){return e.type==="shortcut"?k("Drop on the desktop or a folder","desktop-mode"):e.type==="desktop-file"?k("Drop in a folder","desktop-mode"):""}function ox(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 sx(e){return e.offsetWidth/2}function ix(e){return e.offsetHeight/2}let Om=!1;function rx(e){Om||(Om=!0,document.addEventListener("keydown",t=>{t.key==="Escape"&&e("escape")}),window.addEventListener("blur",()=>{e("blur")}),document.addEventListener("visibilitychange",()=>{document.hidden&&e("visibility")}))}const Mm=4,we={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"},Ai="os-file-tile--dragging",Pm="os-file-tile--drop-target",Wm="data-os-trash-drop-active",$m="data-files-drop-active",Um="data-os-dragging",Fm="data-os-drag-type",sl="data-os-drag-mode";class ax{constructor(){this._registry=new VI,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)<Mm&&Math.abs(s)<Mm)return;this._lift(n,t)}n._ghost&&(n._ghost.moveTo(t.clientX,t.clientY),this._updateHover(n,t.clientX,t.clientY),ct(we.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(),rx(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:()=>Bm(),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(Ai),t._ghost=ZI(t.payload,n.clientX,n.clientY),typeof document<"u"&&document.body&&(document.body.setAttribute(Um,""),document.body.setAttribute(Fm,String(t.payload.type)),document.body.setAttribute(sl,"neutral")),ct(we.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 l=!1;try{l=r.accept(t.payload)}catch(a){console.error("[openstation] drop target accept() threw:",r.id,a)}return{target:r,accepted:l}};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&&il(i,t),t._currentTarget=s.target,t._currentAccepted=s.accepted;let r;s.target?s.accepted?(lx(s.target,t),t._ghost?.setMode("accept",{acceptLabel:s.target.acceptLabel}),r="accept"):(t._ghost?.setMode("reject"),ct(we.REJECTED,{payload:t.payload,targetId:s.target.id}),r="reject"):(t._ghost?.setMode("reject"),r="reject"),typeof document<"u"&&document.body&&document.body.setAttribute(sl,r)}_commit(t,n,o,s){t._finished=!0,this._lastLiftedEndAt=Date.now(),il(n,t),this._cleanupDom(t);const i=this._active;this._active=null;try{n.onDrop(t,{clientX:o,clientY:s})}catch(r){console.error("[openstation] drop target onDrop threw:",n.id,r)}try{t._callbacks.onCommit?.(n)}catch(r){console.error("[openstation] drag onCommit threw:",r)}ct(we.COMMIT,{payload:t.payload,targetId:n.id}),ct(we.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&&il(t._currentTarget,t),this._cleanupDom(t),this._active=null;try{t._callbacks.onCancel?.(n)}catch(o){console.error("[openstation] drag onCancel threw:",o)}ct(we.CANCEL,{payload:t.payload,reason:n}),ct(we.END,{payload:t.payload,reason:n})}}_cleanupDom(t){try{t.payload.source.classList.remove(Ai)}catch{}t._ghost?.dispose(),t._ghost=null,t._currentTarget=null,t._currentAccepted=!1,typeof document<"u"&&document.body&&(document.body.removeAttribute(Um),document.body.removeAttribute(Fm),document.body.removeAttribute(sl)),cx()}}function ct(e,t){typeof document>"u"||document.dispatchEvent(new CustomEvent(e,{detail:t}))}function lx(e,t){try{e.onEnter?.(t)}catch(n){console.error("[openstation] drop target onEnter threw:",e.id,n)}ct(we.ENTER,{payload:t.payload,targetId:e.id})}function il(e,t){try{e.onLeave?.(t)}catch(n){console.error("[openstation] drop target onLeave threw:",e.id,n)}ct(we.LEAVE,{payload:t.payload,targetId:e.id})}function Bm(){if(typeof document>"u")return[];const e=[];for(const t of[`.${Ai}`,`.${Pm}`,`[${Wm}]`,`[${$m}]`])document.querySelectorAll(t).forEach(n=>e.push(n));return e}function cx(){for(const e of Bm())e.classList.remove(Ai,Pm),e.removeAttribute(Wm),e.removeAttribute($m)}const dx=".os-window",Hm="wp-window-";function zm(e,t){const n=document.elementFromPoint(e,t);if(!n)return null;const o=n.closest(dx);return o instanceof HTMLElement?o:null}function ux(e){if(!e.id.startsWith(Hm))return null;const t=e.id.slice(Hm.length);return t.length>0?t:null}const fx="desktop-mode-iframe-drop-",Ci="iframe.os-window__iframe",rl="data-os-iframe-drop-active";let al=!1,Gm=null;const je=new Map,Ft=new Map;let dt=null,Bt=null;function px(){document.querySelectorAll(Ci).forEach(t=>{je.has(t)||(je.set(t,t.style.pointerEvents),t.style.pointerEvents="none")})}function hx(){je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear()}function jm(e,t){const n=zm(e,t);if(!n)return null;const o=n.querySelector(Ci);return o instanceof HTMLIFrameElement?o:null}const Vm=e=>{if(!dt)return;e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy");const t=jm(e.clientX,e.clientY);t!==Bt&&(Bt&&Ht(Bt,{type:"os-drag-leave"}),Bt=t,t&&Ht(t,{type:"os-drag-over",payload:dt}))},qm=e=>{if(!dt)return;e.preventDefault(),e.stopPropagation(),typeof e.stopImmediatePropagation=="function"&&e.stopImmediatePropagation();const t=jm(e.clientX,e.clientY),n=dt;if(ll(),!t)return;const o=t.getBoundingClientRect();Ht(t,{type:"os-drop",payload:n,position:{x:e.clientX-o.left,y:e.clientY-o.top}})},Km=()=>{ll()};function mx(e){if(dt){dt=e;return}dt=e,px(),document.addEventListener("dragover",Vm,!0),document.addEventListener("drop",qm,!0),document.addEventListener("dragend",Km,!0)}function ll(){dt&&(dt=null,Bt&&(Ht(Bt,{type:"os-drag-leave"}),Bt=null),document.removeEventListener("dragover",Vm,!0),document.removeEventListener("drop",qm,!0),document.removeEventListener("dragend",Km,!0),hx())}function Ii(e){if(!e||typeof e!="object")return;const t=e;return t.type!=="shortcut"&&t.type!=="desktop-file"?void 0:t.data?.bridgePayload}function Ht(e,t){const n=e.contentWindow;if(n)try{n.postMessage(t,window.location.origin)}catch{}}function gx(e,t,n,o){return e.registerDropTarget({id:`${fx}${o}`,element:n,accept:s=>!!Ii(s),onEnter:s=>{const i=Ii(s.payload);i&&(n.setAttribute(rl,""),Ht(t,{type:"os-drag-over",payload:i}))},onLeave:()=>{n.removeAttribute(rl),Ht(t,{type:"os-drag-leave"})},onDrop:(s,i)=>{n.removeAttribute(rl);const r=Ii(s.payload);if(!r)return;const l=t.getBoundingClientRect();Ht(t,{type:"os-drop",payload:r,position:{x:i.clientX-l.left,y:i.clientY-l.top}})}})}function Ym(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 wx(e){const t=Gm;if(!t)return;const n=document.querySelectorAll(Ci),o=!!Ii(e);console.info("[openstation] drag-start: suppressing %d iframe(s); bridgeable=%s",n.length,o,e),n.forEach(s=>{if(je.has(s)||(je.set(s,s.style.pointerEvents),s.style.pointerEvents="none"),!o||Ft.has(s))return;const i=s.parentElement;if(!i)return;const r=Ym(s),l=gx(t,s,i,r);Ft.set(s,l)})}function yx(){je.forEach((e,t)=>{t.style.pointerEvents=e}),je.clear(),Ft.forEach(e=>{try{e()}catch{}}),Ft.clear()}function bx(e){al||(al=!0,Gm=e,document.addEventListener(we.START,t=>{const n=t.detail;wx(n?.payload)}),document.addEventListener(we.END,()=>{yx()}),document.addEventListener(En.START,t=>{const n=t.detail;n?.payload&&mx(n.payload)}),document.addEventListener(En.END,()=>{ll()}),Y(_.WINDOW_CLOSED,"desktop-mode/drag/iframe-drop-targets-window-close",()=>{for(const[t]of Array.from(je))t.isConnected||je.delete(t);for(const[t,n]of Array.from(Ft))if(!t.isConnected){try{n()}catch{}Ft.delete(t)}}),window.__openStationIframeDropDebug=()=>({installed:al,iframesInDom:document.querySelectorAll(Ci).length,suppressedCount:je.size,registeredCount:Ft.size,suppressedIframeIds:Array.from(je.keys()).map(Ym)}))}const vx=250,_x=1e3,Ex="os-drag-hover";let Xm=!1,cl=null,dl=null,To=null,No=null,ul=null;function Zm(){To!==null&&(clearTimeout(To),To=null)}function Jm(){No!==null&&(clearTimeout(No),No=null)}function Do(){Zm(),Jm(),dl=null}function Qm(){Jm(),No=setTimeout(()=>{No=null,Do()},_x)}function kx(e,t){const n=cl?.getById(e);if(!(!n||n.isFocused()||!G(_.WINDOW_FOCUS_ON_DRAG_HOVER,!0,{windowId:e,payloadType:t})))try{cl?.focus(n)}catch(s){console.error("[openstation] focus-on-drag-hover focus() threw:",e,s)}}function eg(e,t){e!==dl&&(Zm(),dl=e,e!==null&&(To=setTimeout(()=>{To=null,kx(e,t)},vx)))}function tg(e,t,n){const o=zm(e,t);eg(o?ux(o):null,n)}const Sx=e=>{const t=e.detail;typeof t?.clientX!="number"||typeof t?.clientY!="number"||tg(t.clientX,t.clientY,t.payload?.type??"")},Ax=()=>{Do()};function Cx(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 Ix=e=>{Qm();const t=ul??(Cx(e)?"os-file":"external");tg(e.clientX,e.clientY,t)},ng=()=>{Do()},xx=e=>{e.relatedTarget===null&&Do()};function Lx(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 Tx=e=>{if(e.origin!==window.location.origin)return;const t=e.data;if(!t||t.type!==Ex)return;const n=Lx(e.source);n&&(Qm(),eg(n,typeof t.payloadType=="string"?t.payloadType:"external"))},Nx=e=>{const t=e.detail;t?.payload&&(ul=t.payload.kind??"")},Dx=()=>{ul=null,Do()};function Rx(e){Xm||(Xm=!0,cl=e,document.addEventListener(we.MOVE,Sx),document.addEventListener(we.END,Ax),document.addEventListener(En.START,Nx),document.addEventListener(En.END,Dx),document.addEventListener("dragover",Ix,!0),document.addEventListener("drop",ng,!0),document.addEventListener("dragend",ng,!0),document.addEventListener("dragleave",xx,!0),window.addEventListener("message",Tx))}function og(){const e=window.wp?.os;if(!e)return[];const t=e.windowManager,n=e.config;if(!t||!n)return[];const o=[],s=(r,l)=>({id:r.id,label:r.title,description:l,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=G("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=og();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=og(),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 Mx(){ui(Ox)}const Le=[],Px=new Set;function sg(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=Le.findIndex(n=>n.id===e.id);return t>=0?Le[t]=e:Le.push(e),fl(),()=>{const n=Le.findIndex(o=>o.id===e.id);n>=0&&(Le.splice(n,1),fl())}}function Wx(e){const t=Le.findIndex(n=>n.id===e);t>=0&&(Le.splice(t,1),fl())}function $x(){return Le.slice()}function fl(){for(const e of Array.from(Px))try{e()}catch(t){typeof console<"u"&&console.error("[openstation] palette-registry listener threw:",t)}}function ig(){if(Le.length===0)return;const e=Le.findIndex(n=>{try{return n.isOpen()}catch{return!1}});if(e===-1){try{Le[0].open()}catch{}return}try{Le[e].close()}catch{}const t=e+1;if(t<Le.length)try{Le[t].open()}catch{}}function pl(e){const t=Le.find(n=>n.id===e);if(t){for(const n of Le)if(n.id!==e)try{n.isOpen()&&n.close()}catch{}try{t.open()}catch{}}}let rg=!1;function Ux(){if(rg)return;rg=!0,document.addEventListener("keydown",t=>{!(t.metaKey||t.ctrlKey)||t.key!=="k"||t.shiftKey||t.altKey||(t.preventDefault(),t.stopImmediatePropagation(),ig())},!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"&&ig()})}const Ye=re("os/presence",()=>({byUser:new Map,serverTimeMs:0})),Fx=5*60*1e3;let ag=Date.now(),lg=!1;function xi(){ag=Date.now()}function Bx(e){if(!e||!e.snapshot)return;const t=Ye.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 a={status:i?.status??"offline",lastSeenMs:Number(i?.lastSeenMs??0)||0,lastActiveMs:Number(i?.lastActiveMs??0)||0},c=t.get(r);n.set(r,a),(!c||c.status!==a.status)&&o.push({userId:r,oldStatus:c?c.status:null,newStatus:a.status,entry:a})}Ye.state.byUser=n,typeof e.serverTimeMs=="number"&&(Ye.state.serverTimeMs=e.serverTimeMs),Ye.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})),ke.publish("os/presence-changed",i)}ke.publish("os/presence-snapshot-applied",{applied:Object.keys(e.snapshot).length,transitions:o.length})}function Hx(){lg||(lg=!0,document.addEventListener("pointerdown",xi,{capture:!0,passive:!0}),document.addEventListener("keydown",xi,{capture:!0,passive:!0}),document.addEventListener("visibilitychange",()=>{document.hidden||xi()}),xe.contribute("openstation_presence_active",()=>!0),xe.contribute("openstation_user_active",()=>Date.now()-ag<Fx),xe.subscribe("openstation_presence",e=>{Bx(e)}))}function zx(e){const t=Ye.state.byUser.get(e);return t?t.status:"offline"}function Gx(){return new Map(Ye.state.byUser)}function jx(e){return Ye.state.byUser.get(e)??null}function Vx(e){return Ye.subscribe(t=>e(t))}function qx(){xi()}function Kx(e){if(!Array.isArray(e)||e.length===0)return;const t=Ye.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),l={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,l),(!r||r.status!==l.status)&&o.push({userId:i,oldStatus:r?r.status:null,newStatus:l.status,entry:l})}if(!(o.length===0&&n.size===t.size)){Ye.state.byUser=n,Ye.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})),ke.publish("os/presence-changed",i)}ke.publish("os/presence-snapshot-applied",{applied:e.length,transitions:o.length})}}const Yx=Object.freeze({getStatus:zx,getAll:Gx,getEntry:jx,subscribe:Vx,markActive:qx,applyBatch:Kx});function cg(e){const t=new Set;let n=null;const o=new Set;e.onChange&&o.add(e.onChange);const s=()=>e.order().filter(l=>t.has(l)),i=()=>{const l=s();for(const a of o)try{a(l)}catch(c){console.error("[openstation] selection listener threw:",c)}},r=l=>{const a=t.size,c=Array.from(t);l(),!(t.size===a&&c.every(d=>t.has(d)))&&i()};return{keys:s,has:l=>t.has(l),size:()=>t.size,anchor:()=>n,set(l){r(()=>{t.clear();for(const a of l)t.add(a)}),n=l.length>0?l[l.length-1]:null},add(l){r(()=>{t.add(l)}),n=l},remove(l){r(()=>{t.delete(l)}),n===l&&(n=null)},toggle(l){r(()=>{t.has(l)?t.delete(l):t.add(l)}),n=l},selectRange(l,a=!1){const c=e.order(),d=c.indexOf(l),u=n===null?-1:c.indexOf(n);if(d<0)return;if(u<0){r(()=>{a||t.clear(),t.add(l)}),n=l;return}const f=Math.min(u,d),p=Math.max(u,d);r(()=>{a||t.clear();for(let g=f;g<=p;g+=1)t.add(c[g])})},selectAll(){const l=e.order();r(()=>{for(const a of l)t.add(a)}),n===null&&l.length>0&&(n=l[0])},clear(){r(()=>{t.clear()}),n=null},prune(){const l=new Set(e.order());let a=!1;return r(()=>{for(const c of Array.from(t))l.has(c)||(t.delete(c),a=!0)}),n!==null&&!l.has(n)&&(n=null),a},subscribe(l){return o.add(l),()=>{o.delete(l)}}}}const Xx=".os-file-tile",Zx="os-file-tile--selected",Jx="os-selection-marquee",dg=4,ug=36,fg=12,pg="data-os-marquee";function Qx(e){if(e.scrollHeight<=e.clientHeight)return!1;const t=e.ownerDocument?.defaultView?.getComputedStyle(e)?.overflowY;return t==="auto"||t==="scroll"||t==="overlay"}function eL(e){const t=e.ownerDocument;if(!t)return()=>{};const n=o=>{o.preventDefault()};t.addEventListener("selectstart",n,!0),t.body?.setAttribute(pg,"");try{t.defaultView?.getSelection()?.removeAllRanges()}catch{}return()=>{t.removeEventListener("selectstart",n,!0),t.body?.removeAttribute(pg)}}const tL=".os-window, .os-widgets__list, .os-widgets__card, .os-widgets__add, .os-pinned-note",nL="os-area--overview";function oL(e,t){const n=t.itemSelector??Xx,o=t.background??e,s=t.marquee!==!1,i=t.marqueeExclude??tL,r=()=>Array.from(e.querySelectorAll(n)).filter(R=>t.keyOf(R)!==null),l=()=>{const R=[],S=new Map;r().forEach((U,N)=>{const H=U.parentElement??e;let Z=S.get(H);Z||(Z=[],S.set(H,Z),R.push(H)),Z.push({key:t.keyOf(U),top:parseFloat(U.style.top)||0,left:parseFloat(U.style.left)||0,index:N})});const O=[];for(const U of R){const N=S.get(U)??[];N.sort((H,Z)=>H.top!==Z.top?H.top-Z.top:H.left!==Z.left?H.left-Z.left:H.index-Z.index);for(const H of N)O.push(H.key)}return O},a=t.order??l,c=cg({order:a,onChange:R=>{p(),t.onChange?.(R),u(R)}}),d={},u=R=>{typeof document>"u"||(kn={surface:t.surface??"",scope:t.scope??"",keys:R.slice(),count:R.length},ml=d,document.dispatchEvent(new CustomEvent("os-selection-changed",{detail:kn})))},f=R=>r().find(S=>t.keyOf(S)===R)??null,p=()=>{for(const R of r()){const S=t.keyOf(R),O=c.has(S);O!==R.hasAttribute("selected")&&(O?R.setAttribute("selected",""):R.removeAttribute("selected")),R.classList.toggle(Zx,O),R.hasAttribute("selectable")||R.setAttribute("selectable","");const U=O?"true":"false";R.getAttribute("aria-selected")!==U&&R.setAttribute("aria-selected",U)}};e.setAttribute("role","listbox"),e.setAttribute("aria-multiselectable","true"),t.ariaLabel&&e.setAttribute("aria-label",t.ariaLabel);let g=null;const m=R=>{if(!(R.target instanceof Element))return;const S=R.target.closest(n);if(S&&e.contains(S)){const O=t.keyOf(S);if(O===null)return;if(g=O,R.stopPropagation(),R.shiftKey){c.selectRange(O,R.ctrlKey||R.metaKey);return}if(R.ctrlKey||R.metaKey){c.toggle(O);return}c.set([O]);return}if(w){w=!1;return}c.clear()};o.addEventListener("click",m);let h=null,b=null,y=null,C=[],w=!1,E=0,T=null,M=null;const P=R=>{if(typeof o.setPointerCapture=="function")try{o.setPointerCapture(R),M=R}catch{}},v=()=>{if(M===null||typeof o.releasePointerCapture!="function"){M=null;return}try{o.hasPointerCapture?.(M)&&o.releasePointerCapture(M)}catch{}M=null},$=(R,S)=>{const O=o.getBoundingClientRect();return{x:R-O.left+o.scrollLeft,y:S-O.top+o.scrollTop}},D=()=>{h?.remove(),h=null,b=null,y=null,T?.(),T=null,v(),E&&(cancelAnimationFrame(E),E=0),document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",q),document.removeEventListener("pointercancel",K),o.removeEventListener("lostpointercapture",K),o.removeEventListener("scroll",I),window.removeEventListener("blur",K)};function I(){if(!b||!y)return;const R=$(y.x,y.y),S=R.x-b.x,O=R.y-b.y;if(!h&&Math.abs(S)<dg&&Math.abs(O)<dg)return;h||(h=document.createElement("div"),h.className=Jx,h.setAttribute("aria-hidden","true"),getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.appendChild(h),w=!0,T=eL(o),W());const U=Math.min(b.x,R.x),N=Math.min(b.y,R.y),H=Math.abs(S),Z=Math.abs(O);h.style.left=`${U}px`,h.style.top=`${N}px`,h.style.width=`${H}px`,h.style.height=`${Z}px`;const se=o.getBoundingClientRect(),oe=se.left-o.scrollLeft,_e=se.top-o.scrollTop,pe={left:U+oe,top:N+_e,right:U+H+oe,bottom:N+Z+_e},ye=[];for(const he of r()){const Ae=he.getBoundingClientRect();Ae.left<pe.right&&Ae.right>pe.left&&Ae.top<pe.bottom&&Ae.bottom>pe.top&&ye.push(t.keyOf(he))}c.set(Array.from(new Set([...C,...ye])))}function W(){if(E||typeof requestAnimationFrame!="function")return;const R=()=>{if(E=0,!h||!y)return;const S=o.getBoundingClientRect();if(Qx(o)){let U=0;if(y.y<S.top+ug?U=-fg:y.y>S.bottom-ug&&(U=fg),U!==0){const N=o.scrollTop;o.scrollTop+=U,o.scrollTop!==N&&I()}}E=requestAnimationFrame(R)};E=requestAnimationFrame(R)}const z=R=>{b&&(y={x:R.clientX,y:R.clientY},I())},q=()=>{h&&(hl=Date.now()),D()},K=()=>{D()},x=R=>{if(!s||R.button!==0||!(R.target instanceof Element)||o.classList.contains(nL)||R.target.closest(n))return;const S=R.target.closest(i);S&&S!==o&&o.contains(S)||(b=$(R.clientX,R.clientY),y={x:R.clientX,y:R.clientY},typeof R.pointerId=="number"&&P(R.pointerId),C=R.ctrlKey||R.metaKey||R.shiftKey?c.keys():[],C.length===0&&c.clear(),document.addEventListener("pointermove",z),document.addEventListener("pointerup",q),document.addEventListener("pointercancel",K),o.addEventListener("lostpointercapture",K),window.addEventListener("blur",K),o.addEventListener("scroll",I,{passive:!0}))};o.addEventListener("pointerdown",x);const F=R=>{if(R.key==="a"&&(R.ctrlKey||R.metaKey)){R.preventDefault(),c.selectAll();return}if(R.key==="Escape"){if(h||b){D();return}c.size()>0&&c.clear();return}const S=R.key==="ArrowRight"||R.key==="ArrowDown",O=R.key==="ArrowLeft"||R.key==="ArrowUp";if(!S&&!O)return;const U=S?1:-1,N=a();if(N.length===0)return;const H=g??c.anchor(),Z=H===null?-1:N.indexOf(H),se=Math.min(N.length-1,Math.max(0,Z<0?0:Z+U));R.preventDefault();const oe=N[se];g=oe,R.shiftKey?c.selectRange(oe):c.set([oe]),f(oe)?.focus()};return e.addEventListener("keydown",F),p(),{model:c,keys:()=>c.keys(),elementFor:f,refresh(){c.prune(),p()},destroy(){D(),o.removeEventListener("click",m),o.removeEventListener("pointerdown",x),e.removeEventListener("keydown",F),ml===d&&(kn=null,ml=null)}}}let hl=0;function sL(){return hl>0&&Date.now()-hl<500}let kn=null,ml=null;function iL(){return kn?{...kn,keys:kn.keys.slice()}:null}function gl(e){return typeof e.sort=="number"?e.sort:100}function rL(e,t){return le(k("%1$s (%2$d items)","desktop-mode"),e,t)}function hg(e,t){if(e.length===0)return[];const n=e.map(l=>{const a=t(l);return Array.isArray(a)?a:[]});if(e.length===1)return n[0];const o=e.length,s=[],i=l=>l.multiId??l.id;for(const l of n[0]){const a=i(l),c=[];let d=!1;for(const p of n){const g=p.find(m=>i(m)===a);if(!g||g.multi!==!0){d=!0;break}c.push(g)}if(d||s.some(p=>p.id===a))continue;const u=c[0],f=u.bulkLabel?u.bulkLabel(o):rL(u.label,o);s.push({id:a,label:f,icon:u.icon,disabled:c.some(p=>p.disabled===!0),danger:c.some(p=>p.danger===!0),sort:Math.min(...c.map(gl)),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 C=g.get(y);C?C.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 '${a}' failed for a batch:`,y)}for(const h of m)try{await h.onClick(p)}catch(b){console.error(`[openstation] selection action '${a}' failed for one item:`,b)}}})}s.sort((l,a)=>{const c=gl(l),d=gl(a);return c!==d?c-d:l.label.localeCompare(a.label)});const r=G("os.selection.actions",s,{items:e,count:o});return Array.isArray(r)?r:s}function mg(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 l of r)if(l.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 aL="os-wallpaper-menu";let Sn=null,wl=null,gg=0;function yl(){if(!Sn)return;const e=Sn.dataset.menuScope??"selection",t=wl;Sn.dispatchEvent(new CustomEvent("tile-menu-closed")),Sn.remove(),Sn=null,wl=null,t?.(),L(`os.${e}.menu.closed`,{})}function lL(e,t){yl();const n=++gg;Ns(()=>n===gg,()=>cL(e,t))}function cL(e,{actions:t,dataset:n,className:o,scope:s="selection",onOpened:i,onClosed:r}){if(t.length===0)return;const l=document.createElement("os-context-menu");l.setAttribute("open",""),l.classList.add(aL),o&&l.classList.add(o),l.dataset.menuScope=s;for(const[u,f]of Object.entries(n??{}))l.dataset[u]=f;l.style.left=`${e.x}px`,l.style.top=`${e.y}px`;const a=new Map;for(const u of t){a.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",dL(u.icon)),f.textContent=u.label,l.appendChild(f)}l.addEventListener("os-context-menu-pick",u=>{const f=u.detail,p=a.get(f.id);p&&(yl(),Promise.resolve(p.onClick(new MouseEvent("click"))).catch(g=>{console.error(`[openstation] menu action '${p.id}' threw:`,g)}))}),document.body.appendChild(l),Sn=l,wl=r??null,aa(l);const c=mg(l,{close:()=>yl()});l.addEventListener("tile-menu-closed",c);const d=t.map(u=>u.id);i?.(d),L(`os.${s}.menu.opened`,{items:d,count:t.length})}function dL(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const uL={active:iL,resolveCommonActions:hg,createModel:cg};let Ro=null;function fL(){xe.contribute("openstation_content_changes_seen_ts",()=>Ro===null?0:Ro),xe.subscribe("openstation_content_changes",e=>{if(!e||typeof e.ts!="number")return;const t=Ro===null,n=Ro??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===""||(Da(`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));Ro=o})}const pL="desktop_mode_nonces",bl=new Map;let wg=!1;function vl(e,t){if(typeof e!="string"||e==="")return()=>{};let n=bl.get(e);return n||(n=new Set,bl.set(e,n)),n.add(t),()=>{n.delete(t)}}function hL(){wg||(wg=!0,xe.subscribe(pL,e=>{if(!(!e||typeof e!="object"))for(const[t,n]of Object.entries(e)){if(typeof n!="string"||n==="")continue;const o=bl.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)}}}),mL())}function mL(){vl("wp_rest",gL),vl("desktop-mode-plugins",e=>{yg("desktop-mode-plugins","ajaxNonce",e)}),vl("updates",e=>{yg("desktop-mode-plugins","updatesNonce",e)})}function gL(e){const t=wL();t&&typeof t.restNonce=="string"&&(t.restNonce=e);const n=bg();if(n)for(const o of Object.values(n))o&&typeof o=="object"&&typeof o.restNonce=="string"&&(o.restNonce=e)}function yg(e,t,n){const s=bg()?.[e];s&&typeof s=="object"&&(s[t]=n)}function wL(){if(!(typeof window>"u"))return window.openStationConfig}function bg(){if(!(typeof window>"u"))return window.openStationWindowConfig}const yL="desktop_mode_auth",bL=5e3,vg=1e3,vL=1e4;let _g=!1,Li=!1,_l=!1,Ti=0,Eg=0,Oo=0,An=null,kg=0,Sg=null,Ag=null,Cg=()=>{try{window.location.reload()}catch{}};function El(){try{const e=window.wp?.heartbeat;e&&typeof e.connectNow=="function"&&e.connectNow()}catch{}}function kl(e=vg){const t=Date.now();if(t<Oo){An===null&&(An=window.setTimeout(()=>{An=null,Oo=Date.now()+vg,El()},Oo-t));return}Oo=t+e,El()}function _L(){Li=!0,!_l&&(_l=!0,L(_.AUTH_LOST),document.dispatchEvent(new CustomEvent("os-auth-lost")))}function EL(){for(const e of kL())try{e.contentWindow?.location.reload()}catch{}}function kL(){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 Sl(){const e=Date.now();e-kg<vL||(kg=e,Li=!1,_l=!1,An!==null&&(window.clearTimeout(An),An=null),Oo=0,kl(),EL(),L(_.AUTH_RESTORED),document.dispatchEvent(new CustomEvent("os-auth-restored")))}function SL(e){const t=e&&typeof e=="object"?Number(e.uid):NaN;if(!(!Number.isFinite(t)||t<=0)){if(Ti<=0){Ti=t;return}t!==Ti&&Cg()}}function AL(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<Eg||(Eg=o+bL,El())}function CL(){const e=document.getElementById("wp-auth-check-wrap");if(!e||typeof MutationObserver>"u")return;let t=!e.classList.contains("hidden");Ag=new MutationObserver(()=>{const n=!e.classList.contains("hidden");t&&!n&&kl(),t=n}),Ag.observe(e,{attributes:!0,attributeFilter:["class"]})}function IL(e={}){_g||(_g=!0,Ti=Number(e.currentUserId)>0?Number(e.currentUserId):0,e.reloadShell&&(Cg=e.reloadShell),xe.subscribe("wp-auth-check",t=>{if(t===!1){_L();return}t===!0&&Li&&Sl()}),xe.subscribe("nonces_expired",()=>{if(Li){Sl();return}kl()}),xe.subscribe(yL,SL),Sg=t=>{if(t.origin!==window.location.origin)return;const n=t.data;!n||typeof n!="object"||n.type==="os-reauth-detected"&&Sl()},window.addEventListener("message",Sg),CL())}const Cn=12;function Al(e,t){const n=ae(e,t.adminUrl);return(t.dockItems||[]).find(o=>ae(o.url,t.adminUrl)===n||(o.submenu||[]).some(s=>ae(s.url,t.adminUrl)===n))}function Cl(e,t){const n=Math.max(200,t.width-Cn*2),o=Math.max(200,t.height-Cn*2),s=Math.min(e.width,n),i=Math.min(e.height,o),r=Math.max(0,t.width-s-Cn),l=Math.max(0,t.height-i-Cn),a=Math.max(Cn,Math.min(e.x,r)),c=Math.max(Cn,Math.min(e.y,l));return{x:a,y:c,width:s,height:i}}const Ig=window.location.origin;function xL(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 l=i.getAttribute("href");if(!l||l.charAt(0)==="#"||/^(mailto:|tel:|javascript:|data:)/i.test(l))return;let a;try{a=new URL(l,window.location.href)}catch(m){typeof console<"u"&&console.warn("[openstation] Couldn’t parse href; letting the browser handle the click:",l,m);return}if(a.origin!==Ig)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(!a.pathname.startsWith(c)||/\/(admin-post|admin-ajax)\.php$/.test(a.pathname)||a.searchParams.has("action")&&a.searchParams.get("action")==="logout"||a.searchParams.has("desktop_mode_classic")||(n.preventDefault(),n.stopPropagation(),Ge(a.href)))return;const d=ae(a.href,t.adminUrl),u=Al(a.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:a.href,parentUrl:u?.url??a.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 LL(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 TL(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 NL(e){const t=LL(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=TL(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 DL="os-registry-changed";function RL(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 Il(e,t,n){const{added:o,removed:s}=RL(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(DL,{detail:i}))}function OL(e){const{applyDockItems:t,config:n,syncNativeWindows:o,syncServerWidgets:s,syncServerWallpapers:i,syncServerCommands:r,syncServerSettingsTabs:l,syncServerTitleBarButtons:a,syncServerWindowActions:c,syncServerUnfocusEffects:d,syncServerWindowLinkRenderers:u,syncServerDockRailRenderers:f,syncServerGames:p,syncServerDesktopThemes:g,renderIcons:m,syncShortcuts:h}=e;return function(y){const C=y.dockItems,w=y.nativeWindows,E=y.serverWidgets,T=y.serverWallpapers,M=y.serverCommandScripts,P=y.serverCommands,v=y.serverSettingsTabScripts,$=y.serverSettingsTabs,D=y.serverDockRailRendererScripts,I=y.serverTitleBarButtonScripts,W=y.serverWindowActionScripts,z=y.serverUnfocusEffectScripts,q=y.serverWindowLinkRendererScripts,K=y.serverWindowNotices,x=y.serverGames,F=y.serverDesktopThemes,R=y.desktopIcons;if(!Array.isArray(C)||C.length===0)return;const S=n.dockItems;if(t(C),n.dockItems=C,Il("dock-items",S,C),h?.(),Array.isArray(w)){const O=n.nativeWindows;o(w),n.nativeWindows=w,Il("native-windows",O,w)}if(Array.isArray(E)&&(s(E),n.serverWidgets=E),Array.isArray(T)&&(i(T),n.serverWallpapers=T),Array.isArray(x)&&(p(x),n.serverGames=x),Array.isArray(F)&&(g?.(F),n.serverDesktopThemes=F),Array.isArray(M)&&(r(M,Array.isArray(P)?P:void 0),n.serverCommandScripts=M,Array.isArray(P)&&(n.serverCommands=P)),Array.isArray(v)&&(l(v,Array.isArray($)?$:void 0),n.serverSettingsTabScripts=v,Array.isArray($)&&(n.serverSettingsTabs=$)),Array.isArray(I)&&(a(I),n.serverTitleBarButtonScripts=I),Array.isArray(W)&&(c(W),n.serverWindowActionScripts=W),Array.isArray(z)&&(d(z),n.serverUnfocusEffectScripts=z),Array.isArray(q)&&(u(q),n.serverWindowLinkRendererScripts=q),Array.isArray(D)&&(f(D),n.serverDockRailRendererScripts=D),Array.isArray(K)&&(Oh(K),n.serverWindowNotices=K),Array.isArray(R)){const O=n.desktopIcons;m(R),n.desktopIcons=R,Il("desktop-icons",O,R)}NL(y.updateCounts)}}const ML=8e3,PL=600;function WL(e){const{layoutDispatcher:t,desktopArea:n,config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:l,syncServerSettingsTabs:a,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:m,renderIcons:h,syncShortcuts:b}=e,y=OL({applyDockItems:D=>t?.applyDockItems(D),config:o,syncNativeWindows:s,syncServerWidgets:i,syncServerWallpapers:r,syncServerCommands:l,syncServerSettingsTabs:a,syncServerTitleBarButtons:c,syncServerWindowActions:d,syncServerUnfocusEffects:u,syncServerWindowLinkRenderers:f,syncServerDockRailRenderers:p,syncServerGames:g,syncServerDesktopThemes:m,renderIcons:h,syncShortcuts:b});let C=typeof o.menuSig=="string"?o.menuSig:"",w=!1,E=null,T=!1,M=!1;const P=()=>{if(!o.adminUrl)return Promise.resolve();const D=(()=>{try{const I=new URL("admin.php",o.adminUrl);return I.searchParams.set("openstation_chromeless","1"),I.searchParams.set("openstation_menu_refresh","1"),I.toString()}catch{return null}})();return D?new Promise(I=>{const W=document.createElement("iframe");W.setAttribute("aria-hidden","true"),W.tabIndex=-1,W.style.cssText="position:absolute;top:-9999px;left:-9999px;width:1px;height:1px;border:0;opacity:0;pointer-events:none;",W.src=D;let z=!1;const q=()=>{z||(z=!0,window.clearTimeout(x),window.removeEventListener("message",K),W.parentNode&&W.parentNode.removeChild(W),I())},K=F=>{if(F.source!==W.contentWindow)return;const R=F.data;!R||R.type!=="os-plugins-changed"||q()},x=window.setTimeout(()=>{L(_.SHELL_ERROR,{scope:"menu-refresh",error:new Error("menu refresh probe timed out")}),q()},ML);window.addEventListener("message",K),document.body.appendChild(W)}):Promise.resolve()},v=()=>{if(T){M=!0;return}T=!0,P().finally(()=>{T=!1,M&&(M=!1,v())})},$=()=>{E!==null&&window.clearTimeout(E),E=window.setTimeout(()=>{E=null,v()},PL)};return window.addEventListener("message",D=>{if(D.origin!==Ig)return;const I=D.data;if(I){if(I.type==="os-plugins-changed"){I.payload&&(y(I.payload),typeof I.payload.menuSig=="string"&&(C=I.payload.menuSig));return}if(I.type==="os-updates-changed"){$();return}if(I.type==="os-menu-signature"){const W=I.sig;typeof W=="string"&&W!==""&&W!==C&&!w&&(w=!0,P().finally(()=>{w=!1}))}}}),P}function $L(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 UL(e,t,n=5e3){const o=e.getById(t);return o?Promise.resolve(o):new Promise(s=>{const i=a=>{window.clearTimeout(l),document.removeEventListener("os-window-opened",r),s(a)},r=a=>{a.detail?.windowId===t&&i(e.getById(t)??null)},l=window.setTimeout(()=>i(null),n);document.addEventListener("os-window-opened",r)})}async function FL(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 l=Cl(r,s);i[r.id]={desktopId:r.desktopId,initialState:r.state,x:l.x,y:l.y,width:l.width,height:l.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 UL(e,r.id);continue}const l=Cl(r,s),a=Al(r.url,t),c=await e.openNew({id:r.id,baseId:r.baseId||r.id,desktopId:r.desktopId,multi:!!a?.multi,url:r.url,parentUrl:a?.url??r.url,title:r.title,icon:r.icon||"dashicons-admin-generic",x:l.x,y:l.y,width:l.width,height:l.height,initialState:r.state,submenu:a?.submenu,selfLabel:a?.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 BL(e,t){if(Ge(t.currentPage))return;const n=ae(t.currentPage,t.adminUrl),o=Al(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 HL(e){return!(e.fromPortal&&!e.fromPortalIntent&&(e.hasSession||!e.defaultEnabled||e.isNativeDefault))}function xl(e,t,n,o){const s=Zd(t,n),i=window.fetch(t,s);if(i.then(l=>{if(l.status===401||l.status===403){let a;typeof t=="string"?a=t:t instanceof URL?a=t.href:a=t.url,AL(l.status,a)}},()=>{}),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(l=>{if(!l.ok)throw new Error(zL(l));return l})).catch(()=>{}),i}function zL(e){const t=e.statusText?`${e.status} ${e.statusText}`:String(e.status);return le(k("Request failed (HTTP %s)."),t)}const GL=500,jL=1500;function VL(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 xl(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){L(_.SHELL_ERROR,{scope:"session-save",error:d})}finally{o=!1,s&&(s=!1,a())}},l=()=>{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()},a=()=>{n!==null&&clearTimeout(n);let c=GL;if(i!==0){const d=Date.now()-i;c=Math.max(c,jL-d)}n=window.setTimeout(()=>{n=null,r()},c)};return window.addEventListener("pagehide",l),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&l()}),a}const qL=120;function KL(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(_.DESKTOP_CREATED,"desktop-mode/session-save",e),Y(_.DESKTOP_CLOSED,"desktop-mode/session-save",e),Y(_.DESKTOP_SWITCHED,"desktop-mode/session-save",e)}function YL(){const e=document.getElementById("os-shell");let t=null;const n=()=>{t=null;const o=e?e.getBoundingClientRect():null;L(_.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,qL)}),document.addEventListener("visibilitychange",()=>{L(_.SHELL_VISIBILITY,{state:document.hidden?"hidden":"visible"})})}function XL(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 G(_.DOCK_TILE_CLASS,e,o)}function ZL(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 G(_.DOCK_TILE_ELEMENT,e,o)}function JL(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 G(_.DOCK_TILE_TOOLTIP,e,o)}function QL(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};L(_.DOCK_TILE_RENDERED,{...o,el:e})}const eT=[".os-dock","#os-dock","#os-side-dock",".os-dock__tooltip",".os-dock-submenu"].join(","),Ll=new Set;function tT(e){if(!e||typeof e.closest!="function")return!1;const t=e;if(t.closest(eT))return!0;for(const n of Ll)if(t.closest(n))return!0;return!1}function nT(e){return typeof e!="string"||e.trim()===""?()=>{}:(Ll.add(e),()=>{Ll.delete(e)})}const ut=new Map,oT=window.location.origin;function xg(e){let t=ut.get(e);return t||(t={headers:new Map,observers:new Set,observeCount:0,loadHandler:null,loadHandlerTarget:null},ut.set(e,t)),sT(e,t),t}function sT(e,t){const n=Tl(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(()=>In(e))};n.addEventListener("load",o),t.loadHandler=o,t.loadHandlerTarget=n}function iT(e){e.loadHandlerTarget&&e.loadHandler&&typeof e.loadHandlerTarget.removeEventListener=="function"&&e.loadHandlerTarget.removeEventListener("load",e.loadHandler),e.loadHandler=null,e.loadHandlerTarget=null}function Tl(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 rT(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 In(e){const t=Tl(e);if(!t||!t.contentWindow)return;const n=ut.get(e),o=n?rT(n):{},s=!!n&&n.observeCount>0;try{t.contentWindow.postMessage({type:"os-instrument-set",headers:o,observe:s},oT)}catch{}}Y(_.IFRAME_READY,"desktop-mode/devtools/replay",e=>{const t=e;t&&typeof t.windowId=="string"&&ut.has(t.windowId)&&In(t.windowId)}),Y(_.IFRAME_NETWORK_COMPLETED,"desktop-mode/devtools/dispatch",e=>{const t=e;if(!t||typeof t.windowId!="string")return;const n=ut.get(t.windowId);if(n)for(const o of n.observers)try{o(t)}catch{}});const St=new Map,aT=1e3;function Lg(e,t,n){const o=St.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,!!St.has(e)){typeof r.cursor=="number"&&(o.cursor=r.cursor);for(const l of r.events||[]){const a=o.channels.get(l.channel);if(a)for(const c of a)try{c(l)}catch{}}}}).catch(()=>{o.inflight=!1}).finally(()=>{const r=St.get(e);r&&r.channels.size>0&&(r.timer=setTimeout(()=>Lg(e,t,n),aT))})}function lT(){const e=window.openStationConfig;return!e||!e.restUrl||!e.restNonce?null:{restUrl:e.restUrl,restNonce:e.restNonce}}function cT(e,t){const n=St.get(e);if(!n)return;const o=n.channels.get(t.channel);if(o)for(const s of o)try{s(t)}catch{}}let dT=0;const Tg={addRequestHeader(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="string"||t==="")return()=>{};const o=xg(e),s={value:n};let i=o.headers.get(t);return i||(i=[],o.headers.set(t,i)),i.push(s),In(e),()=>{const r=ut.get(e);if(!r)return;const l=r.headers.get(t);if(!l)return;const a=l.indexOf(s);a>=0&&l.splice(a,1),l.length===0&&r.headers.delete(t),In(e),Ng(e)}},onRequest(e,t,n){if(typeof e!="string"||e==="")return()=>{};if(typeof t!="function")return()=>{};const o=xg(e);o.observers.add(t);const s=!!n?.observe;return s&&(o.observeCount++,In(e)),()=>{const i=ut.get(e);i&&(i.observers.delete(t),s&&(i.observeCount=Math.max(0,i.observeCount-1),In(e)),Ng(e))}},reloadWithDebugSession(e,t,n){if(typeof e!="string"||e===""||typeof t!="string"||t==="")return null;const o=Tl(e);if(!o)return null;const s=n?.headerName||"X-WP-Debug-Session",i=n?.queryArg||"wp_debug_session",r=Tg.addRequestHeader(e,s,t);try{const l=o.getAttribute("src")||o.src||"",a=new URL(l,window.location.origin);a.searchParams.set(i,t),o.src=a.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){cT(e,{id:++dT,t:Date.now(),channel:t,payload:n})},subscribe(e,t,n){let o=St.get(e);const s=!o;o||(o={channels:new Map,cursor:0,timer:null,inflight:!1},St.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=lT();r&&Lg(e,r.restUrl,r.restNonce)}return()=>{const r=St.get(e);if(!r)return;const l=r.channels.get(t);l&&(l.delete(n),l.size===0&&r.channels.delete(t)),r.channels.size===0&&(r.timer&&clearTimeout(r.timer),St.delete(e))}}}};function Ng(e){const t=ut.get(e);t&&t.headers.size===0&&t.observers.size===0&&(iT(t),ut.delete(e))}async function Ni(e){return await fr(pr()),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 uT(e){const t=[];for(const a of e.getVisibleRects()){if(a.state==="minimized"||a.element.offsetParent===null)continue;const c=a.element.getBoundingClientRect();t.push({id:`window:${a.windowId}`,kind:"window",rect:Dg(c),face:"top",element:a.element})}const n=document.getElementById("os-shell");if(n){const a=n.getBoundingClientRect();t.push({id:"shell:floor",kind:"shell",rect:{x:a.left,y:a.bottom-1,width:a.width,height:1},face:"top",element:n})}const o=document.querySelectorAll(".os-dock");let s=0;for(const a of Array.from(o)){const c=a.getBoundingClientRect();if(c.width<=0||c.height<=0)continue;const d=a.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:a}):d==="right"?t.push({id:u,kind:"dock",rect:{x:c.left,y:c.top,width:1,height:c.height},face:"left",element:a}):t.push({id:u,kind:"dock",rect:{x:c.right-1,y:c.top,width:1,height:c.height},face:"right",element:a})}const i=document.querySelectorAll(".os-widgets__card");let r=0;i.forEach(a=>{const c=a.getBoundingClientRect();if(c.width===0&&c.height===0)return;const d=a.dataset.widgetId??String(r++);t.push({id:`widget:${d}`,kind:"widget",rect:Dg(c),face:"top",element:a})});const l=G(_.WALLPAPER_SURFACES,t);return Array.isArray(l)?l:t}function Dg(e){return{x:e.left,y:e.top,width:e.width,height:e.height}}const fT="__openstationKeyedListKey",pT="__openstationKeyedListData";function hT(e){const t=e.__openstationKeyedList;if(t)return t;const n={byKey:new Map};return e.__openstationKeyedList=n,n}function mT(e,t,n){const o=hT(e),s=o.byKey,i=new Map,r=[],l=new Set;for(const a of t){const c=String(n.keyOf(a));l.has(c)&&console.warn("[desktop-mode/keyed-list] duplicate key — only the last item with this key will render:",c),l.add(c);const d=s.get(c);if(d){const f=d.data;n.updateItem?.(d.el,a,f),d.data=a,i.set(c,d),r.push(d.el);continue}const u=n.buildItem(a);u[fT]=c,u[pT]=a,i.set(c,{el:u,data:a}),r.push(u)}for(const[a,c]of s)i.has(a)||c.el.remove();for(let a=0;a<r.length;a++){const c=r[a],d=e.children[a];d!==c&&e.insertBefore(c,d??null)}o.byKey=i}function gT(e){const t=e.__openstationKeyedList;if(t){for(const n of t.byKey.values())n.el.remove();t.byKey.clear(),delete e.__openstationKeyedList}}function wT(e){const{root:t,fetchPage:n,getId:o,renderItem:s,rootMargin:i="200px",initialCursor:r=null,onLoadingChange:l=()=>{},onError:a=P=>{typeof console<"u"&&console.error("[openstation] createInfiniteList:",P)}}=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=P=>{if(p!==P){p=P;try{l(P)}catch(v){a(v)}}},C=()=>{b&&(b.disconnect(),b=null)},w=()=>{b||!c||h||(b=new IntersectionObserver(P=>{for(const v of P)v.isIntersecting&&E()},{rootMargin:i}),b.observe(c))},E=async()=>{if(h||p||!f)return;y(!0),g=new AbortController;const P=g;try{const v=await n(u,P.signal);if(h||P!==g)return;let $=0;const D=document.createDocumentFragment();for(const I of v.items??[]){const W=String(o(I));if(d.has(W))continue;d.add(W);const z=s(I,m+$);D.appendChild(z),$++}$>0&&(c&&c.parentNode===t?t.insertBefore(D,c):t.appendChild(D),m+=$),u=v.nextCursor??null,u||(f=!1,C())}catch(v){if(v?.name==="AbortError")return;a(v)}finally{P===g&&(y(!1),g=null)}},T=()=>{if(h)return;g?.abort(),g=null,d.clear(),u=r,f=!0,m=0;const P=c&&c.parentNode===t;for(;t.firstChild;)t.removeChild(t.firstChild);P&&c&&t.appendChild(c),y(!1),w(),E()},M=()=>{h||(h=!0,C(),g?.abort(),g=null,!e.sentinel&&c&&c.parentNode===t&&t.removeChild(c),c=null,y(!1))};return w(),E(),{reset:T,loadMore:E,hasMore:()=>f,isLoading:()=>p,destroy:M}}const yT=520,bT=720,vT=500;function _T(e,t={}){if(typeof e!="string"||e==="")return Promise.reject(new Error("[openstation] startOAuth requires a non-empty service slug."));const n=kT(),o=ST();return Be(et(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=>ET(s,e,t))}function ET(e,t,n){return new Promise((o,s)=>{const i=n.width??yT,r=n.height??bT,l=Math.max(0,Math.floor((window.screen.width-i)/2)),a=Math.max(0,Math.floor((window.screen.height-r)/2)),c=[`width=${i}`,`height=${r}`,`left=${l}`,`top=${a}`,"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 C=y?.reason??"unknown",w=y?.message??"OAuth flow failed",E=new Error(`[openstation] startOAuth(${t}) failed: ${C} — ${w}`);E.cause=y,s(E)}};window.addEventListener("message",m),f=window.setInterval(()=>{d.closed&&(g(),s(new Error(`[openstation] startOAuth(${t}) cancelled — popup closed before completing.`)))},vT)})}function Rg(){return window.openStationConfig??{}}function kT(){const e=Rg().restRoot;return typeof e=="string"&&e!==""?e:`${window.location.origin}/wp-json/`}function ST(){const e=Rg().restNonce;return typeof e=="string"&&e!==""?e:null}const AT="",CT="system-default",IT={accent:"pulse",desktopLayout:"unified",dockPlacement:"bottom"};function xT(e,t,n={}){const o=t===AT,s=o?null:Gd(t);if(!o&&!s)return{};const i=o?CT:s.slug,r=e.appliedThemeRecommendations.includes(i);if(r&&!n.force)return{};const l=wv(o?IT:s.recommendedOsSettings),a=Object.keys(l);if(a.length===0)return{};const c=e,d={};for(const u of a){const f=l[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 LT=new Set(["windowManager","dock","sideDock","taskbar","desktopLayout","dockPlacement","icons","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","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","debug","fetch"]);function TT(e){const{manager:t,dock:n,layoutDispatcher:o,osSettings:s,iconsApi:i,filesApi:r,saveSession:l,widgetLayer:a,registerWindow:c,openWindowById:d,openNewWindowById:u,placeSystemTile:f,setDefaultWindow:p,refreshMenu:g,openOsSettings:m,aiAssistant:h,dragBridge:b,dragManager:y,connect:C,getConnection:w,wallpaperSuspend:E,mio:T,config:M}=e,P={windowManager:t,dock:n,sideDock:o?.getSide()??null,desktopLayout:s.getOsSettingsSnapshot().desktopLayout,dockPlacement:o?.getDockPlacement()??s.getOsSettingsSnapshot().dockPlacement,icons:i,files:r,confirm:Ni,saveSession:l,hooks:gb(),HOOKS:_,isActive:()=>!!document.getElementById("os-shell"),registerWallpaper:v=>{oo(v),s.apply()},registerWidget:v=>{Ja(v)},widgetLayer:a,widgets:{redock:v=>{a?.redock(v)}},loadVendorScript:Se,getWallpaperSurfaces:()=>uT(t),wallpaper:E,mio:T,games:wp,registerWindow:c,openWindow:d,openNewWindow:u,fetch:(v,$,D)=>xl(t,v,$,D),repaintLoadingOverlays:sf,cloneTemplate:nl,onWindow:DC,createInfiniteList:wT,startOAuth:_T,registerSystemTile:v=>{f(v),L(_.DOCK_ITEM_APPENDED,{id:v.id})},registerModule:rp,loadModules:ap,whenReady:Yc,ready:Yc,isReady:yb,setDefaultWindow:p,refreshMenu:g,config:M,ai:h,dragBridge:b,dragManager:y,registerCommand:ui,unregisterCommand:Ip,listCommands:xp,registerDestructiveAdminAction:_E,unregisterDestructiveAdminAction:rf,listDestructiveAdminActions:EE,registerSettingsTab:Tp,unregisterSettingsTab:Np,listSettingsTabs:Dp,registerDockRailRenderer:id,unregisterDockRailRenderer:Nb,listDockRailRenderers:Ob,openOsSettings:m,getOsSettings:()=>s.getOsSettingsSnapshot(),subscribeOsSettings:v=>s.subscribeOsSettings(v),updateOsSettings:(v,$={})=>{if(typeof v.wallpaper=="string"&&(s.state.wallpaper=v.wallpaper),typeof v.accent=="string"&&(s.state.accent=v.accent),typeof v.dockSize=="string"&&(s.state.dockSize=v.dockSize),typeof v.windowRadius=="string"&&(s.state.windowRadius=v.windowRadius),typeof v.adminBarMode=="string"&&(s.state.adminBarMode=v.adminBarMode),typeof v.desktopLayout=="string"&&(s.state.desktopLayout=v.desktopLayout),typeof v.dockPlacement=="string"&&(s.state.dockPlacement=v.dockPlacement),typeof v.desktopTheme=="string"&&(s.state.desktopTheme=v.desktopTheme),typeof v.unfocusEffect=="string"&&(s.state.unfocusEffect=v.unfocusEffect),typeof v.windowReveal=="string"&&(s.state.windowReveal=v.windowReveal),typeof v.windowRevealDuration=="number"&&(s.state.windowRevealDuration=v.windowRevealDuration),typeof v.dockRailRenderer=="string"&&(s.state.dockRailRenderer=v.dockRailRenderer),typeof v.windowLinkRenderer=="string"&&(s.state.windowLinkRenderer=v.windowLinkRenderer),(v.windowLinkVisibility==="focus"||v.windowLinkVisibility==="always"||v.windowLinkVisibility==="off")&&(s.state.windowLinkVisibility=v.windowLinkVisibility),typeof v.windowLinksEnabled=="boolean"&&(s.state.windowLinksEnabled=v.windowLinksEnabled),typeof v.windowLinkRaiseOnFocus=="boolean"&&(s.state.windowLinkRaiseOnFocus=v.windowLinkRaiseOnFocus),typeof v.windowLinkHighlight=="boolean"&&(s.state.windowLinkHighlight=v.windowLinkHighlight),v.ai&&typeof v.ai=="object"&&(s.state.ai={...s.state.ai,...v.ai}),typeof v.nativePostsEnabled=="boolean"&&(s.state.nativePostsEnabled=v.nativePostsEnabled),typeof v.nativePagesEnabled=="boolean"&&(s.state.nativePagesEnabled=v.nativePagesEnabled),typeof v.nativeUsersEnabled=="boolean"&&(s.state.nativeUsersEnabled=v.nativeUsersEnabled),typeof v.nativePluginsEnabled=="boolean"&&(s.state.nativePluginsEnabled=v.nativePluginsEnabled),typeof v.nativeCommentsEnabled=="boolean"&&(s.state.nativeCommentsEnabled=v.nativeCommentsEnabled),typeof v.foldersSharingEnabled=="boolean"&&(s.state.foldersSharingEnabled=v.foldersSharingEnabled),typeof v.developerModeEnabled=="boolean"&&(s.state.developerModeEnabled=v.developerModeEnabled),Array.isArray(v.nativePostsHiddenColumns)&&(s.state.nativePostsHiddenColumns=v.nativePostsHiddenColumns.filter(D=>typeof D=="string"&&D!=="").slice(0,32)),v.itemVisibility&&typeof v.itemVisibility=="object"){const D=["both","dock","desktop","hidden"],I={};for(const[W,z]of Object.entries(v.itemVisibility))typeof W!="string"||W===""||typeof z!="string"||!D.includes(z)||(I[W]=z);s.state.itemVisibility=I}if(Array.isArray(v.dockOrder)&&(s.state.dockOrder=v.dockOrder.filter(D=>typeof D=="string"&&D!=="").slice(0,256)),v.dockPromotedPositions&&typeof v.dockPromotedPositions=="object"){const I={};for(const[W,z]of Object.entries(v.dockPromotedPositions)){if(typeof W!="string"||W===""||!z||typeof z!="object")continue;const q=z;if(!(typeof q.x!="number"||typeof q.y!="number"||!Number.isFinite(q.x)||!Number.isFinite(q.y)||Math.abs(q.x)>1e5||Math.abs(q.y)>1e5)&&(I[W]={x:q.x,y:q.y},Object.keys(I).length>=256))break}s.state.dockPromotedPositions=I}s.save($),(typeof v.wallpaper=="string"||typeof v.accent=="string"||typeof v.dockSize=="string"||typeof v.windowRadius=="string"||typeof v.adminBarMode=="string"||typeof v.desktopLayout=="string"||typeof v.dockPlacement=="string"||typeof v.dockRailRenderer=="string"||typeof v.desktopTheme=="string")&&s.apply(),(v.itemVisibility||v.dockOrder)&&o?.refresh()},deriveWindowId:(v,$)=>ae(v,$??M.adminUrl),listSystemTiles:()=>o?.listSystemTiles()??[],getSystemTile:v=>o?.getSystemTile(v)??null,getMenuItems:()=>o?.getMenuItems()??[],renderIcon:So,applyTileClasses:XL,applyTileElement:ZL,applyTileTooltip:JL,dispatchTileRendered:QL,isDockElement:tT,registerDockSelector:nT,registerTitleBarButton:pi,unregisterTitleBarButton:Yk,listTitleBarButtons:Zk,registerWindowAction:eS,unregisterWindowAction:tS,listWindowActions:oS,registerUnfocusEffect:gi,unregisterUnfocusEffect:RS,listUnfocusEffects:Ma,registerWindowReveal:Fe,unregisterWindowReveal:uv,listWindowReveals:Td,relations:NE,registerWindowLinkRenderer:Up,unregisterWindowLinkRenderer:iS,listWindowLinkRenderers:Fp,registerWindowTheme:gh,unregisterWindowTheme:wh,listWindowThemes:yh,desktopThemes:{list:_v,getActive:Lr,setActive:fa,subscribe:kv,resolveIcon:$s,resolveIconColor:Tr,applyRecommendedOsSettings:v=>{const $=v??Lr()??"";if($==="")return{};const D=xT(s.state,$,{force:!0});return Object.keys(D).length>0&&(s.save(),s.apply()),D}},applyWindowTheme:(v,$)=>{const D=t.getById(v);D&&D.setAppearanceTheme($)},registerWindowControl:go,unregisterWindowControl:_h,listWindowControls:Eh,applyWindowControls:(v,$)=>{const D=t.getById(v);D&&D.setAppearanceControls($)},registerWindowSlot:Ch,unregisterWindowSlot:za,listWindowSlots:Ih,applyWindowSlot:(v,$,D)=>{const I=t.getById(v);I&&I.setAppearanceSlot($,D)},registerWindowNotice:Dh,unregisterWindowNotice:Ka,listWindowNotices:Rh,dismissWindowNotice:SA,undismissWindowNotice:AA,registerWindowChrome:xA,unregisterWindowChrome:Wh,listWindowChromes:$h,applyWindowChrome:(v,$)=>{const D=t.getById(v);D&&D.setAppearanceChrome($)},connect:C,getConnection:w,broadcast:Da,subscribe:wn,registerPalette:sg,unregisterPalette:Wx,listPalettes:$x,openPalette:pl,devtools:Tg,createSharedStore:re,presence:Yx,selection:uL,activity:ke,heartbeat:xe,showToast:X,notify:_a,pwa:{promptInstall:$I,undismissInstallHint:UI,getState:ro,subscribe:vp,requestNotificationPermission:Ok,getNotificationPermission:Mk},renderKeyedList:mT,clearKeyedList:gT,registerNamespace:(v,$)=>{if(typeof v!="string"||v===""){console.warn("[openstation] registerNamespace: name must be a non-empty string");return}if(!$||typeof $!="object"){console.warn(`[openstation] registerNamespace("${v}"): api must be an object`);return}if(LT.has(v)){console.warn(`[openstation] registerNamespace("${v}"): name is reserved by the shell — pick a plugin-specific key`);return}P[v]=$},getWindowConfig:v=>{const $=window.openStationWindowConfig;if(!$||typeof $!="object")return;const D=$[v];return D===void 0?void 0:D},debug:{window:v=>{const $=(M.nativeWindows??[]).find(K=>K.id===v);if(!$)return null;const D=$.scriptUrl||"";let I="unknown",W=!1;D&&(document.querySelector(`script[data-os-vendor="${D.replace(/"/g,'\\"')}"]`)?(I="lazy",W=!0):Array.from(document.querySelectorAll("script[src]")).find(F=>F.src===D)&&(I="eager",W=!0));const z=window.openStationWindowConfig,q=!!(z&&typeof z=="object"&&Object.prototype.hasOwnProperty.call(z,v));return{id:v,scriptHandle:$.scriptHandle||"",scriptUrl:D,loadPath:I,tagInDom:W,configPresent:q,extras:{hasTranslations:!!$.scriptTranslations,l10nCount:($.scriptL10n??[]).length,beforeCount:($.scriptBefore??[]).length,afterCount:($.scriptAfter??[]).length}}}}};return P}function NT(e){if(window.wp||(window.wp={}),!window.wp.os){window.wp.os=e;return}Object.assign(window.wp.os,e)}const Nl=re("desktop-mode/layout",()=>({layout:"classic"}));function Og(e){Nl.state.layout!==e&&(Nl.state.layout=e,Nl.notify())}class Mg{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 DT extends Mg{constructor(t,n){super(t),this.typeSlug=n}type(){return this.typeSlug}}const Mo=new Map,Dl=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.");Mo.set(e.type,{type:e.type,label:e.label,sort:typeof e.sort=="number"?e.sort:100,DesktopFile:e.DesktopFile}),L("os.files.type-registered",e.type,e),Wg()}function RT(e){Mo.delete(e)&&(L("os.files.type-unregistered",e),Wg())}function OT(e){const t=Mo.get(e);return t||null}function Pg(){const e=Array.from(Mo.values()).slice(),t=G("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 xn(e){const t=Mo.get(e.type);return t?.DesktopFile?new t.DesktopFile(e):new DT(e,e.type)}function MT(e){return Dl.add(e),()=>Dl.delete(e)}function Wg(){for(const e of Dl)try{e()}catch(t){console.error("[openstation] files registry subscriber threw:",t)}}const Di=new Map,Rl=new Set;let Ol={};function $g(e){Ol={...e},$l()}function Ml(){return{...Ol}}function He(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.");Di.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}),L("os.files.opener-registered",e.id,e),$l()}function PT(e){Di.delete(e)&&(L("os.files.opener-unregistered",e),$l())}function WT(e){return Di.get(e)??null}function Ug(){const e=Array.from(Di.values()).slice(),t=G("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 Pl(e,t){return Ug().filter(n=>n.types.includes(e)).filter(n=>n.appliesTo?t!==void 0&&n.appliesTo(t):!0)}function Wl(e,t){const n=Pl(e,t);if(n.length===0)return null;const o=Ol[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]),G("os.files.resolve-opener",s,e)??null}function $T(e){return Rl.add(e),()=>Rl.delete(e)}function $l(){for(const e of Rl)try{e()}catch(t){console.error("[openstation] openers subscriber threw:",t)}}let Po=null;function UT(e){Po=e}async function Ri(e,t){if(!Po)return console.warn("[openstation] wp.os.files.open() called before the shell installed open deps. The file will not open."),!1;const n=Wl(e.type(),e);if(!n)return L("os.files.open-failed",{reason:"no-opener",type:e.type(),ref:e.ref()}),!1;L("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):Po.deriveWindowId(s),r=o.title?o.title(e):e.title(),l=e.icon(),a=Po.openUrl({id:i,url:s,title:r,icon:l});return L("os.files.opened",{file:e,openerId:n.id,kind:"url"}),a}if(o.kind==="window"){const s=o.config?o.config(e):void 0,i=Po.openNativeWindow(o.windowId,s);return L("os.files.opened",{file:e,openerId:n.id,kind:"window"}),i}return await o.open(e,t),L("os.files.opened",{file:e,openerId:n.id,kind:"js"}),!0}catch(o){return L("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}}function FT(){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=re("desktop-mode/agents-chat",()=>({activeAgent:null,transcripts:{},conversationIds:{},conversationsRev:0}));function Fg(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 Bg="desktop-mode/v1/agents/conversations";async function Hg(e,t,n={}){const o=await Be(et(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 BT(e){return e.filter(t=>!t.pending)}async function HT(e,t){const n=qe.state,o=BT(n.transcripts[e.id]??[]);if(o.length!==0){n.conversationIds||(n.conversationIds={});try{const s=n.conversationIds[e.id];if(s)await Hg(t,`${Bg}/${s}`,{method:"PUT",body:JSON.stringify({messages:o})});else{const i=await Hg(t,Bg,{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 zg={post:"post",page:"page",attachment:"media",media:"media",user:"user",comment:"comment"};function Gg(e){const t=Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>0?t:0}function jg(e){if(e.type==="shortcut"){const t=e.data;let n=zg[String(t.kind??"")];n==="post"&&t.bridgePayload?.postType==="page"&&(n="page");const o=Gg(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=zg[String(n.type??"")],s=Gg(n.ref);return!o||!s?null:{kind:o,id:s,title:String(n.title??"")||`#${s}`}}return null}function zT(e,t,n){return!t||n&&t.kind==="user"&&t.id===n||e==null?!1:e.length===0?!0:e.includes(t.kind)}function GT(e){return le(k('The user dropped the %1$s "%2$s" (id %3$s) onto you. Handle it according to your instructions, using your tools as needed.',"desktop-mode"),e.kind,e.title,String(e.id))}function jT(e){return{kind:e.kind,id:e.id,title:e.title}}function Vg(e,t="agents"){Fg(e);const n=window.wp?.os?.openWindow;typeof n=="function"&&n("desktop-mode-agent-run",{source:t})}async function VT(e,t,n,o,s){Fg(e);const i=qe.state.transcripts[e.id],r=i.filter(a=>!a.pending&&a.role!=="error").map(a=>({role:a.role,text:a.text}));i.push({role:"user",text:t,at:Date.now(),attachment:s});const l={role:"agent",text:k("Working…","desktop-mode"),at:Date.now(),pending:!0};i.push(l),qe.notify();try{const a=await Be(et(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 a.json().catch(()=>null);if(!a.ok){const u=c&&typeof c=="object"&&typeof c.message=="string"?c.message:`HTTP ${a.status}`;throw new Error(u)}const d=c;l.text=d.text||k("The agent finished without a text answer.","desktop-mode"),l.toolCalls=d.toolCalls,Array.isArray(d.callToActions)&&d.callToActions.length>0&&(l.callToActions=d.callToActions)}catch(a){l.role="error",l.text=a instanceof Error?a.message:String(a)}l.pending=!1,qe.notify(),HT(e,n)}function qT(e,t,n){return Vg(e,"agents-drop"),VT(e,GT(t),n,"drag",jT(t))}let Ul=null;function qg(e){Ul=e}function Wo(){if(!Ul)throw new Error("[openstation] files REST client called before installRestDeps().");return Ul}function KT(){return Wo()}class Fl 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 fe(e,t){const{baseUrl:n,nonce:o}=Wo(),s=et(n,e),i=new Headers(t.headers??{});i.set("X-WP-Nonce",o),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Be(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/files"}),l=await r.text();let a=null,c=null;if(l)try{a=JSON.parse(l)}catch(d){a=null,c=d}if(!r.ok){if(r.status===409){const u=a?.data?.data??a?.data;if(u&&typeof u=="object")throw new Fl(u)}const d=a;throw new Error(`[openstation] files REST ${r.status}: ${d?.code??""} ${d?.message??""}`.trim())}if(a===null){if(c&&l){const d=l.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 a}function Te(e=0){return fe(`/placements?folder=${encodeURIComponent(String(e))}`,{method:"GET"})}function Ln(e){return fe("/placements",{method:"POST",body:JSON.stringify(e)})}function Tn(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),fe(`/placements/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Bl(e){return fe(`/placements/${e}`,{method:"DELETE"})}async function Oi(e,t){const{baseUrl:n,nonce:o}=Wo(),i=`${n.replace(/\/files\/?$/,"")}/recycle-bin/restore`,r=await Be(i,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":o},credentials:"same-origin",body:JSON.stringify({items:[{id:e,type:t}]})},{source:"desktop-mode/files"});if(!r.ok)throw new Error(`[openstation] restore ${r.status}`);return await r.json()}function Hl(){return fe("/folders",{method:"GET"})}function zl(e){return fe("/folders",{method:"POST",body:JSON.stringify(e)})}function Kg(e,t,n){const o={};return typeof n=="number"&&n>0&&(o["If-Match"]=String(n)),fe(`/folders/${e}`,{method:"PATCH",body:JSON.stringify(t),headers:o})}function Gl(e){return fe(`/folders/${e}`,{method:"DELETE"})}function Yg(e){return fe("/associations",{method:"PUT",body:JSON.stringify({associations:e})})}function Xg(e){return fe(`/folders/${e}/shares`,{method:"GET"})}function Zg(e,t){return fe(`/folders/${e}/shares`,{method:"POST",body:JSON.stringify(t)})}function Jg(e,t,n){return fe(`/folders/${e}/shares/${t}`,{method:"PATCH",body:JSON.stringify({capability:n})})}function Qg(e,t){return fe(`/folders/${e}/shares/${t}`,{method:"DELETE"})}function ew(e,t){return fe(`/folders/${e}/shares/${t}/accept`,{method:"POST"})}function tw(e,t){return fe(`/folders/${e}/shares/${t}/deny`,{method:"POST"})}function nw(e){return fe(`/folders/${e}/leave`,{method:"POST"})}function YT(){return fe("/folder-sharing-tables/purge",{method:"POST"})}function ow(e){return fe(`/uploads/${e}/shares`,{method:"GET"})}function sw(e,t){return fe(`/uploads/${e}/shares`,{method:"POST",body:JSON.stringify({userId:t})})}function iw(e,t){return fe(`/uploads/${e}/shares/${t}`,{method:"DELETE"})}function rw(e,t){return fe(`/uploads/${e}/shares/${t}/accept`,{method:"POST"})}function aw(e,t){return fe(`/uploads/${e}/shares/${t}/deny`,{method:"POST"})}function lw(e){return fe(`/uploads/${e}/leave`,{method:"POST"})}function XT(e,t){return fe(`/uploads/${e}`,{method:"PATCH",body:JSON.stringify({name:t})})}function cw(e,t){return fe("/uploads/paths",{method:"POST",body:JSON.stringify({parentId:e,relativePath:t})})}function zt(e){const{baseUrl:t,nonce:n}=Wo(),o=et(t,`/uploads/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}function dw(e){const{baseUrl:t,nonce:n}=Wo(),o=et(t,`/folders/${e}/download`);return`${o}${o.includes("?")?"&":"?"}_wpnonce=${encodeURIComponent(n)}`}const ZT=Object.freeze(Object.defineProperty({__proto__:null,FilesConflictError:Fl,acceptFileShare:rw,acceptShare:ew,createFolder:zl,createPlacement:Ln,deleteFolder:Gl,deletePlacement:Bl,denyFileShare:aw,denyShare:tw,ensureUploadPath:cw,getFilesRestDeps:KT,getFolderZipUrl:dw,getUploadDownloadUrl:zt,installRestDeps:qg,inviteFileShare:sw,inviteShare:Zg,leaveFileShare:lw,leaveShare:nw,listFileShares:ow,listFolders:Hl,listPlacements:Te,listShares:Xg,purgeFolderSharingTables:YT,renameUpload:XT,restoreTrashedItem:Oi,revokeFileShare:iw,revokeShare:Qg,saveAssociations:Yg,updateFolder:Kg,updatePlacement:Tn,updateShareCapability:Jg},Symbol.toStringTag,{value:"Module"})),JT="desktop-mode/files";function ft(){return re(JT,()=>({placementsByFolder:new Map,folders:new Map,hydratedFolders:new Set}))}function Nn(e){typeof document>"u"||document.dispatchEvent(new CustomEvent("os-files-changed",{detail:{source:"local",...e}}))}function pt(e,t){const n=ft(),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(),Nn({kind:"placements-set",folderId:e})}function Mi(e,t="local"){if(!e||typeof e.id!="number"){console.warn("[openstation] upsertPlacement called with a non-placement value; ignoring.",e);return}const n=ft(),o=new Map(n.state.placementsByFolder);for(const[l,a]of o)if(a.findIndex(d=>d&&d.id===e.id)>=0&&l!==e.parentId){const d=a.filter(Boolean),u=d.findIndex(f=>f.id===e.id);u>=0&&d.splice(u,1),o.set(l,d)}const i=(o.get(e.parentId)?.slice()??[]).filter(Boolean),r=i.findIndex(l=>l.id===e.id);r>=0?i[r]=e:i.push(e),o.set(e.parentId,i),n.state={...n.state,placementsByFolder:o},n.notify(),Nn({kind:"placement-upserted",placementId:e.id,folderId:e.parentId,source:t})}function $o(e,t="local"){const n=ft(),o=new Map(n.state.placementsByFolder);let s;for(const[i,r]of o)if(r.findIndex(a=>a&&a.id===e)>=0){const a=r.filter(Boolean).filter(c=>c.id!==e);o.set(i,a),s=i}s!==void 0&&(n.state={...n.state,placementsByFolder:o},n.notify(),Nn({kind:"placement-removed",placementId:e,folderId:s,source:t}))}function Pi(e){const t=ft(),n=new Map;for(const o of e)n.set(o.id,o);t.state={...t.state,folders:n},t.notify(),Nn({kind:"folders-set"})}function jl(e,t="local"){const n=ft(),o=new Map(n.state.folders);o.set(e.id,e),n.state={...n.state,folders:o},n.notify(),Nn({kind:"folder-upserted",folderRowId:e.id,source:t})}function Vl(e,t="local"){const n=ft(),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(),Nn({kind:"folder-removed",folderRowId:e,source:t})}function ql(e){return ft().subscribe(e)}function At(){return ft().getState()}function uw(e){const t=At(),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 Q={getState:At,subscribe:ql,setFolderPlacements:pt,upsertPlacement:Mi,upsertFolder:jl,removePlacement:$o,removeFolder:Vl,currentPlacement:uw},QT=ce`:host{display:inline-block}`,eN=ce`:host{position:absolute;width:var( --os-ui-ribbon-size,90px );height:var( --os-ui-ribbon-size,90px );overflow:hidden;pointer-events:none;z-index:var( --os-ui-ribbon-z,2 )}:host( [ hidden ] ){display:none}.banner{position:absolute;display:block;width:var( --os-ui-ribbon-banner-width,140px );padding:var( --os-ui-ribbon-padding,4px 0 );text-align:center;font:var( --os-ui-ribbon-font,700 10px/1.4 var( --os-font,system-ui ) );letter-spacing:var( --os-ui-ribbon-tracking,0.06em );text-transform:uppercase;color:var( --os-ui-ribbon-fg,var( --os-ui-fg-on-accent,#fff ) );background:var( --os-ui-ribbon-bg,var( --wp-admin-theme-color,#2271b1 ) );background-size:260% 260%;background-position:30% 40%;box-shadow:var( --os-ui-ribbon-shadow,0 2px 4px rgba( 0,0,0,0.2 ) )}:host(:not( [ placement ] ) ),:host( [ placement='top-end' ] ){inset-block-start:0;inset-inline-end:0}:host(:not( [ placement ] ) ) .banner,:host( [ placement='top-end' ] ) .banner{inset-block-start:var( --os-ui-ribbon-banner-offset,20px );inset-inline-end:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host( [ placement='top-start' ] ){inset-block-start:0;inset-inline-start:0}:host( [ placement='top-start' ] ) .banner{inset-block-start:var( --os-ui-ribbon-banner-offset,20px );inset-inline-start:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-end' ] ){inset-block-end:0;inset-inline-end:0}:host( [ placement='bottom-end' ] ) .banner{inset-block-end:var( --os-ui-ribbon-banner-offset,20px );inset-inline-end:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( -45deg )}:host( [ placement='bottom-start' ] ){inset-block-end:0;inset-inline-start:0}:host( [ placement='bottom-start' ] ) .banner{inset-block-end:var( --os-ui-ribbon-banner-offset,20px );inset-inline-start:var( --os-ui-ribbon-banner-pull,-36px );transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host(:not( [ placement ] ) ) .banner,:host-context( [ dir='rtl' ] ):host( [ placement='top-end' ] ) .banner{transform:rotate( -45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='top-start' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-end' ] ) .banner{transform:rotate( 45deg )}:host-context( [ dir='rtl' ] ):host( [ placement='bottom-start' ] ) .banner{transform:rotate( -45deg )}:host( [ tone='success' ] ) .banner{background:var( --os-ui-ribbon-success,var( --os-ui-success-fg,#1a7f37 ) )}:host( [ tone='warning' ] ) .banner{background:var( --os-ui-ribbon-warning,var( --os-ui-warning-bg,#9a6700 ) )}:host( [ tone='danger' ] ) .banner{background:var( --os-ui-ribbon-danger,var( --os-ui-danger,#cf222e ) )}:host( [ tone='info' ] ) .banner{background:var( --os-ui-ribbon-info,var( --os-ui-info-bg,#0969da ) )}:host( [ tone='neutral' ] ) .banner{background:var( --os-ui-ribbon-neutral,var( --os-ui-surface,#57606a ) )}`,ps=class ps extends Ee{render(){return j`<span class="banner" part="banner"><slot></slot></span>`}};ps.props=["placement","tone"],ps.styles=[eN],ps.help=void 0;let Kl=ps;Ie("os-ribbon",Kl);const ie="os-file-tile",fw={draft:"Draft",pending:"Pending",private:"Private",future:"Scheduled"};function tN(){const e=window.wp?.os?.getOsSettings;if(typeof e!="function")return!0;try{return e()?.showPostStatusRibbons!==!1}catch{return!0}}function nN(){return window.wp?.os?.dragManager??null}const oN=["type","ref","label","icon","thumbnail","kind","status","selected","selectable","missing","access-gated","drag-kind","drag-title","drag-icon"],Hn=class Hn extends Ee{constructor(){super(...arguments),this._pointerdownHandler=null,this._keydownHandler=null}connectedCallback(){super.connectedCallback(),this._keydownHandler||(this._keydownHandler=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),this.click())},this.addEventListener("keydown",this._keydownHandler)),this._paint()}disconnectedCallback(){this._pointerdownHandler&&(this.removeEventListener("pointerdown",this._pointerdownHandler),this._pointerdownHandler=null),this._keydownHandler&&(this.removeEventListener("keydown",this._keydownHandler),this._keydownHandler=null)}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",l=this.getAttribute("status")??"",a=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`),a&&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",a?"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=So(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(l&&l!=="publish"&&fw[l]&&tN()){const b=document.createElement("os-ribbon");b.setAttribute("placement","top-end"),b.setAttribute("tone",sN(l)),b.textContent=fw[l],this.appendChild(b)}vb(this),L("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=nN();if(!s)return;const i=this.getAttribute("ref")??"",r=this.getAttribute("drag-title")??this.getAttribute("label")??void 0,l=this.getAttribute("drag-icon")??this.getAttribute("icon")??void 0,a=this.getBoundingClientRect();s.start({payload:{type:"shortcut",source:this,data:{kind:t,ref:i,title:r,icon:l},ghost:{offsetX:o.clientX-a.left,offsetY:o.clientY-a.top}},origin:o})};this._pointerdownHandler=n,this.addEventListener("pointerdown",n)}};Hn.shadow=!1,Hn.props=oN,Hn.styles=[QT],Hn.help=void 0;let Yl=Hn;function sN(e){switch(e){case"draft":return"warning";case"pending":return"info";case"private":return"danger";case"future":return"primary";default:return"primary"}}Ie("os-tile",Yl);function iN(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=G("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 rN(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 pw(e){const t=e.meta&&typeof e.meta.name=="string"?e.meta.name.trim():"";return t!==""?t:xn(e.file).title()}function aN(e,t){const n=xn(e.file),o=n.previewUrl(),s=pw(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:dm(e.file.ref)||i||$s(Cv(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 lN(e,t){const n=iN(aN(e,t)),o=G("os.files.tile-class",ie,e);o&&o!==ie&&(n.className=o);const s=G("os.files.tile-element",null,e);return s instanceof Element&&n.appendChild(s),n.addEventListener("dblclick",i=>{i.preventDefault(),i.stopPropagation();const r=uw(e),l=xn(r.file);if(r.accessGated){X({message:`You don’t have permission to open "${r.file.title||l.title()}". Ask the folder owner if you need access to this item.`,duration:6e3});return}Ri(l,{placement:{id:r.id,x:r.x,y:r.y,meta:r.meta}})}),L("os.files.tile-rendered",{tile:n,placement:e}),n}function ht(e,t,n){e.style.left=`${t}px`,e.style.top=`${n}px`}const Uo=new Map;function Wi(e,t){const n=Uo.get(e);return n?n.push(t):Uo.set(e,[t]),()=>{const o=Uo.get(e);if(!o)return;const s=o.indexOf(t);s!==-1&&o.splice(s,1),o.length===0&&Uo.delete(e)}}function Xl(e,t){const n=Uo.get(e);if(n)return n.find(o=>o.appliesTo(t))}function cN(e,t){return Xl(e,t)?.acceptLabel}function dN(e,t){const n=Xl(e.type,t);return n?n.accept(e.data,t):!1}function uN(e,t,n){const o=Xl(e.payload.type,n);return o?(o.onDrop(e,t,n),!0):!1}function fN(e,t,n){const o=t.slice().sort((s,i)=>{const r=typeof s.sort=="number"?s.sort:100,l=typeof i.sort=="number"?i.sort:100;return r!==l?r-l:s.label.localeCompare(i.label)});o.length!==0&&lL(e,{actions:o,scope:"files.tile",dataset:{placementId:String(n.placementIds[0]??""),placementIds:n.placementIds.join(",")},onOpened:s=>{L("os.files.tile-menu.opened",{placementId:n.placementIds[0],placementIds:n.placementIds.slice(),items:s})},onClosed:()=>{L("os.files.tile-menu.closed",{})}})}function Zl(e){const t=e.value;return typeof t=="string"?t:e.getAttribute("value")??e.shadowRoot?.querySelector("input")?.value??""}function Gt(e,t){e.disabled=t,t?e.setAttribute("disabled",""):e.removeAttribute("disabled")}function $i(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 Fo=null;function Jl(){Fo&&(Fo.dispatchEvent(new CustomEvent("create-folder-dialog-closed")),Fo.remove(),Fo=null,L("os.files.create-folder.closed",{}))}function Ql(e){if(Jl(),G("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 l=document.createElement("p");l.className=`${Me}__error`,l.hidden=!0,l.setAttribute("role","alert"),s.appendChild(l);const a=document.createElement("div");a.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",a.appendChild(c),a.appendChild(d),s.appendChild(a),o.appendChild(s),document.body.appendChild(o),Fo=o,$i(r),L("os.files.create-folder.opened",{});const u=h=>{Gt(r,h),Gt(c,h),Gt(d,h),s.classList.toggle(`${Me}--busy`,h)},f=h=>{l.textContent=h,l.hidden=!1},p=()=>{Jl(),e.onCancel?.()},g=async()=>{const h=Zl(r).trim();if(!h){f("Please enter a name."),$i(r);return}l.hidden=!0,u(!0);try{await e.onSubmit(h),Jl()}catch(b){u(!1),f(b instanceof Error?b.message:"Could not create the folder."),$i(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 Ui(e){const t=e.meta;if(!t||typeof t!="object")return null;const n=t.__synthFromDockItem;return typeof n=="string"&&n!==""?n:null}function pN(e){return e.id<=0||Ui(e)!==null}function hw(e){if(e.length===0)return;const t=window.wp?.os;if(!t?.getOsSettings||!t?.updateOsSettings)return;const n={...t.getOsSettings().itemVisibility??{}};for(const o of e)n[o]="dock";t.updateOsSettings({itemVisibility:n})}function Dn(e,t,n){window.wp?.os?.broadcast?.(`os.${e}.changed`,{source:"desktop-files",action:t,ids:n})}function Fi(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 ec(e,t){const n=window.wp?.os;n?.showToast&&n.showToast({message:e,duration:6e3,action:{label:"Undo",onClick:t}})}async function mw(e){const t=e.id,n=e.parentId,o=e.file?.title??"Item",s=e.file?.type==="shortcut"?"shortcut":"placement";Q.removePlacement(t);try{await Bl(t),Dn(s,"trashed",[t]),ec(`"${o}" moved to Trash`,async()=>{try{await Oi(t,"placement");const i=await Te(n);Q.setFolderPlacements(n,i.placements),Dn(s,"untrashed",[t])}catch(i){console.error("[openstation] restore failed:",i)}})}catch(i){console.error("[openstation] deletePlacement failed:",i),Fi(i),Te(n).then(r=>{Q.setFolderPlacements(n,r.placements)})}}async function gw(e){const t=parseInt(e.file.ref,10);if(!t)return;const n=e.id,o=e.parentId,s=e.file?.title??"Folder";Q.removePlacement(n),Q.removeFolder(t);try{await Gl(t),Dn("folder","trashed",[t]),ec(`"${s}" moved to Trash`,async()=>{try{await Oi(t,"folder");const i=await Te(o);Q.setFolderPlacements(o,i.placements),Dn("folder","untrashed",[t])}catch(i){console.error("[openstation] restore folder failed:",i)}})}catch(i){console.error("[openstation] deleteFolder failed:",i),Fi(i),Te(o).then(r=>{Q.setFolderPlacements(o,r.placements)})}}async function ww(e){if(e.length===0)return;if(e.length===1)return hN(e[0]);const t=new Set;for(const a of e)if(t.add(a.parentId),Q.removePlacement(a.id),a.file?.type==="folder"){const c=parseInt(a.file.ref,10);c&&Q.removeFolder(c)}const n=async()=>{for(const a of t)try{const c=await Te(a);Q.setFolderPlacements(a,c.placements)}catch(c){console.error("[openstation] files: re-hydrate failed:",c)}},o=await Promise.allSettled(e.map(async a=>{if(a.file?.type==="folder"){const c=parseInt(a.file.ref,10);if(!c)throw new Error("folder placement without a folder id");return await Gl(c),{id:c,kind:"folder",restoreId:c,restoreKind:"folder"}}return await Bl(a.id),{id:a.id,kind:a.file?.type==="shortcut"?"shortcut":"placement",restoreId:a.id,restoreKind:"placement"}})),s=[];let i=0;for(const a of o)a.status==="fulfilled"?s.push(a.value):(i+=1,console.error("[openstation] trash (bulk) failed for one item:",a.reason));if(i>0&&n(),s.length===0){Fi(o.find(a=>a.status==="rejected")?.reason);return}for(const a of["placement","shortcut","folder"]){const c=s.filter(d=>d.kind===a).map(d=>d.id);c.length>0&&Dn(a,"trashed",c)}const r=s.length===1?"item":"items",l=i>0?`${s.length} ${r} moved to Trash · ${i} could not be moved`:`${s.length} ${r} moved to Trash`;ec(l,async()=>{const a=await Promise.allSettled(s.map(u=>Oi(u.restoreId,u.restoreKind)));await n();const c=s.filter((u,f)=>a[f].status==="fulfilled"),d=s.length-c.length;for(const u of a)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&&Dn(u,"untrashed",f)}d>0&&Fi(new Error(`${d} of ${s.length} items could not be restored.`))})}function hN(e){return e.file?.type==="folder"?gw(e):mw(e)}const mN=5,yw=e=>ww(e);async function gN(e){if(!(e.length>mN&&!await Ni({title:`Open ${e.length} items?`,message:`This opens ${e.length} windows at once.`,confirmLabel:"Open all"})))for(const t of e)await Ri(xn(t.file))}function wN(e){const t=parseInt(e.file.ref,10);t&&Ql({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}};Q.upsertPlacement(i);try{const r=Q.getState().folders.get(t)?.updatedAtMs??0,l=await Kg(t,{name:o},r);Q.upsertFolder(l);const a=await Te(e.parentId);Q.setFolderPlacements(e.parentId,a.placements)}catch(r){console.error("[openstation] rename folder failed:",r),Q.upsertPlacement({...e,file:{...e.file,title:s}})}}})}function yN(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 bN(e){const t=[{id:"open",label:"Open",icon:"dashicons-external",sort:10,multi:!0,bulkLabel:i=>`Open ${i} items`,bulk:i=>gN(i),onClick:()=>{Ri(xn(e.file))}}];if(e.file.type==="post"&&t.push({id:"navigate-into",label:"Navigate into",icon:"dashicons-category",sort:20,onClick:()=>yN(e)}),e.file.type==="folder")t.push({id:"rename-folder",label:"Rename…",icon:"dashicons-edit",sort:30,onClick:()=>wN(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:yw,onClick:()=>gw(e)});else{const i=Ui(e),r=e.file.type==="shortcut";if(i||r){const l=i??e.file.ref;t.push({id:"hide-from-desktop",label:"Hide from desktop",icon:"dashicons-hidden",sort:90,multi:!0,bulkLabel:a=>`Hide ${a} items from desktop`,bulk:a=>{hw(a.map(c=>Ui(c)??c.file.ref).filter(c=>!!c))},onClick:()=>hw([l])})}else e.canTrash!==!1&&t.push({id:"remove",multiId:"trash",label:"Move to Trash",icon:"dashicons-trash",sort:90,danger:!0,multi:!0,bulkLabel:l=>`Move ${l} items to Trash`,bulk:yw,onClick:()=>mw(e)})}const o=G("os.files.tile-menu",t,e);return Array.isArray(o)?o:t}const ze=16,vN=88,_N=104,EN=20,kN=16,Ct=vN+EN,Rn=_N+kN;function Bo(e,t){const n=Math.max(0,Math.round((e-ze)/Ct)),o=Math.max(0,Math.round((t-ze)/Rn));return On(n,o)}function On(e,t){return{col:e,row:t,x:ze+e*Ct,y:ze+t*Rn}}function It(e,t,n,o){const s=Bo(e,t);if(!n.has(ve(s.col,s.row)))return s;const i=o?Math.max(1,Math.floor((o.clientHeight-ze)/Rn)):999;for(let r=0;r<999;r++)for(let l=0;l<i;l++)if(!n.has(ve(r,l)))return On(r,l);return s}function tc(e,t){const n=t?Math.max(1,Math.floor((t.clientWidth-ze)/Ct)):4,o=Math.max(1,n);for(let s=0;s<999;s++)for(let i=0;i<o;i++)if(!e.has(ve(i,s)))return On(i,s);return On(0,0)}function bw(e,t){const n=new Set;for(const o of e){const s=Bo(o.x,o.y);n.add(ve(s.col,s.row))}return n}function ve(e,t){return`${e},${t}`}function vw(e){return e instanceof Fl}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 _w(e){const t=SN(e),n=e.detail.current.parentId;let o;n>0&&(o={label:"View folder",onClick:()=>{const s=`os-folder-${n}`,i=window.openStation?.windowManager;i?.focus&&i.focus(s)||i?.open&&i.open(s)}}),X({message:t,action:o,duration:7e3})}const Ho=new Map;function Ew(e,t){return Ho.set(e,t),()=>{Ho.get(e)===t&&Ho.delete(e)}}function AN(e,t){const n=Ho.get(e.type);return n?n.accept(e.data,t):!1}function CN(e,t,n){const o=Ho.get(e.payload.type);return o?(o.onDrop(e,t,n),!0):!1}function Mn(e){const t=e.placements;return Array.isArray(t)&&t.length>0?t:e.placement?[e.placement]:[]}function Bi(e){const t=e.items;return Array.isArray(t)&&t.length>0?t:e.ref?[e]:[]}function IN(e){const t=e.file;if(!t)return;const n=parseInt(String(t.ref??""),10);if(!Number.isFinite(n)||n<=0)return;const o=String(t.title??"");if(t.type==="attachment"){const s=String(t.sourceUrl??t.previewUrl??"");return{kind:"attachment",id:n,url:s,title:o,alt:String(t.alt??""),mime:String(t.mime??""),thumbnailUrl:t.previewUrl?String(t.previewUrl):void 0}}if(t.type==="post")return{kind:"post",id:n,postType:String(t.postType??"post"),url:String(t.link??""),title:o};if(t.type==="user")return{kind:"user",id:n,url:String(t.link??""),title:o}}function zo(){return window.wp?.os?.dragManager??null}const xN="os-files-layer";function LN(e){if(e!==0)return null;const t=window.openStationConfig,n=t?.filesBootPlacements;return!t||!Array.isArray(n)?null:(delete t.filesBootPlacements,n)}function kw(e,t=0){const n=document.createElement("div");n.className=xN,n.setAttribute("role","list"),n.dataset.folderId=String(t),e.appendChild(n);let o="";const s=x=>{const F=Q.getState().placementsByFolder.get(t)??[],R=new Map;for(const S of F)S&&R.set(String(S.id),S);return x.map(S=>R.get(S)).filter(S=>!!S)},i=new Set,r=new Set,l=oL(n,{itemSelector:`.${ie}`,background:e,surface:"files",scope:String(t),keyOf:x=>x.dataset.placementId??null,onChange:x=>{const F=s(x),R=F.length===1?F[0]:null;for(const S of i)try{S(R)}catch(O){console.error("[openstation] files: selection listener threw:",O)}for(const S of r)try{S(F)}catch(O){console.error("[openstation] files: selection listener threw:",O)}}}),a=()=>s(l.keys()),c=x=>{const F=new Map,R=new Set;let S=0;for(const U of x){if(!Pe(U))continue;const N=On(0,S);F.set(U.id,{x:N.x,y:N.y}),R.add(ve(N.col,N.row)),S+=1}const O=new Map;for(const U of x){if(F.has(U.id))continue;const N=Bo(U.x,U.y),H=ve(N.col,N.row);if(!R.has(H)){R.add(H);continue}const Z=It(U.x,U.y,R,e);R.add(ve(Z.col,Z.row)),O.set(U.id,{x:Z.x,y:Z.y})}return{pinnedSlots:F,displaced:O}},d=(x,F,R,S)=>{const O=R.get(F.id),U=S.get(F.id);O?ht(x,O.x,O.y):U?ht(x,U.x,U.y):ht(x,F.x,F.y)},u=(x,F,R)=>{const S=lN(x,t),O=F.get(x.id);if(O){if(ht(S,O.x,O.y),S.classList.add(`${ie}--pinned`),xw(S,x,l,a),Sw(x)){const N=zo();N&&h.set(x.id,Iw(N,S,x))}return S}const U=R.get(x.id);if(U&&ht(S,U.x,U.y),MN(S,x,t,l,a),xw(S,x,l,a),x.file.type==="folder"){const N=parseInt(x.file.ref,10);if(N>0){const H=zo();if(H){const Z=ON(H,S,N);m.set(x.id,Z)}}}else if(Sw(x)){const N=zo();N&&h.set(x.id,Iw(N,S,x))}return S},f=x=>{const F=new Map;for(const U of n.querySelectorAll("[data-placement-id]")){const N=U.dataset.placementId??"",H=parseInt(N,10);if(N===""||Number.isNaN(H)&&N!=="-0")return!1;F.set(H,U)}const R=new Set;for(const U of x)R.add(U.id);for(const U of x){const N=F.get(U.id);if(!N)continue;if(N.dataset.fileType!==U.file.type||N.dataset.fileRef!==U.file.ref||N.classList.contains(`${ie}--pinned`)!==Pe(U))return!1}for(const[U,N]of F){if(R.has(U))continue;const H=m.get(U);if(H){try{H()}catch{}m.delete(U)}const Z=h.get(U);if(Z){try{Z()}catch{}h.delete(U)}N.remove()}const{pinnedSlots:S,displaced:O}=c(x);for(const U of x){const N=F.get(U.id);if(N){d(N,U,S,O),Cw(N,U);continue}n.appendChild(u(U,S,O))}return l.refresh(),L("os.files.grid-rendered",{folderId:t,count:x.length}),!0},p=x=>{const R=(x.placementsByFolder.get(t)??[]).slice().sort((N,H)=>{const Z=Pe(N)?0:1,se=Pe(H)?0:1;return Z-se}),S=TN(R);if(S===o||(o=S,RN(R,n,e))||f(R))return;n.replaceChildren();for(const[,N]of m)try{N()}catch{}m.clear();for(const[,N]of h)try{N()}catch{}h.clear();const{pinnedSlots:O,displaced:U}=c(R);for(const N of R)n.appendChild(u(N,O,U));l.refresh(),L("os.files.grid-rendered",{folderId:t,count:R.length})},g=[],m=new Map,h=new Map;let b=null,y=null;const C=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 R=x.payload.ghost,S=R?.offsetX??0,O=R?.offsetY??0,N=x.payload.data?.placement?.id,H=(oe,_e)=>{const pe=n.getBoundingClientRect(),ye=Math.max(0,oe-pe.left-S),he=Math.max(0,_e-pe.top-O),Ae=Q.getState().placementsByFolder.get(t)??[],As=Go(Ae,N),Ue=It(ye,he,As,e);F.style.transform=`translate3d(${Ue.x}px, ${Ue.y}px, 0)`},Z=x.payload.source.getBoundingClientRect();H(Z.left+S,Z.top+O);const se=oe=>{H(oe.clientX,oe.clientY)};document.addEventListener("pointermove",se),y=se},w=()=>{y&&(document.removeEventListener("pointermove",y),y=null),b&&(b.remove(),b=null)},E={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 R of Mn(F)){if(R.file?.type!=="folder")continue;const S=parseInt(R.file.ref,10);if(!Number.isNaN(S)&&Aw(S,t))return!1}}return!0},onEnter:x=>{e.setAttribute("data-files-drop-active",""),(x.payload.type==="desktop-file"||x.payload.type==="shortcut")&&C(x)},onLeave:()=>{e.removeAttribute("data-files-drop-active"),w()},onDrop:(x,F)=>{if(e.removeAttribute("data-files-drop-active"),w(),x.payload.type!=="desktop-file"&&x.payload.type!=="shortcut"){CN(x,F,{folderId:t,host:e});return}const R=n.getBoundingClientRect(),S=x.payload.ghost,O=S?.offsetX??0,U=S?.offsetY??0,N=Math.max(0,F.clientX-R.left-O),H=Math.max(0,F.clientY-R.top-U),Z=Q.getState().placementsByFolder.get(t)??[];if(x.payload.type==="desktop-file"){const se=x.payload.data,oe=Mn(se),_e=new Set(oe.map(he=>he.id)),pe=Go(Z,_e),ye=It(N,H,pe,e);pe.add(ve(ye.col,ye.row));for(const he of oe){let Ae=ye;if(he.id!==se.placement.id){const Ue=he.x-se.placement.x,ab=he.y-se.placement.y;Ae=It(Math.max(0,ye.x+Ue),Math.max(0,ye.y+ab),pe,e),pe.add(ve(Ae.col,Ae.row))}const As={...he,x:Ae.x,y:Ae.y,parentId:t};if(Q.upsertPlacement(As),L("os.files.tile-manually-placed",{folderId:t,placementId:he.id}),Hi(he)){const Ue=Ui(he);Ue&&DN(Ue,Ae.x,Ae.y);continue}Tn(he.id,{x:Ae.x,y:Ae.y,parentId:t},he.updatedAtMs).then(Ue=>{Q.upsertPlacement(Ue,"remote")}).catch(Ue=>{vw(Ue)?_w(Ue):console.error("[openstation] files: drag persist failed",Ue),Q.upsertPlacement(he)})}return}if(x.payload.type==="shortcut"){const se=x.payload.data,oe=Go(Z);for(const _e of Bi(se)){const pe=tc(oe,e);oe.add(ve(pe.col,pe.row)),Ln({parentId:t,type:_e.kind,ref:_e.ref,x:pe.x,y:pe.y}).then(ye=>{Q.upsertPlacement(ye),L("os.files.shortcut-dropped",{folderId:t,placement:ye})}).catch(ye=>{console.error("[openstation] shortcut drop failed:",ye)})}}}},T=zo();if(T&&g.push(T.registerDropTarget(E)),!Q.getState().hydratedFolders.has(t)){const x=LN(t);x&&Q.setFolderPlacements(t,x)}p(Q.getState()),queueMicrotask(()=>W());const M=Q.subscribe(x=>{p(x),W()});let P=()=>{};const v=new Promise(x=>{P=x});Q.getState().hydratedFolders.has(t)?queueMicrotask(P):Te(t).then(x=>{Q.setFolderPlacements(t,x.placements)}).catch(x=>{console.error("[openstation] files: failed to hydrate folder",t,x)}).finally(()=>{P()});const $=()=>{const x=e.clientWidth>0?e.clientWidth:4*Ct;return Math.max(1,Math.floor((x-ze)/Ct))},D=(x,F)=>{const R=x.slice();switch(F){case"name-asc":R.sort((S,O)=>S.file.title.localeCompare(O.file.title));break;case"name-desc":R.sort((S,O)=>O.file.title.localeCompare(S.file.title));break;case"date-asc":R.sort((S,O)=>S.updatedAtMs-O.updatedAtMs);break;case"date-desc":R.sort((S,O)=>O.updatedAtMs-S.updatedAtMs);break}return R},I=x=>{const F=Q.getState().placementsByFolder.get(t);if(!F||F.length===0)return;const R=F.filter(se=>Pe(se)),S=F.filter(se=>!Pe(se)),O=D(S,x),U=$(),N=new Set;for(let se=0;se<R.length;se+=1)N.add(ve(0,se));let H=0;const Z=()=>{for(;;){const se=Math.floor(H/U),oe=H%U;if(H+=1,!N.has(ve(oe,se)))return{col:oe,row:se}}};O.forEach((se,oe)=>{const _e=Z(),pe=ze+_e.col*Ct,ye=ze+_e.row*Rn,he={...se,x:pe,y:ye,sortOrder:oe};Q.upsertPlacement(he),!Hi(se)&&Tn(se.id,{x:pe,y:ye,sortOrder:oe}).catch(Ae=>{console.error("[openstation] files: sort persist failed",Ae)})})},W=()=>{const x=Q.getState().placementsByFolder.get(t);if(!x||x.length===0)return;const F=e.clientWidth>0?e.clientWidth:1/0,R=e.clientHeight>0?e.clientHeight:1/0;if(!x.some(oe=>oe.x+Ct>F||oe.y+Rn>R))return;const O=$(),U=x.filter(oe=>Pe(oe)),N=x.filter(oe=>!Pe(oe)),H=new Set;for(let oe=0;oe<U.length;oe+=1)H.add(ve(0,oe));let Z=0;const se=()=>{for(;;){const oe=Math.floor(Z/O),_e=Z%O;if(Z+=1,!H.has(ve(_e,oe)))return{col:_e,row:oe}}};for(const oe of N){const _e=se(),pe=ze+_e.col*Ct,ye=ze+_e.row*Rn,he=n.querySelector(`[data-placement-id="${oe.id}"]`);he&&ht(he,pe,ye)}};let z=e.clientWidth,q=e.clientHeight,K=null;return typeof ResizeObserver<"u"&&(K=new ResizeObserver(()=>{const x=e.clientWidth,F=e.clientHeight;x===z&&F===q||(z=x,q=F,W())}),K.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:a,selectAll:()=>l.model.selectAll(),clearSelection:()=>l.model.clear(),sort:I,reflow:W,hydrated:v,dispose(){M(),K?.disconnect(),K=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(),l.destroy(),i.clear(),r.clear(),n.remove()}}}function TN(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 Hi(e){return pN(e)}const NN="desktop-mode-recycle-bin";function Sw(e){return!(e.file?.type==="folder"||e.file?.ref===NN)}function Go(e,t){const n=typeof t=="number"?new Set([t]):t??null,o=e.slice().sort((r,l)=>{const a=Pe(r)?0:1,c=Pe(l)?0:1;return a-c}),s=new Set;let i=0;for(const r of o)if(!n?.has(r.id))if(Pe(r))s.add(ve(0,i)),i+=1;else{const l=Bo(r.x,r.y);s.add(ve(l.col,l.row))}return s}function Aw(e,t){if(t<=0||e<=0)return!1;if(e===t)return!0;const n=new Map,o=Q.getState();for(const l of o.placementsByFolder.values())for(const a of l){if(a.file?.type!=="folder")continue;const c=parseInt(a.file.ref,10);Number.isNaN(c)||c<=0||n.has(c)||n.set(c,a.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 l=n.get(i);if(l===void 0)return!1;i=l}return!1}function DN(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 RN(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 l=0;for(const c of e){if(!Pe(c))continue;const d=On(0,l);i.set(c.id,{x:d.x,y:d.y}),r.add(ve(d.col,d.row)),l+=1}const a=new Map;for(const c of e){if(i.has(c.id))continue;const d=Bo(c.x,c.y),u=ve(d.col,d.row);if(!r.has(u)){r.add(u);continue}const f=It(c.x,c.y,r,n);r.add(ve(f.col,f.row)),a.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=a.get(c.id);u?ht(d,u.x,u.y):f?ht(d,f.x,f.y):ht(d,c.x,c.y),Cw(d,c)}return!0}function Cw(e,t){const n=pw(t);e.getAttribute("label")!==n&&e.setAttribute("label",n)}function Iw(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?cN(s,o):void 0},accept:i=>(s=i.type,dN(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`),uN(i,r,o)}})}function ON(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 l of Mn(r)){if(l.file.type==="folder"&&parseInt(l.file.ref,10)===n||l.parentId===n||Hi(l))return!1;if(l.file.type==="folder"){const a=parseInt(l.file.ref,10);if(!Number.isNaN(a)&&Aw(a,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,l=Q.getState().placementsByFolder.get(n)??[],a=Go(l);for(const c of Mn(r)){const d=tc(a);a.add(ve(d.col,d.row)),Q.upsertPlacement({...c,x:d.x,y:d.y,parentId:n}),Tn(c.id,{x:d.x,y:d.y,parentId:n},c.updatedAtMs).then(u=>{Q.upsertPlacement(u,"remote")}).catch(u=>{vw(u)?_w(u):console.error("[openstation] files: move-into-folder persist failed",u),Q.upsertPlacement(c)})}return}if(i.payload.type==="shortcut"){const r=i.payload.data,l=Q.getState().placementsByFolder.get(n)??[],a=Go(l);for(const c of Bi(r)){const d=tc(a);a.add(ve(d.col,d.row)),Ln({parentId:n,type:c.kind,ref:c.ref,x:d.x,y:d.y}).then(u=>{Q.upsertPlacement(u),L("os.files.shortcut-dropped",{folderId:n,placement:u})}).catch(u=>{console.error("[openstation] shortcut drop into folder failed:",u)})}}}};return e.registerDropTarget(s)}function MN(e,t,n,o,s){e.addEventListener("pointerdown",i=>{if(i.button!==0||i.shiftKey||i.ctrlKey||i.metaKey)return;const r=zo();if(!r)return;const a=Q.getState().placementsByFolder.get(n)?.find(f=>f.id===t.id)??t;parseFloat(e.style.left)||a.x,parseFloat(e.style.top)||a.y;const c=o.model.has(String(a.id)),d=c?s():[],u=d.length>1&&d.some(f=>f.id===a.id)?d:[a];if(!c){const f=()=>{document.removeEventListener("os.drag.start",f),o.model.set([String(a.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:a,...u.length>1?{placements:u}:{},sourceFolderId:n,bridgePayload:IN(a)},ghost:{offsetX:i.clientX-e.getBoundingClientRect().left,offsetY:i.clientY-e.getBoundingClientRect().top,element:u.length>1?rN(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 xw(e,t,n,o){e.addEventListener("contextmenu",s=>{s.preventDefault(),s.stopPropagation();const i=Q.currentPlacement(t);n.model.has(String(i.id))||n.model.set([String(i.id)]);const r=o(),l=r.length>0?r:[i],a=hg(l,bN);fN({x:s.clientX,y:s.clientY},a,{placementIds:l.map(c=>c.id)})})}function jt(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,o=0;for(;n>=1024&&o<t.length-1;)n/=1024,o++;const s=n>=100||o===0?0:1;return`${n.toFixed(s)} ${t[o]}`}const Pn="os-folder-status-bar";function PN(e,t,n={}){const o=document.createElement("div");o.className=Pn,o.setAttribute("role","status"),o.dataset.folderId=String(t),e.appendChild(o);const s=()=>{const l=At().placementsByFolder.get(t)??[],a=l.filter(p=>p.file.type==="folder").length,c=l.length-a;let d=0;for(const p of l)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:a,total:l.length,bytes:d}},f=WN(u);$N(o,f)};s();const i=ql(()=>s()),r=n.selection?.subscribe(()=>s());return{dispose(){i(),r?.(),o.remove()}}}function WN(e){const{folders:t,files:n,bytes:o}=e.totals,s=[{id:"count",label:Tw(n,"file","files")+(t>0?`, ${Tw(t,"folder","folders")}`:"")+(o>0?` (${jt(o)})`:""),align:"start",sort:10}];e.selectedCount>0&&s.push({id:"selection",label:`${e.selectedCount} selected`,align:"end",sort:10});const i=G("os.files.folder-window.status-bar",s,e);return Array.isArray(i)?i:s}function $N(e,t){const n=(i,r)=>{const l=typeof i.sort=="number"?i.sort:100,a=typeof r.sort=="number"?r.sort:100;return l!==a?l-a: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(Lw("start",o)),e.appendChild(Lw("end",s))}function Lw(e,t){const n=document.createElement("div");n.className=`${Pn}__cluster ${Pn}__cluster--${e}`;for(const o of t)n.appendChild(UN(o));return n}function UN(e){const t=typeof e.onClick=="function",n=document.createElement(t?"button":"span");if(n.className=`${Pn}__segment`,n.dataset.segmentId=e.id,t&&(n.type="button",n.addEventListener("click",s=>e.onClick(s))),e.icon){const s=document.createElement("span");s.className=`${Pn}__icon dashicons ${e.icon.replace(/[^a-zA-Z0-9_-]/g,"")}`,s.setAttribute("aria-hidden","true"),n.appendChild(s)}const o=document.createElement("span");return o.className=`${Pn}__label`,o.textContent=e.label,n.appendChild(o),n}function Tw(e,t,n){return`${e} ${e===1?t:n}`}const zi="os-icon-canvas-menu";let jo=null,Gi=null,nc=null,Vo=null,qo=null;function FN(e,t){t.openOnBackgroundClick;const n=i=>{BN(i.target)||Nw(i.target)||(i.preventDefault(),s(i.clientX,i.clientY))};let o=0;const s=(i,r)=>{if(nc===e&&jo){Vt();return}const l=HN(t),a=G("os.icon-canvas.menu",l,t.scope),c=Array.isArray(a)?a:l,d=++o;Ns(()=>d===o,()=>zN(c,{x:i,y:r},e))};return e.addEventListener("contextmenu",n),{dispose:()=>{e.removeEventListener("contextmenu",n),Vt()}}}function BN(e){return e instanceof Element?e.closest(".os-file-tile")!==null:!1}function Nw(e){return e instanceof Element?e.closest(`.${zi}`)!==null:!1}function HN(e){const n=[{id:"sort-by",label:k("Sort by","desktop-mode"),icon:"dashicons-sort",sort:10,children:[{id:"sort-name-asc",label:k("Name (A → Z)","desktop-mode"),sort:10,onClick:()=>e.onSort("name-asc")},{id:"sort-name-desc",label:k("Name (Z → A)","desktop-mode"),sort:20,onClick:()=>e.onSort("name-desc")},{id:"sort-date-desc",label:k("Newest first","desktop-mode"),sort:30,onClick:()=>e.onSort("date-desc")},{id:"sort-date-asc",label:k("Oldest first","desktop-mode"),sort:40,onClick:()=>e.onSort("date-asc")}]}];return Array.isArray(e.extraItems)&&n.push(...e.extraItems),n}function Dw(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 zN(e,t,n){if(Vt(),e.length===0)return;nc=n;const o=Dw(e),s=document.createElement("os-context-menu");s.setAttribute("open",""),s.classList.add(zi),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 l=Rw(s,r);ji(r)&&l.addEventListener("mouseenter",()=>{Ow(r,l)})}s.addEventListener("os-context-menu-pick",r=>{const l=r.detail,a=i.get(l.id);if(a){if(ji(a)){r.stopPropagation();const c=s.querySelector(`[data-menu-item-id="${a.id}"]`);c&&Ow(a,c);return}Vt(),a.onClick?.()}}),document.body.appendChild(s),jo=s,aa(s),queueMicrotask(()=>{Vo=r=>{Nw(r.target)||Vt()},qo=r=>{r.key==="Escape"&&Vt()},document.addEventListener("mousedown",Vo),document.addEventListener("keydown",qo)})}function Rw(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",GN(t.icon)),ji(t)&&n.setAttribute("has-children",""),n.textContent=t.label,e.appendChild(n),n}function Ow(e,t){if(Mw(),!ji(e))return;const n=document.createElement("os-context-menu");n.setAttribute("open",""),n.classList.add(zi,`${zi}--flyout`);const o=new Map;for(const s of Dw(e.children??[]))o.set(s.id,s),Rw(n,s);n.addEventListener("os-context-menu-pick",s=>{const i=s.detail,r=o.get(i.id);r&&(s.stopPropagation(),Vt(),r.onClick?.())}),document.body.appendChild(n),Gi=n,Hf(n,t)}function ji(e){return Array.isArray(e.children)&&e.children.length>0}function Mw(){Gi&&(Gi.remove(),Gi=null)}function Vt(){Mw(),jo&&(jo.remove(),jo=null),nc=null,Vo&&(document.removeEventListener("mousedown",Vo),Vo=null),qo&&(document.removeEventListener("keydown",qo),qo=null)}function GN(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const qt="os-breadcrumbs";function jN(e,t,n={}){if(e.replaceChildren(),e.classList.add(qt),n.onBack){const s=document.createElement("button");s.type="button",s.className=`${qt}__back`,s.setAttribute("aria-label",k("Back","desktop-mode")),s.title=k("Back","desktop-mode");const i=document.createElement("span");i.className="dashicons dashicons-arrow-left-alt2",i.setAttribute("aria-hidden","true"),s.appendChild(i),n.backDisabled&&(s.disabled=!0);const r=n.onBack;s.addEventListener("click",()=>{s.disabled||r()}),e.appendChild(s)}const o=document.createElement("nav");o.className=`${qt}__crumbs`,o.setAttribute("aria-label",k("Breadcrumb","desktop-mode")),t.forEach((s,i)=>{if(i>0){const a=document.createElement("span");a.className=`${qt}__sep`,a.setAttribute("aria-hidden","true"),a.textContent="›",o.appendChild(a)}if(!s.onClick){const a=document.createElement("span");a.className=`${qt}__crumb ${qt}__crumb--current`,a.setAttribute("aria-current","page"),a.textContent=s.label,o.appendChild(a);return}const r=document.createElement("button");r.type="button",r.className=`${qt}__crumb`,r.textContent=s.label;const l=s.onClick;r.addEventListener("click",()=>{l()}),o.appendChild(r)}),e.appendChild(o)}function Vi(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 Ko(e,t={}){const n=await Be(e,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":VN(),...t.headers??{}},...t});if(!n.ok)throw new Error(`${n.status} ${n.statusText}`);return await n.json()}function VN(){return window.wp?.os?.config?.restNonce??""}function qN(){const e=window.wp?.os?.config;return e?.restUrl?e.restUrl.endsWith("/")?e.restUrl:e.restUrl+"/":`${window.location.origin}/wp-json/`}function Yo(e){return et(qN(),e)}function KN(e,t){const n=G("os.files.preview",null,e);if(n instanceof HTMLElement){t.replaceChildren(n);return}if(e.accessGated){t.replaceChildren(YN(e));return}t.replaceChildren(rD()),XN(e).then(o=>{t.replaceChildren(o)}).catch(o=>{t.replaceChildren(aD(o))})}function YN(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 l=document.createElement("p");return l.className="os-files__access-gated-hint",l.textContent="Ask the owner to grant access on the underlying item, or to remove it from the shared folder.",t.appendChild(l),t}async function XN(e){const t=e.file;switch(t.type){case"post":return ZN(t.ref,t);case"folder":return oD(t);case"shortcut":return sD(t);case"attachment":return tD(t.ref,t);case"upload":return nD(t);case"user":return JN(t.ref,t);case"term":return QN(t);case"comment":return eD(t.ref,t);case"bookmark":return iD(t);default:return Xe(t)}}async function ZN(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;for(const u of["wp/v2/posts","wp/v2/pages"])try{o=await Ko(Yo(`${u}/${n}?_fields=id,title,content,date,link,status`));break}catch{}if(!o)return Xe(t);const s=it(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=qi(o.title.rendered)||t.title||`#${n}`,s.appendChild(i);const r=document.createElement("p");r.className="os-my-wordpress__article-meta";const l=[];if(l.push(Pw(o.date)),o.status&&o.status!=="publish"&&l.push(o.status),r.textContent=l.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 a=document.createElement("footer");a.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=k("Explore details","desktop-mode"),u.title=k("See author, comments, categories, tags, attached media, and revisions for this entry.","desktop-mode"),u.addEventListener("click",()=>{const f=typeof t.postType=="string"?t.postType:"post";c.openDetail({entityId:f==="page"?"pages":"posts",postId:n,postTitle:qi(o.title.rendered)||`#${n}`})}),a.appendChild(u)}const d=document.createElement("os-button");return d.setAttribute("variant","primary"),d.textContent=k("Open in editor","desktop-mode"),d.addEventListener("click",()=>{const u=window.wp?.os?.config?.adminUrl;if(!u)return;const f=`${u}post.php?post=${n}&action=edit`,p=window.wp?.os?.windowManager,m=(typeof t.postType=="string"?t.postType:"post")==="page"?"pages":"posts";p?.open({id:`${m}-edit-${n}`,url:f,title:qi(o.title.rendered),icon:t.icon})}),a.appendChild(d),s.appendChild(a),s}async function JN(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;try{o=await Ko(Yo(`desktop-mode/v1/user-stats/${n}`))}catch{return Xe(t)}const s=it("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 l=document.createElement("h2");if(l.className="os-my-wordpress__article-title",l.textContent=o.profile.name||t.title||`#${n}`,r.appendChild(l),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 a=document.createElement("div");return a.className="os-my-wordpress__user-stats",a.appendChild(Wn(o.counts.posts.total.toLocaleString(),k("Posts","desktop-mode"))),a.appendChild(Wn(o.counts.pages.total.toLocaleString(),k("Pages","desktop-mode"))),a.appendChild(Wn(o.counts.commentsReceived.toLocaleString(),k("Comments received","desktop-mode"))),s.appendChild(a),s}async function QN(e){const t=parseInt(e.ref,10),n=typeof e.taxonomy=="string"&&e.taxonomy?e.taxonomy:"category";if(!t)return Xe(e);let o=null;try{o=await Ko(Yo(`desktop-mode/v1/term-stats/${n}/${t}`))}catch{return Xe(e)}const s=it(),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 a=document.createElement("div");a.className="os-my-wordpress__article-content",a.innerHTML=o.profile.description,s.appendChild(a)}const l=document.createElement("div");return l.className="os-my-wordpress__user-stats",l.appendChild(Wn(o.counts.posts.total.toLocaleString(),k("Posts","desktop-mode"))),l.appendChild(Wn(o.counts.commentsReceived.toLocaleString(),k("Comments","desktop-mode"))),l.appendChild(Wn(o.counts.distinctAuthors.toLocaleString(),k("Authors","desktop-mode"))),s.appendChild(l),s}async function eD(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;try{o=await Ko(Yo(`desktop-mode/v1/comment-stats/${n}`))}catch{return Xe(t)}const s=it(),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 l=document.createElement("h2");l.className="os-my-wordpress__article-title",l.textContent=o.author.name,r.appendChild(l);const a=document.createElement("p");a.className="os-my-wordpress__article-meta",a.textContent=`${Pw(o.comment.date)} · ${o.comment.status}`,r.appendChild(a),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 tD(e,t){const n=parseInt(e,10);if(!n)return Xe(t);let o=null;try{o=await Ko(Yo(`wp/v2/media/${n}?_fields=id,title,source_url,mime_type,alt_text,media_details`))}catch{return Xe(t)}const s=it(),i=document.createElement("h2");i.className="os-my-wordpress__article-title",i.textContent=qi(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 l=document.createElement("img");l.className="os-my-wordpress__article-hero";const a=o.media_details?.sizes;l.src=a?.large?.source_url??a?.medium?.source_url??o.source_url,l.alt=o.alt_text??"",s.appendChild(l)}else{const l=document.createElement("p"),a=document.createElement("a");a.href=o.source_url,a.textContent=o.source_url,a.target="_blank",a.rel="noopener noreferrer",l.appendChild(a),s.appendChild(l)}return s}function nD(e){const t=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("Uploaded file","desktop-mode"),t.appendChild(n);const o=typeof e.mime=="string"?e.mime:"",s=typeof e.sizeBytes=="number"?e.sizeBytes:0,i=typeof e.kind=="string"?e.kind:"file",r=document.createElement("p");r.className="os-my-wordpress__article-meta",r.textContent=[o,s>0?jt(s):""].filter(Boolean).join(" · "),t.appendChild(r);const l=parseInt(e.ref,10),a=()=>{const c=document.createElement("p");return c.className="os-my-wordpress__article-meta os-files__no-preview",c.textContent=k("No preview available for this file type.","desktop-mode"),c};if(l>0&&i==="image"){const c=document.createElement("img");c.className="os-my-wordpress__article-hero",c.src=zt(l),c.alt=e.title||"",c.addEventListener("error",()=>{c.replaceWith(a())}),t.appendChild(c)}else if(l>0&&i==="video"){const c=document.createElement("video");c.className="os-my-wordpress__article-hero",c.controls=!0,c.preload="metadata",c.src=zt(l),c.addEventListener("error",()=>{c.replaceWith(a())}),t.appendChild(c)}else if(l>0&&i==="audio"){const c=document.createElement("audio");c.controls=!0,c.preload="metadata",c.src=zt(l),c.style.width="100%",c.addEventListener("error",()=>{c.replaceWith(a())}),t.appendChild(c)}else t.appendChild(a());if(l>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=k("Download","desktop-mode"),d.addEventListener("click",()=>{Vi(zt(l))}),c.appendChild(d),t.appendChild(c)}return t}function oD(e){const t=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("(folder)","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=k("Double-click to open.","desktop-mode"),t.appendChild(o),t}function sD(e){const t=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("Shortcut","desktop-mode"),t.appendChild(n);const o=document.createElement("p");return o.className="os-my-wordpress__article-meta",o.textContent=k("Plugin shortcut. Double-click to open.","desktop-mode"),t.appendChild(o),t}function iD(e){const t=it(),n=document.createElement("h2");n.className="os-my-wordpress__article-title",n.textContent=e.title||k("Bookmark","desktop-mode"),t.appendChild(n);const o=typeof e.url=="string"?e.url:"";if(o){const s=document.createElement("a");s.href=o,s.textContent=o,s.target="_blank",s.rel="noopener noreferrer",t.appendChild(s)}return t}function Xe(e){const t=it(),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(k("Type: %s","desktop-mode"),e.type),t.appendChild(o),!e.exists){const s=document.createElement("p");s.className="os-my-wordpress__article-meta",s.textContent=k("The underlying entity is no longer available.","desktop-mode"),t.appendChild(s)}return t}function it(e=""){const t=document.createElement("article");return t.className="os-my-wordpress__article"+(e?" "+e:""),t}function Wn(e,t){const n=document.createElement("div");n.className="os-my-wordpress__user-stat";const o=document.createElement("span");o.className="os-my-wordpress__user-stat-value",o.textContent=e,n.appendChild(o);const s=document.createElement("span");return s.className="os-my-wordpress__user-stat-label",s.textContent=t,n.appendChild(s),n}function rD(){const e=document.createElement("div");e.className="os-my-wordpress__preview-loading";const t=document.createElement("os-spinner");return e.appendChild(t),e}function aD(e){const t=document.createElement("div");return t.className="os-my-wordpress__error",t.textContent=e instanceof Error?e.message:k("Unknown error.","desktop-mode"),t}function qi(e){const t=document.createElement("div");return t.innerHTML=e,(t.textContent??"").trim()}function Pw(e){if(!e)return"";try{return new Date(e).toLocaleString()}catch{return e}}function Ww(){const e=document.createElement("div");return e.className="os-my-wordpress__preview-empty",e.textContent=k("Select an item to preview it here.","desktop-mode"),e}function lD(e){const t=document.createElement("div");t.className="os-my-wordpress__preview-empty";const n=document.createElement("strong");n.textContent=le(k("%d items selected","desktop-mode"),e.length),t.appendChild(n);const o=new Map;for(const i of e){const r=i.file?.type||"item";o.set(r,(o.get(r)??0)+1)}const s=Array.from(o.entries()).sort((i,r)=>r[1]-i[1]||i[0].localeCompare(r[0])).map(([i,r])=>`${r} × ${i}`).join(" · ");if(s){const i=document.createElement("div");i.className="os-files-preview__selection-breakdown",i.textContent=s,t.appendChild(i)}return t}const Ki="desktop-mode-embed-",cD=800,dD=600,oc=360,sc=240,Yi=16,ic=new Map;function uD(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?`${Ki}${s.id}`:`${Ki}anon-${mD(n)}`,l=i?.name?.trim()??"",a=l!==""?l:e.title(),c={id:r,baseId:r,url:n,title:a,icon:e.icon(),minWidth:oc,minHeight:sc},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}=hD(d,f,p);c.x=g,c.y=m,c.width=h,c.height=b}else c.width=Math.min(cD,Math.max(oc,f-Yi*2)),c.height=Math.min(dD,Math.max(sc,p-Yi*2));s&&d&&ic.set(r,{...d}),o.open(c)}let $w=!1;function fD(){if($w)return;$w=!0;const e=t=>{const o=t?.windowId;if(!o||!o.startsWith(Ki))return;const s=o.slice(Ki.length),i=parseInt(s,10);if(!i)return;const a=window.wp?.os?.windowManager?.getById?.(o)?.element;if(!a)return;const c={x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight},d=ic.get(o);d&&d.x===c.x&&d.y===c.y&&d.width===c.width&&d.height===c.height||(ic.set(o,c),pD(i,c))};Y(_.WINDOW_DRAG_END,"os-embed-persist",e),Y(_.WINDOW_RESIZE_END,"os-embed-persist",e)}async function pD(e,t){try{const i={...(await Te(0)).placements.find(r=>r.id===e)?.meta??{},window:t};await Tn(e,{meta:i})}catch(n){console.warn("[openstation] embed window persist failed:",n)}}function hD(e,t,n){const o=Math.max(oc,Math.min(e.width,t-Yi)),s=Math.max(sc,Math.min(e.height,n-Yi)),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 mD(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 Xo(){const t=window.wp?.os?.config?.adminUrl??"/wp-admin/";return t.endsWith("/")?t:`${t}/`}function Uw(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 gD(){He({id:"wp-post-editor",label:"Block Editor",types:["post"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Xo()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),He({id:"wp-media-editor",label:"Media editor",types:["attachment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Xo()}post.php?post=${encodeURIComponent(e.ref())}&action=edit`}}),He({id:"agent-chat",label:k("Agent chat","desktop-mode"),types:["user"],isDefault:!0,sort:5,appliesTo:e=>e.shape.isAgent===!0,handler:{kind:"js",open:e=>{const t=e.shape;Vg({id:Number.parseInt(t.ref,10),name:t.title,description:t.agentDescription??"",avatarUrl:t.previewUrl??""},"agents-open")}}}),He({id:"wp-user-profile",label:"User profile",types:["user"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Xo()}user-edit.php?user_id=${encodeURIComponent(e.ref())}`}}),He({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`${Xo()}term.php?taxonomy=${encodeURIComponent(t??"")}&tag_ID=${encodeURIComponent(n??"")}`}}}),He({id:"wp-comment-editor",label:"Comment editor",types:["comment"],isDefault:!0,sort:10,handler:{kind:"url",url:e=>`${Xo()}comment.php?action=editcomment&c=${encodeURIComponent(e.ref())}`}}),He({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&&Vi(zt(t))}}}),He({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=Q.getState().folders.get(t),i=Number(window.openStationConfig?.currentUserId??0),r=!!s&&s.ownerId>0&&s.ownerId!==i,l=e.title(),a=r?`${l} · Shared`:l;n.open({id:o,baseId:o,url:`#folder-${t}`,title:a,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()}});jN(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(Ww()),h.appendChild(y);const C=d[d.length-1],w=kw(b,C.folderId),E=w.onSelectionChanged(v=>{if(v.length===0){y.replaceChildren(Ww());return}if(v.length>1){y.replaceChildren(lD(v));return}KN(v[0],y)}),T=v=>{if(!(v.target instanceof Element))return;const $=v.target.closest(".os-file-tile");if(!$||$.dataset.fileType!=="folder")return;const D=parseInt($.dataset.fileRef??"",10);if(!D)return;v.preventDefault(),v.stopPropagation();const I=$.querySelector(".os-file-tile__label")?.textContent??`#${D}`;d.push({folderId:D,title:I}),m()};b.addEventListener("dblclick",T,!0);const M=FN(b,{scope:`os-folder:${C.folderId}`,onSort:v=>w.sort(v),extraItems:[{id:"new-folder",label:"New folder",icon:"dashicons-portfolio",sort:5,onClick:()=>{Ql({onSubmit:async v=>{const $=await zl({name:v}),D=Q.getState().placementsByFolder.get(C.folderId)??[],I=bw(D),W=It(ze,ze,I,b),z=await Ln({type:"folder",ref:String($.id),parentId:C.folderId,x:W.x,y:W.y});Q.upsertFolder($),Q.upsertPlacement(z)}})}}]}),P=PN(p,C.folderId,{selection:{count:()=>w.getSelection().length,subscribe:v=>w.onSelectionChanged(()=>v())}});u=()=>{E(),M.dispose(),P.dispose(),b.removeEventListener("dblclick",T,!0),w.dispose()},g()};m()},width:720,height:480,minWidth:360,minHeight:240})}}}),He({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?ae(o.toString(),s):`desktop-icon-${e.ref()}`,r=im(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{}}}}}),He({id:"browser-navigate",label:"Open in browser",types:["bookmark"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Uw(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),He({id:"desktop-mode-link-opener",label:"Open in browser",types:["link"],isDefault:!0,sort:10,handler:{kind:"js",open:e=>{const t=Uw(e);t&&window.open(t,"_blank","noopener,noreferrer")}}}),He({id:"desktop-mode-embed-opener",label:"Open as window",types:["embed"],isDefault:!0,sort:10,handler:{kind:"js",open:(e,t)=>{uD(e,t)}}})}const wD="os-file-associations";function yD(){Tp({id:wD,label:"File Associations",order:50,render(e){bD(e)}})}function bD(e){e.replaceChildren();const t=Pg();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=Ml(),s=document.createElement("div");s.className="os-file-associations__list",s.setAttribute("role","list");for(const i of t)s.appendChild(vD(i.type,i.label,o));e.appendChild(s)}function vD(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=Pl(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=Wl(e),l=n[e]??r?.id??"",a=document.createElement("os-select");a.setAttribute("value",l),a.setAttribute("aria-label",`Default app for ${t}`),a.className="os-file-associations__select",s.htmlFor=`assoc-${e}`,a.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,a.appendChild(d)}return a.addEventListener("os-pick",c=>{const d=c.detail?.value;if(!d)return;const u={...Ml(),[e]:d};$g(u),Yg(u).catch(f=>{console.error("[openstation] saveAssociations failed:",f)})}),o.appendChild(a),o}function _D(){const e=window.openStationConfig,t=e?.filesBootFolders;return!e||!Array.isArray(t)?!1:(delete e.filesBootFolders,Pi(t),!0)}let rc=null;function Ze(){return rc||(rc=re("desktop-files/shares",()=>({byFolder:new Map,pending:[],sharesVersion:0,deniedFolders:new Set,deniedFiles:new Set}))),rc}function ED(e,t){const n=Ze();n.state.byFolder.set(e,t),n.notify()}function kD(e){if(!e||typeof e.folderId!="number")return;const t=Ze(),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 SD(e,t){const n=Ze(),o=n.state.byFolder.get(e)??[];n.state.byFolder.set(e,o.filter(s=>s.id!==t)),n.notify()}function AD(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 Fw(e){const t=Ze(),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(AD(r,i))continue;t.state.pending=t.state.pending.map(l=>l.id===i.id?i:l)}else t.state.pending.push(i);i.invitedAtMs>t.state.sharesVersion&&(t.state.sharesVersion=i.invitedAtMs),o=!0}o&&t.notify()}function Xi(e,t={}){const n=Ze();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 CD=ce`: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}`,hs=class hs extends Ee{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"},l=await Be(i,r,{source:"desktop-mode/files-user-search",silent:!0});if(!l.ok)throw new Error(`HTTP ${l.status}`);const a=await l.json();this._results=a&&Array.isArray(a.users)?a.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,l=window.innerHeight-n.bottom,a=n.top,c=Math.max(120,Math.min(280,Math.max(l,a)-16));l<200&&a>l?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` |
| 101 |
<button |
| 102 |
type="button" |
| 103 |
class="item" |
| 104 |
role="option" |
| 105 |
@mousedown=${n=>n.preventDefault()} |
| 106 |
@click=${()=>this._pick(t)} |
| 107 |
> |
| 108 |
<img class="avatar" src=${t.avatarUrl} alt="" /> |
| 109 |
<div> |
| 110 |
<div class="name">${t.name}</div> |
| 111 |
<div class="slug">${t.slug}</div> |
| 112 |
</div> |
| 113 |
</button> |
| 114 |
`)}render(){const t=this.getAttribute("placeholder")||"Search users…";return j` |
| 115 |
<input |
| 116 |
class="input" |
| 117 |
type="search" |
| 118 |
placeholder=${t} |
| 119 |
autocomplete="off" |
| 120 |
@input=${this._onInput} |
| 121 |
@focus=${this._onFocus} |
| 122 |
@blur=${this._onBlur} |
| 123 |
.value=${this._query} |
| 124 |
/> |
| 125 |
${this._open?j` |
| 126 |
<div class="dropdown" role="listbox" style=${this._dropdownStyle}> |
| 127 |
${this._dropdownContent()} |
| 128 |
</div> |
| 129 |
`:j``} |
| 130 |
`}};hs.props=["placeholder","exclude","endpoint"],hs.styles=[CD],hs.help=void 0;let ac=hs;Ie("os-user-search",ac);const ID=ce`: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}`,ms=class ms extends Ee{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` |
| 131 |
${t.map(o=>{const s=n.has(o.slug);return j` |
| 132 |
<button |
| 133 |
type="button" |
| 134 |
class="chip" |
| 135 |
aria-pressed=${s?"true":"false"} |
| 136 |
@click=${()=>this._onToggle(o.slug)} |
| 137 |
>${o.name}</button> |
| 138 |
`})} |
| 139 |
`}};ms.props=["selected","roles"],ms.styles=[ID],ms.help=void 0;let lc=ms;Ie("os-role-picker",lc);const xD=ce` ${nt}: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}}`,LD=ce` ${nt} ${oa}: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}`,gs=class gs extends Ee{render(){return this.setAttribute("role","radio"),j` |
| 140 |
<button |
| 141 |
type="button" |
| 142 |
class="os-holo-sheen" |
| 143 |
@click=${()=>this._onPick()} |
| 144 |
> |
| 145 |
<slot></slot> |
| 146 |
</button> |
| 147 |
`}_onPick(){this.emit("os-segment-pick",{value:this.value})}};gs.props=["value"],gs.styles=[LD],gs.help=void 0;let cc=gs;Ie("os-segment",cc);const ws=class ws extends Ee{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 l=o.getBoundingClientRect(),a=c=>`${Math.round(c*100)/100}px`;this.style.setProperty("--_thumb-x",a((l.left-s.left)/r)),this.style.setProperty("--_thumb-w",a(l.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 |
| 148 |
><slot></slot>`}};ws.props=["value","label"],ws.styles=[xD],ws.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` |
| 149 |
<os-segmented value="md" label="Dock size"> |
| 150 |
<os-segment value="sm">Small</os-segment> |
| 151 |
<os-segment value="md">Medium</os-segment> |
| 152 |
<os-segment value="lg">Large</os-segment> |
| 153 |
</os-segmented> |
| 154 |
`};let dc=ws;Ie("os-segmented",dc);const TD=ce`: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}`,ND=ce` ${nt}: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}}`,ar=class ar extends Ee{connectedCallback(){super.connectedCallback(),this.setAttribute("aria-live","polite")}render(){return j`<slot></slot>`}};ar.styles=[TD],ar.help=void 0;let uc=ar;Ie("os-toast-container",uc);const ys=class ys extends Ee{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` |
| 155 |
<span class="os-toast__label"><slot></slot></span> |
| 156 |
<button |
| 157 |
type="button" |
| 158 |
?hidden=${!t} |
| 159 |
@click=${o=>this._onAction(o)} |
| 160 |
> |
| 161 |
${t} |
| 162 |
</button> |
| 163 |
<button |
| 164 |
type="button" |
| 165 |
class="os-toast__close" |
| 166 |
aria-label=${k("Dismiss")} |
| 167 |
?hidden=${!n} |
| 168 |
@click=${o=>this._onDismiss(o)} |
| 169 |
> |
| 170 |
<svg viewBox="0 0 14 14" width="12" height="12" aria-hidden="true" focusable="false"> |
| 171 |
<path |
| 172 |
d="M3 3 L11 11 M11 3 L3 11" |
| 173 |
stroke="currentColor" |
| 174 |
stroke-width="1.7" |
| 175 |
stroke-linecap="round" |
| 176 |
fill="none" |
| 177 |
></path> |
| 178 |
</svg> |
| 179 |
</button> |
| 180 |
`}_onAction(t){t.preventDefault(),t.stopPropagation(),this.emit("os-toast-action",{})}_onDismiss(t){t.preventDefault(),t.stopPropagation(),this.emit("os-toast-dismiss",{})}};ys.props=["action","state","dismissible"],ys.styles=[ND],ys.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` |
| 181 |
<os-toast state="in" action="Undo">Post moved to trash.</os-toast> |
| 182 |
`};let fc=ys;Ie("os-toast",fc);function Bw(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 pc(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 hc(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 a=document.createElement("div");a.style.cssText="opacity:0.7;margin-bottom:14px;font-size:12px;",a.textContent=e.ownerName?`Owner: ${e.ownerName} — cannot be changed`:"Owner cannot be changed",t.appendChild(a);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(E=>E.principalType==="user").map(E=>E.principalRef).concat(o.filter(E=>E.kind==="user").map(E=>E.ref));u.setAttribute("exclude",f.join(",")),u.setAttribute("placeholder","Search users…"),u.addEventListener("os-user-pick",E=>{const T=E.detail;o.push({kind:"user",ref:String(T.user.id),label:T.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(E=>E.principalType==="role").map(E=>E.principalRef),b=o.filter(E=>E.kind==="role").map(E=>E.ref);if(m.setAttribute("selected",[...h,...b].join(",")),m.addEventListener("os-role-toggle",E=>{const T=E.detail,M=n.find(P=>P.principalType==="role"&&P.principalRef===T.slug);if(M){T.selected||r(M);return}if(T.selected){const P=(window.openStationConfig?.shareEligibleRoles??[]).find(v=>v.slug===T.slug);o.push({kind:"role",ref:T.slug,label:P?P.name:T.slug,cap:"read"})}else o=o.filter(P=>!(P.kind==="role"&&P.ref===T.slug));s()}),p.appendChild(m),t.appendChild(p),o.length>0){const E=document.createElement("div");E.style.cssText="border:1px dashed rgba(255,255,255,0.18);border-radius:8px;padding:10px;margin-bottom:14px;";const T=document.createElement("div");T.textContent="New invites (not sent yet)",T.style.cssText="font-weight:600;margin-bottom:6px;font-size:12px;",E.appendChild(T);for(const P of o){const v=document.createElement("div");v.style.cssText="display:flex;align-items:center;gap:8px;padding:4px 0;font-size:13px;";const $=document.createElement("span");$.textContent=P.kind==="role"?`Role: ${P.label}`:P.label,$.style.flex="1",v.appendChild($);const D=Bw(P.cap,W=>{P.cap=W});v.appendChild(D);const I=pc("×",()=>{o=o.filter(W=>!(W.kind===P.kind&&W.ref===P.ref)),s()});v.appendChild(I),E.appendChild(v)}const M=document.createElement("os-button");M.setAttribute("variant","primary"),M.textContent=`Send ${o.length} invite${o.length===1?"":"s"}`,M.style.marginTop="8px",M.addEventListener("click",async()=>{if(o.length===0)return;M.setAttribute("busy",""),M.setAttribute("disabled","");const P=o.slice();let v=0,$=null;for(const D of P)try{await Zg(e.folderId,{principalType:D.kind,principalRef:D.ref,capability:D.cap}),v++}catch(I){$=I;break}v>0&&(o=o.slice(v));try{await i()}catch{}X($?{message:`Could not send invites: ${$.message}`}:{message:v===1?"Invite sent.":`${v} invites sent.`}),M.removeAttribute("busy"),M.removeAttribute("disabled"),s()}),E.appendChild(M),t.appendChild(E)}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 E=document.createElement("div");E.textContent="Only you can see this folder.",E.style.cssText="opacity:0.6;font-size:12px;",t.appendChild(E)}else for(const E of n){const T=document.createElement("div");T.style.cssText="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04);";const M=document.createElement("div");if(M.style.flex="1",M.textContent=E.principalType==="role"?`Role: ${E.displayName}`:E.displayName,E.state==="pending"){const D=document.createElement("span");D.textContent=" · pending",D.style.cssText="opacity:0.6;font-size:12px;",M.appendChild(D)}else if(E.state==="denied"){const D=document.createElement("span");D.textContent=" · denied",D.style.cssText="color:#d63638;font-size:12px;",M.appendChild(D)}T.appendChild(M);const P=E.capability==="write"?"write":"read",v=Bw(P,D=>{l(E,D)});T.appendChild(v);const $=pc("×",()=>{r(E)},{danger:!0});T.appendChild($),t.appendChild(T)}const C=document.createElement("div");C.setAttribute("slot","footer"),C.style.display="flex",C.style.justifyContent="flex-end",C.style.gap="10px",C.style.flexWrap="wrap";const w=document.createElement("os-button");w.setAttribute("variant","secondary"),w.textContent="Done",w.addEventListener("click",()=>t.remove()),C.appendChild(w),t.appendChild(C)},i=async()=>{try{n=(await Xg(e.folderId)).shares,ED(e.folderId,n)}catch(a){X({message:`Could not load shares: ${a.message}`})}s()},r=async a=>{try{await Qg(e.folderId,a.id),SD(e.folderId,a.id),await i(),X({message:"Access revoked."})}catch(c){X({message:`Could not revoke: ${c.message}`})}},l=async(a,c)=>{try{const d=await Jg(e.folderId,a.id,c);kD(d),await i()}catch(d){X({message:`Could not update capability: ${d.message}`})}};t.addEventListener("os-modal-cancel",()=>t.remove()),s(),await i()}async function DD(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 ow(e.fileId)).shares}catch(i){X({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 l=document.createElement("os-user-search");l.setAttribute("exclude",n.map(u=>u.principalRef).join(",")),l.setAttribute("placeholder","Search users…"),l.addEventListener("os-user-pick",u=>{const f=u.detail;(async()=>{try{await sw(e.fileId,f.user.id),X({message:`Invite sent to ${f.user.name}.`})}catch(p){X({message:`Could not invite: ${p.message}`})}await o()})()}),t.appendChild(l);const a=document.createElement("div");if(a.textContent="Who has access",a.style.cssText="font-weight:600;margin:14px 0 6px;",t.appendChild(a),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=pc("×",()=>{(async()=>{try{await iw(e.fileId,u.id),X({message:"Access revoked."})}catch(b){X({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 Hw(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=` |
| 183 |
<p style="margin: 0 0 12px;">Accept the invite to add this file to your desktop.</p> |
| 184 |
<p style="margin: 0; opacity: 0.75;">Access level: <strong>Read + download</strong></p> |
| 185 |
`,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 aw(e.fileId,e.id),Ze().state.deniedFiles.add(e.fileId),Ze().notify(),n.remove(),t("denied")}catch(a){X({message:`Could not deny: ${a.message}`}),r.removeAttribute("busy"),r.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 rw(e.fileId,e.id);try{const a=await Te(0);pt(0,a.placements)}catch{}n.remove(),t("accepted")}catch(a){X({message:`Could not accept: ${a.message}`}),l.removeAttribute("busy"),l.removeAttribute("disabled")}}),s.appendChild(i),s.appendChild(r),s.appendChild(l),n.appendChild(s),n.addEventListener("os-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}function zw(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=` |
| 186 |
<p style="margin: 0 0 12px;">Accept the invite to add this folder to your desktop.</p> |
| 187 |
<p style="margin: 0; opacity: 0.75;">Access level: <strong>${s}</strong></p> |
| 188 |
`,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 l=document.createElement("os-button");l.setAttribute("variant","danger"),l.textContent="Deny",l.addEventListener("click",async()=>{l.setAttribute("busy",""),l.setAttribute("disabled","");try{await tw(e.folderId,e.id),Ze().state.deniedFolders.add(e.folderId),Ze().notify(),n.remove(),t("denied")}catch(c){X({message:`Could not deny: ${c.message}`}),l.removeAttribute("busy"),l.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 ew(e.folderId,e.id);try{const c=await Te(0);pt(0,c.placements)}catch{}n.remove(),t("accepted")}catch(c){X({message:`Could not accept: ${c.message}`}),a.removeAttribute("busy"),a.removeAttribute("disabled")}}),i.appendChild(r),i.appendChild(l),i.appendChild(a),n.appendChild(i),n.addEventListener("os-modal-cancel",()=>{n.remove(),t("dismissed")}),document.body.appendChild(n)})}const RD=Object.freeze(Object.defineProperty({__proto__:null,openFileShareModal:DD,openPendingFileInviteModal:Hw,openPendingInviteModal:zw,openShareSettingsModal:hc},Symbol.toStringTag,{value:"Module"}));function Gw(){return Number(window.openStationConfig?.currentUserId??0)}function mc(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function jw(e){const t=At().folders.get(e);return t?Number(t.ownerId):0}function Vw(e){if(typeof e!="string")return null;const t=/^os-folder-(\d+)$/.exec(e);return t?Number(t[1]):null}function OD(e){if(e.file.type!=="folder")return null;const t=Number(e.file.ref);return!Number.isFinite(t)||t<=0?null:t}function MD(e){return Number(e.file.ownerId??0)}function PD(){zn("os.files.tile-menu","desktop-mode/folder-share",(e,t)=>{if(!mc())return e;const n=OD(t);if(n===null)return e;const o=jw(n)||MD(t),s=Gw();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:()=>{hc({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 Ff({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 nw(n),$o(t.id);try{const a=await Te(0);pt(0,a.placements)}catch{}const r=`os-folder-${n}`;window.openStation?.windowManager?.close?.(r),X({message:"You left the shared folder."})}catch(r){X({message:`Could not leave: ${r.message}`})}}});return e}),pi({id:"desktop-mode/folder-share",label:"Share folder",icon:"dashicons-share",placement:"right",order:50,match:e=>{if(!mc())return!1;const t=e.config.baseId??e.id,n=Vw(t);return n===null?!1:jw(n)===Gw()},onClick:e=>{if(!mc())return;const t=e.config.baseId??e.id,n=Vw(t);n!==null&&hc({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 qw=new Set;function WD(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function $D(){const e=Ze(),t=n=>{if(WD()){for(const o of n.pending)if(!qw.has(o.id)){if(qw.add(o.id),o.targetType==="file"&&typeof o.fileId=="number"){const s=o.fileId;Hw({id:o.id,fileId:s,fileName:o.fileName,ownerName:o.ownerName}).then(i=>{i==="accepted"?Xi(o.id):i==="denied"&&Xi(o.id,{denied:!0,fileId:s})});continue}zw({id:o.id,folderId:o.folderId,folderName:o.folderName,ownerName:o.ownerName,capability:o.capability}).then(s=>{s==="accepted"?Xi(o.id):s==="denied"&&Xi(o.id,{denied:!0,folderId:o.folderId})})}}};e.subscribe(t),t(e.state)}function UD(){return Number(window.openStationConfig?.currentUserId??0)}function Kw(){return window.openStationConfig?.desktopStorage??{}}function FD(){const e=window.wp?.os?.getOsSettings?.();return e?e.foldersSharingEnabled!==!1:!0}function BD(e){if(e.file.type!=="upload")return null;const t=Number(e.file.ref);return Number.isFinite(t)&&t>0?t:null}function HD(){zn("os.files.tile-menu","desktop-mode/uploads",(e,t)=>{if(t.file.type==="folder"&&Kw().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:()=>{Vi(dw(i))}}),e}const n=BD(t);if(n===null)return e;e.push({id:"desktop-mode/upload-download",label:"Download",icon:"dashicons-download",sort:40,onClick:()=>{Vi(zt(n))}});const o=Number(t.file.ownerId??0),s=UD();return o===s&&FD()?e.push({id:"desktop-mode/upload-share",label:"Share file…",icon:"dashicons-share",sort:30,onClick:()=>{Promise.resolve().then(()=>RD).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 Ff({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 lw(n),$o(t.id);try{const r=await Te(0);pt(0,r.placements)}catch{}X({message:"You left the shared file."})}catch(r){X({message:`Could not leave: ${r.message}`})}}}),e}),zn("os.wallpaper-context-menu","desktop-mode/uploads",e=>(Kw().canUpload&&(e.push({id:"desktop-mode/upload-files",label:"Upload files…",icon:"dashicons-upload",sort:15,onClick:()=>Yw(!1)}),e.push({id:"desktop-mode/upload-folder",label:"Upload folder…",icon:"dashicons-portfolio",sort:16,onClick:()=>Yw(!0)})),e))}function Yw(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&&zD(n,e)}),t.click()}async function zD(e,t){const n=window.openStationConfig,o=n?.dropConfig??{enabled:!1,allowedMimes:[],maxSize:0},s=await Promise.resolve().then(()=>v1),{accepted:i,rejected:r}=s.partitionByPolicy(e,o);if(r.length>0&&X({message:r.length===1?r[0].message:`${r.length} files can't be uploaded.`}),i.length===0)return;const l=i.map(({file:c,mime:d})=>({file:c,mime:d,fields:s.defaultFields(c,d),relativePath:t?c.webkitRelativePath??"":""}));await(await Promise.resolve().then(()=>ib)).openUploadDialog({entries:l,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})}FT(),gD(),fD(),yD(),_D(),PD(),HD();const gc=window.openStationConfig?.serverPendingShares;Array.isArray(gc)&&gc.length>0&&Fw(gc),$D();const We={DesktopFile:Mg,registerType:Ve,unregisterType:RT,getType:OT,getTypes:Pg,resolve:xn,subscribe:MT,registerOpener:He,unregisterOpener:PT,getOpener:WT,getOpeners:Ug,getOpenersForType:Pl,resolveOpener:Wl,subscribeOpeners:$T,getUserAssociations:Ml,open:Ri,registerTilePayloadHandler:Wi,rest:ZT,store:{get:ft,getState:At,subscribe:ql,setFolderPlacements:pt,upsertPlacement:Mi,removePlacement:$o,setFolders:Pi,upsertFolder:jl,removeFolder:Vl}},Xw="__synthFromDockItem";function GD(e){let t=0;for(let n=0;n<e.length;n++)t=(t*31+e.charCodeAt(n))%2147483647;return-(t+1)}function Zw(e,t){const{id:n,title:o,icon:s}=e.kind==="dock-item"?e.item:e.tile,i=t[n];return{id:GD(n),parentId:0,x:i?i.x:0,y:i?i.y:0,sortOrder:9999,updatedAtMs:Date.now(),meta:{[Xw]:n},file:{type:"shortcut",ref:e.kind==="dock-item"?`dock-promoted:${n}`:n,title:o,icon:s,previewUrl:"",exists:!0,...e.kind==="dock-item"?{shortcutUrl:e.item.url}:{shortcutSystemTile:n}}}}function jD(){const e=window.wp?.os;return e?.getMenuItems?e.getMenuItems().map(o=>({id:o.id,title:o.title,icon:o.icon,url:o.url,badge:o.badge??0,submenu:o.submenu??[],isCore:o.isCore})):window.openStationConfig?.dockItems??[]}function VD(){const e=window.wp?.os;return typeof e?.listSystemTiles!="function"?[]:e.listSystemTiles().filter(t=>t.placeable)}function qD(){return window.openStationConfig?.desktopIcons??[]}let wc=!1;const yc=new Map;function KD(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 Zo(e,t={}){if(!wc){wc=!0;try{const n=jD(),o=qD(),i=We.store.getState().placementsByFolder.get(0)??[],r=new Map;for(const u of i){const f=(u.meta??null)&&typeof u.meta=="object"?u.meta[Xw]:null;typeof f=="string"&&r.set(f,u)}const l=new Map,a=new Set(o.map(u=>u.id));for(const u of i){const f=u?.file?.ref;typeof f=="string"&&a.has(f)&&l.set(f,u)}const c=new Set;for(const u of n){const f=un(u.id,"dock",e);(f==="desktop"||f==="both")&&(c.add(u.id),r.has(u.id)||We.store.upsertPlacement(Zw({kind:"dock-item",item:u},t)))}for(const u of VD()){const f=un(u.id,"dock",e);(f==="desktop"||f==="both")&&(c.add(u.id),r.has(u.id)||We.store.upsertPlacement(Zw({kind:"system-tile",tile:u},t)))}const d=[];for(const[u,f]of r)c.has(u)||(We.store.removePlacement(f.id),t[u]&&d.push(u));d.length>0&&KD(d);for(const u of o){const f=e[u.id],p=l.get(u.id);if(f==="dock"||f==="hidden"){p&&(yc.set(u.id,p),We.store.removePlacement(p.id));continue}if(!p){const g=yc.get(u.id);g&&(We.store.upsertPlacement(g),yc.delete(u.id))}}}finally{wc=!1}}}function YD(e,t=()=>({})){queueMicrotask(()=>Zo(e(),t()));const n=We.store.subscribe(()=>{Zo(e(),t())}),o="desktop-mode/shortcuts-sync";return Y(_.DOCK_ITEM_APPENDED,o,()=>{Zo(e(),t())}),()=>{n(),ur(_.DOCK_ITEM_APPENDED,o)}}const XD=ce`: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}}`,Jw={xs:20,sm:24,md:40,lg:64,xl:96},Qw=new Set(["online","inactive","offline"]),bs=class bs extends Ee{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),l=this._presenceForRender(),a=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 |
| 189 |
src=${t} |
| 190 |
alt=${s} |
| 191 |
@error=${()=>this._onImgError()} |
| 192 |
loading="lazy" |
| 193 |
/>`:this._initials(n),u=l?j`<span |
| 194 |
class=${`os-avatar__dot os-avatar__dot--${l}`} |
| 195 |
aria-label=${this._presenceLabel(l)} |
| 196 |
></span>`:j``;return a?j` |
| 197 |
<button |
| 198 |
type="button" |
| 199 |
class="os-avatar__tile" |
| 200 |
aria-label=${s||"User"} |
| 201 |
style=${c?`background:${c};`:""} |
| 202 |
@click=${f=>this._onClick(f)} |
| 203 |
>${d}</button> |
| 204 |
${u} |
| 205 |
`:j` |
| 206 |
<div |
| 207 |
class="os-avatar__tile" |
| 208 |
role="img" |
| 209 |
aria-label=${s||"User"} |
| 210 |
style=${c?`background:${c};`:""} |
| 211 |
>${d}</div> |
| 212 |
${u} |
| 213 |
`}_attr(t){return this.getAttribute(t)}_resolveSize(t){if(!t)return 32;if(t in Jw)return Jw[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=dn(t);return`linear-gradient(135deg, hsl(${n} 62% 55%), hsl(${(n+24)%360} 58% 42%))`}_presenceForRender(){const t=this._attr("presence");return t&&Qw.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 l=Math.max(0,Math.min(100,(s+.5)*100)),a=Math.max(0,Math.min(100,(i+.5)*100));this._pendingGlareX=`${l.toFixed(1)}%`,this._pendingGlareY=`${a.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&&Qw.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)}};bs.props=["src","alt","name","size","presence","userId","clickable"],bs.styles=[XD],bs.help=void 0;let bc=bs;Ie("os-avatar",bc);const ZD=ce`: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%}`,ey="os-settings-save-lifecycle",JD=2200,QD=6e3,vs=class vs extends Ee{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` |
| 214 |
<span class="os-save-status"> |
| 215 |
<span class="os-save-status__indicator" aria-hidden="true"> |
| 216 |
<span class="os-save-status__glyph">${this._renderGlyph(t)}</span> |
| 217 |
</span> |
| 218 |
${n==="pill"?j`<span class="os-save-status__label" |
| 219 |
>${this._labelForPhase(t)}</span |
| 220 |
>`:j``} |
| 221 |
</span> |
| 222 |
`}_renderGlyph(t){return t==="saved"?eR():t==="failed"?tR():""}_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||ey;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||ey;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)||JD}if(t==="failed"){const n=this["auto-clear-failed-ms"];return parseInt(n||"",10)||QD}return 0}};vs.props=["phase","mode","variant","animation","auto","event","error","saving-label","saved-label","idle-label","auto-clear-saved-ms","auto-clear-failed-ms"],vs.styles=[ZD],vs.help=void 0;let vc=vs;Ie("os-save-status",vc);function eR(){return j` |
| 223 |
<svg |
| 224 |
viewBox="0 0 12 12" |
| 225 |
aria-hidden="true" |
| 226 |
focusable="false" |
| 227 |
fill="none" |
| 228 |
stroke="currentColor" |
| 229 |
stroke-width="2" |
| 230 |
stroke-linecap="round" |
| 231 |
stroke-linejoin="round" |
| 232 |
> |
| 233 |
<path d="M2.5 6 L5 8.5 L9.5 4" /> |
| 234 |
</svg> |
| 235 |
`}function tR(){return j` |
| 236 |
<svg |
| 237 |
viewBox="0 0 12 12" |
| 238 |
aria-hidden="true" |
| 239 |
focusable="false" |
| 240 |
fill="currentColor" |
| 241 |
> |
| 242 |
<path |
| 243 |
d="M5 2 H7 V7 H5 z M5 8.5 H7 V10.5 H5 z" |
| 244 |
/> |
| 245 |
</svg> |
| 246 |
`}const nR=ce` ${nt} ${sa}: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}`,_s=class _s extends Ee{constructor(){super(...arguments),this._textareaEl=null}connectedCallback(){super.connectedCallback(),Nf(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,l=this._attr("name")||"",a=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` |
| 247 |
${t?j`<label class="os-textarea__label" for=${p}>${t}</label>`:j``} |
| 248 |
<textarea |
| 249 |
id=${p} |
| 250 |
part="textarea" |
| 251 |
.value=${n} |
| 252 |
placeholder=${o} |
| 253 |
?disabled=${s} |
| 254 |
?readonly=${i} |
| 255 |
rows=${a} |
| 256 |
maxlength=${c??""} |
| 257 |
minlength=${d??""} |
| 258 |
name=${l} |
| 259 |
aria-invalid=${u?"true":"false"} |
| 260 |
aria-label=${r||""} |
| 261 |
@input=${g=>this._onInput(g)} |
| 262 |
@change=${g=>this._onChange(g)} |
| 263 |
@keydown=${g=>this._onKeyDown(g)} |
| 264 |
></textarea> |
| 265 |
`}_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,l=parseFloat(o.paddingTop)||0,a=parseFloat(o.paddingBottom)||0,c=r*n+l+a;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))}};_s.props=["label","value","placeholder","disabled","readonly","ariaLabel","name","rows","maxlength","minlength","invalid","autoGrow","maxRows","submitOnEnter"],_s.styles=[nR],_s.help=void 0;let _c=_s;Ie("os-textarea",_c);const oR=ce`: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}`,sR={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 iR(e){const t=(e??"").trim();return t===""||t.length>4096||!/^(https?:\/\/|data:image\/)/i.test(t)||/['"()\\<>\s]/.test(t)?"":t}const Es=class Es extends Ee{constructor(){super(...arguments),this._activateWired=!1}static get observedAttributes(){return[...super.observedAttributes,"aria-label"]}render(){const t=iR(this["icon-src"]||this.getAttribute("icon-src")||""),n=t?"":this.icon||"",o=sR[n]||"",s=this.getAttribute("aria-label")||"";return t?j` |
| 266 |
<button type="button" aria-label="${s}"> |
| 267 |
<span |
| 268 |
class="themed-icon" |
| 269 |
aria-hidden="true" |
| 270 |
style="-webkit-mask: url('${t}') center / contain no-repeat; mask: url('${t}') center / contain no-repeat;" |
| 271 |
></span> |
| 272 |
<slot></slot> |
| 273 |
</button> |
| 274 |
`:j` |
| 275 |
<button type="button" aria-label="${s}"> |
| 276 |
<svg |
| 277 |
width="14" |
| 278 |
height="14" |
| 279 |
viewBox="0 0 12 12" |
| 280 |
aria-hidden="true" |
| 281 |
focusable="false" |
| 282 |
></svg> |
| 283 |
<slot></slot> |
| 284 |
</button> |
| 285 |
<span data-svg-buffer style="display:none">${o}</span> |
| 286 |
`}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}))}))}};Es.props=["icon","icon-src","active","danger"],Es.styles=[oR],Es.help=void 0;let Ec=Es;Ie("os-window-button",Ec);const Kt=["butter","blush","sky","mint","lilac","peach"];function rR(e){return Kt.includes(e)?e:Kt[0]}function kc(e){return e.toLowerCase().replace(/[^a-z0-9_-]/g,"")||Kt[0]}function ty(e){const t=Kt.indexOf(rR(e));return Kt[(t+1)%Kt.length]}const ny="cubic-bezier(0.2, 0.7, 0.2, 1)",oy="cubic-bezier(0.5, 0, 0.9, 0.4)",aR="cubic-bezier(0.2, 0.7, 0.3, 1.15)";function $n(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function rt(e,t,n){return typeof e.animate!="function"?Promise.resolve():e.animate(t,n).finished.then(()=>{}).catch(()=>{})}async function lR(e){const t=e.restRotation??0;if($n()){sy(e.rippleHost,400);return}const n=e.tempo??1,o=e.fallDistance??30;await rt(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:oy,fill:"forwards"}),sy(e.rippleHost,420*n);const s=rt(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=rt(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:ny,fill:"forwards"});await Promise.all([s,i])}function sy(e,t){const n=document.createElement("span");n.className="os-pinned-note__ripple",n.setAttribute("aria-hidden","true"),e.appendChild(n),rt(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 cR(e){if($n())return{onPointerMove:()=>{},setBias:()=>{},stop:()=>{}};const t=14;let n=0,o=0,s=0,i=0,r=null,l=0,a=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-l>80&&(a*=.85),s=Math.max(-14,Math.min(14,-a*.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>l){const m=(p-r)/(g-l)*16.7;a=a*.7+m*.3}r=p,l=g},setBias(p){i=p},stop(){u=!1,window.cancelAnimationFrame(c),e.style.transform=""}}}async function dR(e){if($n()){await rt(e.flyback,[{opacity:1},{opacity:0}],{duration:120,easing:"linear",fill:"forwards"});return}const t=e.swing?rt(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=rt(e.flyback,[{left:`${e.flyback.offsetLeft}px`,top:`${e.flyback.offsetTop}px`},{left:`${e.homeX}px`,top:`${e.homeY}px`}],{duration:330,easing:aR,fill:"forwards"});await Promise.all([n,t])}async function uR(e){if($n()){await rt(e.clone,[{opacity:1},{opacity:0}],{duration:150,easing:"linear",fill:"forwards"});return}e.pin&&rt(e.pin,[{transform:"translate(0, 0) rotate(0deg)",opacity:1},{transform:"translate(2px, -16px) rotate(-30deg)",opacity:0}],{duration:200,easing:ny,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 rt(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:oy,delay:60,fill:"forwards"})}function fR(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 iy(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 pR=.57,hR=.525,mR=56,gR=52;function wR(e){return`${e.replace(/\/$/,"")}/assets/images/pushpin.svg`}function yR(e){const t=document.createElement("img");return t.src=wR(e),t.alt="",t.width=mR,t.height=gR,t.draggable=!1,t.className="os-pinned-note__pin-img",t}let Sc=null;function bR(e){Sc=e}function vR(){if(!Sc)throw new Error("[openstation] notes REST client called before installNotesRestDeps().");return Sc}function _R(e){const t=window.openStationConfig;return typeof t?.restNonce=="string"&&t.restNonce?t.restNonce:e}class ry extends Error{constructor(t){super("Note was changed by another session."),this.status=409,this.name="NotesConflictError",this.current=t}}function ER(e){return e instanceof ry}async function Un(e,t){const{baseUrl:n,nonce:o}=vR(),s=e?et(n,e):n,i=new Headers(t.headers??{});i.set("X-WP-Nonce",_R(o)),t.body&&!i.has("Content-Type")&&i.set("Content-Type","application/json");const r=await Be(s,{...t,headers:i,credentials:"same-origin"},{source:"desktop-mode/notes"}),l=await r.text();let a=null;if(l)try{a=JSON.parse(l)}catch{a=null}if(!r.ok){if(r.status===409){const d=a?.data?.current;throw new ry(d??null)}const c=a;throw new Error(`[openstation] notes REST ${r.status}: ${c?.code??""} ${c?.message??""}`.trim())}if(a===null)throw new Error(`[openstation] notes REST ${r.status}: empty or unparseable body.`);return a}function ay(){return Un("",{method:"GET"})}function kR(e){return Un("",{method:"POST",body:JSON.stringify(e)})}function SR(e,t){return Un(`/${e}`,{method:"PATCH",body:JSON.stringify(t)})}function AR(e){return Un(`/${e}`,{method:"DELETE"})}function ly(e){return Un(`/${e}/restore`,{method:"POST"})}function CR(e){return Un(`/${e}/convert`,{method:"POST"})}const IR="openstation_notes_subscribe",xR="openstation_notes";let cy=!1,Ac=null;function LR(e){Ac=e,!cy&&(cy=!0,xe.contribute(IR,()=>Ac?.getHeartbeatSubscription()),xe.subscribe(xR,t=>{Ac?.applyHeartbeatPayload(t)}))}const TR="wpd_note",NR="note-draft",Fn="note",DR="os-note-created";function Zi(e,t){if(t.length===0)return;window.wp?.os?.broadcast?.(`os.${TR}.changed`,{source:"desktop-mode/notes",action:e,ids:t})}function dy(){const e=window.wp?.os;return e&&typeof e.showToast=="function"?e:null}async function RR(e,t){t.onEvict(e.id);try{await AR(e.id),Zi("trashed",[e.id]),dy()?.showToast?.({message:k("Note moved to Trash","desktop-mode"),duration:6e3,action:{label:k("Undo","desktop-mode"),onClick:()=>{ly(e.id).then(n=>{Zi("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),dy()?.showToast?.({message:k("Could not move the note to the Trash.","desktop-mode"),duration:5e3})}}function Ji(){return window.wp?.os??null}function OR(e){const t=Ji();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:k("Edit draft","desktop-mode"),icon:"dashicons-admin-post"}),n}async function MR(e,t){t.onEvict(e.id);try{const n=await CR(e.id);Zi("trashed",[e.id]);const o=OR(n.editUrl);Ji()?.showToast?.({message:k("Note converted to a draft post","desktop-mode"),duration:6e3,action:{label:k("Undo","desktop-mode"),onClick:()=>{o&&Ji()?.windowManager?.getById?.(o)?.close?.(),ly(e.id).then(s=>{Zi("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),Ji()?.showToast?.({message:k("Could not convert the note to a post.","desktop-mode"),duration:5e3})}}const PR=208,WR=1e3,$R=800,UR=10,FR=1;function BR(){return window.wp?.os?.dragManager??null}function Qi(e){return e.seed||Math.abs(e.id)||1}const HR='<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>',zR='<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="M20 5h-5.7c0-1.3-1-2.3-2.3-2.3S9.7 3.7 9.7 5H4v2h1.5v.3l1.4 12c.1.9.9 1.6 1.8 1.6h6.6c.9 0 1.7-.7 1.8-1.6l1.4-12V7H20V5zM8.4 19l-1.3-12h9.8l-1.3 12H8.4z" /></svg>';class GR{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 ay();t.forEach(n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"none"})}),LR(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 jR({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-PR/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=kc(t.color??Kt[0]),s=t.isPublic===!0,{x:i,y:r}=this.clampPosition(t.x,t.y),l=fR(n||`${i},${r}`),a=this.nextTempId(),c=this.upsertNote({id:a,text:n,color:o,x:i,y:r,z:1,public:s,seed:l,ownerId:0,ownerName:"",ownerAvatar:"",canEdit:!0,updatedAtMs:0},{animate:"thunk"});return this.bringToFront(c),t.focus&&c.focusEditor(),kR({text:n,color:o,x:i,y:r,public:s,seed:l}).then(d=>{this.bumpHighWater(d.updatedAtMs),c.replace(d),this.rekeyNote(a,c),c.flushPendingEdits()}).catch(d=>{this.removeNote(a),this.notifyError(k("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){RR(t,{onEvict:n=>this.removeNote(n),onRestore:n=>{this.bumpHighWater(n.updatedAtMs),this.upsertNote(n,{animate:"move"})}})}convertNote(t){!this.canCreatePosts||!t.canEdit||MR(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 ay(),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",k("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 jR{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=iy(Qi(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=kc(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?k("Pinned note","desktop-mode"):le(k("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(yR(this.layer.pluginUrl)),t.canEdit?(this.pinEl.setAttribute("type","button"),this.pinEl.setAttribute("aria-pressed","false"),this.pinEl.setAttribute("aria-label",k("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=HR;const u=k("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=zR;const l=k("Move to Trash","desktop-mode");r.setAttribute("title",l),r.setAttribute("aria-label",l),r.addEventListener("os-button-activate",()=>this.confirmTrash()),s.appendChild(r);const a=document.createElement("os-textarea");a.className="os-pinned-note__editor",a.setAttribute("aria-label",k("Note text","desktop-mode")),a.setAttribute("rows","5"),a.setAttribute("auto-grow",""),a.setAttribute("max-rows","10"),a.setAttribute("value",this.note.text),["keydown","keypress","keyup"].forEach(d=>{a.addEventListener(d,u=>u.stopPropagation())}),a.addEventListener("os-input-change",d=>{const u=d.detail;this.pendingText=u.value,this.setPhase("pending"),this.scheduleSave()}),a.addEventListener("os-input-commit",()=>this.flushSave()),this.editor=a;const c=document.createElement("div");c.className="os-pinned-note__footer",c.appendChild(s),this.paperEl.append(t,a,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=le(k("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=ty(this.note.color);this.colorDot.style.setProperty("--dm-note-next-paper",`var(--dm-note-${t})`),this.colorDot.setAttribute("aria-label",le(k("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",k(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=Qi(t)!==Qi(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=iy(Qi(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=kc(t.color),this.refreshColorDot()),i&&this.applyPosition(),this.note.canEdit)this.pendingText===null&&this.editor?.setAttribute("value",t.text),this.refreshVisibility();else{const l=this.paperEl.querySelector(".os-pinned-note__body");l&&(l.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})},$R)))}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 lR({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()},WR)}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=ty(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&&!$n()&&this.visibilityBtn&&this.visibilityBtn.animate?.([{transform:"scale(1)"},{transform:"scale(1.25)"},{transform:"scale(1)"}],{duration:300,easing:"ease-out"}),this.layer.announce(k(t?"Note is now public.":"Note is now private.","desktop-mode")),this.note.id>0&&this.queuePatch({public:t})}confirmTrash(){Ni({title:k("Move note to the Trash?","desktop-mode"),message:k("You can restore it from the Trash later.","desktop-mode"),confirmLabel:k("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 SR(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(ER(n)&&n.current){this.pendingText=null,this.replace(n.current),this.setPhase("idle"),this.layer.notifyError(k("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=BR();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:Fn,source:this.element,data:i,ghost:{element:o.root,offsetX:o.tipX,offsetY:o.tipY,hint:{neutral:k("Drop on the desktop to pin","desktop-mode"),accept:k("Pin here","desktop-mode"),reject:k("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*pR,i=o.top-t.top+o.height*hR,r=document.createElement("div");r.className="os-pinned-note-ghost",r.style.width=`${t.width}px`,r.style.height=`${t.height}px`;const l=document.createElement("div");l.className="os-pinned-note-ghost__swing",l.style.transformOrigin=`${s}px ${i}px`;const a=this.pinEl.cloneNode(!0);a.removeAttribute("aria-pressed"),a.setAttribute("aria-hidden","true");const c=this.paperEl.cloneNode(!0);return c.classList.add("os-pinned-note-ghost__paper"),l.dataset.noteColor=this.element.dataset.noteColor??"",l.append(a,c),r.appendChild(l),{root:r,swing:l,pin:a,paper:c,tipX:s,tipY:i}}installDragListeners(t){this.teardownDragListeners();let n=null;const o=l=>{l.detail?.payload?.data?.noteId===this.note.id&&(n=cR(t.swing))},s=l=>{const a=l.detail;this.lastPointer={x:a.clientX,y:a.clientY},n?.onPointerMove(a.clientX)},i=l=>{l.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.add("os-pinned-note-ghost--doom"),n?.setBias(6))},r=l=>{l.detail?.targetId?.startsWith("recycle-bin")&&(t.root.classList.remove("os-pinned-note-ghost--doom"),n?.setBias(0))};document.addEventListener(we.START,o),document.addEventListener(we.MOVE,s),document.addEventListener(we.ENTER,i),document.addEventListener(we.LEAVE,r),this.dragCleanup=()=>{n?.stop(),n=null,document.removeEventListener(we.START,o),document.removeEventListener(we.MOVE,s),document.removeEventListener(we.ENTER,i),document.removeEventListener(we.LEAVE,r)}}teardownDragListeners(){this.dragCleanup?.(),this.dragCleanup=null}async snapBack(t){if(!this.lastPointer||$n()){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 dR({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 uR({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(k("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(k("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?FR:UR,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(k("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 Jo=new Map;function VR(e,t){return Jo.set(e,t),()=>{Jo.get(e)===t&&Jo.delete(e)}}function qR(e){const t=Jo.get(e.type);return t?t.accept(e.data):!1}function KR(e,t){const n=Jo.get(e.payload.type);return n?(n.onDrop(e,t),!0):!1}function uy(e,t,n){const o=e.host.getBoundingClientRect(),s=t.payload.ghost?.offsetX??0,i=t.payload.ghost?.offsetY??0,{width:r,height:l}=e.hostSize();return e.clampPosition((n.clientX-s-o.left)/r,(n.clientY-i-o.top)/l)}function YR(e,t,n){const o=t.payload.data,s=String(o.text??"");if(!s.trim())return;const{x:i,y:r}=uy(e,t,n);e.createNoteAt({x:i,y:r,text:s,color:String(o.color??""),isPublic:o.isPublic===!0})}function XR(e,t,n){const o=t.payload.data,s=e.get(o.noteId);if(!s)return;const{x:i,y:r}=uy(e,t,n);s.moveTo(i,r)}function ZR(e){const t=[],n=o=>o.folderId===0;return t.push(Ew(NR,{accept:(o,s)=>n(s)&&!!String(o.text??"").trim(),onDrop:(o,s)=>YR(e,o,s)})),t.push(Ew(Fn,{accept:(o,s)=>n(s)&&o.canEdit===!0,onDrop:(o,s)=>XR(e,o,s)})),t.push(VR(Fn,{accept:o=>o.canEdit===!0,onDrop:(o,s)=>{const i=o.payload.data,r=e.get(i.noteId);if(!r)return;const l=r.note;r.playCrumpleAt(s.clientX,s.clientY),e.trashNote(l)}})),()=>{t.forEach(o=>o())}}const Cc="data-os-posts-drop-active",fy="desktop-mode-posts",JR='.os-dock__item[data-menu-slug="menu-posts"],.os-dock__item[data-menu-slug="editphp"]',QR="[data-os-posts-root]";function eO(){return window.wp?.os?.dragManager??null}function tO(e){return e.type!==Fn?!1:e.data.canEdit===!0}function nO(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 oO(e){const t=e.placement.file;if(!t||t.type!=="shortcut")return!1;const n=typeof t.shortcutUrl=="string"?t.shortcutUrl:"";return nO(n)}function py(e,t){if(t.payload.type!==Fn)return;const n=t.payload.data;if(typeof n.noteId!="number")return;const o=e.get(n.noteId);o&&e.convertNote(o.note)}let hy=!1,Qo=null,es=null,my=null;function gy(e,t,n,o){return e.registerDropTarget({id:n,element:o,acceptLabel:k("Convert to post","desktop-mode"),accept:s=>tO(s),onEnter:()=>{o.setAttribute(Cc,"")},onLeave:()=>{o.removeAttribute(Cc)},onDrop:s=>{o.removeAttribute(Cc),py(t,s)}})}function sO(e,t){const n=e.debug().listTargets().find(o=>o.id===t);return n?n.element:null}function iO(e){if(hy||!e.canCreatePosts)return;const t=eO();if(!t)return;hy=!0,Wi(Fn,{appliesTo:o=>oO(o),acceptLabel:k("Convert to post","desktop-mode"),accept:o=>o.canEdit===!0,onDrop:o=>py(e,o)});const n=()=>{const o=document.querySelector(JR);if(!(o instanceof HTMLElement)){Qo?.(),Qo=null;return}Qo&&sO(t,"notes-convert-dock")===o||(Qo?.(),Qo=gy(t,e,"notes-convert-dock",o))};n(),Y(_.DOCK_AFTER_RENDER,"desktop-mode/notes/convert-dock-target",n),typeof MutationObserver<"u"&&(my=new MutationObserver(()=>{n()}),my.observe(document.body,{childList:!0,subtree:!0})),Y(_.WINDOW_OPENED,"desktop-mode/notes/convert-window-target",o=>{if(o.windowId!==fy)return;es?.(),es=null;const s=document.querySelector(QR);s instanceof HTMLElement&&(es=gy(t,e,"notes-convert-window",s))}),Y(_.WINDOW_CLOSED,"desktop-mode/notes/convert-window-cleanup",o=>{o.windowId===fy&&(es?.(),es=null)})}const wy="new-note";function rO(e){zn("os.wallpaper-context-menu","desktop-mode/notes",(t,n)=>{if(!Array.isArray(t)||t.some(i=>i.id===wy))return t;const{x:o,y:s}=n??{x:0,y:0};return[...t,{id:wy,label:k("New note","desktop-mode"),icon:"dashicons-edit-page",sort:14,onClick:()=>{const i=e.normalizedFromClient(o,s);e.createNoteAt({...i,focus:!0})}}]})}function aO(e){const t=e.config.notesUrl;if(typeof t!="string"||!t)return null;bR({baseUrl:t,nonce:e.config.restNonce??""});const n=new GR({host:e.host,pluginUrl:e.config.pluginUrl??"",canCreatePosts:e.config.canCreatePosts??!1,onError:e.onError});return ZR(n),iO(n),rO(n),document.addEventListener(DR,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 lO={id:"clock",get label(){return k("Clock")},get description(){return k("Local time and date, refreshed every second.")},icon:"dashicons-clock",mount:e=>{e.classList.add("os-widget-clock");const t=document.createElement("div");t.className="os-widget-clock__time",e.appendChild(t);const n=document.createElement("div");n.className="os-widget-clock__date",e.appendChild(n);const o=()=>{const l=new Date;t.textContent=l.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}),n.textContent=l.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 cO(){Ja(lO)}async function dO(){const e=window;if(e.openStationReleaseCard)return e.openStationReleaseCard;const t=e.openStationConfig?.releaseCardBundleUrl??"";if(!t)return null;try{await Se(t)}catch{return null}return e.openStationReleaseCard??null}function yy(e,t){if(t){const o=k('WordPress %1$s "%2$s" is available.');return le(o,e,t)}const n=k("WordPress %s is available.");return le(n,e)}async function uO(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,l=`desktop-mode/core-update:${typeof t.available=="string"&&t.available?t.available:o}`;if(Va(l))return;const a=()=>n({url:t.url,title:k("WordPress Updates")}),d=e.resolveArt&&e.loadImage&&e.showCard?null:await dO(),u=e.resolveArt??d?.resolveReleaseArt,f=e.loadImage??d?.preloadImage,p=e.showCard??d?.showReleaseCard,g=u?await u(s):null;if(g&&g.artUrl&&f&&p&&await f(g.artUrl)){p({message:yy(o,i?g.name:""),artUrl:g.artUrl,dismissKey:l,onUpdate:a});return}X({message:yy(o,""),persistent:!0,dismissible:!0,onDismiss:()=>bi(l),action:{label:k("Update now"),onClick:a}})}function by(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(Va(i))continue;const r=s.actionLabel,l=s.actionUrl,a=s.title||r||"";let c;r&&l&&(c={label:r,onClick:()=>n({url:l,title:a})}),X({message:s.message,persistent:!0,dismissible:!0,onDismiss:()=>bi(i),action:c})}}const Ic="desktop-mode/starter",fO="desktop-mode/dev-mode-gate";let vy=!1;function pO({osSettings:e,layer:t}){if(vy)return;vy=!0,zn(_.WIDGETS,fO,o=>e.getOsSettingsSnapshot().developerModeEnabled?o:o.filter(s=>s.id!==Ic));let n=e.getOsSettingsSnapshot().developerModeEnabled;e.subscribeOsSettings(o=>{o.developerModeEnabled!==n&&(n=o.developerModeEnabled,n?t.mountIfEnabled(Ic):t.unmount(Ic),Eo())})}function hO(e){const{layer:t}=e,n=new Set,o=new Set,s=async a=>{if(!(!a.scriptUrl||o.has(a.scriptUrl))){try{await Se(a.scriptUrl,{translations:a.scriptTranslations,l10n:a.scriptL10n,before:a.scriptBefore,after:a.scriptAfter})}catch(c){L(_.SHELL_ERROR,{scope:"widget-script-load",id:a.id,error:c});return}o.add(a.scriptUrl)}},i=a=>{const d=(window.openStationWidgets||{})[a.id];return d?{id:a.id,label:a.label,description:a.description,icon:a.icon,movable:a.movable,resizable:a.resizable,minWidth:a.minWidth||void 0,minHeight:a.minHeight||void 0,maxWidth:a.maxWidth||void 0,maxHeight:a.maxHeight||void 0,defaultWidth:a.defaultWidth||void 0,defaultHeight:a.defaultHeight||void 0,mount:d}:(L(_.SHELL_ERROR,{scope:"widget-missing-mount",id:a.id,error:new Error(`[openstation] No mount callback on window.openStationWidgets["${a.id}"]. Plugin script loaded but didn't register. Check the plugin's enqueue + global assignment.`)}),null)},r=async a=>{if(n.has(a.id))return;await s(a);const c=i(a);if(c){try{Ja(c)}catch(d){L(_.SHELL_ERROR,{scope:"widget-register",id:a.id,error:d});return}n.add(a.id),Eo(),t&&t.mountIfEnabled(a.id)}},l=a=>{n.has(a)&&(t?.unmount(a),KA(a),n.delete(a),Eo())};return async a=>{const c=new Set;for(const d of a)c.add(d.id);for(const d of Array.from(n))c.has(d)||l(d);for(const d of a)n.has(d.id)||await r(d)}}const _y=["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"],Ey=new Set(_y),mO=2e3,xc=new Set,ky=new WeakSet;let Sy=!1;function gO(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 l=1;l<=o;l++){const a=s[l];s[l]=e[i-1]===t[l-1]?r:1+Math.min(r,s[l],s[l-1]),r=a}}return s[o]}function wO(e){let t=null,n=1/0;for(const o of Ey){const s=gO(e,o);s<n&&(n=s,t=o)}return n>0&&n<=3?t:null}function yO(e){return e.startsWith("os-")?e.slice(4):e}function bO(e,t){if(xc.has(e))return;if(xc.add(e),Ey.has(e)){const s=yO(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. |
| 287 |
|
| 288 |
Fix — side-effect-import the component module from wherever you render it: |
| 289 |
|
| 290 |
import '<rel>/ui/components/${s}/${s}'; |
| 291 |
|
| 292 |
Or pull every os-* component in one go (heavier — only do this from an entry bundle): |
| 293 |
|
| 294 |
import '<rel>/ui/components'; |
| 295 |
|
| 296 |
See docs/components-reference.md for the full list.`,` |
| 297 |
First offending element:`,t);return}const o=wO(e);if(o){console.error(`[wp.os] <${e}> is not a registered os-* component. Did you mean <${o}>? |
| 298 |
|
| 299 |
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'.`,` |
| 300 |
First offending element:`,t);return}console.error(`[wp.os] <${e}> looks like a os-* tag but no component by that name exists. |
| 301 |
|
| 302 |
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.`,` |
| 303 |
First offending element:`,t)}function Ay(e){const t=e.tagName.toLowerCase();if(!t.startsWith("os-")||xc.has(t)||customElements.get(t))return;let n=!1;customElements.whenDefined(t).then(()=>{n=!0}),setTimeout(()=>{n||customElements.get(t)||bO(t,e)},mO)}function Cy(e){e instanceof Element&&(Ay(e),e.shadowRoot&&er(e.shadowRoot));const t=e.querySelectorAll("*");for(let n=0;n<t.length;n++){const o=t[n];Ay(o),o.shadowRoot&&er(o.shadowRoot)}}function er(e){if(ky.has(e))return;ky.add(e),Cy(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&&Cy(r)}}}).observe(e,{childList:!0,subtree:!0})}function vO(){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"&&er(s),s};n.__wpdPatched=!0,e.attachShadow=n}function _O(){Sy||typeof document>"u"||(Sy=!0,vO(),er(document))}const Iy={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}},ee={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 te(e,t,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n[1],Math.max(n[0],e))}function xy(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 Ly(e,t){return typeof e=="boolean"?e:t}const EO=["circle","blob","ghost","potato","star","flower","heart","diamond","drop","cloud","custom"];function kO(e,t){return EO.includes(e)?e:t}function ts(e,t=Iy){const n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},o=n.appearance??{},s=n.physics??{},i={radius:te(o.radius,t.appearance.radius,ee.radius),bodyColor:xy(o.bodyColor,t.appearance.bodyColor),bodyAlpha:te(o.bodyAlpha,t.appearance.bodyAlpha,ee.bodyAlpha),hueStart:te(o.hueStart,t.appearance.hueStart,ee.hueStart),hueSpan:te(o.hueSpan,t.appearance.hueSpan,ee.hueSpan),hueDrift:te(o.hueDrift,t.appearance.hueDrift,ee.hueDrift),hueLoop:Ly(o.hueLoop,t.appearance.hueLoop),hueAngle:te(o.hueAngle,t.appearance.hueAngle,ee.hueAngle),hueSpin:te(o.hueSpin,t.appearance.hueSpin,ee.hueSpin),saturation:te(o.saturation,t.appearance.saturation,ee.saturation),lightness:te(o.lightness,t.appearance.lightness,ee.lightness),iridescence:te(o.iridescence,t.appearance.iridescence,ee.iridescence),outlineWidth:te(o.outlineWidth,t.appearance.outlineWidth,ee.outlineWidth),glow:te(o.glow,t.appearance.glow,ee.glow),glowBlur:Ly(o.glowBlur,t.appearance.glowBlur),eyeColor:xy(o.eyeColor,t.appearance.eyeColor),eyeScale:te(o.eyeScale,t.appearance.eyeScale,ee.eyeScale)},r={points:Math.round(te(s.points,t.physics.points,ee.points)),shapePreset:kO(s.shapePreset,t.physics.shapePreset),shapeLobes:Math.round(te(s.shapeLobes,t.physics.shapeLobes,ee.shapeLobes)),shapeAmount:te(s.shapeAmount,t.physics.shapeAmount,ee.shapeAmount),shapeAngle:te(s.shapeAngle,t.physics.shapeAngle,ee.shapeAngle),shapeShuffle:te(s.shapeShuffle,t.physics.shapeShuffle,ee.shapeShuffle),radialStiffness:te(s.radialStiffness,t.physics.radialStiffness,ee.radialStiffness),edgeStiffness:te(s.edgeStiffness,t.physics.edgeStiffness,ee.edgeStiffness),bendStiffness:te(s.bendStiffness,t.physics.bendStiffness,ee.bendStiffness),pressure:te(s.pressure,t.physics.pressure,ee.pressure),damping:te(s.damping,t.physics.damping,ee.damping),airDamping:te(s.airDamping,t.physics.airDamping,ee.airDamping),magnetStrength:te(s.magnetStrength,t.physics.magnetStrength,ee.magnetStrength),magnetRange:te(s.magnetRange,t.physics.magnetRange,ee.magnetRange),magnetGrip:te(s.magnetGrip,t.physics.magnetGrip,ee.magnetGrip),magnetDamping:te(s.magnetDamping,t.physics.magnetDamping,ee.magnetDamping),floatAmplitude:te(s.floatAmplitude,t.physics.floatAmplitude,ee.floatAmplitude),floatSpeed:te(s.floatSpeed,t.physics.floatSpeed,ee.floatSpeed),idleWobble:te(s.idleWobble,t.physics.idleWobble,ee.idleWobble),idleWobbleSpeed:te(s.idleWobbleSpeed,t.physics.idleWobbleSpeed,ee.idleWobbleSpeed),speedStretch:te(s.speedStretch,t.physics.speedStretch,ee.speedStretch),friction:te(s.friction,t.physics.friction,ee.friction),restitution:te(s.restitution,t.physics.restitution,ee.restitution),dragStiffness:te(s.dragStiffness,t.physics.dragStiffness,ee.dragStiffness),throwBoost:te(s.throwBoost,t.physics.throwBoost,ee.throwBoost),minStretch:te(s.minStretch,t.physics.minStretch,ee.minStretch),maxStretch:te(s.maxStretch,t.physics.maxStretch,ee.maxStretch),minAngularGap:te(s.minAngularGap,t.physics.minAngularGap,ee.minAngularGap),dragMaxAccel:te(s.dragMaxAccel,t.physics.dragMaxAccel,ee.dragMaxAccel),limitIterations:Math.round(te(s.limitIterations,t.physics.limitIterations,ee.limitIterations)),subStep:te(s.subStep,t.physics.subStep,ee.subStep),maxSubSteps:Math.round(te(s.maxSubSteps,t.physics.maxSubSteps,ee.maxSubSteps))};return{appearance:i,physics:r}}const Ty="desktop-mode-mio-position",Ny="os-mio",SO="os-mio-toggle",AO=`data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"> |
| 304 |
<defs><linearGradient id="mio" x1="19" y1="19" x2="5" y2="5" gradientUnits="userSpaceOnUse"> |
| 305 |
<stop offset="0" stop-color="#3f6dff"/><stop offset=".5" stop-color="#a855f7"/><stop offset="1" stop-color="#ff4fd8"/> |
| 306 |
</linearGradient></defs> |
| 307 |
<circle cx="12" cy="12" r="8.2" fill="none" stroke="url(#mio)" stroke-width="2.6"/> |
| 308 |
<rect x="8" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 309 |
<rect x="13.1" y="9.6" width="2.9" height="4.8" rx="1.45" fill="#fff"/> |
| 310 |
</svg>`)}`;class CO{constructor(t){this.layer=null,this.handle=null,this.parked=null,this.generation=0,this.loading=null,this.look=Xr(),this.options=t,this.enabled=t.enabled,this.look=Ef(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=ts(t,this.config),this.handle?.applyConfig(this.config)},setStyle:t=>{const n=FE(t);this.look={appearance:{...this.look.appearance,...n.appearance},physics:{...this.look.physics,...n.physics}},this.config=ts({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=Xr(),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),L(t?"os.mio.enabled":"os.mio.disabled",{}),L(_.DOCK_REFRESH_ACTIVE,{}),t?await this.mount():this.unmount())}resolveConfig(){const t=ts(this.options.serverConfig,Iy),n=G("os.mio.config",t),o=ts(n,t);return ts({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(Ny);if(t)return this.layer=t,t;const n=document.createElement("div");return n.id=Ny,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:IO(),savePosition:Dy});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&&Dy(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=Se(this.options.bundleUrl).catch(t=>{throw this.loading=null,t})}return this.loading}}function IO(){try{const e=window.localStorage.getItem(Ty);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 Dy(e){try{window.localStorage.setItem(Ty,JSON.stringify(e))}catch{}}const Ry=8,xO=e=>`<rect x="28" y="5" width="8" height="12" rx="2" fill="currentColor" transform="rotate(${360/Ry*e} 32 32)"/>`,LO='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">'+Array.from({length:Ry},(e,t)=>xO(t)).join("")+'<circle cx="32" cy="32" r="15.5" fill="none" stroke="currentColor" stroke-width="9"/></svg>',TO=`data:image/svg+xml;base64,${btoa(LO)}`,NO='<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>',DO=2400,Oy="os-notch";function RO(e,t){document.getElementById(Oy)?.remove();const n=document.createElement("button");n.type="button",n.id=Oy,n.className="os-notch",n.setAttribute("aria-label",k("Open the site assistant"));const o=document.createElement("span");o.className="os-notch__glyph",o.setAttribute("aria-hidden","true"),o.innerHTML=NO,n.appendChild(o);const s=document.createElement("span");s.className="os-notch__label",s.setAttribute("aria-hidden","true"),s.textContent=k("Site assistant"),n.appendChild(s);const i=document.createElement("span");i.className="os-notch__message",i.setAttribute("aria-live","polite"),n.appendChild(i),n.addEventListener("click",t);let r=null;const l=a=>{r!==null&&window.clearTimeout(r),i.textContent=a,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)},DO)};return e.appendChild(n),{say:l,destroy:()=>{r!==null&&window.clearTimeout(r),n.remove()}}}function OO(){return document.fullscreenElement!==null}function MO(){if(OO()){document.exitFullscreen?.().catch(()=>{});return}document.documentElement.requestFullscreen?.().catch(()=>{})}function My(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 PO(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"),l=document.createElement("tr");for(const c of i){const d=document.createElement("th");d.scope="col",d.textContent=s[c]??"",l.appendChild(d)}r.appendChild(l),o.appendChild(r);const a=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(My(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)}a.appendChild(d)}return o.appendChild(a),n.appendChild(o),t.appendChild(n),t}function WO(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(My(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 $O(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(PO(n.contextual)),n.general&&t.appendChild(WO(n.general)),e.appendChild(t)}const Lc="openstation-shortcuts",UO=`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 FO(e){e({id:Lc,baseId:Lc,url:"#os-shortcuts",title:window.openStationAdminBar?.shortcuts?.title?String(window.openStationAdminBar.shortcuts.title):"Keyboard shortcuts",icon:UO,native:!0,render:$O,width:760,height:560,minWidth:480,minHeight:360})}const Py="openstation-rebrand",BO=1200,HO="a[href], button:not([disabled])";async function zO(e){const t=e.seenIntrosUrl;if(t)try{await Be(`${t.replace(/\/$/,"")}/seen`,{method:"POST",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce??""},body:JSON.stringify({slug:Py})},{source:"desktop-mode/rebrand-notice",silent:!0})}catch{}}function GO(){const e=document.createElement("div");e.className="os-announce",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","os-announce-title"),e.setAttribute("aria-describedby","os-announce-desc");const t=document.createElement("div");t.className="os-announce__card",e.appendChild(t);const n=document.createElement("div");n.className="os-announce__hero",t.appendChild(n);const o=document.createElement("span");o.className="os-announce__eyebrow";const s=document.createElement("span");s.className="os-announce__eyebrow-dot",s.setAttribute("aria-hidden","true"),o.appendChild(s),o.appendChild(document.createTextNode(k("New name"))),n.appendChild(o);const i=document.createElement("h2");i.id="os-announce-title",i.className="os-announce__title",i.textContent=k("Desktop Mode is now OpenStation"),n.appendChild(i);const r=document.createElement("p");r.className="os-announce__subtitle",r.textContent=k("The beginning of a new identity."),n.appendChild(r);const l=document.createElement("div");l.className="os-announce__body",t.appendChild(l);const a=document.createElement("p");a.id="os-announce-desc",a.textContent=k("Why OpenStation? Because it represents much more than a desktop interface. It's an open workspace where WordPress becomes a complete environment for creating, managing and building, just like a real workstation, but powered by the web."),l.appendChild(a);const c=document.createElement("p");c.textContent=k("This update also comes with a new default theme that we hope you enjoy."),l.appendChild(c);const d=document.createElement("p");d.className="os-announce__fine",d.textContent=k("Everything is already set up. You don't need to install any new plugins, so you can keep using the same features as before."),l.appendChild(d);const u=document.createElement("div");u.className="os-announce__actions",t.appendChild(u);const f=document.createElement("button");return f.type="button",f.className="os-announce__btn os-announce__btn--primary",f.dataset.rebrandDismiss="",f.textContent=k("Got it"),u.appendChild(f),e}async function jO(e){const{config:t}=e;if(!t.rebrandNotice||t.seenIntros?.includes(Py))return;await new Promise(c=>window.setTimeout(c,BO));const n=GO(),o=n.querySelector(".os-announce__card"),i=document.activeElement;let r=!1;const l=()=>{r||(r=!0,document.removeEventListener("keydown",a,!0),n.remove(),i?.focus?.(),zO(t))};function a(c){if(!n.isConnected){document.removeEventListener("keydown",a,!0);return}if(c.key==="Escape"){c.preventDefault(),l();return}if(c.key!=="Tab")return;const d=Array.from(n.querySelectorAll(HO));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)&&l()});for(const c of n.querySelectorAll("[data-rebrand-dismiss]"))c.addEventListener("click",l);document.addEventListener("keydown",a,!0),document.body.appendChild(n),n.querySelector(".os-announce__btn--primary")?.focus()}const VO=new Set(["post"]);function Wy(){const e=window.wp?.os?.myWordpress;return e&&typeof e.trashEntity=="function"?e:null}const Tc="data-os-trash-drop-active",Yt="desktop-mode-recycle-bin",qO=[{id:"recycle-bin-tile",selector:`.os-file-tile[data-file-ref="${Yt}"]`},{id:"recycle-bin-icon",selector:`[data-icon-id="${Yt}"]`},{id:"recycle-bin-dock",selector:`[data-system-id="${Yt}"]`}];let $y=!1;const Nc=new Map;let ns=null,Uy=null;function KO(e){return e.payload.type==="desktop-file"}function YO(e){return e.payload.type==="shortcut"}function XO(e){if(!e.kind||!e.ref||!e.entityId||!VO.has(e.kind))return!1;const t=Number.parseInt(e.ref,10);return!Number.isFinite(t)||t<=0?!1:Wy()!==null}function Fy(e,t,n){return e.registerDropTarget({id:t,element:n,acceptLabel:k("Move to Trash","desktop-mode"),accept:o=>{if(o.type==="desktop-file"){const s=o.data,i=s?.placement;if(!i)return!1;const r=Mn(s);return r.length>1?r.every(l=>l.file?.ref!==Yt&&l.canTrash!==!1):i.file?.ref===Yt?!1:i.canTrash!==!1}if(o.type==="shortcut"){const s=o.data,i=Bi(s);return i.length>0&&i.every(r=>XO(r))}return qR(o)},onEnter:()=>{n.setAttribute(Tc,"")},onLeave:()=>{n.removeAttribute(Tc)},onDrop:(o,s)=>{if(n.removeAttribute(Tc),KO(o)){ww(Mn(o.payload.data));return}if(!(o.payload.type!=="shortcut"&&KR(o,s))&&YO(o)){const i=Wy();if(!i?.trashEntity)return;const r=i.trashEntity,a=Bi(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(a.length===0)return;Promise.allSettled(a.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=a.length-d.length;(u>1||d.length>0)&&X({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 ZO(e){if($y)return;$y=!0;const t=()=>{for(const{id:n,selector:o}of qO){const s=document.querySelector(o),i=s instanceof HTMLElement?s:null,r=Nc.get(n);if(!i){r?.deregister(),Nc.delete(n);continue}r&&r.el===i||(r?.deregister(),Nc.set(n,{el:i,deregister:Fy(e,n,i)}))}};if(t(),document.addEventListener("os-files-changed",t),Y(_.DESKTOP_ICONS_RENDERED,"desktop-mode/files/recycle-bin-icons-target",t),Y(_.DOCK_AFTER_RENDER,"desktop-mode/files/recycle-bin-dock-target",t),typeof MutationObserver<"u"){Uy=new MutationObserver(()=>{t()});const n=document.getElementById("os-area")??document.body;Uy.observe(n,{childList:!0,subtree:!0})}Y(_.WINDOW_OPENED,"desktop-mode/files/recycle-bin-window-target",n=>{if(n.windowId!==Yt)return;ns?.(),ns=null;const o=document.querySelector("[data-os-recycle-bin-root]");o instanceof HTMLElement&&(ns=Fy(e,"recycle-bin-window",o))}),Y(_.WINDOW_CLOSED,"desktop-mode/files/recycle-bin-window-cleanup",n=>{n.windowId===Yt&&(ns?.(),ns=null)})}function Dc(e){const t=e.placement.file;return!t||t.type!=="user"||t.isAgent!==!0?null:t}function JO(){const e=window.openStationConfig;return e?.restUrl&&e?.restNonce?{restRoot:e.restUrl,restNonce:e.restNonce}:null}function By(e){return{appliesTo(t){return Dc(t)!==null},accept(t,n){const o=Dc(n);if(!o)return!1;const s=jg({type:e,data:t});return zT(o.agentDragKinds??null,s,Number.parseInt(String(o.ref??""),10)||void 0)},acceptLabel:k("Send to agent","desktop-mode"),onDrop(t,n,o){const s=Dc(o);if(!s)return;const i=jg({type:t.payload.type,data:t.payload.data}),r=JO();!i||!r||qT({id:Number.parseInt(String(s.ref??""),10),name:String(s.title??""),description:"",avatarUrl:String(s.previewUrl??"")},i,r)}}}let Hy=!1;function QO(){Hy||(Hy=!0,Wi("shortcut",By("shortcut")),Wi("desktop-file",By("desktop-file")))}let zy=!1,Xt=0;function e1(){zy||(zy=!0,xe.contribute("openstation_files_subscribe",()=>{const e=At(),t={};for(const[n,o]of e.folders)t[String(n)]=o.updatedAtMs;return{folderVersions:t,placementsVersion:Xt,sharesVersion:Ze().state.sharesVersion}}),xe.subscribe("openstation_files",e=>{t1(e)}))}function t1(e){const t=e.folders??[];for(const i of t)jl(i,"remote"),i.updatedAtMs>Xt&&(Xt=i.updatedAtMs);const n=e.placements??[];for(const i of n)Mi(i,"remote"),i.updatedAtMs>Xt&&(Xt=i.updatedAtMs);const o=e.removed??{};for(const i of o.folders??[])Vl(i,"remote");for(const i of o.placements??[])$o(i,"remote");typeof e.serverTimeMs=="number"&&e.serverTimeMs>Xt&&(Xt=e.serverTimeMs);const s=e.shares?.pending;if(Array.isArray(s)&&s.length>0&&Fw(s),e.truncated){const i=Array.from(At().hydratedFolders);for(const r of i)Te(r).then(l=>{pt(r,l.placements)}).catch(()=>{})}}let Gy=!1;const n1=[];function o1(){if(Gy)return;Gy=!0;const e=t=>{const n=t;!n||n.action!=="untrashed"||s1()};n1.push(wn("os.placement.changed",e),wn("os.shortcut.changed",e),wn("os.folder.changed",e))}function s1(){Hl().then(t=>{Pi(t.folders)}).catch(t=>{console.error("[openstation] files restore-sync: listFolders failed",t)});const e=Array.from(At().hydratedFolders);for(const t of e)Te(t).then(n=>{pt(t,n.placements)}).catch(n=>{console.error("[openstation] files restore-sync: listPlacements failed for",t,n)})}const os="os-wallpaper-menu";let Bn=null;function jy(){return Bn!==null}let Vy=0;function i1(e,t,n,o={}){ss();const s=++Vy;Ns(()=>s===Vy,()=>r1(e,t,n,o))}function r1(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(os),s.style.left=`${t.x}px`,s.style.top=`${t.y}px`;const i=new Map;let r=null,l=null;const a=()=>{r&&(r.remove(),r=null,l=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",qy(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}a()}),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(),l&&l.id===p.id){a();return}const g=s.querySelector(`[data-menu-item-id="${p.id}"]`);g&&c(p,g);return}ss(),p.onClick(new MouseEvent("click"))}});function c(u,f){a();const p=document.createElement("os-context-menu");p.setAttribute("open",""),p.classList.add(os,`${os}--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",qy(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(),ss(),m.onClick(new MouseEvent("click"))}),p.appendChild(h)}document.body.appendChild(p),r=p,l=u,Hf(p,f)}e.appendChild(s),Bn=s,aa(s);const d=mg(s,{close:()=>ss(),siblingSelectors:[`.${os}--flyout`],excludeOutsideTarget:o.excludeOutsideTarget});s.addEventListener("wallpaper-menu-closed",d),L("os.wallpaper-menu.opened",{items:n.map(u=>u.id)})}function ss(){Bn&&(document.querySelectorAll(`.${os}--flyout`).forEach(e=>e.remove()),Bn.dispatchEvent(new CustomEvent("wallpaper-menu-closed")),Bn.remove(),Bn=null,L("os.wallpaper-menu.closed",{}))}function a1(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:"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=>l1(i,e)),o=[...t,...n],s=G("os.wallpaper-context-menu",o,{x:e.position?.x??0,y:e.position?.y??0});return Array.isArray(s)?s:o}function l1(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()}L("os.wallpaper-context-menu.activated",{id:e.id,callbackId:e.callbackId??""})}}}function qy(e){return e.replace(/[^a-zA-Z0-9_-]/g,"")}const is="os-url-dialog";let rs=null;function Rc(){rs&&(rs.dispatchEvent(new CustomEvent("url-dialog-closed")),rs.remove(),rs=null,L("os.files.url-dialog.closed",{}))}function c1(e){if(Rc(),G("os.files.url-dialog",null,e)===!1)return;const n=document.createElement("div");n.className=`${is}__overlay os-create-folder-dialog__overlay`,n.setAttribute("role","presentation");const o=document.createElement("div");o.className=`${is} os-create-folder-dialog`,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-labelledby",`${is}-title`);const s=document.createElement("h2");if(s.id=`${is}-title`,s.className="os-create-folder-dialog__title",s.textContent=e.title,o.appendChild(s),e.description){const h=document.createElement("p");h.className=`${is}__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 l=document.createElement("p");l.className="os-create-folder-dialog__error",l.hidden=!0,l.setAttribute("role","alert"),o.appendChild(l);const a=document.createElement("div");a.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",a.appendChild(c),a.appendChild(d),o.appendChild(a),n.appendChild(o),document.body.appendChild(n),rs=n,$i(i),L("os.files.url-dialog.opened",{});const u=h=>{Gt(i,h),Gt(r,h),Gt(c,h),Gt(d,h),o.classList.toggle("os-create-folder-dialog--busy",h)},f=h=>{l.textContent=h,l.hidden=!1},p=()=>{Rc(),e.onCancel?.()},g=async()=>{const h=Zl(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=Zl(i).trim();l.hidden=!0,u(!0);try{await e.onSubmit({name:y,url:b}),Rc()}catch(C){u(!1),f(C instanceof Error?C.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 Ky=[];let Oc=!1;(function(){const t=window;if(t.wp||(t.wp={}),t.wp.os)return;const n={whenReady(o){if(typeof o=="function"){if(Oc){Promise.resolve().then(o);return}Ky.push(o)}},ready(o){n.whenReady(o)},isReady(){return Oc}};t.wp.os=n})();const tr="desktop-mode-os-settings";let Mc=[],nr=Number.POSITIVE_INFINITY,Pc=!1;function Ke(e,t=1500){if(Mc.push(e),t<nr&&(nr=t),Pc)return;Pc=!0;const n=()=>{const o=Mc;Mc=[],nr=Number.POSITIVE_INFINITY,Pc=!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:nr}):window.setTimeout(n,0)}function Yy(){const e=window.openStationConfig;if(!e)return;const t=document.getElementById("os-area");if(!t)return;const n=new aE(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 l=null;cO(),z0(),r&&(l=new EC(r,s)),rp({id:"pixijs",url:`${s}/assets/vendor/pixi.min.js`,isReady:()=>typeof window.PIXI<"u"});const a=new J0({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));a.apply();const c=document.getElementById("os-shell"),d=new CO({shell:c??document.body,bundleUrl:e.mioBundleUrl??"",serverConfig:e.mio,enabled:a.state.mioEnabled,persist:A=>{a.state.mioEnabled=A,a.save()},savedLook:a.state.mioStyle,persistLook:A=>{a.state.mioStyle=A,a.save()}}),u=d.api();d.boot(),l&&pO({osSettings:a,layer:l});const f=new YC({aiSearchUrl:e.aiSearchUrl??"",restNonce:e.restNonce,adminUrl:e.adminUrl,isAiAvailable:()=>e.aiAssistant?.available===!0&&e.aiAssistant?.assistantProviderConfigured===!0,isOverrideEnabled:()=>a.getOsSettingsSnapshot().ai.enabled!==!1},e.aiAssistantBundleUrl??"");f.attachAsk(eI({config:()=>e,fallbackContext:()=>({close:()=>f.close(),openInWindow:(A,B,V)=>{n.open({url:A,title:B,icon:V??"dashicons-admin-generic"})},confirm:A=>Ni({message:A})})}));const p=new jI,g=new ax;document.addEventListener(we.START,A=>{const V=A.detail?.payload;if(!V||V.type!=="shortcut"&&V.type!=="desktop-file")return;const ne=V.data?.bridgePayload;ne&&p.start(ne)}),document.addEventListener(we.END,()=>{p.end()}),Ke(()=>bx(g)),Ke(()=>Rx(n)),window.addEventListener("message",A=>{if(A.origin!==window.location.origin)return;const B=A.data;!B||B.type!=="os-drop-failed"||X({message:"Could not insert into the editor."})}),sg({id:"desktop-mode-ai-assistant",label:"AI Assistant",open:()=>f.open(),close:()=>f.close(),isOpen:()=>f.isOpen}),Ux(),cE(n),hE(n),Ke(()=>{new UA({manager:n,adminUrl:e.adminUrl}).install(),new qA({manager:n,adminUrl:e.adminUrl}).install()}),document.addEventListener("os-open-ai",()=>{pl("desktop-mode-ai-assistant")}),document.addEventListener("click",A=>{const B=A.target;!(B instanceof Element)||!B.closest("#wp-admin-bar-command-palette")||(A.preventDefault(),A.stopImmediatePropagation(),pl("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,C=!1;const w=A=>A.some(B=>!!B.windowId&&n.getAllByBaseIdOnActiveDesktop(B.windowId).length>0),E=RC({manager:n,appendSystemTile:A=>y?.appendSystemTile(A),removeSystemTile:A=>y?.removeSystemTile(A)}),T=E.sync;bE({getSnapshot:()=>a.getOsSettingsSnapshot(),openById:(A,B)=>E.openById(A,B),adminUrl:e.adminUrl});const M=A=>{const B=ae(A,e.adminUrl),V=y?y.getMenuItems():e.dockItems??[];for(const ne of V){if(ae(ne.url,e.adminUrl)===B)return{title:ne.title,icon:ne.icon,url:ne.url,submenu:ne.submenu,selfLabel:ne.selfLabel,multi:ne.multi};for(const ge of ne.submenu??[])if(ae(ge.url,e.adminUrl)===B)return{title:ge.title,icon:ne.icon,url:ne.url,multi:ne.multi}}return null};if(OE({adminUrl:e.adminUrl,deriveSlug:A=>ae(A,e.adminUrl),openWindow:A=>{n.open(A)},findDockEntry:M}),ln({id:"desktop-mode-posts",nativeWindowId:"desktop-mode-posts",matches:(A,B)=>{if(!B.pathname.endsWith("/edit.php"))return!1;const V=B.searchParams.get("post_type");return!V||V==="post"},enabled:A=>A.nativePostsEnabled===!0}),ln({id:"desktop-mode-pages",nativeWindowId:"desktop-mode-pages",matches:(A,B)=>B.pathname.endsWith("/edit.php")?B.searchParams.get("post_type")==="page":!1,enabled:A=>A.nativePagesEnabled===!0}),ln({id:"desktop-mode-users",nativeWindowId:"desktop-mode-users",matches:(A,B)=>B.pathname.endsWith("/users.php"),enabled:A=>A.nativeUsersEnabled===!0}),ln({id:"desktop-mode-user-edit",nativeWindowId:"desktop-mode-user-edit",matches:(A,B)=>{if(yE(B))return!1;const V=B.pathname;return V.endsWith("/profile.php")?!0:V.endsWith("/user-edit.php")?B.searchParams.has("user_id"):!1},enabled:A=>A.nativeUsersEnabled===!0,onMatch:(A,B)=>{const V=parseInt(B.searchParams.get("user_id")??"0",10);V>0&&tk(V)}}),ln({id:"desktop-mode-comments",nativeWindowId:"desktop-mode-comments",matches:(A,B)=>B.pathname.endsWith("/edit-comments.php"),enabled:A=>A.nativeCommentsEnabled===!0,onMatch:(A,B)=>{const V=parseInt(B.searchParams.get("p")??"0",10);V>0?ip(V):ok()}}),ln({id:"desktop-mode-plugins",nativeWindowId:"desktop-mode-plugins",matches:(A,B)=>{const V=B.pathname;return V.endsWith("/plugins.php")||V.endsWith("/plugin-install.php")},enabled:A=>A.nativePluginsEnabled===!0,onMatch:(A,B)=>{const V=B.pathname.endsWith("/plugin-install.php")?"browse":"installed";Promise.resolve().then(()=>$1).then(ne=>{ne.setPluginsWindowTab(V)})}}),m&&h&&b&&e.dockItems){t.classList.add("os-area--with-dock");const A=a.getOsSettingsSnapshot(),B=A.desktopLayout,V=A.dockPlacement,ne=be=>{fm(t,be,{openWindow:E.openById,manager:n,deriveWindowId:Ce=>ae(Ce,e.adminUrl)})};y=qC({shellRoot:h,shellBody:b,bottomDockEl:m,desktopArea:t,windowManager:n,adminUrl:e.adminUrl,renderIcons:ne,getSettings:()=>{const be=a.getOsSettingsSnapshot();return{itemVisibility:be.itemVisibility,dockOrder:be.dockOrder}}},B,e.dockItems,e.desktopIcons,V),XS({windowManager:n,adminUrl:e.adminUrl,getMenuItems:()=>y?.getMenuItems()??[],getSystemItem:be=>y?.getSystemTile(be)??null}),RO(h,()=>{document.dispatchEvent(new CustomEvent("os-open-ai"))});const ge=PI(e.pwa?.appName||"WordPress",X),gt={id:Kv,title:"System",icon:Xv,order:Bs.system,onOpen:P,get submenu(){const be=[{title:"OpenStation Preferences",url:"",windowId:tr,onSelect:()=>P()}];return e.homeUrl&&be.push({title:"View site",url:e.homeUrl}),be.push({title:"Fullscreen",url:"",onSelect:MO},{title:"Keyboard shortcuts",url:"",windowId:Lc,onSelect:()=>FO(Ce=>{n.open(Ce)})},{title:"Report a bug",url:"",windowId:Lo,onSelect:()=>v()}),!Im()&&!C&&be.push({title:ge.title,url:"",onSelect:ge.onOpen}),e.logoutUrl&&be.push({title:"Log out",url:"",onSelect:()=>{window.location.assign(e.logoutUrl)}}),be},isOpen:()=>w(gt.submenu??[])};y.appendSystemTile(gt,"core"),xm().then(be=>{C=be})}function P(A={}){const B={extended:"features",effects:"windows"},V=A.tabId?B[A.tabId]:void 0;V&&(A={...A,tabId:V}),A.tabId&&(a.activeTabId=A.tabId),n.open({id:tr,baseId:tr,url:"#os-settings",title:"OpenStation Preferences",icon:TO,native:!0,render:ne=>a.renderPanel(ne),width:820,height:720,minWidth:560,minHeight:480}),A.tabId&&a.focusTab(A.tabId)}function v(){n.open({id:Lo,baseId:Lo,url:`#${Lo}`,title:"Report a bug",icon:"dashicons-buddicons-replies",native:!0,render:A=>bI(A),width:560,height:620,minWidth:420,minHeight:480})}document.addEventListener("os-open-bug-report",()=>{v()}),y&&(y.appendSystemTile(Jv(),"core"),y.appendSystemTile({id:SO,title:"Mio",icon:AO,placeable:!0,order:Bs.mio,isOpen:()=>u.isEnabled(),onOpen:()=>{u.toggle()}},"plugin"),y.appendSystemTile({id:qv,title:"Overview",icon:Yv,order:Bs.overview,isOpen:()=>n._overviewActive,onOpen:()=>{n._overviewActive?n.exitOverview():n.enterOverview()}},"plugin"));const $=y?.getPrimary()??null;T(Array.isArray(e.nativeWindows)?e.nativeWindows:[]);const D=$L(e.session);function I(A){return A===tr?(P(),!0):A===Lo?(v(),!0):E.openById(A)}const W=typeof e.soloWindow=="string"?e.soloWindow:"";W&&queueMicrotask(()=>{if(I(W))return;const A=W.startsWith("os-game-")?W.slice(8):"";if(A){wp.launch(A).catch(B=>{typeof console<"u"&&console.error("[openstation] solo game failed to launch:",B)});return}typeof console<"u"&&console.error(`[openstation] solo window "${W}" is not registered; nothing to paint.`)});const z=D&&!W?FL(n,e,t,I).catch(A=>{typeof console<"u"&&console.error("[openstation] session restore failed:",A)}):Promise.resolve(),q=e.defaultWindow?.enabled!==!1,K=e.defaultWindow?.url??"",x=typeof K=="string"&&K.startsWith("native:");!W&&HL({fromPortal:e.fromPortal,fromPortalIntent:e.fromPortalIntent,hasSession:D,defaultEnabled:q,isNativeDefault:x})&&z.then(()=>BL(n,e).catch(A=>{typeof console<"u"&&console.error("[openstation] openCurrentPage failed:",A)}));const F=VL(n,e);KL(F);const R=async A=>{try{const B=await xl(n,e.defaultWindowUrl,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","X-WP-Nonce":e.restNonce},body:JSON.stringify({url:A})},{source:"desktop-mode/default-window"});if(!B.ok)throw new Error(`HTTP ${B.status}`);const V=await B.json();e.defaultWindow=V,document.dispatchEvent(new CustomEvent("os-default-window-changed",{detail:V}))}catch(B){L(_.SHELL_ERROR,{scope:"default-window-save",error:B}),typeof console<"u"&&console.error("[openstation] Failed to save default window:",B)}};if(n.onToggleStartupRequested=A=>{const B=e.defaultWindow,V=!!A.config.native,ne=V?`native:${A.id}`:A.getCurrentUrl(),ge=V?B?.url===ne:Jc(B?.url??"")===Jc(ne),gt=!!B?.enabled&≥R(gt?null:ne)},e.defaultWindow?.enabled&&e.fromPortal&&!e.fromPortalIntent&&!D&&x){const A=K.slice(7);queueMicrotask(()=>{I(A)})}const S=A=>{y?.appendSystemTile(A)},O=hO({layer:l});O(Array.isArray(e.serverWidgets)?e.serverWidgets:[]);const U=Ik({osSettings:a});U(Array.isArray(e.serverWallpapers)?e.serverWallpapers:[]),Y(_.WALLPAPERS_SERVER_CHANGED,"desktop-mode/wallpapers-server-sync",A=>{const B=A?.wallpapers;Array.isArray(B)&&U(B)});const N=Lk();N(Array.isArray(e.serverGames)?e.serverGames:[]);const H=Tk();H(Array.isArray(e.serverDesktopThemes)?e.serverDesktopThemes:[]);const Z=Gk();Z(Array.isArray(e.serverCommandScripts)?e.serverCommandScripts:[],Array.isArray(e.serverCommands)?e.serverCommands:[]);const se=qk();se(Array.isArray(e.serverSettingsTabScripts)?e.serverSettingsTabScripts:[],Array.isArray(e.serverSettingsTabs)?e.serverSettingsTabs:[]);const oe=Jk();oe(Array.isArray(e.serverTitleBarButtonScripts)?e.serverTitleBarButtonScripts:[]);const _e=sS();_e(Array.isArray(e.serverWindowActionScripts)?e.serverWindowActionScripts:[]);const pe=PS();pe(Array.isArray(e.serverUnfocusEffectScripts)?e.serverUnfocusEffectScripts:[]);const ye=WS();ye(Array.isArray(e.serverWindowLinkRendererScripts)?e.serverWindowLinkRendererScripts:[]),US({manager:n,osSettings:a}),m_({osSettings:a}),DE({manager:n}),gS({manager:n,osSettings:a}),vS({manager:n,openUrl:A=>{if(Ge(A.url))return;const B=ae(A.url,e.adminUrl);n.open({id:B,baseId:B,url:A.url,title:A.label,icon:A.icon||"dashicons-admin-links"})}}),DS({manager:n});const he=FS();he(Array.isArray(e.serverDockRailRendererScripts)?e.serverDockRailRendererScripts:[]),uA()(Array.isArray(e.serverWindowThemeScripts)?e.serverWindowThemeScripts:[],Array.isArray(e.serverWindowThemes)?e.serverWindowThemes:[]),hA(),mA()(Array.isArray(e.serverWindowControlScripts)?e.serverWindowControlScripts:[],Array.isArray(e.serverWindowControls)?e.serverWindowControls:[]),yA()(Array.isArray(e.serverWindowSlotScripts)?e.serverWindowSlotScripts:[],Array.isArray(e.serverWindowSlots)?e.serverWindowSlots:[]),Oh(Array.isArray(e.serverWindowNotices)?e.serverWindowNotices:[]),TA()(Array.isArray(e.serverWindowChromeScripts)?e.serverWindowChromeScripts:[],Array.isArray(e.serverWindowChromes)?e.serverWindowChromes:[]);const Cs=OA(n);_S(n),Ke(()=>ES()),mE(),Y("os.shell.toast","desktop-mode/shell-toast",A=>{!A||typeof A.message!="string"||X({message:A.message,action:A.action,duration:A.duration})});const Vc=e,Z1=Vc.recycleBinCount;sI(Number(Z1)||0,typeof Vc.recycleBinCountUrl=="string"?Vc.recycleBinCountUrl:""),pI({getRecycleBinCount:oI}),window.__openStationConnectionBridge=Cs,Y(_.WINDOW_CLOSED,"desktop-mode/connection-cleanup",A=>{A?.windowId&&Cs.onWindowClosed(A.windowId)}),Y(_.IFRAME_READY,"desktop-mode/connection-rearm",A=>{A?.windowId&&Cs.onIframeReady(A.windowId)});const J1=TC(n),Q1=WL({layoutDispatcher:y,desktopArea:t,config:e,syncNativeWindows:T,syncServerWidgets:O,syncServerWallpapers:U,syncServerCommands:Z,syncServerSettingsTabs:se,syncServerTitleBarButtons:oe,syncServerWindowActions:_e,syncServerUnfocusEffects:pe,syncServerWindowLinkRenderers:ye,syncServerDockRailRenderers:he,syncServerGames:N,syncServerDesktopThemes:H,renderIcons:A=>{if(y){y.applyDesktopIcons(A);return}fm(t,A,{openWindow:E.openById,manager:n,deriveWindowId:B=>ae(B,e.adminUrl)})},syncShortcuts:()=>{const A=a.getOsSettingsSnapshot();Zo(A.itemVisibility,A.dockPromotedPositions)}});document.addEventListener(Jf,()=>{y&&y.setLayout(y.getLayout());for(const A of n._stack)try{A.repaintWindowControls(),A.repaintThemedChrome()}catch(B){L(_.SHELL_ERROR,{scope:"desktop-theme-repaint",id:A.id,error:B})}}),a.subscribeOsSettings(A=>{if(!y)return;const B=y.getLayout(),V=y.getDockPlacement();y.setDockPlacement(A.dockPlacement),y.setLayout(A.desktopLayout),Is.dock=y.getPrimary(),Is.sideDock=y.getSide(),Is.desktopLayout=A.desktopLayout,Is.dockPlacement=y.getDockPlacement(),B===A.desktopLayout&&V===A.dockPlacement&&y.refresh(),Zo(A.itemVisibility,A.dockPromotedPositions),Og(A.desktopLayout)}),YD(()=>a.getOsSettingsSnapshot().itemVisibility,()=>a.getOsSettingsSnapshot().dockPromotedPositions),Og(a.getOsSettingsSnapshot().desktopLayout);const Is=TT({manager:n,dock:$,layoutDispatcher:y,osSettings:a,iconsApi:HC,filesApi:We,saveSession:F,widgetLayer:l,registerWindow:J1,openWindowById:E.openById,openNewWindowById:E.openNewById,placeSystemTile:S,setDefaultWindow:R,refreshMenu:Q1,openOsSettings:P,aiAssistant:f,dragBridge:p,dragManager:g,connect:Cs.connect,getConnection:Cs.getConnection,mio:u,wallpaperSuspend:{suspend:A=>i?.suspend(A),resume:A=>i?.resume(A),isSuspended:()=>i?.isSuspended()??!1},config:e});NT(Is),Ke(()=>ZO(g)),Ke(()=>QO()),Nk(),c_(),e.gamesEnabled!==!1&&Fk({currentUserId:Number(e.currentUserId)||0}),Ke(()=>fL()),Ke(()=>hL()),Ke(()=>IL({currentUserId:Number(e.currentUserId)||0})),aO({host:t,config:e,onError:A=>{X({message:A})}}),UT({openUrl:({id:A,url:B,title:V,icon:ne})=>(Ge(B)||n.open({id:A,baseId:A,url:B,title:V,icon:ne}),!0),openNativeWindow:A=>E.openById(A),deriveWindowId:A=>ae(A,e.adminUrl)}),$g(e.userFileAssociations??{}),uO({update:e.coreUpdate,openUrl:({url:A,title:B})=>{Ge(A)||n.open({id:"update-core",baseId:"update-core",url:A,title:B,icon:"dashicons-update"})}});const lb=({url:A,title:B})=>{if(Ge(A))return;const V=ae(A,e.adminUrl);n.open({id:V,baseId:V,url:A,title:B,icon:"dashicons-info"})};if(by({notices:e.coreNotices,openUrl:lb}),by({notices:e.pluginNotices,openUrl:lb,keyPrefix:"plugin-notice"}),jO({config:e}),typeof e.filesUrl=="string"&&e.filesUrl){qg({baseUrl:e.filesUrl,nonce:e.restNonce});const A=document.getElementById("os-area");if(A){const B=kw(A,0),V=()=>{t.classList.contains("os-area--booting")&&requestAnimationFrame(()=>{t.classList.remove("os-area--booting")})},ne=setTimeout(V,2e3);B.hydrated.then(()=>{clearTimeout(ne),V()})}}Ke(()=>e1()),Ke(()=>o1()),Ke(()=>Hx()),L(_.COMPONENTS_REGISTERED,{tags:[..._y]}),Mx(),FI(e,X);const cb=()=>{Ab(e.shellOverlaysBundleUrl??""),Eb(e.windowSystemBundleUrl??"")};typeof window.requestIdleCallback=="function"?window.requestIdleCallback(cb,{timeout:1500}):window.setTimeout(cb,0),L(_.INIT,{config:e}),Oc=!0;const eM=Ky.splice(0);for(const A of eM)try{A()}catch(B){L(_.SHELL_ERROR,{scope:"when-ready-cb",error:B}),typeof console<"u"&&console.error("[openstation] whenReady cb threw:",B)}a.apply(),l?.hydrate(),window.addEventListener("pagehide",()=>{i?.teardownActive(),l?.disposeAll()}),YL(),xL(n,e);const db=(A,B=!0)=>{const V=We.store.getState().placementsByFolder.get(0)??[],ne=A(V),ge=Math.max(1,Math.floor((t.clientHeight-16)/110)),gt=new Set;let be=0;for(const Ce of ne){const Re=It(16+Math.floor(be/ge)*96,16+be%ge*110,gt,t);gt.add(`${Re.col},${Re.row}`),be++,!(Ce.x===Re.x&&Ce.y===Re.y)&&(We.store.upsertPlacement({...Ce,x:Re.x,y:Re.y,sortOrder:be}),!(!B||Hi(Ce))&&Tn(Ce.id,{x:Re.x,y:Re.y,sortOrder:be}).catch(wt=>{console.error("[openstation] relayout persist failed",wt)}))}},ub=A=>B=>{const V=B.slice();switch(A){case"name-asc":V.sort((ne,ge)=>ne.file.title.localeCompare(ge.file.title));break;case"name-desc":V.sort((ne,ge)=>ge.file.title.localeCompare(ne.file.title));break;case"date-asc":V.sort((ne,ge)=>ne.updatedAtMs-ge.updatedAtMs);break;case"date-desc":V.sort((ne,ge)=>ge.updatedAtMs-ne.updatedAtMs);break}return V},qc="desktop-mode:root-sort-mode",tM=A=>A==="name-asc"||A==="name-desc"||A==="date-asc"||A==="date-desc";let lr=(()=>{try{const A=window.localStorage.getItem(qc);return tM(A)?A:null}catch{return null}})();const fb=A=>{lr=A;try{A?window.localStorage.setItem(qc,A):window.localStorage.removeItem(qc)}catch{}};if(Y("os.files.tile-manually-placed","desktop-mode/root-sort-clear",A=>{A?.folderId===0&&fb(null)}),typeof ResizeObserver<"u"){let A=t.clientWidth,B=t.clientHeight;new ResizeObserver(()=>{if(!lr)return;const ne=t.clientWidth,ge=t.clientHeight;ne===A&&ge===B||(A=ne,B=ge,db(ub(lr),!1))}).observe(t)}let pb=!1;t.addEventListener("pointerdown",A=>{A.isPrimary&&(pb=A.target===t)}),t.addEventListener("click",A=>{a.state.showDesktopOnWallpaperClick&&A.target===t&&pb&&(t.classList.contains("os-area--overview")||jy()||g.recentlyEndedDrag()||sL()||n.toggleShowDesktop())}),t.addEventListener("contextmenu",A=>{if(A.target!==t)return;A.preventDefault();const B=A.clientX,V=A.clientY;(()=>{if(t.classList.contains("os-area--overview"))return;if(jy()){ss();return}const ne={x:B,y:V},ge=()=>{const Ce=t.getBoundingClientRect(),Re=Math.max(0,ne.x-Ce.left),wt=Math.max(0,ne.y-Ce.top),xs=bw(We.store.getState().placementsByFolder.get(0)??[]);return It(Re,wt,xs,t)},gt=(Ce,Re)=>{c1({title:Ce,description:Re,nameLabel:"Name",urlLabel:"URL",submitLabel:"Create",onSubmit:async({name:wt,url:xs})=>{const hb=ge(),nM=await Ln({type:"link",ref:xs,parentId:0,x:hb.x,y:hb.y,meta:wt?{name:wt}:void 0});We.store.upsertPlacement(nM)}})},be=a1({createFolder:()=>{Ql({onSubmit:async Ce=>{const Re=await zl({name:Ce}),wt=ge(),xs=await Ln({type:"folder",ref:String(Re.id),parentId:0,x:wt.x,y:wt.y});We.store.upsertFolder(Re),We.store.upsertPlacement(xs)}})},createUrl:()=>gt("New URL","Opens the URL in a new browser tab."),toggleShowDesktop:()=>n.toggleShowDesktop(),openOsSettings:()=>P(),sortIcons:Ce=>{fb(Ce),db(ub(Ce))},currentSortMode:lr,includeShowDesktop:!a.state.showDesktopOnWallpaperClick,position:{x:B,y:V},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"},serverItems:e.serverWallpaperMenuItems??[]});i1(document.body,{x:B,y:V},be)})()}),Promise.resolve().then(()=>X1).then(A=>{A.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:D}}))}_O(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Yy):Yy();const de={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"},d1=32;function u1(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 f1(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 p1(e){return new Promise((t,n)=>{e.file(t,n)})}async function h1(e){const t={files:[],emptyDirs:[],hadDirectory:!1};for(const n of e)await Xy(n,"",t,0);return t}async function Xy(e,t,n,o){if(o>d1)return;if(e.isFile){try{const r=await p1(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 f1(e)}catch{i=[]}if(i.length===0){n.emptyDirs.push(s);return}for(const r of i)await Xy(r,`${s}/`,n,o+1)}const Zy=[".components-drop-zone","[data-drop-zone]",".uploader-window",".media-frame-content"];function as(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 or(e){const t=e?.closest?.(".os-window");if(!t)return;const n=/^wp-window-(.+)$/.exec(t.id||"");return n?n[1]:void 0}function m1(e){if(!e)return;const t=document.querySelectorAll("iframe");for(const n of Array.from(t))if(n.contentWindow===e){const o=or(n);return o||n.closest("[data-window-id]")?.getAttribute("data-window-id")||void 0}}function Jy(e){const t=window;if(t.__openStationOsFileDropMounted)return t.__openStationOsFileDropMounted;if(!e.config.enabled)return w1();const n=g1();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)},l=m=>{as(m)&&(m.preventDefault(),o++,n.classList.add("is-active"),r())},a=m=>{if(as(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(!as(m))return;if(m.defaultPrevented){i();return}m.preventDefault(),i();const h=u1(m.dataTransfer?.items),b=Qy(m);if(h.some(C=>C.isDirectory)){eb(h,b,e);return}const y=m.dataTransfer?.files?Array.from(m.dataTransfer.files):[];y.length!==0&&Wc(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(w=>w instanceof File);if(b.length===0)return;const y=m1(m.source);if(!y)return;const C={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"),Wc(b,C,e)};window.addEventListener("dragenter",l),window.addEventListener("dragover",a),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",l),window.removeEventListener("dragover",a),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 g1(){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 w1(){const e=o=>{if(!as(o))return;const s=o.target;s?.closest&&Zy.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 Qy(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:or(o),x:t,y:n};if(o.classList.contains("os-window")||o.hasAttribute("data-window-id")){const s=or(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 Wc(e,t,n){const o=G(de.FILES_DETECTED,e,t);if(!Array.isArray(o)||o.length===0)return;const{accepted:s,rejected:i}=$c(o,n.config);if(i.length>0&&(L(de.FILES_REJECTED,{rejections:i,context:t}),X({message:i.length===1?i[0].message:`${i.length} files couldn't be uploaded.`})),s.length===0)return;const r=s.map(({file:l,mime:a})=>{const c={file:l,mime:a,fields:Uc(l,a)},d=G(de.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 eb(e,t,n){if(!n.storage?.canUpload||!n.filesUrl){X({message:"Folder uploads need desktop storage, which is not available for your account."});return}const o=await h1(e),s=G(de.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:l,rejected:a}=$c(r.map(u=>u.file),n.config);a.length>0&&(L(de.FILES_REJECTED,{rejections:a,context:t}),X({message:a.length===1?a[0].message:`${a.length} files couldn't be uploaded.`}));const c=new Map(r.map(u=>[u.file,u.relativePath])),d=l.map(({file:u,mime:f})=>({file:u,mime:f,fields:Uc(u,f),relativePath:c.get(u)??""}));d.length===0&&o.emptyDirs.length===0||await n.openDialog(d,t,{forceDesktop:!0,emptyDirs:o.emptyDirs})}function $c(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 ${b1(t.maxSize)} upload limit.`});continue}const i=tb(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 tb(e,t,n){if(t.length===0)return null;const o=e.type.toLowerCase();if(o&&t.includes(o))return o;const s=nb(e.name);if(!s)return null;if(n){for(const[r,l]of Object.entries(n))if(r.split("|").includes(s)&&t.includes(l))return l;return null}const i=y1[s];return i&&t.includes(i)?i:null}const y1={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 nb(e){const t=e.lastIndexOf(".");return t<0?"":e.slice(t+1).toLowerCase()}function Uc(e,t){const n=ob(e.name),o=nb(n),s=o?n.slice(0,n.length-o.length-1):n,i=sb(s);return{title:i,altText:t.startsWith("image/")?i:"",caption:"",description:"",filename:n}}function ob(e){return e.replace(/[\\/]/g,"-").replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").replace(/ *- */g,"-").replace(/-+/g,"-").trim().replace(/^[-.]+|[-.]+$/g,"")||"upload"}function sb(e){const t=e.replace(/[-_]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1):"Upload"}function b1(e){return e>=1048576?`${(e/1048576).toFixed(0)} MB`:e>=1024?`${(e/1024).toFixed(0)} KB`:`${e} B`}const v1=Object.freeze(Object.defineProperty({__proto__:null,IFRAME_PASSTHROUGH_SELECTORS:Zy,classifyDropTarget:Qy,defaultFields:Uc,dragHasFiles:as,handleFiles:Wc,handleTreeDrop:eb,humanize:sb,mountOsFileDropManager:Jy,partitionByPolicy:$c,resolveAllowedMime:tb,sanitizeFilename:ob,windowIdFromElement:or},Symbol.toStringTag,{value:"Module"})),_1=ce` ${nt} ${sa}: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}`,ks=class ks extends Ee{constructor(){super(...arguments),this._revealed=!1}connectedCallback(){super.connectedCallback(),Nf(this)}render(){const t=this.label||"",n=this.value??"",o=this.placeholder||"",s=this.disabled!==null,i=this.readonly!==null,r=this.autocomplete,l=this.type||"text",a=l==="password";let c=r||"off";a&&(!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=l==="password",y=b&&!(h&&this._revealed);let C;b||h&&this._revealed?C="text":C=l;const w=h?"os-text-field__row os-text-field__row--has-reveal":"os-text-field__row",E=y?"os-text-field__input os-text-field__input--masked":"os-text-field__input",M=`${this.id||"os-unnamed"}__input`;return j` |
| 311 |
${t?j`<label |
| 312 |
class="os-text-field__label" |
| 313 |
for=${M} |
| 314 |
>${t}</label>`:j``} |
| 315 |
<span class=${w}> |
| 316 |
<input |
| 317 |
id=${M} |
| 318 |
class=${E} |
| 319 |
type=${C} |
| 320 |
.value=${n} |
| 321 |
placeholder=${o} |
| 322 |
?disabled=${s} |
| 323 |
?readonly=${i} |
| 324 |
autocomplete=${c} |
| 325 |
maxlength=${d??""} |
| 326 |
minlength=${u??""} |
| 327 |
pattern=${f} |
| 328 |
name=${p} |
| 329 |
aria-invalid=${m?"true":"false"} |
| 330 |
aria-label=${t||""} |
| 331 |
@input=${P=>this._onInput(P)} |
| 332 |
@change=${P=>this._onChange(P)} |
| 333 |
@keydown=${P=>this._onKeyDown(P)} |
| 334 |
/> |
| 335 |
${g?j`<span class="os-text-field__suffix">${g}</span>`:j``} |
| 336 |
${h?this._renderRevealButton(s):j``} |
| 337 |
</span> |
| 338 |
`}_renderRevealButton(t){const n=this._revealed?"Hide":"Show";return j` |
| 339 |
<button |
| 340 |
type="button" |
| 341 |
class="os-text-field__reveal" |
| 342 |
aria-label=${n} |
| 343 |
aria-pressed=${this._revealed?"true":"false"} |
| 344 |
?disabled=${t} |
| 345 |
tabindex="0" |
| 346 |
@click=${()=>this._onToggleReveal()} |
| 347 |
> |
| 348 |
${this._revealed?k1():E1()} |
| 349 |
</button> |
| 350 |
`}_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})}}};ks.props=["label","value","placeholder","disabled","readonly","autocomplete","type","maxlength","minlength","pattern","name","suffix","invalid","reveal"],ks.styles=[_1],ks.help=void 0;let Fc=ks;Ie("os-text-field",Fc);function E1(){return j` |
| 351 |
<svg |
| 352 |
viewBox="0 0 16 16" |
| 353 |
width="14" |
| 354 |
height="14" |
| 355 |
fill="none" |
| 356 |
stroke="currentColor" |
| 357 |
stroke-width="1.5" |
| 358 |
stroke-linecap="round" |
| 359 |
stroke-linejoin="round" |
| 360 |
aria-hidden="true" |
| 361 |
focusable="false" |
| 362 |
> |
| 363 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 364 |
<circle cx="8" cy="8" r="2" /> |
| 365 |
</svg> |
| 366 |
`}function k1(){return j` |
| 367 |
<svg |
| 368 |
viewBox="0 0 16 16" |
| 369 |
width="14" |
| 370 |
height="14" |
| 371 |
fill="none" |
| 372 |
stroke="currentColor" |
| 373 |
stroke-width="1.5" |
| 374 |
stroke-linecap="round" |
| 375 |
stroke-linejoin="round" |
| 376 |
aria-hidden="true" |
| 377 |
focusable="false" |
| 378 |
> |
| 379 |
<path d="M1 8C1 8 3.5 3 8 3s7 5 7 5-2.5 5-7 5S1 8 1 8z" /> |
| 380 |
<circle cx="8" cy="8" r="2" /> |
| 381 |
<line x1="2" y1="2" x2="14" y2="14" /> |
| 382 |
</svg> |
| 383 |
`}async function S1(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=G(de.BEFORE_UPLOAD,t,e.context);if(!n)throw new Bc;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 l=new XMLHttpRequest;l.open("POST",e.mediaUrl,!0),l.withCredentials=!0,l.setRequestHeader("X-WP-Nonce",e.restNonce),l.responseType="text";let a=!1,c=!1,d=!1;const u=()=>{if(d=!0,!c){a=!0;try{l.abort()}catch{}}};L(de.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:u}),l.upload.addEventListener("progress",f=>{L(de.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:f.loaded,total:f.lengthComputable?f.total:0,indeterminate:!f.lengthComputable})}),l.upload.addEventListener("load",()=>{c=!0,L(de.UPLOAD_PROGRESS,{file:n.file,fields:n.fields,context:e.context,loaded:n.file.size,total:n.file.size,indeterminate:!1})}),l.addEventListener("error",()=>{if(a)return;const f=new Error("Network error during upload.");L(de.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),r(f)}),l.addEventListener("abort",()=>{const f=new sr;L(de.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),r(f)}),l.addEventListener("load",()=>{if(a)return;if(l.status<200||l.status>=300){const g=C1(l),m=new Error(g);L(de.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}let f;try{f=JSON.parse(l.responseText)}catch(g){const m=g instanceof Error?g:new Error("Could not parse server response.");L(de.UPLOAD_FAILED,{file:n.file,error:m,context:e.context}),r(m);return}if(d&&f.id){A1(e.mediaUrl,e.restNonce,f.id);const g=new sr;L(de.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};L(de.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:e.context}),i(p)}),l.send(o)})}class Bc extends Error{constructor(){super("Upload cancelled by os.drop.before-upload filter."),this.name="UploadCancelledError"}}class sr extends Error{constructor(){super("Upload aborted by the caller."),this.name="UploadAbortedError"}}function A1(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 C1(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 I1(e){const t={file:e.file,mime:e.mime,fields:e.fields},n=G(de.BEFORE_UPLOAD,t,e.context);if(!n)throw new Bc;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,l)=>{const a=new XMLHttpRequest;a.open("POST",i,!0),a.withCredentials=!0,a.setRequestHeader("X-WP-Nonce",e.restNonce),a.responseType="text";let c=!1;const d=()=>{c=!0;try{a.abort()}catch{}};L(de.UPLOAD_STARTED,{file:n.file,fields:n.fields,context:e.context,abort:d}),a.upload.addEventListener("progress",f=>{L(de.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=>{L(de.UPLOAD_FAILED,{file:n.file,error:f,context:e.context}),l(f)};a.addEventListener("error",()=>{c||u(new Error("Network error during upload."))}),a.addEventListener("abort",()=>u(new sr)),a.addEventListener("load",()=>{if(c)return;if(a.status<200||a.status>=300){u(new Error(x1(a,n.file.name)));return}let f;try{f=JSON.parse(a.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}Mi(f.placement,"local");const p={placement:f.placement,storedFileId:f.storedFileId};L(de.AFTER_UPLOAD,{file:n.file,result:p,fields:n.fields,context:e.context}),r(p)}),a.send(o)})}function x1(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 L1(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 T1=/^(image|video|audio)\//;function Hc(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=>T1.test(n))?"media":"desktop":"media"}let Zt=null;async function N1(e){if(e.entries.length===0&&!e.emptyDirs?.length)return;if(Zt){Zt.replace(e);return}const t=!!(e.storage?.canUpload&&e.filesUrl);let n=Hc({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 C=document.createElement("os-segment");C.setAttribute("value","media"),C.textContent="Media Library",b.appendChild(C),b.addEventListener("os-pick",w=>{n=w.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: ${jt(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(l(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",()=>{a(g,p)}),f.appendChild(p),f.appendChild(g),o.appendChild(f)},l=(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"} · ${jt(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(ls("Filename",u.filename,y=>u.filename=y)),p}return p.appendChild(ls("Title",u.title,y=>u.title=y)),p.appendChild(ls("Filename",u.filename,y=>u.filename=y)),d.mime.startsWith("image/")&&p.appendChild(ls("Alt text",u.altText,y=>u.altText=y)),p.appendChild(ls("Caption",u.caption,y=>u.caption=y)),p.appendChild(D1("Description",u.description,y=>u.description=y)),p},a=async(d,u)=>{Zt===c&&(Zt=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 w=0;w<f;w++){const E=e.entries[w];try{if(n==="desktop"&&e.filesUrl){const M=!E.relativePath&&!y&&e.context.surface==="wallpaper"?L1(e.context.x,e.context.y):void 0;M&&(y=!0),await I1({file:E.file,mime:E.mime,fields:i[w],context:e.context,filesUrl:e.filesUrl,restNonce:e.restNonce,parentId:b,relativePath:E.relativePath??"",coords:M})}else await S1({file:E.file,mime:E.mime,fields:i[w],context:e.context,mediaUrl:e.mediaUrl,restNonce:e.restNonce});p++}catch(T){if(T instanceof Bc){m++;continue}if(T instanceof sr){m++;continue}g++;const M=T instanceof Error?T.message:"Upload failed.";h.push(`“${E.file.name}” — ${M}`)}}if(n==="desktop"&&e.emptyDirs?.length)for(const w of e.emptyDirs)try{await cw(b,w)}catch{}const C=e.entries.some(w=>w.relativePath)||!!e.emptyDirs?.length;if(n==="desktop"&&C)try{const[w,E]=await Promise.all([Hl(),Te(b)]);Pi(w.folders),pt(b,E.placements)}catch{}o.remove(),R1({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=Hc({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()}};Zt=c,r(),await new Promise(d=>{const u=()=>{Zt===c&&(Zt=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 ls(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 D1(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 R1(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"&&X({message:"Folder created on your desktop."});return}if(t===1){n===1?X({message:`Uploaded to ${r}.`}):o===1&&i[0]?X({message:i[0]}):s===1&&X({message:"Upload cancelled."});return}if(n===t){X({message:`Uploaded ${n} files to ${r}.`});return}if(s===t){X({message:"All uploads cancelled."});return}if(o===t){X({message:o===1&&i[0]?i[0]:`${o} uploads failed.`});return}const l=[];n>0&&l.push(`Uploaded ${n} file${n===1?"":"s"}.`),s>0&&l.push(`Cancelled ${s}.`),o>0&&l.push(`Failed ${o}.`),X({message:l.join(" ")})}const ib=Object.freeze(Object.defineProperty({__proto__:null,openUploadDialog:N1,resolveDefaultDestination:Hc},Symbol.toStringTag,{value:"Module"})),O1={tab:null,requestedAt:0};let ir=null;function zc(){if(ir)return ir;const t=window.wp?.os?.createSharedStore;return typeof t!="function"?null:(ir=t("desktop-mode/plugins-window/tab-target",()=>({...O1})),ir)}function M1(e){const t=zc();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 P1(){const e=zc();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 W1(e){const t=zc();return t?t.subscribe(n=>e({...n})):()=>{}}const $1=Object.freeze(Object.defineProperty({__proto__:null,consumePluginsWindowTab:P1,setPluginsWindowTab:M1,subscribePluginsWindowTab:W1},Symbol.toStringTag,{value:"Module"})),U1=ce` ${nt} ${Mf}: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}}`,Ss=class Ss extends Ee{constructor(){super(...arguments),this._ownedAriaLabel=null}render(){return j`<div class="root" part="root"> |
| 384 |
<div class="header" part="header" hidden> |
| 385 |
<span class="label" part="label"></span> |
| 386 |
<span class="percent" part="percent"></span> |
| 387 |
</div> |
| 388 |
<div class="track" part="track"> |
| 389 |
<div class="fill" part="fill"></div> |
| 390 |
</div> |
| 391 |
</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),l=this.getAttribute("label")??"",a=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=l||a&&!o;d.hidden=!g,u.textContent=l,f.hidden=!(a&&!o),f.textContent=`${r}%`}this._syncAria(n,s,o,l);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))),l?p.setAttribute("aria-label",l):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}};Ss.props=["value","max","indeterminate","tone","label","showPercent"],Ss.styles=[U1],Ss.help=void 0;let Gc=Ss;Ie("os-progress-bar",Gc);const Je=new Map;let mt=null;function F1(){if(document.body.hasAttribute("data-os-suppress-upload-hud")||window.__wpdUploadHud)return;window.__wpdUploadHud=!0;const e="desktop-mode/os-file-drop-hud";Y(de.UPLOAD_STARTED,e,t=>B1(t.file,t.fields,t.abort)),Y(de.UPLOAD_PROGRESS,e,t=>H1(t.file,t.loaded,t.total,t.indeterminate)),Y(de.AFTER_UPLOAD,e,t=>z1(t.file,t.fields,t.result)),Y(de.UPLOAD_FAILED,e,t=>G1(t.file,t.error))}function B1(e,t,n){const o=j1(),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 l=document.createElement("div");l.className="os-upload-hud__status",l.textContent="Uploading…",i.append(r,l);const a=document.createElement("os-progress-bar");a.setAttribute("indeterminate",""),a.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=Je.get(e);u&&(u.state==="running"?(u.statusEl.textContent="Cancelling…",u.cancelBtn.disabled=!0,u.abort()):jc(u))}),c.appendChild(d),s.append(i,a,c),o.querySelector(".os-upload-hud__list").appendChild(s),Je.set(e,{file:e,abort:n,root:s,bar:a,statusEl:l,cancelBtn:d,state:"running",lingerTimer:null}),rr()}function H1(e,t,n,o){const s=Je.get(e);!s||s.state!=="running"||(o||n<=0?(s.bar.setAttribute("indeterminate",""),s.statusEl.textContent=`${jt(t)} sent`):(s.bar.removeAttribute("indeterminate"),s.bar.setAttribute("max",String(n)),s.bar.setAttribute("value",String(t)),s.statusEl.textContent=`${jt(t)} / ${jt(n)}`))}function z1(e,t,n){const o=Je.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(()=>jc(o),2500),rr(),ke.publish("os/upload-hud-complete",{filename:t.filename||n.filename,attachmentId:n.id}))}function G1(e,t){const n=Je.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"),rr())}function jc(e){e.lingerTimer&&clearTimeout(e.lingerTimer),Je.delete(e.file),e.root.remove(),rr(),Je.size===0&&mt&&(mt.hidden=!0)}function j1(){if(mt&&mt.isConnected)return mt.hidden=!1,mt;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[...Je.values()])i.state!=="running"&&jc(i);Je.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),mt=e,e}function rr(){if(!mt)return;const e=mt.querySelector(".os-upload-hud__title");if(!e)return;const t=Je.size,n=[...Je.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 V1(){if(document.body.hasAttribute("data-os-suppress-media-library-refresh"))return;const e=window;e.__wpdMediaLibraryRefresher||(e.__wpdMediaLibraryRefresher=!0,Y(de.AFTER_UPLOAD,"desktop-mode/os-file-drop-library-refresh",()=>q1()))}function q1(){const e=document.querySelectorAll("iframe");for(const t of Array.from(e))if(K1(rb(t)))try{t.contentWindow?.location.reload()}catch{const n=rb(t);n&&t.setAttribute("src",n)}}function rb(e){try{return e.contentWindow?.location.href??e.src??""}catch{return e.src??""}}function K1(e){return e?/\/wp-admin\/upload\.php(?:[?#]|$)/.test(e):!1}function Y1(e){const t=e.config||{enabled:!1,allowedMimes:[],maxSize:0};F1(),V1(),Jy({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(()=>ib);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 X1=Object.freeze(Object.defineProperty({__proto__:null,FILE_DROP_HOOKS:de,bootOsFileDrop:Y1},Symbol.toStringTag,{value:"Module"}));return cr.clampGeometryToViewport=Cl,Object.defineProperty(cr,Symbol.toStringTag,{value:"Module"}),cr}({}); |
| 392 |
|